xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision ccae0b50330edda9b094cee1ec6a0ad35443e8b0)
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 
775 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
776     ipha_t *, ill_t *, boolean_t);
777 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
778 
779 /* How long, in seconds, we allow frags to hang around. */
780 #define	IP_FRAG_TIMEOUT	60
781 
782 /*
783  * Threshold which determines whether MDT should be used when
784  * generating IP fragments; payload size must be greater than
785  * this threshold for MDT to take place.
786  */
787 #define	IP_WPUT_FRAG_MDT_MIN	32768
788 
789 /* Setable in /etc/system only */
790 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
791 
792 static long ip_rput_pullups;
793 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
794 
795 vmem_t *ip_minor_arena;
796 
797 int	ip_debug;
798 
799 #ifdef DEBUG
800 uint32_t ipsechw_debug = 0;
801 #endif
802 
803 /*
804  * Multirouting/CGTP stuff
805  */
806 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
807 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
808 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
809 
810 /*
811  * XXX following really should only be in a header. Would need more
812  * header and .c clean up first.
813  */
814 extern optdb_obj_t	ip_opt_obj;
815 
816 ulong_t ip_squeue_enter_unbound = 0;
817 
818 /*
819  * Named Dispatch Parameter Table.
820  * All of these are alterable, within the min/max values given, at run time.
821  */
822 static ipparam_t	lcl_param_arr[] = {
823 	/* min	max	value	name */
824 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
825 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
826 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
827 	{  0,	1,	0,	"ip_respond_to_timestamp"},
828 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
829 	{  0,	1,	1,	"ip_send_redirects"},
830 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
831 	{  0,	10,	0,	"ip_debug"},
832 	{  0,	10,	0,	"ip_mrtdebug"},
833 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
834 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
835 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
836 	{  1,	255,	255,	"ip_def_ttl" },
837 	{  0,	1,	0,	"ip_forward_src_routed"},
838 	{  0,	256,	32,	"ip_wroff_extra" },
839 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
840 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
841 	{  0,	1,	1,	"ip_path_mtu_discovery" },
842 	{  0,	240,	30,	"ip_ignore_delete_time" },
843 	{  0,	1,	0,	"ip_ignore_redirect" },
844 	{  0,	1,	1,	"ip_output_queue" },
845 	{  1,	254,	1,	"ip_broadcast_ttl" },
846 	{  0,	99999,	100,	"ip_icmp_err_interval" },
847 	{  1,	99999,	10,	"ip_icmp_err_burst" },
848 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
849 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
850 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
851 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
852 	{  0,	1,	1,	"icmp_accept_clear_messages" },
853 	{  0,	1,	1,	"igmp_accept_clear_messages" },
854 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
855 				"ip_ndp_delay_first_probe_time"},
856 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
857 				"ip_ndp_max_unicast_solicit"},
858 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
859 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
860 	{  0,	1,	0,	"ip6_forward_src_routed"},
861 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
862 	{  0,	1,	1,	"ip6_send_redirects"},
863 	{  0,	1,	0,	"ip6_ignore_redirect" },
864 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
865 
866 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
867 
868 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
869 
870 	{  0,	1,	1,	"pim_accept_clear_messages" },
871 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
872 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
873 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
874 	{  0,	15,	0,	"ip_policy_mask" },
875 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
876 	{  0,	255,	1,	"ip_multirt_ttl" },
877 	{  0,	1,	1,	"ip_multidata_outbound" },
878 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
879 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
880 	{  0,	1000,	1,	"ip_max_temp_defend" },
881 	{  0,	1000,	3,	"ip_max_defend" },
882 	{  0,	999999,	30,	"ip_defend_interval" },
883 	{  0,	3600000, 300000, "ip_dup_recovery" },
884 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
885 	{  0,	1,	1,	"ip_lso_outbound" },
886 #ifdef DEBUG
887 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
888 #else
889 	{  0,	0,	0,	"" },
890 #endif
891 };
892 
893 /*
894  * Extended NDP table
895  * The addresses for the first two are filled in to be ips_ip_g_forward
896  * and ips_ipv6_forward at init time.
897  */
898 static ipndp_t	lcl_ndp_arr[] = {
899 	/* getf			setf		data			name */
900 #define	IPNDP_IP_FORWARDING_OFFSET	0
901 	{  ip_param_generic_get,	ip_forward_set,	NULL,
902 	    "ip_forwarding" },
903 #define	IPNDP_IP6_FORWARDING_OFFSET	1
904 	{  ip_param_generic_get,	ip_forward_set,	NULL,
905 	    "ip6_forwarding" },
906 	{  ip_ill_report,	NULL,		NULL,
907 	    "ip_ill_status" },
908 	{  ip_ipif_report,	NULL,		NULL,
909 	    "ip_ipif_status" },
910 	{  ip_ire_report,	NULL,		NULL,
911 	    "ipv4_ire_status" },
912 	{  ip_ire_report_mrtun,	NULL,		NULL,
913 	    "ipv4_mrtun_ire_status" },
914 	{  ip_ire_report_srcif,	NULL,		NULL,
915 	    "ipv4_srcif_ire_status" },
916 	{  ip_ire_report_v6,	NULL,		NULL,
917 	    "ipv6_ire_status" },
918 	{  ip_conn_report,	NULL,		NULL,
919 	    "ip_conn_status" },
920 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
921 	    "ip_rput_pullups" },
922 	{  ndp_report,		NULL,		NULL,
923 	    "ip_ndp_cache_report" },
924 	{  ip_srcid_report,	NULL,		NULL,
925 	    "ip_srcid_status" },
926 	{ ip_param_generic_get, ip_squeue_profile_set,
927 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
928 	{ ip_param_generic_get, ip_squeue_bind_set,
929 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
930 	{ ip_param_generic_get, ip_input_proc_set,
931 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
932 	{ ip_param_generic_get, ip_int_set,
933 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
934 #define	IPNDP_CGTP_FILTER_OFFSET	16
935 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
936 	    "ip_cgtp_filter" },
937 	{ ip_param_generic_get, ip_int_set,
938 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
939 #define	IPNDP_IPMP_HOOK_OFFSET	18
940 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
941 	    "ipmp_hook_emulation" },
942 };
943 
944 /*
945  * Table of IP ioctls encoding the various properties of the ioctl and
946  * indexed based on the last byte of the ioctl command. Occasionally there
947  * is a clash, and there is more than 1 ioctl with the same last byte.
948  * In such a case 1 ioctl is encoded in the ndx table and the remaining
949  * ioctls are encoded in the misc table. An entry in the ndx table is
950  * retrieved by indexing on the last byte of the ioctl command and comparing
951  * the ioctl command with the value in the ndx table. In the event of a
952  * mismatch the misc table is then searched sequentially for the desired
953  * ioctl command.
954  *
955  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
956  */
957 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
958 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
961 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
962 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
963 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
964 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
965 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
966 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
967 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
968 
969 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
970 			MISC_CMD, ip_siocaddrt, NULL },
971 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
972 			MISC_CMD, ip_siocdelrt, NULL },
973 
974 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
975 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
976 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
977 			IF_CMD, ip_sioctl_get_addr, NULL },
978 
979 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
980 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
981 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
982 			IPI_GET_CMD | IPI_REPL,
983 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
984 
985 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
986 			IPI_PRIV | IPI_WR | IPI_REPL,
987 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
988 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
989 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
990 			IF_CMD, ip_sioctl_get_flags, NULL },
991 
992 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
993 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
994 
995 	/* copyin size cannot be coded for SIOCGIFCONF */
996 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
997 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
998 
999 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1000 			IF_CMD, ip_sioctl_mtu, NULL },
1001 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1002 			IF_CMD, ip_sioctl_get_mtu, NULL },
1003 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1004 			IPI_GET_CMD | IPI_REPL,
1005 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1006 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1007 			IF_CMD, ip_sioctl_brdaddr, NULL },
1008 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1009 			IPI_GET_CMD | IPI_REPL,
1010 			IF_CMD, ip_sioctl_get_netmask, NULL },
1011 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1012 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1013 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1014 			IPI_GET_CMD | IPI_REPL,
1015 			IF_CMD, ip_sioctl_get_metric, NULL },
1016 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1017 			IF_CMD, ip_sioctl_metric, NULL },
1018 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 
1020 	/* See 166-168 below for extended SIOC*XARP ioctls */
1021 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1022 			MISC_CMD, ip_sioctl_arp, NULL },
1023 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1024 			MISC_CMD, ip_sioctl_arp, NULL },
1025 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1026 			MISC_CMD, ip_sioctl_arp, NULL },
1027 
1028 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 
1050 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1051 			MISC_CMD, if_unitsel, if_unitsel_restart },
1052 
1053 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 
1072 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1073 			IPI_PRIV | IPI_WR | IPI_MODOK,
1074 			IF_CMD, ip_sioctl_sifname, NULL },
1075 
1076 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1087 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1088 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1089 
1090 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1091 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1092 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1093 			IF_CMD, ip_sioctl_get_muxid, NULL },
1094 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1095 			IPI_PRIV | IPI_WR | IPI_REPL,
1096 			IF_CMD, ip_sioctl_muxid, NULL },
1097 
1098 	/* Both if and lif variants share same func */
1099 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1100 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1101 	/* Both if and lif variants share same func */
1102 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1103 			IPI_PRIV | IPI_WR | IPI_REPL,
1104 			IF_CMD, ip_sioctl_slifindex, NULL },
1105 
1106 	/* copyin size cannot be coded for SIOCGIFCONF */
1107 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1108 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1109 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 
1127 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1128 			IPI_PRIV | IPI_WR | IPI_REPL,
1129 			LIF_CMD, ip_sioctl_removeif,
1130 			ip_sioctl_removeif_restart },
1131 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1132 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1133 			LIF_CMD, ip_sioctl_addif, NULL },
1134 #define	SIOCLIFADDR_NDX 112
1135 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1136 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1137 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1138 			IPI_GET_CMD | IPI_REPL,
1139 			LIF_CMD, ip_sioctl_get_addr, NULL },
1140 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1141 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1142 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1143 			IPI_GET_CMD | IPI_REPL,
1144 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1145 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1146 			IPI_PRIV | IPI_WR | IPI_REPL,
1147 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1148 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1149 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1150 			LIF_CMD, ip_sioctl_get_flags, NULL },
1151 
1152 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 
1155 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1156 			ip_sioctl_get_lifconf, NULL },
1157 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1158 			LIF_CMD, ip_sioctl_mtu, NULL },
1159 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1161 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1162 			IPI_GET_CMD | IPI_REPL,
1163 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1164 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1165 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1166 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1167 			IPI_GET_CMD | IPI_REPL,
1168 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1169 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1170 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1171 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1172 			IPI_GET_CMD | IPI_REPL,
1173 			LIF_CMD, ip_sioctl_get_metric, NULL },
1174 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1175 			LIF_CMD, ip_sioctl_metric, NULL },
1176 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1177 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1178 			LIF_CMD, ip_sioctl_slifname,
1179 			ip_sioctl_slifname_restart },
1180 
1181 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1182 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1183 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1184 			IPI_GET_CMD | IPI_REPL,
1185 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1186 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1187 			IPI_PRIV | IPI_WR | IPI_REPL,
1188 			LIF_CMD, ip_sioctl_muxid, NULL },
1189 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1190 			IPI_GET_CMD | IPI_REPL,
1191 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1192 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1193 			IPI_PRIV | IPI_WR | IPI_REPL,
1194 			LIF_CMD, ip_sioctl_slifindex, 0 },
1195 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_token, NULL },
1197 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1198 			IPI_GET_CMD | IPI_REPL,
1199 			LIF_CMD, ip_sioctl_get_token, NULL },
1200 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1201 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1202 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1203 			IPI_GET_CMD | IPI_REPL,
1204 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1205 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1206 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1207 
1208 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1209 			IPI_GET_CMD | IPI_REPL,
1210 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1211 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1212 			LIF_CMD, ip_siocdelndp_v6, NULL },
1213 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1214 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1215 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1216 			LIF_CMD, ip_siocsetndp_v6, NULL },
1217 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1218 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1219 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1220 			MISC_CMD, ip_sioctl_tonlink, NULL },
1221 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1222 			MISC_CMD, ip_sioctl_tmysite, NULL },
1223 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1224 			TUN_CMD, ip_sioctl_tunparam, NULL },
1225 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1226 			IPI_PRIV | IPI_WR,
1227 			TUN_CMD, ip_sioctl_tunparam, NULL },
1228 
1229 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1230 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1231 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1232 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1233 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1234 
1235 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1236 			IPI_PRIV | IPI_WR | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1238 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1239 			IPI_PRIV | IPI_WR | IPI_REPL,
1240 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1241 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1242 			IPI_PRIV | IPI_WR,
1243 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1244 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1245 			IPI_GET_CMD | IPI_REPL,
1246 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1247 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1248 			IPI_GET_CMD | IPI_REPL,
1249 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1250 
1251 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1252 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1253 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1254 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1255 
1256 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1257 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1258 
1259 	/* These are handled in ip_sioctl_copyin_setup itself */
1260 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1261 			MISC_CMD, NULL, NULL },
1262 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1263 			MISC_CMD, NULL, NULL },
1264 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1265 
1266 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1267 			ip_sioctl_get_lifconf, NULL },
1268 
1269 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1270 			MISC_CMD, ip_sioctl_xarp, NULL },
1271 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1272 			MISC_CMD, ip_sioctl_xarp, NULL },
1273 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1274 			MISC_CMD, ip_sioctl_xarp, NULL },
1275 
1276 	/* SIOCPOPSOCKFS is not handled by IP */
1277 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1278 
1279 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1280 			IPI_GET_CMD | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1282 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1283 			IPI_PRIV | IPI_WR | IPI_REPL,
1284 			LIF_CMD, ip_sioctl_slifzone,
1285 			ip_sioctl_slifzone_restart },
1286 	/* 172-174 are SCTP ioctls and not handled by IP */
1287 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1288 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1289 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1290 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1291 			IPI_GET_CMD, LIF_CMD,
1292 			ip_sioctl_get_lifusesrc, 0 },
1293 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1294 			IPI_PRIV | IPI_WR,
1295 			LIF_CMD, ip_sioctl_slifusesrc,
1296 			NULL },
1297 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1298 			ip_sioctl_get_lifsrcof, NULL },
1299 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1300 			MISC_CMD, ip_sioctl_msfilter, NULL },
1301 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1302 			MISC_CMD, ip_sioctl_msfilter, NULL },
1303 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1304 			MISC_CMD, ip_sioctl_msfilter, NULL },
1305 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1306 			MISC_CMD, ip_sioctl_msfilter, NULL },
1307 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1308 			ip_sioctl_set_ipmpfailback, NULL }
1309 };
1310 
1311 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1312 
1313 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1314 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1315 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1316 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1317 		TUN_CMD, ip_sioctl_tunparam, NULL },
1318 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1319 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1320 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1321 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1322 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1323 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1324 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1325 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1326 		MISC_CMD, mrt_ioctl},
1327 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1328 		MISC_CMD, mrt_ioctl},
1329 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1330 		MISC_CMD, mrt_ioctl}
1331 };
1332 
1333 int ip_misc_ioctl_count =
1334     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1335 
1336 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1337 					/* Settable in /etc/system */
1338 /* Defined in ip_ire.c */
1339 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1340 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1341 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1342 
1343 static nv_t	ire_nv_arr[] = {
1344 	{ IRE_BROADCAST, "BROADCAST" },
1345 	{ IRE_LOCAL, "LOCAL" },
1346 	{ IRE_LOOPBACK, "LOOPBACK" },
1347 	{ IRE_CACHE, "CACHE" },
1348 	{ IRE_DEFAULT, "DEFAULT" },
1349 	{ IRE_PREFIX, "PREFIX" },
1350 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1351 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1352 	{ IRE_HOST, "HOST" },
1353 	{ 0 }
1354 };
1355 
1356 nv_t	*ire_nv_tbl = ire_nv_arr;
1357 
1358 /* Defined in ip_netinfo.c */
1359 extern ddi_taskq_t	*eventq_queue_nic;
1360 
1361 /* Simple ICMP IP Header Template */
1362 static ipha_t icmp_ipha = {
1363 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1364 };
1365 
1366 struct module_info ip_mod_info = {
1367 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1368 };
1369 
1370 /*
1371  * Duplicate static symbols within a module confuses mdb; so we avoid the
1372  * problem by making the symbols here distinct from those in udp.c.
1373  */
1374 
1375 static struct qinit iprinit = {
1376 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1377 	&ip_mod_info
1378 };
1379 
1380 static struct qinit ipwinit = {
1381 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1382 	&ip_mod_info
1383 };
1384 
1385 static struct qinit iplrinit = {
1386 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1387 	&ip_mod_info
1388 };
1389 
1390 static struct qinit iplwinit = {
1391 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1392 	&ip_mod_info
1393 };
1394 
1395 struct streamtab ipinfo = {
1396 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1397 };
1398 
1399 #ifdef	DEBUG
1400 static boolean_t skip_sctp_cksum = B_FALSE;
1401 #endif
1402 
1403 /*
1404  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1405  * ip_rput_v6(), ip_output(), etc.  If the message
1406  * block already has a M_CTL at the front of it, then simply set the zoneid
1407  * appropriately.
1408  */
1409 mblk_t *
1410 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1411 {
1412 	mblk_t		*first_mp;
1413 	ipsec_out_t	*io;
1414 
1415 	ASSERT(zoneid != ALL_ZONES);
1416 	if (mp->b_datap->db_type == M_CTL) {
1417 		io = (ipsec_out_t *)mp->b_rptr;
1418 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1419 		io->ipsec_out_zoneid = zoneid;
1420 		return (mp);
1421 	}
1422 
1423 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1424 	if (first_mp == NULL)
1425 		return (NULL);
1426 	io = (ipsec_out_t *)first_mp->b_rptr;
1427 	/* This is not a secure packet */
1428 	io->ipsec_out_secure = B_FALSE;
1429 	io->ipsec_out_zoneid = zoneid;
1430 	first_mp->b_cont = mp;
1431 	return (first_mp);
1432 }
1433 
1434 /*
1435  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1436  */
1437 mblk_t *
1438 ip_copymsg(mblk_t *mp)
1439 {
1440 	mblk_t *nmp;
1441 	ipsec_info_t *in;
1442 
1443 	if (mp->b_datap->db_type != M_CTL)
1444 		return (copymsg(mp));
1445 
1446 	in = (ipsec_info_t *)mp->b_rptr;
1447 
1448 	/*
1449 	 * Note that M_CTL is also used for delivering ICMP error messages
1450 	 * upstream to transport layers.
1451 	 */
1452 	if (in->ipsec_info_type != IPSEC_OUT &&
1453 	    in->ipsec_info_type != IPSEC_IN)
1454 		return (copymsg(mp));
1455 
1456 	nmp = copymsg(mp->b_cont);
1457 
1458 	if (in->ipsec_info_type == IPSEC_OUT) {
1459 		return (ipsec_out_tag(mp, nmp,
1460 			    ((ipsec_out_t *)in)->ipsec_out_ns));
1461 	} else {
1462 		return (ipsec_in_tag(mp, nmp,
1463 			    ((ipsec_in_t *)in)->ipsec_in_ns));
1464 	}
1465 }
1466 
1467 /* Generate an ICMP fragmentation needed message. */
1468 static void
1469 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1470     ip_stack_t *ipst)
1471 {
1472 	icmph_t	icmph;
1473 	mblk_t *first_mp;
1474 	boolean_t mctl_present;
1475 
1476 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1477 
1478 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1479 		if (mctl_present)
1480 			freeb(first_mp);
1481 		return;
1482 	}
1483 
1484 	bzero(&icmph, sizeof (icmph_t));
1485 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1486 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1487 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1488 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1489 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1490 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1491 	    ipst);
1492 }
1493 
1494 /*
1495  * icmp_inbound deals with ICMP messages in the following ways.
1496  *
1497  * 1) It needs to send a reply back and possibly delivering it
1498  *    to the "interested" upper clients.
1499  * 2) It needs to send it to the upper clients only.
1500  * 3) It needs to change some values in IP only.
1501  * 4) It needs to change some values in IP and upper layers e.g TCP.
1502  *
1503  * We need to accomodate icmp messages coming in clear until we get
1504  * everything secure from the wire. If icmp_accept_clear_messages
1505  * is zero we check with the global policy and act accordingly. If
1506  * it is non-zero, we accept the message without any checks. But
1507  * *this does not mean* that this will be delivered to the upper
1508  * clients. By accepting we might send replies back, change our MTU
1509  * value etc. but delivery to the ULP/clients depends on their policy
1510  * dispositions.
1511  *
1512  * We handle the above 4 cases in the context of IPSEC in the
1513  * following way :
1514  *
1515  * 1) Send the reply back in the same way as the request came in.
1516  *    If it came in encrypted, it goes out encrypted. If it came in
1517  *    clear, it goes out in clear. Thus, this will prevent chosen
1518  *    plain text attack.
1519  * 2) The client may or may not expect things to come in secure.
1520  *    If it comes in secure, the policy constraints are checked
1521  *    before delivering it to the upper layers. If it comes in
1522  *    clear, ipsec_inbound_accept_clear will decide whether to
1523  *    accept this in clear or not. In both the cases, if the returned
1524  *    message (IP header + 8 bytes) that caused the icmp message has
1525  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1526  *    sending up. If there are only 8 bytes of returned message, then
1527  *    upper client will not be notified.
1528  * 3) Check with global policy to see whether it matches the constaints.
1529  *    But this will be done only if icmp_accept_messages_in_clear is
1530  *    zero.
1531  * 4) If we need to change both in IP and ULP, then the decision taken
1532  *    while affecting the values in IP and while delivering up to TCP
1533  *    should be the same.
1534  *
1535  * 	There are two cases.
1536  *
1537  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1538  *	   failed), we will not deliver it to the ULP, even though they
1539  *	   are *willing* to accept in *clear*. This is fine as our global
1540  *	   disposition to icmp messages asks us reject the datagram.
1541  *
1542  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1543  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1544  *	   to deliver it to ULP (policy failed), it can lead to
1545  *	   consistency problems. The cases known at this time are
1546  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1547  *	   values :
1548  *
1549  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1550  *	     and Upper layer rejects. Then the communication will
1551  *	     come to a stop. This is solved by making similar decisions
1552  *	     at both levels. Currently, when we are unable to deliver
1553  *	     to the Upper Layer (due to policy failures) while IP has
1554  *	     adjusted ire_max_frag, the next outbound datagram would
1555  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1556  *	     will be with the right level of protection. Thus the right
1557  *	     value will be communicated even if we are not able to
1558  *	     communicate when we get from the wire initially. But this
1559  *	     assumes there would be at least one outbound datagram after
1560  *	     IP has adjusted its ire_max_frag value. To make things
1561  *	     simpler, we accept in clear after the validation of
1562  *	     AH/ESP headers.
1563  *
1564  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1565  *	     upper layer depending on the level of protection the upper
1566  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1567  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1568  *	     should be accepted in clear when the Upper layer expects secure.
1569  *	     Thus the communication may get aborted by some bad ICMP
1570  *	     packets.
1571  *
1572  * IPQoS Notes:
1573  * The only instance when a packet is sent for processing is when there
1574  * isn't an ICMP client and if we are interested in it.
1575  * If there is a client, IPPF processing will take place in the
1576  * ip_fanout_proto routine.
1577  *
1578  * Zones notes:
1579  * The packet is only processed in the context of the specified zone: typically
1580  * only this zone will reply to an echo request, and only interested clients in
1581  * this zone will receive a copy of the packet. This means that the caller must
1582  * call icmp_inbound() for each relevant zone.
1583  */
1584 static void
1585 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1586     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1587     ill_t *recv_ill, zoneid_t zoneid)
1588 {
1589 	icmph_t	*icmph;
1590 	ipha_t	*ipha;
1591 	int	iph_hdr_length;
1592 	int	hdr_length;
1593 	boolean_t	interested;
1594 	uint32_t	ts;
1595 	uchar_t	*wptr;
1596 	ipif_t	*ipif;
1597 	mblk_t *first_mp;
1598 	ipsec_in_t *ii;
1599 	ire_t *src_ire;
1600 	boolean_t onlink;
1601 	timestruc_t now;
1602 	uint32_t ill_index;
1603 	ip_stack_t *ipst;
1604 
1605 	ASSERT(ill != NULL);
1606 	ipst = ill->ill_ipst;
1607 
1608 	first_mp = mp;
1609 	if (mctl_present) {
1610 		mp = first_mp->b_cont;
1611 		ASSERT(mp != NULL);
1612 	}
1613 
1614 	ipha = (ipha_t *)mp->b_rptr;
1615 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1616 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1617 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1618 		if (first_mp == NULL)
1619 			return;
1620 	}
1621 
1622 	/*
1623 	 * On a labeled system, we have to check whether the zone itself is
1624 	 * permitted to receive raw traffic.
1625 	 */
1626 	if (is_system_labeled()) {
1627 		if (zoneid == ALL_ZONES)
1628 			zoneid = tsol_packet_to_zoneid(mp);
1629 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1630 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1631 			    zoneid));
1632 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1633 			freemsg(first_mp);
1634 			return;
1635 		}
1636 	}
1637 
1638 	/*
1639 	 * We have accepted the ICMP message. It means that we will
1640 	 * respond to the packet if needed. It may not be delivered
1641 	 * to the upper client depending on the policy constraints
1642 	 * and the disposition in ipsec_inbound_accept_clear.
1643 	 */
1644 
1645 	ASSERT(ill != NULL);
1646 
1647 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1648 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1649 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1650 		/* Last chance to get real. */
1651 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1652 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1653 			freemsg(first_mp);
1654 			return;
1655 		}
1656 		/* Refresh iph following the pullup. */
1657 		ipha = (ipha_t *)mp->b_rptr;
1658 	}
1659 	/* ICMP header checksum, including checksum field, should be zero. */
1660 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1661 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1662 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1663 		freemsg(first_mp);
1664 		return;
1665 	}
1666 	/* The IP header will always be a multiple of four bytes */
1667 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1668 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1669 	    icmph->icmph_code));
1670 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1671 	/* We will set "interested" to "true" if we want a copy */
1672 	interested = B_FALSE;
1673 	switch (icmph->icmph_type) {
1674 	case ICMP_ECHO_REPLY:
1675 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1676 		break;
1677 	case ICMP_DEST_UNREACHABLE:
1678 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1679 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1680 		interested = B_TRUE;	/* Pass up to transport */
1681 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1682 		break;
1683 	case ICMP_SOURCE_QUENCH:
1684 		interested = B_TRUE;	/* Pass up to transport */
1685 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1686 		break;
1687 	case ICMP_REDIRECT:
1688 		if (!ipst->ips_ip_ignore_redirect)
1689 			interested = B_TRUE;
1690 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1691 		break;
1692 	case ICMP_ECHO_REQUEST:
1693 		/*
1694 		 * Whether to respond to echo requests that come in as IP
1695 		 * broadcasts or as IP multicast is subject to debate
1696 		 * (what isn't?).  We aim to please, you pick it.
1697 		 * Default is do it.
1698 		 */
1699 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1700 			/* unicast: always respond */
1701 			interested = B_TRUE;
1702 		} else if (CLASSD(ipha->ipha_dst)) {
1703 			/* multicast: respond based on tunable */
1704 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1705 		} else if (broadcast) {
1706 			/* broadcast: respond based on tunable */
1707 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1708 		}
1709 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1710 		break;
1711 	case ICMP_ROUTER_ADVERTISEMENT:
1712 	case ICMP_ROUTER_SOLICITATION:
1713 		break;
1714 	case ICMP_TIME_EXCEEDED:
1715 		interested = B_TRUE;	/* Pass up to transport */
1716 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1717 		break;
1718 	case ICMP_PARAM_PROBLEM:
1719 		interested = B_TRUE;	/* Pass up to transport */
1720 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1721 		break;
1722 	case ICMP_TIME_STAMP_REQUEST:
1723 		/* Response to Time Stamp Requests is local policy. */
1724 		if (ipst->ips_ip_g_resp_to_timestamp &&
1725 		    /* So is whether to respond if it was an IP broadcast. */
1726 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1727 			int tstamp_len = 3 * sizeof (uint32_t);
1728 
1729 			if (wptr +  tstamp_len > mp->b_wptr) {
1730 				if (!pullupmsg(mp, wptr + tstamp_len -
1731 				    mp->b_rptr)) {
1732 					BUMP_MIB(ill->ill_ip_mib,
1733 					    ipIfStatsInDiscards);
1734 					freemsg(first_mp);
1735 					return;
1736 				}
1737 				/* Refresh ipha following the pullup. */
1738 				ipha = (ipha_t *)mp->b_rptr;
1739 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1740 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1741 			}
1742 			interested = B_TRUE;
1743 		}
1744 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1745 		break;
1746 	case ICMP_TIME_STAMP_REPLY:
1747 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1748 		break;
1749 	case ICMP_INFO_REQUEST:
1750 		/* Per RFC 1122 3.2.2.7, ignore this. */
1751 	case ICMP_INFO_REPLY:
1752 		break;
1753 	case ICMP_ADDRESS_MASK_REQUEST:
1754 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1755 			!broadcast) &&
1756 		    /* TODO m_pullup of complete header? */
1757 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1758 			interested = B_TRUE;
1759 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1760 		break;
1761 	case ICMP_ADDRESS_MASK_REPLY:
1762 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1763 		break;
1764 	default:
1765 		interested = B_TRUE;	/* Pass up to transport */
1766 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1767 		break;
1768 	}
1769 	/* See if there is an ICMP client. */
1770 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1771 		/* If there is an ICMP client and we want one too, copy it. */
1772 		mblk_t *first_mp1;
1773 
1774 		if (!interested) {
1775 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1776 			    ip_policy, recv_ill, zoneid);
1777 			return;
1778 		}
1779 		first_mp1 = ip_copymsg(first_mp);
1780 		if (first_mp1 != NULL) {
1781 			ip_fanout_proto(q, first_mp1, ill, ipha,
1782 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1783 		}
1784 	} else if (!interested) {
1785 		freemsg(first_mp);
1786 		return;
1787 	} else {
1788 		/*
1789 		 * Initiate policy processing for this packet if ip_policy
1790 		 * is true.
1791 		 */
1792 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1793 			ill_index = ill->ill_phyint->phyint_ifindex;
1794 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1795 			if (mp == NULL) {
1796 				if (mctl_present) {
1797 					freeb(first_mp);
1798 				}
1799 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1800 				return;
1801 			}
1802 		}
1803 	}
1804 	/* We want to do something with it. */
1805 	/* Check db_ref to make sure we can modify the packet. */
1806 	if (mp->b_datap->db_ref > 1) {
1807 		mblk_t	*first_mp1;
1808 
1809 		first_mp1 = ip_copymsg(first_mp);
1810 		freemsg(first_mp);
1811 		if (!first_mp1) {
1812 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1813 			return;
1814 		}
1815 		first_mp = first_mp1;
1816 		if (mctl_present) {
1817 			mp = first_mp->b_cont;
1818 			ASSERT(mp != NULL);
1819 		} else {
1820 			mp = first_mp;
1821 		}
1822 		ipha = (ipha_t *)mp->b_rptr;
1823 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1824 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1825 	}
1826 	switch (icmph->icmph_type) {
1827 	case ICMP_ADDRESS_MASK_REQUEST:
1828 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1829 		if (ipif == NULL) {
1830 			freemsg(first_mp);
1831 			return;
1832 		}
1833 		/*
1834 		 * outging interface must be IPv4
1835 		 */
1836 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1837 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1838 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1839 		ipif_refrele(ipif);
1840 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1841 		break;
1842 	case ICMP_ECHO_REQUEST:
1843 		icmph->icmph_type = ICMP_ECHO_REPLY;
1844 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1845 		break;
1846 	case ICMP_TIME_STAMP_REQUEST: {
1847 		uint32_t *tsp;
1848 
1849 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1850 		tsp = (uint32_t *)wptr;
1851 		tsp++;		/* Skip past 'originate time' */
1852 		/* Compute # of milliseconds since midnight */
1853 		gethrestime(&now);
1854 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1855 		    now.tv_nsec / (NANOSEC / MILLISEC);
1856 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1857 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1858 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1859 		break;
1860 	}
1861 	default:
1862 		ipha = (ipha_t *)&icmph[1];
1863 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1864 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1865 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1866 				freemsg(first_mp);
1867 				return;
1868 			}
1869 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1870 			ipha = (ipha_t *)&icmph[1];
1871 		}
1872 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1873 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1874 			freemsg(first_mp);
1875 			return;
1876 		}
1877 		hdr_length = IPH_HDR_LENGTH(ipha);
1878 		if (hdr_length < sizeof (ipha_t)) {
1879 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1880 			freemsg(first_mp);
1881 			return;
1882 		}
1883 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1884 			if (!pullupmsg(mp,
1885 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1886 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1887 				freemsg(first_mp);
1888 				return;
1889 			}
1890 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1891 			ipha = (ipha_t *)&icmph[1];
1892 		}
1893 		switch (icmph->icmph_type) {
1894 		case ICMP_REDIRECT:
1895 			/*
1896 			 * As there is no upper client to deliver, we don't
1897 			 * need the first_mp any more.
1898 			 */
1899 			if (mctl_present) {
1900 				freeb(first_mp);
1901 			}
1902 			icmp_redirect(ill, mp);
1903 			return;
1904 		case ICMP_DEST_UNREACHABLE:
1905 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1906 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1907 				    zoneid, mp, iph_hdr_length, ipst)) {
1908 					freemsg(first_mp);
1909 					return;
1910 				}
1911 				/*
1912 				 * icmp_inbound_too_big() may alter mp.
1913 				 * Resynch ipha and icmph accordingly.
1914 				 */
1915 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1916 				ipha = (ipha_t *)&icmph[1];
1917 			}
1918 			/* FALLTHRU */
1919 		default :
1920 			/*
1921 			 * IPQoS notes: Since we have already done IPQoS
1922 			 * processing we don't want to do it again in
1923 			 * the fanout routines called by
1924 			 * icmp_inbound_error_fanout, hence the last
1925 			 * argument, ip_policy, is B_FALSE.
1926 			 */
1927 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1928 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1929 			    B_FALSE, recv_ill, zoneid);
1930 		}
1931 		return;
1932 	}
1933 	/* Send out an ICMP packet */
1934 	icmph->icmph_checksum = 0;
1935 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1936 	if (icmph->icmph_checksum == 0)
1937 		icmph->icmph_checksum = 0xFFFF;
1938 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1939 		ipif_t	*ipif_chosen;
1940 		/*
1941 		 * Make it look like it was directed to us, so we don't look
1942 		 * like a fool with a broadcast or multicast source address.
1943 		 */
1944 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1945 		/*
1946 		 * Make sure that we haven't grabbed an interface that's DOWN.
1947 		 */
1948 		if (ipif != NULL) {
1949 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1950 			    ipha->ipha_src, zoneid);
1951 			if (ipif_chosen != NULL) {
1952 				ipif_refrele(ipif);
1953 				ipif = ipif_chosen;
1954 			}
1955 		}
1956 		if (ipif == NULL) {
1957 			ip0dbg(("icmp_inbound: "
1958 			    "No source for broadcast/multicast:\n"
1959 			    "\tsrc 0x%x dst 0x%x ill %p "
1960 			    "ipif_lcl_addr 0x%x\n",
1961 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1962 			    (void *)ill,
1963 			    ill->ill_ipif->ipif_lcl_addr));
1964 			freemsg(first_mp);
1965 			return;
1966 		}
1967 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1968 		ipha->ipha_dst = ipif->ipif_src_addr;
1969 		ipif_refrele(ipif);
1970 	}
1971 	/* Reset time to live. */
1972 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1973 	{
1974 		/* Swap source and destination addresses */
1975 		ipaddr_t tmp;
1976 
1977 		tmp = ipha->ipha_src;
1978 		ipha->ipha_src = ipha->ipha_dst;
1979 		ipha->ipha_dst = tmp;
1980 	}
1981 	ipha->ipha_ident = 0;
1982 	if (!IS_SIMPLE_IPH(ipha))
1983 		icmp_options_update(ipha);
1984 
1985 	/*
1986 	 * ICMP echo replies should go out on the same interface
1987 	 * the request came on as probes used by in.mpathd for detecting
1988 	 * NIC failures are ECHO packets. We turn-off load spreading
1989 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1990 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1991 	 * function. This is in turn handled by ip_wput and ip_newroute
1992 	 * to make sure that the packet goes out on the interface it came
1993 	 * in on. If we don't turnoff load spreading, the packets might get
1994 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1995 	 * to go out and in.mpathd would wrongly detect a failure or
1996 	 * mis-detect a NIC failure for link failure. As load spreading
1997 	 * can happen only if ill_group is not NULL, we do only for
1998 	 * that case and this does not affect the normal case.
1999 	 *
2000 	 * We turn off load spreading only on echo packets that came from
2001 	 * on-link hosts. If the interface route has been deleted, this will
2002 	 * not be enforced as we can't do much. For off-link hosts, as the
2003 	 * default routes in IPv4 does not typically have an ire_ipif
2004 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2005 	 * Moreover, expecting a default route through this interface may
2006 	 * not be correct. We use ipha_dst because of the swap above.
2007 	 */
2008 	onlink = B_FALSE;
2009 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2010 		/*
2011 		 * First, we need to make sure that it is not one of our
2012 		 * local addresses. If we set onlink when it is one of
2013 		 * our local addresses, we will end up creating IRE_CACHES
2014 		 * for one of our local addresses. Then, we will never
2015 		 * accept packets for them afterwards.
2016 		 */
2017 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2018 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2019 		if (src_ire == NULL) {
2020 			ipif = ipif_get_next_ipif(NULL, ill);
2021 			if (ipif == NULL) {
2022 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2023 				freemsg(mp);
2024 				return;
2025 			}
2026 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2027 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2028 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2029 			ipif_refrele(ipif);
2030 			if (src_ire != NULL) {
2031 				onlink = B_TRUE;
2032 				ire_refrele(src_ire);
2033 			}
2034 		} else {
2035 			ire_refrele(src_ire);
2036 		}
2037 	}
2038 	if (!mctl_present) {
2039 		/*
2040 		 * This packet should go out the same way as it
2041 		 * came in i.e in clear. To make sure that global
2042 		 * policy will not be applied to this in ip_wput_ire,
2043 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2044 		 */
2045 		ASSERT(first_mp == mp);
2046 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2047 		if (first_mp == NULL) {
2048 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2049 			freemsg(mp);
2050 			return;
2051 		}
2052 		ii = (ipsec_in_t *)first_mp->b_rptr;
2053 
2054 		/* This is not a secure packet */
2055 		ii->ipsec_in_secure = B_FALSE;
2056 		if (onlink) {
2057 			ii->ipsec_in_attach_if = B_TRUE;
2058 			ii->ipsec_in_ill_index =
2059 			    ill->ill_phyint->phyint_ifindex;
2060 			ii->ipsec_in_rill_index =
2061 			    recv_ill->ill_phyint->phyint_ifindex;
2062 		}
2063 		first_mp->b_cont = mp;
2064 	} else if (onlink) {
2065 		ii = (ipsec_in_t *)first_mp->b_rptr;
2066 		ii->ipsec_in_attach_if = B_TRUE;
2067 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2068 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2069 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2070 	} else {
2071 		ii = (ipsec_in_t *)first_mp->b_rptr;
2072 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2073 	}
2074 	ii->ipsec_in_zoneid = zoneid;
2075 	ASSERT(zoneid != ALL_ZONES);
2076 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2077 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2078 		return;
2079 	}
2080 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2081 	put(WR(q), first_mp);
2082 }
2083 
2084 static ipaddr_t
2085 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2086 {
2087 	conn_t *connp;
2088 	connf_t *connfp;
2089 	ipaddr_t nexthop_addr = INADDR_ANY;
2090 	int hdr_length = IPH_HDR_LENGTH(ipha);
2091 	uint16_t *up;
2092 	uint32_t ports;
2093 	ip_stack_t *ipst = ill->ill_ipst;
2094 
2095 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2096 	switch (ipha->ipha_protocol) {
2097 		case IPPROTO_TCP:
2098 		{
2099 			tcph_t *tcph;
2100 
2101 			/* do a reverse lookup */
2102 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2103 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2104 			    TCPS_LISTEN, ipst);
2105 			break;
2106 		}
2107 		case IPPROTO_UDP:
2108 		{
2109 			uint32_t dstport, srcport;
2110 
2111 			((uint16_t *)&ports)[0] = up[1];
2112 			((uint16_t *)&ports)[1] = up[0];
2113 
2114 			/* Extract ports in net byte order */
2115 			dstport = htons(ntohl(ports) & 0xFFFF);
2116 			srcport = htons(ntohl(ports) >> 16);
2117 
2118 			connfp = &ipst->ips_ipcl_udp_fanout[
2119 			    IPCL_UDP_HASH(dstport, ipst)];
2120 			mutex_enter(&connfp->connf_lock);
2121 			connp = connfp->connf_head;
2122 
2123 			/* do a reverse lookup */
2124 			while ((connp != NULL) &&
2125 			    (!IPCL_UDP_MATCH(connp, dstport,
2126 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2127 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2128 				connp = connp->conn_next;
2129 			}
2130 			if (connp != NULL)
2131 				CONN_INC_REF(connp);
2132 			mutex_exit(&connfp->connf_lock);
2133 			break;
2134 		}
2135 		case IPPROTO_SCTP:
2136 		{
2137 			in6_addr_t map_src, map_dst;
2138 
2139 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2140 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2141 			((uint16_t *)&ports)[0] = up[1];
2142 			((uint16_t *)&ports)[1] = up[0];
2143 
2144 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2145 			    zoneid, ipst->ips_netstack->netstack_sctp);
2146 			if (connp == NULL) {
2147 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2148 				    zoneid, ports, ipha, ipst);
2149 			} else {
2150 				CONN_INC_REF(connp);
2151 				SCTP_REFRELE(CONN2SCTP(connp));
2152 			}
2153 			break;
2154 		}
2155 		default:
2156 		{
2157 			ipha_t ripha;
2158 
2159 			ripha.ipha_src = ipha->ipha_dst;
2160 			ripha.ipha_dst = ipha->ipha_src;
2161 			ripha.ipha_protocol = ipha->ipha_protocol;
2162 
2163 			connfp = &ipst->ips_ipcl_proto_fanout[
2164 			    ipha->ipha_protocol];
2165 			mutex_enter(&connfp->connf_lock);
2166 			connp = connfp->connf_head;
2167 			for (connp = connfp->connf_head; connp != NULL;
2168 			    connp = connp->conn_next) {
2169 				if (IPCL_PROTO_MATCH(connp,
2170 				    ipha->ipha_protocol, &ripha, ill,
2171 				    0, zoneid)) {
2172 					CONN_INC_REF(connp);
2173 					break;
2174 				}
2175 			}
2176 			mutex_exit(&connfp->connf_lock);
2177 		}
2178 	}
2179 	if (connp != NULL) {
2180 		if (connp->conn_nexthop_set)
2181 			nexthop_addr = connp->conn_nexthop_v4;
2182 		CONN_DEC_REF(connp);
2183 	}
2184 	return (nexthop_addr);
2185 }
2186 
2187 /* Table from RFC 1191 */
2188 static int icmp_frag_size_table[] =
2189 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2190 
2191 /*
2192  * Process received ICMP Packet too big.
2193  * After updating any IRE it does the fanout to any matching transport streams.
2194  * Assumes the message has been pulled up till the IP header that caused
2195  * the error.
2196  *
2197  * Returns B_FALSE on failure and B_TRUE on success.
2198  */
2199 static boolean_t
2200 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2201     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2202     ip_stack_t *ipst)
2203 {
2204 	ire_t	*ire, *first_ire;
2205 	int	mtu;
2206 	int	hdr_length;
2207 	ipaddr_t nexthop_addr;
2208 
2209 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2210 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2211 	ASSERT(ill != NULL);
2212 
2213 	hdr_length = IPH_HDR_LENGTH(ipha);
2214 
2215 	/* Drop if the original packet contained a source route */
2216 	if (ip_source_route_included(ipha)) {
2217 		return (B_FALSE);
2218 	}
2219 	/*
2220 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2221 	 * header.
2222 	 */
2223 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2224 	    mp->b_wptr) {
2225 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2226 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2227 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2228 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2229 			return (B_FALSE);
2230 		}
2231 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2232 		ipha = (ipha_t *)&icmph[1];
2233 	}
2234 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2235 	if (nexthop_addr != INADDR_ANY) {
2236 		/* nexthop set */
2237 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2238 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2239 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2240 	} else {
2241 		/* nexthop not set */
2242 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2243 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2244 	}
2245 
2246 	if (!first_ire) {
2247 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2248 		    ntohl(ipha->ipha_dst)));
2249 		return (B_FALSE);
2250 	}
2251 	/* Check for MTU discovery advice as described in RFC 1191 */
2252 	mtu = ntohs(icmph->icmph_du_mtu);
2253 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2254 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2255 	    ire = ire->ire_next) {
2256 		/*
2257 		 * Look for the connection to which this ICMP message is
2258 		 * directed. If it has the IP_NEXTHOP option set, then the
2259 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2260 		 * option. Else the search is limited to regular IREs.
2261 		 */
2262 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2263 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2264 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2265 		    (nexthop_addr != INADDR_ANY)))
2266 			continue;
2267 
2268 		mutex_enter(&ire->ire_lock);
2269 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2270 			/* Reduce the IRE max frag value as advised. */
2271 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2272 			    mtu, ire->ire_max_frag));
2273 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2274 		} else {
2275 			uint32_t length;
2276 			int	i;
2277 
2278 			/*
2279 			 * Use the table from RFC 1191 to figure out
2280 			 * the next "plateau" based on the length in
2281 			 * the original IP packet.
2282 			 */
2283 			length = ntohs(ipha->ipha_length);
2284 			if (ire->ire_max_frag <= length &&
2285 			    ire->ire_max_frag >= length - hdr_length) {
2286 				/*
2287 				 * Handle broken BSD 4.2 systems that
2288 				 * return the wrong iph_length in ICMP
2289 				 * errors.
2290 				 */
2291 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2292 				    length, ire->ire_max_frag));
2293 				length -= hdr_length;
2294 			}
2295 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2296 				if (length > icmp_frag_size_table[i])
2297 					break;
2298 			}
2299 			if (i == A_CNT(icmp_frag_size_table)) {
2300 				/* Smaller than 68! */
2301 				ip1dbg(("Too big for packet size %d\n",
2302 				    length));
2303 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2304 				ire->ire_frag_flag = 0;
2305 			} else {
2306 				mtu = icmp_frag_size_table[i];
2307 				ip1dbg(("Calculated mtu %d, packet size %d, "
2308 				    "before %d", mtu, length,
2309 				    ire->ire_max_frag));
2310 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2311 				ip1dbg((", after %d\n", ire->ire_max_frag));
2312 			}
2313 			/* Record the new max frag size for the ULP. */
2314 			icmph->icmph_du_zero = 0;
2315 			icmph->icmph_du_mtu =
2316 			    htons((uint16_t)ire->ire_max_frag);
2317 		}
2318 		mutex_exit(&ire->ire_lock);
2319 	}
2320 	rw_exit(&first_ire->ire_bucket->irb_lock);
2321 	ire_refrele(first_ire);
2322 	return (B_TRUE);
2323 }
2324 
2325 /*
2326  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2327  * calls this function.
2328  */
2329 static mblk_t *
2330 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2331 {
2332 	ipha_t *ipha;
2333 	icmph_t *icmph;
2334 	ipha_t *in_ipha;
2335 	int length;
2336 
2337 	ASSERT(mp->b_datap->db_type == M_DATA);
2338 
2339 	/*
2340 	 * For Self-encapsulated packets, we added an extra IP header
2341 	 * without the options. Inner IP header is the one from which
2342 	 * the outer IP header was formed. Thus, we need to remove the
2343 	 * outer IP header. To do this, we pullup the whole message
2344 	 * and overlay whatever follows the outer IP header over the
2345 	 * outer IP header.
2346 	 */
2347 
2348 	if (!pullupmsg(mp, -1))
2349 		return (NULL);
2350 
2351 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2352 	ipha = (ipha_t *)&icmph[1];
2353 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2354 
2355 	/*
2356 	 * The length that we want to overlay is following the inner
2357 	 * IP header. Subtracting the IP header + icmp header + outer
2358 	 * IP header's length should give us the length that we want to
2359 	 * overlay.
2360 	 */
2361 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2362 	    hdr_length;
2363 	/*
2364 	 * Overlay whatever follows the inner header over the
2365 	 * outer header.
2366 	 */
2367 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2368 
2369 	/* Set the wptr to account for the outer header */
2370 	mp->b_wptr -= hdr_length;
2371 	return (mp);
2372 }
2373 
2374 /*
2375  * Try to pass the ICMP message upstream in case the ULP cares.
2376  *
2377  * If the packet that caused the ICMP error is secure, we send
2378  * it to AH/ESP to make sure that the attached packet has a
2379  * valid association. ipha in the code below points to the
2380  * IP header of the packet that caused the error.
2381  *
2382  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2383  * in the context of IPSEC. Normally we tell the upper layer
2384  * whenever we send the ire (including ip_bind), the IPSEC header
2385  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2386  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2387  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2388  * same thing. As TCP has the IPSEC options size that needs to be
2389  * adjusted, we just pass the MTU unchanged.
2390  *
2391  * IFN could have been generated locally or by some router.
2392  *
2393  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2394  *	    This happens because IP adjusted its value of MTU on an
2395  *	    earlier IFN message and could not tell the upper layer,
2396  *	    the new adjusted value of MTU e.g. Packet was encrypted
2397  *	    or there was not enough information to fanout to upper
2398  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2399  *	    generates the IFN, where IPSEC processing has *not* been
2400  *	    done.
2401  *
2402  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2403  *	    could have generated this. This happens because ire_max_frag
2404  *	    value in IP was set to a new value, while the IPSEC processing
2405  *	    was being done and after we made the fragmentation check in
2406  *	    ip_wput_ire. Thus on return from IPSEC processing,
2407  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2408  *	    and generates the IFN. As IPSEC processing is over, we fanout
2409  *	    to AH/ESP to remove the header.
2410  *
2411  *	    In both these cases, ipsec_in_loopback will be set indicating
2412  *	    that IFN was generated locally.
2413  *
2414  * ROUTER : IFN could be secure or non-secure.
2415  *
2416  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2417  *	      packet in error has AH/ESP headers to validate the AH/ESP
2418  *	      headers. AH/ESP will verify whether there is a valid SA or
2419  *	      not and send it back. We will fanout again if we have more
2420  *	      data in the packet.
2421  *
2422  *	      If the packet in error does not have AH/ESP, we handle it
2423  *	      like any other case.
2424  *
2425  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2426  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2427  *	      for validation. AH/ESP will verify whether there is a
2428  *	      valid SA or not and send it back. We will fanout again if
2429  *	      we have more data in the packet.
2430  *
2431  *	      If the packet in error does not have AH/ESP, we handle it
2432  *	      like any other case.
2433  */
2434 static void
2435 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2436     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2437     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2438     zoneid_t zoneid)
2439 {
2440 	uint16_t *up;	/* Pointer to ports in ULP header */
2441 	uint32_t ports;	/* reversed ports for fanout */
2442 	ipha_t ripha;	/* With reversed addresses */
2443 	mblk_t *first_mp;
2444 	ipsec_in_t *ii;
2445 	tcph_t	*tcph;
2446 	conn_t	*connp;
2447 	ip_stack_t *ipst;
2448 
2449 	ASSERT(ill != NULL);
2450 
2451 	ASSERT(recv_ill != NULL);
2452 	ipst = recv_ill->ill_ipst;
2453 
2454 	first_mp = mp;
2455 	if (mctl_present) {
2456 		mp = first_mp->b_cont;
2457 		ASSERT(mp != NULL);
2458 
2459 		ii = (ipsec_in_t *)first_mp->b_rptr;
2460 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2461 	} else {
2462 		ii = NULL;
2463 	}
2464 
2465 	switch (ipha->ipha_protocol) {
2466 	case IPPROTO_UDP:
2467 		/*
2468 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2469 		 * transport header.
2470 		 */
2471 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2472 		    mp->b_wptr) {
2473 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2474 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2475 				goto discard_pkt;
2476 			}
2477 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2478 			ipha = (ipha_t *)&icmph[1];
2479 		}
2480 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2481 
2482 		/*
2483 		 * Attempt to find a client stream based on port.
2484 		 * Note that we do a reverse lookup since the header is
2485 		 * in the form we sent it out.
2486 		 * The ripha header is only used for the IP_UDP_MATCH and we
2487 		 * only set the src and dst addresses and protocol.
2488 		 */
2489 		ripha.ipha_src = ipha->ipha_dst;
2490 		ripha.ipha_dst = ipha->ipha_src;
2491 		ripha.ipha_protocol = ipha->ipha_protocol;
2492 		((uint16_t *)&ports)[0] = up[1];
2493 		((uint16_t *)&ports)[1] = up[0];
2494 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2495 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2496 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2497 		    icmph->icmph_type, icmph->icmph_code));
2498 
2499 		/* Have to change db_type after any pullupmsg */
2500 		DB_TYPE(mp) = M_CTL;
2501 
2502 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2503 		    mctl_present, ip_policy, recv_ill, zoneid);
2504 		return;
2505 
2506 	case IPPROTO_TCP:
2507 		/*
2508 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2509 		 * transport header.
2510 		 */
2511 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2512 		    mp->b_wptr) {
2513 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2514 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2515 				goto discard_pkt;
2516 			}
2517 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2518 			ipha = (ipha_t *)&icmph[1];
2519 		}
2520 		/*
2521 		 * Find a TCP client stream for this packet.
2522 		 * Note that we do a reverse lookup since the header is
2523 		 * in the form we sent it out.
2524 		 */
2525 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2526 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2527 		    ipst);
2528 		if (connp == NULL)
2529 			goto discard_pkt;
2530 
2531 		/* Have to change db_type after any pullupmsg */
2532 		DB_TYPE(mp) = M_CTL;
2533 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2534 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2535 		return;
2536 
2537 	case IPPROTO_SCTP:
2538 		/*
2539 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2540 		 * transport header.
2541 		 */
2542 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2543 		    mp->b_wptr) {
2544 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2545 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2546 				goto discard_pkt;
2547 			}
2548 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2549 			ipha = (ipha_t *)&icmph[1];
2550 		}
2551 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2552 		/*
2553 		 * Find a SCTP client stream for this packet.
2554 		 * Note that we do a reverse lookup since the header is
2555 		 * in the form we sent it out.
2556 		 * The ripha header is only used for the matching and we
2557 		 * only set the src and dst addresses, protocol, and version.
2558 		 */
2559 		ripha.ipha_src = ipha->ipha_dst;
2560 		ripha.ipha_dst = ipha->ipha_src;
2561 		ripha.ipha_protocol = ipha->ipha_protocol;
2562 		ripha.ipha_version_and_hdr_length =
2563 		    ipha->ipha_version_and_hdr_length;
2564 		((uint16_t *)&ports)[0] = up[1];
2565 		((uint16_t *)&ports)[1] = up[0];
2566 
2567 		/* Have to change db_type after any pullupmsg */
2568 		DB_TYPE(mp) = M_CTL;
2569 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2570 		    mctl_present, ip_policy, zoneid);
2571 		return;
2572 
2573 	case IPPROTO_ESP:
2574 	case IPPROTO_AH: {
2575 		int ipsec_rc;
2576 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2577 
2578 		/*
2579 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2580 		 * We will re-use the IPSEC_IN if it is already present as
2581 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2582 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2583 		 * one and attach it in the front.
2584 		 */
2585 		if (ii != NULL) {
2586 			/*
2587 			 * ip_fanout_proto_again converts the ICMP errors
2588 			 * that come back from AH/ESP to M_DATA so that
2589 			 * if it is non-AH/ESP and we do a pullupmsg in
2590 			 * this function, it would work. Convert it back
2591 			 * to M_CTL before we send up as this is a ICMP
2592 			 * error. This could have been generated locally or
2593 			 * by some router. Validate the inner IPSEC
2594 			 * headers.
2595 			 *
2596 			 * NOTE : ill_index is used by ip_fanout_proto_again
2597 			 * to locate the ill.
2598 			 */
2599 			ASSERT(ill != NULL);
2600 			ii->ipsec_in_ill_index =
2601 			    ill->ill_phyint->phyint_ifindex;
2602 			ii->ipsec_in_rill_index =
2603 			    recv_ill->ill_phyint->phyint_ifindex;
2604 			DB_TYPE(first_mp->b_cont) = M_CTL;
2605 		} else {
2606 			/*
2607 			 * IPSEC_IN is not present. We attach a ipsec_in
2608 			 * message and send up to IPSEC for validating
2609 			 * and removing the IPSEC headers. Clear
2610 			 * ipsec_in_secure so that when we return
2611 			 * from IPSEC, we don't mistakenly think that this
2612 			 * is a secure packet came from the network.
2613 			 *
2614 			 * NOTE : ill_index is used by ip_fanout_proto_again
2615 			 * to locate the ill.
2616 			 */
2617 			ASSERT(first_mp == mp);
2618 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2619 			if (first_mp == NULL) {
2620 				freemsg(mp);
2621 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2622 				return;
2623 			}
2624 			ii = (ipsec_in_t *)first_mp->b_rptr;
2625 
2626 			/* This is not a secure packet */
2627 			ii->ipsec_in_secure = B_FALSE;
2628 			first_mp->b_cont = mp;
2629 			DB_TYPE(mp) = M_CTL;
2630 			ASSERT(ill != NULL);
2631 			ii->ipsec_in_ill_index =
2632 			    ill->ill_phyint->phyint_ifindex;
2633 			ii->ipsec_in_rill_index =
2634 			    recv_ill->ill_phyint->phyint_ifindex;
2635 		}
2636 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2637 
2638 		if (!ipsec_loaded(ipss)) {
2639 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2640 			return;
2641 		}
2642 
2643 		if (ipha->ipha_protocol == IPPROTO_ESP)
2644 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2645 		else
2646 			ipsec_rc = ipsecah_icmp_error(first_mp);
2647 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2648 			return;
2649 
2650 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2651 		return;
2652 	}
2653 	default:
2654 		/*
2655 		 * The ripha header is only used for the lookup and we
2656 		 * only set the src and dst addresses and protocol.
2657 		 */
2658 		ripha.ipha_src = ipha->ipha_dst;
2659 		ripha.ipha_dst = ipha->ipha_src;
2660 		ripha.ipha_protocol = ipha->ipha_protocol;
2661 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2662 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2663 		    ntohl(ipha->ipha_dst),
2664 		    icmph->icmph_type, icmph->icmph_code));
2665 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2666 			ipha_t *in_ipha;
2667 
2668 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2669 			    mp->b_wptr) {
2670 				if (!pullupmsg(mp, (uchar_t *)ipha +
2671 				    hdr_length + sizeof (ipha_t) -
2672 				    mp->b_rptr)) {
2673 					goto discard_pkt;
2674 				}
2675 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2676 				ipha = (ipha_t *)&icmph[1];
2677 			}
2678 			/*
2679 			 * Caller has verified that length has to be
2680 			 * at least the size of IP header.
2681 			 */
2682 			ASSERT(hdr_length >= sizeof (ipha_t));
2683 			/*
2684 			 * Check the sanity of the inner IP header like
2685 			 * we did for the outer header.
2686 			 */
2687 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2688 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2689 				goto discard_pkt;
2690 			}
2691 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2692 				goto discard_pkt;
2693 			}
2694 			/* Check for Self-encapsulated tunnels */
2695 			if (in_ipha->ipha_src == ipha->ipha_src &&
2696 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2697 
2698 				mp = icmp_inbound_self_encap_error(mp,
2699 				    iph_hdr_length, hdr_length);
2700 				if (mp == NULL)
2701 					goto discard_pkt;
2702 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2703 				ipha = (ipha_t *)&icmph[1];
2704 				hdr_length = IPH_HDR_LENGTH(ipha);
2705 				/*
2706 				 * The packet in error is self-encapsualted.
2707 				 * And we are finding it further encapsulated
2708 				 * which we could not have possibly generated.
2709 				 */
2710 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2711 					goto discard_pkt;
2712 				}
2713 				icmp_inbound_error_fanout(q, ill, first_mp,
2714 				    icmph, ipha, iph_hdr_length, hdr_length,
2715 				    mctl_present, ip_policy, recv_ill, zoneid);
2716 				return;
2717 			}
2718 		}
2719 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2720 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2721 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2722 		    ii != NULL &&
2723 		    ii->ipsec_in_loopback &&
2724 		    ii->ipsec_in_secure) {
2725 			/*
2726 			 * For IP tunnels that get a looped-back
2727 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2728 			 * reported new MTU to take into account the IPsec
2729 			 * headers protecting this configured tunnel.
2730 			 *
2731 			 * This allows the tunnel module (tun.c) to blindly
2732 			 * accept the MTU reported in an ICMP "too big"
2733 			 * message.
2734 			 *
2735 			 * Non-looped back ICMP messages will just be
2736 			 * handled by the security protocols (if needed),
2737 			 * and the first subsequent packet will hit this
2738 			 * path.
2739 			 */
2740 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2741 			    ipsec_in_extra_length(first_mp));
2742 		}
2743 		/* Have to change db_type after any pullupmsg */
2744 		DB_TYPE(mp) = M_CTL;
2745 
2746 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2747 		    ip_policy, recv_ill, zoneid);
2748 		return;
2749 	}
2750 	/* NOTREACHED */
2751 discard_pkt:
2752 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2753 drop_pkt:;
2754 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2755 	freemsg(first_mp);
2756 }
2757 
2758 /*
2759  * Common IP options parser.
2760  *
2761  * Setup routine: fill in *optp with options-parsing state, then
2762  * tail-call ipoptp_next to return the first option.
2763  */
2764 uint8_t
2765 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2766 {
2767 	uint32_t totallen; /* total length of all options */
2768 
2769 	totallen = ipha->ipha_version_and_hdr_length -
2770 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2771 	totallen <<= 2;
2772 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2773 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2774 	optp->ipoptp_flags = 0;
2775 	return (ipoptp_next(optp));
2776 }
2777 
2778 /*
2779  * Common IP options parser: extract next option.
2780  */
2781 uint8_t
2782 ipoptp_next(ipoptp_t *optp)
2783 {
2784 	uint8_t *end = optp->ipoptp_end;
2785 	uint8_t *cur = optp->ipoptp_next;
2786 	uint8_t opt, len, pointer;
2787 
2788 	/*
2789 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2790 	 * has been corrupted.
2791 	 */
2792 	ASSERT(cur <= end);
2793 
2794 	if (cur == end)
2795 		return (IPOPT_EOL);
2796 
2797 	opt = cur[IPOPT_OPTVAL];
2798 
2799 	/*
2800 	 * Skip any NOP options.
2801 	 */
2802 	while (opt == IPOPT_NOP) {
2803 		cur++;
2804 		if (cur == end)
2805 			return (IPOPT_EOL);
2806 		opt = cur[IPOPT_OPTVAL];
2807 	}
2808 
2809 	if (opt == IPOPT_EOL)
2810 		return (IPOPT_EOL);
2811 
2812 	/*
2813 	 * Option requiring a length.
2814 	 */
2815 	if ((cur + 1) >= end) {
2816 		optp->ipoptp_flags |= IPOPTP_ERROR;
2817 		return (IPOPT_EOL);
2818 	}
2819 	len = cur[IPOPT_OLEN];
2820 	if (len < 2) {
2821 		optp->ipoptp_flags |= IPOPTP_ERROR;
2822 		return (IPOPT_EOL);
2823 	}
2824 	optp->ipoptp_cur = cur;
2825 	optp->ipoptp_len = len;
2826 	optp->ipoptp_next = cur + len;
2827 	if (cur + len > end) {
2828 		optp->ipoptp_flags |= IPOPTP_ERROR;
2829 		return (IPOPT_EOL);
2830 	}
2831 
2832 	/*
2833 	 * For the options which require a pointer field, make sure
2834 	 * its there, and make sure it points to either something
2835 	 * inside this option, or the end of the option.
2836 	 */
2837 	switch (opt) {
2838 	case IPOPT_RR:
2839 	case IPOPT_TS:
2840 	case IPOPT_LSRR:
2841 	case IPOPT_SSRR:
2842 		if (len <= IPOPT_OFFSET) {
2843 			optp->ipoptp_flags |= IPOPTP_ERROR;
2844 			return (opt);
2845 		}
2846 		pointer = cur[IPOPT_OFFSET];
2847 		if (pointer - 1 > len) {
2848 			optp->ipoptp_flags |= IPOPTP_ERROR;
2849 			return (opt);
2850 		}
2851 		break;
2852 	}
2853 
2854 	/*
2855 	 * Sanity check the pointer field based on the type of the
2856 	 * option.
2857 	 */
2858 	switch (opt) {
2859 	case IPOPT_RR:
2860 	case IPOPT_SSRR:
2861 	case IPOPT_LSRR:
2862 		if (pointer < IPOPT_MINOFF_SR)
2863 			optp->ipoptp_flags |= IPOPTP_ERROR;
2864 		break;
2865 	case IPOPT_TS:
2866 		if (pointer < IPOPT_MINOFF_IT)
2867 			optp->ipoptp_flags |= IPOPTP_ERROR;
2868 		/*
2869 		 * Note that the Internet Timestamp option also
2870 		 * contains two four bit fields (the Overflow field,
2871 		 * and the Flag field), which follow the pointer
2872 		 * field.  We don't need to check that these fields
2873 		 * fall within the length of the option because this
2874 		 * was implicitely done above.  We've checked that the
2875 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2876 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2877 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2878 		 */
2879 		ASSERT(len > IPOPT_POS_OV_FLG);
2880 		break;
2881 	}
2882 
2883 	return (opt);
2884 }
2885 
2886 /*
2887  * Use the outgoing IP header to create an IP_OPTIONS option the way
2888  * it was passed down from the application.
2889  */
2890 int
2891 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2892 {
2893 	ipoptp_t	opts;
2894 	const uchar_t	*opt;
2895 	uint8_t		optval;
2896 	uint8_t		optlen;
2897 	uint32_t	len = 0;
2898 	uchar_t	*buf1 = buf;
2899 
2900 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2901 	len += IP_ADDR_LEN;
2902 	bzero(buf1, IP_ADDR_LEN);
2903 
2904 	/*
2905 	 * OK to cast away const here, as we don't store through the returned
2906 	 * opts.ipoptp_cur pointer.
2907 	 */
2908 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2909 	    optval != IPOPT_EOL;
2910 	    optval = ipoptp_next(&opts)) {
2911 		int	off;
2912 
2913 		opt = opts.ipoptp_cur;
2914 		optlen = opts.ipoptp_len;
2915 		switch (optval) {
2916 		case IPOPT_SSRR:
2917 		case IPOPT_LSRR:
2918 
2919 			/*
2920 			 * Insert ipha_dst as the first entry in the source
2921 			 * route and move down the entries on step.
2922 			 * The last entry gets placed at buf1.
2923 			 */
2924 			buf[IPOPT_OPTVAL] = optval;
2925 			buf[IPOPT_OLEN] = optlen;
2926 			buf[IPOPT_OFFSET] = optlen;
2927 
2928 			off = optlen - IP_ADDR_LEN;
2929 			if (off < 0) {
2930 				/* No entries in source route */
2931 				break;
2932 			}
2933 			/* Last entry in source route */
2934 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2935 			off -= IP_ADDR_LEN;
2936 
2937 			while (off > 0) {
2938 				bcopy(opt + off,
2939 				    buf + off + IP_ADDR_LEN,
2940 				    IP_ADDR_LEN);
2941 				off -= IP_ADDR_LEN;
2942 			}
2943 			/* ipha_dst into first slot */
2944 			bcopy(&ipha->ipha_dst,
2945 			    buf + off + IP_ADDR_LEN,
2946 			    IP_ADDR_LEN);
2947 			buf += optlen;
2948 			len += optlen;
2949 			break;
2950 
2951 		case IPOPT_COMSEC:
2952 		case IPOPT_SECURITY:
2953 			/* if passing up a label is not ok, then remove */
2954 			if (is_system_labeled())
2955 				break;
2956 			/* FALLTHROUGH */
2957 		default:
2958 			bcopy(opt, buf, optlen);
2959 			buf += optlen;
2960 			len += optlen;
2961 			break;
2962 		}
2963 	}
2964 done:
2965 	/* Pad the resulting options */
2966 	while (len & 0x3) {
2967 		*buf++ = IPOPT_EOL;
2968 		len++;
2969 	}
2970 	return (len);
2971 }
2972 
2973 /*
2974  * Update any record route or timestamp options to include this host.
2975  * Reverse any source route option.
2976  * This routine assumes that the options are well formed i.e. that they
2977  * have already been checked.
2978  */
2979 static void
2980 icmp_options_update(ipha_t *ipha)
2981 {
2982 	ipoptp_t	opts;
2983 	uchar_t		*opt;
2984 	uint8_t		optval;
2985 	ipaddr_t	src;		/* Our local address */
2986 	ipaddr_t	dst;
2987 
2988 	ip2dbg(("icmp_options_update\n"));
2989 	src = ipha->ipha_src;
2990 	dst = ipha->ipha_dst;
2991 
2992 	for (optval = ipoptp_first(&opts, ipha);
2993 	    optval != IPOPT_EOL;
2994 	    optval = ipoptp_next(&opts)) {
2995 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2996 		opt = opts.ipoptp_cur;
2997 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2998 		    optval, opts.ipoptp_len));
2999 		switch (optval) {
3000 			int off1, off2;
3001 		case IPOPT_SSRR:
3002 		case IPOPT_LSRR:
3003 			/*
3004 			 * Reverse the source route.  The first entry
3005 			 * should be the next to last one in the current
3006 			 * source route (the last entry is our address).
3007 			 * The last entry should be the final destination.
3008 			 */
3009 			off1 = IPOPT_MINOFF_SR - 1;
3010 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3011 			if (off2 < 0) {
3012 				/* No entries in source route */
3013 				ip1dbg((
3014 				    "icmp_options_update: bad src route\n"));
3015 				break;
3016 			}
3017 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3018 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3019 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3020 			off2 -= IP_ADDR_LEN;
3021 
3022 			while (off1 < off2) {
3023 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3024 				bcopy((char *)opt + off2, (char *)opt + off1,
3025 				    IP_ADDR_LEN);
3026 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3027 				off1 += IP_ADDR_LEN;
3028 				off2 -= IP_ADDR_LEN;
3029 			}
3030 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3031 			break;
3032 		}
3033 	}
3034 }
3035 
3036 /*
3037  * Process received ICMP Redirect messages.
3038  */
3039 static void
3040 icmp_redirect(ill_t *ill, mblk_t *mp)
3041 {
3042 	ipha_t	*ipha;
3043 	int	iph_hdr_length;
3044 	icmph_t	*icmph;
3045 	ipha_t	*ipha_err;
3046 	ire_t	*ire;
3047 	ire_t	*prev_ire;
3048 	ire_t	*save_ire;
3049 	ipaddr_t  src, dst, gateway;
3050 	iulp_t	ulp_info = { 0 };
3051 	int	error;
3052 	ip_stack_t *ipst;
3053 
3054 	ASSERT(ill != NULL);
3055 	ipst = ill->ill_ipst;
3056 
3057 	ipha = (ipha_t *)mp->b_rptr;
3058 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3059 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3060 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3061 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3062 		freemsg(mp);
3063 		return;
3064 	}
3065 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3066 	ipha_err = (ipha_t *)&icmph[1];
3067 	src = ipha->ipha_src;
3068 	dst = ipha_err->ipha_dst;
3069 	gateway = icmph->icmph_rd_gateway;
3070 	/* Make sure the new gateway is reachable somehow. */
3071 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3072 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3073 	/*
3074 	 * Make sure we had a route for the dest in question and that
3075 	 * that route was pointing to the old gateway (the source of the
3076 	 * redirect packet.)
3077 	 */
3078 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3079 	    NULL, MATCH_IRE_GW, ipst);
3080 	/*
3081 	 * Check that
3082 	 *	the redirect was not from ourselves
3083 	 *	the new gateway and the old gateway are directly reachable
3084 	 */
3085 	if (!prev_ire ||
3086 	    !ire ||
3087 	    ire->ire_type == IRE_LOCAL) {
3088 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3089 		freemsg(mp);
3090 		if (ire != NULL)
3091 			ire_refrele(ire);
3092 		if (prev_ire != NULL)
3093 			ire_refrele(prev_ire);
3094 		return;
3095 	}
3096 
3097 	/*
3098 	 * Should we use the old ULP info to create the new gateway?  From
3099 	 * a user's perspective, we should inherit the info so that it
3100 	 * is a "smooth" transition.  If we do not do that, then new
3101 	 * connections going thru the new gateway will have no route metrics,
3102 	 * which is counter-intuitive to user.  From a network point of
3103 	 * view, this may or may not make sense even though the new gateway
3104 	 * is still directly connected to us so the route metrics should not
3105 	 * change much.
3106 	 *
3107 	 * But if the old ire_uinfo is not initialized, we do another
3108 	 * recursive lookup on the dest using the new gateway.  There may
3109 	 * be a route to that.  If so, use it to initialize the redirect
3110 	 * route.
3111 	 */
3112 	if (prev_ire->ire_uinfo.iulp_set) {
3113 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3114 	} else {
3115 		ire_t *tmp_ire;
3116 		ire_t *sire;
3117 
3118 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3119 		    ALL_ZONES, 0, NULL,
3120 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3121 		    ipst);
3122 		if (sire != NULL) {
3123 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3124 			/*
3125 			 * If sire != NULL, ire_ftable_lookup() should not
3126 			 * return a NULL value.
3127 			 */
3128 			ASSERT(tmp_ire != NULL);
3129 			ire_refrele(tmp_ire);
3130 			ire_refrele(sire);
3131 		} else if (tmp_ire != NULL) {
3132 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3133 			    sizeof (iulp_t));
3134 			ire_refrele(tmp_ire);
3135 		}
3136 	}
3137 	if (prev_ire->ire_type == IRE_CACHE)
3138 		ire_delete(prev_ire);
3139 	ire_refrele(prev_ire);
3140 	/*
3141 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3142 	 * require TOS routing
3143 	 */
3144 	switch (icmph->icmph_code) {
3145 	case 0:
3146 	case 1:
3147 		/* TODO: TOS specificity for cases 2 and 3 */
3148 	case 2:
3149 	case 3:
3150 		break;
3151 	default:
3152 		freemsg(mp);
3153 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3154 		ire_refrele(ire);
3155 		return;
3156 	}
3157 	/*
3158 	 * Create a Route Association.  This will allow us to remember that
3159 	 * someone we believe told us to use the particular gateway.
3160 	 */
3161 	save_ire = ire;
3162 	ire = ire_create(
3163 		(uchar_t *)&dst,			/* dest addr */
3164 		(uchar_t *)&ip_g_all_ones,		/* mask */
3165 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3166 		(uchar_t *)&gateway,			/* gateway addr */
3167 		NULL,					/* no in_srcaddr */
3168 		&save_ire->ire_max_frag,		/* max frag */
3169 		NULL,					/* Fast Path header */
3170 		NULL,					/* no rfq */
3171 		NULL,					/* no stq */
3172 		IRE_HOST,
3173 		NULL,
3174 		NULL,
3175 		NULL,
3176 		0,
3177 		0,
3178 		0,
3179 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3180 		&ulp_info,
3181 		NULL,
3182 		NULL,
3183 		ipst);
3184 
3185 	if (ire == NULL) {
3186 		freemsg(mp);
3187 		ire_refrele(save_ire);
3188 		return;
3189 	}
3190 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3191 	ire_refrele(save_ire);
3192 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3193 
3194 	if (error == 0) {
3195 		ire_refrele(ire);		/* Held in ire_add_v4 */
3196 		/* tell routing sockets that we received a redirect */
3197 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3198 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3199 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3200 	}
3201 
3202 	/*
3203 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3204 	 * This together with the added IRE has the effect of
3205 	 * modifying an existing redirect.
3206 	 */
3207 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3208 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3209 	if (prev_ire != NULL) {
3210 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3211 			ire_delete(prev_ire);
3212 		ire_refrele(prev_ire);
3213 	}
3214 
3215 	freemsg(mp);
3216 }
3217 
3218 /*
3219  * Generate an ICMP parameter problem message.
3220  */
3221 static void
3222 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3223 	ip_stack_t *ipst)
3224 {
3225 	icmph_t	icmph;
3226 	boolean_t mctl_present;
3227 	mblk_t *first_mp;
3228 
3229 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3230 
3231 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3232 		if (mctl_present)
3233 			freeb(first_mp);
3234 		return;
3235 	}
3236 
3237 	bzero(&icmph, sizeof (icmph_t));
3238 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3239 	icmph.icmph_pp_ptr = ptr;
3240 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3241 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3242 	    ipst);
3243 }
3244 
3245 /*
3246  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3247  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3248  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3249  * an icmp error packet can be sent.
3250  * Assigns an appropriate source address to the packet. If ipha_dst is
3251  * one of our addresses use it for source. Otherwise pick a source based
3252  * on a route lookup back to ipha_src.
3253  * Note that ipha_src must be set here since the
3254  * packet is likely to arrive on an ill queue in ip_wput() which will
3255  * not set a source address.
3256  */
3257 static void
3258 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3259     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3260 {
3261 	ipaddr_t dst;
3262 	icmph_t	*icmph;
3263 	ipha_t	*ipha;
3264 	uint_t	len_needed;
3265 	size_t	msg_len;
3266 	mblk_t	*mp1;
3267 	ipaddr_t src;
3268 	ire_t	*ire;
3269 	mblk_t *ipsec_mp;
3270 	ipsec_out_t	*io = NULL;
3271 	boolean_t xmit_if_on = B_FALSE;
3272 
3273 	if (mctl_present) {
3274 		/*
3275 		 * If it is :
3276 		 *
3277 		 * 1) a IPSEC_OUT, then this is caused by outbound
3278 		 *    datagram originating on this host. IPSEC processing
3279 		 *    may or may not have been done. Refer to comments above
3280 		 *    icmp_inbound_error_fanout for details.
3281 		 *
3282 		 * 2) a IPSEC_IN if we are generating a icmp_message
3283 		 *    for an incoming datagram destined for us i.e called
3284 		 *    from ip_fanout_send_icmp.
3285 		 */
3286 		ipsec_info_t *in;
3287 		ipsec_mp = mp;
3288 		mp = ipsec_mp->b_cont;
3289 
3290 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3291 		ipha = (ipha_t *)mp->b_rptr;
3292 
3293 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3294 		    in->ipsec_info_type == IPSEC_IN);
3295 
3296 		if (in->ipsec_info_type == IPSEC_IN) {
3297 			/*
3298 			 * Convert the IPSEC_IN to IPSEC_OUT.
3299 			 */
3300 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3301 				BUMP_MIB(&ipst->ips_ip_mib,
3302 				    ipIfStatsOutDiscards);
3303 				return;
3304 			}
3305 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3306 		} else {
3307 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3308 			io = (ipsec_out_t *)in;
3309 			if (io->ipsec_out_xmit_if)
3310 				xmit_if_on = B_TRUE;
3311 			/*
3312 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3313 			 * ire lookup.
3314 			 */
3315 			io->ipsec_out_proc_begin = B_FALSE;
3316 		}
3317 		ASSERT(zoneid == io->ipsec_out_zoneid);
3318 		ASSERT(zoneid != ALL_ZONES);
3319 	} else {
3320 		/*
3321 		 * This is in clear. The icmp message we are building
3322 		 * here should go out in clear.
3323 		 *
3324 		 * Pardon the convolution of it all, but it's easier to
3325 		 * allocate a "use cleartext" IPSEC_IN message and convert
3326 		 * it than it is to allocate a new one.
3327 		 */
3328 		ipsec_in_t *ii;
3329 		ASSERT(DB_TYPE(mp) == M_DATA);
3330 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3331 		if (ipsec_mp == NULL) {
3332 			freemsg(mp);
3333 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3334 			return;
3335 		}
3336 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3337 
3338 		/* This is not a secure packet */
3339 		ii->ipsec_in_secure = B_FALSE;
3340 		/*
3341 		 * For trusted extensions using a shared IP address we can
3342 		 * send using any zoneid.
3343 		 */
3344 		if (zoneid == ALL_ZONES)
3345 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3346 		else
3347 			ii->ipsec_in_zoneid = zoneid;
3348 		ipsec_mp->b_cont = mp;
3349 		ipha = (ipha_t *)mp->b_rptr;
3350 		/*
3351 		 * Convert the IPSEC_IN to IPSEC_OUT.
3352 		 */
3353 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3354 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3355 			return;
3356 		}
3357 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3358 	}
3359 
3360 	/* Remember our eventual destination */
3361 	dst = ipha->ipha_src;
3362 
3363 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3364 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3365 	if (ire != NULL &&
3366 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3367 		src = ipha->ipha_dst;
3368 	} else if (!xmit_if_on) {
3369 		if (ire != NULL)
3370 			ire_refrele(ire);
3371 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3372 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3373 		    ipst);
3374 		if (ire == NULL) {
3375 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3376 			freemsg(ipsec_mp);
3377 			return;
3378 		}
3379 		src = ire->ire_src_addr;
3380 	} else {
3381 		ipif_t	*ipif = NULL;
3382 		ill_t	*ill;
3383 		/*
3384 		 * This must be an ICMP error coming from
3385 		 * ip_mrtun_forward(). The src addr should
3386 		 * be equal to the IP-addr of the outgoing
3387 		 * interface.
3388 		 */
3389 		if (io == NULL) {
3390 			/* This is not a IPSEC_OUT type control msg */
3391 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3392 			freemsg(ipsec_mp);
3393 			return;
3394 		}
3395 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3396 		    NULL, NULL, NULL, NULL, ipst);
3397 		if (ill != NULL) {
3398 			ipif = ipif_get_next_ipif(NULL, ill);
3399 			ill_refrele(ill);
3400 		}
3401 		if (ipif == NULL) {
3402 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3403 			freemsg(ipsec_mp);
3404 			return;
3405 		}
3406 		src = ipif->ipif_src_addr;
3407 		ipif_refrele(ipif);
3408 	}
3409 
3410 	if (ire != NULL)
3411 		ire_refrele(ire);
3412 
3413 	/*
3414 	 * Check if we can send back more then 8 bytes in addition
3415 	 * to the IP header. We will include as much as 64 bytes.
3416 	 */
3417 	len_needed = IPH_HDR_LENGTH(ipha);
3418 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3419 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3420 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3421 	}
3422 	len_needed += ipst->ips_ip_icmp_return;
3423 	msg_len = msgdsize(mp);
3424 	if (msg_len > len_needed) {
3425 		(void) adjmsg(mp, len_needed - msg_len);
3426 		msg_len = len_needed;
3427 	}
3428 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3429 	if (mp1 == NULL) {
3430 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3431 		freemsg(ipsec_mp);
3432 		return;
3433 	}
3434 	/*
3435 	 * On an unlabeled system, dblks don't necessarily have creds.
3436 	 */
3437 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3438 	if (DB_CRED(mp) != NULL)
3439 		mblk_setcred(mp1, DB_CRED(mp));
3440 	mp1->b_cont = mp;
3441 	mp = mp1;
3442 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3443 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3444 	    io->ipsec_out_type == IPSEC_OUT);
3445 	ipsec_mp->b_cont = mp;
3446 
3447 	/*
3448 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3449 	 * node generates be accepted in peace by all on-host destinations.
3450 	 * If we do NOT assume that all on-host destinations trust
3451 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3452 	 * (Look for ipsec_out_icmp_loopback).
3453 	 */
3454 	io->ipsec_out_icmp_loopback = B_TRUE;
3455 
3456 	ipha = (ipha_t *)mp->b_rptr;
3457 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3458 	*ipha = icmp_ipha;
3459 	ipha->ipha_src = src;
3460 	ipha->ipha_dst = dst;
3461 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3462 	msg_len += sizeof (icmp_ipha) + len;
3463 	if (msg_len > IP_MAXPACKET) {
3464 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3465 		msg_len = IP_MAXPACKET;
3466 	}
3467 	ipha->ipha_length = htons((uint16_t)msg_len);
3468 	icmph = (icmph_t *)&ipha[1];
3469 	bcopy(stuff, icmph, len);
3470 	icmph->icmph_checksum = 0;
3471 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3472 	if (icmph->icmph_checksum == 0)
3473 		icmph->icmph_checksum = 0xFFFF;
3474 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3475 	put(q, ipsec_mp);
3476 }
3477 
3478 /*
3479  * Determine if an ICMP error packet can be sent given the rate limit.
3480  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3481  * in milliseconds) and a burst size. Burst size number of packets can
3482  * be sent arbitrarely closely spaced.
3483  * The state is tracked using two variables to implement an approximate
3484  * token bucket filter:
3485  *	icmp_pkt_err_last - lbolt value when the last burst started
3486  *	icmp_pkt_err_sent - number of packets sent in current burst
3487  */
3488 boolean_t
3489 icmp_err_rate_limit(ip_stack_t *ipst)
3490 {
3491 	clock_t now = TICK_TO_MSEC(lbolt);
3492 	uint_t refilled; /* Number of packets refilled in tbf since last */
3493 	/* Guard against changes by loading into local variable */
3494 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3495 
3496 	if (err_interval == 0)
3497 		return (B_FALSE);
3498 
3499 	if (ipst->ips_icmp_pkt_err_last > now) {
3500 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3501 		ipst->ips_icmp_pkt_err_last = 0;
3502 		ipst->ips_icmp_pkt_err_sent = 0;
3503 	}
3504 	/*
3505 	 * If we are in a burst update the token bucket filter.
3506 	 * Update the "last" time to be close to "now" but make sure
3507 	 * we don't loose precision.
3508 	 */
3509 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3510 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3511 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3512 			ipst->ips_icmp_pkt_err_sent = 0;
3513 		} else {
3514 			ipst->ips_icmp_pkt_err_sent -= refilled;
3515 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3516 		}
3517 	}
3518 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3519 		/* Start of new burst */
3520 		ipst->ips_icmp_pkt_err_last = now;
3521 	}
3522 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3523 		ipst->ips_icmp_pkt_err_sent++;
3524 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3525 			    ipst->ips_icmp_pkt_err_sent));
3526 		return (B_FALSE);
3527 	}
3528 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3529 	return (B_TRUE);
3530 }
3531 
3532 /*
3533  * Check if it is ok to send an IPv4 ICMP error packet in
3534  * response to the IPv4 packet in mp.
3535  * Free the message and return null if no
3536  * ICMP error packet should be sent.
3537  */
3538 static mblk_t *
3539 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3540 {
3541 	icmph_t	*icmph;
3542 	ipha_t	*ipha;
3543 	uint_t	len_needed;
3544 	ire_t	*src_ire;
3545 	ire_t	*dst_ire;
3546 
3547 	if (!mp)
3548 		return (NULL);
3549 	ipha = (ipha_t *)mp->b_rptr;
3550 	if (ip_csum_hdr(ipha)) {
3551 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3552 		freemsg(mp);
3553 		return (NULL);
3554 	}
3555 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3556 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3557 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3558 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3559 	if (src_ire != NULL || dst_ire != NULL ||
3560 	    CLASSD(ipha->ipha_dst) ||
3561 	    CLASSD(ipha->ipha_src) ||
3562 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3563 		/* Note: only errors to the fragment with offset 0 */
3564 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3565 		freemsg(mp);
3566 		if (src_ire != NULL)
3567 			ire_refrele(src_ire);
3568 		if (dst_ire != NULL)
3569 			ire_refrele(dst_ire);
3570 		return (NULL);
3571 	}
3572 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3573 		/*
3574 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3575 		 * errors in response to any ICMP errors.
3576 		 */
3577 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3578 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3579 			if (!pullupmsg(mp, len_needed)) {
3580 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3581 				freemsg(mp);
3582 				return (NULL);
3583 			}
3584 			ipha = (ipha_t *)mp->b_rptr;
3585 		}
3586 		icmph = (icmph_t *)
3587 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3588 		switch (icmph->icmph_type) {
3589 		case ICMP_DEST_UNREACHABLE:
3590 		case ICMP_SOURCE_QUENCH:
3591 		case ICMP_TIME_EXCEEDED:
3592 		case ICMP_PARAM_PROBLEM:
3593 		case ICMP_REDIRECT:
3594 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3595 			freemsg(mp);
3596 			return (NULL);
3597 		default:
3598 			break;
3599 		}
3600 	}
3601 	/*
3602 	 * If this is a labeled system, then check to see if we're allowed to
3603 	 * send a response to this particular sender.  If not, then just drop.
3604 	 */
3605 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3606 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3607 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3608 		freemsg(mp);
3609 		return (NULL);
3610 	}
3611 	if (icmp_err_rate_limit(ipst)) {
3612 		/*
3613 		 * Only send ICMP error packets every so often.
3614 		 * This should be done on a per port/source basis,
3615 		 * but for now this will suffice.
3616 		 */
3617 		freemsg(mp);
3618 		return (NULL);
3619 	}
3620 	return (mp);
3621 }
3622 
3623 /*
3624  * Generate an ICMP redirect message.
3625  */
3626 static void
3627 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3628 {
3629 	icmph_t	icmph;
3630 
3631 	/*
3632 	 * We are called from ip_rput where we could
3633 	 * not have attached an IPSEC_IN.
3634 	 */
3635 	ASSERT(mp->b_datap->db_type == M_DATA);
3636 
3637 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3638 		return;
3639 	}
3640 
3641 	bzero(&icmph, sizeof (icmph_t));
3642 	icmph.icmph_type = ICMP_REDIRECT;
3643 	icmph.icmph_code = 1;
3644 	icmph.icmph_rd_gateway = gateway;
3645 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3646 	/* Redirects sent by router, and router is global zone */
3647 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3648 }
3649 
3650 /*
3651  * Generate an ICMP time exceeded message.
3652  */
3653 void
3654 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3655     ip_stack_t *ipst)
3656 {
3657 	icmph_t	icmph;
3658 	boolean_t mctl_present;
3659 	mblk_t *first_mp;
3660 
3661 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3662 
3663 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3664 		if (mctl_present)
3665 			freeb(first_mp);
3666 		return;
3667 	}
3668 
3669 	bzero(&icmph, sizeof (icmph_t));
3670 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3671 	icmph.icmph_code = code;
3672 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3673 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3674 	    ipst);
3675 }
3676 
3677 /*
3678  * Generate an ICMP unreachable message.
3679  */
3680 void
3681 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3682     ip_stack_t *ipst)
3683 {
3684 	icmph_t	icmph;
3685 	mblk_t *first_mp;
3686 	boolean_t mctl_present;
3687 
3688 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3689 
3690 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3691 		if (mctl_present)
3692 			freeb(first_mp);
3693 		return;
3694 	}
3695 
3696 	bzero(&icmph, sizeof (icmph_t));
3697 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3698 	icmph.icmph_code = code;
3699 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3700 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3701 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3702 	    zoneid, ipst);
3703 }
3704 
3705 /*
3706  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3707  * duplicate.  As long as someone else holds the address, the interface will
3708  * stay down.  When that conflict goes away, the interface is brought back up.
3709  * This is done so that accidental shutdowns of addresses aren't made
3710  * permanent.  Your server will recover from a failure.
3711  *
3712  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3713  * user space process (dhcpagent).
3714  *
3715  * Recovery completes if ARP reports that the address is now ours (via
3716  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3717  *
3718  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3719  */
3720 static void
3721 ipif_dup_recovery(void *arg)
3722 {
3723 	ipif_t *ipif = arg;
3724 	ill_t *ill = ipif->ipif_ill;
3725 	mblk_t *arp_add_mp;
3726 	mblk_t *arp_del_mp;
3727 	area_t *area;
3728 	ip_stack_t *ipst = ill->ill_ipst;
3729 
3730 	ipif->ipif_recovery_id = 0;
3731 
3732 	/*
3733 	 * No lock needed for moving or condemned check, as this is just an
3734 	 * optimization.
3735 	 */
3736 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3737 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3738 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3739 		/* No reason to try to bring this address back. */
3740 		return;
3741 	}
3742 
3743 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3744 		goto alloc_fail;
3745 
3746 	if (ipif->ipif_arp_del_mp == NULL) {
3747 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3748 			goto alloc_fail;
3749 		ipif->ipif_arp_del_mp = arp_del_mp;
3750 	}
3751 
3752 	/* Setting the 'unverified' flag restarts DAD */
3753 	area = (area_t *)arp_add_mp->b_rptr;
3754 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3755 	    ACE_F_UNVERIFIED;
3756 	putnext(ill->ill_rq, arp_add_mp);
3757 	return;
3758 
3759 alloc_fail:
3760 	/*
3761 	 * On allocation failure, just restart the timer.  Note that the ipif
3762 	 * is down here, so no other thread could be trying to start a recovery
3763 	 * timer.  The ill_lock protects the condemned flag and the recovery
3764 	 * timer ID.
3765 	 */
3766 	freemsg(arp_add_mp);
3767 	mutex_enter(&ill->ill_lock);
3768 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3769 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3770 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3771 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3772 	}
3773 	mutex_exit(&ill->ill_lock);
3774 }
3775 
3776 /*
3777  * This is for exclusive changes due to ARP.  Either tear down an interface due
3778  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3779  */
3780 /* ARGSUSED */
3781 static void
3782 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3783 {
3784 	ill_t	*ill = rq->q_ptr;
3785 	arh_t *arh;
3786 	ipaddr_t src;
3787 	ipif_t	*ipif;
3788 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3789 	char hbuf[MAC_STR_LEN];
3790 	char sbuf[INET_ADDRSTRLEN];
3791 	const char *failtype;
3792 	boolean_t bring_up;
3793 	ip_stack_t *ipst = ill->ill_ipst;
3794 
3795 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3796 	case AR_CN_READY:
3797 		failtype = NULL;
3798 		bring_up = B_TRUE;
3799 		break;
3800 	case AR_CN_FAILED:
3801 		failtype = "in use";
3802 		bring_up = B_FALSE;
3803 		break;
3804 	default:
3805 		failtype = "claimed";
3806 		bring_up = B_FALSE;
3807 		break;
3808 	}
3809 
3810 	arh = (arh_t *)mp->b_cont->b_rptr;
3811 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3812 
3813 	/* Handle failures due to probes */
3814 	if (src == 0) {
3815 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3816 		    IP_ADDR_LEN);
3817 	}
3818 
3819 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3820 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3821 	    sizeof (hbuf));
3822 	(void) ip_dot_addr(src, sbuf);
3823 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3824 
3825 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3826 		    ipif->ipif_lcl_addr != src) {
3827 			continue;
3828 		}
3829 
3830 		/*
3831 		 * If we failed on a recovery probe, then restart the timer to
3832 		 * try again later.
3833 		 */
3834 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3835 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3836 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3837 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3838 		    ipst->ips_ip_dup_recovery > 0 &&
3839 		    ipif->ipif_recovery_id == 0) {
3840 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3841 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3842 			continue;
3843 		}
3844 
3845 		/*
3846 		 * If what we're trying to do has already been done, then do
3847 		 * nothing.
3848 		 */
3849 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3850 			continue;
3851 
3852 		if (ipif->ipif_id != 0) {
3853 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3854 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3855 			    ipif->ipif_id);
3856 		}
3857 		if (failtype == NULL) {
3858 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3859 			    ibuf);
3860 		} else {
3861 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3862 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3863 		}
3864 
3865 		if (bring_up) {
3866 			ASSERT(ill->ill_dl_up);
3867 			/*
3868 			 * Free up the ARP delete message so we can allocate
3869 			 * a fresh one through the normal path.
3870 			 */
3871 			freemsg(ipif->ipif_arp_del_mp);
3872 			ipif->ipif_arp_del_mp = NULL;
3873 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3874 			    EINPROGRESS) {
3875 				ipif->ipif_addr_ready = 1;
3876 				(void) ipif_up_done(ipif);
3877 			}
3878 			continue;
3879 		}
3880 
3881 		mutex_enter(&ill->ill_lock);
3882 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3883 		ipif->ipif_flags |= IPIF_DUPLICATE;
3884 		ill->ill_ipif_dup_count++;
3885 		mutex_exit(&ill->ill_lock);
3886 		/*
3887 		 * Already exclusive on the ill; no need to handle deferred
3888 		 * processing here.
3889 		 */
3890 		(void) ipif_down(ipif, NULL, NULL);
3891 		ipif_down_tail(ipif);
3892 		mutex_enter(&ill->ill_lock);
3893 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3894 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3895 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3896 		    ipst->ips_ip_dup_recovery > 0) {
3897 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3898 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3899 		}
3900 		mutex_exit(&ill->ill_lock);
3901 	}
3902 	freemsg(mp);
3903 }
3904 
3905 /* ARGSUSED */
3906 static void
3907 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3908 {
3909 	ill_t	*ill = rq->q_ptr;
3910 	arh_t *arh;
3911 	ipaddr_t src;
3912 	ipif_t	*ipif;
3913 
3914 	arh = (arh_t *)mp->b_cont->b_rptr;
3915 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3916 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3917 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3918 			(void) ipif_resolver_up(ipif, Res_act_defend);
3919 	}
3920 	freemsg(mp);
3921 }
3922 
3923 /*
3924  * News from ARP.  ARP sends notification of interesting events down
3925  * to its clients using M_CTL messages with the interesting ARP packet
3926  * attached via b_cont.
3927  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3928  * queue as opposed to ARP sending the message to all the clients, i.e. all
3929  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3930  * table if a cache IRE is found to delete all the entries for the address in
3931  * the packet.
3932  */
3933 static void
3934 ip_arp_news(queue_t *q, mblk_t *mp)
3935 {
3936 	arcn_t		*arcn;
3937 	arh_t		*arh;
3938 	ire_t		*ire = NULL;
3939 	char		hbuf[MAC_STR_LEN];
3940 	char		sbuf[INET_ADDRSTRLEN];
3941 	ipaddr_t	src;
3942 	in6_addr_t	v6src;
3943 	boolean_t	isv6 = B_FALSE;
3944 	ipif_t		*ipif;
3945 	ill_t		*ill;
3946 	ip_stack_t	*ipst;
3947 
3948 	if (CONN_Q(q)) {
3949 		conn_t *connp = Q_TO_CONN(q);
3950 
3951 		ipst = connp->conn_netstack->netstack_ip;
3952 	} else {
3953 		ill_t *ill = (ill_t *)q->q_ptr;
3954 
3955 		ipst = ill->ill_ipst;
3956 	}
3957 
3958 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3959 		if (q->q_next) {
3960 			putnext(q, mp);
3961 		} else
3962 			freemsg(mp);
3963 		return;
3964 	}
3965 	arh = (arh_t *)mp->b_cont->b_rptr;
3966 	/* Is it one we are interested in? */
3967 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3968 		isv6 = B_TRUE;
3969 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3970 		    IPV6_ADDR_LEN);
3971 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3972 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3973 		    IP_ADDR_LEN);
3974 	} else {
3975 		freemsg(mp);
3976 		return;
3977 	}
3978 
3979 	ill = q->q_ptr;
3980 
3981 	arcn = (arcn_t *)mp->b_rptr;
3982 	switch (arcn->arcn_code) {
3983 	case AR_CN_BOGON:
3984 		/*
3985 		 * Someone is sending ARP packets with a source protocol
3986 		 * address that we have published and for which we believe our
3987 		 * entry is authoritative and (when ill_arp_extend is set)
3988 		 * verified to be unique on the network.
3989 		 *
3990 		 * The ARP module internally handles the cases where the sender
3991 		 * is just probing (for DAD) and where the hardware address of
3992 		 * a non-authoritative entry has changed.  Thus, these are the
3993 		 * real conflicts, and we have to do resolution.
3994 		 *
3995 		 * We back away quickly from the address if it's from DHCP or
3996 		 * otherwise temporary and hasn't been used recently (or at
3997 		 * all).  We'd like to include "deprecated" addresses here as
3998 		 * well (as there's no real reason to defend something we're
3999 		 * discarding), but IPMP "reuses" this flag to mean something
4000 		 * other than the standard meaning.
4001 		 *
4002 		 * If the ARP module above is not extended (meaning that it
4003 		 * doesn't know how to defend the address), then we just log
4004 		 * the problem as we always did and continue on.  It's not
4005 		 * right, but there's little else we can do, and those old ATM
4006 		 * users are going away anyway.
4007 		 */
4008 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4009 		    hbuf, sizeof (hbuf));
4010 		(void) ip_dot_addr(src, sbuf);
4011 		if (isv6) {
4012 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4013 			    ipst);
4014 		} else {
4015 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4016 		}
4017 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4018 			uint32_t now;
4019 			uint32_t maxage;
4020 			clock_t lused;
4021 			uint_t maxdefense;
4022 			uint_t defs;
4023 
4024 			/*
4025 			 * First, figure out if this address hasn't been used
4026 			 * in a while.  If it hasn't, then it's a better
4027 			 * candidate for abandoning.
4028 			 */
4029 			ipif = ire->ire_ipif;
4030 			ASSERT(ipif != NULL);
4031 			now = gethrestime_sec();
4032 			maxage = now - ire->ire_create_time;
4033 			if (maxage > ipst->ips_ip_max_temp_idle)
4034 				maxage = ipst->ips_ip_max_temp_idle;
4035 			lused = drv_hztousec(ddi_get_lbolt() -
4036 			    ire->ire_last_used_time) / MICROSEC + 1;
4037 			if (lused >= maxage && (ipif->ipif_flags &
4038 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4039 				maxdefense = ipst->ips_ip_max_temp_defend;
4040 			else
4041 				maxdefense = ipst->ips_ip_max_defend;
4042 
4043 			/*
4044 			 * Now figure out how many times we've defended
4045 			 * ourselves.  Ignore defenses that happened long in
4046 			 * the past.
4047 			 */
4048 			mutex_enter(&ire->ire_lock);
4049 			if ((defs = ire->ire_defense_count) > 0 &&
4050 			    now - ire->ire_defense_time >
4051 			    ipst->ips_ip_defend_interval) {
4052 				ire->ire_defense_count = defs = 0;
4053 			}
4054 			ire->ire_defense_count++;
4055 			ire->ire_defense_time = now;
4056 			mutex_exit(&ire->ire_lock);
4057 			ill_refhold(ill);
4058 			ire_refrele(ire);
4059 
4060 			/*
4061 			 * If we've defended ourselves too many times already,
4062 			 * then give up and tear down the interface(s) using
4063 			 * this address.  Otherwise, defend by sending out a
4064 			 * gratuitous ARP.
4065 			 */
4066 			if (defs >= maxdefense && ill->ill_arp_extend) {
4067 				(void) qwriter_ip(NULL, ill, q, mp,
4068 				    ip_arp_excl, CUR_OP, B_FALSE);
4069 			} else {
4070 				cmn_err(CE_WARN,
4071 				    "node %s is using our IP address %s on %s",
4072 				    hbuf, sbuf, ill->ill_name);
4073 				/*
4074 				 * If this is an old (ATM) ARP module, then
4075 				 * don't try to defend the address.  Remain
4076 				 * compatible with the old behavior.  Defend
4077 				 * only with new ARP.
4078 				 */
4079 				if (ill->ill_arp_extend) {
4080 					(void) qwriter_ip(NULL, ill, q, mp,
4081 					    ip_arp_defend, CUR_OP, B_FALSE);
4082 				} else {
4083 					ill_refrele(ill);
4084 				}
4085 			}
4086 			return;
4087 		}
4088 		cmn_err(CE_WARN,
4089 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4090 		    hbuf, sbuf, ill->ill_name);
4091 		if (ire != NULL)
4092 			ire_refrele(ire);
4093 		break;
4094 	case AR_CN_ANNOUNCE:
4095 		if (isv6) {
4096 			/*
4097 			 * For XRESOLV interfaces.
4098 			 * Delete the IRE cache entry and NCE for this
4099 			 * v6 address
4100 			 */
4101 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4102 			/*
4103 			 * If v6src is a non-zero, it's a router address
4104 			 * as below. Do the same sort of thing to clean
4105 			 * out off-net IRE_CACHE entries that go through
4106 			 * the router.
4107 			 */
4108 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4109 				ire_walk_v6(ire_delete_cache_gw_v6,
4110 				    (char *)&v6src, ALL_ZONES, ipst);
4111 			}
4112 		} else {
4113 			nce_hw_map_t hwm;
4114 
4115 			/*
4116 			 * ARP gives us a copy of any packet where it thinks
4117 			 * the address has changed, so that we can update our
4118 			 * caches.  We're responsible for caching known answers
4119 			 * in the current design.  We check whether the
4120 			 * hardware address really has changed in all of our
4121 			 * entries that have cached this mapping, and if so, we
4122 			 * blow them away.  This way we will immediately pick
4123 			 * up the rare case of a host changing hardware
4124 			 * address.
4125 			 */
4126 			if (src == 0)
4127 				break;
4128 			hwm.hwm_addr = src;
4129 			hwm.hwm_hwlen = arh->arh_hlen;
4130 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4131 			ndp_walk_common(ipst->ips_ndp4, NULL,
4132 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4133 		}
4134 		break;
4135 	case AR_CN_READY:
4136 		/* No external v6 resolver has a contract to use this */
4137 		if (isv6)
4138 			break;
4139 		/* If the link is down, we'll retry this later */
4140 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4141 			break;
4142 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4143 		    NULL, NULL, ipst);
4144 		if (ipif != NULL) {
4145 			/*
4146 			 * If this is a duplicate recovery, then we now need to
4147 			 * go exclusive to bring this thing back up.
4148 			 */
4149 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4150 			    IPIF_DUPLICATE) {
4151 				ipif_refrele(ipif);
4152 				ill_refhold(ill);
4153 				(void) qwriter_ip(NULL, ill, q, mp,
4154 				    ip_arp_excl, CUR_OP, B_FALSE);
4155 				return;
4156 			}
4157 			/*
4158 			 * If this is the first notice that this address is
4159 			 * ready, then let the user know now.
4160 			 */
4161 			if ((ipif->ipif_flags & IPIF_UP) &&
4162 			    !ipif->ipif_addr_ready) {
4163 				ipif_mask_reply(ipif);
4164 				ip_rts_ifmsg(ipif);
4165 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4166 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4167 			}
4168 			ipif->ipif_addr_ready = 1;
4169 			ipif_refrele(ipif);
4170 		}
4171 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4172 		if (ire != NULL) {
4173 			ire->ire_defense_count = 0;
4174 			ire_refrele(ire);
4175 		}
4176 		break;
4177 	case AR_CN_FAILED:
4178 		/* No external v6 resolver has a contract to use this */
4179 		if (isv6)
4180 			break;
4181 		ill_refhold(ill);
4182 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4183 		    B_FALSE);
4184 		return;
4185 	}
4186 	freemsg(mp);
4187 }
4188 
4189 /*
4190  * Create a mblk suitable for carrying the interface index and/or source link
4191  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4192  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4193  * application.
4194  */
4195 mblk_t *
4196 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4197     ip_stack_t *ipst)
4198 {
4199 	mblk_t		*mp;
4200 	ip_pktinfo_t	*pinfo;
4201 	ipha_t *ipha;
4202 	struct ether_header *pether;
4203 
4204 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4205 	if (mp == NULL) {
4206 		ip1dbg(("ip_add_info: allocation failure.\n"));
4207 		return (data_mp);
4208 	}
4209 
4210 	ipha	= (ipha_t *)data_mp->b_rptr;
4211 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4212 	bzero(pinfo, sizeof (ip_pktinfo_t));
4213 	pinfo->ip_pkt_flags = (uchar_t)flags;
4214 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4215 
4216 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4217 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4218 	if (flags & IPF_RECVADDR) {
4219 		ipif_t	*ipif;
4220 		ire_t	*ire;
4221 
4222 		/*
4223 		 * Only valid for V4
4224 		 */
4225 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4226 		    (IPV4_VERSION << 4));
4227 
4228 		ipif = ipif_get_next_ipif(NULL, ill);
4229 		if (ipif != NULL) {
4230 			/*
4231 			 * Since a decision has already been made to deliver the
4232 			 * packet, there is no need to test for SECATTR and
4233 			 * ZONEONLY.
4234 			 */
4235 			ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0, ipif,
4236 			    zoneid, NULL, MATCH_IRE_ILL_GROUP, ipst);
4237 			if (ire == NULL) {
4238 				/*
4239 				 * packet must have come on a different
4240 				 * interface.
4241 				 * Since a decision has already been made to
4242 				 * deliver the packet, there is no need to test
4243 				 * for SECATTR and ZONEONLY.
4244 				 */
4245 				ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0,
4246 				    ipif, zoneid, NULL, NULL, ipst);
4247 			}
4248 
4249 			if (ire == NULL) {
4250 				/*
4251 				 * This is either a multicast packet or
4252 				 * the address has been removed since
4253 				 * the packet was received.
4254 				 * Return INADDR_ANY so that normal source
4255 				 * selection occurs for the response.
4256 				 */
4257 
4258 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4259 			} else {
4260 				ASSERT(ire->ire_type != IRE_CACHE);
4261 				pinfo->ip_pkt_match_addr.s_addr =
4262 				    ire->ire_src_addr;
4263 				ire_refrele(ire);
4264 			}
4265 			ipif_refrele(ipif);
4266 		} else {
4267 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4268 		}
4269 	}
4270 
4271 	pether = (struct ether_header *)((char *)ipha
4272 	    - sizeof (struct ether_header));
4273 	/*
4274 	 * Make sure the interface is an ethernet type, since this option
4275 	 * is currently supported only on this type of interface. Also make
4276 	 * sure we are pointing correctly above db_base.
4277 	 */
4278 
4279 	if ((flags & IPF_RECVSLLA) &&
4280 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4281 	    (ill->ill_type == IFT_ETHER) &&
4282 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4283 
4284 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4285 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4286 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4287 	} else {
4288 		/*
4289 		 * Clear the bit. Indicate to upper layer that IP is not
4290 		 * sending this ancillary info.
4291 		 */
4292 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4293 	}
4294 
4295 	mp->b_datap->db_type = M_CTL;
4296 	mp->b_wptr += sizeof (ip_pktinfo_t);
4297 	mp->b_cont = data_mp;
4298 
4299 	return (mp);
4300 }
4301 
4302 /*
4303  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4304  * part of the bind request.
4305  */
4306 
4307 boolean_t
4308 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4309 {
4310 	ipsec_in_t *ii;
4311 
4312 	ASSERT(policy_mp != NULL);
4313 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4314 
4315 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4316 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4317 
4318 	connp->conn_policy = ii->ipsec_in_policy;
4319 	ii->ipsec_in_policy = NULL;
4320 
4321 	if (ii->ipsec_in_action != NULL) {
4322 		if (connp->conn_latch == NULL) {
4323 			connp->conn_latch = iplatch_create();
4324 			if (connp->conn_latch == NULL)
4325 				return (B_FALSE);
4326 		}
4327 		ipsec_latch_inbound(connp->conn_latch, ii);
4328 	}
4329 	return (B_TRUE);
4330 }
4331 
4332 /*
4333  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4334  * and to arrange for power-fanout assist.  The ULP is identified by
4335  * adding a single byte at the end of the original bind message.
4336  * A ULP other than UDP or TCP that wishes to be recognized passes
4337  * down a bind with a zero length address.
4338  *
4339  * The binding works as follows:
4340  * - A zero byte address means just bind to the protocol.
4341  * - A four byte address is treated as a request to validate
4342  *   that the address is a valid local address, appropriate for
4343  *   an application to bind to. This does not affect any fanout
4344  *   information in IP.
4345  * - A sizeof sin_t byte address is used to bind to only the local address
4346  *   and port.
4347  * - A sizeof ipa_conn_t byte address contains complete fanout information
4348  *   consisting of local and remote addresses and ports.  In
4349  *   this case, the addresses are both validated as appropriate
4350  *   for this operation, and, if so, the information is retained
4351  *   for use in the inbound fanout.
4352  *
4353  * The ULP (except in the zero-length bind) can append an
4354  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4355  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4356  * a copy of the source or destination IRE (source for local bind;
4357  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4358  * policy information contained should be copied on to the conn.
4359  *
4360  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4361  */
4362 mblk_t *
4363 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4364 {
4365 	ssize_t		len;
4366 	struct T_bind_req	*tbr;
4367 	sin_t		*sin;
4368 	ipa_conn_t	*ac;
4369 	uchar_t		*ucp;
4370 	mblk_t		*mp1;
4371 	boolean_t	ire_requested;
4372 	boolean_t	ipsec_policy_set = B_FALSE;
4373 	int		error = 0;
4374 	int		protocol;
4375 	ipa_conn_x_t	*acx;
4376 
4377 	ASSERT(!connp->conn_af_isv6);
4378 	connp->conn_pkt_isv6 = B_FALSE;
4379 
4380 	len = MBLKL(mp);
4381 	if (len < (sizeof (*tbr) + 1)) {
4382 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4383 		    "ip_bind: bogus msg, len %ld", len);
4384 		/* XXX: Need to return something better */
4385 		goto bad_addr;
4386 	}
4387 	/* Back up and extract the protocol identifier. */
4388 	mp->b_wptr--;
4389 	protocol = *mp->b_wptr & 0xFF;
4390 	tbr = (struct T_bind_req *)mp->b_rptr;
4391 	/* Reset the message type in preparation for shipping it back. */
4392 	DB_TYPE(mp) = M_PCPROTO;
4393 
4394 	connp->conn_ulp = (uint8_t)protocol;
4395 
4396 	/*
4397 	 * Check for a zero length address.  This is from a protocol that
4398 	 * wants to register to receive all packets of its type.
4399 	 */
4400 	if (tbr->ADDR_length == 0) {
4401 		/*
4402 		 * These protocols are now intercepted in ip_bind_v6().
4403 		 * Reject protocol-level binds here for now.
4404 		 *
4405 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4406 		 * so that the protocol type cannot be SCTP.
4407 		 */
4408 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4409 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4410 			goto bad_addr;
4411 		}
4412 
4413 		/*
4414 		 *
4415 		 * The udp module never sends down a zero-length address,
4416 		 * and allowing this on a labeled system will break MLP
4417 		 * functionality.
4418 		 */
4419 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4420 			goto bad_addr;
4421 
4422 		if (connp->conn_mac_exempt)
4423 			goto bad_addr;
4424 
4425 		/* No hash here really.  The table is big enough. */
4426 		connp->conn_srcv6 = ipv6_all_zeros;
4427 
4428 		ipcl_proto_insert(connp, protocol);
4429 
4430 		tbr->PRIM_type = T_BIND_ACK;
4431 		return (mp);
4432 	}
4433 
4434 	/* Extract the address pointer from the message. */
4435 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4436 	    tbr->ADDR_length);
4437 	if (ucp == NULL) {
4438 		ip1dbg(("ip_bind: no address\n"));
4439 		goto bad_addr;
4440 	}
4441 	if (!OK_32PTR(ucp)) {
4442 		ip1dbg(("ip_bind: unaligned address\n"));
4443 		goto bad_addr;
4444 	}
4445 	/*
4446 	 * Check for trailing mps.
4447 	 */
4448 
4449 	mp1 = mp->b_cont;
4450 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4451 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4452 
4453 	switch (tbr->ADDR_length) {
4454 	default:
4455 		ip1dbg(("ip_bind: bad address length %d\n",
4456 		    (int)tbr->ADDR_length));
4457 		goto bad_addr;
4458 
4459 	case IP_ADDR_LEN:
4460 		/* Verification of local address only */
4461 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4462 		    ire_requested, ipsec_policy_set, B_FALSE);
4463 		break;
4464 
4465 	case sizeof (sin_t):
4466 		sin = (sin_t *)ucp;
4467 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4468 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4469 		break;
4470 
4471 	case sizeof (ipa_conn_t):
4472 		ac = (ipa_conn_t *)ucp;
4473 		/* For raw socket, the local port is not set. */
4474 		if (ac->ac_lport == 0)
4475 			ac->ac_lport = connp->conn_lport;
4476 		/* Always verify destination reachability. */
4477 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4478 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4479 		    ipsec_policy_set, B_TRUE, B_TRUE);
4480 		break;
4481 
4482 	case sizeof (ipa_conn_x_t):
4483 		acx = (ipa_conn_x_t *)ucp;
4484 		/*
4485 		 * Whether or not to verify destination reachability depends
4486 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4487 		 */
4488 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4489 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4490 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4491 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4492 		break;
4493 	}
4494 	if (error == EINPROGRESS)
4495 		return (NULL);
4496 	else if (error != 0)
4497 		goto bad_addr;
4498 	/*
4499 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4500 	 * We can't do this in ip_bind_insert_ire because the policy
4501 	 * may not have been inherited at that point in time and hence
4502 	 * conn_out_enforce_policy may not be set.
4503 	 */
4504 	mp1 = mp->b_cont;
4505 	if (ire_requested && connp->conn_out_enforce_policy &&
4506 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4507 		ire_t *ire = (ire_t *)mp1->b_rptr;
4508 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4509 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4510 	}
4511 
4512 	/* Send it home. */
4513 	mp->b_datap->db_type = M_PCPROTO;
4514 	tbr->PRIM_type = T_BIND_ACK;
4515 	return (mp);
4516 
4517 bad_addr:
4518 	/*
4519 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4520 	 * a unix errno.
4521 	 */
4522 	if (error > 0)
4523 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4524 	else
4525 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4526 	return (mp);
4527 }
4528 
4529 /*
4530  * Here address is verified to be a valid local address.
4531  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4532  * address is also considered a valid local address.
4533  * In the case of a broadcast/multicast address, however, the
4534  * upper protocol is expected to reset the src address
4535  * to 0 if it sees a IRE_BROADCAST type returned so that
4536  * no packets are emitted with broadcast/multicast address as
4537  * source address (that violates hosts requirements RFC1122)
4538  * The addresses valid for bind are:
4539  *	(1) - INADDR_ANY (0)
4540  *	(2) - IP address of an UP interface
4541  *	(3) - IP address of a DOWN interface
4542  *	(4) - valid local IP broadcast addresses. In this case
4543  *	the conn will only receive packets destined to
4544  *	the specified broadcast address.
4545  *	(5) - a multicast address. In this case
4546  *	the conn will only receive packets destined to
4547  *	the specified multicast address. Note: the
4548  *	application still has to issue an
4549  *	IP_ADD_MEMBERSHIP socket option.
4550  *
4551  * On error, return -1 for TBADADDR otherwise pass the
4552  * errno with TSYSERR reply.
4553  *
4554  * In all the above cases, the bound address must be valid in the current zone.
4555  * When the address is loopback, multicast or broadcast, there might be many
4556  * matching IREs so bind has to look up based on the zone.
4557  *
4558  * Note: lport is in network byte order.
4559  */
4560 int
4561 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4562     boolean_t ire_requested, boolean_t ipsec_policy_set,
4563     boolean_t fanout_insert)
4564 {
4565 	int		error = 0;
4566 	ire_t		*src_ire;
4567 	mblk_t		*policy_mp;
4568 	ipif_t		*ipif;
4569 	zoneid_t	zoneid;
4570 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4571 
4572 	if (ipsec_policy_set) {
4573 		policy_mp = mp->b_cont;
4574 	}
4575 
4576 	/*
4577 	 * If it was previously connected, conn_fully_bound would have
4578 	 * been set.
4579 	 */
4580 	connp->conn_fully_bound = B_FALSE;
4581 
4582 	src_ire = NULL;
4583 	ipif = NULL;
4584 
4585 	zoneid = IPCL_ZONEID(connp);
4586 
4587 	if (src_addr) {
4588 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4589 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4590 		/*
4591 		 * If an address other than 0.0.0.0 is requested,
4592 		 * we verify that it is a valid address for bind
4593 		 * Note: Following code is in if-else-if form for
4594 		 * readability compared to a condition check.
4595 		 */
4596 		/* LINTED - statement has no consequent */
4597 		if (IRE_IS_LOCAL(src_ire)) {
4598 			/*
4599 			 * (2) Bind to address of local UP interface
4600 			 */
4601 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4602 			/*
4603 			 * (4) Bind to broadcast address
4604 			 * Note: permitted only from transports that
4605 			 * request IRE
4606 			 */
4607 			if (!ire_requested)
4608 				error = EADDRNOTAVAIL;
4609 		} else {
4610 			/*
4611 			 * (3) Bind to address of local DOWN interface
4612 			 * (ipif_lookup_addr() looks up all interfaces
4613 			 * but we do not get here for UP interfaces
4614 			 * - case (2) above)
4615 			 * We put the protocol byte back into the mblk
4616 			 * since we may come back via ip_wput_nondata()
4617 			 * later with this mblk if ipif_lookup_addr chooses
4618 			 * to defer processing.
4619 			 */
4620 			*mp->b_wptr++ = (char)connp->conn_ulp;
4621 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4622 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4623 			    &error, ipst)) != NULL) {
4624 				ipif_refrele(ipif);
4625 			} else if (error == EINPROGRESS) {
4626 				if (src_ire != NULL)
4627 					ire_refrele(src_ire);
4628 				return (EINPROGRESS);
4629 			} else if (CLASSD(src_addr)) {
4630 				error = 0;
4631 				if (src_ire != NULL)
4632 					ire_refrele(src_ire);
4633 				/*
4634 				 * (5) bind to multicast address.
4635 				 * Fake out the IRE returned to upper
4636 				 * layer to be a broadcast IRE.
4637 				 */
4638 				src_ire = ire_ctable_lookup(
4639 				    INADDR_BROADCAST, INADDR_ANY,
4640 				    IRE_BROADCAST, NULL, zoneid, NULL,
4641 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4642 				    ipst);
4643 				if (src_ire == NULL || !ire_requested)
4644 					error = EADDRNOTAVAIL;
4645 			} else {
4646 				/*
4647 				 * Not a valid address for bind
4648 				 */
4649 				error = EADDRNOTAVAIL;
4650 			}
4651 			/*
4652 			 * Just to keep it consistent with the processing in
4653 			 * ip_bind_v4()
4654 			 */
4655 			mp->b_wptr--;
4656 		}
4657 		if (error) {
4658 			/* Red Alert!  Attempting to be a bogon! */
4659 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4660 			    ntohl(src_addr)));
4661 			goto bad_addr;
4662 		}
4663 	}
4664 
4665 	/*
4666 	 * Allow setting new policies. For example, disconnects come
4667 	 * down as ipa_t bind. As we would have set conn_policy_cached
4668 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4669 	 * can change after the disconnect.
4670 	 */
4671 	connp->conn_policy_cached = B_FALSE;
4672 
4673 	/*
4674 	 * If not fanout_insert this was just an address verification
4675 	 */
4676 	if (fanout_insert) {
4677 		/*
4678 		 * The addresses have been verified. Time to insert in
4679 		 * the correct fanout list.
4680 		 */
4681 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4682 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4683 		connp->conn_lport = lport;
4684 		connp->conn_fport = 0;
4685 		/*
4686 		 * Do we need to add a check to reject Multicast packets
4687 		 *
4688 		 * We need to make sure that the conn_recv is set to a non-null
4689 		 * value before we insert the conn into the classifier table.
4690 		 * This is to avoid a race with an incoming packet which does an
4691 		 * ipcl_classify().
4692 		 */
4693 		if (*mp->b_wptr == IPPROTO_TCP)
4694 			connp->conn_recv = tcp_conn_request;
4695 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4696 	}
4697 
4698 	if (error == 0) {
4699 		if (ire_requested) {
4700 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4701 				error = -1;
4702 				/* Falls through to bad_addr */
4703 			}
4704 		} else if (ipsec_policy_set) {
4705 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4706 				error = -1;
4707 				/* Falls through to bad_addr */
4708 			}
4709 		}
4710 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4711 		connp->conn_recv = tcp_input;
4712 	}
4713 bad_addr:
4714 	if (error != 0) {
4715 		if (connp->conn_anon_port) {
4716 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4717 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4718 			    B_FALSE);
4719 		}
4720 		connp->conn_mlp_type = mlptSingle;
4721 	}
4722 	if (src_ire != NULL)
4723 		IRE_REFRELE(src_ire);
4724 	if (ipsec_policy_set) {
4725 		ASSERT(policy_mp == mp->b_cont);
4726 		ASSERT(policy_mp != NULL);
4727 		freeb(policy_mp);
4728 		/*
4729 		 * As of now assume that nothing else accompanies
4730 		 * IPSEC_POLICY_SET.
4731 		 */
4732 		mp->b_cont = NULL;
4733 	}
4734 	return (error);
4735 }
4736 
4737 /*
4738  * Verify that both the source and destination addresses
4739  * are valid.  If verify_dst is false, then the destination address may be
4740  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4741  * destination reachability, while tunnels do not.
4742  * Note that we allow connect to broadcast and multicast
4743  * addresses when ire_requested is set. Thus the ULP
4744  * has to check for IRE_BROADCAST and multicast.
4745  *
4746  * Returns zero if ok.
4747  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4748  * (for use with TSYSERR reply).
4749  *
4750  * Note: lport and fport are in network byte order.
4751  */
4752 int
4753 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4754     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4755     boolean_t ire_requested, boolean_t ipsec_policy_set,
4756     boolean_t fanout_insert, boolean_t verify_dst)
4757 {
4758 	ire_t		*src_ire;
4759 	ire_t		*dst_ire;
4760 	int		error = 0;
4761 	int 		protocol;
4762 	mblk_t		*policy_mp;
4763 	ire_t		*sire = NULL;
4764 	ire_t		*md_dst_ire = NULL;
4765 	ire_t		*lso_dst_ire = NULL;
4766 	ill_t		*ill = NULL;
4767 	zoneid_t	zoneid;
4768 	ipaddr_t	src_addr = *src_addrp;
4769 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4770 
4771 	src_ire = dst_ire = NULL;
4772 	protocol = *mp->b_wptr & 0xFF;
4773 
4774 	/*
4775 	 * If we never got a disconnect before, clear it now.
4776 	 */
4777 	connp->conn_fully_bound = B_FALSE;
4778 
4779 	if (ipsec_policy_set) {
4780 		policy_mp = mp->b_cont;
4781 	}
4782 
4783 	zoneid = IPCL_ZONEID(connp);
4784 
4785 	if (CLASSD(dst_addr)) {
4786 		/* Pick up an IRE_BROADCAST */
4787 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4788 		    NULL, zoneid, MBLK_GETLABEL(mp),
4789 		    (MATCH_IRE_RECURSIVE |
4790 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4791 		    MATCH_IRE_SECATTR), ipst);
4792 	} else {
4793 		/*
4794 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4795 		 * and onlink ipif is not found set ENETUNREACH error.
4796 		 */
4797 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4798 			ipif_t *ipif;
4799 
4800 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4801 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4802 			if (ipif == NULL) {
4803 				error = ENETUNREACH;
4804 				goto bad_addr;
4805 			}
4806 			ipif_refrele(ipif);
4807 		}
4808 
4809 		if (connp->conn_nexthop_set) {
4810 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4811 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4812 			    MATCH_IRE_SECATTR, ipst);
4813 		} else {
4814 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4815 			    &sire, zoneid, MBLK_GETLABEL(mp),
4816 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4817 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4818 			    MATCH_IRE_SECATTR), ipst);
4819 		}
4820 	}
4821 	/*
4822 	 * dst_ire can't be a broadcast when not ire_requested.
4823 	 * We also prevent ire's with src address INADDR_ANY to
4824 	 * be used, which are created temporarily for
4825 	 * sending out packets from endpoints that have
4826 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4827 	 * reachable.  If verify_dst is false, the destination needn't be
4828 	 * reachable.
4829 	 *
4830 	 * If we match on a reject or black hole, then we've got a
4831 	 * local failure.  May as well fail out the connect() attempt,
4832 	 * since it's never going to succeed.
4833 	 */
4834 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4835 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4836 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4837 		/*
4838 		 * If we're verifying destination reachability, we always want
4839 		 * to complain here.
4840 		 *
4841 		 * If we're not verifying destination reachability but the
4842 		 * destination has a route, we still want to fail on the
4843 		 * temporary address and broadcast address tests.
4844 		 */
4845 		if (verify_dst || (dst_ire != NULL)) {
4846 			if (ip_debug > 2) {
4847 				pr_addr_dbg("ip_bind_connected: bad connected "
4848 				    "dst %s\n", AF_INET, &dst_addr);
4849 			}
4850 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4851 				error = ENETUNREACH;
4852 			else
4853 				error = EHOSTUNREACH;
4854 			goto bad_addr;
4855 		}
4856 	}
4857 
4858 	/*
4859 	 * We now know that routing will allow us to reach the destination.
4860 	 * Check whether Trusted Solaris policy allows communication with this
4861 	 * host, and pretend that the destination is unreachable if not.
4862 	 *
4863 	 * This is never a problem for TCP, since that transport is known to
4864 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4865 	 * handling.  If the remote is unreachable, it will be detected at that
4866 	 * point, so there's no reason to check it here.
4867 	 *
4868 	 * Note that for sendto (and other datagram-oriented friends), this
4869 	 * check is done as part of the data path label computation instead.
4870 	 * The check here is just to make non-TCP connect() report the right
4871 	 * error.
4872 	 */
4873 	if (dst_ire != NULL && is_system_labeled() &&
4874 	    !IPCL_IS_TCP(connp) &&
4875 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4876 	    connp->conn_mac_exempt, ipst) != 0) {
4877 		error = EHOSTUNREACH;
4878 		if (ip_debug > 2) {
4879 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4880 			    AF_INET, &dst_addr);
4881 		}
4882 		goto bad_addr;
4883 	}
4884 
4885 	/*
4886 	 * If the app does a connect(), it means that it will most likely
4887 	 * send more than 1 packet to the destination.  It makes sense
4888 	 * to clear the temporary flag.
4889 	 */
4890 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4891 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4892 		irb_t *irb = dst_ire->ire_bucket;
4893 
4894 		rw_enter(&irb->irb_lock, RW_WRITER);
4895 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4896 		irb->irb_tmp_ire_cnt--;
4897 		rw_exit(&irb->irb_lock);
4898 	}
4899 
4900 	/*
4901 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4902 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4903 	 * eligibility tests for passive connects are handled separately
4904 	 * through tcp_adapt_ire().  We do this before the source address
4905 	 * selection, because dst_ire may change after a call to
4906 	 * ipif_select_source().  This is a best-effort check, as the
4907 	 * packet for this connection may not actually go through
4908 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4909 	 * calling ip_newroute().  This is why we further check on the
4910 	 * IRE during LSO/Multidata packet transmission in
4911 	 * tcp_lsosend()/tcp_multisend().
4912 	 */
4913 	if (!ipsec_policy_set && dst_ire != NULL &&
4914 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4915 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4916 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4917 			lso_dst_ire = dst_ire;
4918 			IRE_REFHOLD(lso_dst_ire);
4919 		} else if (ipst->ips_ip_multidata_outbound &&
4920 		    ILL_MDT_CAPABLE(ill)) {
4921 			md_dst_ire = dst_ire;
4922 			IRE_REFHOLD(md_dst_ire);
4923 		}
4924 	}
4925 
4926 	if (dst_ire != NULL &&
4927 	    dst_ire->ire_type == IRE_LOCAL &&
4928 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4929 		/*
4930 		 * If the IRE belongs to a different zone, look for a matching
4931 		 * route in the forwarding table and use the source address from
4932 		 * that route.
4933 		 */
4934 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4935 		    zoneid, 0, NULL,
4936 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4937 		    MATCH_IRE_RJ_BHOLE, ipst);
4938 		if (src_ire == NULL) {
4939 			error = EHOSTUNREACH;
4940 			goto bad_addr;
4941 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4942 			if (!(src_ire->ire_type & IRE_HOST))
4943 				error = ENETUNREACH;
4944 			else
4945 				error = EHOSTUNREACH;
4946 			goto bad_addr;
4947 		}
4948 		if (src_addr == INADDR_ANY)
4949 			src_addr = src_ire->ire_src_addr;
4950 		ire_refrele(src_ire);
4951 		src_ire = NULL;
4952 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4953 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4954 			src_addr = sire->ire_src_addr;
4955 			ire_refrele(dst_ire);
4956 			dst_ire = sire;
4957 			sire = NULL;
4958 		} else {
4959 			/*
4960 			 * Pick a source address so that a proper inbound
4961 			 * load spreading would happen.
4962 			 */
4963 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4964 			ipif_t *src_ipif = NULL;
4965 			ire_t *ipif_ire;
4966 
4967 			/*
4968 			 * Supply a local source address such that inbound
4969 			 * load spreading happens.
4970 			 *
4971 			 * Determine the best source address on this ill for
4972 			 * the destination.
4973 			 *
4974 			 * 1) For broadcast, we should return a broadcast ire
4975 			 *    found above so that upper layers know that the
4976 			 *    destination address is a broadcast address.
4977 			 *
4978 			 * 2) If this is part of a group, select a better
4979 			 *    source address so that better inbound load
4980 			 *    balancing happens. Do the same if the ipif
4981 			 *    is DEPRECATED.
4982 			 *
4983 			 * 3) If the outgoing interface is part of a usesrc
4984 			 *    group, then try selecting a source address from
4985 			 *    the usesrc ILL.
4986 			 */
4987 			if ((dst_ire->ire_zoneid != zoneid &&
4988 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4989 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4990 			    ((dst_ill->ill_group != NULL) ||
4991 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4992 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4993 				/*
4994 				 * If the destination is reachable via a
4995 				 * given gateway, the selected source address
4996 				 * should be in the same subnet as the gateway.
4997 				 * Otherwise, the destination is not reachable.
4998 				 *
4999 				 * If there are no interfaces on the same subnet
5000 				 * as the destination, ipif_select_source gives
5001 				 * first non-deprecated interface which might be
5002 				 * on a different subnet than the gateway.
5003 				 * This is not desirable. Hence pass the dst_ire
5004 				 * source address to ipif_select_source.
5005 				 * It is sure that the destination is reachable
5006 				 * with the dst_ire source address subnet.
5007 				 * So passing dst_ire source address to
5008 				 * ipif_select_source will make sure that the
5009 				 * selected source will be on the same subnet
5010 				 * as dst_ire source address.
5011 				 */
5012 				ipaddr_t saddr =
5013 				    dst_ire->ire_ipif->ipif_src_addr;
5014 				src_ipif = ipif_select_source(dst_ill,
5015 				    saddr, zoneid);
5016 				if (src_ipif != NULL) {
5017 					if (IS_VNI(src_ipif->ipif_ill)) {
5018 						/*
5019 						 * For VNI there is no
5020 						 * interface route
5021 						 */
5022 						src_addr =
5023 						    src_ipif->ipif_src_addr;
5024 					} else {
5025 						ipif_ire =
5026 						    ipif_to_ire(src_ipif);
5027 						if (ipif_ire != NULL) {
5028 							IRE_REFRELE(dst_ire);
5029 							dst_ire = ipif_ire;
5030 						}
5031 						src_addr =
5032 						    dst_ire->ire_src_addr;
5033 					}
5034 					ipif_refrele(src_ipif);
5035 				} else {
5036 					src_addr = dst_ire->ire_src_addr;
5037 				}
5038 			} else {
5039 				src_addr = dst_ire->ire_src_addr;
5040 			}
5041 		}
5042 	}
5043 
5044 	/*
5045 	 * We do ire_route_lookup() here (and not
5046 	 * interface lookup as we assert that
5047 	 * src_addr should only come from an
5048 	 * UP interface for hard binding.
5049 	 */
5050 	ASSERT(src_ire == NULL);
5051 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5052 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5053 	/* src_ire must be a local|loopback */
5054 	if (!IRE_IS_LOCAL(src_ire)) {
5055 		if (ip_debug > 2) {
5056 			pr_addr_dbg("ip_bind_connected: bad connected "
5057 			    "src %s\n", AF_INET, &src_addr);
5058 		}
5059 		error = EADDRNOTAVAIL;
5060 		goto bad_addr;
5061 	}
5062 
5063 	/*
5064 	 * If the source address is a loopback address, the
5065 	 * destination had best be local or multicast.
5066 	 * The transports that can't handle multicast will reject
5067 	 * those addresses.
5068 	 */
5069 	if (src_ire->ire_type == IRE_LOOPBACK &&
5070 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5071 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5072 		error = -1;
5073 		goto bad_addr;
5074 	}
5075 
5076 	/*
5077 	 * Allow setting new policies. For example, disconnects come
5078 	 * down as ipa_t bind. As we would have set conn_policy_cached
5079 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5080 	 * can change after the disconnect.
5081 	 */
5082 	connp->conn_policy_cached = B_FALSE;
5083 
5084 	/*
5085 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5086 	 * can handle their passed-in conn's.
5087 	 */
5088 
5089 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5090 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5091 	connp->conn_lport = lport;
5092 	connp->conn_fport = fport;
5093 	*src_addrp = src_addr;
5094 
5095 	ASSERT(!(ipsec_policy_set && ire_requested));
5096 	if (ire_requested) {
5097 		iulp_t *ulp_info = NULL;
5098 
5099 		/*
5100 		 * Note that sire will not be NULL if this is an off-link
5101 		 * connection and there is not cache for that dest yet.
5102 		 *
5103 		 * XXX Because of an existing bug, if there are multiple
5104 		 * default routes, the IRE returned now may not be the actual
5105 		 * default route used (default routes are chosen in a
5106 		 * round robin fashion).  So if the metrics for different
5107 		 * default routes are different, we may return the wrong
5108 		 * metrics.  This will not be a problem if the existing
5109 		 * bug is fixed.
5110 		 */
5111 		if (sire != NULL) {
5112 			ulp_info = &(sire->ire_uinfo);
5113 		}
5114 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5115 			error = -1;
5116 			goto bad_addr;
5117 		}
5118 	} else if (ipsec_policy_set) {
5119 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5120 			error = -1;
5121 			goto bad_addr;
5122 		}
5123 	}
5124 
5125 	/*
5126 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5127 	 * we'll cache that.  If we don't, we'll inherit global policy.
5128 	 *
5129 	 * We can't insert until the conn reflects the policy. Note that
5130 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5131 	 * connections where we don't have a policy. This is to prevent
5132 	 * global policy lookups in the inbound path.
5133 	 *
5134 	 * If we insert before we set conn_policy_cached,
5135 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5136 	 * because global policy cound be non-empty. We normally call
5137 	 * ipsec_check_policy() for conn_policy_cached connections only if
5138 	 * ipc_in_enforce_policy is set. But in this case,
5139 	 * conn_policy_cached can get set anytime since we made the
5140 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5141 	 * called, which will make the above assumption false.  Thus, we
5142 	 * need to insert after we set conn_policy_cached.
5143 	 */
5144 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5145 		goto bad_addr;
5146 
5147 	if (fanout_insert) {
5148 		/*
5149 		 * The addresses have been verified. Time to insert in
5150 		 * the correct fanout list.
5151 		 * We need to make sure that the conn_recv is set to a non-null
5152 		 * value before we insert into the classifier table to avoid a
5153 		 * race with an incoming packet which does an ipcl_classify().
5154 		 */
5155 		if (protocol == IPPROTO_TCP)
5156 			connp->conn_recv = tcp_input;
5157 		error = ipcl_conn_insert(connp, protocol, src_addr,
5158 		    dst_addr, connp->conn_ports);
5159 	}
5160 
5161 	if (error == 0) {
5162 		connp->conn_fully_bound = B_TRUE;
5163 		/*
5164 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5165 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5166 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5167 		 * ip_xxinfo_return(), which performs further checks
5168 		 * against them and upon success, returns the LSO/MDT info
5169 		 * mblk which we will attach to the bind acknowledgment.
5170 		 */
5171 		if (lso_dst_ire != NULL) {
5172 			mblk_t *lsoinfo_mp;
5173 
5174 			ASSERT(ill->ill_lso_capab != NULL);
5175 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5176 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5177 				linkb(mp, lsoinfo_mp);
5178 		} else if (md_dst_ire != NULL) {
5179 			mblk_t *mdinfo_mp;
5180 
5181 			ASSERT(ill->ill_mdt_capab != NULL);
5182 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5183 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5184 				linkb(mp, mdinfo_mp);
5185 		}
5186 	}
5187 bad_addr:
5188 	if (ipsec_policy_set) {
5189 		ASSERT(policy_mp == mp->b_cont);
5190 		ASSERT(policy_mp != NULL);
5191 		freeb(policy_mp);
5192 		/*
5193 		 * As of now assume that nothing else accompanies
5194 		 * IPSEC_POLICY_SET.
5195 		 */
5196 		mp->b_cont = NULL;
5197 	}
5198 	if (src_ire != NULL)
5199 		IRE_REFRELE(src_ire);
5200 	if (dst_ire != NULL)
5201 		IRE_REFRELE(dst_ire);
5202 	if (sire != NULL)
5203 		IRE_REFRELE(sire);
5204 	if (md_dst_ire != NULL)
5205 		IRE_REFRELE(md_dst_ire);
5206 	if (lso_dst_ire != NULL)
5207 		IRE_REFRELE(lso_dst_ire);
5208 	return (error);
5209 }
5210 
5211 /*
5212  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5213  * Prefers dst_ire over src_ire.
5214  */
5215 static boolean_t
5216 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5217 {
5218 	mblk_t	*mp1;
5219 	ire_t *ret_ire = NULL;
5220 
5221 	mp1 = mp->b_cont;
5222 	ASSERT(mp1 != NULL);
5223 
5224 	if (ire != NULL) {
5225 		/*
5226 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5227 		 * appended mblk. Its <upper protocol>'s
5228 		 * job to make sure there is room.
5229 		 */
5230 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5231 			return (0);
5232 
5233 		mp1->b_datap->db_type = IRE_DB_TYPE;
5234 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5235 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5236 		ret_ire = (ire_t *)mp1->b_rptr;
5237 		/*
5238 		 * Pass the latest setting of the ip_path_mtu_discovery and
5239 		 * copy the ulp info if any.
5240 		 */
5241 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5242 		    IPH_DF : 0;
5243 		if (ulp_info != NULL) {
5244 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5245 			    sizeof (iulp_t));
5246 		}
5247 		ret_ire->ire_mp = mp1;
5248 	} else {
5249 		/*
5250 		 * No IRE was found. Remove IRE mblk.
5251 		 */
5252 		mp->b_cont = mp1->b_cont;
5253 		freeb(mp1);
5254 	}
5255 
5256 	return (1);
5257 }
5258 
5259 /*
5260  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5261  * the final piece where we don't.  Return a pointer to the first mblk in the
5262  * result, and update the pointer to the next mblk to chew on.  If anything
5263  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5264  * NULL pointer.
5265  */
5266 mblk_t *
5267 ip_carve_mp(mblk_t **mpp, ssize_t len)
5268 {
5269 	mblk_t	*mp0;
5270 	mblk_t	*mp1;
5271 	mblk_t	*mp2;
5272 
5273 	if (!len || !mpp || !(mp0 = *mpp))
5274 		return (NULL);
5275 	/* If we aren't going to consume the first mblk, we need a dup. */
5276 	if (mp0->b_wptr - mp0->b_rptr > len) {
5277 		mp1 = dupb(mp0);
5278 		if (mp1) {
5279 			/* Partition the data between the two mblks. */
5280 			mp1->b_wptr = mp1->b_rptr + len;
5281 			mp0->b_rptr = mp1->b_wptr;
5282 			/*
5283 			 * after adjustments if mblk not consumed is now
5284 			 * unaligned, try to align it. If this fails free
5285 			 * all messages and let upper layer recover.
5286 			 */
5287 			if (!OK_32PTR(mp0->b_rptr)) {
5288 				if (!pullupmsg(mp0, -1)) {
5289 					freemsg(mp0);
5290 					freemsg(mp1);
5291 					*mpp = NULL;
5292 					return (NULL);
5293 				}
5294 			}
5295 		}
5296 		return (mp1);
5297 	}
5298 	/* Eat through as many mblks as we need to get len bytes. */
5299 	len -= mp0->b_wptr - mp0->b_rptr;
5300 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5301 		if (mp2->b_wptr - mp2->b_rptr > len) {
5302 			/*
5303 			 * We won't consume the entire last mblk.  Like
5304 			 * above, dup and partition it.
5305 			 */
5306 			mp1->b_cont = dupb(mp2);
5307 			mp1 = mp1->b_cont;
5308 			if (!mp1) {
5309 				/*
5310 				 * Trouble.  Rather than go to a lot of
5311 				 * trouble to clean up, we free the messages.
5312 				 * This won't be any worse than losing it on
5313 				 * the wire.
5314 				 */
5315 				freemsg(mp0);
5316 				freemsg(mp2);
5317 				*mpp = NULL;
5318 				return (NULL);
5319 			}
5320 			mp1->b_wptr = mp1->b_rptr + len;
5321 			mp2->b_rptr = mp1->b_wptr;
5322 			/*
5323 			 * after adjustments if mblk not consumed is now
5324 			 * unaligned, try to align it. If this fails free
5325 			 * all messages and let upper layer recover.
5326 			 */
5327 			if (!OK_32PTR(mp2->b_rptr)) {
5328 				if (!pullupmsg(mp2, -1)) {
5329 					freemsg(mp0);
5330 					freemsg(mp2);
5331 					*mpp = NULL;
5332 					return (NULL);
5333 				}
5334 			}
5335 			*mpp = mp2;
5336 			return (mp0);
5337 		}
5338 		/* Decrement len by the amount we just got. */
5339 		len -= mp2->b_wptr - mp2->b_rptr;
5340 	}
5341 	/*
5342 	 * len should be reduced to zero now.  If not our caller has
5343 	 * screwed up.
5344 	 */
5345 	if (len) {
5346 		/* Shouldn't happen! */
5347 		freemsg(mp0);
5348 		*mpp = NULL;
5349 		return (NULL);
5350 	}
5351 	/*
5352 	 * We consumed up to exactly the end of an mblk.  Detach the part
5353 	 * we are returning from the rest of the chain.
5354 	 */
5355 	mp1->b_cont = NULL;
5356 	*mpp = mp2;
5357 	return (mp0);
5358 }
5359 
5360 /* The ill stream is being unplumbed. Called from ip_close */
5361 int
5362 ip_modclose(ill_t *ill)
5363 {
5364 
5365 	boolean_t success;
5366 	ipsq_t	*ipsq;
5367 	ipif_t	*ipif;
5368 	queue_t	*q = ill->ill_rq;
5369 	ip_stack_t	*ipst = ill->ill_ipst;
5370 	clock_t timeout;
5371 
5372 	/*
5373 	 * Wait for the ACKs of all deferred control messages to be processed.
5374 	 * In particular, we wait for a potential capability reset initiated
5375 	 * in ip_sioctl_plink() to complete before proceeding.
5376 	 *
5377 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5378 	 * in case the driver never replies.
5379 	 */
5380 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5381 	mutex_enter(&ill->ill_lock);
5382 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5383 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5384 			/* Timeout */
5385 			break;
5386 		}
5387 	}
5388 	mutex_exit(&ill->ill_lock);
5389 
5390 	/*
5391 	 * Forcibly enter the ipsq after some delay. This is to take
5392 	 * care of the case when some ioctl does not complete because
5393 	 * we sent a control message to the driver and it did not
5394 	 * send us a reply. We want to be able to at least unplumb
5395 	 * and replumb rather than force the user to reboot the system.
5396 	 */
5397 	success = ipsq_enter(ill, B_FALSE);
5398 
5399 	/*
5400 	 * Open/close/push/pop is guaranteed to be single threaded
5401 	 * per stream by STREAMS. FS guarantees that all references
5402 	 * from top are gone before close is called. So there can't
5403 	 * be another close thread that has set CONDEMNED on this ill.
5404 	 * and cause ipsq_enter to return failure.
5405 	 */
5406 	ASSERT(success);
5407 	ipsq = ill->ill_phyint->phyint_ipsq;
5408 
5409 	/*
5410 	 * Mark it condemned. No new reference will be made to this ill.
5411 	 * Lookup functions will return an error. Threads that try to
5412 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5413 	 * that the refcnt will drop down to zero.
5414 	 */
5415 	mutex_enter(&ill->ill_lock);
5416 	ill->ill_state_flags |= ILL_CONDEMNED;
5417 	for (ipif = ill->ill_ipif; ipif != NULL;
5418 	    ipif = ipif->ipif_next) {
5419 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5420 	}
5421 	/*
5422 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5423 	 * returns  error if ILL_CONDEMNED is set
5424 	 */
5425 	cv_broadcast(&ill->ill_cv);
5426 	mutex_exit(&ill->ill_lock);
5427 
5428 	/*
5429 	 * Send all the deferred control messages downstream which came in
5430 	 * during the small window right before ipsq_enter(). We do this
5431 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5432 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5433 	 */
5434 	ill_send_all_deferred_mp(ill);
5435 
5436 	/*
5437 	 * Shut down fragmentation reassembly.
5438 	 * ill_frag_timer won't start a timer again.
5439 	 * Now cancel any existing timer
5440 	 */
5441 	(void) untimeout(ill->ill_frag_timer_id);
5442 	(void) ill_frag_timeout(ill, 0);
5443 
5444 	/*
5445 	 * If MOVE was in progress, clear the
5446 	 * move_in_progress fields also.
5447 	 */
5448 	if (ill->ill_move_in_progress) {
5449 		ILL_CLEAR_MOVE(ill);
5450 	}
5451 
5452 	/*
5453 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5454 	 * this ill. Then wait for the refcnts to drop to zero.
5455 	 * ill_is_quiescent checks whether the ill is really quiescent.
5456 	 * Then make sure that threads that are waiting to enter the
5457 	 * ipsq have seen the error returned by ipsq_enter and have
5458 	 * gone away. Then we call ill_delete_tail which does the
5459 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5460 	 */
5461 	ill_delete(ill);
5462 	mutex_enter(&ill->ill_lock);
5463 	while (!ill_is_quiescent(ill))
5464 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5465 	while (ill->ill_waiters)
5466 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5467 
5468 	mutex_exit(&ill->ill_lock);
5469 
5470 	/*
5471 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5472 	 * it held until the end of the function since the cleanup
5473 	 * below needs to be able to use the ip_stack_t.
5474 	 */
5475 	netstack_hold(ipst->ips_netstack);
5476 
5477 	/* qprocsoff is called in ill_delete_tail */
5478 	ill_delete_tail(ill);
5479 	ASSERT(ill->ill_ipst == NULL);
5480 
5481 	/*
5482 	 * Walk through all upper (conn) streams and qenable
5483 	 * those that have queued data.
5484 	 * close synchronization needs this to
5485 	 * be done to ensure that all upper layers blocked
5486 	 * due to flow control to the closing device
5487 	 * get unblocked.
5488 	 */
5489 	ip1dbg(("ip_wsrv: walking\n"));
5490 	conn_walk_drain(ipst);
5491 
5492 	mutex_enter(&ipst->ips_ip_mi_lock);
5493 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5494 	mutex_exit(&ipst->ips_ip_mi_lock);
5495 
5496 	/*
5497 	 * credp could be null if the open didn't succeed and ip_modopen
5498 	 * itself calls ip_close.
5499 	 */
5500 	if (ill->ill_credp != NULL)
5501 		crfree(ill->ill_credp);
5502 
5503 	mutex_enter(&ill->ill_lock);
5504 	ill_nic_info_dispatch(ill);
5505 	mutex_exit(&ill->ill_lock);
5506 
5507 	/*
5508 	 * Now we are done with the module close pieces that
5509 	 * need the netstack_t.
5510 	 */
5511 	netstack_rele(ipst->ips_netstack);
5512 
5513 	mi_close_free((IDP)ill);
5514 	q->q_ptr = WR(q)->q_ptr = NULL;
5515 
5516 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5517 
5518 	return (0);
5519 }
5520 
5521 /*
5522  * This is called as part of close() for both IP and UDP
5523  * in order to quiesce the conn.
5524  */
5525 void
5526 ip_quiesce_conn(conn_t *connp)
5527 {
5528 	boolean_t	drain_cleanup_reqd = B_FALSE;
5529 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5530 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5531 	ip_stack_t	*ipst;
5532 
5533 	ASSERT(!IPCL_IS_TCP(connp));
5534 	ipst = connp->conn_netstack->netstack_ip;
5535 
5536 	/*
5537 	 * Mark the conn as closing, and this conn must not be
5538 	 * inserted in future into any list. Eg. conn_drain_insert(),
5539 	 * won't insert this conn into the conn_drain_list.
5540 	 * Similarly ill_pending_mp_add() will not add any mp to
5541 	 * the pending mp list, after this conn has started closing.
5542 	 *
5543 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5544 	 * cannot get set henceforth.
5545 	 */
5546 	mutex_enter(&connp->conn_lock);
5547 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5548 	connp->conn_state_flags |= CONN_CLOSING;
5549 	if (connp->conn_idl != NULL)
5550 		drain_cleanup_reqd = B_TRUE;
5551 	if (connp->conn_oper_pending_ill != NULL)
5552 		conn_ioctl_cleanup_reqd = B_TRUE;
5553 	if (connp->conn_ilg_inuse != 0)
5554 		ilg_cleanup_reqd = B_TRUE;
5555 	mutex_exit(&connp->conn_lock);
5556 
5557 	if (IPCL_IS_UDP(connp))
5558 		udp_quiesce_conn(connp);
5559 
5560 	if (conn_ioctl_cleanup_reqd)
5561 		conn_ioctl_cleanup(connp);
5562 
5563 	if (is_system_labeled() && connp->conn_anon_port) {
5564 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5565 		    connp->conn_mlp_type, connp->conn_ulp,
5566 		    ntohs(connp->conn_lport), B_FALSE);
5567 		connp->conn_anon_port = 0;
5568 	}
5569 	connp->conn_mlp_type = mlptSingle;
5570 
5571 	/*
5572 	 * Remove this conn from any fanout list it is on.
5573 	 * and then wait for any threads currently operating
5574 	 * on this endpoint to finish
5575 	 */
5576 	ipcl_hash_remove(connp);
5577 
5578 	/*
5579 	 * Remove this conn from the drain list, and do
5580 	 * any other cleanup that may be required.
5581 	 * (Only non-tcp streams may have a non-null conn_idl.
5582 	 * TCP streams are never flow controlled, and
5583 	 * conn_idl will be null)
5584 	 */
5585 	if (drain_cleanup_reqd)
5586 		conn_drain_tail(connp, B_TRUE);
5587 
5588 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5589 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5590 		(void) ip_mrouter_done(NULL, ipst);
5591 
5592 	if (ilg_cleanup_reqd)
5593 		ilg_delete_all(connp);
5594 
5595 	conn_delete_ire(connp, NULL);
5596 
5597 	/*
5598 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5599 	 * callers from write side can't be there now because close
5600 	 * is in progress. The only other caller is ipcl_walk
5601 	 * which checks for the condemned flag.
5602 	 */
5603 	mutex_enter(&connp->conn_lock);
5604 	connp->conn_state_flags |= CONN_CONDEMNED;
5605 	while (connp->conn_ref != 1)
5606 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5607 	connp->conn_state_flags |= CONN_QUIESCED;
5608 	mutex_exit(&connp->conn_lock);
5609 }
5610 
5611 /* ARGSUSED */
5612 int
5613 ip_close(queue_t *q, int flags)
5614 {
5615 	conn_t		*connp;
5616 
5617 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5618 
5619 	/*
5620 	 * Call the appropriate delete routine depending on whether this is
5621 	 * a module or device.
5622 	 */
5623 	if (WR(q)->q_next != NULL) {
5624 		/* This is a module close */
5625 		return (ip_modclose((ill_t *)q->q_ptr));
5626 	}
5627 
5628 	connp = q->q_ptr;
5629 	ip_quiesce_conn(connp);
5630 
5631 	qprocsoff(q);
5632 
5633 	/*
5634 	 * Now we are truly single threaded on this stream, and can
5635 	 * delete the things hanging off the connp, and finally the connp.
5636 	 * We removed this connp from the fanout list, it cannot be
5637 	 * accessed thru the fanouts, and we already waited for the
5638 	 * conn_ref to drop to 0. We are already in close, so
5639 	 * there cannot be any other thread from the top. qprocsoff
5640 	 * has completed, and service has completed or won't run in
5641 	 * future.
5642 	 */
5643 	ASSERT(connp->conn_ref == 1);
5644 
5645 	/*
5646 	 * A conn which was previously marked as IPCL_UDP cannot
5647 	 * retain the flag because it would have been cleared by
5648 	 * udp_close().
5649 	 */
5650 	ASSERT(!IPCL_IS_UDP(connp));
5651 
5652 	if (connp->conn_latch != NULL) {
5653 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5654 		connp->conn_latch = NULL;
5655 	}
5656 	if (connp->conn_policy != NULL) {
5657 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5658 		connp->conn_policy = NULL;
5659 	}
5660 	if (connp->conn_ipsec_opt_mp != NULL) {
5661 		freemsg(connp->conn_ipsec_opt_mp);
5662 		connp->conn_ipsec_opt_mp = NULL;
5663 	}
5664 
5665 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5666 
5667 	connp->conn_ref--;
5668 	ipcl_conn_destroy(connp);
5669 
5670 	q->q_ptr = WR(q)->q_ptr = NULL;
5671 	return (0);
5672 }
5673 
5674 int
5675 ip_snmpmod_close(queue_t *q)
5676 {
5677 	conn_t *connp = Q_TO_CONN(q);
5678 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5679 
5680 	qprocsoff(q);
5681 
5682 	if (connp->conn_flags & IPCL_UDPMOD)
5683 		udp_close_free(connp);
5684 
5685 	if (connp->conn_cred != NULL) {
5686 		crfree(connp->conn_cred);
5687 		connp->conn_cred = NULL;
5688 	}
5689 	CONN_DEC_REF(connp);
5690 	q->q_ptr = WR(q)->q_ptr = NULL;
5691 	return (0);
5692 }
5693 
5694 /*
5695  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5696  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5697  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5698  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5699  * queues as we never enqueue messages there and we don't handle any ioctls.
5700  * Everything else is freed.
5701  */
5702 void
5703 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5704 {
5705 	conn_t	*connp = q->q_ptr;
5706 	pfi_t	setfn;
5707 	pfi_t	getfn;
5708 
5709 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5710 
5711 	switch (DB_TYPE(mp)) {
5712 	case M_PROTO:
5713 	case M_PCPROTO:
5714 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5715 		    ((((union T_primitives *)mp->b_rptr)->type ==
5716 			T_SVR4_OPTMGMT_REQ) ||
5717 		    (((union T_primitives *)mp->b_rptr)->type ==
5718 			T_OPTMGMT_REQ))) {
5719 			/*
5720 			 * This is the only TPI primitive supported. Its
5721 			 * handling does not require tcp_t, but it does require
5722 			 * conn_t to check permissions.
5723 			 */
5724 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5725 
5726 			if (connp->conn_flags & IPCL_TCPMOD) {
5727 				setfn = tcp_snmp_set;
5728 				getfn = tcp_snmp_get;
5729 			} else {
5730 				setfn = udp_snmp_set;
5731 				getfn = udp_snmp_get;
5732 			}
5733 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5734 				freemsg(mp);
5735 				return;
5736 			}
5737 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5738 		    != NULL)
5739 			qreply(q, mp);
5740 		break;
5741 	case M_FLUSH:
5742 	case M_IOCTL:
5743 		putnext(q, mp);
5744 		break;
5745 	default:
5746 		freemsg(mp);
5747 		break;
5748 	}
5749 }
5750 
5751 /* Return the IP checksum for the IP header at "iph". */
5752 uint16_t
5753 ip_csum_hdr(ipha_t *ipha)
5754 {
5755 	uint16_t	*uph;
5756 	uint32_t	sum;
5757 	int		opt_len;
5758 
5759 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5760 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5761 	uph = (uint16_t *)ipha;
5762 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5763 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5764 	if (opt_len > 0) {
5765 		do {
5766 			sum += uph[10];
5767 			sum += uph[11];
5768 			uph += 2;
5769 		} while (--opt_len);
5770 	}
5771 	sum = (sum & 0xFFFF) + (sum >> 16);
5772 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5773 	if (sum == 0xffff)
5774 		sum = 0;
5775 	return ((uint16_t)sum);
5776 }
5777 
5778 /*
5779  * Called when the module is about to be unloaded
5780  */
5781 void
5782 ip_ddi_destroy(void)
5783 {
5784 	tnet_fini();
5785 
5786 	sctp_ddi_g_destroy();
5787 	tcp_ddi_g_destroy();
5788 	ipsec_policy_g_destroy();
5789 	ipcl_g_destroy();
5790 	ip_net_g_destroy();
5791 	ip_ire_g_fini();
5792 	inet_minor_destroy(ip_minor_arena);
5793 
5794 	netstack_unregister(NS_IP);
5795 }
5796 
5797 /*
5798  * First step in cleanup.
5799  */
5800 /* ARGSUSED */
5801 static void
5802 ip_stack_shutdown(netstackid_t stackid, void *arg)
5803 {
5804 	ip_stack_t *ipst = (ip_stack_t *)arg;
5805 
5806 #ifdef NS_DEBUG
5807 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5808 #endif
5809 
5810 	/* Get rid of loopback interfaces and their IREs */
5811 	ip_loopback_cleanup(ipst);
5812 }
5813 
5814 /*
5815  * Free the IP stack instance.
5816  */
5817 static void
5818 ip_stack_fini(netstackid_t stackid, void *arg)
5819 {
5820 	ip_stack_t *ipst = (ip_stack_t *)arg;
5821 	int ret;
5822 
5823 #ifdef NS_DEBUG
5824 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5825 #endif
5826 	ipv4_hook_destroy(ipst);
5827 	ipv6_hook_destroy(ipst);
5828 	ip_net_destroy(ipst);
5829 
5830 	rw_destroy(&ipst->ips_srcid_lock);
5831 
5832 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5833 	ipst->ips_ip_mibkp = NULL;
5834 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5835 	ipst->ips_icmp_mibkp = NULL;
5836 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5837 	ipst->ips_ip_kstat = NULL;
5838 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5839 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5840 	ipst->ips_ip6_kstat = NULL;
5841 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5842 
5843 	nd_free(&ipst->ips_ip_g_nd);
5844 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5845 	ipst->ips_param_arr = NULL;
5846 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5847 	ipst->ips_ndp_arr = NULL;
5848 
5849 	ip_mrouter_stack_destroy(ipst);
5850 
5851 	mutex_destroy(&ipst->ips_ip_mi_lock);
5852 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5853 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5854 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5855 
5856 	ret = untimeout(ipst->ips_igmp_timeout_id);
5857 	if (ret == -1) {
5858 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5859 	} else {
5860 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5861 		ipst->ips_igmp_timeout_id = 0;
5862 	}
5863 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5864 	if (ret == -1) {
5865 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5866 	} else {
5867 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5868 		ipst->ips_igmp_slowtimeout_id = 0;
5869 	}
5870 	ret = untimeout(ipst->ips_mld_timeout_id);
5871 	if (ret == -1) {
5872 		ASSERT(ipst->ips_mld_timeout_id == 0);
5873 	} else {
5874 		ASSERT(ipst->ips_mld_timeout_id != 0);
5875 		ipst->ips_mld_timeout_id = 0;
5876 	}
5877 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5878 	if (ret == -1) {
5879 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5880 	} else {
5881 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5882 		ipst->ips_mld_slowtimeout_id = 0;
5883 	}
5884 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5885 	if (ret == -1) {
5886 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5887 	} else {
5888 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5889 		ipst->ips_ip_ire_expire_id = 0;
5890 	}
5891 
5892 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5893 	mutex_destroy(&ipst->ips_mld_timer_lock);
5894 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5895 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5896 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5897 	rw_destroy(&ipst->ips_ill_g_lock);
5898 
5899 	ip_ire_fini(ipst);
5900 	ip6_asp_free(ipst);
5901 	conn_drain_fini(ipst);
5902 	ipcl_destroy(ipst);
5903 
5904 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5905 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5906 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5907 	ipst->ips_ndp4 = NULL;
5908 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5909 	ipst->ips_ndp6 = NULL;
5910 
5911 	if (ipst->ips_loopback_ksp != NULL) {
5912 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5913 		ipst->ips_loopback_ksp = NULL;
5914 	}
5915 
5916 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5917 	ipst->ips_phyint_g_list = NULL;
5918 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5919 	ipst->ips_ill_g_heads = NULL;
5920 
5921 	kmem_free(ipst, sizeof (*ipst));
5922 }
5923 
5924 /*
5925  * Called when the IP kernel module is loaded into the kernel
5926  */
5927 void
5928 ip_ddi_init(void)
5929 {
5930 	TCP6_MAJ = ddi_name_to_major(TCP6);
5931 	TCP_MAJ	= ddi_name_to_major(TCP);
5932 	SCTP_MAJ = ddi_name_to_major(SCTP);
5933 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5934 
5935 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5936 
5937 	/*
5938 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5939 	 * initial devices: ip, ip6, tcp, tcp6.
5940 	 */
5941 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5942 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5943 		cmn_err(CE_PANIC,
5944 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5945 	}
5946 
5947 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5948 
5949 	ipcl_g_init();
5950 	ip_ire_g_init();
5951 	ip_net_g_init();
5952 
5953 	/*
5954 	 * We want to be informed each time a stack is created or
5955 	 * destroyed in the kernel, so we can maintain the
5956 	 * set of udp_stack_t's.
5957 	 */
5958 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5959 	    ip_stack_fini);
5960 
5961 	ipsec_policy_g_init();
5962 	tcp_ddi_g_init();
5963 	sctp_ddi_g_init();
5964 
5965 	tnet_init();
5966 }
5967 
5968 /*
5969  * Initialize the IP stack instance.
5970  */
5971 static void *
5972 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5973 {
5974 	ip_stack_t	*ipst;
5975 	ipparam_t	*pa;
5976 	ipndp_t		*na;
5977 
5978 #ifdef NS_DEBUG
5979 	printf("ip_stack_init(stack %d)\n", stackid);
5980 #endif
5981 
5982 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5983 	ipst->ips_netstack = ns;
5984 
5985 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5986 	    KM_SLEEP);
5987 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5988 	    KM_SLEEP);
5989 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5990 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5991 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5992 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5993 
5994 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5995 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5996 	ipst->ips_igmp_deferred_next = INFINITY;
5997 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5998 	ipst->ips_mld_deferred_next = INFINITY;
5999 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6000 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6001 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6002 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6003 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6004 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6005 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6006 
6007 	ipcl_init(ipst);
6008 	ip_ire_init(ipst);
6009 	ip6_asp_init(ipst);
6010 	ipif_init(ipst);
6011 	conn_drain_init(ipst);
6012 	ip_mrouter_stack_init(ipst);
6013 
6014 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6015 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6016 
6017 	ipst->ips_ip_multirt_log_interval = 1000;
6018 
6019 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6020 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6021 	ipst->ips_ill_index = 1;
6022 
6023 	ipst->ips_saved_ip_g_forward = -1;
6024 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6025 
6026 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6027 	ipst->ips_param_arr = pa;
6028 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6029 
6030 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6031 	ipst->ips_ndp_arr = na;
6032 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6033 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6034 	    (caddr_t)&ipst->ips_ip_g_forward;
6035 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6036 	    (caddr_t)&ipst->ips_ipv6_forward;
6037 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6038 		"ip_cgtp_filter") == 0);
6039 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6040 	    (caddr_t)&ip_cgtp_filter;
6041 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6042 		"ipmp_hook_emulation") == 0);
6043 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6044 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6045 
6046 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6047 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6048 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6049 
6050 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6051 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6052 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6053 	ipst->ips_ip6_kstat =
6054 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6055 
6056 	ipst->ips_ipmp_enable_failback = B_TRUE;
6057 
6058 	ipst->ips_ip_src_id = 1;
6059 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6060 
6061 	ip_net_init(ipst, ns);
6062 	ipv4_hook_init(ipst);
6063 	ipv6_hook_init(ipst);
6064 
6065 	return (ipst);
6066 }
6067 
6068 /*
6069  * Allocate and initialize a DLPI template of the specified length.  (May be
6070  * called as writer.)
6071  */
6072 mblk_t *
6073 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6074 {
6075 	mblk_t	*mp;
6076 
6077 	mp = allocb(len, BPRI_MED);
6078 	if (!mp)
6079 		return (NULL);
6080 
6081 	/*
6082 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6083 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6084 	 * that other DLPI are M_PROTO.
6085 	 */
6086 	if (prim == DL_INFO_REQ) {
6087 		mp->b_datap->db_type = M_PCPROTO;
6088 	} else {
6089 		mp->b_datap->db_type = M_PROTO;
6090 	}
6091 
6092 	mp->b_wptr = mp->b_rptr + len;
6093 	bzero(mp->b_rptr, len);
6094 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6095 	return (mp);
6096 }
6097 
6098 const char *
6099 dlpi_prim_str(int prim)
6100 {
6101 	switch (prim) {
6102 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6103 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6104 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6105 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6106 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6107 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6108 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6109 	case DL_OK_ACK:		return ("DL_OK_ACK");
6110 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6111 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6112 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6113 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6114 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6115 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6116 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6117 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6118 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6119 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6120 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6121 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6122 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6123 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6124 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6125 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6126 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6127 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6128 	default:		return ("<unknown primitive>");
6129 	}
6130 }
6131 
6132 const char *
6133 dlpi_err_str(int err)
6134 {
6135 	switch (err) {
6136 	case DL_ACCESS:		return ("DL_ACCESS");
6137 	case DL_BADADDR:	return ("DL_BADADDR");
6138 	case DL_BADCORR:	return ("DL_BADCORR");
6139 	case DL_BADDATA:	return ("DL_BADDATA");
6140 	case DL_BADPPA:		return ("DL_BADPPA");
6141 	case DL_BADPRIM:	return ("DL_BADPRIM");
6142 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6143 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6144 	case DL_BADSAP:		return ("DL_BADSAP");
6145 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6146 	case DL_BOUND:		return ("DL_BOUND");
6147 	case DL_INITFAILED:	return ("DL_INITFAILED");
6148 	case DL_NOADDR:		return ("DL_NOADDR");
6149 	case DL_NOTINIT:	return ("DL_NOTINIT");
6150 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6151 	case DL_SYSERR:		return ("DL_SYSERR");
6152 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6153 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6154 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6155 	case DL_TOOMANY:	return ("DL_TOOMANY");
6156 	case DL_NOTENAB:	return ("DL_NOTENAB");
6157 	case DL_BUSY:		return ("DL_BUSY");
6158 	case DL_NOAUTO:		return ("DL_NOAUTO");
6159 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6160 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6161 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6162 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6163 	case DL_PENDING:	return ("DL_PENDING");
6164 	default:		return ("<unknown error>");
6165 	}
6166 }
6167 
6168 /*
6169  * Debug formatting routine.  Returns a character string representation of the
6170  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6171  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6172  *
6173  * Once the ndd table-printing interfaces are removed, this can be changed to
6174  * standard dotted-decimal form.
6175  */
6176 char *
6177 ip_dot_addr(ipaddr_t addr, char *buf)
6178 {
6179 	uint8_t *ap = (uint8_t *)&addr;
6180 
6181 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6182 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6183 	return (buf);
6184 }
6185 
6186 /*
6187  * Write the given MAC address as a printable string in the usual colon-
6188  * separated format.
6189  */
6190 const char *
6191 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6192 {
6193 	char *bp;
6194 
6195 	if (alen == 0 || buflen < 4)
6196 		return ("?");
6197 	bp = buf;
6198 	for (;;) {
6199 		/*
6200 		 * If there are more MAC address bytes available, but we won't
6201 		 * have any room to print them, then add "..." to the string
6202 		 * instead.  See below for the 'magic number' explanation.
6203 		 */
6204 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6205 			(void) strcpy(bp, "...");
6206 			break;
6207 		}
6208 		(void) sprintf(bp, "%02x", *addr++);
6209 		bp += 2;
6210 		if (--alen == 0)
6211 			break;
6212 		*bp++ = ':';
6213 		buflen -= 3;
6214 		/*
6215 		 * At this point, based on the first 'if' statement above,
6216 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6217 		 * buflen >= 4.  The first case leaves room for the final "xx"
6218 		 * number and trailing NUL byte.  The second leaves room for at
6219 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6220 		 * that statement.
6221 		 */
6222 	}
6223 	return (buf);
6224 }
6225 
6226 /*
6227  * Send an ICMP error after patching up the packet appropriately.  Returns
6228  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6229  */
6230 static boolean_t
6231 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6232     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6233     zoneid_t zoneid, ip_stack_t *ipst)
6234 {
6235 	ipha_t *ipha;
6236 	mblk_t *first_mp;
6237 	boolean_t secure;
6238 	unsigned char db_type;
6239 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6240 
6241 	first_mp = mp;
6242 	if (mctl_present) {
6243 		mp = mp->b_cont;
6244 		secure = ipsec_in_is_secure(first_mp);
6245 		ASSERT(mp != NULL);
6246 	} else {
6247 		/*
6248 		 * If this is an ICMP error being reported - which goes
6249 		 * up as M_CTLs, we need to convert them to M_DATA till
6250 		 * we finish checking with global policy because
6251 		 * ipsec_check_global_policy() assumes M_DATA as clear
6252 		 * and M_CTL as secure.
6253 		 */
6254 		db_type = DB_TYPE(mp);
6255 		DB_TYPE(mp) = M_DATA;
6256 		secure = B_FALSE;
6257 	}
6258 	/*
6259 	 * We are generating an icmp error for some inbound packet.
6260 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6261 	 * Before we generate an error, check with global policy
6262 	 * to see whether this is allowed to enter the system. As
6263 	 * there is no "conn", we are checking with global policy.
6264 	 */
6265 	ipha = (ipha_t *)mp->b_rptr;
6266 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6267 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6268 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6269 		if (first_mp == NULL)
6270 			return (B_FALSE);
6271 	}
6272 
6273 	if (!mctl_present)
6274 		DB_TYPE(mp) = db_type;
6275 
6276 	if (flags & IP_FF_SEND_ICMP) {
6277 		if (flags & IP_FF_HDR_COMPLETE) {
6278 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6279 				freemsg(first_mp);
6280 				return (B_TRUE);
6281 			}
6282 		}
6283 		if (flags & IP_FF_CKSUM) {
6284 			/*
6285 			 * Have to correct checksum since
6286 			 * the packet might have been
6287 			 * fragmented and the reassembly code in ip_rput
6288 			 * does not restore the IP checksum.
6289 			 */
6290 			ipha->ipha_hdr_checksum = 0;
6291 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6292 		}
6293 		switch (icmp_type) {
6294 		case ICMP_DEST_UNREACHABLE:
6295 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6296 			    ipst);
6297 			break;
6298 		default:
6299 			freemsg(first_mp);
6300 			break;
6301 		}
6302 	} else {
6303 		freemsg(first_mp);
6304 		return (B_FALSE);
6305 	}
6306 
6307 	return (B_TRUE);
6308 }
6309 
6310 /*
6311  * Used to send an ICMP error message when a packet is received for
6312  * a protocol that is not supported. The mblk passed as argument
6313  * is consumed by this function.
6314  */
6315 void
6316 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6317     ip_stack_t *ipst)
6318 {
6319 	mblk_t *mp;
6320 	ipha_t *ipha;
6321 	ill_t *ill;
6322 	ipsec_in_t *ii;
6323 
6324 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6325 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6326 
6327 	mp = ipsec_mp->b_cont;
6328 	ipsec_mp->b_cont = NULL;
6329 	ipha = (ipha_t *)mp->b_rptr;
6330 	/* Get ill from index in ipsec_in_t. */
6331 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6332 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6333 	    ipst);
6334 	if (ill != NULL) {
6335 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6336 			if (ip_fanout_send_icmp(q, mp, flags,
6337 			    ICMP_DEST_UNREACHABLE,
6338 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6339 				BUMP_MIB(ill->ill_ip_mib,
6340 				    ipIfStatsInUnknownProtos);
6341 			}
6342 		} else {
6343 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6344 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6345 			    0, B_FALSE, zoneid, ipst)) {
6346 				BUMP_MIB(ill->ill_ip_mib,
6347 				    ipIfStatsInUnknownProtos);
6348 			}
6349 		}
6350 		ill_refrele(ill);
6351 	} else { /* re-link for the freemsg() below. */
6352 		ipsec_mp->b_cont = mp;
6353 	}
6354 
6355 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6356 	freemsg(ipsec_mp);
6357 }
6358 
6359 /*
6360  * See if the inbound datagram has had IPsec processing applied to it.
6361  */
6362 boolean_t
6363 ipsec_in_is_secure(mblk_t *ipsec_mp)
6364 {
6365 	ipsec_in_t *ii;
6366 
6367 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6368 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6369 
6370 	if (ii->ipsec_in_loopback) {
6371 		return (ii->ipsec_in_secure);
6372 	} else {
6373 		return (ii->ipsec_in_ah_sa != NULL ||
6374 		    ii->ipsec_in_esp_sa != NULL ||
6375 		    ii->ipsec_in_decaps);
6376 	}
6377 }
6378 
6379 /*
6380  * Handle protocols with which IP is less intimate.  There
6381  * can be more than one stream bound to a particular
6382  * protocol.  When this is the case, normally each one gets a copy
6383  * of any incoming packets.
6384  *
6385  * IPSEC NOTE :
6386  *
6387  * Don't allow a secure packet going up a non-secure connection.
6388  * We don't allow this because
6389  *
6390  * 1) Reply might go out in clear which will be dropped at
6391  *    the sending side.
6392  * 2) If the reply goes out in clear it will give the
6393  *    adversary enough information for getting the key in
6394  *    most of the cases.
6395  *
6396  * Moreover getting a secure packet when we expect clear
6397  * implies that SA's were added without checking for
6398  * policy on both ends. This should not happen once ISAKMP
6399  * is used to negotiate SAs as SAs will be added only after
6400  * verifying the policy.
6401  *
6402  * NOTE : If the packet was tunneled and not multicast we only send
6403  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6404  * back to delivering packets to AF_INET6 raw sockets.
6405  *
6406  * IPQoS Notes:
6407  * Once we have determined the client, invoke IPPF processing.
6408  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6409  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6410  * ip_policy will be false.
6411  *
6412  * Zones notes:
6413  * Currently only applications in the global zone can create raw sockets for
6414  * protocols other than ICMP. So unlike the broadcast / multicast case of
6415  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6416  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6417  */
6418 static void
6419 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6420     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6421     zoneid_t zoneid)
6422 {
6423 	queue_t	*rq;
6424 	mblk_t	*mp1, *first_mp1;
6425 	uint_t	protocol = ipha->ipha_protocol;
6426 	ipaddr_t dst;
6427 	boolean_t one_only;
6428 	mblk_t *first_mp = mp;
6429 	boolean_t secure;
6430 	uint32_t ill_index;
6431 	conn_t	*connp, *first_connp, *next_connp;
6432 	connf_t	*connfp;
6433 	boolean_t shared_addr;
6434 	mib2_ipIfStatsEntry_t *mibptr;
6435 	ip_stack_t *ipst = recv_ill->ill_ipst;
6436 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6437 
6438 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6439 	if (mctl_present) {
6440 		mp = first_mp->b_cont;
6441 		secure = ipsec_in_is_secure(first_mp);
6442 		ASSERT(mp != NULL);
6443 	} else {
6444 		secure = B_FALSE;
6445 	}
6446 	dst = ipha->ipha_dst;
6447 	/*
6448 	 * If the packet was tunneled and not multicast we only send to it
6449 	 * the first match.
6450 	 */
6451 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6452 	    !CLASSD(dst));
6453 
6454 	shared_addr = (zoneid == ALL_ZONES);
6455 	if (shared_addr) {
6456 		/*
6457 		 * We don't allow multilevel ports for raw IP, so no need to
6458 		 * check for that here.
6459 		 */
6460 		zoneid = tsol_packet_to_zoneid(mp);
6461 	}
6462 
6463 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6464 	mutex_enter(&connfp->connf_lock);
6465 	connp = connfp->connf_head;
6466 	for (connp = connfp->connf_head; connp != NULL;
6467 		connp = connp->conn_next) {
6468 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6469 		    zoneid) &&
6470 		    (!is_system_labeled() ||
6471 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6472 		    connp)))
6473 			break;
6474 	}
6475 
6476 	if (connp == NULL || connp->conn_upq == NULL) {
6477 		/*
6478 		 * No one bound to these addresses.  Is
6479 		 * there a client that wants all
6480 		 * unclaimed datagrams?
6481 		 */
6482 		mutex_exit(&connfp->connf_lock);
6483 		/*
6484 		 * Check for IPPROTO_ENCAP...
6485 		 */
6486 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6487 			/*
6488 			 * If an IPsec mblk is here on a multicast
6489 			 * tunnel (using ip_mroute stuff), check policy here,
6490 			 * THEN ship off to ip_mroute_decap().
6491 			 *
6492 			 * BTW,  If I match a configured IP-in-IP
6493 			 * tunnel, this path will not be reached, and
6494 			 * ip_mroute_decap will never be called.
6495 			 */
6496 			first_mp = ipsec_check_global_policy(first_mp, connp,
6497 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6498 			if (first_mp != NULL) {
6499 				if (mctl_present)
6500 					freeb(first_mp);
6501 				ip_mroute_decap(q, mp, ill);
6502 			} /* Else we already freed everything! */
6503 		} else {
6504 			/*
6505 			 * Otherwise send an ICMP protocol unreachable.
6506 			 */
6507 			if (ip_fanout_send_icmp(q, first_mp, flags,
6508 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6509 			    mctl_present, zoneid, ipst)) {
6510 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6511 			}
6512 		}
6513 		return;
6514 	}
6515 	CONN_INC_REF(connp);
6516 	first_connp = connp;
6517 
6518 	/*
6519 	 * Only send message to one tunnel driver by immediately
6520 	 * terminating the loop.
6521 	 */
6522 	connp = one_only ? NULL : connp->conn_next;
6523 
6524 	for (;;) {
6525 		while (connp != NULL) {
6526 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6527 			    flags, zoneid) &&
6528 			    (!is_system_labeled() ||
6529 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6530 			    shared_addr, connp)))
6531 				break;
6532 			connp = connp->conn_next;
6533 		}
6534 
6535 		/*
6536 		 * Copy the packet.
6537 		 */
6538 		if (connp == NULL || connp->conn_upq == NULL ||
6539 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6540 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6541 			/*
6542 			 * No more interested clients or memory
6543 			 * allocation failed
6544 			 */
6545 			connp = first_connp;
6546 			break;
6547 		}
6548 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6549 		CONN_INC_REF(connp);
6550 		mutex_exit(&connfp->connf_lock);
6551 		rq = connp->conn_rq;
6552 		if (!canputnext(rq)) {
6553 			if (flags & IP_FF_RAWIP) {
6554 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6555 			} else {
6556 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6557 			}
6558 
6559 			freemsg(first_mp1);
6560 		} else {
6561 			/*
6562 			 * Don't enforce here if we're an actual tunnel -
6563 			 * let "tun" do it instead.
6564 			 */
6565 			if (!IPCL_IS_IPTUN(connp) &&
6566 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6567 			    secure)) {
6568 				first_mp1 = ipsec_check_inbound_policy
6569 				    (first_mp1, connp, ipha, NULL,
6570 				    mctl_present);
6571 			}
6572 			if (first_mp1 != NULL) {
6573 				int in_flags = 0;
6574 				/*
6575 				 * ip_fanout_proto also gets called from
6576 				 * icmp_inbound_error_fanout, in which case
6577 				 * the msg type is M_CTL.  Don't add info
6578 				 * in this case for the time being. In future
6579 				 * when there is a need for knowing the
6580 				 * inbound iface index for ICMP error msgs,
6581 				 * then this can be changed.
6582 				 */
6583 				if (connp->conn_recvif)
6584 					in_flags = IPF_RECVIF;
6585 				/*
6586 				 * The ULP may support IP_RECVPKTINFO for both
6587 				 * IP v4 and v6 so pass the appropriate argument
6588 				 * based on conn IP version.
6589 				 */
6590 				if (connp->conn_ip_recvpktinfo) {
6591 					if (connp->conn_af_isv6) {
6592 						/*
6593 						 * V6 only needs index
6594 						 */
6595 						in_flags |= IPF_RECVIF;
6596 					} else {
6597 						/*
6598 						 * V4 needs index +
6599 						 * matching address.
6600 						 */
6601 						in_flags |= IPF_RECVADDR;
6602 					}
6603 				}
6604 				if ((in_flags != 0) &&
6605 				    (mp->b_datap->db_type != M_CTL)) {
6606 					/*
6607 					 * the actual data will be
6608 					 * contained in b_cont upon
6609 					 * successful return of the
6610 					 * following call else
6611 					 * original mblk is returned
6612 					 */
6613 					ASSERT(recv_ill != NULL);
6614 					mp1 = ip_add_info(mp1, recv_ill,
6615 					    in_flags, IPCL_ZONEID(connp), ipst);
6616 				}
6617 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6618 				if (mctl_present)
6619 					freeb(first_mp1);
6620 				putnext(rq, mp1);
6621 			}
6622 		}
6623 		mutex_enter(&connfp->connf_lock);
6624 		/* Follow the next pointer before releasing the conn. */
6625 		next_connp = connp->conn_next;
6626 		CONN_DEC_REF(connp);
6627 		connp = next_connp;
6628 	}
6629 
6630 	/* Last one.  Send it upstream. */
6631 	mutex_exit(&connfp->connf_lock);
6632 
6633 	/*
6634 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6635 	 * will be set to false.
6636 	 */
6637 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6638 		ill_index = ill->ill_phyint->phyint_ifindex;
6639 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6640 		if (mp == NULL) {
6641 			CONN_DEC_REF(connp);
6642 			if (mctl_present) {
6643 				freeb(first_mp);
6644 			}
6645 			return;
6646 		}
6647 	}
6648 
6649 	rq = connp->conn_rq;
6650 	if (!canputnext(rq)) {
6651 		if (flags & IP_FF_RAWIP) {
6652 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6653 		} else {
6654 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6655 		}
6656 
6657 		freemsg(first_mp);
6658 	} else {
6659 		if (IPCL_IS_IPTUN(connp)) {
6660 			/*
6661 			 * Tunneled packet.  We enforce policy in the tunnel
6662 			 * module itself.
6663 			 *
6664 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6665 			 * a policy check.
6666 			 */
6667 			putnext(rq, first_mp);
6668 			CONN_DEC_REF(connp);
6669 			return;
6670 		}
6671 
6672 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6673 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6674 			    ipha, NULL, mctl_present);
6675 		}
6676 
6677 		if (first_mp != NULL) {
6678 			int in_flags = 0;
6679 
6680 			/*
6681 			 * ip_fanout_proto also gets called
6682 			 * from icmp_inbound_error_fanout, in
6683 			 * which case the msg type is M_CTL.
6684 			 * Don't add info in this case for time
6685 			 * being. In future when there is a
6686 			 * need for knowing the inbound iface
6687 			 * index for ICMP error msgs, then this
6688 			 * can be changed
6689 			 */
6690 			if (connp->conn_recvif)
6691 				in_flags = IPF_RECVIF;
6692 			if (connp->conn_ip_recvpktinfo) {
6693 				if (connp->conn_af_isv6) {
6694 					/*
6695 					 * V6 only needs index
6696 					 */
6697 					in_flags |= IPF_RECVIF;
6698 				} else {
6699 					/*
6700 					 * V4 needs index +
6701 					 * matching address.
6702 					 */
6703 					in_flags |= IPF_RECVADDR;
6704 				}
6705 			}
6706 			if ((in_flags != 0) &&
6707 			    (mp->b_datap->db_type != M_CTL)) {
6708 
6709 				/*
6710 				 * the actual data will be contained in
6711 				 * b_cont upon successful return
6712 				 * of the following call else original
6713 				 * mblk is returned
6714 				 */
6715 				ASSERT(recv_ill != NULL);
6716 				mp = ip_add_info(mp, recv_ill,
6717 				    in_flags, IPCL_ZONEID(connp), ipst);
6718 			}
6719 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6720 			putnext(rq, mp);
6721 			if (mctl_present)
6722 				freeb(first_mp);
6723 		}
6724 	}
6725 	CONN_DEC_REF(connp);
6726 }
6727 
6728 /*
6729  * Fanout for TCP packets
6730  * The caller puts <fport, lport> in the ports parameter.
6731  *
6732  * IPQoS Notes
6733  * Before sending it to the client, invoke IPPF processing.
6734  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6735  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6736  * ip_policy is false.
6737  */
6738 static void
6739 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6740     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6741 {
6742 	mblk_t  *first_mp;
6743 	boolean_t secure;
6744 	uint32_t ill_index;
6745 	int	ip_hdr_len;
6746 	tcph_t	*tcph;
6747 	boolean_t syn_present = B_FALSE;
6748 	conn_t	*connp;
6749 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6750 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6751 
6752 	ASSERT(recv_ill != NULL);
6753 
6754 	first_mp = mp;
6755 	if (mctl_present) {
6756 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6757 		mp = first_mp->b_cont;
6758 		secure = ipsec_in_is_secure(first_mp);
6759 		ASSERT(mp != NULL);
6760 	} else {
6761 		secure = B_FALSE;
6762 	}
6763 
6764 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6765 
6766 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6767 		    zoneid, ipst)) == NULL) {
6768 		/*
6769 		 * No connected connection or listener. Send a
6770 		 * TH_RST via tcp_xmit_listeners_reset.
6771 		 */
6772 
6773 		/* Initiate IPPf processing, if needed. */
6774 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6775 			uint32_t ill_index;
6776 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6777 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6778 			if (first_mp == NULL)
6779 				return;
6780 		}
6781 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6782 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6783 		    zoneid));
6784 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6785 		    ipst->ips_netstack->netstack_tcp);
6786 		return;
6787 	}
6788 
6789 	/*
6790 	 * Allocate the SYN for the TCP connection here itself
6791 	 */
6792 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6793 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6794 		if (IPCL_IS_TCP(connp)) {
6795 			squeue_t *sqp;
6796 
6797 			/*
6798 			 * For fused tcp loopback, assign the eager's
6799 			 * squeue to be that of the active connect's.
6800 			 * Note that we don't check for IP_FF_LOOPBACK
6801 			 * here since this routine gets called only
6802 			 * for loopback (unlike the IPv6 counterpart).
6803 			 */
6804 			ASSERT(Q_TO_CONN(q) != NULL);
6805 			if (do_tcp_fusion &&
6806 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6807 			    !secure &&
6808 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6809 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6810 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6811 				sqp = Q_TO_CONN(q)->conn_sqp;
6812 			} else {
6813 				sqp = IP_SQUEUE_GET(lbolt);
6814 			}
6815 
6816 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6817 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6818 			syn_present = B_TRUE;
6819 		}
6820 	}
6821 
6822 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6823 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6824 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6825 		if ((flags & TH_RST) || (flags & TH_URG)) {
6826 			CONN_DEC_REF(connp);
6827 			freemsg(first_mp);
6828 			return;
6829 		}
6830 		if (flags & TH_ACK) {
6831 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6832 			    ipst->ips_netstack->netstack_tcp);
6833 			CONN_DEC_REF(connp);
6834 			return;
6835 		}
6836 
6837 		CONN_DEC_REF(connp);
6838 		freemsg(first_mp);
6839 		return;
6840 	}
6841 
6842 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6843 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6844 		    NULL, mctl_present);
6845 		if (first_mp == NULL) {
6846 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6847 			CONN_DEC_REF(connp);
6848 			return;
6849 		}
6850 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6851 			ASSERT(syn_present);
6852 			if (mctl_present) {
6853 				ASSERT(first_mp != mp);
6854 				first_mp->b_datap->db_struioflag |=
6855 				    STRUIO_POLICY;
6856 			} else {
6857 				ASSERT(first_mp == mp);
6858 				mp->b_datap->db_struioflag &=
6859 				    ~STRUIO_EAGER;
6860 				mp->b_datap->db_struioflag |=
6861 				    STRUIO_POLICY;
6862 			}
6863 		} else {
6864 			/*
6865 			 * Discard first_mp early since we're dealing with a
6866 			 * fully-connected conn_t and tcp doesn't do policy in
6867 			 * this case.
6868 			 */
6869 			if (mctl_present) {
6870 				freeb(first_mp);
6871 				mctl_present = B_FALSE;
6872 			}
6873 			first_mp = mp;
6874 		}
6875 	}
6876 
6877 	/*
6878 	 * Initiate policy processing here if needed. If we get here from
6879 	 * icmp_inbound_error_fanout, ip_policy is false.
6880 	 */
6881 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6882 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6883 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6884 		if (mp == NULL) {
6885 			CONN_DEC_REF(connp);
6886 			if (mctl_present)
6887 				freeb(first_mp);
6888 			return;
6889 		} else if (mctl_present) {
6890 			ASSERT(first_mp != mp);
6891 			first_mp->b_cont = mp;
6892 		} else {
6893 			first_mp = mp;
6894 		}
6895 	}
6896 
6897 
6898 
6899 	/* Handle socket options. */
6900 	if (!syn_present &&
6901 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6902 		/* Add header */
6903 		ASSERT(recv_ill != NULL);
6904 		/*
6905 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6906 		 * IPF_RECVIF.
6907 		 */
6908 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6909 		    ipst);
6910 		if (mp == NULL) {
6911 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6912 			CONN_DEC_REF(connp);
6913 			if (mctl_present)
6914 				freeb(first_mp);
6915 			return;
6916 		} else if (mctl_present) {
6917 			/*
6918 			 * ip_add_info might return a new mp.
6919 			 */
6920 			ASSERT(first_mp != mp);
6921 			first_mp->b_cont = mp;
6922 		} else {
6923 			first_mp = mp;
6924 		}
6925 	}
6926 
6927 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6928 	if (IPCL_IS_TCP(connp)) {
6929 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6930 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6931 	} else {
6932 		putnext(connp->conn_rq, first_mp);
6933 		CONN_DEC_REF(connp);
6934 	}
6935 }
6936 
6937 /*
6938  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6939  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6940  * Caller is responsible for dropping references to the conn, and freeing
6941  * first_mp.
6942  *
6943  * IPQoS Notes
6944  * Before sending it to the client, invoke IPPF processing. Policy processing
6945  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6946  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6947  * ip_wput_local, ip_policy is false.
6948  */
6949 static void
6950 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6951     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6952     boolean_t ip_policy)
6953 {
6954 	boolean_t	mctl_present = (first_mp != NULL);
6955 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6956 	uint32_t	ill_index;
6957 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6958 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6959 
6960 	ASSERT(ill != NULL);
6961 
6962 	if (mctl_present)
6963 		first_mp->b_cont = mp;
6964 	else
6965 		first_mp = mp;
6966 
6967 	if (CONN_UDP_FLOWCTLD(connp)) {
6968 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6969 		freemsg(first_mp);
6970 		return;
6971 	}
6972 
6973 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6974 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6975 		    NULL, mctl_present);
6976 		if (first_mp == NULL) {
6977 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6978 			return;	/* Freed by ipsec_check_inbound_policy(). */
6979 		}
6980 	}
6981 	if (mctl_present)
6982 		freeb(first_mp);
6983 
6984 	/* Handle options. */
6985 	if (connp->conn_recvif)
6986 		in_flags = IPF_RECVIF;
6987 	/*
6988 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6989 	 * passed to ip_add_info is based on IP version of connp.
6990 	 */
6991 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6992 		if (connp->conn_af_isv6) {
6993 			/*
6994 			 * V6 only needs index
6995 			 */
6996 			in_flags |= IPF_RECVIF;
6997 		} else {
6998 			/*
6999 			 * V4 needs index + matching address.
7000 			 */
7001 			in_flags |= IPF_RECVADDR;
7002 		}
7003 	}
7004 
7005 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7006 		in_flags |= IPF_RECVSLLA;
7007 
7008 	/*
7009 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7010 	 * freed if the packet is dropped. The caller will do so.
7011 	 */
7012 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7013 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7014 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7015 		if (mp == NULL) {
7016 			return;
7017 		}
7018 	}
7019 	if ((in_flags != 0) &&
7020 	    (mp->b_datap->db_type != M_CTL)) {
7021 		/*
7022 		 * The actual data will be contained in b_cont
7023 		 * upon successful return of the following call
7024 		 * else original mblk is returned
7025 		 */
7026 		ASSERT(recv_ill != NULL);
7027 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7028 		    ipst);
7029 	}
7030 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7031 	/* Send it upstream */
7032 	CONN_UDP_RECV(connp, mp);
7033 }
7034 
7035 /*
7036  * Fanout for UDP packets.
7037  * The caller puts <fport, lport> in the ports parameter.
7038  *
7039  * If SO_REUSEADDR is set all multicast and broadcast packets
7040  * will be delivered to all streams bound to the same port.
7041  *
7042  * Zones notes:
7043  * Multicast and broadcast packets will be distributed to streams in all zones.
7044  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7045  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7046  * packets. To maintain this behavior with multiple zones, the conns are grouped
7047  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7048  * each zone. If unset, all the following conns in the same zone are skipped.
7049  */
7050 static void
7051 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7052     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7053     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7054 {
7055 	uint32_t	dstport, srcport;
7056 	ipaddr_t	dst;
7057 	mblk_t		*first_mp;
7058 	boolean_t	secure;
7059 	in6_addr_t	v6src;
7060 	conn_t		*connp;
7061 	connf_t		*connfp;
7062 	conn_t		*first_connp;
7063 	conn_t		*next_connp;
7064 	mblk_t		*mp1, *first_mp1;
7065 	ipaddr_t	src;
7066 	zoneid_t	last_zoneid;
7067 	boolean_t	reuseaddr;
7068 	boolean_t	shared_addr;
7069 	ip_stack_t	*ipst;
7070 
7071 	ASSERT(recv_ill != NULL);
7072 	ipst = recv_ill->ill_ipst;
7073 
7074 	first_mp = mp;
7075 	if (mctl_present) {
7076 		mp = first_mp->b_cont;
7077 		first_mp->b_cont = NULL;
7078 		secure = ipsec_in_is_secure(first_mp);
7079 		ASSERT(mp != NULL);
7080 	} else {
7081 		first_mp = NULL;
7082 		secure = B_FALSE;
7083 	}
7084 
7085 	/* Extract ports in net byte order */
7086 	dstport = htons(ntohl(ports) & 0xFFFF);
7087 	srcport = htons(ntohl(ports) >> 16);
7088 	dst = ipha->ipha_dst;
7089 	src = ipha->ipha_src;
7090 
7091 	shared_addr = (zoneid == ALL_ZONES);
7092 	if (shared_addr) {
7093 		/*
7094 		 * No need to handle exclusive-stack zones since ALL_ZONES
7095 		 * only applies to the shared stack.
7096 		 */
7097 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7098 		if (zoneid == ALL_ZONES)
7099 			zoneid = tsol_packet_to_zoneid(mp);
7100 	}
7101 
7102 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7103 	mutex_enter(&connfp->connf_lock);
7104 	connp = connfp->connf_head;
7105 	if (!broadcast && !CLASSD(dst)) {
7106 		/*
7107 		 * Not broadcast or multicast. Send to the one (first)
7108 		 * client we find. No need to check conn_wantpacket()
7109 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7110 		 * IPv4 unicast packets.
7111 		 */
7112 		while ((connp != NULL) &&
7113 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7114 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7115 			connp = connp->conn_next;
7116 		}
7117 
7118 		if (connp == NULL || connp->conn_upq == NULL)
7119 			goto notfound;
7120 
7121 		if (is_system_labeled() &&
7122 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7123 		    connp))
7124 			goto notfound;
7125 
7126 		CONN_INC_REF(connp);
7127 		mutex_exit(&connfp->connf_lock);
7128 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7129 		    flags, recv_ill, ip_policy);
7130 		IP_STAT(ipst, ip_udp_fannorm);
7131 		CONN_DEC_REF(connp);
7132 		return;
7133 	}
7134 
7135 	/*
7136 	 * Broadcast and multicast case
7137 	 *
7138 	 * Need to check conn_wantpacket().
7139 	 * If SO_REUSEADDR has been set on the first we send the
7140 	 * packet to all clients that have joined the group and
7141 	 * match the port.
7142 	 */
7143 
7144 	while (connp != NULL) {
7145 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7146 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7147 		    (!is_system_labeled() ||
7148 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7149 		    connp)))
7150 			break;
7151 		connp = connp->conn_next;
7152 	}
7153 
7154 	if (connp == NULL || connp->conn_upq == NULL)
7155 		goto notfound;
7156 
7157 	first_connp = connp;
7158 	/*
7159 	 * When SO_REUSEADDR is not set, send the packet only to the first
7160 	 * matching connection in its zone by keeping track of the zoneid.
7161 	 */
7162 	reuseaddr = first_connp->conn_reuseaddr;
7163 	last_zoneid = first_connp->conn_zoneid;
7164 
7165 	CONN_INC_REF(connp);
7166 	connp = connp->conn_next;
7167 	for (;;) {
7168 		while (connp != NULL) {
7169 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7170 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7171 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7172 			    (!is_system_labeled() ||
7173 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7174 			    shared_addr, connp)))
7175 				break;
7176 			connp = connp->conn_next;
7177 		}
7178 		/*
7179 		 * Just copy the data part alone. The mctl part is
7180 		 * needed just for verifying policy and it is never
7181 		 * sent up.
7182 		 */
7183 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7184 		    ((mp1 = copymsg(mp)) == NULL))) {
7185 			/*
7186 			 * No more interested clients or memory
7187 			 * allocation failed
7188 			 */
7189 			connp = first_connp;
7190 			break;
7191 		}
7192 		if (connp->conn_zoneid != last_zoneid) {
7193 			/*
7194 			 * Update the zoneid so that the packet isn't sent to
7195 			 * any more conns in the same zone unless SO_REUSEADDR
7196 			 * is set.
7197 			 */
7198 			reuseaddr = connp->conn_reuseaddr;
7199 			last_zoneid = connp->conn_zoneid;
7200 		}
7201 		if (first_mp != NULL) {
7202 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7203 			    ipsec_info_type == IPSEC_IN);
7204 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7205 			    ipst->ips_netstack);
7206 			if (first_mp1 == NULL) {
7207 				freemsg(mp1);
7208 				connp = first_connp;
7209 				break;
7210 			}
7211 		} else {
7212 			first_mp1 = NULL;
7213 		}
7214 		CONN_INC_REF(connp);
7215 		mutex_exit(&connfp->connf_lock);
7216 		/*
7217 		 * IPQoS notes: We don't send the packet for policy
7218 		 * processing here, will do it for the last one (below).
7219 		 * i.e. we do it per-packet now, but if we do policy
7220 		 * processing per-conn, then we would need to do it
7221 		 * here too.
7222 		 */
7223 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7224 		    ipha, flags, recv_ill, B_FALSE);
7225 		mutex_enter(&connfp->connf_lock);
7226 		/* Follow the next pointer before releasing the conn. */
7227 		next_connp = connp->conn_next;
7228 		IP_STAT(ipst, ip_udp_fanmb);
7229 		CONN_DEC_REF(connp);
7230 		connp = next_connp;
7231 	}
7232 
7233 	/* Last one.  Send it upstream. */
7234 	mutex_exit(&connfp->connf_lock);
7235 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7236 	    recv_ill, ip_policy);
7237 	IP_STAT(ipst, ip_udp_fanmb);
7238 	CONN_DEC_REF(connp);
7239 	return;
7240 
7241 notfound:
7242 
7243 	mutex_exit(&connfp->connf_lock);
7244 	IP_STAT(ipst, ip_udp_fanothers);
7245 	/*
7246 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7247 	 * have already been matched above, since they live in the IPv4
7248 	 * fanout tables. This implies we only need to
7249 	 * check for IPv6 in6addr_any endpoints here.
7250 	 * Thus we compare using ipv6_all_zeros instead of the destination
7251 	 * address, except for the multicast group membership lookup which
7252 	 * uses the IPv4 destination.
7253 	 */
7254 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7255 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7256 	mutex_enter(&connfp->connf_lock);
7257 	connp = connfp->connf_head;
7258 	if (!broadcast && !CLASSD(dst)) {
7259 		while (connp != NULL) {
7260 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7261 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7262 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7263 			    !connp->conn_ipv6_v6only)
7264 				break;
7265 			connp = connp->conn_next;
7266 		}
7267 
7268 		if (connp != NULL && is_system_labeled() &&
7269 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7270 		    connp))
7271 			connp = NULL;
7272 
7273 		if (connp == NULL || connp->conn_upq == NULL) {
7274 			/*
7275 			 * No one bound to this port.  Is
7276 			 * there a client that wants all
7277 			 * unclaimed datagrams?
7278 			 */
7279 			mutex_exit(&connfp->connf_lock);
7280 
7281 			if (mctl_present)
7282 				first_mp->b_cont = mp;
7283 			else
7284 				first_mp = mp;
7285 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7286 			    connf_head != NULL) {
7287 				ip_fanout_proto(q, first_mp, ill, ipha,
7288 				    flags | IP_FF_RAWIP, mctl_present,
7289 				    ip_policy, recv_ill, zoneid);
7290 			} else {
7291 				if (ip_fanout_send_icmp(q, first_mp, flags,
7292 				    ICMP_DEST_UNREACHABLE,
7293 				    ICMP_PORT_UNREACHABLE,
7294 				    mctl_present, zoneid, ipst)) {
7295 					BUMP_MIB(ill->ill_ip_mib,
7296 					    udpIfStatsNoPorts);
7297 				}
7298 			}
7299 			return;
7300 		}
7301 
7302 		CONN_INC_REF(connp);
7303 		mutex_exit(&connfp->connf_lock);
7304 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7305 		    flags, recv_ill, ip_policy);
7306 		CONN_DEC_REF(connp);
7307 		return;
7308 	}
7309 	/*
7310 	 * IPv4 multicast packet being delivered to an AF_INET6
7311 	 * in6addr_any endpoint.
7312 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7313 	 * and not conn_wantpacket_v6() since any multicast membership is
7314 	 * for an IPv4-mapped multicast address.
7315 	 * The packet is sent to all clients in all zones that have joined the
7316 	 * group and match the port.
7317 	 */
7318 	while (connp != NULL) {
7319 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7320 		    srcport, v6src) &&
7321 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7322 		    (!is_system_labeled() ||
7323 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7324 		    connp)))
7325 			break;
7326 		connp = connp->conn_next;
7327 	}
7328 
7329 	if (connp == NULL || connp->conn_upq == NULL) {
7330 		/*
7331 		 * No one bound to this port.  Is
7332 		 * there a client that wants all
7333 		 * unclaimed datagrams?
7334 		 */
7335 		mutex_exit(&connfp->connf_lock);
7336 
7337 		if (mctl_present)
7338 			first_mp->b_cont = mp;
7339 		else
7340 			first_mp = mp;
7341 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7342 		    NULL) {
7343 			ip_fanout_proto(q, first_mp, ill, ipha,
7344 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7345 			    recv_ill, zoneid);
7346 		} else {
7347 			/*
7348 			 * We used to attempt to send an icmp error here, but
7349 			 * since this is known to be a multicast packet
7350 			 * and we don't send icmp errors in response to
7351 			 * multicast, just drop the packet and give up sooner.
7352 			 */
7353 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7354 			freemsg(first_mp);
7355 		}
7356 		return;
7357 	}
7358 
7359 	first_connp = connp;
7360 
7361 	CONN_INC_REF(connp);
7362 	connp = connp->conn_next;
7363 	for (;;) {
7364 		while (connp != NULL) {
7365 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7366 			    ipv6_all_zeros, srcport, v6src) &&
7367 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7368 			    (!is_system_labeled() ||
7369 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7370 			    shared_addr, connp)))
7371 				break;
7372 			connp = connp->conn_next;
7373 		}
7374 		/*
7375 		 * Just copy the data part alone. The mctl part is
7376 		 * needed just for verifying policy and it is never
7377 		 * sent up.
7378 		 */
7379 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7380 		    ((mp1 = copymsg(mp)) == NULL))) {
7381 			/*
7382 			 * No more intested clients or memory
7383 			 * allocation failed
7384 			 */
7385 			connp = first_connp;
7386 			break;
7387 		}
7388 		if (first_mp != NULL) {
7389 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7390 			    ipsec_info_type == IPSEC_IN);
7391 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7392 			    ipst->ips_netstack);
7393 			if (first_mp1 == NULL) {
7394 				freemsg(mp1);
7395 				connp = first_connp;
7396 				break;
7397 			}
7398 		} else {
7399 			first_mp1 = NULL;
7400 		}
7401 		CONN_INC_REF(connp);
7402 		mutex_exit(&connfp->connf_lock);
7403 		/*
7404 		 * IPQoS notes: We don't send the packet for policy
7405 		 * processing here, will do it for the last one (below).
7406 		 * i.e. we do it per-packet now, but if we do policy
7407 		 * processing per-conn, then we would need to do it
7408 		 * here too.
7409 		 */
7410 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7411 		    ipha, flags, recv_ill, B_FALSE);
7412 		mutex_enter(&connfp->connf_lock);
7413 		/* Follow the next pointer before releasing the conn. */
7414 		next_connp = connp->conn_next;
7415 		CONN_DEC_REF(connp);
7416 		connp = next_connp;
7417 	}
7418 
7419 	/* Last one.  Send it upstream. */
7420 	mutex_exit(&connfp->connf_lock);
7421 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7422 	    recv_ill, ip_policy);
7423 	CONN_DEC_REF(connp);
7424 }
7425 
7426 /*
7427  * Complete the ip_wput header so that it
7428  * is possible to generate ICMP
7429  * errors.
7430  */
7431 int
7432 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7433 {
7434 	ire_t *ire;
7435 
7436 	if (ipha->ipha_src == INADDR_ANY) {
7437 		ire = ire_lookup_local(zoneid, ipst);
7438 		if (ire == NULL) {
7439 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7440 			return (1);
7441 		}
7442 		ipha->ipha_src = ire->ire_addr;
7443 		ire_refrele(ire);
7444 	}
7445 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7446 	ipha->ipha_hdr_checksum = 0;
7447 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7448 	return (0);
7449 }
7450 
7451 /*
7452  * Nobody should be sending
7453  * packets up this stream
7454  */
7455 static void
7456 ip_lrput(queue_t *q, mblk_t *mp)
7457 {
7458 	mblk_t *mp1;
7459 
7460 	switch (mp->b_datap->db_type) {
7461 	case M_FLUSH:
7462 		/* Turn around */
7463 		if (*mp->b_rptr & FLUSHW) {
7464 			*mp->b_rptr &= ~FLUSHR;
7465 			qreply(q, mp);
7466 			return;
7467 		}
7468 		break;
7469 	}
7470 	/* Could receive messages that passed through ar_rput */
7471 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7472 		mp1->b_prev = mp1->b_next = NULL;
7473 	freemsg(mp);
7474 }
7475 
7476 /* Nobody should be sending packets down this stream */
7477 /* ARGSUSED */
7478 void
7479 ip_lwput(queue_t *q, mblk_t *mp)
7480 {
7481 	freemsg(mp);
7482 }
7483 
7484 /*
7485  * Move the first hop in any source route to ipha_dst and remove that part of
7486  * the source route.  Called by other protocols.  Errors in option formatting
7487  * are ignored - will be handled by ip_wput_options Return the final
7488  * destination (either ipha_dst or the last entry in a source route.)
7489  */
7490 ipaddr_t
7491 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7492 {
7493 	ipoptp_t	opts;
7494 	uchar_t		*opt;
7495 	uint8_t		optval;
7496 	uint8_t		optlen;
7497 	ipaddr_t	dst;
7498 	int		i;
7499 	ire_t		*ire;
7500 	ip_stack_t	*ipst = ns->netstack_ip;
7501 
7502 	ip2dbg(("ip_massage_options\n"));
7503 	dst = ipha->ipha_dst;
7504 	for (optval = ipoptp_first(&opts, ipha);
7505 	    optval != IPOPT_EOL;
7506 	    optval = ipoptp_next(&opts)) {
7507 		opt = opts.ipoptp_cur;
7508 		switch (optval) {
7509 			uint8_t off;
7510 		case IPOPT_SSRR:
7511 		case IPOPT_LSRR:
7512 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7513 				ip1dbg(("ip_massage_options: bad src route\n"));
7514 				break;
7515 			}
7516 			optlen = opts.ipoptp_len;
7517 			off = opt[IPOPT_OFFSET];
7518 			off--;
7519 		redo_srr:
7520 			if (optlen < IP_ADDR_LEN ||
7521 			    off > optlen - IP_ADDR_LEN) {
7522 				/* End of source route */
7523 				ip1dbg(("ip_massage_options: end of SR\n"));
7524 				break;
7525 			}
7526 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7527 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7528 			    ntohl(dst)));
7529 			/*
7530 			 * Check if our address is present more than
7531 			 * once as consecutive hops in source route.
7532 			 * XXX verify per-interface ip_forwarding
7533 			 * for source route?
7534 			 */
7535 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7536 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7537 			if (ire != NULL) {
7538 				ire_refrele(ire);
7539 				off += IP_ADDR_LEN;
7540 				goto redo_srr;
7541 			}
7542 			if (dst == htonl(INADDR_LOOPBACK)) {
7543 				ip1dbg(("ip_massage_options: loopback addr in "
7544 				    "source route!\n"));
7545 				break;
7546 			}
7547 			/*
7548 			 * Update ipha_dst to be the first hop and remove the
7549 			 * first hop from the source route (by overwriting
7550 			 * part of the option with NOP options).
7551 			 */
7552 			ipha->ipha_dst = dst;
7553 			/* Put the last entry in dst */
7554 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7555 			    3;
7556 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7557 
7558 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7559 			    ntohl(dst)));
7560 			/* Move down and overwrite */
7561 			opt[IP_ADDR_LEN] = opt[0];
7562 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7563 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7564 			for (i = 0; i < IP_ADDR_LEN; i++)
7565 				opt[i] = IPOPT_NOP;
7566 			break;
7567 		}
7568 	}
7569 	return (dst);
7570 }
7571 
7572 /*
7573  * This function's job is to forward data to the reverse tunnel (FA->HA)
7574  * after doing a few checks. It is assumed that the incoming interface
7575  * of the packet is always different than the outgoing interface and the
7576  * ire_type of the found ire has to be a non-resolver type.
7577  *
7578  * IPQoS notes
7579  * IP policy is invoked twice for a forwarded packet, once on the read side
7580  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7581  * enabled.
7582  */
7583 static void
7584 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7585 {
7586 	ipha_t		*ipha;
7587 	queue_t		*q;
7588 	uint32_t 	pkt_len;
7589 #define	rptr    ((uchar_t *)ipha)
7590 	uint32_t 	sum;
7591 	uint32_t 	max_frag;
7592 	mblk_t		*first_mp;
7593 	uint32_t	ill_index;
7594 	ipxmit_state_t	pktxmit_state;
7595 	ill_t		*out_ill;
7596 	ip_stack_t	*ipst = in_ill->ill_ipst;
7597 
7598 	ASSERT(ire != NULL);
7599 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7600 	ASSERT(ire->ire_stq != NULL);
7601 
7602 	/* Initiate read side IPPF processing */
7603 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
7604 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7605 		ip_process(IPP_FWD_IN, &mp, ill_index);
7606 		if (mp == NULL) {
7607 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7608 			    "dropped during IPPF processing\n"));
7609 			return;
7610 		}
7611 	}
7612 
7613 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7614 		ILLF_ROUTER) == 0) ||
7615 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7616 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7617 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7618 		    "forwarding is not turned on\n"));
7619 		goto drop_pkt;
7620 	}
7621 
7622 	/*
7623 	 * Don't forward if the interface is down
7624 	 */
7625 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7626 		goto discard_pkt;
7627 	}
7628 
7629 	ipha = (ipha_t *)mp->b_rptr;
7630 	pkt_len = ntohs(ipha->ipha_length);
7631 	/* Adjust the checksum to reflect the ttl decrement. */
7632 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7633 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7634 	if (ipha->ipha_ttl-- <= 1) {
7635 		if (ip_csum_hdr(ipha)) {
7636 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7637 			goto drop_pkt;
7638 		}
7639 		q = ire->ire_stq;
7640 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7641 		    BPRI_HI)) == NULL) {
7642 			goto discard_pkt;
7643 		}
7644 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7645 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7646 		/* Sent by forwarding path, and router is global zone */
7647 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7648 		    GLOBAL_ZONEID, ipst);
7649 		return;
7650 	}
7651 
7652 	/* Get the ill_index of the ILL */
7653 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7654 
7655 	/*
7656 	 * This location is chosen for the placement of the forwarding hook
7657 	 * because at this point we know that we have a path out for the
7658 	 * packet but haven't yet applied any logic (such as fragmenting)
7659 	 * that happen as part of transmitting the packet out.
7660 	 */
7661 	out_ill = ire->ire_ipif->ipif_ill;
7662 
7663 	DTRACE_PROBE4(ip4__forwarding__start,
7664 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7665 
7666 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
7667 	    ipst->ips_ipv4firewall_forwarding,
7668 	    in_ill, out_ill, ipha, mp, mp, ipst);
7669 
7670 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7671 
7672 	if (mp == NULL)
7673 		return;
7674 	pkt_len = ntohs(ipha->ipha_length);
7675 
7676 	/*
7677 	 * ip_mrtun_forward is only used by foreign agent to reverse
7678 	 * tunnel the incoming packet. So it does not do any option
7679 	 * processing for source routing.
7680 	 */
7681 	max_frag = ire->ire_max_frag;
7682 	if (pkt_len > max_frag) {
7683 		/*
7684 		 * It needs fragging on its way out.  We haven't
7685 		 * verified the header checksum yet.  Since we
7686 		 * are going to put a surely good checksum in the
7687 		 * outgoing header, we have to make sure that it
7688 		 * was good coming in.
7689 		 */
7690 		if (ip_csum_hdr(ipha)) {
7691 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7692 			goto drop_pkt;
7693 		}
7694 
7695 		/* Initiate write side IPPF processing */
7696 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
7697 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7698 			if (mp == NULL) {
7699 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7700 				    "dropped/deferred during ip policy "\
7701 				    "processing\n"));
7702 				return;
7703 			}
7704 		}
7705 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7706 		    BPRI_HI)) == NULL) {
7707 			goto discard_pkt;
7708 		}
7709 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7710 		mp = first_mp;
7711 
7712 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
7713 		return;
7714 	}
7715 
7716 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7717 
7718 	ASSERT(ire->ire_ipif != NULL);
7719 
7720 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7721 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7722 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
7723 	    ipst->ips_ipv4firewall_physical_out,
7724 	    NULL, out_ill, ipha, mp, mp, ipst);
7725 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7726 	if (mp == NULL)
7727 		return;
7728 
7729 	/* Now send the packet to the tunnel interface */
7730 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7731 	q = ire->ire_stq;
7732 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7733 	if ((pktxmit_state == SEND_FAILED) ||
7734 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7735 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7736 		    q->q_ptr));
7737 	}
7738 
7739 	return;
7740 discard_pkt:
7741 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7742 drop_pkt:;
7743 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7744 	freemsg(mp);
7745 #undef	rptr
7746 }
7747 
7748 /*
7749  * Fills the ipsec_out_t data structure with appropriate fields and
7750  * prepends it to mp which contains the IP hdr + data that was meant
7751  * to be forwarded. Please note that ipsec_out_info data structure
7752  * is used here to communicate the outgoing ill path at ip_wput()
7753  * for the ICMP error packet. This has nothing to do with ipsec IP
7754  * security. ipsec_out_t is really used to pass the info to the module
7755  * IP where this information cannot be extracted from conn.
7756  * This functions is called by ip_mrtun_forward().
7757  */
7758 void
7759 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7760 {
7761 	ipsec_out_t	*io;
7762 
7763 	ASSERT(xmit_ill != NULL);
7764 	first_mp->b_datap->db_type = M_CTL;
7765 	first_mp->b_wptr += sizeof (ipsec_info_t);
7766 	/*
7767 	 * This is to pass info to ip_wput in absence of conn.
7768 	 * ipsec_out_secure will be B_FALSE because of this.
7769 	 * Thus ipsec_out_secure being B_FALSE indicates that
7770 	 * this is not IPSEC security related information.
7771 	 */
7772 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7773 	io = (ipsec_out_t *)first_mp->b_rptr;
7774 	io->ipsec_out_type = IPSEC_OUT;
7775 	io->ipsec_out_len = sizeof (ipsec_out_t);
7776 	first_mp->b_cont = mp;
7777 	io->ipsec_out_ill_index =
7778 	    xmit_ill->ill_phyint->phyint_ifindex;
7779 	io->ipsec_out_xmit_if = B_TRUE;
7780 	io->ipsec_out_ns = xmit_ill->ill_ipst->ips_netstack;
7781 }
7782 
7783 /*
7784  * Return the network mask
7785  * associated with the specified address.
7786  */
7787 ipaddr_t
7788 ip_net_mask(ipaddr_t addr)
7789 {
7790 	uchar_t	*up = (uchar_t *)&addr;
7791 	ipaddr_t mask = 0;
7792 	uchar_t	*maskp = (uchar_t *)&mask;
7793 
7794 #if defined(__i386) || defined(__amd64)
7795 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7796 #endif
7797 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7798 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7799 #endif
7800 	if (CLASSD(addr)) {
7801 		maskp[0] = 0xF0;
7802 		return (mask);
7803 	}
7804 	if (addr == 0)
7805 		return (0);
7806 	maskp[0] = 0xFF;
7807 	if ((up[0] & 0x80) == 0)
7808 		return (mask);
7809 
7810 	maskp[1] = 0xFF;
7811 	if ((up[0] & 0xC0) == 0x80)
7812 		return (mask);
7813 
7814 	maskp[2] = 0xFF;
7815 	if ((up[0] & 0xE0) == 0xC0)
7816 		return (mask);
7817 
7818 	/* Must be experimental or multicast, indicate as much */
7819 	return ((ipaddr_t)0);
7820 }
7821 
7822 /*
7823  * Select an ill for the packet by considering load spreading across
7824  * a different ill in the group if dst_ill is part of some group.
7825  */
7826 ill_t *
7827 ip_newroute_get_dst_ill(ill_t *dst_ill)
7828 {
7829 	ill_t *ill;
7830 
7831 	/*
7832 	 * We schedule irrespective of whether the source address is
7833 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7834 	 */
7835 	ill = illgrp_scheduler(dst_ill);
7836 	if (ill == NULL)
7837 		return (NULL);
7838 
7839 	/*
7840 	 * For groups with names ip_sioctl_groupname ensures that all
7841 	 * ills are of same type. For groups without names, ifgrp_insert
7842 	 * ensures this.
7843 	 */
7844 	ASSERT(dst_ill->ill_type == ill->ill_type);
7845 
7846 	return (ill);
7847 }
7848 
7849 /*
7850  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7851  */
7852 ill_t *
7853 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7854     ip_stack_t *ipst)
7855 {
7856 	ill_t *ret_ill;
7857 
7858 	ASSERT(ifindex != 0);
7859 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7860 	    ipst);
7861 	if (ret_ill == NULL ||
7862 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7863 		if (isv6) {
7864 			if (ill != NULL) {
7865 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7866 			} else {
7867 				BUMP_MIB(&ipst->ips_ip6_mib,
7868 				    ipIfStatsOutDiscards);
7869 			}
7870 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7871 			    "bad ifindex %d.\n", ifindex));
7872 		} else {
7873 			if (ill != NULL) {
7874 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7875 			} else {
7876 				BUMP_MIB(&ipst->ips_ip_mib,
7877 				    ipIfStatsOutDiscards);
7878 			}
7879 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7880 			    "bad ifindex %d.\n", ifindex));
7881 		}
7882 		if (ret_ill != NULL)
7883 			ill_refrele(ret_ill);
7884 		freemsg(first_mp);
7885 		return (NULL);
7886 	}
7887 
7888 	return (ret_ill);
7889 }
7890 
7891 /*
7892  * IPv4 -
7893  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7894  * out a packet to a destination address for which we do not have specific
7895  * (or sufficient) routing information.
7896  *
7897  * NOTE : These are the scopes of some of the variables that point at IRE,
7898  *	  which needs to be followed while making any future modifications
7899  *	  to avoid memory leaks.
7900  *
7901  *	- ire and sire are the entries looked up initially by
7902  *	  ire_ftable_lookup.
7903  *	- ipif_ire is used to hold the interface ire associated with
7904  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7905  *	  it before branching out to error paths.
7906  *	- save_ire is initialized before ire_create, so that ire returned
7907  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7908  *	  before breaking out of the switch.
7909  *
7910  *	Thus on failures, we have to REFRELE only ire and sire, if they
7911  *	are not NULL.
7912  */
7913 void
7914 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7915     zoneid_t zoneid, ip_stack_t *ipst)
7916 {
7917 	areq_t	*areq;
7918 	ipaddr_t gw = 0;
7919 	ire_t	*ire = NULL;
7920 	mblk_t	*res_mp;
7921 	ipaddr_t *addrp;
7922 	ipaddr_t nexthop_addr;
7923 	ipif_t  *src_ipif = NULL;
7924 	ill_t	*dst_ill = NULL;
7925 	ipha_t  *ipha;
7926 	ire_t	*sire = NULL;
7927 	mblk_t	*first_mp;
7928 	ire_t	*save_ire;
7929 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7930 	ushort_t ire_marks = 0;
7931 	boolean_t mctl_present;
7932 	ipsec_out_t *io;
7933 	mblk_t	*saved_mp;
7934 	ire_t	*first_sire = NULL;
7935 	mblk_t	*copy_mp = NULL;
7936 	mblk_t	*xmit_mp = NULL;
7937 	ipaddr_t save_dst;
7938 	uint32_t multirt_flags =
7939 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7940 	boolean_t multirt_is_resolvable;
7941 	boolean_t multirt_resolve_next;
7942 	boolean_t do_attach_ill = B_FALSE;
7943 	boolean_t ip_nexthop = B_FALSE;
7944 	tsol_ire_gw_secattr_t *attrp = NULL;
7945 	tsol_gcgrp_t *gcgrp = NULL;
7946 	tsol_gcgrp_addr_t ga;
7947 
7948 	if (ip_debug > 2) {
7949 		/* ip1dbg */
7950 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7951 	}
7952 
7953 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7954 	if (mctl_present) {
7955 		io = (ipsec_out_t *)first_mp->b_rptr;
7956 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7957 		ASSERT(zoneid == io->ipsec_out_zoneid);
7958 		ASSERT(zoneid != ALL_ZONES);
7959 	}
7960 
7961 	ipha = (ipha_t *)mp->b_rptr;
7962 
7963 	/* All multicast lookups come through ip_newroute_ipif() */
7964 	if (CLASSD(dst)) {
7965 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7966 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7967 		freemsg(first_mp);
7968 		return;
7969 	}
7970 
7971 	if (mctl_present && io->ipsec_out_attach_if) {
7972 		/* ip_grab_attach_ill returns a held ill */
7973 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7974 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7975 
7976 		/* Failure case frees things for us. */
7977 		if (attach_ill == NULL)
7978 			return;
7979 
7980 		/*
7981 		 * Check if we need an ire that will not be
7982 		 * looked up by anybody else i.e. HIDDEN.
7983 		 */
7984 		if (ill_is_probeonly(attach_ill))
7985 			ire_marks = IRE_MARK_HIDDEN;
7986 	}
7987 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7988 		ip_nexthop = B_TRUE;
7989 		nexthop_addr = io->ipsec_out_nexthop_addr;
7990 	}
7991 	/*
7992 	 * If this IRE is created for forwarding or it is not for
7993 	 * traffic for congestion controlled protocols, mark it as temporary.
7994 	 */
7995 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7996 		ire_marks |= IRE_MARK_TEMPORARY;
7997 
7998 	/*
7999 	 * Get what we can from ire_ftable_lookup which will follow an IRE
8000 	 * chain until it gets the most specific information available.
8001 	 * For example, we know that there is no IRE_CACHE for this dest,
8002 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
8003 	 * ire_ftable_lookup will look up the gateway, etc.
8004 	 * Check if in_ill != NULL. If it is true, the packet must be
8005 	 * from an incoming interface where RTA_SRCIFP is set.
8006 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
8007 	 * to the destination, of equal netmask length in the forward table,
8008 	 * will be recursively explored. If no information is available
8009 	 * for the final gateway of that route, we force the returned ire
8010 	 * to be equal to sire using MATCH_IRE_PARENT.
8011 	 * At least, in this case we have a starting point (in the buckets)
8012 	 * to look for other routes to the destination in the forward table.
8013 	 * This is actually used only for multirouting, where a list
8014 	 * of routes has to be processed in sequence.
8015 	 *
8016 	 * In the process of coming up with the most specific information,
8017 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8018 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8019 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8020 	 * Two caveats when handling incomplete ire's in ip_newroute:
8021 	 * - we should be careful when accessing its ire_nce (specifically
8022 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8023 	 * - not all legacy code path callers are prepared to handle
8024 	 *   incomplete ire's, so we should not create/add incomplete
8025 	 *   ire_cache entries here. (See discussion about temporary solution
8026 	 *   further below).
8027 	 *
8028 	 * In order to minimize packet dropping, and to preserve existing
8029 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8030 	 * gateway, and instead use the IF_RESOLVER ire to send out
8031 	 * another request to ARP (this is achieved by passing the
8032 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8033 	 * arp response comes back in ip_wput_nondata, we will create
8034 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8035 	 *
8036 	 * Note that this is a temporary solution; the correct solution is
8037 	 * to create an incomplete  per-dst ire_cache entry, and send the
8038 	 * packet out when the gw's nce is resolved. In order to achieve this,
8039 	 * all packet processing must have been completed prior to calling
8040 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8041 	 * to be modified to accomodate this solution.
8042 	 */
8043 	if (in_ill != NULL) {
8044 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
8045 		    in_ill, MATCH_IRE_TYPE);
8046 	} else if (ip_nexthop) {
8047 		/*
8048 		 * The first time we come here, we look for an IRE_INTERFACE
8049 		 * entry for the specified nexthop, set the dst to be the
8050 		 * nexthop address and create an IRE_CACHE entry for the
8051 		 * nexthop. The next time around, we are able to find an
8052 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8053 		 * nexthop address and create an IRE_CACHE entry for the
8054 		 * destination address via the specified nexthop.
8055 		 */
8056 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8057 		    MBLK_GETLABEL(mp), ipst);
8058 		if (ire != NULL) {
8059 			gw = nexthop_addr;
8060 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8061 		} else {
8062 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8063 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8064 			    MBLK_GETLABEL(mp),
8065 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8066 			    ipst);
8067 			if (ire != NULL) {
8068 				dst = nexthop_addr;
8069 			}
8070 		}
8071 	} else if (attach_ill == NULL) {
8072 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8073 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8074 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8075 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8076 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8077 		    ipst);
8078 	} else {
8079 		/*
8080 		 * attach_ill is set only for communicating with
8081 		 * on-link hosts. So, don't look for DEFAULT.
8082 		 */
8083 		ipif_t	*attach_ipif;
8084 
8085 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8086 		if (attach_ipif == NULL) {
8087 			ill_refrele(attach_ill);
8088 			goto icmp_err_ret;
8089 		}
8090 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8091 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8092 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8093 		    MATCH_IRE_SECATTR, ipst);
8094 		ipif_refrele(attach_ipif);
8095 	}
8096 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8097 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8098 
8099 	/*
8100 	 * This loop is run only once in most cases.
8101 	 * We loop to resolve further routes only when the destination
8102 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8103 	 */
8104 	do {
8105 		/* Clear the previous iteration's values */
8106 		if (src_ipif != NULL) {
8107 			ipif_refrele(src_ipif);
8108 			src_ipif = NULL;
8109 		}
8110 		if (dst_ill != NULL) {
8111 			ill_refrele(dst_ill);
8112 			dst_ill = NULL;
8113 		}
8114 
8115 		multirt_resolve_next = B_FALSE;
8116 		/*
8117 		 * We check if packets have to be multirouted.
8118 		 * In this case, given the current <ire, sire> couple,
8119 		 * we look for the next suitable <ire, sire>.
8120 		 * This check is done in ire_multirt_lookup(),
8121 		 * which applies various criteria to find the next route
8122 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8123 		 * unchanged if it detects it has not been tried yet.
8124 		 */
8125 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8126 			ip3dbg(("ip_newroute: starting next_resolution "
8127 			    "with first_mp %p, tag %d\n",
8128 			    (void *)first_mp,
8129 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8130 
8131 			ASSERT(sire != NULL);
8132 			multirt_is_resolvable =
8133 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8134 				MBLK_GETLABEL(mp), ipst);
8135 
8136 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8137 			    "ire %p, sire %p\n",
8138 			    multirt_is_resolvable,
8139 			    (void *)ire, (void *)sire));
8140 
8141 			if (!multirt_is_resolvable) {
8142 				/*
8143 				 * No more multirt route to resolve; give up
8144 				 * (all routes resolved or no more
8145 				 * resolvable routes).
8146 				 */
8147 				if (ire != NULL) {
8148 					ire_refrele(ire);
8149 					ire = NULL;
8150 				}
8151 			} else {
8152 				ASSERT(sire != NULL);
8153 				ASSERT(ire != NULL);
8154 				/*
8155 				 * We simply use first_sire as a flag that
8156 				 * indicates if a resolvable multirt route
8157 				 * has already been found.
8158 				 * If it is not the case, we may have to send
8159 				 * an ICMP error to report that the
8160 				 * destination is unreachable.
8161 				 * We do not IRE_REFHOLD first_sire.
8162 				 */
8163 				if (first_sire == NULL) {
8164 					first_sire = sire;
8165 				}
8166 			}
8167 		}
8168 		if (ire == NULL) {
8169 			if (ip_debug > 3) {
8170 				/* ip2dbg */
8171 				pr_addr_dbg("ip_newroute: "
8172 				    "can't resolve %s\n", AF_INET, &dst);
8173 			}
8174 			ip3dbg(("ip_newroute: "
8175 			    "ire %p, sire %p, first_sire %p\n",
8176 			    (void *)ire, (void *)sire, (void *)first_sire));
8177 
8178 			if (sire != NULL) {
8179 				ire_refrele(sire);
8180 				sire = NULL;
8181 			}
8182 
8183 			if (first_sire != NULL) {
8184 				/*
8185 				 * At least one multirt route has been found
8186 				 * in the same call to ip_newroute();
8187 				 * there is no need to report an ICMP error.
8188 				 * first_sire was not IRE_REFHOLDed.
8189 				 */
8190 				MULTIRT_DEBUG_UNTAG(first_mp);
8191 				freemsg(first_mp);
8192 				return;
8193 			}
8194 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8195 			    RTA_DST, ipst);
8196 			if (attach_ill != NULL)
8197 				ill_refrele(attach_ill);
8198 			goto icmp_err_ret;
8199 		}
8200 
8201 		/*
8202 		 * When RTA_SRCIFP is used to add a route, then an interface
8203 		 * route is added in the source interface's routing table.
8204 		 * If the outgoing interface of this route is of type
8205 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8206 		 * ire_nce->nce_res_mp is set to NULL.
8207 		 * Later, when this route is first used for forwarding
8208 		 * a packet, ip_newroute() is called
8209 		 * to resolve the hardware address of the outgoing ipif.
8210 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8211 		 * source interface based table. We only come here if the
8212 		 * outgoing interface is a resolver interface and we don't
8213 		 * have the ire_nce->nce_res_mp information yet.
8214 		 * If in_ill is not null that means it is called from
8215 		 * ip_rput.
8216 		 */
8217 
8218 		ASSERT(ire->ire_in_ill == NULL ||
8219 		    (ire->ire_type == IRE_IF_RESOLVER &&
8220 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8221 
8222 		/*
8223 		 * Verify that the returned IRE does not have either
8224 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8225 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8226 		 */
8227 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8228 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8229 			if (attach_ill != NULL)
8230 				ill_refrele(attach_ill);
8231 			goto icmp_err_ret;
8232 		}
8233 		/*
8234 		 * Increment the ire_ob_pkt_count field for ire if it is an
8235 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8236 		 * increment the same for the parent IRE, sire, if it is some
8237 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
8238 		 * and HOST_REDIRECT).
8239 		 */
8240 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8241 			UPDATE_OB_PKT_COUNT(ire);
8242 			ire->ire_last_used_time = lbolt;
8243 		}
8244 
8245 		if (sire != NULL) {
8246 			gw = sire->ire_gateway_addr;
8247 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8248 			    IRE_INTERFACE)) == 0);
8249 			UPDATE_OB_PKT_COUNT(sire);
8250 			sire->ire_last_used_time = lbolt;
8251 		}
8252 		/*
8253 		 * We have a route to reach the destination.
8254 		 *
8255 		 * 1) If the interface is part of ill group, try to get a new
8256 		 *    ill taking load spreading into account.
8257 		 *
8258 		 * 2) After selecting the ill, get a source address that
8259 		 *    might create good inbound load spreading.
8260 		 *    ipif_select_source does this for us.
8261 		 *
8262 		 * If the application specified the ill (ifindex), we still
8263 		 * load spread. Only if the packets needs to go out
8264 		 * specifically on a given ill e.g. binding to
8265 		 * IPIF_NOFAILOVER address, then we don't try to use a
8266 		 * different ill for load spreading.
8267 		 */
8268 		if (attach_ill == NULL) {
8269 			/*
8270 			 * Don't perform outbound load spreading in the
8271 			 * case of an RTF_MULTIRT route, as we actually
8272 			 * typically want to replicate outgoing packets
8273 			 * through particular interfaces.
8274 			 */
8275 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8276 				dst_ill = ire->ire_ipif->ipif_ill;
8277 				/* for uniformity */
8278 				ill_refhold(dst_ill);
8279 			} else {
8280 				/*
8281 				 * If we are here trying to create an IRE_CACHE
8282 				 * for an offlink destination and have the
8283 				 * IRE_CACHE for the next hop and the latter is
8284 				 * using virtual IP source address selection i.e
8285 				 * it's ire->ire_ipif is pointing to a virtual
8286 				 * network interface (vni) then
8287 				 * ip_newroute_get_dst_ll() will return the vni
8288 				 * interface as the dst_ill. Since the vni is
8289 				 * virtual i.e not associated with any physical
8290 				 * interface, it cannot be the dst_ill, hence
8291 				 * in such a case call ip_newroute_get_dst_ll()
8292 				 * with the stq_ill instead of the ire_ipif ILL.
8293 				 * The function returns a refheld ill.
8294 				 */
8295 				if ((ire->ire_type == IRE_CACHE) &&
8296 				    IS_VNI(ire->ire_ipif->ipif_ill))
8297 					dst_ill = ip_newroute_get_dst_ill(
8298 						ire->ire_stq->q_ptr);
8299 				else
8300 					dst_ill = ip_newroute_get_dst_ill(
8301 						ire->ire_ipif->ipif_ill);
8302 			}
8303 			if (dst_ill == NULL) {
8304 				if (ip_debug > 2) {
8305 					pr_addr_dbg("ip_newroute: "
8306 					    "no dst ill for dst"
8307 					    " %s\n", AF_INET, &dst);
8308 				}
8309 				goto icmp_err_ret;
8310 			}
8311 		} else {
8312 			dst_ill = ire->ire_ipif->ipif_ill;
8313 			/* for uniformity */
8314 			ill_refhold(dst_ill);
8315 			/*
8316 			 * We should have found a route matching ill as we
8317 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8318 			 * Rather than asserting, when there is a mismatch,
8319 			 * we just drop the packet.
8320 			 */
8321 			if (dst_ill != attach_ill) {
8322 				ip0dbg(("ip_newroute: Packet dropped as "
8323 				    "IPIF_NOFAILOVER ill is %s, "
8324 				    "ire->ire_ipif->ipif_ill is %s\n",
8325 				    attach_ill->ill_name,
8326 				    dst_ill->ill_name));
8327 				ill_refrele(attach_ill);
8328 				goto icmp_err_ret;
8329 			}
8330 		}
8331 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8332 		if (attach_ill != NULL) {
8333 			ill_refrele(attach_ill);
8334 			attach_ill = NULL;
8335 			do_attach_ill = B_TRUE;
8336 		}
8337 		ASSERT(dst_ill != NULL);
8338 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8339 
8340 		/*
8341 		 * Pick the best source address from dst_ill.
8342 		 *
8343 		 * 1) If it is part of a multipathing group, we would
8344 		 *    like to spread the inbound packets across different
8345 		 *    interfaces. ipif_select_source picks a random source
8346 		 *    across the different ills in the group.
8347 		 *
8348 		 * 2) If it is not part of a multipathing group, we try
8349 		 *    to pick the source address from the destination
8350 		 *    route. Clustering assumes that when we have multiple
8351 		 *    prefixes hosted on an interface, the prefix of the
8352 		 *    source address matches the prefix of the destination
8353 		 *    route. We do this only if the address is not
8354 		 *    DEPRECATED.
8355 		 *
8356 		 * 3) If the conn is in a different zone than the ire, we
8357 		 *    need to pick a source address from the right zone.
8358 		 *
8359 		 * NOTE : If we hit case (1) above, the prefix of the source
8360 		 *	  address picked may not match the prefix of the
8361 		 *	  destination routes prefix as ipif_select_source
8362 		 *	  does not look at "dst" while picking a source
8363 		 *	  address.
8364 		 *	  If we want the same behavior as (2), we will need
8365 		 *	  to change the behavior of ipif_select_source.
8366 		 */
8367 		ASSERT(src_ipif == NULL);
8368 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8369 			/*
8370 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8371 			 * Check that the ipif matching the requested source
8372 			 * address still exists.
8373 			 */
8374 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8375 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8376 		}
8377 		if (src_ipif == NULL) {
8378 			ire_marks |= IRE_MARK_USESRC_CHECK;
8379 			if ((dst_ill->ill_group != NULL) ||
8380 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8381 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8382 			    ire->ire_zoneid != ALL_ZONES) ||
8383 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8384 				/*
8385 				 * If the destination is reachable via a
8386 				 * given gateway, the selected source address
8387 				 * should be in the same subnet as the gateway.
8388 				 * Otherwise, the destination is not reachable.
8389 				 *
8390 				 * If there are no interfaces on the same subnet
8391 				 * as the destination, ipif_select_source gives
8392 				 * first non-deprecated interface which might be
8393 				 * on a different subnet than the gateway.
8394 				 * This is not desirable. Hence pass the dst_ire
8395 				 * source address to ipif_select_source.
8396 				 * It is sure that the destination is reachable
8397 				 * with the dst_ire source address subnet.
8398 				 * So passing dst_ire source address to
8399 				 * ipif_select_source will make sure that the
8400 				 * selected source will be on the same subnet
8401 				 * as dst_ire source address.
8402 				 */
8403 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8404 				src_ipif = ipif_select_source(dst_ill, saddr,
8405 				    zoneid);
8406 				if (src_ipif == NULL) {
8407 					if (ip_debug > 2) {
8408 						pr_addr_dbg("ip_newroute: "
8409 						    "no src for dst %s ",
8410 						    AF_INET, &dst);
8411 						printf("through interface %s\n",
8412 						    dst_ill->ill_name);
8413 					}
8414 					goto icmp_err_ret;
8415 				}
8416 			} else {
8417 				src_ipif = ire->ire_ipif;
8418 				ASSERT(src_ipif != NULL);
8419 				/* hold src_ipif for uniformity */
8420 				ipif_refhold(src_ipif);
8421 			}
8422 		}
8423 
8424 		/*
8425 		 * Assign a source address while we have the conn.
8426 		 * We can't have ip_wput_ire pick a source address when the
8427 		 * packet returns from arp since we need to look at
8428 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8429 		 * going through arp.
8430 		 *
8431 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8432 		 *	  it uses ip6i to store this information.
8433 		 */
8434 		if (ipha->ipha_src == INADDR_ANY &&
8435 		    (connp == NULL || !connp->conn_unspec_src)) {
8436 			ipha->ipha_src = src_ipif->ipif_src_addr;
8437 		}
8438 		if (ip_debug > 3) {
8439 			/* ip2dbg */
8440 			pr_addr_dbg("ip_newroute: first hop %s\n",
8441 			    AF_INET, &gw);
8442 		}
8443 		ip2dbg(("\tire type %s (%d)\n",
8444 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8445 
8446 		/*
8447 		 * The TTL of multirouted packets is bounded by the
8448 		 * ip_multirt_ttl ndd variable.
8449 		 */
8450 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8451 			/* Force TTL of multirouted packets */
8452 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8453 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8454 				ip2dbg(("ip_newroute: forcing multirt TTL "
8455 				    "to %d (was %d), dst 0x%08x\n",
8456 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8457 				    ntohl(sire->ire_addr)));
8458 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8459 			}
8460 		}
8461 		/*
8462 		 * At this point in ip_newroute(), ire is either the
8463 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8464 		 * destination or an IRE_INTERFACE type that should be used
8465 		 * to resolve an on-subnet destination or an on-subnet
8466 		 * next-hop gateway.
8467 		 *
8468 		 * In the IRE_CACHE case, we have the following :
8469 		 *
8470 		 * 1) src_ipif - used for getting a source address.
8471 		 *
8472 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8473 		 *    means packets using this IRE_CACHE will go out on
8474 		 *    dst_ill.
8475 		 *
8476 		 * 3) The IRE sire will point to the prefix that is the
8477 		 *    longest  matching route for the destination. These
8478 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8479 		 *
8480 		 *    The newly created IRE_CACHE entry for the off-subnet
8481 		 *    destination is tied to both the prefix route and the
8482 		 *    interface route used to resolve the next-hop gateway
8483 		 *    via the ire_phandle and ire_ihandle fields,
8484 		 *    respectively.
8485 		 *
8486 		 * In the IRE_INTERFACE 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 the IRE_CACHE that we will build
8492 		 *    here will go out on dst_ill.
8493 		 *
8494 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8495 		 *    to be created will only be tied to the IRE_INTERFACE
8496 		 *    that was derived from the ire_ihandle field.
8497 		 *
8498 		 *    If sire is non-NULL, it means the destination is
8499 		 *    off-link and we will first create the IRE_CACHE for the
8500 		 *    gateway. Next time through ip_newroute, we will create
8501 		 *    the IRE_CACHE for the final destination as described
8502 		 *    above.
8503 		 *
8504 		 * In both cases, after the current resolution has been
8505 		 * completed (or possibly initialised, in the IRE_INTERFACE
8506 		 * case), the loop may be re-entered to attempt the resolution
8507 		 * of another RTF_MULTIRT route.
8508 		 *
8509 		 * When an IRE_CACHE entry for the off-subnet destination is
8510 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8511 		 * for further processing in emission loops.
8512 		 */
8513 		save_ire = ire;
8514 		switch (ire->ire_type) {
8515 		case IRE_CACHE: {
8516 			ire_t	*ipif_ire;
8517 			mblk_t	*ire_fp_mp;
8518 
8519 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8520 			if (gw == 0)
8521 				gw = ire->ire_gateway_addr;
8522 			/*
8523 			 * We need 3 ire's to create a new cache ire for an
8524 			 * off-link destination from the cache ire of the
8525 			 * gateway.
8526 			 *
8527 			 *	1. The prefix ire 'sire' (Note that this does
8528 			 *	   not apply to the conn_nexthop_set case)
8529 			 *	2. The cache ire of the gateway 'ire'
8530 			 *	3. The interface ire 'ipif_ire'
8531 			 *
8532 			 * We have (1) and (2). We lookup (3) below.
8533 			 *
8534 			 * If there is no interface route to the gateway,
8535 			 * it is a race condition, where we found the cache
8536 			 * but the interface route has been deleted.
8537 			 */
8538 			if (ip_nexthop) {
8539 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8540 			} else {
8541 				ipif_ire =
8542 				    ire_ihandle_lookup_offlink(ire, sire);
8543 			}
8544 			if (ipif_ire == NULL) {
8545 				ip1dbg(("ip_newroute: "
8546 				    "ire_ihandle_lookup_offlink failed\n"));
8547 				goto icmp_err_ret;
8548 			}
8549 			/*
8550 			 * XXX We are using the same res_mp
8551 			 * (DL_UNITDATA_REQ) though the save_ire is not
8552 			 * pointing at the same ill.
8553 			 * This is incorrect. We need to send it up to the
8554 			 * resolver to get the right res_mp. For ethernets
8555 			 * this may be okay (ill_type == DL_ETHER).
8556 			 */
8557 			res_mp = save_ire->ire_nce->nce_res_mp;
8558 			ire_fp_mp = NULL;
8559 			/*
8560 			 * save_ire's nce_fp_mp can't change since it is
8561 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8562 			 * LOCK_IRE_FP_MP does not do any useful work in
8563 			 * the case of IRE_CACHE. So we don't use it below.
8564 			 */
8565 			if (save_ire->ire_stq == dst_ill->ill_wq)
8566 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8567 
8568 			/*
8569 			 * Check cached gateway IRE for any security
8570 			 * attributes; if found, associate the gateway
8571 			 * credentials group to the destination IRE.
8572 			 */
8573 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8574 				mutex_enter(&attrp->igsa_lock);
8575 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8576 					GCGRP_REFHOLD(gcgrp);
8577 				mutex_exit(&attrp->igsa_lock);
8578 			}
8579 
8580 			ire = ire_create(
8581 			    (uchar_t *)&dst,		/* dest address */
8582 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8583 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8584 			    (uchar_t *)&gw,		/* gateway address */
8585 			    NULL,
8586 			    &save_ire->ire_max_frag,
8587 			    ire_fp_mp,			/* Fast Path header */
8588 			    dst_ill->ill_rq,		/* recv-from queue */
8589 			    dst_ill->ill_wq,		/* send-to queue */
8590 			    IRE_CACHE,			/* IRE type */
8591 			    res_mp,
8592 			    src_ipif,
8593 			    in_ill,			/* incoming ill */
8594 			    (sire != NULL) ?
8595 				sire->ire_mask : 0, 	/* Parent mask */
8596 			    (sire != NULL) ?
8597 				sire->ire_phandle : 0,  /* Parent handle */
8598 			    ipif_ire->ire_ihandle,	/* Interface handle */
8599 			    (sire != NULL) ? (sire->ire_flags &
8600 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8601 			    (sire != NULL) ?
8602 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8603 			    NULL,
8604 			    gcgrp,
8605 			    ipst);
8606 
8607 			if (ire == NULL) {
8608 				if (gcgrp != NULL) {
8609 					GCGRP_REFRELE(gcgrp);
8610 					gcgrp = NULL;
8611 				}
8612 				ire_refrele(ipif_ire);
8613 				ire_refrele(save_ire);
8614 				break;
8615 			}
8616 
8617 			/* reference now held by IRE */
8618 			gcgrp = NULL;
8619 
8620 			ire->ire_marks |= ire_marks;
8621 
8622 			/*
8623 			 * Prevent sire and ipif_ire from getting deleted.
8624 			 * The newly created ire is tied to both of them via
8625 			 * the phandle and ihandle respectively.
8626 			 */
8627 			if (sire != NULL) {
8628 				IRB_REFHOLD(sire->ire_bucket);
8629 				/* Has it been removed already ? */
8630 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8631 					IRB_REFRELE(sire->ire_bucket);
8632 					ire_refrele(ipif_ire);
8633 					ire_refrele(save_ire);
8634 					break;
8635 				}
8636 			}
8637 
8638 			IRB_REFHOLD(ipif_ire->ire_bucket);
8639 			/* Has it been removed already ? */
8640 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8641 				IRB_REFRELE(ipif_ire->ire_bucket);
8642 				if (sire != NULL)
8643 					IRB_REFRELE(sire->ire_bucket);
8644 				ire_refrele(ipif_ire);
8645 				ire_refrele(save_ire);
8646 				break;
8647 			}
8648 
8649 			xmit_mp = first_mp;
8650 			/*
8651 			 * In the case of multirouting, a copy
8652 			 * of the packet is done before its sending.
8653 			 * The copy is used to attempt another
8654 			 * route resolution, in a next loop.
8655 			 */
8656 			if (ire->ire_flags & RTF_MULTIRT) {
8657 				copy_mp = copymsg(first_mp);
8658 				if (copy_mp != NULL) {
8659 					xmit_mp = copy_mp;
8660 					MULTIRT_DEBUG_TAG(first_mp);
8661 				}
8662 			}
8663 			ire_add_then_send(q, ire, xmit_mp);
8664 			ire_refrele(save_ire);
8665 
8666 			/* Assert that sire is not deleted yet. */
8667 			if (sire != NULL) {
8668 				ASSERT(sire->ire_ptpn != NULL);
8669 				IRB_REFRELE(sire->ire_bucket);
8670 			}
8671 
8672 			/* Assert that ipif_ire is not deleted yet. */
8673 			ASSERT(ipif_ire->ire_ptpn != NULL);
8674 			IRB_REFRELE(ipif_ire->ire_bucket);
8675 			ire_refrele(ipif_ire);
8676 
8677 			/*
8678 			 * If copy_mp is not NULL, multirouting was
8679 			 * requested. We loop to initiate a next
8680 			 * route resolution attempt, starting from sire.
8681 			 */
8682 			if (copy_mp != NULL) {
8683 				/*
8684 				 * Search for the next unresolved
8685 				 * multirt route.
8686 				 */
8687 				copy_mp = NULL;
8688 				ipif_ire = NULL;
8689 				ire = NULL;
8690 				multirt_resolve_next = B_TRUE;
8691 				continue;
8692 			}
8693 			if (sire != NULL)
8694 				ire_refrele(sire);
8695 			ipif_refrele(src_ipif);
8696 			ill_refrele(dst_ill);
8697 			return;
8698 		}
8699 		case IRE_IF_NORESOLVER: {
8700 			/*
8701 			 * We have what we need to build an IRE_CACHE.
8702 			 *
8703 			 * Create a new res_mp with the IP gateway address
8704 			 * in destination address in the DLPI hdr if the
8705 			 * physical length is exactly 4 bytes.
8706 			 */
8707 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8708 				uchar_t *addr;
8709 
8710 				if (gw)
8711 					addr = (uchar_t *)&gw;
8712 				else
8713 					addr = (uchar_t *)&dst;
8714 
8715 				res_mp = ill_dlur_gen(addr,
8716 				    dst_ill->ill_phys_addr_length,
8717 				    dst_ill->ill_sap,
8718 				    dst_ill->ill_sap_length);
8719 
8720 				if (res_mp == NULL) {
8721 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8722 					break;
8723 				}
8724 			} else if (dst_ill->ill_resolver_mp == NULL) {
8725 				ip1dbg(("ip_newroute: dst_ill %p "
8726 				    "for IF_NORESOLV ire %p has "
8727 				    "no ill_resolver_mp\n",
8728 				    (void *)dst_ill, (void *)ire));
8729 				break;
8730 			} else {
8731 				res_mp = NULL;
8732 			}
8733 
8734 			/*
8735 			 * TSol note: We are creating the ire cache for the
8736 			 * destination 'dst'. If 'dst' is offlink, going
8737 			 * through the first hop 'gw', the security attributes
8738 			 * of 'dst' must be set to point to the gateway
8739 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8740 			 * is possible that 'dst' is a potential gateway that is
8741 			 * referenced by some route that has some security
8742 			 * attributes. Thus in the former case, we need to do a
8743 			 * gcgrp_lookup of 'gw' while in the latter case we
8744 			 * need to do gcgrp_lookup of 'dst' itself.
8745 			 */
8746 			ga.ga_af = AF_INET;
8747 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8748 			    &ga.ga_addr);
8749 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8750 
8751 			ire = ire_create(
8752 			    (uchar_t *)&dst,		/* dest address */
8753 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8754 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8755 			    (uchar_t *)&gw,		/* gateway address */
8756 			    NULL,
8757 			    &save_ire->ire_max_frag,
8758 			    NULL,			/* Fast Path header */
8759 			    dst_ill->ill_rq,		/* recv-from queue */
8760 			    dst_ill->ill_wq,		/* send-to queue */
8761 			    IRE_CACHE,
8762 			    res_mp,
8763 			    src_ipif,
8764 			    in_ill,			/* Incoming ill */
8765 			    save_ire->ire_mask,		/* Parent mask */
8766 			    (sire != NULL) ?		/* Parent handle */
8767 				sire->ire_phandle : 0,
8768 			    save_ire->ire_ihandle,	/* Interface handle */
8769 			    (sire != NULL) ? sire->ire_flags &
8770 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8771 			    &(save_ire->ire_uinfo),
8772 			    NULL,
8773 			    gcgrp,
8774 			    ipst);
8775 
8776 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8777 				freeb(res_mp);
8778 
8779 			if (ire == NULL) {
8780 				if (gcgrp != NULL) {
8781 					GCGRP_REFRELE(gcgrp);
8782 					gcgrp = NULL;
8783 				}
8784 				ire_refrele(save_ire);
8785 				break;
8786 			}
8787 
8788 			/* reference now held by IRE */
8789 			gcgrp = NULL;
8790 
8791 			ire->ire_marks |= ire_marks;
8792 
8793 			/* Prevent save_ire from getting deleted */
8794 			IRB_REFHOLD(save_ire->ire_bucket);
8795 			/* Has it been removed already ? */
8796 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8797 				IRB_REFRELE(save_ire->ire_bucket);
8798 				ire_refrele(save_ire);
8799 				break;
8800 			}
8801 
8802 			/*
8803 			 * In the case of multirouting, a copy
8804 			 * of the packet is made before it is sent.
8805 			 * The copy is used in the next
8806 			 * loop to attempt another resolution.
8807 			 */
8808 			xmit_mp = first_mp;
8809 			if ((sire != NULL) &&
8810 			    (sire->ire_flags & RTF_MULTIRT)) {
8811 				copy_mp = copymsg(first_mp);
8812 				if (copy_mp != NULL) {
8813 					xmit_mp = copy_mp;
8814 					MULTIRT_DEBUG_TAG(first_mp);
8815 				}
8816 			}
8817 			ire_add_then_send(q, ire, xmit_mp);
8818 
8819 			/* Assert that it is not deleted yet. */
8820 			ASSERT(save_ire->ire_ptpn != NULL);
8821 			IRB_REFRELE(save_ire->ire_bucket);
8822 			ire_refrele(save_ire);
8823 
8824 			if (copy_mp != NULL) {
8825 				/*
8826 				 * If we found a (no)resolver, we ignore any
8827 				 * trailing top priority IRE_CACHE in further
8828 				 * loops. This ensures that we do not omit any
8829 				 * (no)resolver.
8830 				 * This IRE_CACHE, if any, will be processed
8831 				 * by another thread entering ip_newroute().
8832 				 * IRE_CACHE entries, if any, will be processed
8833 				 * by another thread entering ip_newroute(),
8834 				 * (upon resolver response, for instance).
8835 				 * This aims to force parallel multirt
8836 				 * resolutions as soon as a packet must be sent.
8837 				 * In the best case, after the tx of only one
8838 				 * packet, all reachable routes are resolved.
8839 				 * Otherwise, the resolution of all RTF_MULTIRT
8840 				 * routes would require several emissions.
8841 				 */
8842 				multirt_flags &= ~MULTIRT_CACHEGW;
8843 
8844 				/*
8845 				 * Search for the next unresolved multirt
8846 				 * route.
8847 				 */
8848 				copy_mp = NULL;
8849 				save_ire = NULL;
8850 				ire = NULL;
8851 				multirt_resolve_next = B_TRUE;
8852 				continue;
8853 			}
8854 
8855 			/*
8856 			 * Don't need sire anymore
8857 			 */
8858 			if (sire != NULL)
8859 				ire_refrele(sire);
8860 
8861 			ipif_refrele(src_ipif);
8862 			ill_refrele(dst_ill);
8863 			return;
8864 		}
8865 		case IRE_IF_RESOLVER:
8866 			/*
8867 			 * We can't build an IRE_CACHE yet, but at least we
8868 			 * found a resolver that can help.
8869 			 */
8870 			res_mp = dst_ill->ill_resolver_mp;
8871 			if (!OK_RESOLVER_MP(res_mp))
8872 				break;
8873 
8874 			/*
8875 			 * To be at this point in the code with a non-zero gw
8876 			 * means that dst is reachable through a gateway that
8877 			 * we have never resolved.  By changing dst to the gw
8878 			 * addr we resolve the gateway first.
8879 			 * When ire_add_then_send() tries to put the IP dg
8880 			 * to dst, it will reenter ip_newroute() at which
8881 			 * time we will find the IRE_CACHE for the gw and
8882 			 * create another IRE_CACHE in case IRE_CACHE above.
8883 			 */
8884 			if (gw != INADDR_ANY) {
8885 				/*
8886 				 * The source ipif that was determined above was
8887 				 * relative to the destination address, not the
8888 				 * gateway's. If src_ipif was not taken out of
8889 				 * the IRE_IF_RESOLVER entry, we'll need to call
8890 				 * ipif_select_source() again.
8891 				 */
8892 				if (src_ipif != ire->ire_ipif) {
8893 					ipif_refrele(src_ipif);
8894 					src_ipif = ipif_select_source(dst_ill,
8895 					    gw, zoneid);
8896 					if (src_ipif == NULL) {
8897 						if (ip_debug > 2) {
8898 							pr_addr_dbg(
8899 							    "ip_newroute: no "
8900 							    "src for gw %s ",
8901 							    AF_INET, &gw);
8902 							printf("through "
8903 							    "interface %s\n",
8904 							    dst_ill->ill_name);
8905 						}
8906 						goto icmp_err_ret;
8907 					}
8908 				}
8909 				save_dst = dst;
8910 				dst = gw;
8911 				gw = INADDR_ANY;
8912 			}
8913 
8914 			/*
8915 			 * We obtain a partial IRE_CACHE which we will pass
8916 			 * along with the resolver query.  When the response
8917 			 * comes back it will be there ready for us to add.
8918 			 * The ire_max_frag is atomically set under the
8919 			 * irebucket lock in ire_add_v[46].
8920 			 */
8921 
8922 			ire = ire_create_mp(
8923 			    (uchar_t *)&dst,		/* dest address */
8924 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8925 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8926 			    (uchar_t *)&gw,		/* gateway address */
8927 			    NULL,			/* no in_src_addr */
8928 			    NULL,			/* ire_max_frag */
8929 			    NULL,			/* Fast Path header */
8930 			    dst_ill->ill_rq,		/* recv-from queue */
8931 			    dst_ill->ill_wq,		/* send-to queue */
8932 			    IRE_CACHE,
8933 			    NULL,
8934 			    src_ipif,			/* Interface ipif */
8935 			    in_ill,			/* Incoming ILL */
8936 			    save_ire->ire_mask,		/* Parent mask */
8937 			    0,
8938 			    save_ire->ire_ihandle,	/* Interface handle */
8939 			    0,				/* flags if any */
8940 			    &(save_ire->ire_uinfo),
8941 			    NULL,
8942 			    NULL,
8943 			    ipst);
8944 
8945 			if (ire == NULL) {
8946 				ire_refrele(save_ire);
8947 				break;
8948 			}
8949 
8950 			if ((sire != NULL) &&
8951 			    (sire->ire_flags & RTF_MULTIRT)) {
8952 				copy_mp = copymsg(first_mp);
8953 				if (copy_mp != NULL)
8954 					MULTIRT_DEBUG_TAG(copy_mp);
8955 			}
8956 
8957 			ire->ire_marks |= ire_marks;
8958 
8959 			/*
8960 			 * Construct message chain for the resolver
8961 			 * of the form:
8962 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8963 			 * Packet could contain a IPSEC_OUT mp.
8964 			 *
8965 			 * NOTE : ire will be added later when the response
8966 			 * comes back from ARP. If the response does not
8967 			 * come back, ARP frees the packet. For this reason,
8968 			 * we can't REFHOLD the bucket of save_ire to prevent
8969 			 * deletions. We may not be able to REFRELE the bucket
8970 			 * if the response never comes back. Thus, before
8971 			 * adding the ire, ire_add_v4 will make sure that the
8972 			 * interface route does not get deleted. This is the
8973 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8974 			 * where we can always prevent deletions because of
8975 			 * the synchronous nature of adding IRES i.e
8976 			 * ire_add_then_send is called after creating the IRE.
8977 			 */
8978 			ASSERT(ire->ire_mp != NULL);
8979 			ire->ire_mp->b_cont = first_mp;
8980 			/* Have saved_mp handy, for cleanup if canput fails */
8981 			saved_mp = mp;
8982 			mp = copyb(res_mp);
8983 			if (mp == NULL) {
8984 				/* Prepare for cleanup */
8985 				mp = saved_mp; /* pkt */
8986 				ire_delete(ire); /* ire_mp */
8987 				ire = NULL;
8988 				ire_refrele(save_ire);
8989 				if (copy_mp != NULL) {
8990 					MULTIRT_DEBUG_UNTAG(copy_mp);
8991 					freemsg(copy_mp);
8992 					copy_mp = NULL;
8993 				}
8994 				break;
8995 			}
8996 			linkb(mp, ire->ire_mp);
8997 
8998 			/*
8999 			 * Fill in the source and dest addrs for the resolver.
9000 			 * NOTE: this depends on memory layouts imposed by
9001 			 * ill_init().
9002 			 */
9003 			areq = (areq_t *)mp->b_rptr;
9004 			addrp = (ipaddr_t *)((char *)areq +
9005 			    areq->areq_sender_addr_offset);
9006 			if (do_attach_ill) {
9007 				/*
9008 				 * This is bind to no failover case.
9009 				 * arp packet also must go out on attach_ill.
9010 				 */
9011 				ASSERT(ipha->ipha_src != NULL);
9012 				*addrp = ipha->ipha_src;
9013 			} else {
9014 				*addrp = save_ire->ire_src_addr;
9015 			}
9016 
9017 			ire_refrele(save_ire);
9018 			addrp = (ipaddr_t *)((char *)areq +
9019 			    areq->areq_target_addr_offset);
9020 			*addrp = dst;
9021 			/* Up to the resolver. */
9022 			if (canputnext(dst_ill->ill_rq) &&
9023 			    !(dst_ill->ill_arp_closing)) {
9024 				putnext(dst_ill->ill_rq, mp);
9025 				ire = NULL;
9026 				if (copy_mp != NULL) {
9027 					/*
9028 					 * If we found a resolver, we ignore
9029 					 * any trailing top priority IRE_CACHE
9030 					 * in the further loops. This ensures
9031 					 * that we do not omit any resolver.
9032 					 * IRE_CACHE entries, if any, will be
9033 					 * processed next time we enter
9034 					 * ip_newroute().
9035 					 */
9036 					multirt_flags &= ~MULTIRT_CACHEGW;
9037 					/*
9038 					 * Search for the next unresolved
9039 					 * multirt route.
9040 					 */
9041 					first_mp = copy_mp;
9042 					copy_mp = NULL;
9043 					/* Prepare the next resolution loop. */
9044 					mp = first_mp;
9045 					EXTRACT_PKT_MP(mp, first_mp,
9046 					    mctl_present);
9047 					if (mctl_present)
9048 						io = (ipsec_out_t *)
9049 						    first_mp->b_rptr;
9050 					ipha = (ipha_t *)mp->b_rptr;
9051 
9052 					ASSERT(sire != NULL);
9053 
9054 					dst = save_dst;
9055 					multirt_resolve_next = B_TRUE;
9056 					continue;
9057 				}
9058 
9059 				if (sire != NULL)
9060 					ire_refrele(sire);
9061 
9062 				/*
9063 				 * The response will come back in ip_wput
9064 				 * with db_type IRE_DB_TYPE.
9065 				 */
9066 				ipif_refrele(src_ipif);
9067 				ill_refrele(dst_ill);
9068 				return;
9069 			} else {
9070 				/* Prepare for cleanup */
9071 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
9072 				    mp);
9073 				mp->b_cont = NULL;
9074 				freeb(mp); /* areq */
9075 				/*
9076 				 * this is an ire that is not added to the
9077 				 * cache. ire_freemblk will handle the release
9078 				 * of any resources associated with the ire.
9079 				 */
9080 				ire_delete(ire); /* ire_mp */
9081 				mp = saved_mp; /* pkt */
9082 				ire = NULL;
9083 				if (copy_mp != NULL) {
9084 					MULTIRT_DEBUG_UNTAG(copy_mp);
9085 					freemsg(copy_mp);
9086 					copy_mp = NULL;
9087 				}
9088 				break;
9089 			}
9090 		default:
9091 			break;
9092 		}
9093 	} while (multirt_resolve_next);
9094 
9095 	ip1dbg(("ip_newroute: dropped\n"));
9096 	/* Did this packet originate externally? */
9097 	if (mp->b_prev) {
9098 		mp->b_next = NULL;
9099 		mp->b_prev = NULL;
9100 		if (in_ill != NULL) {
9101 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
9102 		} else {
9103 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9104 		}
9105 	} else {
9106 		if (dst_ill != NULL) {
9107 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
9108 		} else {
9109 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
9110 		}
9111 	}
9112 	ASSERT(copy_mp == NULL);
9113 	MULTIRT_DEBUG_UNTAG(first_mp);
9114 	freemsg(first_mp);
9115 	if (ire != NULL)
9116 		ire_refrele(ire);
9117 	if (sire != NULL)
9118 		ire_refrele(sire);
9119 	if (src_ipif != NULL)
9120 		ipif_refrele(src_ipif);
9121 	if (dst_ill != NULL)
9122 		ill_refrele(dst_ill);
9123 	return;
9124 
9125 icmp_err_ret:
9126 	ip1dbg(("ip_newroute: no route\n"));
9127 	if (src_ipif != NULL)
9128 		ipif_refrele(src_ipif);
9129 	if (dst_ill != NULL)
9130 		ill_refrele(dst_ill);
9131 	if (sire != NULL)
9132 		ire_refrele(sire);
9133 	/* Did this packet originate externally? */
9134 	if (mp->b_prev) {
9135 		mp->b_next = NULL;
9136 		mp->b_prev = NULL;
9137 		if (in_ill != NULL) {
9138 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
9139 		} else {
9140 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9141 		}
9142 		q = WR(q);
9143 	} else {
9144 		/*
9145 		 * There is no outgoing ill, so just increment the
9146 		 * system MIB.
9147 		 */
9148 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9149 		/*
9150 		 * Since ip_wput() isn't close to finished, we fill
9151 		 * in enough of the header for credible error reporting.
9152 		 */
9153 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9154 			/* Failed */
9155 			MULTIRT_DEBUG_UNTAG(first_mp);
9156 			freemsg(first_mp);
9157 			if (ire != NULL)
9158 				ire_refrele(ire);
9159 			return;
9160 		}
9161 	}
9162 
9163 	/*
9164 	 * At this point we will have ire only if RTF_BLACKHOLE
9165 	 * or RTF_REJECT flags are set on the IRE. It will not
9166 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9167 	 */
9168 	if (ire != NULL) {
9169 		if (ire->ire_flags & RTF_BLACKHOLE) {
9170 			ire_refrele(ire);
9171 			MULTIRT_DEBUG_UNTAG(first_mp);
9172 			freemsg(first_mp);
9173 			return;
9174 		}
9175 		ire_refrele(ire);
9176 	}
9177 	if (ip_source_routed(ipha, ipst)) {
9178 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9179 		    zoneid, ipst);
9180 		return;
9181 	}
9182 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9183 }
9184 
9185 ip_opt_info_t zero_info;
9186 
9187 /*
9188  * IPv4 -
9189  * ip_newroute_ipif is called by ip_wput_multicast and
9190  * ip_rput_forward_multicast whenever we need to send
9191  * out a packet to a destination address for which we do not have specific
9192  * routing information. It is used when the packet will be sent out
9193  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9194  * socket option is set or icmp error message wants to go out on a particular
9195  * interface for a unicast packet.
9196  *
9197  * In most cases, the destination address is resolved thanks to the ipif
9198  * intrinsic resolver. However, there are some cases where the call to
9199  * ip_newroute_ipif must take into account the potential presence of
9200  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9201  * that uses the interface. This is specified through flags,
9202  * which can be a combination of:
9203  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9204  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9205  *   and flags. Additionally, the packet source address has to be set to
9206  *   the specified address. The caller is thus expected to set this flag
9207  *   if the packet has no specific source address yet.
9208  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9209  *   flag, the resulting ire will inherit the flag. All unresolved routes
9210  *   to the destination must be explored in the same call to
9211  *   ip_newroute_ipif().
9212  */
9213 static void
9214 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9215     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9216 {
9217 	areq_t	*areq;
9218 	ire_t	*ire = NULL;
9219 	mblk_t	*res_mp;
9220 	ipaddr_t *addrp;
9221 	mblk_t *first_mp;
9222 	ire_t	*save_ire = NULL;
9223 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9224 	ipif_t	*src_ipif = NULL;
9225 	ushort_t ire_marks = 0;
9226 	ill_t	*dst_ill = NULL;
9227 	boolean_t mctl_present;
9228 	ipsec_out_t *io;
9229 	ipha_t *ipha;
9230 	int	ihandle = 0;
9231 	mblk_t	*saved_mp;
9232 	ire_t   *fire = NULL;
9233 	mblk_t  *copy_mp = NULL;
9234 	boolean_t multirt_resolve_next;
9235 	ipaddr_t ipha_dst;
9236 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9237 
9238 	/*
9239 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9240 	 * here for uniformity
9241 	 */
9242 	ipif_refhold(ipif);
9243 
9244 	/*
9245 	 * This loop is run only once in most cases.
9246 	 * We loop to resolve further routes only when the destination
9247 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9248 	 */
9249 	do {
9250 		if (dst_ill != NULL) {
9251 			ill_refrele(dst_ill);
9252 			dst_ill = NULL;
9253 		}
9254 		if (src_ipif != NULL) {
9255 			ipif_refrele(src_ipif);
9256 			src_ipif = NULL;
9257 		}
9258 		multirt_resolve_next = B_FALSE;
9259 
9260 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9261 		    ipif->ipif_ill->ill_name));
9262 
9263 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9264 		if (mctl_present)
9265 			io = (ipsec_out_t *)first_mp->b_rptr;
9266 
9267 		ipha = (ipha_t *)mp->b_rptr;
9268 
9269 		/*
9270 		 * Save the packet destination address, we may need it after
9271 		 * the packet has been consumed.
9272 		 */
9273 		ipha_dst = ipha->ipha_dst;
9274 
9275 		/*
9276 		 * If the interface is a pt-pt interface we look for an
9277 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9278 		 * local_address and the pt-pt destination address. Otherwise
9279 		 * we just match the local address.
9280 		 * NOTE: dst could be different than ipha->ipha_dst in case
9281 		 * of sending igmp multicast packets over a point-to-point
9282 		 * connection.
9283 		 * Thus we must be careful enough to check ipha_dst to be a
9284 		 * multicast address, otherwise it will take xmit_if path for
9285 		 * multicast packets resulting into kernel stack overflow by
9286 		 * repeated calls to ip_newroute_ipif from ire_send().
9287 		 */
9288 		if (CLASSD(ipha_dst) &&
9289 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9290 			goto err_ret;
9291 		}
9292 
9293 		/*
9294 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9295 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9296 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9297 		 * propagate its flags to the new ire.
9298 		 */
9299 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9300 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9301 			ip2dbg(("ip_newroute_ipif: "
9302 			    "ipif_lookup_multi_ire("
9303 			    "ipif %p, dst %08x) = fire %p\n",
9304 			    (void *)ipif, ntohl(dst), (void *)fire));
9305 		}
9306 
9307 		if (mctl_present && io->ipsec_out_attach_if) {
9308 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9309 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9310 
9311 			/* Failure case frees things for us. */
9312 			if (attach_ill == NULL) {
9313 				ipif_refrele(ipif);
9314 				if (fire != NULL)
9315 					ire_refrele(fire);
9316 				return;
9317 			}
9318 
9319 			/*
9320 			 * Check if we need an ire that will not be
9321 			 * looked up by anybody else i.e. HIDDEN.
9322 			 */
9323 			if (ill_is_probeonly(attach_ill)) {
9324 				ire_marks = IRE_MARK_HIDDEN;
9325 			}
9326 			/*
9327 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9328 			 * case.
9329 			 */
9330 			dst_ill = ipif->ipif_ill;
9331 			/* attach_ill has been refheld by ip_grab_attach_ill */
9332 			ASSERT(dst_ill == attach_ill);
9333 		} else {
9334 			/*
9335 			 * If this is set by IP_XMIT_IF, then make sure that
9336 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9337 			 * specified ill.
9338 			 */
9339 			ASSERT((connp == NULL) ||
9340 			    (connp->conn_xmit_if_ill == NULL) ||
9341 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9342 			/*
9343 			 * If the interface belongs to an interface group,
9344 			 * make sure the next possible interface in the group
9345 			 * is used.  This encourages load spreading among
9346 			 * peers in an interface group.
9347 			 * Note: load spreading is disabled for RTF_MULTIRT
9348 			 * routes.
9349 			 */
9350 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9351 			    (fire->ire_flags & RTF_MULTIRT)) {
9352 				/*
9353 				 * Don't perform outbound load spreading
9354 				 * in the case of an RTF_MULTIRT issued route,
9355 				 * we actually typically want to replicate
9356 				 * outgoing packets through particular
9357 				 * interfaces.
9358 				 */
9359 				dst_ill = ipif->ipif_ill;
9360 				ill_refhold(dst_ill);
9361 			} else {
9362 				dst_ill = ip_newroute_get_dst_ill(
9363 				    ipif->ipif_ill);
9364 			}
9365 			if (dst_ill == NULL) {
9366 				if (ip_debug > 2) {
9367 					pr_addr_dbg("ip_newroute_ipif: "
9368 					    "no dst ill for dst %s\n",
9369 					    AF_INET, &dst);
9370 				}
9371 				goto err_ret;
9372 			}
9373 		}
9374 
9375 		/*
9376 		 * Pick a source address preferring non-deprecated ones.
9377 		 * Unlike ip_newroute, we don't do any source address
9378 		 * selection here since for multicast it really does not help
9379 		 * in inbound load spreading as in the unicast case.
9380 		 */
9381 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9382 		    (fire->ire_flags & RTF_SETSRC)) {
9383 			/*
9384 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9385 			 * on that interface. This ire has RTF_SETSRC flag, so
9386 			 * the source address of the packet must be changed.
9387 			 * Check that the ipif matching the requested source
9388 			 * address still exists.
9389 			 */
9390 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9391 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9392 		}
9393 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9394 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9395 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9396 		    (src_ipif == NULL)) {
9397 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9398 			if (src_ipif == NULL) {
9399 				if (ip_debug > 2) {
9400 					/* ip1dbg */
9401 					pr_addr_dbg("ip_newroute_ipif: "
9402 					    "no src for dst %s",
9403 					    AF_INET, &dst);
9404 				}
9405 				ip1dbg((" through interface %s\n",
9406 				    dst_ill->ill_name));
9407 				goto err_ret;
9408 			}
9409 			ipif_refrele(ipif);
9410 			ipif = src_ipif;
9411 			ipif_refhold(ipif);
9412 		}
9413 		if (src_ipif == NULL) {
9414 			src_ipif = ipif;
9415 			ipif_refhold(src_ipif);
9416 		}
9417 
9418 		/*
9419 		 * Assign a source address while we have the conn.
9420 		 * We can't have ip_wput_ire pick a source address when the
9421 		 * packet returns from arp since conn_unspec_src might be set
9422 		 * and we loose the conn when going through arp.
9423 		 */
9424 		if (ipha->ipha_src == INADDR_ANY &&
9425 		    (connp == NULL || !connp->conn_unspec_src)) {
9426 			ipha->ipha_src = src_ipif->ipif_src_addr;
9427 		}
9428 
9429 		/*
9430 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9431 		 * interface does not have an interface ire.
9432 		 * Example: Thousands of mobileip PPP interfaces to mobile
9433 		 * nodes. We don't want to create interface ires because
9434 		 * packets from other mobile nodes must not take the route
9435 		 * via interface ires to the visiting mobile node without
9436 		 * going through the home agent, in absence of mobileip
9437 		 * route optimization.
9438 		 */
9439 		if (CLASSD(ipha_dst) && (connp == NULL ||
9440 		    connp->conn_xmit_if_ill == NULL) &&
9441 		    infop->ip_opt_ill_index == 0) {
9442 			/* ipif_to_ire returns an held ire */
9443 			ire = ipif_to_ire(ipif);
9444 			if (ire == NULL)
9445 				goto err_ret;
9446 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9447 				goto err_ret;
9448 			/*
9449 			 * ihandle is needed when the ire is added to
9450 			 * cache table.
9451 			 */
9452 			save_ire = ire;
9453 			ihandle = save_ire->ire_ihandle;
9454 
9455 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9456 			    "flags %04x\n",
9457 			    (void *)ire, (void *)ipif, flags));
9458 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9459 			    (fire->ire_flags & RTF_MULTIRT)) {
9460 				/*
9461 				 * As requested by flags, an IRE_OFFSUBNET was
9462 				 * looked up on that interface. This ire has
9463 				 * RTF_MULTIRT flag, so the resolution loop will
9464 				 * be re-entered to resolve additional routes on
9465 				 * other interfaces. For that purpose, a copy of
9466 				 * the packet is performed at this point.
9467 				 */
9468 				fire->ire_last_used_time = lbolt;
9469 				copy_mp = copymsg(first_mp);
9470 				if (copy_mp) {
9471 					MULTIRT_DEBUG_TAG(copy_mp);
9472 				}
9473 			}
9474 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9475 			    (fire->ire_flags & RTF_SETSRC)) {
9476 				/*
9477 				 * As requested by flags, an IRE_OFFSUBET was
9478 				 * looked up on that interface. This ire has
9479 				 * RTF_SETSRC flag, so the source address of the
9480 				 * packet must be changed.
9481 				 */
9482 				ipha->ipha_src = fire->ire_src_addr;
9483 			}
9484 		} else {
9485 			ASSERT((connp == NULL) ||
9486 			    (connp->conn_xmit_if_ill != NULL) ||
9487 			    (connp->conn_dontroute) ||
9488 			    infop->ip_opt_ill_index != 0);
9489 			/*
9490 			 * The only ways we can come here are:
9491 			 * 1) IP_XMIT_IF socket option is set
9492 			 * 2) ICMP error message generated from
9493 			 *    ip_mrtun_forward() routine and it needs
9494 			 *    to go through the specified ill.
9495 			 * 3) SO_DONTROUTE socket option is set
9496 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9497 			 * In all cases, the new ire will not be added
9498 			 * into cache table.
9499 			 */
9500 			ire_marks |= IRE_MARK_NOADD;
9501 		}
9502 
9503 		switch (ipif->ipif_net_type) {
9504 		case IRE_IF_NORESOLVER: {
9505 			/* We have what we need to build an IRE_CACHE. */
9506 			mblk_t	*res_mp;
9507 
9508 			/*
9509 			 * Create a new res_mp with the
9510 			 * IP gateway address as destination address in the
9511 			 * DLPI hdr if the physical length is exactly 4 bytes.
9512 			 */
9513 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9514 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9515 				    dst_ill->ill_phys_addr_length,
9516 				    dst_ill->ill_sap,
9517 				    dst_ill->ill_sap_length);
9518 			} else if (dst_ill->ill_resolver_mp == NULL) {
9519 				ip1dbg(("ip_newroute: dst_ill %p "
9520 				    "for IF_NORESOLV ire %p has "
9521 				    "no ill_resolver_mp\n",
9522 				    (void *)dst_ill, (void *)ire));
9523 				break;
9524 			} else {
9525 				/* use the value set in ip_ll_subnet_defaults */
9526 				res_mp = ill_dlur_gen(NULL,
9527 				    dst_ill->ill_phys_addr_length,
9528 				    dst_ill->ill_sap,
9529 				    dst_ill->ill_sap_length);
9530 			}
9531 
9532 			if (res_mp == NULL)
9533 				break;
9534 			/*
9535 			 * The new ire inherits the IRE_OFFSUBNET flags
9536 			 * and source address, if this was requested.
9537 			 */
9538 			ire = ire_create(
9539 			    (uchar_t *)&dst,		/* dest address */
9540 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9541 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9542 			    NULL,			/* gateway address */
9543 			    NULL,
9544 			    &ipif->ipif_mtu,
9545 			    NULL,			/* Fast Path header */
9546 			    dst_ill->ill_rq,		/* recv-from queue */
9547 			    dst_ill->ill_wq,		/* send-to queue */
9548 			    IRE_CACHE,
9549 			    res_mp,
9550 			    src_ipif,
9551 			    NULL,
9552 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9553 			    (fire != NULL) ?		/* Parent handle */
9554 				fire->ire_phandle : 0,
9555 			    ihandle,			/* Interface handle */
9556 			    (fire != NULL) ?
9557 				(fire->ire_flags &
9558 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9559 			    (save_ire == NULL ? &ire_uinfo_null :
9560 				&save_ire->ire_uinfo),
9561 			    NULL,
9562 			    NULL,
9563 			    ipst);
9564 
9565 			freeb(res_mp);
9566 
9567 			if (ire == NULL) {
9568 				if (save_ire != NULL)
9569 					ire_refrele(save_ire);
9570 				break;
9571 			}
9572 
9573 			ire->ire_marks |= ire_marks;
9574 
9575 			/*
9576 			 * If IRE_MARK_NOADD is set then we need to convert
9577 			 * the max_fragp to a useable value now. This is
9578 			 * normally done in ire_add_v[46]. We also need to
9579 			 * associate the ire with an nce (normally would be
9580 			 * done in ip_wput_nondata()).
9581 			 *
9582 			 * Note that IRE_MARK_NOADD packets created here
9583 			 * do not have a non-null ire_mp pointer. The null
9584 			 * value of ire_bucket indicates that they were
9585 			 * never added.
9586 			 */
9587 			if (ire->ire_marks & IRE_MARK_NOADD) {
9588 				uint_t  max_frag;
9589 
9590 				max_frag = *ire->ire_max_fragp;
9591 				ire->ire_max_fragp = NULL;
9592 				ire->ire_max_frag = max_frag;
9593 
9594 				if ((ire->ire_nce = ndp_lookup_v4(
9595 				    ire_to_ill(ire),
9596 				    (ire->ire_gateway_addr != INADDR_ANY ?
9597 				    &ire->ire_gateway_addr : &ire->ire_addr),
9598 				    B_FALSE)) == NULL) {
9599 					if (save_ire != NULL)
9600 						ire_refrele(save_ire);
9601 					break;
9602 				}
9603 				ASSERT(ire->ire_nce->nce_state ==
9604 				    ND_REACHABLE);
9605 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9606 			}
9607 
9608 			/* Prevent save_ire from getting deleted */
9609 			if (save_ire != NULL) {
9610 				IRB_REFHOLD(save_ire->ire_bucket);
9611 				/* Has it been removed already ? */
9612 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9613 					IRB_REFRELE(save_ire->ire_bucket);
9614 					ire_refrele(save_ire);
9615 					break;
9616 				}
9617 			}
9618 
9619 			ire_add_then_send(q, ire, first_mp);
9620 
9621 			/* Assert that save_ire is not deleted yet. */
9622 			if (save_ire != NULL) {
9623 				ASSERT(save_ire->ire_ptpn != NULL);
9624 				IRB_REFRELE(save_ire->ire_bucket);
9625 				ire_refrele(save_ire);
9626 				save_ire = NULL;
9627 			}
9628 			if (fire != NULL) {
9629 				ire_refrele(fire);
9630 				fire = NULL;
9631 			}
9632 
9633 			/*
9634 			 * the resolution loop is re-entered if this
9635 			 * was requested through flags and if we
9636 			 * actually are in a multirouting case.
9637 			 */
9638 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9639 				boolean_t need_resolve =
9640 				    ire_multirt_need_resolve(ipha_dst,
9641 					MBLK_GETLABEL(copy_mp), ipst);
9642 				if (!need_resolve) {
9643 					MULTIRT_DEBUG_UNTAG(copy_mp);
9644 					freemsg(copy_mp);
9645 					copy_mp = NULL;
9646 				} else {
9647 					/*
9648 					 * ipif_lookup_group() calls
9649 					 * ire_lookup_multi() that uses
9650 					 * ire_ftable_lookup() to find
9651 					 * an IRE_INTERFACE for the group.
9652 					 * In the multirt case,
9653 					 * ire_lookup_multi() then invokes
9654 					 * ire_multirt_lookup() to find
9655 					 * the next resolvable ire.
9656 					 * As a result, we obtain an new
9657 					 * interface, derived from the
9658 					 * next ire.
9659 					 */
9660 					ipif_refrele(ipif);
9661 					ipif = ipif_lookup_group(ipha_dst,
9662 					    zoneid, ipst);
9663 					ip2dbg(("ip_newroute_ipif: "
9664 					    "multirt dst %08x, ipif %p\n",
9665 					    htonl(dst), (void *)ipif));
9666 					if (ipif != NULL) {
9667 						mp = copy_mp;
9668 						copy_mp = NULL;
9669 						multirt_resolve_next = B_TRUE;
9670 						continue;
9671 					} else {
9672 						freemsg(copy_mp);
9673 					}
9674 				}
9675 			}
9676 			if (ipif != NULL)
9677 				ipif_refrele(ipif);
9678 			ill_refrele(dst_ill);
9679 			ipif_refrele(src_ipif);
9680 			return;
9681 		}
9682 		case IRE_IF_RESOLVER:
9683 			/*
9684 			 * We can't build an IRE_CACHE yet, but at least
9685 			 * we found a resolver that can help.
9686 			 */
9687 			res_mp = dst_ill->ill_resolver_mp;
9688 			if (!OK_RESOLVER_MP(res_mp))
9689 				break;
9690 
9691 			/*
9692 			 * We obtain a partial IRE_CACHE which we will pass
9693 			 * along with the resolver query.  When the response
9694 			 * comes back it will be there ready for us to add.
9695 			 * The new ire inherits the IRE_OFFSUBNET flags
9696 			 * and source address, if this was requested.
9697 			 * The ire_max_frag is atomically set under the
9698 			 * irebucket lock in ire_add_v[46]. Only in the
9699 			 * case of IRE_MARK_NOADD, we set it here itself.
9700 			 */
9701 			ire = ire_create_mp(
9702 			    (uchar_t *)&dst,		/* dest address */
9703 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9704 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9705 			    NULL,			/* gateway address */
9706 			    NULL,			/* no in_src_addr */
9707 			    (ire_marks & IRE_MARK_NOADD) ?
9708 				ipif->ipif_mtu : 0,	/* max_frag */
9709 			    NULL,			/* Fast path header */
9710 			    dst_ill->ill_rq,		/* recv-from queue */
9711 			    dst_ill->ill_wq,		/* send-to queue */
9712 			    IRE_CACHE,
9713 			    NULL,	/* let ire_nce_init figure res_mp out */
9714 			    src_ipif,
9715 			    NULL,
9716 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9717 			    (fire != NULL) ?		/* Parent handle */
9718 				fire->ire_phandle : 0,
9719 			    ihandle,			/* Interface handle */
9720 			    (fire != NULL) ?		/* flags if any */
9721 				(fire->ire_flags &
9722 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9723 			    (save_ire == NULL ? &ire_uinfo_null :
9724 				&save_ire->ire_uinfo),
9725 			    NULL,
9726 			    NULL,
9727 			    ipst);
9728 
9729 			if (save_ire != NULL) {
9730 				ire_refrele(save_ire);
9731 				save_ire = NULL;
9732 			}
9733 			if (ire == NULL)
9734 				break;
9735 
9736 			ire->ire_marks |= ire_marks;
9737 			/*
9738 			 * Construct message chain for the resolver of the
9739 			 * form:
9740 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9741 			 *
9742 			 * NOTE : ire will be added later when the response
9743 			 * comes back from ARP. If the response does not
9744 			 * come back, ARP frees the packet. For this reason,
9745 			 * we can't REFHOLD the bucket of save_ire to prevent
9746 			 * deletions. We may not be able to REFRELE the
9747 			 * bucket if the response never comes back.
9748 			 * Thus, before adding the ire, ire_add_v4 will make
9749 			 * sure that the interface route does not get deleted.
9750 			 * This is the only case unlike ip_newroute_v6,
9751 			 * ip_newroute_ipif_v6 where we can always prevent
9752 			 * deletions because ire_add_then_send is called after
9753 			 * creating the IRE.
9754 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9755 			 * does not add this IRE into the IRE CACHE.
9756 			 */
9757 			ASSERT(ire->ire_mp != NULL);
9758 			ire->ire_mp->b_cont = first_mp;
9759 			/* Have saved_mp handy, for cleanup if canput fails */
9760 			saved_mp = mp;
9761 			mp = copyb(res_mp);
9762 			if (mp == NULL) {
9763 				/* Prepare for cleanup */
9764 				mp = saved_mp; /* pkt */
9765 				ire_delete(ire); /* ire_mp */
9766 				ire = NULL;
9767 				if (copy_mp != NULL) {
9768 					MULTIRT_DEBUG_UNTAG(copy_mp);
9769 					freemsg(copy_mp);
9770 					copy_mp = NULL;
9771 				}
9772 				break;
9773 			}
9774 			linkb(mp, ire->ire_mp);
9775 
9776 			/*
9777 			 * Fill in the source and dest addrs for the resolver.
9778 			 * NOTE: this depends on memory layouts imposed by
9779 			 * ill_init().
9780 			 */
9781 			areq = (areq_t *)mp->b_rptr;
9782 			addrp = (ipaddr_t *)((char *)areq +
9783 			    areq->areq_sender_addr_offset);
9784 			*addrp = ire->ire_src_addr;
9785 			addrp = (ipaddr_t *)((char *)areq +
9786 			    areq->areq_target_addr_offset);
9787 			*addrp = dst;
9788 			/* Up to the resolver. */
9789 			if (canputnext(dst_ill->ill_rq) &&
9790 			    !(dst_ill->ill_arp_closing)) {
9791 				putnext(dst_ill->ill_rq, mp);
9792 				/*
9793 				 * The response will come back in ip_wput
9794 				 * with db_type IRE_DB_TYPE.
9795 				 */
9796 			} else {
9797 				mp->b_cont = NULL;
9798 				freeb(mp); /* areq */
9799 				ire_delete(ire); /* ire_mp */
9800 				saved_mp->b_next = NULL;
9801 				saved_mp->b_prev = NULL;
9802 				freemsg(first_mp); /* pkt */
9803 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9804 			}
9805 
9806 			if (fire != NULL) {
9807 				ire_refrele(fire);
9808 				fire = NULL;
9809 			}
9810 
9811 
9812 			/*
9813 			 * The resolution loop is re-entered if this was
9814 			 * requested through flags and we actually are
9815 			 * in a multirouting case.
9816 			 */
9817 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9818 				boolean_t need_resolve =
9819 				    ire_multirt_need_resolve(ipha_dst,
9820 					MBLK_GETLABEL(copy_mp), ipst);
9821 				if (!need_resolve) {
9822 					MULTIRT_DEBUG_UNTAG(copy_mp);
9823 					freemsg(copy_mp);
9824 					copy_mp = NULL;
9825 				} else {
9826 					/*
9827 					 * ipif_lookup_group() calls
9828 					 * ire_lookup_multi() that uses
9829 					 * ire_ftable_lookup() to find
9830 					 * an IRE_INTERFACE for the group.
9831 					 * In the multirt case,
9832 					 * ire_lookup_multi() then invokes
9833 					 * ire_multirt_lookup() to find
9834 					 * the next resolvable ire.
9835 					 * As a result, we obtain an new
9836 					 * interface, derived from the
9837 					 * next ire.
9838 					 */
9839 					ipif_refrele(ipif);
9840 					ipif = ipif_lookup_group(ipha_dst,
9841 					    zoneid, ipst);
9842 					if (ipif != NULL) {
9843 						mp = copy_mp;
9844 						copy_mp = NULL;
9845 						multirt_resolve_next = B_TRUE;
9846 						continue;
9847 					} else {
9848 						freemsg(copy_mp);
9849 					}
9850 				}
9851 			}
9852 			if (ipif != NULL)
9853 				ipif_refrele(ipif);
9854 			ill_refrele(dst_ill);
9855 			ipif_refrele(src_ipif);
9856 			return;
9857 		default:
9858 			break;
9859 		}
9860 	} while (multirt_resolve_next);
9861 
9862 err_ret:
9863 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9864 	if (fire != NULL)
9865 		ire_refrele(fire);
9866 	ipif_refrele(ipif);
9867 	/* Did this packet originate externally? */
9868 	if (dst_ill != NULL)
9869 		ill_refrele(dst_ill);
9870 	if (src_ipif != NULL)
9871 		ipif_refrele(src_ipif);
9872 	if (mp->b_prev || mp->b_next) {
9873 		mp->b_next = NULL;
9874 		mp->b_prev = NULL;
9875 	} else {
9876 		/*
9877 		 * Since ip_wput() isn't close to finished, we fill
9878 		 * in enough of the header for credible error reporting.
9879 		 */
9880 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9881 			/* Failed */
9882 			freemsg(first_mp);
9883 			if (ire != NULL)
9884 				ire_refrele(ire);
9885 			return;
9886 		}
9887 	}
9888 	/*
9889 	 * At this point we will have ire only if RTF_BLACKHOLE
9890 	 * or RTF_REJECT flags are set on the IRE. It will not
9891 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9892 	 */
9893 	if (ire != NULL) {
9894 		if (ire->ire_flags & RTF_BLACKHOLE) {
9895 			ire_refrele(ire);
9896 			freemsg(first_mp);
9897 			return;
9898 		}
9899 		ire_refrele(ire);
9900 	}
9901 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9902 }
9903 
9904 /* Name/Value Table Lookup Routine */
9905 char *
9906 ip_nv_lookup(nv_t *nv, int value)
9907 {
9908 	if (!nv)
9909 		return (NULL);
9910 	for (; nv->nv_name; nv++) {
9911 		if (nv->nv_value == value)
9912 			return (nv->nv_name);
9913 	}
9914 	return ("unknown");
9915 }
9916 
9917 /*
9918  * This is a module open, i.e. this is a control stream for access
9919  * to a DLPI device.  We allocate an ill_t as the instance data in
9920  * this case.
9921  */
9922 int
9923 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9924 {
9925 	ill_t	*ill;
9926 	int	err;
9927 	zoneid_t zoneid;
9928 	netstack_t *ns;
9929 	ip_stack_t *ipst;
9930 
9931 	/*
9932 	 * Prevent unprivileged processes from pushing IP so that
9933 	 * they can't send raw IP.
9934 	 */
9935 	if (secpolicy_net_rawaccess(credp) != 0)
9936 		return (EPERM);
9937 
9938 	ns = netstack_find_by_cred(credp);
9939 	ASSERT(ns != NULL);
9940 	ipst = ns->netstack_ip;
9941 	ASSERT(ipst != NULL);
9942 
9943 	/*
9944 	 * For exclusive stacks we set the zoneid to zero
9945 	 * to make IP operate as if in the global zone.
9946 	 */
9947 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9948 		zoneid = GLOBAL_ZONEID;
9949 	else
9950 		zoneid = crgetzoneid(credp);
9951 
9952 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9953 	q->q_ptr = WR(q)->q_ptr = ill;
9954 	ill->ill_ipst = ipst;
9955 	ill->ill_zoneid = zoneid;
9956 
9957 	/*
9958 	 * ill_init initializes the ill fields and then sends down
9959 	 * down a DL_INFO_REQ after calling qprocson.
9960 	 */
9961 	err = ill_init(q, ill);
9962 	if (err != 0) {
9963 		mi_free(ill);
9964 		netstack_rele(ipst->ips_netstack);
9965 		q->q_ptr = NULL;
9966 		WR(q)->q_ptr = NULL;
9967 		return (err);
9968 	}
9969 
9970 	/* ill_init initializes the ipsq marking this thread as writer */
9971 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9972 	/* Wait for the DL_INFO_ACK */
9973 	mutex_enter(&ill->ill_lock);
9974 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9975 		/*
9976 		 * Return value of 0 indicates a pending signal.
9977 		 */
9978 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9979 		if (err == 0) {
9980 			mutex_exit(&ill->ill_lock);
9981 			(void) ip_close(q, 0);
9982 			return (EINTR);
9983 		}
9984 	}
9985 	mutex_exit(&ill->ill_lock);
9986 
9987 	/*
9988 	 * ip_rput_other could have set an error  in ill_error on
9989 	 * receipt of M_ERROR.
9990 	 */
9991 
9992 	err = ill->ill_error;
9993 	if (err != 0) {
9994 		(void) ip_close(q, 0);
9995 		return (err);
9996 	}
9997 
9998 	ill->ill_credp = credp;
9999 	crhold(credp);
10000 
10001 	mutex_enter(&ipst->ips_ip_mi_lock);
10002 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
10003 	    credp);
10004 	mutex_exit(&ipst->ips_ip_mi_lock);
10005 	if (err) {
10006 		(void) ip_close(q, 0);
10007 		return (err);
10008 	}
10009 	return (0);
10010 }
10011 
10012 /* IP open routine. */
10013 int
10014 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
10015 {
10016 	conn_t 		*connp;
10017 	major_t		maj;
10018 	zoneid_t	zoneid;
10019 	netstack_t	*ns;
10020 	ip_stack_t	*ipst;
10021 
10022 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
10023 
10024 	/* Allow reopen. */
10025 	if (q->q_ptr != NULL)
10026 		return (0);
10027 
10028 	if (sflag & MODOPEN) {
10029 		/* This is a module open */
10030 		return (ip_modopen(q, devp, flag, sflag, credp));
10031 	}
10032 
10033 	ns = netstack_find_by_cred(credp);
10034 	ASSERT(ns != NULL);
10035 	ipst = ns->netstack_ip;
10036 	ASSERT(ipst != NULL);
10037 
10038 	/*
10039 	 * For exclusive stacks we set the zoneid to zero
10040 	 * to make IP operate as if in the global zone.
10041 	 */
10042 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
10043 		zoneid = GLOBAL_ZONEID;
10044 	else
10045 		zoneid = crgetzoneid(credp);
10046 
10047 	/*
10048 	 * We are opening as a device. This is an IP client stream, and we
10049 	 * allocate an conn_t as the instance data.
10050 	 */
10051 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
10052 
10053 	/*
10054 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
10055 	 * done by netstack_find_by_cred()
10056 	 */
10057 	netstack_rele(ipst->ips_netstack);
10058 
10059 	connp->conn_zoneid = zoneid;
10060 
10061 	connp->conn_upq = q;
10062 	q->q_ptr = WR(q)->q_ptr = connp;
10063 
10064 	if (flag & SO_SOCKSTR)
10065 		connp->conn_flags |= IPCL_SOCKET;
10066 
10067 	/* Minor tells us which /dev entry was opened */
10068 	if (geteminor(*devp) == IPV6_MINOR) {
10069 		connp->conn_flags |= IPCL_ISV6;
10070 		connp->conn_af_isv6 = B_TRUE;
10071 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
10072 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
10073 	} else {
10074 		connp->conn_af_isv6 = B_FALSE;
10075 		connp->conn_pkt_isv6 = B_FALSE;
10076 	}
10077 
10078 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
10079 		/* CONN_DEC_REF takes care of netstack_rele() */
10080 		q->q_ptr = WR(q)->q_ptr = NULL;
10081 		CONN_DEC_REF(connp);
10082 		return (EBUSY);
10083 	}
10084 
10085 	maj = getemajor(*devp);
10086 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
10087 
10088 	/*
10089 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
10090 	 */
10091 	connp->conn_cred = credp;
10092 	crhold(connp->conn_cred);
10093 
10094 	/*
10095 	 * If the caller has the process-wide flag set, then default to MAC
10096 	 * exempt mode.  This allows read-down to unlabeled hosts.
10097 	 */
10098 	if (getpflags(NET_MAC_AWARE, credp) != 0)
10099 		connp->conn_mac_exempt = B_TRUE;
10100 
10101 	/*
10102 	 * This should only happen for ndd, netstat, raw socket or other SCTP
10103 	 * administrative ops.  In these cases, we just need a normal conn_t
10104 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
10105 	 * an error will be returned.
10106 	 */
10107 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
10108 		connp->conn_rq = q;
10109 		connp->conn_wq = WR(q);
10110 	} else {
10111 		connp->conn_ulp = IPPROTO_SCTP;
10112 		connp->conn_rq = connp->conn_wq = NULL;
10113 	}
10114 	/* Non-zero default values */
10115 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
10116 
10117 	/*
10118 	 * Make the conn globally visible to walkers
10119 	 */
10120 	mutex_enter(&connp->conn_lock);
10121 	connp->conn_state_flags &= ~CONN_INCIPIENT;
10122 	mutex_exit(&connp->conn_lock);
10123 	ASSERT(connp->conn_ref == 1);
10124 
10125 	qprocson(q);
10126 
10127 	return (0);
10128 }
10129 
10130 /*
10131  * Change q_qinfo based on the value of isv6.
10132  * This can not called on an ill queue.
10133  * Note that there is no race since either q_qinfo works for conn queues - it
10134  * is just an optimization to enter the best wput routine directly.
10135  */
10136 void
10137 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
10138 {
10139 	ASSERT(q->q_flag & QREADR);
10140 	ASSERT(WR(q)->q_next == NULL);
10141 	ASSERT(q->q_ptr != NULL);
10142 
10143 	if (minor == IPV6_MINOR)  {
10144 		if (bump_mib) {
10145 			BUMP_MIB(&ipst->ips_ip6_mib,
10146 			    ipIfStatsOutSwitchIPVersion);
10147 		}
10148 		q->q_qinfo = &rinit_ipv6;
10149 		WR(q)->q_qinfo = &winit_ipv6;
10150 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
10151 	} else {
10152 		if (bump_mib) {
10153 			BUMP_MIB(&ipst->ips_ip_mib,
10154 			    ipIfStatsOutSwitchIPVersion);
10155 		}
10156 		q->q_qinfo = &iprinit;
10157 		WR(q)->q_qinfo = &ipwinit;
10158 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
10159 	}
10160 
10161 }
10162 
10163 /*
10164  * See if IPsec needs loading because of the options in mp.
10165  */
10166 static boolean_t
10167 ipsec_opt_present(mblk_t *mp)
10168 {
10169 	uint8_t *optcp, *next_optcp, *opt_endcp;
10170 	struct opthdr *opt;
10171 	struct T_opthdr *topt;
10172 	int opthdr_len;
10173 	t_uscalar_t optname, optlevel;
10174 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10175 	ipsec_req_t *ipsr;
10176 
10177 	/*
10178 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10179 	 * return TRUE.
10180 	 */
10181 
10182 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10183 	opt_endcp = optcp + tor->OPT_length;
10184 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10185 		opthdr_len = sizeof (struct T_opthdr);
10186 	} else {		/* O_OPTMGMT_REQ */
10187 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10188 		opthdr_len = sizeof (struct opthdr);
10189 	}
10190 	for (; optcp < opt_endcp; optcp = next_optcp) {
10191 		if (optcp + opthdr_len > opt_endcp)
10192 			return (B_FALSE);	/* Not enough option header. */
10193 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10194 			topt = (struct T_opthdr *)optcp;
10195 			optlevel = topt->level;
10196 			optname = topt->name;
10197 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10198 		} else {
10199 			opt = (struct opthdr *)optcp;
10200 			optlevel = opt->level;
10201 			optname = opt->name;
10202 			next_optcp = optcp + opthdr_len +
10203 			    _TPI_ALIGN_OPT(opt->len);
10204 		}
10205 		if ((next_optcp < optcp) || /* wraparound pointer space */
10206 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10207 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10208 			return (B_FALSE); /* bad option buffer */
10209 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10210 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10211 			/*
10212 			 * Check to see if it's an all-bypass or all-zeroes
10213 			 * IPsec request.  Don't bother loading IPsec if
10214 			 * the socket doesn't want to use it.  (A good example
10215 			 * is a bypass request.)
10216 			 *
10217 			 * Basically, if any of the non-NEVER bits are set,
10218 			 * load IPsec.
10219 			 */
10220 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10221 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10222 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10223 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10224 			    != 0)
10225 				return (B_TRUE);
10226 		}
10227 	}
10228 	return (B_FALSE);
10229 }
10230 
10231 /*
10232  * If conn is is waiting for ipsec to finish loading, kick it.
10233  */
10234 /* ARGSUSED */
10235 static void
10236 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10237 {
10238 	t_scalar_t	optreq_prim;
10239 	mblk_t		*mp;
10240 	cred_t		*cr;
10241 	int		err = 0;
10242 
10243 	/*
10244 	 * This function is called, after ipsec loading is complete.
10245 	 * Since IP checks exclusively and atomically (i.e it prevents
10246 	 * ipsec load from completing until ip_optcom_req completes)
10247 	 * whether ipsec load is complete, there cannot be a race with IP
10248 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10249 	 */
10250 	mutex_enter(&connp->conn_lock);
10251 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10252 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10253 		mp = connp->conn_ipsec_opt_mp;
10254 		connp->conn_ipsec_opt_mp = NULL;
10255 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10256 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10257 		mutex_exit(&connp->conn_lock);
10258 
10259 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10260 
10261 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10262 		if (optreq_prim == T_OPTMGMT_REQ) {
10263 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10264 			    &ip_opt_obj);
10265 		} else {
10266 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10267 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10268 			    &ip_opt_obj);
10269 		}
10270 		if (err != EINPROGRESS)
10271 			CONN_OPER_PENDING_DONE(connp);
10272 		return;
10273 	}
10274 	mutex_exit(&connp->conn_lock);
10275 }
10276 
10277 /*
10278  * Called from the ipsec_loader thread, outside any perimeter, to tell
10279  * ip qenable any of the queues waiting for the ipsec loader to
10280  * complete.
10281  */
10282 void
10283 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10284 {
10285 	netstack_t *ns = ipss->ipsec_netstack;
10286 
10287 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10288 }
10289 
10290 /*
10291  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10292  * determines the grp on which it has to become exclusive, queues the mp
10293  * and sq draining restarts the optmgmt
10294  */
10295 static boolean_t
10296 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10297 {
10298 	conn_t *connp = Q_TO_CONN(q);
10299 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10300 
10301 	/*
10302 	 * Take IPsec requests and treat them special.
10303 	 */
10304 	if (ipsec_opt_present(mp)) {
10305 		/* First check if IPsec is loaded. */
10306 		mutex_enter(&ipss->ipsec_loader_lock);
10307 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10308 			mutex_exit(&ipss->ipsec_loader_lock);
10309 			return (B_FALSE);
10310 		}
10311 		mutex_enter(&connp->conn_lock);
10312 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10313 
10314 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10315 		connp->conn_ipsec_opt_mp = mp;
10316 		mutex_exit(&connp->conn_lock);
10317 		mutex_exit(&ipss->ipsec_loader_lock);
10318 
10319 		ipsec_loader_loadnow(ipss);
10320 		return (B_TRUE);
10321 	}
10322 	return (B_FALSE);
10323 }
10324 
10325 /*
10326  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10327  * all of them are copied to the conn_t. If the req is "zero", the policy is
10328  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10329  * fields.
10330  * We keep only the latest setting of the policy and thus policy setting
10331  * is not incremental/cumulative.
10332  *
10333  * Requests to set policies with multiple alternative actions will
10334  * go through a different API.
10335  */
10336 int
10337 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10338 {
10339 	uint_t ah_req = 0;
10340 	uint_t esp_req = 0;
10341 	uint_t se_req = 0;
10342 	ipsec_selkey_t sel;
10343 	ipsec_act_t *actp = NULL;
10344 	uint_t nact;
10345 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10346 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10347 	ipsec_policy_root_t *pr;
10348 	ipsec_policy_head_t *ph;
10349 	int fam;
10350 	boolean_t is_pol_reset;
10351 	int error = 0;
10352 	netstack_t	*ns = connp->conn_netstack;
10353 	ip_stack_t	*ipst = ns->netstack_ip;
10354 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10355 
10356 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10357 
10358 	/*
10359 	 * The IP_SEC_OPT option does not allow variable length parameters,
10360 	 * hence a request cannot be NULL.
10361 	 */
10362 	if (req == NULL)
10363 		return (EINVAL);
10364 
10365 	ah_req = req->ipsr_ah_req;
10366 	esp_req = req->ipsr_esp_req;
10367 	se_req = req->ipsr_self_encap_req;
10368 
10369 	/*
10370 	 * Are we dealing with a request to reset the policy (i.e.
10371 	 * zero requests).
10372 	 */
10373 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10374 	    (esp_req & REQ_MASK) == 0 &&
10375 	    (se_req & REQ_MASK) == 0);
10376 
10377 	if (!is_pol_reset) {
10378 		/*
10379 		 * If we couldn't load IPsec, fail with "protocol
10380 		 * not supported".
10381 		 * IPsec may not have been loaded for a request with zero
10382 		 * policies, so we don't fail in this case.
10383 		 */
10384 		mutex_enter(&ipss->ipsec_loader_lock);
10385 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10386 			mutex_exit(&ipss->ipsec_loader_lock);
10387 			return (EPROTONOSUPPORT);
10388 		}
10389 		mutex_exit(&ipss->ipsec_loader_lock);
10390 
10391 		/*
10392 		 * Test for valid requests. Invalid algorithms
10393 		 * need to be tested by IPSEC code because new
10394 		 * algorithms can be added dynamically.
10395 		 */
10396 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10397 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10398 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10399 			return (EINVAL);
10400 		}
10401 
10402 		/*
10403 		 * Only privileged users can issue these
10404 		 * requests.
10405 		 */
10406 		if (((ah_req & IPSEC_PREF_NEVER) ||
10407 		    (esp_req & IPSEC_PREF_NEVER) ||
10408 		    (se_req & IPSEC_PREF_NEVER)) &&
10409 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10410 			return (EPERM);
10411 		}
10412 
10413 		/*
10414 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10415 		 * are mutually exclusive.
10416 		 */
10417 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10418 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10419 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10420 			/* Both of them are set */
10421 			return (EINVAL);
10422 		}
10423 	}
10424 
10425 	mutex_enter(&connp->conn_lock);
10426 
10427 	/*
10428 	 * If we have already cached policies in ip_bind_connected*(), don't
10429 	 * let them change now. We cache policies for connections
10430 	 * whose src,dst [addr, port] is known.
10431 	 */
10432 	if (connp->conn_policy_cached) {
10433 		mutex_exit(&connp->conn_lock);
10434 		return (EINVAL);
10435 	}
10436 
10437 	/*
10438 	 * We have a zero policies, reset the connection policy if already
10439 	 * set. This will cause the connection to inherit the
10440 	 * global policy, if any.
10441 	 */
10442 	if (is_pol_reset) {
10443 		if (connp->conn_policy != NULL) {
10444 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10445 			connp->conn_policy = NULL;
10446 		}
10447 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10448 		connp->conn_in_enforce_policy = B_FALSE;
10449 		connp->conn_out_enforce_policy = B_FALSE;
10450 		mutex_exit(&connp->conn_lock);
10451 		return (0);
10452 	}
10453 
10454 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10455 	    ipst->ips_netstack);
10456 	if (ph == NULL)
10457 		goto enomem;
10458 
10459 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10460 	if (actp == NULL)
10461 		goto enomem;
10462 
10463 	/*
10464 	 * Always allocate IPv4 policy entries, since they can also
10465 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10466 	 */
10467 	bzero(&sel, sizeof (sel));
10468 	sel.ipsl_valid = IPSL_IPV4;
10469 
10470 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10471 	    ipst->ips_netstack);
10472 	if (pin4 == NULL)
10473 		goto enomem;
10474 
10475 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10476 	    ipst->ips_netstack);
10477 	if (pout4 == NULL)
10478 		goto enomem;
10479 
10480 	if (connp->conn_pkt_isv6) {
10481 		/*
10482 		 * We're looking at a v6 socket, also allocate the
10483 		 * v6-specific entries...
10484 		 */
10485 		sel.ipsl_valid = IPSL_IPV6;
10486 		pin6 = ipsec_policy_create(&sel, actp, nact,
10487 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10488 		if (pin6 == NULL)
10489 			goto enomem;
10490 
10491 		pout6 = ipsec_policy_create(&sel, actp, nact,
10492 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10493 		if (pout6 == NULL)
10494 			goto enomem;
10495 
10496 		/*
10497 		 * .. and file them away in the right place.
10498 		 */
10499 		fam = IPSEC_AF_V6;
10500 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10501 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10502 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10503 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10504 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10505 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10506 	}
10507 
10508 	ipsec_actvec_free(actp, nact);
10509 
10510 	/*
10511 	 * File the v4 policies.
10512 	 */
10513 	fam = IPSEC_AF_V4;
10514 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10515 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10516 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10517 
10518 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10519 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10520 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10521 
10522 	/*
10523 	 * If the requests need security, set enforce_policy.
10524 	 * If the requests are IPSEC_PREF_NEVER, one should
10525 	 * still set conn_out_enforce_policy so that an ipsec_out
10526 	 * gets attached in ip_wput. This is needed so that
10527 	 * for connections that we don't cache policy in ip_bind,
10528 	 * if global policy matches in ip_wput_attach_policy, we
10529 	 * don't wrongly inherit global policy. Similarly, we need
10530 	 * to set conn_in_enforce_policy also so that we don't verify
10531 	 * policy wrongly.
10532 	 */
10533 	if ((ah_req & REQ_MASK) != 0 ||
10534 	    (esp_req & REQ_MASK) != 0 ||
10535 	    (se_req & REQ_MASK) != 0) {
10536 		connp->conn_in_enforce_policy = B_TRUE;
10537 		connp->conn_out_enforce_policy = B_TRUE;
10538 		connp->conn_flags |= IPCL_CHECK_POLICY;
10539 	}
10540 
10541 	mutex_exit(&connp->conn_lock);
10542 	return (error);
10543 #undef REQ_MASK
10544 
10545 	/*
10546 	 * Common memory-allocation-failure exit path.
10547 	 */
10548 enomem:
10549 	mutex_exit(&connp->conn_lock);
10550 	if (actp != NULL)
10551 		ipsec_actvec_free(actp, nact);
10552 	if (pin4 != NULL)
10553 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10554 	if (pout4 != NULL)
10555 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10556 	if (pin6 != NULL)
10557 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10558 	if (pout6 != NULL)
10559 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10560 	return (ENOMEM);
10561 }
10562 
10563 /*
10564  * Only for options that pass in an IP addr. Currently only V4 options
10565  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10566  * So this function assumes level is IPPROTO_IP
10567  */
10568 int
10569 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10570     mblk_t *first_mp)
10571 {
10572 	ipif_t *ipif = NULL;
10573 	int error;
10574 	ill_t *ill;
10575 	int zoneid;
10576 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10577 
10578 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10579 
10580 	if (addr != INADDR_ANY || checkonly) {
10581 		ASSERT(connp != NULL);
10582 		zoneid = IPCL_ZONEID(connp);
10583 		if (option == IP_NEXTHOP) {
10584 			ipif = ipif_lookup_onlink_addr(addr,
10585 			    connp->conn_zoneid, ipst);
10586 		} else {
10587 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10588 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10589 			    &error, ipst);
10590 		}
10591 		if (ipif == NULL) {
10592 			if (error == EINPROGRESS)
10593 				return (error);
10594 			else if ((option == IP_MULTICAST_IF) ||
10595 			    (option == IP_NEXTHOP))
10596 				return (EHOSTUNREACH);
10597 			else
10598 				return (EINVAL);
10599 		} else if (checkonly) {
10600 			if (option == IP_MULTICAST_IF) {
10601 				ill = ipif->ipif_ill;
10602 				/* not supported by the virtual network iface */
10603 				if (IS_VNI(ill)) {
10604 					ipif_refrele(ipif);
10605 					return (EINVAL);
10606 				}
10607 			}
10608 			ipif_refrele(ipif);
10609 			return (0);
10610 		}
10611 		ill = ipif->ipif_ill;
10612 		mutex_enter(&connp->conn_lock);
10613 		mutex_enter(&ill->ill_lock);
10614 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10615 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10616 			mutex_exit(&ill->ill_lock);
10617 			mutex_exit(&connp->conn_lock);
10618 			ipif_refrele(ipif);
10619 			return (option == IP_MULTICAST_IF ?
10620 			    EHOSTUNREACH : EINVAL);
10621 		}
10622 	} else {
10623 		mutex_enter(&connp->conn_lock);
10624 	}
10625 
10626 	/* None of the options below are supported on the VNI */
10627 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10628 		mutex_exit(&ill->ill_lock);
10629 		mutex_exit(&connp->conn_lock);
10630 		ipif_refrele(ipif);
10631 		return (EINVAL);
10632 	}
10633 
10634 	switch (option) {
10635 	case IP_DONTFAILOVER_IF:
10636 		/*
10637 		 * This option is used by in.mpathd to ensure
10638 		 * that IPMP probe packets only go out on the
10639 		 * test interfaces. in.mpathd sets this option
10640 		 * on the non-failover interfaces.
10641 		 * For backward compatibility, this option
10642 		 * implicitly sets IP_MULTICAST_IF, as used
10643 		 * be done in bind(), so that ip_wput gets
10644 		 * this ipif to send mcast packets.
10645 		 */
10646 		if (ipif != NULL) {
10647 			ASSERT(addr != INADDR_ANY);
10648 			connp->conn_nofailover_ill = ipif->ipif_ill;
10649 			connp->conn_multicast_ipif = ipif;
10650 		} else {
10651 			ASSERT(addr == INADDR_ANY);
10652 			connp->conn_nofailover_ill = NULL;
10653 			connp->conn_multicast_ipif = NULL;
10654 		}
10655 		break;
10656 
10657 	case IP_MULTICAST_IF:
10658 		connp->conn_multicast_ipif = ipif;
10659 		break;
10660 	case IP_NEXTHOP:
10661 		connp->conn_nexthop_v4 = addr;
10662 		connp->conn_nexthop_set = B_TRUE;
10663 		break;
10664 	}
10665 
10666 	if (ipif != NULL) {
10667 		mutex_exit(&ill->ill_lock);
10668 		mutex_exit(&connp->conn_lock);
10669 		ipif_refrele(ipif);
10670 		return (0);
10671 	}
10672 	mutex_exit(&connp->conn_lock);
10673 	/* We succeded in cleared the option */
10674 	return (0);
10675 }
10676 
10677 /*
10678  * For options that pass in an ifindex specifying the ill. V6 options always
10679  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10680  */
10681 int
10682 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10683     int level, int option, mblk_t *first_mp)
10684 {
10685 	ill_t *ill = NULL;
10686 	int error = 0;
10687 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10688 
10689 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10690 	if (ifindex != 0) {
10691 		ASSERT(connp != NULL);
10692 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10693 		    first_mp, ip_restart_optmgmt, &error, ipst);
10694 		if (ill != NULL) {
10695 			if (checkonly) {
10696 				/* not supported by the virtual network iface */
10697 				if (IS_VNI(ill)) {
10698 					ill_refrele(ill);
10699 					return (EINVAL);
10700 				}
10701 				ill_refrele(ill);
10702 				return (0);
10703 			}
10704 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10705 			    0, NULL)) {
10706 				ill_refrele(ill);
10707 				ill = NULL;
10708 				mutex_enter(&connp->conn_lock);
10709 				goto setit;
10710 			}
10711 			mutex_enter(&connp->conn_lock);
10712 			mutex_enter(&ill->ill_lock);
10713 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10714 				mutex_exit(&ill->ill_lock);
10715 				mutex_exit(&connp->conn_lock);
10716 				ill_refrele(ill);
10717 				ill = NULL;
10718 				mutex_enter(&connp->conn_lock);
10719 			}
10720 			goto setit;
10721 		} else if (error == EINPROGRESS) {
10722 			return (error);
10723 		} else {
10724 			error = 0;
10725 		}
10726 	}
10727 	mutex_enter(&connp->conn_lock);
10728 setit:
10729 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10730 
10731 	/*
10732 	 * The options below assume that the ILL (if any) transmits and/or
10733 	 * receives traffic. Neither of which is true for the virtual network
10734 	 * interface, so fail setting these on a VNI.
10735 	 */
10736 	if (IS_VNI(ill)) {
10737 		ASSERT(ill != NULL);
10738 		mutex_exit(&ill->ill_lock);
10739 		mutex_exit(&connp->conn_lock);
10740 		ill_refrele(ill);
10741 		return (EINVAL);
10742 	}
10743 
10744 	if (level == IPPROTO_IP) {
10745 		switch (option) {
10746 		case IP_BOUND_IF:
10747 			connp->conn_incoming_ill = ill;
10748 			connp->conn_outgoing_ill = ill;
10749 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10750 			    0 : ifindex;
10751 			break;
10752 
10753 		case IP_XMIT_IF:
10754 			/*
10755 			 * Similar to IP_BOUND_IF, but this only
10756 			 * determines the outgoing interface for
10757 			 * unicast packets. Also no IRE_CACHE entry
10758 			 * is added for the destination of the
10759 			 * outgoing packets. This feature is needed
10760 			 * for mobile IP.
10761 			 */
10762 			connp->conn_xmit_if_ill = ill;
10763 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10764 			    0 : ifindex;
10765 			break;
10766 
10767 		case IP_MULTICAST_IF:
10768 			/*
10769 			 * This option is an internal special. The socket
10770 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10771 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10772 			 * specifies an ifindex and we try first on V6 ill's.
10773 			 * If we don't find one, we they try using on v4 ill's
10774 			 * intenally and we come here.
10775 			 */
10776 			if (!checkonly && ill != NULL) {
10777 				ipif_t	*ipif;
10778 				ipif = ill->ill_ipif;
10779 
10780 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10781 					mutex_exit(&ill->ill_lock);
10782 					mutex_exit(&connp->conn_lock);
10783 					ill_refrele(ill);
10784 					ill = NULL;
10785 					mutex_enter(&connp->conn_lock);
10786 				} else {
10787 					connp->conn_multicast_ipif = ipif;
10788 				}
10789 			}
10790 			break;
10791 		}
10792 	} else {
10793 		switch (option) {
10794 		case IPV6_BOUND_IF:
10795 			connp->conn_incoming_ill = ill;
10796 			connp->conn_outgoing_ill = ill;
10797 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10798 			    0 : ifindex;
10799 			break;
10800 
10801 		case IPV6_BOUND_PIF:
10802 			/*
10803 			 * Limit all transmit to this ill.
10804 			 * Unlike IPV6_BOUND_IF, using this option
10805 			 * prevents load spreading and failover from
10806 			 * happening when the interface is part of the
10807 			 * group. That's why we don't need to remember
10808 			 * the ifindex in orig_bound_ifindex as in
10809 			 * IPV6_BOUND_IF.
10810 			 */
10811 			connp->conn_outgoing_pill = ill;
10812 			break;
10813 
10814 		case IPV6_DONTFAILOVER_IF:
10815 			/*
10816 			 * This option is used by in.mpathd to ensure
10817 			 * that IPMP probe packets only go out on the
10818 			 * test interfaces. in.mpathd sets this option
10819 			 * on the non-failover interfaces.
10820 			 */
10821 			connp->conn_nofailover_ill = ill;
10822 			/*
10823 			 * For backward compatibility, this option
10824 			 * implicitly sets ip_multicast_ill as used in
10825 			 * IP_MULTICAST_IF so that ip_wput gets
10826 			 * this ipif to send mcast packets.
10827 			 */
10828 			connp->conn_multicast_ill = ill;
10829 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10830 			    0 : ifindex;
10831 			break;
10832 
10833 		case IPV6_MULTICAST_IF:
10834 			/*
10835 			 * Set conn_multicast_ill to be the IPv6 ill.
10836 			 * Set conn_multicast_ipif to be an IPv4 ipif
10837 			 * for ifindex to make IPv4 mapped addresses
10838 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10839 			 * Even if no IPv6 ill exists for the ifindex
10840 			 * we need to check for an IPv4 ifindex in order
10841 			 * for this to work with mapped addresses. In that
10842 			 * case only set conn_multicast_ipif.
10843 			 */
10844 			if (!checkonly) {
10845 				if (ifindex == 0) {
10846 					connp->conn_multicast_ill = NULL;
10847 					connp->conn_orig_multicast_ifindex = 0;
10848 					connp->conn_multicast_ipif = NULL;
10849 				} else if (ill != NULL) {
10850 					connp->conn_multicast_ill = ill;
10851 					connp->conn_orig_multicast_ifindex =
10852 					    ifindex;
10853 				}
10854 			}
10855 			break;
10856 		}
10857 	}
10858 
10859 	if (ill != NULL) {
10860 		mutex_exit(&ill->ill_lock);
10861 		mutex_exit(&connp->conn_lock);
10862 		ill_refrele(ill);
10863 		return (0);
10864 	}
10865 	mutex_exit(&connp->conn_lock);
10866 	/*
10867 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10868 	 * locate the ill and could not set the option (ifindex != 0)
10869 	 */
10870 	return (ifindex == 0 ? 0 : EINVAL);
10871 }
10872 
10873 /* This routine sets socket options. */
10874 /* ARGSUSED */
10875 int
10876 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10877     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10878     void *dummy, cred_t *cr, mblk_t *first_mp)
10879 {
10880 	int		*i1 = (int *)invalp;
10881 	conn_t		*connp = Q_TO_CONN(q);
10882 	int		error = 0;
10883 	boolean_t	checkonly;
10884 	ire_t		*ire;
10885 	boolean_t	found;
10886 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10887 
10888 	switch (optset_context) {
10889 
10890 	case SETFN_OPTCOM_CHECKONLY:
10891 		checkonly = B_TRUE;
10892 		/*
10893 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10894 		 * inlen != 0 implies value supplied and
10895 		 * 	we have to "pretend" to set it.
10896 		 * inlen == 0 implies that there is no
10897 		 * 	value part in T_CHECK request and just validation
10898 		 * done elsewhere should be enough, we just return here.
10899 		 */
10900 		if (inlen == 0) {
10901 			*outlenp = 0;
10902 			return (0);
10903 		}
10904 		break;
10905 	case SETFN_OPTCOM_NEGOTIATE:
10906 	case SETFN_UD_NEGOTIATE:
10907 	case SETFN_CONN_NEGOTIATE:
10908 		checkonly = B_FALSE;
10909 		break;
10910 	default:
10911 		/*
10912 		 * We should never get here
10913 		 */
10914 		*outlenp = 0;
10915 		return (EINVAL);
10916 	}
10917 
10918 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10919 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10920 
10921 	/*
10922 	 * For fixed length options, no sanity check
10923 	 * of passed in length is done. It is assumed *_optcom_req()
10924 	 * routines do the right thing.
10925 	 */
10926 
10927 	switch (level) {
10928 	case SOL_SOCKET:
10929 		/*
10930 		 * conn_lock protects the bitfields, and is used to
10931 		 * set the fields atomically.
10932 		 */
10933 		switch (name) {
10934 		case SO_BROADCAST:
10935 			if (!checkonly) {
10936 				/* TODO: use value someplace? */
10937 				mutex_enter(&connp->conn_lock);
10938 				connp->conn_broadcast = *i1 ? 1 : 0;
10939 				mutex_exit(&connp->conn_lock);
10940 			}
10941 			break;	/* goto sizeof (int) option return */
10942 		case SO_USELOOPBACK:
10943 			if (!checkonly) {
10944 				/* TODO: use value someplace? */
10945 				mutex_enter(&connp->conn_lock);
10946 				connp->conn_loopback = *i1 ? 1 : 0;
10947 				mutex_exit(&connp->conn_lock);
10948 			}
10949 			break;	/* goto sizeof (int) option return */
10950 		case SO_DONTROUTE:
10951 			if (!checkonly) {
10952 				mutex_enter(&connp->conn_lock);
10953 				connp->conn_dontroute = *i1 ? 1 : 0;
10954 				mutex_exit(&connp->conn_lock);
10955 			}
10956 			break;	/* goto sizeof (int) option return */
10957 		case SO_REUSEADDR:
10958 			if (!checkonly) {
10959 				mutex_enter(&connp->conn_lock);
10960 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10961 				mutex_exit(&connp->conn_lock);
10962 			}
10963 			break;	/* goto sizeof (int) option return */
10964 		case SO_PROTOTYPE:
10965 			if (!checkonly) {
10966 				mutex_enter(&connp->conn_lock);
10967 				connp->conn_proto = *i1;
10968 				mutex_exit(&connp->conn_lock);
10969 			}
10970 			break;	/* goto sizeof (int) option return */
10971 		case SO_ALLZONES:
10972 			if (!checkonly) {
10973 				mutex_enter(&connp->conn_lock);
10974 				if (IPCL_IS_BOUND(connp)) {
10975 					mutex_exit(&connp->conn_lock);
10976 					return (EINVAL);
10977 				}
10978 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10979 				mutex_exit(&connp->conn_lock);
10980 			}
10981 			break;	/* goto sizeof (int) option return */
10982 		case SO_ANON_MLP:
10983 			if (!checkonly) {
10984 				mutex_enter(&connp->conn_lock);
10985 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10986 				mutex_exit(&connp->conn_lock);
10987 			}
10988 			break;	/* goto sizeof (int) option return */
10989 		case SO_MAC_EXEMPT:
10990 			if (secpolicy_net_mac_aware(cr) != 0 ||
10991 			    IPCL_IS_BOUND(connp))
10992 				return (EACCES);
10993 			if (!checkonly) {
10994 				mutex_enter(&connp->conn_lock);
10995 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10996 				mutex_exit(&connp->conn_lock);
10997 			}
10998 			break;	/* goto sizeof (int) option return */
10999 		default:
11000 			/*
11001 			 * "soft" error (negative)
11002 			 * option not handled at this level
11003 			 * Note: Do not modify *outlenp
11004 			 */
11005 			return (-EINVAL);
11006 		}
11007 		break;
11008 	case IPPROTO_IP:
11009 		switch (name) {
11010 		case IP_NEXTHOP:
11011 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
11012 				return (EPERM);
11013 			/* FALLTHRU */
11014 		case IP_MULTICAST_IF:
11015 		case IP_DONTFAILOVER_IF: {
11016 			ipaddr_t addr = *i1;
11017 
11018 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
11019 			    first_mp);
11020 			if (error != 0)
11021 				return (error);
11022 			break;	/* goto sizeof (int) option return */
11023 		}
11024 
11025 		case IP_MULTICAST_TTL:
11026 			/* Recorded in transport above IP */
11027 			*outvalp = *invalp;
11028 			*outlenp = sizeof (uchar_t);
11029 			return (0);
11030 		case IP_MULTICAST_LOOP:
11031 			if (!checkonly) {
11032 				mutex_enter(&connp->conn_lock);
11033 				connp->conn_multicast_loop = *invalp ? 1 : 0;
11034 				mutex_exit(&connp->conn_lock);
11035 			}
11036 			*outvalp = *invalp;
11037 			*outlenp = sizeof (uchar_t);
11038 			return (0);
11039 		case IP_ADD_MEMBERSHIP:
11040 		case MCAST_JOIN_GROUP:
11041 		case IP_DROP_MEMBERSHIP:
11042 		case MCAST_LEAVE_GROUP: {
11043 			struct ip_mreq *mreqp;
11044 			struct group_req *greqp;
11045 			ire_t *ire;
11046 			boolean_t done = B_FALSE;
11047 			ipaddr_t group, ifaddr;
11048 			struct sockaddr_in *sin;
11049 			uint32_t *ifindexp;
11050 			boolean_t mcast_opt = B_TRUE;
11051 			mcast_record_t fmode;
11052 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11053 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11054 
11055 			switch (name) {
11056 			case IP_ADD_MEMBERSHIP:
11057 				mcast_opt = B_FALSE;
11058 				/* FALLTHRU */
11059 			case MCAST_JOIN_GROUP:
11060 				fmode = MODE_IS_EXCLUDE;
11061 				optfn = ip_opt_add_group;
11062 				break;
11063 
11064 			case IP_DROP_MEMBERSHIP:
11065 				mcast_opt = B_FALSE;
11066 				/* FALLTHRU */
11067 			case MCAST_LEAVE_GROUP:
11068 				fmode = MODE_IS_INCLUDE;
11069 				optfn = ip_opt_delete_group;
11070 				break;
11071 			}
11072 
11073 			if (mcast_opt) {
11074 				greqp = (struct group_req *)i1;
11075 				sin = (struct sockaddr_in *)&greqp->gr_group;
11076 				if (sin->sin_family != AF_INET) {
11077 					*outlenp = 0;
11078 					return (ENOPROTOOPT);
11079 				}
11080 				group = (ipaddr_t)sin->sin_addr.s_addr;
11081 				ifaddr = INADDR_ANY;
11082 				ifindexp = &greqp->gr_interface;
11083 			} else {
11084 				mreqp = (struct ip_mreq *)i1;
11085 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
11086 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
11087 				ifindexp = NULL;
11088 			}
11089 
11090 			/*
11091 			 * In the multirouting case, we need to replicate
11092 			 * the request on all interfaces that will take part
11093 			 * in replication.  We do so because multirouting is
11094 			 * reflective, thus we will probably receive multi-
11095 			 * casts on those interfaces.
11096 			 * The ip_multirt_apply_membership() succeeds if the
11097 			 * operation succeeds on at least one interface.
11098 			 */
11099 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
11100 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11101 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11102 			if (ire != NULL) {
11103 				if (ire->ire_flags & RTF_MULTIRT) {
11104 					error = ip_multirt_apply_membership(
11105 					    optfn, ire, connp, checkonly, group,
11106 					    fmode, INADDR_ANY, first_mp);
11107 					done = B_TRUE;
11108 				}
11109 				ire_refrele(ire);
11110 			}
11111 			if (!done) {
11112 				error = optfn(connp, checkonly, group, ifaddr,
11113 				    ifindexp, fmode, INADDR_ANY, first_mp);
11114 			}
11115 			if (error) {
11116 				/*
11117 				 * EINPROGRESS is a soft error, needs retry
11118 				 * so don't make *outlenp zero.
11119 				 */
11120 				if (error != EINPROGRESS)
11121 					*outlenp = 0;
11122 				return (error);
11123 			}
11124 			/* OK return - copy input buffer into output buffer */
11125 			if (invalp != outvalp) {
11126 				/* don't trust bcopy for identical src/dst */
11127 				bcopy(invalp, outvalp, inlen);
11128 			}
11129 			*outlenp = inlen;
11130 			return (0);
11131 		}
11132 		case IP_BLOCK_SOURCE:
11133 		case IP_UNBLOCK_SOURCE:
11134 		case IP_ADD_SOURCE_MEMBERSHIP:
11135 		case IP_DROP_SOURCE_MEMBERSHIP:
11136 		case MCAST_BLOCK_SOURCE:
11137 		case MCAST_UNBLOCK_SOURCE:
11138 		case MCAST_JOIN_SOURCE_GROUP:
11139 		case MCAST_LEAVE_SOURCE_GROUP: {
11140 			struct ip_mreq_source *imreqp;
11141 			struct group_source_req *gsreqp;
11142 			in_addr_t grp, src, ifaddr = INADDR_ANY;
11143 			uint32_t ifindex = 0;
11144 			mcast_record_t fmode;
11145 			struct sockaddr_in *sin;
11146 			ire_t *ire;
11147 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11148 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11149 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11150 
11151 			switch (name) {
11152 			case IP_BLOCK_SOURCE:
11153 				mcast_opt = B_FALSE;
11154 				/* FALLTHRU */
11155 			case MCAST_BLOCK_SOURCE:
11156 				fmode = MODE_IS_EXCLUDE;
11157 				optfn = ip_opt_add_group;
11158 				break;
11159 
11160 			case IP_UNBLOCK_SOURCE:
11161 				mcast_opt = B_FALSE;
11162 				/* FALLTHRU */
11163 			case MCAST_UNBLOCK_SOURCE:
11164 				fmode = MODE_IS_EXCLUDE;
11165 				optfn = ip_opt_delete_group;
11166 				break;
11167 
11168 			case IP_ADD_SOURCE_MEMBERSHIP:
11169 				mcast_opt = B_FALSE;
11170 				/* FALLTHRU */
11171 			case MCAST_JOIN_SOURCE_GROUP:
11172 				fmode = MODE_IS_INCLUDE;
11173 				optfn = ip_opt_add_group;
11174 				break;
11175 
11176 			case IP_DROP_SOURCE_MEMBERSHIP:
11177 				mcast_opt = B_FALSE;
11178 				/* FALLTHRU */
11179 			case MCAST_LEAVE_SOURCE_GROUP:
11180 				fmode = MODE_IS_INCLUDE;
11181 				optfn = ip_opt_delete_group;
11182 				break;
11183 			}
11184 
11185 			if (mcast_opt) {
11186 				gsreqp = (struct group_source_req *)i1;
11187 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11188 					*outlenp = 0;
11189 					return (ENOPROTOOPT);
11190 				}
11191 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11192 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11193 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11194 				src = (ipaddr_t)sin->sin_addr.s_addr;
11195 				ifindex = gsreqp->gsr_interface;
11196 			} else {
11197 				imreqp = (struct ip_mreq_source *)i1;
11198 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11199 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11200 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11201 			}
11202 
11203 			/*
11204 			 * In the multirouting case, we need to replicate
11205 			 * the request as noted in the mcast cases above.
11206 			 */
11207 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11208 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11209 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11210 			if (ire != NULL) {
11211 				if (ire->ire_flags & RTF_MULTIRT) {
11212 					error = ip_multirt_apply_membership(
11213 					    optfn, ire, connp, checkonly, grp,
11214 					    fmode, src, first_mp);
11215 					done = B_TRUE;
11216 				}
11217 				ire_refrele(ire);
11218 			}
11219 			if (!done) {
11220 				error = optfn(connp, checkonly, grp, ifaddr,
11221 				    &ifindex, fmode, src, first_mp);
11222 			}
11223 			if (error != 0) {
11224 				/*
11225 				 * EINPROGRESS is a soft error, needs retry
11226 				 * so don't make *outlenp zero.
11227 				 */
11228 				if (error != EINPROGRESS)
11229 					*outlenp = 0;
11230 				return (error);
11231 			}
11232 			/* OK return - copy input buffer into output buffer */
11233 			if (invalp != outvalp) {
11234 				bcopy(invalp, outvalp, inlen);
11235 			}
11236 			*outlenp = inlen;
11237 			return (0);
11238 		}
11239 		case IP_SEC_OPT:
11240 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11241 			if (error != 0) {
11242 				*outlenp = 0;
11243 				return (error);
11244 			}
11245 			break;
11246 		case IP_HDRINCL:
11247 		case IP_OPTIONS:
11248 		case T_IP_OPTIONS:
11249 		case IP_TOS:
11250 		case T_IP_TOS:
11251 		case IP_TTL:
11252 		case IP_RECVDSTADDR:
11253 		case IP_RECVOPTS:
11254 			/* OK return - copy input buffer into output buffer */
11255 			if (invalp != outvalp) {
11256 				/* don't trust bcopy for identical src/dst */
11257 				bcopy(invalp, outvalp, inlen);
11258 			}
11259 			*outlenp = inlen;
11260 			return (0);
11261 		case IP_RECVIF:
11262 			/* Retrieve the inbound interface index */
11263 			if (!checkonly) {
11264 				mutex_enter(&connp->conn_lock);
11265 				connp->conn_recvif = *i1 ? 1 : 0;
11266 				mutex_exit(&connp->conn_lock);
11267 			}
11268 			break;	/* goto sizeof (int) option return */
11269 		case IP_RECVPKTINFO:
11270 			if (!checkonly) {
11271 				mutex_enter(&connp->conn_lock);
11272 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11273 				mutex_exit(&connp->conn_lock);
11274 			}
11275 			break;	/* goto sizeof (int) option return */
11276 		case IP_RECVSLLA:
11277 			/* Retrieve the source link layer address */
11278 			if (!checkonly) {
11279 				mutex_enter(&connp->conn_lock);
11280 				connp->conn_recvslla = *i1 ? 1 : 0;
11281 				mutex_exit(&connp->conn_lock);
11282 			}
11283 			break;	/* goto sizeof (int) option return */
11284 		case MRT_INIT:
11285 		case MRT_DONE:
11286 		case MRT_ADD_VIF:
11287 		case MRT_DEL_VIF:
11288 		case MRT_ADD_MFC:
11289 		case MRT_DEL_MFC:
11290 		case MRT_ASSERT:
11291 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11292 				*outlenp = 0;
11293 				return (error);
11294 			}
11295 			error = ip_mrouter_set((int)name, q, checkonly,
11296 			    (uchar_t *)invalp, inlen, first_mp);
11297 			if (error) {
11298 				*outlenp = 0;
11299 				return (error);
11300 			}
11301 			/* OK return - copy input buffer into output buffer */
11302 			if (invalp != outvalp) {
11303 				/* don't trust bcopy for identical src/dst */
11304 				bcopy(invalp, outvalp, inlen);
11305 			}
11306 			*outlenp = inlen;
11307 			return (0);
11308 		case IP_BOUND_IF:
11309 		case IP_XMIT_IF:
11310 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11311 			    level, name, first_mp);
11312 			if (error != 0)
11313 				return (error);
11314 			break; 		/* goto sizeof (int) option return */
11315 
11316 		case IP_UNSPEC_SRC:
11317 			/* Allow sending with a zero source address */
11318 			if (!checkonly) {
11319 				mutex_enter(&connp->conn_lock);
11320 				connp->conn_unspec_src = *i1 ? 1 : 0;
11321 				mutex_exit(&connp->conn_lock);
11322 			}
11323 			break;	/* goto sizeof (int) option return */
11324 		default:
11325 			/*
11326 			 * "soft" error (negative)
11327 			 * option not handled at this level
11328 			 * Note: Do not modify *outlenp
11329 			 */
11330 			return (-EINVAL);
11331 		}
11332 		break;
11333 	case IPPROTO_IPV6:
11334 		switch (name) {
11335 		case IPV6_BOUND_IF:
11336 		case IPV6_BOUND_PIF:
11337 		case IPV6_DONTFAILOVER_IF:
11338 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11339 			    level, name, first_mp);
11340 			if (error != 0)
11341 				return (error);
11342 			break; 		/* goto sizeof (int) option return */
11343 
11344 		case IPV6_MULTICAST_IF:
11345 			/*
11346 			 * The only possible errors are EINPROGRESS and
11347 			 * EINVAL. EINPROGRESS will be restarted and is not
11348 			 * a hard error. We call this option on both V4 and V6
11349 			 * If both return EINVAL, then this call returns
11350 			 * EINVAL. If at least one of them succeeds we
11351 			 * return success.
11352 			 */
11353 			found = B_FALSE;
11354 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11355 			    level, name, first_mp);
11356 			if (error == EINPROGRESS)
11357 				return (error);
11358 			if (error == 0)
11359 				found = B_TRUE;
11360 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11361 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11362 			if (error == 0)
11363 				found = B_TRUE;
11364 			if (!found)
11365 				return (error);
11366 			break; 		/* goto sizeof (int) option return */
11367 
11368 		case IPV6_MULTICAST_HOPS:
11369 			/* Recorded in transport above IP */
11370 			break;	/* goto sizeof (int) option return */
11371 		case IPV6_MULTICAST_LOOP:
11372 			if (!checkonly) {
11373 				mutex_enter(&connp->conn_lock);
11374 				connp->conn_multicast_loop = *i1;
11375 				mutex_exit(&connp->conn_lock);
11376 			}
11377 			break;	/* goto sizeof (int) option return */
11378 		case IPV6_JOIN_GROUP:
11379 		case MCAST_JOIN_GROUP:
11380 		case IPV6_LEAVE_GROUP:
11381 		case MCAST_LEAVE_GROUP: {
11382 			struct ipv6_mreq *ip_mreqp;
11383 			struct group_req *greqp;
11384 			ire_t *ire;
11385 			boolean_t done = B_FALSE;
11386 			in6_addr_t groupv6;
11387 			uint32_t ifindex;
11388 			boolean_t mcast_opt = B_TRUE;
11389 			mcast_record_t fmode;
11390 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11391 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11392 
11393 			switch (name) {
11394 			case IPV6_JOIN_GROUP:
11395 				mcast_opt = B_FALSE;
11396 				/* FALLTHRU */
11397 			case MCAST_JOIN_GROUP:
11398 				fmode = MODE_IS_EXCLUDE;
11399 				optfn = ip_opt_add_group_v6;
11400 				break;
11401 
11402 			case IPV6_LEAVE_GROUP:
11403 				mcast_opt = B_FALSE;
11404 				/* FALLTHRU */
11405 			case MCAST_LEAVE_GROUP:
11406 				fmode = MODE_IS_INCLUDE;
11407 				optfn = ip_opt_delete_group_v6;
11408 				break;
11409 			}
11410 
11411 			if (mcast_opt) {
11412 				struct sockaddr_in *sin;
11413 				struct sockaddr_in6 *sin6;
11414 				greqp = (struct group_req *)i1;
11415 				if (greqp->gr_group.ss_family == AF_INET) {
11416 					sin = (struct sockaddr_in *)
11417 					    &(greqp->gr_group);
11418 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11419 					    &groupv6);
11420 				} else {
11421 					sin6 = (struct sockaddr_in6 *)
11422 					    &(greqp->gr_group);
11423 					groupv6 = sin6->sin6_addr;
11424 				}
11425 				ifindex = greqp->gr_interface;
11426 			} else {
11427 				ip_mreqp = (struct ipv6_mreq *)i1;
11428 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11429 				ifindex = ip_mreqp->ipv6mr_interface;
11430 			}
11431 			/*
11432 			 * In the multirouting case, we need to replicate
11433 			 * the request on all interfaces that will take part
11434 			 * in replication.  We do so because multirouting is
11435 			 * reflective, thus we will probably receive multi-
11436 			 * casts on those interfaces.
11437 			 * The ip_multirt_apply_membership_v6() succeeds if
11438 			 * the operation succeeds on at least one interface.
11439 			 */
11440 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11441 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11442 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11443 			if (ire != NULL) {
11444 				if (ire->ire_flags & RTF_MULTIRT) {
11445 					error = ip_multirt_apply_membership_v6(
11446 					    optfn, ire, connp, checkonly,
11447 					    &groupv6, fmode, &ipv6_all_zeros,
11448 					    first_mp);
11449 					done = B_TRUE;
11450 				}
11451 				ire_refrele(ire);
11452 			}
11453 			if (!done) {
11454 				error = optfn(connp, checkonly, &groupv6,
11455 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11456 			}
11457 			if (error) {
11458 				/*
11459 				 * EINPROGRESS is a soft error, needs retry
11460 				 * so don't make *outlenp zero.
11461 				 */
11462 				if (error != EINPROGRESS)
11463 					*outlenp = 0;
11464 				return (error);
11465 			}
11466 			/* OK return - copy input buffer into output buffer */
11467 			if (invalp != outvalp) {
11468 				/* don't trust bcopy for identical src/dst */
11469 				bcopy(invalp, outvalp, inlen);
11470 			}
11471 			*outlenp = inlen;
11472 			return (0);
11473 		}
11474 		case MCAST_BLOCK_SOURCE:
11475 		case MCAST_UNBLOCK_SOURCE:
11476 		case MCAST_JOIN_SOURCE_GROUP:
11477 		case MCAST_LEAVE_SOURCE_GROUP: {
11478 			struct group_source_req *gsreqp;
11479 			in6_addr_t v6grp, v6src;
11480 			uint32_t ifindex;
11481 			mcast_record_t fmode;
11482 			ire_t *ire;
11483 			boolean_t done = B_FALSE;
11484 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11485 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11486 
11487 			switch (name) {
11488 			case MCAST_BLOCK_SOURCE:
11489 				fmode = MODE_IS_EXCLUDE;
11490 				optfn = ip_opt_add_group_v6;
11491 				break;
11492 			case MCAST_UNBLOCK_SOURCE:
11493 				fmode = MODE_IS_EXCLUDE;
11494 				optfn = ip_opt_delete_group_v6;
11495 				break;
11496 			case MCAST_JOIN_SOURCE_GROUP:
11497 				fmode = MODE_IS_INCLUDE;
11498 				optfn = ip_opt_add_group_v6;
11499 				break;
11500 			case MCAST_LEAVE_SOURCE_GROUP:
11501 				fmode = MODE_IS_INCLUDE;
11502 				optfn = ip_opt_delete_group_v6;
11503 				break;
11504 			}
11505 
11506 			gsreqp = (struct group_source_req *)i1;
11507 			ifindex = gsreqp->gsr_interface;
11508 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11509 				struct sockaddr_in *s;
11510 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11511 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11512 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11513 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11514 			} else {
11515 				struct sockaddr_in6 *s6;
11516 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11517 				v6grp = s6->sin6_addr;
11518 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11519 				v6src = s6->sin6_addr;
11520 			}
11521 
11522 			/*
11523 			 * In the multirouting case, we need to replicate
11524 			 * the request as noted in the mcast cases above.
11525 			 */
11526 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11527 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11528 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11529 			if (ire != NULL) {
11530 				if (ire->ire_flags & RTF_MULTIRT) {
11531 					error = ip_multirt_apply_membership_v6(
11532 					    optfn, ire, connp, checkonly,
11533 					    &v6grp, fmode, &v6src, first_mp);
11534 					done = B_TRUE;
11535 				}
11536 				ire_refrele(ire);
11537 			}
11538 			if (!done) {
11539 				error = optfn(connp, checkonly, &v6grp,
11540 				    ifindex, fmode, &v6src, first_mp);
11541 			}
11542 			if (error != 0) {
11543 				/*
11544 				 * EINPROGRESS is a soft error, needs retry
11545 				 * so don't make *outlenp zero.
11546 				 */
11547 				if (error != EINPROGRESS)
11548 					*outlenp = 0;
11549 				return (error);
11550 			}
11551 			/* OK return - copy input buffer into output buffer */
11552 			if (invalp != outvalp) {
11553 				bcopy(invalp, outvalp, inlen);
11554 			}
11555 			*outlenp = inlen;
11556 			return (0);
11557 		}
11558 		case IPV6_UNICAST_HOPS:
11559 			/* Recorded in transport above IP */
11560 			break;	/* goto sizeof (int) option return */
11561 		case IPV6_UNSPEC_SRC:
11562 			/* Allow sending with a zero source address */
11563 			if (!checkonly) {
11564 				mutex_enter(&connp->conn_lock);
11565 				connp->conn_unspec_src = *i1 ? 1 : 0;
11566 				mutex_exit(&connp->conn_lock);
11567 			}
11568 			break;	/* goto sizeof (int) option return */
11569 		case IPV6_RECVPKTINFO:
11570 			if (!checkonly) {
11571 				mutex_enter(&connp->conn_lock);
11572 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11573 				mutex_exit(&connp->conn_lock);
11574 			}
11575 			break;	/* goto sizeof (int) option return */
11576 		case IPV6_RECVTCLASS:
11577 			if (!checkonly) {
11578 				if (*i1 < 0 || *i1 > 1) {
11579 					return (EINVAL);
11580 				}
11581 				mutex_enter(&connp->conn_lock);
11582 				connp->conn_ipv6_recvtclass = *i1;
11583 				mutex_exit(&connp->conn_lock);
11584 			}
11585 			break;
11586 		case IPV6_RECVPATHMTU:
11587 			if (!checkonly) {
11588 				if (*i1 < 0 || *i1 > 1) {
11589 					return (EINVAL);
11590 				}
11591 				mutex_enter(&connp->conn_lock);
11592 				connp->conn_ipv6_recvpathmtu = *i1;
11593 				mutex_exit(&connp->conn_lock);
11594 			}
11595 			break;
11596 		case IPV6_RECVHOPLIMIT:
11597 			if (!checkonly) {
11598 				mutex_enter(&connp->conn_lock);
11599 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11600 				mutex_exit(&connp->conn_lock);
11601 			}
11602 			break;	/* goto sizeof (int) option return */
11603 		case IPV6_RECVHOPOPTS:
11604 			if (!checkonly) {
11605 				mutex_enter(&connp->conn_lock);
11606 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11607 				mutex_exit(&connp->conn_lock);
11608 			}
11609 			break;	/* goto sizeof (int) option return */
11610 		case IPV6_RECVDSTOPTS:
11611 			if (!checkonly) {
11612 				mutex_enter(&connp->conn_lock);
11613 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11614 				mutex_exit(&connp->conn_lock);
11615 			}
11616 			break;	/* goto sizeof (int) option return */
11617 		case IPV6_RECVRTHDR:
11618 			if (!checkonly) {
11619 				mutex_enter(&connp->conn_lock);
11620 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11621 				mutex_exit(&connp->conn_lock);
11622 			}
11623 			break;	/* goto sizeof (int) option return */
11624 		case IPV6_RECVRTHDRDSTOPTS:
11625 			if (!checkonly) {
11626 				mutex_enter(&connp->conn_lock);
11627 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11628 				mutex_exit(&connp->conn_lock);
11629 			}
11630 			break;	/* goto sizeof (int) option return */
11631 		case IPV6_PKTINFO:
11632 			if (inlen == 0)
11633 				return (-EINVAL);	/* clearing option */
11634 			error = ip6_set_pktinfo(cr, connp,
11635 			    (struct in6_pktinfo *)invalp, first_mp);
11636 			if (error != 0)
11637 				*outlenp = 0;
11638 			else
11639 				*outlenp = inlen;
11640 			return (error);
11641 		case IPV6_NEXTHOP: {
11642 			struct sockaddr_in6 *sin6;
11643 
11644 			/* Verify that the nexthop is reachable */
11645 			if (inlen == 0)
11646 				return (-EINVAL);	/* clearing option */
11647 
11648 			sin6 = (struct sockaddr_in6 *)invalp;
11649 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11650 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11651 			    NULL, MATCH_IRE_DEFAULT, ipst);
11652 
11653 			if (ire == NULL) {
11654 				*outlenp = 0;
11655 				return (EHOSTUNREACH);
11656 			}
11657 			ire_refrele(ire);
11658 			return (-EINVAL);
11659 		}
11660 		case IPV6_SEC_OPT:
11661 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11662 			if (error != 0) {
11663 				*outlenp = 0;
11664 				return (error);
11665 			}
11666 			break;
11667 		case IPV6_SRC_PREFERENCES: {
11668 			/*
11669 			 * This is implemented strictly in the ip module
11670 			 * (here and in tcp_opt_*() to accomodate tcp
11671 			 * sockets).  Modules above ip pass this option
11672 			 * down here since ip is the only one that needs to
11673 			 * be aware of source address preferences.
11674 			 *
11675 			 * This socket option only affects connected
11676 			 * sockets that haven't already bound to a specific
11677 			 * IPv6 address.  In other words, sockets that
11678 			 * don't call bind() with an address other than the
11679 			 * unspecified address and that call connect().
11680 			 * ip_bind_connected_v6() passes these preferences
11681 			 * to the ipif_select_source_v6() function.
11682 			 */
11683 			if (inlen != sizeof (uint32_t))
11684 				return (EINVAL);
11685 			error = ip6_set_src_preferences(connp,
11686 			    *(uint32_t *)invalp);
11687 			if (error != 0) {
11688 				*outlenp = 0;
11689 				return (error);
11690 			} else {
11691 				*outlenp = sizeof (uint32_t);
11692 			}
11693 			break;
11694 		}
11695 		case IPV6_V6ONLY:
11696 			if (*i1 < 0 || *i1 > 1) {
11697 				return (EINVAL);
11698 			}
11699 			mutex_enter(&connp->conn_lock);
11700 			connp->conn_ipv6_v6only = *i1;
11701 			mutex_exit(&connp->conn_lock);
11702 			break;
11703 		default:
11704 			return (-EINVAL);
11705 		}
11706 		break;
11707 	default:
11708 		/*
11709 		 * "soft" error (negative)
11710 		 * option not handled at this level
11711 		 * Note: Do not modify *outlenp
11712 		 */
11713 		return (-EINVAL);
11714 	}
11715 	/*
11716 	 * Common case of return from an option that is sizeof (int)
11717 	 */
11718 	*(int *)outvalp = *i1;
11719 	*outlenp = sizeof (int);
11720 	return (0);
11721 }
11722 
11723 /*
11724  * This routine gets default values of certain options whose default
11725  * values are maintained by protocol specific code
11726  */
11727 /* ARGSUSED */
11728 int
11729 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11730 {
11731 	int *i1 = (int *)ptr;
11732 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11733 
11734 	switch (level) {
11735 	case IPPROTO_IP:
11736 		switch (name) {
11737 		case IP_MULTICAST_TTL:
11738 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11739 			return (sizeof (uchar_t));
11740 		case IP_MULTICAST_LOOP:
11741 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11742 			return (sizeof (uchar_t));
11743 		default:
11744 			return (-1);
11745 		}
11746 	case IPPROTO_IPV6:
11747 		switch (name) {
11748 		case IPV6_UNICAST_HOPS:
11749 			*i1 = ipst->ips_ipv6_def_hops;
11750 			return (sizeof (int));
11751 		case IPV6_MULTICAST_HOPS:
11752 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11753 			return (sizeof (int));
11754 		case IPV6_MULTICAST_LOOP:
11755 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11756 			return (sizeof (int));
11757 		case IPV6_V6ONLY:
11758 			*i1 = 1;
11759 			return (sizeof (int));
11760 		default:
11761 			return (-1);
11762 		}
11763 	default:
11764 		return (-1);
11765 	}
11766 	/* NOTREACHED */
11767 }
11768 
11769 /*
11770  * Given a destination address and a pointer to where to put the information
11771  * this routine fills in the mtuinfo.
11772  */
11773 int
11774 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11775     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11776 {
11777 	ire_t *ire;
11778 	ip_stack_t	*ipst = ns->netstack_ip;
11779 
11780 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11781 		return (-1);
11782 
11783 	bzero(mtuinfo, sizeof (*mtuinfo));
11784 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11785 	mtuinfo->ip6m_addr.sin6_port = port;
11786 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11787 
11788 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11789 	if (ire != NULL) {
11790 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11791 		ire_refrele(ire);
11792 	} else {
11793 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11794 	}
11795 	return (sizeof (struct ip6_mtuinfo));
11796 }
11797 
11798 /*
11799  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11800  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11801  * isn't.  This doesn't matter as the error checking is done properly for the
11802  * other MRT options coming in through ip_opt_set.
11803  */
11804 int
11805 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11806 {
11807 	conn_t		*connp = Q_TO_CONN(q);
11808 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11809 
11810 	switch (level) {
11811 	case IPPROTO_IP:
11812 		switch (name) {
11813 		case MRT_VERSION:
11814 		case MRT_ASSERT:
11815 			(void) ip_mrouter_get(name, q, ptr);
11816 			return (sizeof (int));
11817 		case IP_SEC_OPT:
11818 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11819 		case IP_NEXTHOP:
11820 			if (connp->conn_nexthop_set) {
11821 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11822 				return (sizeof (ipaddr_t));
11823 			} else
11824 				return (0);
11825 		case IP_RECVPKTINFO:
11826 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11827 			return (sizeof (int));
11828 		default:
11829 			break;
11830 		}
11831 		break;
11832 	case IPPROTO_IPV6:
11833 		switch (name) {
11834 		case IPV6_SEC_OPT:
11835 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11836 		case IPV6_SRC_PREFERENCES: {
11837 			return (ip6_get_src_preferences(connp,
11838 			    (uint32_t *)ptr));
11839 		}
11840 		case IPV6_V6ONLY:
11841 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11842 			return (sizeof (int));
11843 		case IPV6_PATHMTU:
11844 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11845 				(struct ip6_mtuinfo *)ptr,
11846 				connp->conn_netstack));
11847 		default:
11848 			break;
11849 		}
11850 		break;
11851 	default:
11852 		break;
11853 	}
11854 	return (-1);
11855 }
11856 
11857 /* Named Dispatch routine to get a current value out of our parameter table. */
11858 /* ARGSUSED */
11859 static int
11860 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11861 {
11862 	ipparam_t *ippa = (ipparam_t *)cp;
11863 
11864 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11865 	return (0);
11866 }
11867 
11868 /* ARGSUSED */
11869 static int
11870 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11871 {
11872 
11873 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11874 	return (0);
11875 }
11876 
11877 /*
11878  * Set ip{,6}_forwarding values.  This means walking through all of the
11879  * ill's and toggling their forwarding values.
11880  */
11881 /* ARGSUSED */
11882 static int
11883 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11884 {
11885 	long new_value;
11886 	int *forwarding_value = (int *)cp;
11887 	ill_t *walker;
11888 	boolean_t isv6;
11889 	ill_walk_context_t ctx;
11890 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11891 
11892 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11893 
11894 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11895 	    new_value < 0 || new_value > 1) {
11896 		return (EINVAL);
11897 	}
11898 
11899 	*forwarding_value = new_value;
11900 
11901 	/*
11902 	 * Regardless of the current value of ip_forwarding, set all per-ill
11903 	 * values of ip_forwarding to the value being set.
11904 	 *
11905 	 * Bring all the ill's up to date with the new global value.
11906 	 */
11907 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11908 
11909 	if (isv6)
11910 		walker = ILL_START_WALK_V6(&ctx, ipst);
11911 	else
11912 		walker = ILL_START_WALK_V4(&ctx, ipst);
11913 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11914 		(void) ill_forward_set(q, mp, (new_value != 0),
11915 		    (caddr_t)walker);
11916 	}
11917 	rw_exit(&ipst->ips_ill_g_lock);
11918 
11919 	return (0);
11920 }
11921 
11922 /*
11923  * Walk through the param array specified registering each element with the
11924  * Named Dispatch handler. This is called only during init. So it is ok
11925  * not to acquire any locks
11926  */
11927 static boolean_t
11928 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11929     ipndp_t *ipnd, size_t ipnd_cnt)
11930 {
11931 	for (; ippa_cnt-- > 0; ippa++) {
11932 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11933 			if (!nd_load(ndp, ippa->ip_param_name,
11934 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11935 				nd_free(ndp);
11936 				return (B_FALSE);
11937 			}
11938 		}
11939 	}
11940 
11941 	for (; ipnd_cnt-- > 0; ipnd++) {
11942 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11943 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11944 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11945 			    ipnd->ip_ndp_data)) {
11946 				nd_free(ndp);
11947 				return (B_FALSE);
11948 			}
11949 		}
11950 	}
11951 
11952 	return (B_TRUE);
11953 }
11954 
11955 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11956 /* ARGSUSED */
11957 static int
11958 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11959 {
11960 	long		new_value;
11961 	ipparam_t	*ippa = (ipparam_t *)cp;
11962 
11963 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11964 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11965 		return (EINVAL);
11966 	}
11967 	ippa->ip_param_value = new_value;
11968 	return (0);
11969 }
11970 
11971 /*
11972  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11973  * When an ipf is passed here for the first time, if
11974  * we already have in-order fragments on the queue, we convert from the fast-
11975  * path reassembly scheme to the hard-case scheme.  From then on, additional
11976  * fragments are reassembled here.  We keep track of the start and end offsets
11977  * of each piece, and the number of holes in the chain.  When the hole count
11978  * goes to zero, we are done!
11979  *
11980  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11981  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11982  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11983  * after the call to ip_reassemble().
11984  */
11985 int
11986 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11987     size_t msg_len)
11988 {
11989 	uint_t	end;
11990 	mblk_t	*next_mp;
11991 	mblk_t	*mp1;
11992 	uint_t	offset;
11993 	boolean_t incr_dups = B_TRUE;
11994 	boolean_t offset_zero_seen = B_FALSE;
11995 	boolean_t pkt_boundary_checked = B_FALSE;
11996 
11997 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11998 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11999 
12000 	/* Add in byte count */
12001 	ipf->ipf_count += msg_len;
12002 	if (ipf->ipf_end) {
12003 		/*
12004 		 * We were part way through in-order reassembly, but now there
12005 		 * is a hole.  We walk through messages already queued, and
12006 		 * mark them for hard case reassembly.  We know that up till
12007 		 * now they were in order starting from offset zero.
12008 		 */
12009 		offset = 0;
12010 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12011 			IP_REASS_SET_START(mp1, offset);
12012 			if (offset == 0) {
12013 				ASSERT(ipf->ipf_nf_hdr_len != 0);
12014 				offset = -ipf->ipf_nf_hdr_len;
12015 			}
12016 			offset += mp1->b_wptr - mp1->b_rptr;
12017 			IP_REASS_SET_END(mp1, offset);
12018 		}
12019 		/* One hole at the end. */
12020 		ipf->ipf_hole_cnt = 1;
12021 		/* Brand it as a hard case, forever. */
12022 		ipf->ipf_end = 0;
12023 	}
12024 	/* Walk through all the new pieces. */
12025 	do {
12026 		end = start + (mp->b_wptr - mp->b_rptr);
12027 		/*
12028 		 * If start is 0, decrease 'end' only for the first mblk of
12029 		 * the fragment. Otherwise 'end' can get wrong value in the
12030 		 * second pass of the loop if first mblk is exactly the
12031 		 * size of ipf_nf_hdr_len.
12032 		 */
12033 		if (start == 0 && !offset_zero_seen) {
12034 			/* First segment */
12035 			ASSERT(ipf->ipf_nf_hdr_len != 0);
12036 			end -= ipf->ipf_nf_hdr_len;
12037 			offset_zero_seen = B_TRUE;
12038 		}
12039 		next_mp = mp->b_cont;
12040 		/*
12041 		 * We are checking to see if there is any interesing data
12042 		 * to process.  If there isn't and the mblk isn't the
12043 		 * one which carries the unfragmentable header then we
12044 		 * drop it.  It's possible to have just the unfragmentable
12045 		 * header come through without any data.  That needs to be
12046 		 * saved.
12047 		 *
12048 		 * If the assert at the top of this function holds then the
12049 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
12050 		 * is infrequently traveled enough that the test is left in
12051 		 * to protect against future code changes which break that
12052 		 * invariant.
12053 		 */
12054 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
12055 			/* Empty.  Blast it. */
12056 			IP_REASS_SET_START(mp, 0);
12057 			IP_REASS_SET_END(mp, 0);
12058 			/*
12059 			 * If the ipf points to the mblk we are about to free,
12060 			 * update ipf to point to the next mblk (or NULL
12061 			 * if none).
12062 			 */
12063 			if (ipf->ipf_mp->b_cont == mp)
12064 				ipf->ipf_mp->b_cont = next_mp;
12065 			freeb(mp);
12066 			continue;
12067 		}
12068 		mp->b_cont = NULL;
12069 		IP_REASS_SET_START(mp, start);
12070 		IP_REASS_SET_END(mp, end);
12071 		if (!ipf->ipf_tail_mp) {
12072 			ipf->ipf_tail_mp = mp;
12073 			ipf->ipf_mp->b_cont = mp;
12074 			if (start == 0 || !more) {
12075 				ipf->ipf_hole_cnt = 1;
12076 				/*
12077 				 * if the first fragment comes in more than one
12078 				 * mblk, this loop will be executed for each
12079 				 * mblk. Need to adjust hole count so exiting
12080 				 * this routine will leave hole count at 1.
12081 				 */
12082 				if (next_mp)
12083 					ipf->ipf_hole_cnt++;
12084 			} else
12085 				ipf->ipf_hole_cnt = 2;
12086 			continue;
12087 		} else if (ipf->ipf_last_frag_seen && !more &&
12088 			    !pkt_boundary_checked) {
12089 			/*
12090 			 * We check datagram boundary only if this fragment
12091 			 * claims to be the last fragment and we have seen a
12092 			 * last fragment in the past too. We do this only
12093 			 * once for a given fragment.
12094 			 *
12095 			 * start cannot be 0 here as fragments with start=0
12096 			 * and MF=0 gets handled as a complete packet. These
12097 			 * fragments should not reach here.
12098 			 */
12099 
12100 			if (start + msgdsize(mp) !=
12101 			    IP_REASS_END(ipf->ipf_tail_mp)) {
12102 				/*
12103 				 * We have two fragments both of which claim
12104 				 * to be the last fragment but gives conflicting
12105 				 * information about the whole datagram size.
12106 				 * Something fishy is going on. Drop the
12107 				 * fragment and free up the reassembly list.
12108 				 */
12109 				return (IP_REASS_FAILED);
12110 			}
12111 
12112 			/*
12113 			 * We shouldn't come to this code block again for this
12114 			 * particular fragment.
12115 			 */
12116 			pkt_boundary_checked = B_TRUE;
12117 		}
12118 
12119 		/* New stuff at or beyond tail? */
12120 		offset = IP_REASS_END(ipf->ipf_tail_mp);
12121 		if (start >= offset) {
12122 			if (ipf->ipf_last_frag_seen) {
12123 				/* current fragment is beyond last fragment */
12124 				return (IP_REASS_FAILED);
12125 			}
12126 			/* Link it on end. */
12127 			ipf->ipf_tail_mp->b_cont = mp;
12128 			ipf->ipf_tail_mp = mp;
12129 			if (more) {
12130 				if (start != offset)
12131 					ipf->ipf_hole_cnt++;
12132 			} else if (start == offset && next_mp == NULL)
12133 					ipf->ipf_hole_cnt--;
12134 			continue;
12135 		}
12136 		mp1 = ipf->ipf_mp->b_cont;
12137 		offset = IP_REASS_START(mp1);
12138 		/* New stuff at the front? */
12139 		if (start < offset) {
12140 			if (start == 0) {
12141 				if (end >= offset) {
12142 					/* Nailed the hole at the begining. */
12143 					ipf->ipf_hole_cnt--;
12144 				}
12145 			} else if (end < offset) {
12146 				/*
12147 				 * A hole, stuff, and a hole where there used
12148 				 * to be just a hole.
12149 				 */
12150 				ipf->ipf_hole_cnt++;
12151 			}
12152 			mp->b_cont = mp1;
12153 			/* Check for overlap. */
12154 			while (end > offset) {
12155 				if (end < IP_REASS_END(mp1)) {
12156 					mp->b_wptr -= end - offset;
12157 					IP_REASS_SET_END(mp, offset);
12158 					BUMP_MIB(ill->ill_ip_mib,
12159 					    ipIfStatsReasmPartDups);
12160 					break;
12161 				}
12162 				/* Did we cover another hole? */
12163 				if ((mp1->b_cont &&
12164 				    IP_REASS_END(mp1) !=
12165 				    IP_REASS_START(mp1->b_cont) &&
12166 				    end >= IP_REASS_START(mp1->b_cont)) ||
12167 				    (!ipf->ipf_last_frag_seen && !more)) {
12168 					ipf->ipf_hole_cnt--;
12169 				}
12170 				/* Clip out mp1. */
12171 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12172 					/*
12173 					 * After clipping out mp1, this guy
12174 					 * is now hanging off the end.
12175 					 */
12176 					ipf->ipf_tail_mp = mp;
12177 				}
12178 				IP_REASS_SET_START(mp1, 0);
12179 				IP_REASS_SET_END(mp1, 0);
12180 				/* Subtract byte count */
12181 				ipf->ipf_count -= mp1->b_datap->db_lim -
12182 				    mp1->b_datap->db_base;
12183 				freeb(mp1);
12184 				BUMP_MIB(ill->ill_ip_mib,
12185 				    ipIfStatsReasmPartDups);
12186 				mp1 = mp->b_cont;
12187 				if (!mp1)
12188 					break;
12189 				offset = IP_REASS_START(mp1);
12190 			}
12191 			ipf->ipf_mp->b_cont = mp;
12192 			continue;
12193 		}
12194 		/*
12195 		 * The new piece starts somewhere between the start of the head
12196 		 * and before the end of the tail.
12197 		 */
12198 		for (; mp1; mp1 = mp1->b_cont) {
12199 			offset = IP_REASS_END(mp1);
12200 			if (start < offset) {
12201 				if (end <= offset) {
12202 					/* Nothing new. */
12203 					IP_REASS_SET_START(mp, 0);
12204 					IP_REASS_SET_END(mp, 0);
12205 					/* Subtract byte count */
12206 					ipf->ipf_count -= mp->b_datap->db_lim -
12207 					    mp->b_datap->db_base;
12208 					if (incr_dups) {
12209 						ipf->ipf_num_dups++;
12210 						incr_dups = B_FALSE;
12211 					}
12212 					freeb(mp);
12213 					BUMP_MIB(ill->ill_ip_mib,
12214 					    ipIfStatsReasmDuplicates);
12215 					break;
12216 				}
12217 				/*
12218 				 * Trim redundant stuff off beginning of new
12219 				 * piece.
12220 				 */
12221 				IP_REASS_SET_START(mp, offset);
12222 				mp->b_rptr += offset - start;
12223 				BUMP_MIB(ill->ill_ip_mib,
12224 				    ipIfStatsReasmPartDups);
12225 				start = offset;
12226 				if (!mp1->b_cont) {
12227 					/*
12228 					 * After trimming, this guy is now
12229 					 * hanging off the end.
12230 					 */
12231 					mp1->b_cont = mp;
12232 					ipf->ipf_tail_mp = mp;
12233 					if (!more) {
12234 						ipf->ipf_hole_cnt--;
12235 					}
12236 					break;
12237 				}
12238 			}
12239 			if (start >= IP_REASS_START(mp1->b_cont))
12240 				continue;
12241 			/* Fill a hole */
12242 			if (start > offset)
12243 				ipf->ipf_hole_cnt++;
12244 			mp->b_cont = mp1->b_cont;
12245 			mp1->b_cont = mp;
12246 			mp1 = mp->b_cont;
12247 			offset = IP_REASS_START(mp1);
12248 			if (end >= offset) {
12249 				ipf->ipf_hole_cnt--;
12250 				/* Check for overlap. */
12251 				while (end > offset) {
12252 					if (end < IP_REASS_END(mp1)) {
12253 						mp->b_wptr -= end - offset;
12254 						IP_REASS_SET_END(mp, offset);
12255 						/*
12256 						 * TODO we might bump
12257 						 * this up twice if there is
12258 						 * overlap at both ends.
12259 						 */
12260 						BUMP_MIB(ill->ill_ip_mib,
12261 						    ipIfStatsReasmPartDups);
12262 						break;
12263 					}
12264 					/* Did we cover another hole? */
12265 					if ((mp1->b_cont &&
12266 					    IP_REASS_END(mp1)
12267 					    != IP_REASS_START(mp1->b_cont) &&
12268 					    end >=
12269 					    IP_REASS_START(mp1->b_cont)) ||
12270 					    (!ipf->ipf_last_frag_seen &&
12271 					    !more)) {
12272 						ipf->ipf_hole_cnt--;
12273 					}
12274 					/* Clip out mp1. */
12275 					if ((mp->b_cont = mp1->b_cont) ==
12276 					    NULL) {
12277 						/*
12278 						 * After clipping out mp1,
12279 						 * this guy is now hanging
12280 						 * off the end.
12281 						 */
12282 						ipf->ipf_tail_mp = mp;
12283 					}
12284 					IP_REASS_SET_START(mp1, 0);
12285 					IP_REASS_SET_END(mp1, 0);
12286 					/* Subtract byte count */
12287 					ipf->ipf_count -=
12288 					    mp1->b_datap->db_lim -
12289 					    mp1->b_datap->db_base;
12290 					freeb(mp1);
12291 					BUMP_MIB(ill->ill_ip_mib,
12292 					    ipIfStatsReasmPartDups);
12293 					mp1 = mp->b_cont;
12294 					if (!mp1)
12295 						break;
12296 					offset = IP_REASS_START(mp1);
12297 				}
12298 			}
12299 			break;
12300 		}
12301 	} while (start = end, mp = next_mp);
12302 
12303 	/* Fragment just processed could be the last one. Remember this fact */
12304 	if (!more)
12305 		ipf->ipf_last_frag_seen = B_TRUE;
12306 
12307 	/* Still got holes? */
12308 	if (ipf->ipf_hole_cnt)
12309 		return (IP_REASS_PARTIAL);
12310 	/* Clean up overloaded fields to avoid upstream disasters. */
12311 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12312 		IP_REASS_SET_START(mp1, 0);
12313 		IP_REASS_SET_END(mp1, 0);
12314 	}
12315 	return (IP_REASS_COMPLETE);
12316 }
12317 
12318 /*
12319  * ipsec processing for the fast path, used for input UDP Packets
12320  */
12321 static boolean_t
12322 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12323     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12324 {
12325 	uint32_t	ill_index;
12326 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12327 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12328 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12329 
12330 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12331 	/* The ill_index of the incoming ILL */
12332 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12333 
12334 	/* pass packet up to the transport */
12335 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12336 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12337 		    NULL, mctl_present);
12338 		if (*first_mpp == NULL) {
12339 			return (B_FALSE);
12340 		}
12341 	}
12342 
12343 	/* Initiate IPPF processing for fastpath UDP */
12344 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12345 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12346 		if (*mpp == NULL) {
12347 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12348 			    "deferred/dropped during IPPF processing\n"));
12349 			return (B_FALSE);
12350 		}
12351 	}
12352 	/*
12353 	 * We make the checks as below since we are in the fast path
12354 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12355 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12356 	 */
12357 	if (connp->conn_recvif || connp->conn_recvslla ||
12358 	    connp->conn_ip_recvpktinfo) {
12359 		if (connp->conn_recvif) {
12360 			in_flags = IPF_RECVIF;
12361 		}
12362 		/*
12363 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12364 		 * so the flag passed to ip_add_info is based on IP version
12365 		 * of connp.
12366 		 */
12367 		if (connp->conn_ip_recvpktinfo) {
12368 			if (connp->conn_af_isv6) {
12369 				/*
12370 				 * V6 only needs index
12371 				 */
12372 				in_flags |= IPF_RECVIF;
12373 			} else {
12374 				/*
12375 				 * V4 needs index + matching address.
12376 				 */
12377 				in_flags |= IPF_RECVADDR;
12378 			}
12379 		}
12380 		if (connp->conn_recvslla) {
12381 			in_flags |= IPF_RECVSLLA;
12382 		}
12383 		/*
12384 		 * since in_flags are being set ill will be
12385 		 * referenced in ip_add_info, so it better not
12386 		 * be NULL.
12387 		 */
12388 		/*
12389 		 * the actual data will be contained in b_cont
12390 		 * upon successful return of the following call.
12391 		 * If the call fails then the original mblk is
12392 		 * returned.
12393 		 */
12394 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12395 		    ipst);
12396 	}
12397 
12398 	return (B_TRUE);
12399 }
12400 
12401 /*
12402  * Fragmentation reassembly.  Each ILL has a hash table for
12403  * queuing packets undergoing reassembly for all IPIFs
12404  * associated with the ILL.  The hash is based on the packet
12405  * IP ident field.  The ILL frag hash table was allocated
12406  * as a timer block at the time the ILL was created.  Whenever
12407  * there is anything on the reassembly queue, the timer will
12408  * be running.  Returns B_TRUE if successful else B_FALSE;
12409  * frees mp on failure.
12410  */
12411 static boolean_t
12412 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12413     uint32_t *cksum_val, uint16_t *cksum_flags)
12414 {
12415 	uint32_t	frag_offset_flags;
12416 	ill_t		*ill = (ill_t *)q->q_ptr;
12417 	mblk_t		*mp = *mpp;
12418 	mblk_t		*t_mp;
12419 	ipaddr_t	dst;
12420 	uint8_t		proto = ipha->ipha_protocol;
12421 	uint32_t	sum_val;
12422 	uint16_t	sum_flags;
12423 	ipf_t		*ipf;
12424 	ipf_t		**ipfp;
12425 	ipfb_t		*ipfb;
12426 	uint16_t	ident;
12427 	uint32_t	offset;
12428 	ipaddr_t	src;
12429 	uint_t		hdr_length;
12430 	uint32_t	end;
12431 	mblk_t		*mp1;
12432 	mblk_t		*tail_mp;
12433 	size_t		count;
12434 	size_t		msg_len;
12435 	uint8_t		ecn_info = 0;
12436 	uint32_t	packet_size;
12437 	boolean_t	pruned = B_FALSE;
12438 	ip_stack_t *ipst = ill->ill_ipst;
12439 
12440 	if (cksum_val != NULL)
12441 		*cksum_val = 0;
12442 	if (cksum_flags != NULL)
12443 		*cksum_flags = 0;
12444 
12445 	/*
12446 	 * Drop the fragmented as early as possible, if
12447 	 * we don't have resource(s) to re-assemble.
12448 	 */
12449 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12450 		freemsg(mp);
12451 		return (B_FALSE);
12452 	}
12453 
12454 	/* Check for fragmentation offset; return if there's none */
12455 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12456 	    (IPH_MF | IPH_OFFSET)) == 0)
12457 		return (B_TRUE);
12458 
12459 	/*
12460 	 * We utilize hardware computed checksum info only for UDP since
12461 	 * IP fragmentation is a normal occurence for the protocol.  In
12462 	 * addition, checksum offload support for IP fragments carrying
12463 	 * UDP payload is commonly implemented across network adapters.
12464 	 */
12465 	ASSERT(ill != NULL);
12466 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12467 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12468 		mblk_t *mp1 = mp->b_cont;
12469 		int32_t len;
12470 
12471 		/* Record checksum information from the packet */
12472 		sum_val = (uint32_t)DB_CKSUM16(mp);
12473 		sum_flags = DB_CKSUMFLAGS(mp);
12474 
12475 		/* IP payload offset from beginning of mblk */
12476 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12477 
12478 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12479 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12480 		    offset >= DB_CKSUMSTART(mp) &&
12481 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12482 			uint32_t adj;
12483 			/*
12484 			 * Partial checksum has been calculated by hardware
12485 			 * and attached to the packet; in addition, any
12486 			 * prepended extraneous data is even byte aligned.
12487 			 * If any such data exists, we adjust the checksum;
12488 			 * this would also handle any postpended data.
12489 			 */
12490 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12491 			    mp, mp1, len, adj);
12492 
12493 			/* One's complement subtract extraneous checksum */
12494 			if (adj >= sum_val)
12495 				sum_val = ~(adj - sum_val) & 0xFFFF;
12496 			else
12497 				sum_val -= adj;
12498 		}
12499 	} else {
12500 		sum_val = 0;
12501 		sum_flags = 0;
12502 	}
12503 
12504 	/* Clear hardware checksumming flag */
12505 	DB_CKSUMFLAGS(mp) = 0;
12506 
12507 	ident = ipha->ipha_ident;
12508 	offset = (frag_offset_flags << 3) & 0xFFFF;
12509 	src = ipha->ipha_src;
12510 	dst = ipha->ipha_dst;
12511 	hdr_length = IPH_HDR_LENGTH(ipha);
12512 	end = ntohs(ipha->ipha_length) - hdr_length;
12513 
12514 	/* If end == 0 then we have a packet with no data, so just free it */
12515 	if (end == 0) {
12516 		freemsg(mp);
12517 		return (B_FALSE);
12518 	}
12519 
12520 	/* Record the ECN field info. */
12521 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12522 	if (offset != 0) {
12523 		/*
12524 		 * If this isn't the first piece, strip the header, and
12525 		 * add the offset to the end value.
12526 		 */
12527 		mp->b_rptr += hdr_length;
12528 		end += offset;
12529 	}
12530 
12531 	msg_len = MBLKSIZE(mp);
12532 	tail_mp = mp;
12533 	while (tail_mp->b_cont != NULL) {
12534 		tail_mp = tail_mp->b_cont;
12535 		msg_len += MBLKSIZE(tail_mp);
12536 	}
12537 
12538 	/* If the reassembly list for this ILL will get too big, prune it */
12539 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12540 	    ipst->ips_ip_reass_queue_bytes) {
12541 		ill_frag_prune(ill,
12542 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12543 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12544 		pruned = B_TRUE;
12545 	}
12546 
12547 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12548 	mutex_enter(&ipfb->ipfb_lock);
12549 
12550 	ipfp = &ipfb->ipfb_ipf;
12551 	/* Try to find an existing fragment queue for this packet. */
12552 	for (;;) {
12553 		ipf = ipfp[0];
12554 		if (ipf != NULL) {
12555 			/*
12556 			 * It has to match on ident and src/dst address.
12557 			 */
12558 			if (ipf->ipf_ident == ident &&
12559 			    ipf->ipf_src == src &&
12560 			    ipf->ipf_dst == dst &&
12561 			    ipf->ipf_protocol == proto) {
12562 				/*
12563 				 * If we have received too many
12564 				 * duplicate fragments for this packet
12565 				 * free it.
12566 				 */
12567 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12568 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12569 					freemsg(mp);
12570 					mutex_exit(&ipfb->ipfb_lock);
12571 					return (B_FALSE);
12572 				}
12573 				/* Found it. */
12574 				break;
12575 			}
12576 			ipfp = &ipf->ipf_hash_next;
12577 			continue;
12578 		}
12579 
12580 		/*
12581 		 * If we pruned the list, do we want to store this new
12582 		 * fragment?. We apply an optimization here based on the
12583 		 * fact that most fragments will be received in order.
12584 		 * So if the offset of this incoming fragment is zero,
12585 		 * it is the first fragment of a new packet. We will
12586 		 * keep it.  Otherwise drop the fragment, as we have
12587 		 * probably pruned the packet already (since the
12588 		 * packet cannot be found).
12589 		 */
12590 		if (pruned && offset != 0) {
12591 			mutex_exit(&ipfb->ipfb_lock);
12592 			freemsg(mp);
12593 			return (B_FALSE);
12594 		}
12595 
12596 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12597 			/*
12598 			 * Too many fragmented packets in this hash
12599 			 * bucket. Free the oldest.
12600 			 */
12601 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12602 		}
12603 
12604 		/* New guy.  Allocate a frag message. */
12605 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12606 		if (mp1 == NULL) {
12607 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12608 			freemsg(mp);
12609 reass_done:
12610 			mutex_exit(&ipfb->ipfb_lock);
12611 			return (B_FALSE);
12612 		}
12613 
12614 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12615 		mp1->b_cont = mp;
12616 
12617 		/* Initialize the fragment header. */
12618 		ipf = (ipf_t *)mp1->b_rptr;
12619 		ipf->ipf_mp = mp1;
12620 		ipf->ipf_ptphn = ipfp;
12621 		ipfp[0] = ipf;
12622 		ipf->ipf_hash_next = NULL;
12623 		ipf->ipf_ident = ident;
12624 		ipf->ipf_protocol = proto;
12625 		ipf->ipf_src = src;
12626 		ipf->ipf_dst = dst;
12627 		ipf->ipf_nf_hdr_len = 0;
12628 		/* Record reassembly start time. */
12629 		ipf->ipf_timestamp = gethrestime_sec();
12630 		/* Record ipf generation and account for frag header */
12631 		ipf->ipf_gen = ill->ill_ipf_gen++;
12632 		ipf->ipf_count = MBLKSIZE(mp1);
12633 		ipf->ipf_last_frag_seen = B_FALSE;
12634 		ipf->ipf_ecn = ecn_info;
12635 		ipf->ipf_num_dups = 0;
12636 		ipfb->ipfb_frag_pkts++;
12637 		ipf->ipf_checksum = 0;
12638 		ipf->ipf_checksum_flags = 0;
12639 
12640 		/* Store checksum value in fragment header */
12641 		if (sum_flags != 0) {
12642 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12643 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12644 			ipf->ipf_checksum = sum_val;
12645 			ipf->ipf_checksum_flags = sum_flags;
12646 		}
12647 
12648 		/*
12649 		 * We handle reassembly two ways.  In the easy case,
12650 		 * where all the fragments show up in order, we do
12651 		 * minimal bookkeeping, and just clip new pieces on
12652 		 * the end.  If we ever see a hole, then we go off
12653 		 * to ip_reassemble which has to mark the pieces and
12654 		 * keep track of the number of holes, etc.  Obviously,
12655 		 * the point of having both mechanisms is so we can
12656 		 * handle the easy case as efficiently as possible.
12657 		 */
12658 		if (offset == 0) {
12659 			/* Easy case, in-order reassembly so far. */
12660 			ipf->ipf_count += msg_len;
12661 			ipf->ipf_tail_mp = tail_mp;
12662 			/*
12663 			 * Keep track of next expected offset in
12664 			 * ipf_end.
12665 			 */
12666 			ipf->ipf_end = end;
12667 			ipf->ipf_nf_hdr_len = hdr_length;
12668 		} else {
12669 			/* Hard case, hole at the beginning. */
12670 			ipf->ipf_tail_mp = NULL;
12671 			/*
12672 			 * ipf_end == 0 means that we have given up
12673 			 * on easy reassembly.
12674 			 */
12675 			ipf->ipf_end = 0;
12676 
12677 			/* Forget checksum offload from now on */
12678 			ipf->ipf_checksum_flags = 0;
12679 
12680 			/*
12681 			 * ipf_hole_cnt is set by ip_reassemble.
12682 			 * ipf_count is updated by ip_reassemble.
12683 			 * No need to check for return value here
12684 			 * as we don't expect reassembly to complete
12685 			 * or fail for the first fragment itself.
12686 			 */
12687 			(void) ip_reassemble(mp, ipf,
12688 			    (frag_offset_flags & IPH_OFFSET) << 3,
12689 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12690 		}
12691 		/* Update per ipfb and ill byte counts */
12692 		ipfb->ipfb_count += ipf->ipf_count;
12693 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12694 		ill->ill_frag_count += ipf->ipf_count;
12695 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12696 		/* If the frag timer wasn't already going, start it. */
12697 		mutex_enter(&ill->ill_lock);
12698 		ill_frag_timer_start(ill);
12699 		mutex_exit(&ill->ill_lock);
12700 		goto reass_done;
12701 	}
12702 
12703 	/*
12704 	 * If the packet's flag has changed (it could be coming up
12705 	 * from an interface different than the previous, therefore
12706 	 * possibly different checksum capability), then forget about
12707 	 * any stored checksum states.  Otherwise add the value to
12708 	 * the existing one stored in the fragment header.
12709 	 */
12710 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12711 		sum_val += ipf->ipf_checksum;
12712 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12713 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12714 		ipf->ipf_checksum = sum_val;
12715 	} else if (ipf->ipf_checksum_flags != 0) {
12716 		/* Forget checksum offload from now on */
12717 		ipf->ipf_checksum_flags = 0;
12718 	}
12719 
12720 	/*
12721 	 * We have a new piece of a datagram which is already being
12722 	 * reassembled.  Update the ECN info if all IP fragments
12723 	 * are ECN capable.  If there is one which is not, clear
12724 	 * all the info.  If there is at least one which has CE
12725 	 * code point, IP needs to report that up to transport.
12726 	 */
12727 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12728 		if (ecn_info == IPH_ECN_CE)
12729 			ipf->ipf_ecn = IPH_ECN_CE;
12730 	} else {
12731 		ipf->ipf_ecn = IPH_ECN_NECT;
12732 	}
12733 	if (offset && ipf->ipf_end == offset) {
12734 		/* The new fragment fits at the end */
12735 		ipf->ipf_tail_mp->b_cont = mp;
12736 		/* Update the byte count */
12737 		ipf->ipf_count += msg_len;
12738 		/* Update per ipfb and ill byte counts */
12739 		ipfb->ipfb_count += msg_len;
12740 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12741 		ill->ill_frag_count += msg_len;
12742 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12743 		if (frag_offset_flags & IPH_MF) {
12744 			/* More to come. */
12745 			ipf->ipf_end = end;
12746 			ipf->ipf_tail_mp = tail_mp;
12747 			goto reass_done;
12748 		}
12749 	} else {
12750 		/* Go do the hard cases. */
12751 		int ret;
12752 
12753 		if (offset == 0)
12754 			ipf->ipf_nf_hdr_len = hdr_length;
12755 
12756 		/* Save current byte count */
12757 		count = ipf->ipf_count;
12758 		ret = ip_reassemble(mp, ipf,
12759 		    (frag_offset_flags & IPH_OFFSET) << 3,
12760 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12761 		/* Count of bytes added and subtracted (freeb()ed) */
12762 		count = ipf->ipf_count - count;
12763 		if (count) {
12764 			/* Update per ipfb and ill byte counts */
12765 			ipfb->ipfb_count += count;
12766 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12767 			ill->ill_frag_count += count;
12768 			ASSERT(ill->ill_frag_count > 0);
12769 		}
12770 		if (ret == IP_REASS_PARTIAL) {
12771 			goto reass_done;
12772 		} else if (ret == IP_REASS_FAILED) {
12773 			/* Reassembly failed. Free up all resources */
12774 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12775 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12776 				IP_REASS_SET_START(t_mp, 0);
12777 				IP_REASS_SET_END(t_mp, 0);
12778 			}
12779 			freemsg(mp);
12780 			goto reass_done;
12781 		}
12782 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12783 	}
12784 	/*
12785 	 * We have completed reassembly.  Unhook the frag header from
12786 	 * the reassembly list.
12787 	 *
12788 	 * Before we free the frag header, record the ECN info
12789 	 * to report back to the transport.
12790 	 */
12791 	ecn_info = ipf->ipf_ecn;
12792 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12793 	ipfp = ipf->ipf_ptphn;
12794 
12795 	/* We need to supply these to caller */
12796 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12797 		sum_val = ipf->ipf_checksum;
12798 	else
12799 		sum_val = 0;
12800 
12801 	mp1 = ipf->ipf_mp;
12802 	count = ipf->ipf_count;
12803 	ipf = ipf->ipf_hash_next;
12804 	if (ipf != NULL)
12805 		ipf->ipf_ptphn = ipfp;
12806 	ipfp[0] = ipf;
12807 	ill->ill_frag_count -= count;
12808 	ASSERT(ipfb->ipfb_count >= count);
12809 	ipfb->ipfb_count -= count;
12810 	ipfb->ipfb_frag_pkts--;
12811 	mutex_exit(&ipfb->ipfb_lock);
12812 	/* Ditch the frag header. */
12813 	mp = mp1->b_cont;
12814 
12815 	freeb(mp1);
12816 
12817 	/* Restore original IP length in header. */
12818 	packet_size = (uint32_t)msgdsize(mp);
12819 	if (packet_size > IP_MAXPACKET) {
12820 		freemsg(mp);
12821 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12822 		return (B_FALSE);
12823 	}
12824 
12825 	if (DB_REF(mp) > 1) {
12826 		mblk_t *mp2 = copymsg(mp);
12827 
12828 		freemsg(mp);
12829 		if (mp2 == NULL) {
12830 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12831 			return (B_FALSE);
12832 		}
12833 		mp = mp2;
12834 	}
12835 	ipha = (ipha_t *)mp->b_rptr;
12836 
12837 	ipha->ipha_length = htons((uint16_t)packet_size);
12838 	/* We're now complete, zip the frag state */
12839 	ipha->ipha_fragment_offset_and_flags = 0;
12840 	/* Record the ECN info. */
12841 	ipha->ipha_type_of_service &= 0xFC;
12842 	ipha->ipha_type_of_service |= ecn_info;
12843 	*mpp = mp;
12844 
12845 	/* Reassembly is successful; return checksum information if needed */
12846 	if (cksum_val != NULL)
12847 		*cksum_val = sum_val;
12848 	if (cksum_flags != NULL)
12849 		*cksum_flags = sum_flags;
12850 
12851 	return (B_TRUE);
12852 }
12853 
12854 /*
12855  * Perform ip header check sum update local options.
12856  * return B_TRUE if all is well, else return B_FALSE and release
12857  * the mp. caller is responsible for decrementing ire ref cnt.
12858  */
12859 static boolean_t
12860 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12861     ip_stack_t *ipst)
12862 {
12863 	mblk_t		*first_mp;
12864 	boolean_t	mctl_present;
12865 	uint16_t	sum;
12866 
12867 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12868 	/*
12869 	 * Don't do the checksum if it has gone through AH/ESP
12870 	 * processing.
12871 	 */
12872 	if (!mctl_present) {
12873 		sum = ip_csum_hdr(ipha);
12874 		if (sum != 0) {
12875 			if (ill != NULL) {
12876 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12877 			} else {
12878 				BUMP_MIB(&ipst->ips_ip_mib,
12879 				    ipIfStatsInCksumErrs);
12880 			}
12881 			freemsg(first_mp);
12882 			return (B_FALSE);
12883 		}
12884 	}
12885 
12886 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12887 		if (mctl_present)
12888 			freeb(first_mp);
12889 		return (B_FALSE);
12890 	}
12891 
12892 	return (B_TRUE);
12893 }
12894 
12895 /*
12896  * All udp packet are delivered to the local host via this routine.
12897  */
12898 void
12899 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12900     ill_t *recv_ill)
12901 {
12902 	uint32_t	sum;
12903 	uint32_t	u1;
12904 	boolean_t	mctl_present;
12905 	conn_t		*connp;
12906 	mblk_t		*first_mp;
12907 	uint16_t	*up;
12908 	ill_t		*ill = (ill_t *)q->q_ptr;
12909 	uint16_t	reass_hck_flags = 0;
12910 	ip_stack_t	*ipst;
12911 
12912 	ASSERT(recv_ill != NULL);
12913 	ipst = recv_ill->ill_ipst;
12914 
12915 #define	rptr    ((uchar_t *)ipha)
12916 
12917 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12918 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12919 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12920 	ASSERT(ill != NULL);
12921 
12922 	/*
12923 	 * FAST PATH for udp packets
12924 	 */
12925 
12926 	/* u1 is # words of IP options */
12927 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12928 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12929 
12930 	/* IP options present */
12931 	if (u1 != 0)
12932 		goto ipoptions;
12933 
12934 	/* Check the IP header checksum.  */
12935 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12936 		/* Clear the IP header h/w cksum flag */
12937 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12938 	} else {
12939 #define	uph	((uint16_t *)ipha)
12940 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12941 		    uph[6] + uph[7] + uph[8] + uph[9];
12942 #undef	uph
12943 		/* finish doing IP checksum */
12944 		sum = (sum & 0xFFFF) + (sum >> 16);
12945 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12946 		/*
12947 		 * Don't verify header checksum if this packet is coming
12948 		 * back from AH/ESP as we already did it.
12949 		 */
12950 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12951 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12952 			freemsg(first_mp);
12953 			return;
12954 		}
12955 	}
12956 
12957 	/*
12958 	 * Count for SNMP of inbound packets for ire.
12959 	 * if mctl is present this might be a secure packet and
12960 	 * has already been counted for in ip_proto_input().
12961 	 */
12962 	if (!mctl_present) {
12963 		UPDATE_IB_PKT_COUNT(ire);
12964 		ire->ire_last_used_time = lbolt;
12965 	}
12966 
12967 	/* packet part of fragmented IP packet? */
12968 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12969 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12970 		goto fragmented;
12971 	}
12972 
12973 	/* u1 = IP header length (20 bytes) */
12974 	u1 = IP_SIMPLE_HDR_LENGTH;
12975 
12976 	/* packet does not contain complete IP & UDP headers */
12977 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12978 		goto udppullup;
12979 
12980 	/* up points to UDP header */
12981 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12982 #define	iphs    ((uint16_t *)ipha)
12983 
12984 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12985 	if (up[3] != 0) {
12986 		mblk_t *mp1 = mp->b_cont;
12987 		boolean_t cksum_err;
12988 		uint16_t hck_flags = 0;
12989 
12990 		/* Pseudo-header checksum */
12991 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12992 		    iphs[9] + up[2];
12993 
12994 		/*
12995 		 * Revert to software checksum calculation if the interface
12996 		 * isn't capable of checksum offload or if IPsec is present.
12997 		 */
12998 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12999 			hck_flags = DB_CKSUMFLAGS(mp);
13000 
13001 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13002 			IP_STAT(ipst, ip_in_sw_cksum);
13003 
13004 		IP_CKSUM_RECV(hck_flags, u1,
13005 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13006 		    (int32_t)((uchar_t *)up - rptr),
13007 		    mp, mp1, cksum_err);
13008 
13009 		if (cksum_err) {
13010 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13011 			if (hck_flags & HCK_FULLCKSUM)
13012 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13013 			else if (hck_flags & HCK_PARTIALCKSUM)
13014 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13015 			else
13016 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13017 
13018 			freemsg(first_mp);
13019 			return;
13020 		}
13021 	}
13022 
13023 	/* Non-fragmented broadcast or multicast packet? */
13024 	if (ire->ire_type == IRE_BROADCAST)
13025 		goto udpslowpath;
13026 
13027 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
13028 	    ire->ire_zoneid, ipst)) != NULL) {
13029 		ASSERT(connp->conn_upq != NULL);
13030 		IP_STAT(ipst, ip_udp_fast_path);
13031 
13032 		if (CONN_UDP_FLOWCTLD(connp)) {
13033 			freemsg(mp);
13034 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
13035 		} else {
13036 			if (!mctl_present) {
13037 				BUMP_MIB(ill->ill_ip_mib,
13038 				    ipIfStatsHCInDelivers);
13039 			}
13040 			/*
13041 			 * mp and first_mp can change.
13042 			 */
13043 			if (ip_udp_check(q, connp, recv_ill,
13044 			    ipha, &mp, &first_mp, mctl_present)) {
13045 				/* Send it upstream */
13046 				CONN_UDP_RECV(connp, mp);
13047 			}
13048 		}
13049 		/*
13050 		 * freeb() cannot deal with null mblk being passed
13051 		 * in and first_mp can be set to null in the call
13052 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
13053 		 */
13054 		if (mctl_present && first_mp != NULL) {
13055 			freeb(first_mp);
13056 		}
13057 		CONN_DEC_REF(connp);
13058 		return;
13059 	}
13060 
13061 	/*
13062 	 * if we got here we know the packet is not fragmented and
13063 	 * has no options. The classifier could not find a conn_t and
13064 	 * most likely its an icmp packet so send it through slow path.
13065 	 */
13066 
13067 	goto udpslowpath;
13068 
13069 ipoptions:
13070 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
13071 		goto slow_done;
13072 	}
13073 
13074 	UPDATE_IB_PKT_COUNT(ire);
13075 	ire->ire_last_used_time = lbolt;
13076 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13077 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13078 fragmented:
13079 		/*
13080 		 * "sum" and "reass_hck_flags" are non-zero if the
13081 		 * reassembled packet has a valid hardware computed
13082 		 * checksum information associated with it.
13083 		 */
13084 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
13085 			goto slow_done;
13086 		/*
13087 		 * Make sure that first_mp points back to mp as
13088 		 * the mp we came in with could have changed in
13089 		 * ip_rput_fragment().
13090 		 */
13091 		ASSERT(!mctl_present);
13092 		ipha = (ipha_t *)mp->b_rptr;
13093 		first_mp = mp;
13094 	}
13095 
13096 	/* Now we have a complete datagram, destined for this machine. */
13097 	u1 = IPH_HDR_LENGTH(ipha);
13098 	/* Pull up the UDP header, if necessary. */
13099 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
13100 udppullup:
13101 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
13102 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13103 			freemsg(first_mp);
13104 			goto slow_done;
13105 		}
13106 		ipha = (ipha_t *)mp->b_rptr;
13107 	}
13108 
13109 	/*
13110 	 * Validate the checksum for the reassembled packet; for the
13111 	 * pullup case we calculate the payload checksum in software.
13112 	 */
13113 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
13114 	if (up[3] != 0) {
13115 		boolean_t cksum_err;
13116 
13117 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13118 			IP_STAT(ipst, ip_in_sw_cksum);
13119 
13120 		IP_CKSUM_RECV_REASS(reass_hck_flags,
13121 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
13122 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13123 		    iphs[9] + up[2], sum, cksum_err);
13124 
13125 		if (cksum_err) {
13126 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13127 
13128 			if (reass_hck_flags & HCK_FULLCKSUM)
13129 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13130 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13131 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13132 			else
13133 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13134 
13135 			freemsg(first_mp);
13136 			goto slow_done;
13137 		}
13138 	}
13139 udpslowpath:
13140 
13141 	/* Clear hardware checksum flag to be safe */
13142 	DB_CKSUMFLAGS(mp) = 0;
13143 
13144 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13145 	    (ire->ire_type == IRE_BROADCAST),
13146 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13147 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13148 
13149 slow_done:
13150 	IP_STAT(ipst, ip_udp_slow_path);
13151 	return;
13152 
13153 #undef  iphs
13154 #undef  rptr
13155 }
13156 
13157 /* ARGSUSED */
13158 static mblk_t *
13159 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13160     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13161     ill_rx_ring_t *ill_ring)
13162 {
13163 	conn_t		*connp;
13164 	uint32_t	sum;
13165 	uint32_t	u1;
13166 	uint16_t	*up;
13167 	int		offset;
13168 	ssize_t		len;
13169 	mblk_t		*mp1;
13170 	boolean_t	syn_present = B_FALSE;
13171 	tcph_t		*tcph;
13172 	uint_t		ip_hdr_len;
13173 	ill_t		*ill = (ill_t *)q->q_ptr;
13174 	zoneid_t	zoneid = ire->ire_zoneid;
13175 	boolean_t	cksum_err;
13176 	uint16_t	hck_flags = 0;
13177 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13178 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13179 
13180 #define	rptr	((uchar_t *)ipha)
13181 
13182 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13183 	ASSERT(ill != NULL);
13184 
13185 	/*
13186 	 * FAST PATH for tcp packets
13187 	 */
13188 
13189 	/* u1 is # words of IP options */
13190 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13191 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13192 
13193 	/* IP options present */
13194 	if (u1) {
13195 		goto ipoptions;
13196 	} else {
13197 		/* Check the IP header checksum.  */
13198 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13199 			/* Clear the IP header h/w cksum flag */
13200 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13201 		} else {
13202 #define	uph	((uint16_t *)ipha)
13203 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13204 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13205 #undef	uph
13206 			/* finish doing IP checksum */
13207 			sum = (sum & 0xFFFF) + (sum >> 16);
13208 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13209 			/*
13210 			 * Don't verify header checksum if this packet
13211 			 * is coming back from AH/ESP as we already did it.
13212 			 */
13213 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13214 				BUMP_MIB(ill->ill_ip_mib,
13215 				    ipIfStatsInCksumErrs);
13216 				goto error;
13217 			}
13218 		}
13219 	}
13220 
13221 	if (!mctl_present) {
13222 		UPDATE_IB_PKT_COUNT(ire);
13223 		ire->ire_last_used_time = lbolt;
13224 	}
13225 
13226 	/* packet part of fragmented IP packet? */
13227 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13228 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13229 		goto fragmented;
13230 	}
13231 
13232 	/* u1 = IP header length (20 bytes) */
13233 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13234 
13235 	/* does packet contain IP+TCP headers? */
13236 	len = mp->b_wptr - rptr;
13237 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13238 		IP_STAT(ipst, ip_tcppullup);
13239 		goto tcppullup;
13240 	}
13241 
13242 	/* TCP options present? */
13243 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13244 
13245 	/*
13246 	 * If options need to be pulled up, then goto tcpoptions.
13247 	 * otherwise we are still in the fast path
13248 	 */
13249 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13250 		IP_STAT(ipst, ip_tcpoptions);
13251 		goto tcpoptions;
13252 	}
13253 
13254 	/* multiple mblks of tcp data? */
13255 	if ((mp1 = mp->b_cont) != NULL) {
13256 		/* more then two? */
13257 		if (mp1->b_cont != NULL) {
13258 			IP_STAT(ipst, ip_multipkttcp);
13259 			goto multipkttcp;
13260 		}
13261 		len += mp1->b_wptr - mp1->b_rptr;
13262 	}
13263 
13264 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13265 
13266 	/* part of pseudo checksum */
13267 
13268 	/* TCP datagram length */
13269 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13270 
13271 #define	iphs    ((uint16_t *)ipha)
13272 
13273 #ifdef	_BIG_ENDIAN
13274 	u1 += IPPROTO_TCP;
13275 #else
13276 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13277 #endif
13278 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13279 
13280 	/*
13281 	 * Revert to software checksum calculation if the interface
13282 	 * isn't capable of checksum offload or if IPsec is present.
13283 	 */
13284 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13285 		hck_flags = DB_CKSUMFLAGS(mp);
13286 
13287 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13288 		IP_STAT(ipst, ip_in_sw_cksum);
13289 
13290 	IP_CKSUM_RECV(hck_flags, u1,
13291 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13292 	    (int32_t)((uchar_t *)up - rptr),
13293 	    mp, mp1, cksum_err);
13294 
13295 	if (cksum_err) {
13296 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13297 
13298 		if (hck_flags & HCK_FULLCKSUM)
13299 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13300 		else if (hck_flags & HCK_PARTIALCKSUM)
13301 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13302 		else
13303 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13304 
13305 		goto error;
13306 	}
13307 
13308 try_again:
13309 
13310 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13311 		    zoneid, ipst)) == NULL) {
13312 		/* Send the TH_RST */
13313 		goto no_conn;
13314 	}
13315 
13316 	/*
13317 	 * TCP FAST PATH for AF_INET socket.
13318 	 *
13319 	 * TCP fast path to avoid extra work. An AF_INET socket type
13320 	 * does not have facility to receive extra information via
13321 	 * ip_process or ip_add_info. Also, when the connection was
13322 	 * established, we made a check if this connection is impacted
13323 	 * by any global IPSec policy or per connection policy (a
13324 	 * policy that comes in effect later will not apply to this
13325 	 * connection). Since all this can be determined at the
13326 	 * connection establishment time, a quick check of flags
13327 	 * can avoid extra work.
13328 	 */
13329 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13330 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13331 		ASSERT(first_mp == mp);
13332 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13333 		SET_SQUEUE(mp, tcp_rput_data, connp);
13334 		return (mp);
13335 	}
13336 
13337 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13338 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13339 		if (IPCL_IS_TCP(connp)) {
13340 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13341 			DB_CKSUMSTART(mp) =
13342 			    (intptr_t)ip_squeue_get(ill_ring);
13343 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13344 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13345 				BUMP_MIB(ill->ill_ip_mib,
13346 				    ipIfStatsHCInDelivers);
13347 				SET_SQUEUE(mp, connp->conn_recv, connp);
13348 				return (mp);
13349 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13350 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13351 				BUMP_MIB(ill->ill_ip_mib,
13352 				    ipIfStatsHCInDelivers);
13353 				ip_squeue_enter_unbound++;
13354 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13355 				    connp);
13356 				return (mp);
13357 			}
13358 			syn_present = B_TRUE;
13359 		}
13360 
13361 	}
13362 
13363 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13364 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13365 
13366 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13367 		/* No need to send this packet to TCP */
13368 		if ((flags & TH_RST) || (flags & TH_URG)) {
13369 			CONN_DEC_REF(connp);
13370 			freemsg(first_mp);
13371 			return (NULL);
13372 		}
13373 		if (flags & TH_ACK) {
13374 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13375 			    ipst->ips_netstack->netstack_tcp);
13376 			CONN_DEC_REF(connp);
13377 			return (NULL);
13378 		}
13379 
13380 		CONN_DEC_REF(connp);
13381 		freemsg(first_mp);
13382 		return (NULL);
13383 	}
13384 
13385 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13386 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13387 		    ipha, NULL, mctl_present);
13388 		if (first_mp == NULL) {
13389 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13390 			CONN_DEC_REF(connp);
13391 			return (NULL);
13392 		}
13393 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13394 			ASSERT(syn_present);
13395 			if (mctl_present) {
13396 				ASSERT(first_mp != mp);
13397 				first_mp->b_datap->db_struioflag |=
13398 				    STRUIO_POLICY;
13399 			} else {
13400 				ASSERT(first_mp == mp);
13401 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13402 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13403 			}
13404 		} else {
13405 			/*
13406 			 * Discard first_mp early since we're dealing with a
13407 			 * fully-connected conn_t and tcp doesn't do policy in
13408 			 * this case.
13409 			 */
13410 			if (mctl_present) {
13411 				freeb(first_mp);
13412 				mctl_present = B_FALSE;
13413 			}
13414 			first_mp = mp;
13415 		}
13416 	}
13417 
13418 	/* Initiate IPPF processing for fastpath */
13419 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13420 		uint32_t	ill_index;
13421 
13422 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13423 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13424 		if (mp == NULL) {
13425 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13426 			    "deferred/dropped during IPPF processing\n"));
13427 			CONN_DEC_REF(connp);
13428 			if (mctl_present)
13429 				freeb(first_mp);
13430 			return (NULL);
13431 		} else if (mctl_present) {
13432 			/*
13433 			 * ip_process might return a new mp.
13434 			 */
13435 			ASSERT(first_mp != mp);
13436 			first_mp->b_cont = mp;
13437 		} else {
13438 			first_mp = mp;
13439 		}
13440 
13441 	}
13442 
13443 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13444 		/*
13445 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13446 		 * make sure IPF_RECVIF is passed to ip_add_info.
13447 		 */
13448 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13449 		    IPCL_ZONEID(connp), ipst);
13450 		if (mp == NULL) {
13451 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13452 			CONN_DEC_REF(connp);
13453 			if (mctl_present)
13454 				freeb(first_mp);
13455 			return (NULL);
13456 		} else if (mctl_present) {
13457 			/*
13458 			 * ip_add_info might return a new mp.
13459 			 */
13460 			ASSERT(first_mp != mp);
13461 			first_mp->b_cont = mp;
13462 		} else {
13463 			first_mp = mp;
13464 		}
13465 	}
13466 
13467 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13468 	if (IPCL_IS_TCP(connp)) {
13469 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13470 		return (first_mp);
13471 	} else {
13472 		putnext(connp->conn_rq, first_mp);
13473 		CONN_DEC_REF(connp);
13474 		return (NULL);
13475 	}
13476 
13477 no_conn:
13478 	/* Initiate IPPf processing, if needed. */
13479 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13480 		uint32_t ill_index;
13481 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13482 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13483 		if (first_mp == NULL) {
13484 			return (NULL);
13485 		}
13486 	}
13487 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13488 
13489 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13490 	    ipst->ips_netstack->netstack_tcp);
13491 	return (NULL);
13492 ipoptions:
13493 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13494 		goto slow_done;
13495 	}
13496 
13497 	UPDATE_IB_PKT_COUNT(ire);
13498 	ire->ire_last_used_time = lbolt;
13499 
13500 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13501 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13502 fragmented:
13503 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13504 			if (mctl_present)
13505 				freeb(first_mp);
13506 			goto slow_done;
13507 		}
13508 		/*
13509 		 * Make sure that first_mp points back to mp as
13510 		 * the mp we came in with could have changed in
13511 		 * ip_rput_fragment().
13512 		 */
13513 		ASSERT(!mctl_present);
13514 		ipha = (ipha_t *)mp->b_rptr;
13515 		first_mp = mp;
13516 	}
13517 
13518 	/* Now we have a complete datagram, destined for this machine. */
13519 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13520 
13521 	len = mp->b_wptr - mp->b_rptr;
13522 	/* Pull up a minimal TCP header, if necessary. */
13523 	if (len < (u1 + 20)) {
13524 tcppullup:
13525 		if (!pullupmsg(mp, u1 + 20)) {
13526 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13527 			goto error;
13528 		}
13529 		ipha = (ipha_t *)mp->b_rptr;
13530 		len = mp->b_wptr - mp->b_rptr;
13531 	}
13532 
13533 	/*
13534 	 * Extract the offset field from the TCP header.  As usual, we
13535 	 * try to help the compiler more than the reader.
13536 	 */
13537 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13538 	if (offset != 5) {
13539 tcpoptions:
13540 		if (offset < 5) {
13541 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13542 			goto error;
13543 		}
13544 		/*
13545 		 * There must be TCP options.
13546 		 * Make sure we can grab them.
13547 		 */
13548 		offset <<= 2;
13549 		offset += u1;
13550 		if (len < offset) {
13551 			if (!pullupmsg(mp, offset)) {
13552 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13553 				goto error;
13554 			}
13555 			ipha = (ipha_t *)mp->b_rptr;
13556 			len = mp->b_wptr - rptr;
13557 		}
13558 	}
13559 
13560 	/* Get the total packet length in len, including headers. */
13561 	if (mp->b_cont) {
13562 multipkttcp:
13563 		len = msgdsize(mp);
13564 	}
13565 
13566 	/*
13567 	 * Check the TCP checksum by pulling together the pseudo-
13568 	 * header checksum, and passing it to ip_csum to be added in
13569 	 * with the TCP datagram.
13570 	 *
13571 	 * Since we are not using the hwcksum if available we must
13572 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13573 	 * If either of these fails along the way the mblk is freed.
13574 	 * If this logic ever changes and mblk is reused to say send
13575 	 * ICMP's back, then this flag may need to be cleared in
13576 	 * other places as well.
13577 	 */
13578 	DB_CKSUMFLAGS(mp) = 0;
13579 
13580 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13581 
13582 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13583 #ifdef	_BIG_ENDIAN
13584 	u1 += IPPROTO_TCP;
13585 #else
13586 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13587 #endif
13588 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13589 	/*
13590 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13591 	 */
13592 	IP_STAT(ipst, ip_in_sw_cksum);
13593 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13594 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13595 		goto error;
13596 	}
13597 
13598 	IP_STAT(ipst, ip_tcp_slow_path);
13599 	goto try_again;
13600 #undef  iphs
13601 #undef  rptr
13602 
13603 error:
13604 	freemsg(first_mp);
13605 slow_done:
13606 	return (NULL);
13607 }
13608 
13609 /* ARGSUSED */
13610 static void
13611 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13612     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13613 {
13614 	conn_t		*connp;
13615 	uint32_t	sum;
13616 	uint32_t	u1;
13617 	ssize_t		len;
13618 	sctp_hdr_t	*sctph;
13619 	zoneid_t	zoneid = ire->ire_zoneid;
13620 	uint32_t	pktsum;
13621 	uint32_t	calcsum;
13622 	uint32_t	ports;
13623 	in6_addr_t	map_src, map_dst;
13624 	ill_t		*ill = (ill_t *)q->q_ptr;
13625 	ip_stack_t	*ipst;
13626 	sctp_stack_t	*sctps;
13627 
13628 	ASSERT(recv_ill != NULL);
13629 	ipst = recv_ill->ill_ipst;
13630 	sctps = ipst->ips_netstack->netstack_sctp;
13631 
13632 #define	rptr	((uchar_t *)ipha)
13633 
13634 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13635 	ASSERT(ill != NULL);
13636 
13637 	/* u1 is # words of IP options */
13638 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13639 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13640 
13641 	/* IP options present */
13642 	if (u1 > 0) {
13643 		goto ipoptions;
13644 	} else {
13645 		/* Check the IP header checksum.  */
13646 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13647 #define	uph	((uint16_t *)ipha)
13648 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13649 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13650 #undef	uph
13651 			/* finish doing IP checksum */
13652 			sum = (sum & 0xFFFF) + (sum >> 16);
13653 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13654 			/*
13655 			 * Don't verify header checksum if this packet
13656 			 * is coming back from AH/ESP as we already did it.
13657 			 */
13658 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13659 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13660 				goto error;
13661 			}
13662 		}
13663 		/*
13664 		 * Since there is no SCTP h/w cksum support yet, just
13665 		 * clear the flag.
13666 		 */
13667 		DB_CKSUMFLAGS(mp) = 0;
13668 	}
13669 
13670 	/*
13671 	 * Don't verify header checksum if this packet is coming
13672 	 * back from AH/ESP as we already did it.
13673 	 */
13674 	if (!mctl_present) {
13675 		UPDATE_IB_PKT_COUNT(ire);
13676 		ire->ire_last_used_time = lbolt;
13677 	}
13678 
13679 	/* packet part of fragmented IP packet? */
13680 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13681 	if (u1 & (IPH_MF | IPH_OFFSET))
13682 		goto fragmented;
13683 
13684 	/* u1 = IP header length (20 bytes) */
13685 	u1 = IP_SIMPLE_HDR_LENGTH;
13686 
13687 find_sctp_client:
13688 	/* Pullup if we don't have the sctp common header. */
13689 	len = MBLKL(mp);
13690 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13691 		if (mp->b_cont == NULL ||
13692 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13693 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13694 			goto error;
13695 		}
13696 		ipha = (ipha_t *)mp->b_rptr;
13697 		len = MBLKL(mp);
13698 	}
13699 
13700 	sctph = (sctp_hdr_t *)(rptr + u1);
13701 #ifdef	DEBUG
13702 	if (!skip_sctp_cksum) {
13703 #endif
13704 		pktsum = sctph->sh_chksum;
13705 		sctph->sh_chksum = 0;
13706 		calcsum = sctp_cksum(mp, u1);
13707 		if (calcsum != pktsum) {
13708 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13709 			goto error;
13710 		}
13711 		sctph->sh_chksum = pktsum;
13712 #ifdef	DEBUG	/* skip_sctp_cksum */
13713 	}
13714 #endif
13715 	/* get the ports */
13716 	ports = *(uint32_t *)&sctph->sh_sport;
13717 
13718 	IRE_REFRELE(ire);
13719 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13720 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13721 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13722 	    sctps)) == NULL) {
13723 		/* Check for raw socket or OOTB handling */
13724 		goto no_conn;
13725 	}
13726 
13727 	/* Found a client; up it goes */
13728 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13729 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13730 	return;
13731 
13732 no_conn:
13733 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13734 	    ports, mctl_present, flags, B_TRUE, zoneid);
13735 	return;
13736 
13737 ipoptions:
13738 	DB_CKSUMFLAGS(mp) = 0;
13739 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13740 		goto slow_done;
13741 
13742 	UPDATE_IB_PKT_COUNT(ire);
13743 	ire->ire_last_used_time = lbolt;
13744 
13745 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13746 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13747 fragmented:
13748 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13749 			goto slow_done;
13750 		/*
13751 		 * Make sure that first_mp points back to mp as
13752 		 * the mp we came in with could have changed in
13753 		 * ip_rput_fragment().
13754 		 */
13755 		ASSERT(!mctl_present);
13756 		ipha = (ipha_t *)mp->b_rptr;
13757 		first_mp = mp;
13758 	}
13759 
13760 	/* Now we have a complete datagram, destined for this machine. */
13761 	u1 = IPH_HDR_LENGTH(ipha);
13762 	goto find_sctp_client;
13763 #undef  iphs
13764 #undef  rptr
13765 
13766 error:
13767 	freemsg(first_mp);
13768 slow_done:
13769 	IRE_REFRELE(ire);
13770 }
13771 
13772 #define	VER_BITS	0xF0
13773 #define	VERSION_6	0x60
13774 
13775 static boolean_t
13776 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13777     ipaddr_t *dstp, ip_stack_t *ipst)
13778 {
13779 	uint_t	opt_len;
13780 	ipha_t *ipha;
13781 	ssize_t len;
13782 	uint_t	pkt_len;
13783 
13784 	ASSERT(ill != NULL);
13785 	IP_STAT(ipst, ip_ipoptions);
13786 	ipha = *iphapp;
13787 
13788 #define	rptr    ((uchar_t *)ipha)
13789 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13790 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13791 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13792 		freemsg(mp);
13793 		return (B_FALSE);
13794 	}
13795 
13796 	/* multiple mblk or too short */
13797 	pkt_len = ntohs(ipha->ipha_length);
13798 
13799 	/* Get the number of words of IP options in the IP header. */
13800 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13801 	if (opt_len) {
13802 		/* IP Options present!  Validate and process. */
13803 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13804 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13805 			goto done;
13806 		}
13807 		/*
13808 		 * Recompute complete header length and make sure we
13809 		 * have access to all of it.
13810 		 */
13811 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13812 		if (len > (mp->b_wptr - rptr)) {
13813 			if (len > pkt_len) {
13814 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13815 				goto done;
13816 			}
13817 			if (!pullupmsg(mp, len)) {
13818 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13819 				goto done;
13820 			}
13821 			ipha = (ipha_t *)mp->b_rptr;
13822 		}
13823 		/*
13824 		 * Go off to ip_rput_options which returns the next hop
13825 		 * destination address, which may have been affected
13826 		 * by source routing.
13827 		 */
13828 		IP_STAT(ipst, ip_opt);
13829 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13830 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13831 			return (B_FALSE);
13832 		}
13833 	}
13834 	*iphapp = ipha;
13835 	return (B_TRUE);
13836 done:
13837 	/* clear b_prev - used by ip_mroute_decap */
13838 	mp->b_prev = NULL;
13839 	freemsg(mp);
13840 	return (B_FALSE);
13841 #undef  rptr
13842 }
13843 
13844 /*
13845  * Deal with the fact that there is no ire for the destination.
13846  * The incoming ill (in_ill) is passed in to ip_newroute only
13847  * in the case of packets coming from mobile ip forward tunnel.
13848  * It must be null otherwise.
13849  */
13850 static ire_t *
13851 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13852     ipaddr_t dst)
13853 {
13854 	ipha_t	*ipha;
13855 	ill_t	*ill;
13856 	ire_t	*ire;
13857 	boolean_t	check_multirt = B_FALSE;
13858 	ip_stack_t *ipst;
13859 
13860 	ipha = (ipha_t *)mp->b_rptr;
13861 	ill = (ill_t *)q->q_ptr;
13862 
13863 	ASSERT(ill != NULL);
13864 	ipst = ill->ill_ipst;
13865 
13866 	/*
13867 	 * No IRE for this destination, so it can't be for us.
13868 	 * Unless we are forwarding, drop the packet.
13869 	 * We have to let source routed packets through
13870 	 * since we don't yet know if they are 'ping -l'
13871 	 * packets i.e. if they will go out over the
13872 	 * same interface as they came in on.
13873 	 */
13874 	if (ll_multicast) {
13875 		freemsg(mp);
13876 		return (NULL);
13877 	}
13878 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13879 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13880 		freemsg(mp);
13881 		return (NULL);
13882 	}
13883 
13884 	/*
13885 	 * Mark this packet as having originated externally.
13886 	 *
13887 	 * For non-forwarding code path, ire_send later double
13888 	 * checks this interface to see if it is still exists
13889 	 * post-ARP resolution.
13890 	 *
13891 	 * Also, IPQOS uses this to differentiate between
13892 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13893 	 * QOS packet processing in ip_wput_attach_llhdr().
13894 	 * The QoS module can mark the b_band for a fastpath message
13895 	 * or the dl_priority field in a unitdata_req header for
13896 	 * CoS marking. This info can only be found in
13897 	 * ip_wput_attach_llhdr().
13898 	 */
13899 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13900 	/*
13901 	 * Clear the indication that this may have a hardware checksum
13902 	 * as we are not using it
13903 	 */
13904 	DB_CKSUMFLAGS(mp) = 0;
13905 
13906 	if (in_ill != NULL) {
13907 		/*
13908 		 * Now hand the packet to ip_newroute.
13909 		 */
13910 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13911 		return (NULL);
13912 	}
13913 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13914 	    MBLK_GETLABEL(mp), ipst);
13915 
13916 	if (ire == NULL && check_multirt) {
13917 		/* Let ip_newroute handle CGTP  */
13918 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13919 		return (NULL);
13920 	}
13921 
13922 	if (ire != NULL)
13923 		return (ire);
13924 
13925 	mp->b_prev = mp->b_next = 0;
13926 	/* send icmp unreachable */
13927 	q = WR(q);
13928 	/* Sent by forwarding path, and router is global zone */
13929 	if (ip_source_routed(ipha, ipst)) {
13930 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13931 		    GLOBAL_ZONEID, ipst);
13932 	} else {
13933 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13934 		    ipst);
13935 	}
13936 
13937 	return (NULL);
13938 
13939 }
13940 
13941 /*
13942  * check ip header length and align it.
13943  */
13944 static boolean_t
13945 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13946 {
13947 	ssize_t len;
13948 	ill_t *ill;
13949 	ipha_t	*ipha;
13950 
13951 	len = MBLKL(mp);
13952 
13953 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13954 		ill = (ill_t *)q->q_ptr;
13955 
13956 		if (!OK_32PTR(mp->b_rptr))
13957 			IP_STAT(ipst, ip_notaligned1);
13958 		else
13959 			IP_STAT(ipst, ip_notaligned2);
13960 		/* Guard against bogus device drivers */
13961 		if (len < 0) {
13962 			/* clear b_prev - used by ip_mroute_decap */
13963 			mp->b_prev = NULL;
13964 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13965 			freemsg(mp);
13966 			return (B_FALSE);
13967 		}
13968 
13969 		if (ip_rput_pullups++ == 0) {
13970 			ipha = (ipha_t *)mp->b_rptr;
13971 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13972 			    "ip_check_and_align_header: %s forced us to "
13973 			    " pullup pkt, hdr len %ld, hdr addr %p",
13974 			    ill->ill_name, len, ipha);
13975 		}
13976 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13977 			/* clear b_prev - used by ip_mroute_decap */
13978 			mp->b_prev = NULL;
13979 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13980 			freemsg(mp);
13981 			return (B_FALSE);
13982 		}
13983 	}
13984 	return (B_TRUE);
13985 }
13986 
13987 ire_t *
13988 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13989 {
13990 	ire_t		*new_ire;
13991 	ill_t		*ire_ill;
13992 	uint_t		ifindex;
13993 	ip_stack_t	*ipst = ill->ill_ipst;
13994 	boolean_t	strict_check = B_FALSE;
13995 
13996 	/*
13997 	 * This packet came in on an interface other than the one associated
13998 	 * with the first ire we found for the destination address. We do
13999 	 * another ire lookup here, using the ingress ill, to see if the
14000 	 * interface is in an interface group.
14001 	 * As long as the ills belong to the same group, we don't consider
14002 	 * them to be arriving on the wrong interface. Thus, if the switch
14003 	 * is doing inbound load spreading, we won't drop packets when the
14004 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
14005 	 * for 'usesrc groups' where the destination address may belong to
14006 	 * another interface to allow multipathing to happen.
14007 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
14008 	 * where the local address may not be unique. In this case we were
14009 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
14010 	 * actually returned. The new lookup, which is more specific, should
14011 	 * only find the IRE_LOCAL associated with the ingress ill if one
14012 	 * exists.
14013 	 */
14014 
14015 	if (ire->ire_ipversion == IPV4_VERSION) {
14016 		if (ipst->ips_ip_strict_dst_multihoming)
14017 			strict_check = B_TRUE;
14018 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
14019 		    ill->ill_ipif, ALL_ZONES, NULL,
14020 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14021 	} else {
14022 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
14023 		if (ipst->ips_ipv6_strict_dst_multihoming)
14024 			strict_check = B_TRUE;
14025 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
14026 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
14027 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14028 	}
14029 	/*
14030 	 * If the same ire that was returned in ip_input() is found then this
14031 	 * is an indication that interface groups are in use. The packet
14032 	 * arrived on a different ill in the group than the one associated with
14033 	 * the destination address.  If a different ire was found then the same
14034 	 * IP address must be hosted on multiple ills. This is possible with
14035 	 * unnumbered point2point interfaces. We switch to use this new ire in
14036 	 * order to have accurate interface statistics.
14037 	 */
14038 	if (new_ire != NULL) {
14039 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
14040 			ire_refrele(ire);
14041 			ire = new_ire;
14042 		} else {
14043 			ire_refrele(new_ire);
14044 		}
14045 		return (ire);
14046 	} else if ((ire->ire_rfq == NULL) &&
14047 		    (ire->ire_ipversion == IPV4_VERSION)) {
14048 		/*
14049 		 * The best match could have been the original ire which
14050 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
14051 		 * the strict multihoming checks are irrelevant as we consider
14052 		 * local addresses hosted on lo0 to be interface agnostic. We
14053 		 * only expect a null ire_rfq on IREs which are associated with
14054 		 * lo0 hence we can return now.
14055 		 */
14056 		return (ire);
14057 	}
14058 
14059 	/*
14060 	 * Chase pointers once and store locally.
14061 	 */
14062 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
14063 	    (ill_t *)(ire->ire_rfq->q_ptr);
14064 	ifindex = ill->ill_usesrc_ifindex;
14065 
14066 	/*
14067 	 * Check if it's a legal address on the 'usesrc' interface.
14068 	 */
14069 	if ((ifindex != 0) && (ire_ill != NULL) &&
14070 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
14071 		return (ire);
14072 	}
14073 
14074 	/*
14075 	 * If the ip*_strict_dst_multihoming switch is on then we can
14076 	 * only accept this packet if the interface is marked as routing.
14077 	 */
14078 	if (!(strict_check))
14079 		return (ire);
14080 
14081 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
14082 	    ILLF_ROUTER) != 0) {
14083 		return (ire);
14084 	}
14085 
14086 	ire_refrele(ire);
14087 	return (NULL);
14088 }
14089 
14090 ire_t *
14091 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
14092 {
14093 	ipha_t	*ipha;
14094 	ipaddr_t ip_dst, ip_src;
14095 	ire_t	*src_ire = NULL;
14096 	ill_t	*stq_ill;
14097 	uint_t	hlen;
14098 	uint_t	pkt_len;
14099 	uint32_t sum;
14100 	queue_t	*dev_q;
14101 	boolean_t check_multirt = B_FALSE;
14102 	ip_stack_t *ipst = ill->ill_ipst;
14103 
14104 	ipha = (ipha_t *)mp->b_rptr;
14105 
14106 	/*
14107 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14108 	 * The loopback address check for both src and dst has already
14109 	 * been checked in ip_input
14110 	 */
14111 	ip_dst = ntohl(dst);
14112 	ip_src = ntohl(ipha->ipha_src);
14113 
14114 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
14115 	    IN_CLASSD(ip_src)) {
14116 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14117 		goto drop;
14118 	}
14119 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14120 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14121 
14122 	if (src_ire != NULL) {
14123 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14124 		goto drop;
14125 	}
14126 
14127 
14128 	/* No ire cache of nexthop. So first create one  */
14129 	if (ire == NULL) {
14130 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
14131 		/*
14132 		 * We only come to ip_fast_forward if ip_cgtp_filter is
14133 		 * is not set. So upon return from ire_forward
14134 		 * check_multirt should remain as false.
14135 		 */
14136 		ASSERT(!check_multirt);
14137 		if (ire == NULL) {
14138 			/* An attempt was made to forward the packet */
14139 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14140 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14141 			mp->b_prev = mp->b_next = 0;
14142 			/* send icmp unreachable */
14143 			/* Sent by forwarding path, and router is global zone */
14144 			if (ip_source_routed(ipha, ipst)) {
14145 				icmp_unreachable(ill->ill_wq, mp,
14146 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
14147 				    ipst);
14148 			} else {
14149 				icmp_unreachable(ill->ill_wq, mp,
14150 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
14151 				    ipst);
14152 			}
14153 			return (ire);
14154 		}
14155 	}
14156 
14157 	/*
14158 	 * Forwarding fastpath exception case:
14159 	 * If either of the follwoing case is true, we take
14160 	 * the slowpath
14161 	 *	o forwarding is not enabled
14162 	 *	o incoming and outgoing interface are the same, or the same
14163 	 *	  IPMP group
14164 	 *	o corresponding ire is in incomplete state
14165 	 *	o packet needs fragmentation
14166 	 *
14167 	 * The codeflow from here on is thus:
14168 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14169 	 */
14170 	pkt_len = ntohs(ipha->ipha_length);
14171 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14172 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14173 	    !(ill->ill_flags & ILLF_ROUTER) ||
14174 	    (ill == stq_ill) ||
14175 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14176 	    (ire->ire_nce == NULL) ||
14177 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14178 	    (pkt_len > ire->ire_max_frag) ||
14179 	    ipha->ipha_ttl <= 1) {
14180 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14181 		    ipha, ill, B_FALSE);
14182 		return (ire);
14183 	}
14184 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14185 
14186 	DTRACE_PROBE4(ip4__forwarding__start,
14187 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14188 
14189 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14190 	    ipst->ips_ipv4firewall_forwarding,
14191 	    ill, stq_ill, ipha, mp, mp, ipst);
14192 
14193 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14194 
14195 	if (mp == NULL)
14196 		goto drop;
14197 
14198 	mp->b_datap->db_struioun.cksum.flags = 0;
14199 	/* Adjust the checksum to reflect the ttl decrement. */
14200 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14201 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14202 	ipha->ipha_ttl--;
14203 
14204 	dev_q = ire->ire_stq->q_next;
14205 	if ((dev_q->q_next != NULL ||
14206 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14207 		goto indiscard;
14208 	}
14209 
14210 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14211 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14212 
14213 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14214 		mblk_t *mpip = mp;
14215 
14216 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14217 		if (mp != NULL) {
14218 			DTRACE_PROBE4(ip4__physical__out__start,
14219 			    ill_t *, NULL, ill_t *, stq_ill,
14220 			    ipha_t *, ipha, mblk_t *, mp);
14221 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14222 			    ipst->ips_ipv4firewall_physical_out,
14223 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14224 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14225 			    mp);
14226 			if (mp == NULL)
14227 				goto drop;
14228 
14229 			UPDATE_IB_PKT_COUNT(ire);
14230 			ire->ire_last_used_time = lbolt;
14231 			BUMP_MIB(stq_ill->ill_ip_mib,
14232 			    ipIfStatsHCOutForwDatagrams);
14233 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14234 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14235 			    pkt_len);
14236 			putnext(ire->ire_stq, mp);
14237 			return (ire);
14238 		}
14239 	}
14240 
14241 indiscard:
14242 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14243 drop:
14244 	if (mp != NULL)
14245 		freemsg(mp);
14246 	if (src_ire != NULL)
14247 		ire_refrele(src_ire);
14248 	return (ire);
14249 
14250 }
14251 
14252 /*
14253  * This function is called in the forwarding slowpath, when
14254  * either the ire lacks the link-layer address, or the packet needs
14255  * further processing(eg. fragmentation), before transmission.
14256  */
14257 
14258 static void
14259 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14260     ill_t *ill, boolean_t ll_multicast)
14261 {
14262 	ill_group_t	*ill_group;
14263 	ill_group_t	*ire_group;
14264 	queue_t		*dev_q;
14265 	ire_t		*src_ire;
14266 	ip_stack_t	*ipst = ill->ill_ipst;
14267 
14268 	ASSERT(ire->ire_stq != NULL);
14269 
14270 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14271 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14272 
14273 	if (ll_multicast != 0) {
14274 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14275 		goto drop_pkt;
14276 	}
14277 
14278 	/*
14279 	 * check if ipha_src is a broadcast address. Note that this
14280 	 * check is redundant when we get here from ip_fast_forward()
14281 	 * which has already done this check. However, since we can
14282 	 * also get here from ip_rput_process_broadcast() or, for
14283 	 * for the slow path through ip_fast_forward(), we perform
14284 	 * the check again for code-reusability
14285 	 */
14286 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14287 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14288 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14289 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14290 		if (src_ire != NULL)
14291 			ire_refrele(src_ire);
14292 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14293 		ip2dbg(("ip_rput_process_forward: Received packet with"
14294 		    " bad src/dst address on %s\n", ill->ill_name));
14295 		goto drop_pkt;
14296 	}
14297 
14298 	ill_group = ill->ill_group;
14299 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14300 	/*
14301 	 * Check if we want to forward this one at this time.
14302 	 * We allow source routed packets on a host provided that
14303 	 * they go out the same interface or same interface group
14304 	 * as they came in on.
14305 	 *
14306 	 * XXX To be quicker, we may wish to not chase pointers to
14307 	 * get the ILLF_ROUTER flag and instead store the
14308 	 * forwarding policy in the ire.  An unfortunate
14309 	 * side-effect of that would be requiring an ire flush
14310 	 * whenever the ILLF_ROUTER flag changes.
14311 	 */
14312 	if (((ill->ill_flags &
14313 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14314 	    ILLF_ROUTER) == 0) &&
14315 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14316 	    (ill_group != NULL && ill_group == ire_group)))) {
14317 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14318 		if (ip_source_routed(ipha, ipst)) {
14319 			q = WR(q);
14320 			/*
14321 			 * Clear the indication that this may have
14322 			 * hardware checksum as we are not using it.
14323 			 */
14324 			DB_CKSUMFLAGS(mp) = 0;
14325 			/* Sent by forwarding path, and router is global zone */
14326 			icmp_unreachable(q, mp,
14327 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14328 			return;
14329 		}
14330 		goto drop_pkt;
14331 	}
14332 
14333 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14334 
14335 	/* Packet is being forwarded. Turning off hwcksum flag. */
14336 	DB_CKSUMFLAGS(mp) = 0;
14337 	if (ipst->ips_ip_g_send_redirects) {
14338 		/*
14339 		 * Check whether the incoming interface and outgoing
14340 		 * interface is part of the same group. If so,
14341 		 * send redirects.
14342 		 *
14343 		 * Check the source address to see if it originated
14344 		 * on the same logical subnet it is going back out on.
14345 		 * If so, we should be able to send it a redirect.
14346 		 * Avoid sending a redirect if the destination
14347 		 * is directly connected (i.e., ipha_dst is the same
14348 		 * as ire_gateway_addr or the ire_addr of the
14349 		 * nexthop IRE_CACHE ), or if the packet was source
14350 		 * routed out this interface.
14351 		 */
14352 		ipaddr_t src, nhop;
14353 		mblk_t	*mp1;
14354 		ire_t	*nhop_ire = NULL;
14355 
14356 		/*
14357 		 * Check whether ire_rfq and q are from the same ill
14358 		 * or if they are not same, they at least belong
14359 		 * to the same group. If so, send redirects.
14360 		 */
14361 		if ((ire->ire_rfq == q ||
14362 		    (ill_group != NULL && ill_group == ire_group)) &&
14363 		    !ip_source_routed(ipha, ipst)) {
14364 
14365 			nhop = (ire->ire_gateway_addr != 0 ?
14366 			    ire->ire_gateway_addr : ire->ire_addr);
14367 
14368 			if (ipha->ipha_dst == nhop) {
14369 				/*
14370 				 * We avoid sending a redirect if the
14371 				 * destination is directly connected
14372 				 * because it is possible that multiple
14373 				 * IP subnets may have been configured on
14374 				 * the link, and the source may not
14375 				 * be on the same subnet as ip destination,
14376 				 * even though they are on the same
14377 				 * physical link.
14378 				 */
14379 				goto sendit;
14380 			}
14381 
14382 			src = ipha->ipha_src;
14383 
14384 			/*
14385 			 * We look up the interface ire for the nexthop,
14386 			 * to see if ipha_src is in the same subnet
14387 			 * as the nexthop.
14388 			 *
14389 			 * Note that, if, in the future, IRE_CACHE entries
14390 			 * are obsoleted,  this lookup will not be needed,
14391 			 * as the ire passed to this function will be the
14392 			 * same as the nhop_ire computed below.
14393 			 */
14394 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14395 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14396 			    0, NULL, MATCH_IRE_TYPE, ipst);
14397 
14398 			if (nhop_ire != NULL) {
14399 				if ((src & nhop_ire->ire_mask) ==
14400 				    (nhop & nhop_ire->ire_mask)) {
14401 					/*
14402 					 * The source is directly connected.
14403 					 * Just copy the ip header (which is
14404 					 * in the first mblk)
14405 					 */
14406 					mp1 = copyb(mp);
14407 					if (mp1 != NULL) {
14408 						icmp_send_redirect(WR(q), mp1,
14409 						    nhop, ipst);
14410 					}
14411 				}
14412 				ire_refrele(nhop_ire);
14413 			}
14414 		}
14415 	}
14416 sendit:
14417 	dev_q = ire->ire_stq->q_next;
14418 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14419 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14420 		freemsg(mp);
14421 		return;
14422 	}
14423 
14424 	ip_rput_forward(ire, ipha, mp, ill);
14425 	return;
14426 
14427 drop_pkt:
14428 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14429 	freemsg(mp);
14430 }
14431 
14432 ire_t *
14433 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14434     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14435 {
14436 	queue_t		*q;
14437 	uint16_t	hcksumflags;
14438 	ip_stack_t	*ipst = ill->ill_ipst;
14439 
14440 	q = *qp;
14441 
14442 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14443 
14444 	/*
14445 	 * Clear the indication that this may have hardware
14446 	 * checksum as we are not using it for forwarding.
14447 	 */
14448 	hcksumflags = DB_CKSUMFLAGS(mp);
14449 	DB_CKSUMFLAGS(mp) = 0;
14450 
14451 	/*
14452 	 * Directed broadcast forwarding: if the packet came in over a
14453 	 * different interface then it is routed out over we can forward it.
14454 	 */
14455 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14456 		ire_refrele(ire);
14457 		freemsg(mp);
14458 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14459 		return (NULL);
14460 	}
14461 	/*
14462 	 * For multicast we have set dst to be INADDR_BROADCAST
14463 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14464 	 * only for broadcast packets.
14465 	 */
14466 	if (!CLASSD(ipha->ipha_dst)) {
14467 		ire_t *new_ire;
14468 		ipif_t *ipif;
14469 		/*
14470 		 * For ill groups, as the switch duplicates broadcasts
14471 		 * across all the ports, we need to filter out and
14472 		 * send up only one copy. There is one copy for every
14473 		 * broadcast address on each ill. Thus, we look for a
14474 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14475 		 * later to see whether this ill is eligible to receive
14476 		 * them or not. ill_nominate_bcast_rcv() nominates only
14477 		 * one set of IREs for receiving.
14478 		 */
14479 
14480 		ipif = ipif_get_next_ipif(NULL, ill);
14481 		if (ipif == NULL) {
14482 			ire_refrele(ire);
14483 			freemsg(mp);
14484 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14485 			return (NULL);
14486 		}
14487 		new_ire = ire_ctable_lookup(dst, 0, 0,
14488 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14489 		ipif_refrele(ipif);
14490 
14491 		if (new_ire != NULL) {
14492 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14493 				ire_refrele(ire);
14494 				ire_refrele(new_ire);
14495 				freemsg(mp);
14496 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14497 				return (NULL);
14498 			}
14499 			/*
14500 			 * In the special case of multirouted broadcast
14501 			 * packets, we unconditionally need to "gateway"
14502 			 * them to the appropriate interface here.
14503 			 * In the normal case, this cannot happen, because
14504 			 * there is no broadcast IRE tagged with the
14505 			 * RTF_MULTIRT flag.
14506 			 */
14507 			if (new_ire->ire_flags & RTF_MULTIRT) {
14508 				ire_refrele(new_ire);
14509 				if (ire->ire_rfq != NULL) {
14510 					q = ire->ire_rfq;
14511 					*qp = q;
14512 				}
14513 			} else {
14514 				ire_refrele(ire);
14515 				ire = new_ire;
14516 			}
14517 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14518 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14519 				/*
14520 				 * Free the message if
14521 				 * ip_g_forward_directed_bcast is turned
14522 				 * off for non-local broadcast.
14523 				 */
14524 				ire_refrele(ire);
14525 				freemsg(mp);
14526 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14527 				return (NULL);
14528 			}
14529 		} else {
14530 			/*
14531 			 * This CGTP packet successfully passed the
14532 			 * CGTP filter, but the related CGTP
14533 			 * broadcast IRE has not been found,
14534 			 * meaning that the redundant ipif is
14535 			 * probably down. However, if we discarded
14536 			 * this packet, its duplicate would be
14537 			 * filtered out by the CGTP filter so none
14538 			 * of them would get through. So we keep
14539 			 * going with this one.
14540 			 */
14541 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14542 			if (ire->ire_rfq != NULL) {
14543 				q = ire->ire_rfq;
14544 				*qp = q;
14545 			}
14546 		}
14547 	}
14548 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14549 		/*
14550 		 * Verify that there are not more then one
14551 		 * IRE_BROADCAST with this broadcast address which
14552 		 * has ire_stq set.
14553 		 * TODO: simplify, loop over all IRE's
14554 		 */
14555 		ire_t	*ire1;
14556 		int	num_stq = 0;
14557 		mblk_t	*mp1;
14558 
14559 		/* Find the first one with ire_stq set */
14560 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14561 		for (ire1 = ire; ire1 &&
14562 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14563 		    ire1 = ire1->ire_next)
14564 			;
14565 		if (ire1) {
14566 			ire_refrele(ire);
14567 			ire = ire1;
14568 			IRE_REFHOLD(ire);
14569 		}
14570 
14571 		/* Check if there are additional ones with stq set */
14572 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14573 			if (ire->ire_addr != ire1->ire_addr)
14574 				break;
14575 			if (ire1->ire_stq) {
14576 				num_stq++;
14577 				break;
14578 			}
14579 		}
14580 		rw_exit(&ire->ire_bucket->irb_lock);
14581 		if (num_stq == 1 && ire->ire_stq != NULL) {
14582 			ip1dbg(("ip_rput_process_broadcast: directed "
14583 			    "broadcast to 0x%x\n",
14584 			    ntohl(ire->ire_addr)));
14585 			mp1 = copymsg(mp);
14586 			if (mp1) {
14587 				switch (ipha->ipha_protocol) {
14588 				case IPPROTO_UDP:
14589 					ip_udp_input(q, mp1, ipha, ire, ill);
14590 					break;
14591 				default:
14592 					ip_proto_input(q, mp1, ipha, ire, ill);
14593 					break;
14594 				}
14595 			}
14596 			/*
14597 			 * Adjust ttl to 2 (1+1 - the forward engine
14598 			 * will decrement it by one.
14599 			 */
14600 			if (ip_csum_hdr(ipha)) {
14601 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14602 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14603 				freemsg(mp);
14604 				ire_refrele(ire);
14605 				return (NULL);
14606 			}
14607 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14608 			ipha->ipha_hdr_checksum = 0;
14609 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14610 			ip_rput_process_forward(q, mp, ire, ipha,
14611 			    ill, ll_multicast);
14612 			ire_refrele(ire);
14613 			return (NULL);
14614 		}
14615 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14616 		    ntohl(ire->ire_addr)));
14617 	}
14618 
14619 
14620 	/* Restore any hardware checksum flags */
14621 	DB_CKSUMFLAGS(mp) = hcksumflags;
14622 	return (ire);
14623 }
14624 
14625 /* ARGSUSED */
14626 static boolean_t
14627 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14628     int *ll_multicast, ipaddr_t *dstp)
14629 {
14630 	ip_stack_t	*ipst = ill->ill_ipst;
14631 
14632 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14633 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14634 	    ntohs(ipha->ipha_length));
14635 
14636 	/*
14637 	 * Forward packets only if we have joined the allmulti
14638 	 * group on this interface.
14639 	 */
14640 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14641 		int retval;
14642 
14643 		/*
14644 		 * Clear the indication that this may have hardware
14645 		 * checksum as we are not using it.
14646 		 */
14647 		DB_CKSUMFLAGS(mp) = 0;
14648 		retval = ip_mforward(ill, ipha, mp);
14649 		/* ip_mforward updates mib variables if needed */
14650 		/* clear b_prev - used by ip_mroute_decap */
14651 		mp->b_prev = NULL;
14652 
14653 		switch (retval) {
14654 		case 0:
14655 			/*
14656 			 * pkt is okay and arrived on phyint.
14657 			 *
14658 			 * If we are running as a multicast router
14659 			 * we need to see all IGMP and/or PIM packets.
14660 			 */
14661 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14662 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14663 				goto done;
14664 			}
14665 			break;
14666 		case -1:
14667 			/* pkt is mal-formed, toss it */
14668 			goto drop_pkt;
14669 		case 1:
14670 			/* pkt is okay and arrived on a tunnel */
14671 			/*
14672 			 * If we are running a multicast router
14673 			 *  we need to see all igmp packets.
14674 			 */
14675 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14676 				*dstp = INADDR_BROADCAST;
14677 				*ll_multicast = 1;
14678 				return (B_FALSE);
14679 			}
14680 
14681 			goto drop_pkt;
14682 		}
14683 	}
14684 
14685 	ILM_WALKER_HOLD(ill);
14686 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14687 		/*
14688 		 * This might just be caused by the fact that
14689 		 * multiple IP Multicast addresses map to the same
14690 		 * link layer multicast - no need to increment counter!
14691 		 */
14692 		ILM_WALKER_RELE(ill);
14693 		freemsg(mp);
14694 		return (B_TRUE);
14695 	}
14696 	ILM_WALKER_RELE(ill);
14697 done:
14698 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14699 	/*
14700 	 * This assumes the we deliver to all streams for multicast
14701 	 * and broadcast packets.
14702 	 */
14703 	*dstp = INADDR_BROADCAST;
14704 	*ll_multicast = 1;
14705 	return (B_FALSE);
14706 drop_pkt:
14707 	ip2dbg(("ip_rput: drop pkt\n"));
14708 	freemsg(mp);
14709 	return (B_TRUE);
14710 }
14711 
14712 static boolean_t
14713 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14714     int *ll_multicast, mblk_t **mpp)
14715 {
14716 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14717 	boolean_t must_copy = B_FALSE;
14718 	struct iocblk   *iocp;
14719 	ipha_t		*ipha;
14720 	ip_stack_t	*ipst = ill->ill_ipst;
14721 
14722 #define	rptr    ((uchar_t *)ipha)
14723 
14724 	first_mp = *first_mpp;
14725 	mp = *mpp;
14726 
14727 	ASSERT(first_mp == mp);
14728 
14729 	/*
14730 	 * if db_ref > 1 then copymsg and free original. Packet may be
14731 	 * changed and do not want other entity who has a reference to this
14732 	 * message to trip over the changes. This is a blind change because
14733 	 * trying to catch all places that might change packet is too
14734 	 * difficult (since it may be a module above this one)
14735 	 *
14736 	 * This corresponds to the non-fast path case. We walk down the full
14737 	 * chain in this case, and check the db_ref count of all the dblks,
14738 	 * and do a copymsg if required. It is possible that the db_ref counts
14739 	 * of the data blocks in the mblk chain can be different.
14740 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14741 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14742 	 * 'snoop' is running.
14743 	 */
14744 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14745 		if (mp1->b_datap->db_ref > 1) {
14746 			must_copy = B_TRUE;
14747 			break;
14748 		}
14749 	}
14750 
14751 	if (must_copy) {
14752 		mp1 = copymsg(mp);
14753 		if (mp1 == NULL) {
14754 			for (mp1 = mp; mp1 != NULL;
14755 			    mp1 = mp1->b_cont) {
14756 				mp1->b_next = NULL;
14757 				mp1->b_prev = NULL;
14758 			}
14759 			freemsg(mp);
14760 			if (ill != NULL) {
14761 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14762 			} else {
14763 				BUMP_MIB(&ipst->ips_ip_mib,
14764 				    ipIfStatsInDiscards);
14765 			}
14766 			return (B_TRUE);
14767 		}
14768 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14769 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14770 			/* Copy b_prev - used by ip_mroute_decap */
14771 			to_mp->b_prev = from_mp->b_prev;
14772 			from_mp->b_prev = NULL;
14773 		}
14774 		*first_mpp = first_mp = mp1;
14775 		freemsg(mp);
14776 		mp = mp1;
14777 		*mpp = mp1;
14778 	}
14779 
14780 	ipha = (ipha_t *)mp->b_rptr;
14781 
14782 	/*
14783 	 * previous code has a case for M_DATA.
14784 	 * We want to check how that happens.
14785 	 */
14786 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14787 	switch (first_mp->b_datap->db_type) {
14788 	case M_PROTO:
14789 	case M_PCPROTO:
14790 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14791 		    DL_UNITDATA_IND) {
14792 			/* Go handle anything other than data elsewhere. */
14793 			ip_rput_dlpi(q, mp);
14794 			return (B_TRUE);
14795 		}
14796 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14797 		/* Ditch the DLPI header. */
14798 		mp1 = mp->b_cont;
14799 		ASSERT(first_mp == mp);
14800 		*first_mpp = mp1;
14801 		freeb(mp);
14802 		*mpp = mp1;
14803 		return (B_FALSE);
14804 	case M_IOCACK:
14805 		ip1dbg(("got iocack "));
14806 		iocp = (struct iocblk *)mp->b_rptr;
14807 		switch (iocp->ioc_cmd) {
14808 		case DL_IOC_HDR_INFO:
14809 			ill = (ill_t *)q->q_ptr;
14810 			ill_fastpath_ack(ill, mp);
14811 			return (B_TRUE);
14812 		case SIOCSTUNPARAM:
14813 		case OSIOCSTUNPARAM:
14814 			/* Go through qwriter_ip */
14815 			break;
14816 		case SIOCGTUNPARAM:
14817 		case OSIOCGTUNPARAM:
14818 			ip_rput_other(NULL, q, mp, NULL);
14819 			return (B_TRUE);
14820 		default:
14821 			putnext(q, mp);
14822 			return (B_TRUE);
14823 		}
14824 		/* FALLTHRU */
14825 	case M_ERROR:
14826 	case M_HANGUP:
14827 		/*
14828 		 * Since this is on the ill stream we unconditionally
14829 		 * bump up the refcount
14830 		 */
14831 		ill_refhold(ill);
14832 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14833 		    B_FALSE);
14834 		return (B_TRUE);
14835 	case M_CTL:
14836 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14837 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14838 			IPHADA_M_CTL)) {
14839 			/*
14840 			 * It's an IPsec accelerated packet.
14841 			 * Make sure that the ill from which we received the
14842 			 * packet has enabled IPsec hardware acceleration.
14843 			 */
14844 			if (!(ill->ill_capabilities &
14845 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14846 				/* IPsec kstats: bean counter */
14847 				freemsg(mp);
14848 				return (B_TRUE);
14849 			}
14850 
14851 			/*
14852 			 * Make mp point to the mblk following the M_CTL,
14853 			 * then process according to type of mp.
14854 			 * After this processing, first_mp will point to
14855 			 * the data-attributes and mp to the pkt following
14856 			 * the M_CTL.
14857 			 */
14858 			mp = first_mp->b_cont;
14859 			if (mp == NULL) {
14860 				freemsg(first_mp);
14861 				return (B_TRUE);
14862 			}
14863 			/*
14864 			 * A Hardware Accelerated packet can only be M_DATA
14865 			 * ESP or AH packet.
14866 			 */
14867 			if (mp->b_datap->db_type != M_DATA) {
14868 				/* non-M_DATA IPsec accelerated packet */
14869 				IPSECHW_DEBUG(IPSECHW_PKT,
14870 				    ("non-M_DATA IPsec accelerated pkt\n"));
14871 				freemsg(first_mp);
14872 				return (B_TRUE);
14873 			}
14874 			ipha = (ipha_t *)mp->b_rptr;
14875 			if (ipha->ipha_protocol != IPPROTO_AH &&
14876 			    ipha->ipha_protocol != IPPROTO_ESP) {
14877 				IPSECHW_DEBUG(IPSECHW_PKT,
14878 				    ("non-M_DATA IPsec accelerated pkt\n"));
14879 				freemsg(first_mp);
14880 				return (B_TRUE);
14881 			}
14882 			*mpp = mp;
14883 			return (B_FALSE);
14884 		}
14885 		putnext(q, mp);
14886 		return (B_TRUE);
14887 	case M_FLUSH:
14888 		if (*mp->b_rptr & FLUSHW) {
14889 			*mp->b_rptr &= ~FLUSHR;
14890 			qreply(q, mp);
14891 			return (B_TRUE);
14892 		}
14893 		freemsg(mp);
14894 		return (B_TRUE);
14895 	case M_IOCNAK:
14896 		ip1dbg(("got iocnak "));
14897 		iocp = (struct iocblk *)mp->b_rptr;
14898 		switch (iocp->ioc_cmd) {
14899 		case DL_IOC_HDR_INFO:
14900 		case SIOCSTUNPARAM:
14901 		case OSIOCSTUNPARAM:
14902 			/*
14903 			 * Since this is on the ill stream we unconditionally
14904 			 * bump up the refcount
14905 			 */
14906 			ill_refhold(ill);
14907 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14908 			    CUR_OP, B_FALSE);
14909 			return (B_TRUE);
14910 		case SIOCGTUNPARAM:
14911 		case OSIOCGTUNPARAM:
14912 			ip_rput_other(NULL, q, mp, NULL);
14913 			return (B_TRUE);
14914 		default:
14915 			break;
14916 		}
14917 		/* FALLTHRU */
14918 	default:
14919 		putnext(q, mp);
14920 		return (B_TRUE);
14921 	}
14922 }
14923 
14924 /* Read side put procedure.  Packets coming from the wire arrive here. */
14925 void
14926 ip_rput(queue_t *q, mblk_t *mp)
14927 {
14928 	ill_t	*ill;
14929 	ip_stack_t	*ipst;
14930 
14931 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14932 
14933 	ill = (ill_t *)q->q_ptr;
14934 	ipst = ill->ill_ipst;
14935 
14936 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14937 		union DL_primitives *dl;
14938 
14939 		/*
14940 		 * Things are opening or closing. Only accept DLPI control
14941 		 * messages. In the open case, the ill->ill_ipif has not yet
14942 		 * been created. In the close case, things hanging off the
14943 		 * ill could have been freed already. In either case it
14944 		 * may not be safe to proceed further.
14945 		 */
14946 
14947 		dl = (union DL_primitives *)mp->b_rptr;
14948 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14949 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14950 			/*
14951 			 * Also SIOC[GS]TUN* ioctls can come here.
14952 			 */
14953 			inet_freemsg(mp);
14954 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14955 			    "ip_input_end: q %p (%S)", q, "uninit");
14956 			return;
14957 		}
14958 	}
14959 
14960 	/*
14961 	 * if db_ref > 1 then copymsg and free original. Packet may be
14962 	 * changed and we do not want the other entity who has a reference to
14963 	 * this message to trip over the changes. This is a blind change because
14964 	 * trying to catch all places that might change the packet is too
14965 	 * difficult.
14966 	 *
14967 	 * This corresponds to the fast path case, where we have a chain of
14968 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14969 	 * in the mblk chain. There doesn't seem to be a reason why a device
14970 	 * driver would send up data with varying db_ref counts in the mblk
14971 	 * chain. In any case the Fast path is a private interface, and our
14972 	 * drivers don't do such a thing. Given the above assumption, there is
14973 	 * no need to walk down the entire mblk chain (which could have a
14974 	 * potential performance problem)
14975 	 */
14976 	if (mp->b_datap->db_ref > 1) {
14977 		mblk_t  *mp1;
14978 		boolean_t adjusted = B_FALSE;
14979 		IP_STAT(ipst, ip_db_ref);
14980 
14981 		/*
14982 		 * The IP_RECVSLLA option depends on having the link layer
14983 		 * header. First check that:
14984 		 * a> the underlying device is of type ether, since this
14985 		 * option is currently supported only over ethernet.
14986 		 * b> there is enough room to copy over the link layer header.
14987 		 *
14988 		 * Once the checks are done, adjust rptr so that the link layer
14989 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14990 		 * be returned by some non-ethernet drivers but in this case the
14991 		 * second check will fail.
14992 		 */
14993 		if (ill->ill_type == IFT_ETHER &&
14994 		    (mp->b_rptr - mp->b_datap->db_base) >=
14995 		    sizeof (struct ether_header)) {
14996 			mp->b_rptr -= sizeof (struct ether_header);
14997 			adjusted = B_TRUE;
14998 		}
14999 		mp1 = copymsg(mp);
15000 		if (mp1 == NULL) {
15001 			mp->b_next = NULL;
15002 			/* clear b_prev - used by ip_mroute_decap */
15003 			mp->b_prev = NULL;
15004 			freemsg(mp);
15005 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15006 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15007 			    "ip_rput_end: q %p (%S)", q, "copymsg");
15008 			return;
15009 		}
15010 		if (adjusted) {
15011 			/*
15012 			 * Copy is done. Restore the pointer in the _new_ mblk
15013 			 */
15014 			mp1->b_rptr += sizeof (struct ether_header);
15015 		}
15016 		/* Copy b_prev - used by ip_mroute_decap */
15017 		mp1->b_prev = mp->b_prev;
15018 		mp->b_prev = NULL;
15019 		freemsg(mp);
15020 		mp = mp1;
15021 	}
15022 
15023 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15024 	    "ip_rput_end: q %p (%S)", q, "end");
15025 
15026 	ip_input(ill, NULL, mp, NULL);
15027 }
15028 
15029 /*
15030  * Direct read side procedure capable of dealing with chains. GLDv3 based
15031  * drivers call this function directly with mblk chains while STREAMS
15032  * read side procedure ip_rput() calls this for single packet with ip_ring
15033  * set to NULL to process one packet at a time.
15034  *
15035  * The ill will always be valid if this function is called directly from
15036  * the driver.
15037  *
15038  * If ip_input() is called from GLDv3:
15039  *
15040  *   - This must be a non-VLAN IP stream.
15041  *   - 'mp' is either an untagged or a special priority-tagged packet.
15042  *   - Any VLAN tag that was in the MAC header has been stripped.
15043  *
15044  * If the IP header in packet is not 32-bit aligned, every message in the
15045  * chain will be aligned before further operations. This is required on SPARC
15046  * platform.
15047  */
15048 /* ARGSUSED */
15049 void
15050 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
15051     struct mac_header_info_s *mhip)
15052 {
15053 	ipaddr_t		dst = NULL;
15054 	ipaddr_t		prev_dst;
15055 	ire_t			*ire = NULL;
15056 	ipha_t			*ipha;
15057 	uint_t			pkt_len;
15058 	ssize_t			len;
15059 	uint_t			opt_len;
15060 	int			ll_multicast;
15061 	int			cgtp_flt_pkt;
15062 	queue_t			*q = ill->ill_rq;
15063 	squeue_t		*curr_sqp = NULL;
15064 	mblk_t 			*head = NULL;
15065 	mblk_t			*tail = NULL;
15066 	mblk_t			*first_mp;
15067 	mblk_t 			*mp;
15068 	mblk_t			*dmp;
15069 	int			cnt = 0;
15070 	ip_stack_t		*ipst = ill->ill_ipst;
15071 
15072 	ASSERT(mp_chain != NULL);
15073 	ASSERT(ill != NULL);
15074 
15075 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15076 
15077 #define	rptr	((uchar_t *)ipha)
15078 
15079 	while (mp_chain != NULL) {
15080 		first_mp = mp = mp_chain;
15081 		mp_chain = mp_chain->b_next;
15082 		mp->b_next = NULL;
15083 		ll_multicast = 0;
15084 
15085 		/*
15086 		 * We do ire caching from one iteration to
15087 		 * another. In the event the packet chain contains
15088 		 * all packets from the same dst, this caching saves
15089 		 * an ire_cache_lookup for each of the succeeding
15090 		 * packets in a packet chain.
15091 		 */
15092 		prev_dst = dst;
15093 
15094 		/*
15095 		 * Check and align the IP header.
15096 		 */
15097 		if (DB_TYPE(mp) == M_DATA) {
15098 			dmp = mp;
15099 		} else if (DB_TYPE(mp) == M_PROTO &&
15100 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15101 			dmp = mp->b_cont;
15102 		} else {
15103 			dmp = NULL;
15104 		}
15105 		if (dmp != NULL) {
15106 			/*
15107 			 * IP header ptr not aligned?
15108 			 * OR IP header not complete in first mblk
15109 			 */
15110 			if (!OK_32PTR(dmp->b_rptr) ||
15111 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15112 				if (!ip_check_and_align_header(q, dmp, ipst))
15113 					continue;
15114 			}
15115 		}
15116 
15117 		/*
15118 		 * ip_input fast path
15119 		 */
15120 
15121 		/* mblk type is not M_DATA */
15122 		if (DB_TYPE(mp) != M_DATA) {
15123 			if (ip_rput_process_notdata(q, &first_mp, ill,
15124 			    &ll_multicast, &mp))
15125 				continue;
15126 		}
15127 
15128 		/* Make sure its an M_DATA and that its aligned */
15129 		ASSERT(DB_TYPE(mp) == M_DATA);
15130 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15131 
15132 		ipha = (ipha_t *)mp->b_rptr;
15133 		len = mp->b_wptr - rptr;
15134 		pkt_len = ntohs(ipha->ipha_length);
15135 
15136 		/*
15137 		 * We must count all incoming packets, even if they end
15138 		 * up being dropped later on.
15139 		 */
15140 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15141 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15142 
15143 		/* multiple mblk or too short */
15144 		len -= pkt_len;
15145 		if (len != 0) {
15146 			/*
15147 			 * Make sure we have data length consistent
15148 			 * with the IP header.
15149 			 */
15150 			if (mp->b_cont == NULL) {
15151 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15152 					BUMP_MIB(ill->ill_ip_mib,
15153 					    ipIfStatsInHdrErrors);
15154 					ip2dbg(("ip_input: drop pkt\n"));
15155 					freemsg(mp);
15156 					continue;
15157 				}
15158 				mp->b_wptr = rptr + pkt_len;
15159 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15160 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15161 					BUMP_MIB(ill->ill_ip_mib,
15162 					    ipIfStatsInHdrErrors);
15163 					ip2dbg(("ip_input: drop pkt\n"));
15164 					freemsg(mp);
15165 					continue;
15166 				}
15167 				(void) adjmsg(mp, -len);
15168 				IP_STAT(ipst, ip_multimblk3);
15169 			}
15170 		}
15171 
15172 		/* Obtain the dst of the current packet */
15173 		dst = ipha->ipha_dst;
15174 
15175 		if (IP_LOOPBACK_ADDR(dst) ||
15176 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15177 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15178 			cmn_err(CE_CONT, "dst %X src %X\n",
15179 			    dst, ipha->ipha_src);
15180 			freemsg(mp);
15181 			continue;
15182 		}
15183 
15184 		/*
15185 		 * The event for packets being received from a 'physical'
15186 		 * interface is placed after validation of the source and/or
15187 		 * destination address as being local so that packets can be
15188 		 * redirected to loopback addresses using ipnat.
15189 		 */
15190 		DTRACE_PROBE4(ip4__physical__in__start,
15191 		    ill_t *, ill, ill_t *, NULL,
15192 		    ipha_t *, ipha, mblk_t *, first_mp);
15193 
15194 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15195 		    ipst->ips_ipv4firewall_physical_in,
15196 		    ill, NULL, ipha, first_mp, mp, ipst);
15197 
15198 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15199 
15200 		if (first_mp == NULL) {
15201 			continue;
15202 		}
15203 		dst = ipha->ipha_dst;
15204 
15205 		/*
15206 		 * Attach any necessary label information to
15207 		 * this packet
15208 		 */
15209 		if (is_system_labeled() &&
15210 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15211 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15212 			freemsg(mp);
15213 			continue;
15214 		}
15215 
15216 		/*
15217 		 * Reuse the cached ire only if the ipha_dst of the previous
15218 		 * packet is the same as the current packet AND it is not
15219 		 * INADDR_ANY.
15220 		 */
15221 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15222 		    (ire != NULL)) {
15223 			ire_refrele(ire);
15224 			ire = NULL;
15225 		}
15226 		opt_len = ipha->ipha_version_and_hdr_length -
15227 		    IP_SIMPLE_HDR_VERSION;
15228 
15229 		/*
15230 		 * Check to see if we can take the fastpath.
15231 		 * That is possible if the following conditions are met
15232 		 *	o Tsol disabled
15233 		 *	o CGTP disabled
15234 		 *	o ipp_action_count is 0
15235 		 *	o Mobile IP not running
15236 		 *	o no options in the packet
15237 		 *	o not a RSVP packet
15238 		 * 	o not a multicast packet
15239 		 */
15240 		if (!is_system_labeled() &&
15241 		    !ip_cgtp_filter && ipp_action_count == 0 &&
15242 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
15243 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15244 		    !ll_multicast && !CLASSD(dst)) {
15245 			if (ire == NULL)
15246 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15247 				    ipst);
15248 
15249 			/* incoming packet is for forwarding */
15250 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15251 				ire = ip_fast_forward(ire, dst, ill, mp);
15252 				continue;
15253 			}
15254 			/* incoming packet is for local consumption */
15255 			if (ire->ire_type & IRE_LOCAL)
15256 				goto local;
15257 		}
15258 
15259 		/*
15260 		 * Disable ire caching for anything more complex
15261 		 * than the simple fast path case we checked for above.
15262 		 */
15263 		if (ire != NULL) {
15264 			ire_refrele(ire);
15265 			ire = NULL;
15266 		}
15267 
15268 		/* Full-blown slow path */
15269 		if (opt_len != 0) {
15270 			if (len != 0)
15271 				IP_STAT(ipst, ip_multimblk4);
15272 			else
15273 				IP_STAT(ipst, ip_ipoptions);
15274 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15275 			    &dst, ipst))
15276 				continue;
15277 		}
15278 
15279 		/*
15280 		 * Invoke the CGTP (multirouting) filtering module to process
15281 		 * the incoming packet. Packets identified as duplicates
15282 		 * must be discarded. Filtering is active only if the
15283 		 * the ip_cgtp_filter ndd variable is non-zero.
15284 		 *
15285 		 * Only applies to the shared stack since the filter_ops
15286 		 * do not carry an ip_stack_t or zoneid.
15287 		 */
15288 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15289 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
15290 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
15291 			cgtp_flt_pkt =
15292 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15293 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15294 				freemsg(first_mp);
15295 				continue;
15296 			}
15297 		}
15298 
15299 		/*
15300 		 * If rsvpd is running, let RSVP daemon handle its processing
15301 		 * and forwarding of RSVP multicast/unicast packets.
15302 		 * If rsvpd is not running but mrouted is running, RSVP
15303 		 * multicast packets are forwarded as multicast traffic
15304 		 * and RSVP unicast packets are forwarded by unicast router.
15305 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15306 		 * packets are not forwarded, but the unicast packets are
15307 		 * forwarded like unicast traffic.
15308 		 */
15309 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15310 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15311 		    NULL) {
15312 			/* RSVP packet and rsvpd running. Treat as ours */
15313 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15314 			/*
15315 			 * This assumes that we deliver to all streams for
15316 			 * multicast and broadcast packets.
15317 			 * We have to force ll_multicast to 1 to handle the
15318 			 * M_DATA messages passed in from ip_mroute_decap.
15319 			 */
15320 			dst = INADDR_BROADCAST;
15321 			ll_multicast = 1;
15322 		} else if (CLASSD(dst)) {
15323 			/* packet is multicast */
15324 			mp->b_next = NULL;
15325 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15326 			    &ll_multicast, &dst))
15327 				continue;
15328 		}
15329 
15330 
15331 		/*
15332 		 * Check if the packet is coming from the Mobile IP
15333 		 * forward tunnel interface
15334 		 */
15335 		if (ill->ill_srcif_refcnt > 0) {
15336 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15337 			    NULL, ill, MATCH_IRE_TYPE);
15338 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15339 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15340 
15341 				/* We need to resolve the link layer info */
15342 				ire_refrele(ire);
15343 				ire = NULL;
15344 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15345 				    ll_multicast, dst);
15346 				continue;
15347 			}
15348 		}
15349 
15350 		if (ire == NULL) {
15351 			ire = ire_cache_lookup(dst, ALL_ZONES,
15352 			    MBLK_GETLABEL(mp), ipst);
15353 		}
15354 
15355 		/*
15356 		 * If mipagent is running and reverse tunnel is created as per
15357 		 * mobile node request, then any packet coming through the
15358 		 * incoming interface from the mobile-node, should be reverse
15359 		 * tunneled to it's home agent except those that are destined
15360 		 * to foreign agent only.
15361 		 * This needs source address based ire lookup. The routing
15362 		 * entries for source address based lookup are only created by
15363 		 * mipagent program only when a reverse tunnel is created.
15364 		 * Reference : RFC2002, RFC2344
15365 		 */
15366 		if (ill->ill_mrtun_refcnt > 0) {
15367 			ipaddr_t	srcaddr;
15368 			ire_t		*tmp_ire;
15369 
15370 			tmp_ire = ire;	/* Save, we might need it later */
15371 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15372 			    ire->ire_type != IRE_BROADCAST)) {
15373 				srcaddr = ipha->ipha_src;
15374 				ire = ire_mrtun_lookup(srcaddr, ill);
15375 				if (ire != NULL) {
15376 					/*
15377 					 * Should not be getting iphada packet
15378 					 * here. we should only get those for
15379 					 * IRE_LOCAL traffic, excluded above.
15380 					 * Fail-safe (drop packet) in the event
15381 					 * hardware is misbehaving.
15382 					 */
15383 					if (first_mp != mp) {
15384 						/* IPsec KSTATS: beancount me */
15385 						freemsg(first_mp);
15386 					} else {
15387 						/*
15388 						 * This packet must be forwarded
15389 						 * to Reverse Tunnel
15390 						 */
15391 						ip_mrtun_forward(ire, ill, mp);
15392 					}
15393 					ire_refrele(ire);
15394 					ire = NULL;
15395 					if (tmp_ire != NULL) {
15396 						ire_refrele(tmp_ire);
15397 						tmp_ire = NULL;
15398 					}
15399 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15400 					    "ip_input_end: q %p (%S)",
15401 					    q, "uninit");
15402 					continue;
15403 				}
15404 			}
15405 			/*
15406 			 * If this packet is from a non-mobilenode  or a
15407 			 * mobile-node which does not request reverse
15408 			 * tunnel service
15409 			 */
15410 			ire = tmp_ire;
15411 		}
15412 
15413 
15414 		/*
15415 		 * If we reach here that means the incoming packet satisfies
15416 		 * one of the following conditions:
15417 		 *   - packet is from a mobile node which does not request
15418 		 *	reverse tunnel
15419 		 *   - packet is from a non-mobile node, which is the most
15420 		 *	common case
15421 		 *   - packet is from a reverse tunnel enabled mobile node
15422 		 *	and destined to foreign agent only
15423 		 */
15424 
15425 		if (ire == NULL) {
15426 			/*
15427 			 * No IRE for this destination, so it can't be for us.
15428 			 * Unless we are forwarding, drop the packet.
15429 			 * We have to let source routed packets through
15430 			 * since we don't yet know if they are 'ping -l'
15431 			 * packets i.e. if they will go out over the
15432 			 * same interface as they came in on.
15433 			 */
15434 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15435 			if (ire == NULL)
15436 				continue;
15437 		}
15438 
15439 		/*
15440 		 * Broadcast IRE may indicate either broadcast or
15441 		 * multicast packet
15442 		 */
15443 		if (ire->ire_type == IRE_BROADCAST) {
15444 			/*
15445 			 * Skip broadcast checks if packet is UDP multicast;
15446 			 * we'd rather not enter ip_rput_process_broadcast()
15447 			 * unless the packet is broadcast for real, since
15448 			 * that routine is a no-op for multicast.
15449 			 */
15450 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15451 			    !CLASSD(ipha->ipha_dst)) {
15452 				ire = ip_rput_process_broadcast(&q, mp,
15453 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15454 				    ll_multicast);
15455 				if (ire == NULL)
15456 					continue;
15457 			}
15458 		} else if (ire->ire_stq != NULL) {
15459 			/* fowarding? */
15460 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15461 			    ll_multicast);
15462 			/* ip_rput_process_forward consumed the packet */
15463 			continue;
15464 		}
15465 
15466 local:
15467 		/*
15468 		 * If the queue in the ire is different to the ingress queue
15469 		 * then we need to check to see if we can accept the packet.
15470 		 * Note that for multicast packets and broadcast packets sent
15471 		 * to a broadcast address which is shared between multiple
15472 		 * interfaces we should not do this since we just got a random
15473 		 * broadcast ire.
15474 		 */
15475 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15476 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15477 			    ill)) == NULL) {
15478 				/* Drop packet */
15479 				BUMP_MIB(ill->ill_ip_mib,
15480 				    ipIfStatsForwProhibits);
15481 				freemsg(mp);
15482 				continue;
15483 			}
15484 			if (ire->ire_rfq != NULL)
15485 				q = ire->ire_rfq;
15486 		}
15487 
15488 		switch (ipha->ipha_protocol) {
15489 		case IPPROTO_TCP:
15490 			ASSERT(first_mp == mp);
15491 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15492 				mp, 0, q, ip_ring)) != NULL) {
15493 				if (curr_sqp == NULL) {
15494 					curr_sqp = GET_SQUEUE(mp);
15495 					ASSERT(cnt == 0);
15496 					cnt++;
15497 					head = tail = mp;
15498 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15499 					ASSERT(tail != NULL);
15500 					cnt++;
15501 					tail->b_next = mp;
15502 					tail = mp;
15503 				} else {
15504 					/*
15505 					 * A different squeue. Send the
15506 					 * chain for the previous squeue on
15507 					 * its way. This shouldn't happen
15508 					 * often unless interrupt binding
15509 					 * changes.
15510 					 */
15511 					IP_STAT(ipst, ip_input_multi_squeue);
15512 					squeue_enter_chain(curr_sqp, head,
15513 					    tail, cnt, SQTAG_IP_INPUT);
15514 					curr_sqp = GET_SQUEUE(mp);
15515 					head = mp;
15516 					tail = mp;
15517 					cnt = 1;
15518 				}
15519 			}
15520 			continue;
15521 		case IPPROTO_UDP:
15522 			ASSERT(first_mp == mp);
15523 			ip_udp_input(q, mp, ipha, ire, ill);
15524 			continue;
15525 		case IPPROTO_SCTP:
15526 			ASSERT(first_mp == mp);
15527 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15528 			    q, dst);
15529 			/* ire has been released by ip_sctp_input */
15530 			ire = NULL;
15531 			continue;
15532 		default:
15533 			ip_proto_input(q, first_mp, ipha, ire, ill);
15534 			continue;
15535 		}
15536 	}
15537 
15538 	if (ire != NULL)
15539 		ire_refrele(ire);
15540 
15541 	if (head != NULL)
15542 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15543 
15544 	/*
15545 	 * This code is there just to make netperf/ttcp look good.
15546 	 *
15547 	 * Its possible that after being in polling mode (and having cleared
15548 	 * the backlog), squeues have turned the interrupt frequency higher
15549 	 * to improve latency at the expense of more CPU utilization (less
15550 	 * packets per interrupts or more number of interrupts). Workloads
15551 	 * like ttcp/netperf do manage to tickle polling once in a while
15552 	 * but for the remaining time, stay in higher interrupt mode since
15553 	 * their packet arrival rate is pretty uniform and this shows up
15554 	 * as higher CPU utilization. Since people care about CPU utilization
15555 	 * while running netperf/ttcp, turn the interrupt frequency back to
15556 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15557 	 */
15558 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15559 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15560 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15561 			ip_ring->rr_blank(ip_ring->rr_handle,
15562 			    ip_ring->rr_normal_blank_time,
15563 			    ip_ring->rr_normal_pkt_cnt);
15564 		}
15565 		}
15566 
15567 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15568 	    "ip_input_end: q %p (%S)", q, "end");
15569 #undef  rptr
15570 }
15571 
15572 static void
15573 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15574     t_uscalar_t err)
15575 {
15576 	if (dl_err == DL_SYSERR) {
15577 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15578 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15579 		    ill->ill_name, dlpi_prim_str(prim), err);
15580 		return;
15581 	}
15582 
15583 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15584 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15585 	    dlpi_err_str(dl_err));
15586 }
15587 
15588 /*
15589  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15590  * than DL_UNITDATA_IND messages. If we need to process this message
15591  * exclusively, we call qwriter_ip, in which case we also need to call
15592  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15593  */
15594 void
15595 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15596 {
15597 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15598 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15599 	ill_t		*ill;
15600 
15601 	ip1dbg(("ip_rput_dlpi"));
15602 	ill = (ill_t *)q->q_ptr;
15603 	switch (dloa->dl_primitive) {
15604 	case DL_ERROR_ACK:
15605 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15606 		    "%s (0x%x), unix %u\n", ill->ill_name,
15607 		    dlpi_prim_str(dlea->dl_error_primitive),
15608 		    dlea->dl_error_primitive,
15609 		    dlpi_err_str(dlea->dl_errno),
15610 		    dlea->dl_errno,
15611 		    dlea->dl_unix_errno));
15612 		switch (dlea->dl_error_primitive) {
15613 		case DL_UNBIND_REQ:
15614 			mutex_enter(&ill->ill_lock);
15615 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15616 			cv_signal(&ill->ill_cv);
15617 			mutex_exit(&ill->ill_lock);
15618 			/* FALLTHRU */
15619 		case DL_NOTIFY_REQ:
15620 		case DL_ATTACH_REQ:
15621 		case DL_DETACH_REQ:
15622 		case DL_INFO_REQ:
15623 		case DL_BIND_REQ:
15624 		case DL_ENABMULTI_REQ:
15625 		case DL_PHYS_ADDR_REQ:
15626 		case DL_CAPABILITY_REQ:
15627 		case DL_CONTROL_REQ:
15628 			/*
15629 			 * Refhold the ill to match qwriter_ip which does a
15630 			 * refrele. Since this is on the ill stream we
15631 			 * unconditionally bump up the refcount without
15632 			 * checking for ILL_CAN_LOOKUP
15633 			 */
15634 			ill_refhold(ill);
15635 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15636 			    CUR_OP, B_FALSE);
15637 			return;
15638 		case DL_DISABMULTI_REQ:
15639 			freemsg(mp);	/* Don't want to pass this up */
15640 			return;
15641 		default:
15642 			break;
15643 		}
15644 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15645 		    dlea->dl_errno, dlea->dl_unix_errno);
15646 		freemsg(mp);
15647 		return;
15648 	case DL_INFO_ACK:
15649 	case DL_BIND_ACK:
15650 	case DL_PHYS_ADDR_ACK:
15651 	case DL_NOTIFY_ACK:
15652 	case DL_CAPABILITY_ACK:
15653 	case DL_CONTROL_ACK:
15654 		/*
15655 		 * Refhold the ill to match qwriter_ip which does a refrele
15656 		 * Since this is on the ill stream we unconditionally
15657 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15658 		 */
15659 		ill_refhold(ill);
15660 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15661 		    CUR_OP, B_FALSE);
15662 		return;
15663 	case DL_NOTIFY_IND:
15664 		ill_refhold(ill);
15665 		/*
15666 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15667 		 * relation to the current ioctl in progress (if any). Hence we
15668 		 * pass in NEW_OP in this case.
15669 		 */
15670 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15671 		    NEW_OP, B_FALSE);
15672 		return;
15673 	case DL_OK_ACK:
15674 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15675 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15676 		switch (dloa->dl_correct_primitive) {
15677 		case DL_UNBIND_REQ:
15678 			mutex_enter(&ill->ill_lock);
15679 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15680 			cv_signal(&ill->ill_cv);
15681 			mutex_exit(&ill->ill_lock);
15682 			/* FALLTHRU */
15683 		case DL_ATTACH_REQ:
15684 		case DL_DETACH_REQ:
15685 			/*
15686 			 * Refhold the ill to match qwriter_ip which does a
15687 			 * refrele. Since this is on the ill stream we
15688 			 * unconditionally bump up the refcount
15689 			 */
15690 			ill_refhold(ill);
15691 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15692 			    CUR_OP, B_FALSE);
15693 			return;
15694 		case DL_ENABMULTI_REQ:
15695 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15696 				ill->ill_dlpi_multicast_state = IDS_OK;
15697 			break;
15698 
15699 		}
15700 		break;
15701 	default:
15702 		break;
15703 	}
15704 	freemsg(mp);
15705 }
15706 
15707 /*
15708  * Handling of DLPI messages that require exclusive access to the ipsq.
15709  *
15710  * Need to do ill_pending_mp_release on ioctl completion, which could
15711  * happen here. (along with mi_copy_done)
15712  */
15713 /* ARGSUSED */
15714 static void
15715 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15716 {
15717 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15718 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15719 	int		err = 0;
15720 	ill_t		*ill;
15721 	ipif_t		*ipif = NULL;
15722 	mblk_t		*mp1 = NULL;
15723 	conn_t		*connp = NULL;
15724 	t_uscalar_t	paddrreq;
15725 	mblk_t		*mp_hw;
15726 	boolean_t	success;
15727 	boolean_t	ioctl_aborted = B_FALSE;
15728 	boolean_t	log = B_TRUE;
15729 	hook_nic_event_t	*info;
15730 	ip_stack_t		*ipst;
15731 
15732 	ip1dbg(("ip_rput_dlpi_writer .."));
15733 	ill = (ill_t *)q->q_ptr;
15734 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15735 
15736 	ASSERT(IAM_WRITER_ILL(ill));
15737 
15738 	ipst = ill->ill_ipst;
15739 
15740 	/*
15741 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15742 	 * both are null or non-null. However we can assert that only
15743 	 * after grabbing the ipsq_lock. So we don't make any assertion
15744 	 * here and in other places in the code.
15745 	 */
15746 	ipif = ipsq->ipsq_pending_ipif;
15747 	/*
15748 	 * The current ioctl could have been aborted by the user and a new
15749 	 * ioctl to bring up another ill could have started. We could still
15750 	 * get a response from the driver later.
15751 	 */
15752 	if (ipif != NULL && ipif->ipif_ill != ill)
15753 		ioctl_aborted = B_TRUE;
15754 
15755 	switch (dloa->dl_primitive) {
15756 	case DL_ERROR_ACK:
15757 		switch (dlea->dl_error_primitive) {
15758 		case DL_UNBIND_REQ:
15759 		case DL_ATTACH_REQ:
15760 		case DL_DETACH_REQ:
15761 		case DL_INFO_REQ:
15762 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15763 			break;
15764 		case DL_NOTIFY_REQ:
15765 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15766 			log = B_FALSE;
15767 			break;
15768 		case DL_PHYS_ADDR_REQ:
15769 			/*
15770 			 * For IPv6 only, there are two additional
15771 			 * phys_addr_req's sent to the driver to get the
15772 			 * IPv6 token and lla. This allows IP to acquire
15773 			 * the hardware address format for a given interface
15774 			 * without having built in knowledge of the hardware
15775 			 * address. ill_phys_addr_pend keeps track of the last
15776 			 * DL_PAR sent so we know which response we are
15777 			 * dealing with. ill_dlpi_done will update
15778 			 * ill_phys_addr_pend when it sends the next req.
15779 			 * We don't complete the IOCTL until all three DL_PARs
15780 			 * have been attempted, so set *_len to 0 and break.
15781 			 */
15782 			paddrreq = ill->ill_phys_addr_pend;
15783 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15784 			if (paddrreq == DL_IPV6_TOKEN) {
15785 				ill->ill_token_length = 0;
15786 				log = B_FALSE;
15787 				break;
15788 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15789 				ill->ill_nd_lla_len = 0;
15790 				log = B_FALSE;
15791 				break;
15792 			}
15793 			/*
15794 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15795 			 * We presumably have an IOCTL hanging out waiting
15796 			 * for completion. Find it and complete the IOCTL
15797 			 * with the error noted.
15798 			 * However, ill_dl_phys was called on an ill queue
15799 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15800 			 * set. But the ioctl is known to be pending on ill_wq.
15801 			 */
15802 			if (!ill->ill_ifname_pending)
15803 				break;
15804 			ill->ill_ifname_pending = 0;
15805 			if (!ioctl_aborted)
15806 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15807 			if (mp1 != NULL) {
15808 				/*
15809 				 * This operation (SIOCSLIFNAME) must have
15810 				 * happened on the ill. Assert there is no conn
15811 				 */
15812 				ASSERT(connp == NULL);
15813 				q = ill->ill_wq;
15814 			}
15815 			break;
15816 		case DL_BIND_REQ:
15817 			ill_dlpi_done(ill, DL_BIND_REQ);
15818 			if (ill->ill_ifname_pending)
15819 				break;
15820 			/*
15821 			 * Something went wrong with the bind.  We presumably
15822 			 * have an IOCTL hanging out waiting for completion.
15823 			 * Find it, take down the interface that was coming
15824 			 * up, and complete the IOCTL with the error noted.
15825 			 */
15826 			if (!ioctl_aborted)
15827 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15828 			if (mp1 != NULL) {
15829 				/*
15830 				 * This operation (SIOCSLIFFLAGS) must have
15831 				 * happened from a conn.
15832 				 */
15833 				ASSERT(connp != NULL);
15834 				q = CONNP_TO_WQ(connp);
15835 				if (ill->ill_move_in_progress) {
15836 					ILL_CLEAR_MOVE(ill);
15837 				}
15838 				(void) ipif_down(ipif, NULL, NULL);
15839 				/* error is set below the switch */
15840 			}
15841 			break;
15842 		case DL_ENABMULTI_REQ:
15843 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15844 
15845 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15846 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15847 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15848 				ipif_t *ipif;
15849 
15850 				log = B_FALSE;
15851 				printf("ip: joining multicasts failed (%d)"
15852 				    " on %s - will use link layer "
15853 				    "broadcasts for multicast\n",
15854 				    dlea->dl_errno, ill->ill_name);
15855 
15856 				/*
15857 				 * Set up the multicast mapping alone.
15858 				 * writer, so ok to access ill->ill_ipif
15859 				 * without any lock.
15860 				 */
15861 				ipif = ill->ill_ipif;
15862 				mutex_enter(&ill->ill_phyint->phyint_lock);
15863 				ill->ill_phyint->phyint_flags |=
15864 				    PHYI_MULTI_BCAST;
15865 				mutex_exit(&ill->ill_phyint->phyint_lock);
15866 
15867 				if (!ill->ill_isv6) {
15868 					(void) ipif_arp_setup_multicast(ipif,
15869 					    NULL);
15870 				} else {
15871 					(void) ipif_ndp_setup_multicast(ipif,
15872 					    NULL);
15873 				}
15874 			}
15875 			freemsg(mp);	/* Don't want to pass this up */
15876 			return;
15877 		case DL_CAPABILITY_REQ:
15878 		case DL_CONTROL_REQ:
15879 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15880 			    "DL_CAPABILITY/CONTROL REQ\n"));
15881 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15882 			ill->ill_dlpi_capab_state = IDS_FAILED;
15883 			freemsg(mp);
15884 			return;
15885 		}
15886 		/*
15887 		 * Note the error for IOCTL completion (mp1 is set when
15888 		 * ready to complete ioctl). If ill_ifname_pending_err is
15889 		 * set, an error occured during plumbing (ill_ifname_pending),
15890 		 * so we want to report that error.
15891 		 *
15892 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15893 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15894 		 * expected to get errack'd if the driver doesn't support
15895 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15896 		 * if these error conditions are encountered.
15897 		 */
15898 		if (mp1 != NULL) {
15899 			if (ill->ill_ifname_pending_err != 0)  {
15900 				err = ill->ill_ifname_pending_err;
15901 				ill->ill_ifname_pending_err = 0;
15902 			} else {
15903 				err = dlea->dl_unix_errno ?
15904 				    dlea->dl_unix_errno : ENXIO;
15905 			}
15906 		/*
15907 		 * If we're plumbing an interface and an error hasn't already
15908 		 * been saved, set ill_ifname_pending_err to the error passed
15909 		 * up. Ignore the error if log is B_FALSE (see comment above).
15910 		 */
15911 		} else if (log && ill->ill_ifname_pending &&
15912 		    ill->ill_ifname_pending_err == 0) {
15913 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15914 			dlea->dl_unix_errno : ENXIO;
15915 		}
15916 
15917 		if (log)
15918 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15919 			    dlea->dl_errno, dlea->dl_unix_errno);
15920 		break;
15921 	case DL_CAPABILITY_ACK: {
15922 		boolean_t reneg_flag = B_FALSE;
15923 		/* Call a routine to handle this one. */
15924 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15925 		/*
15926 		 * Check if the ACK is due to renegotiation case since we
15927 		 * will need to send a new CAPABILITY_REQ later.
15928 		 */
15929 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15930 			/* This is the ack for a renogiation case */
15931 			reneg_flag = B_TRUE;
15932 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15933 		}
15934 		ill_capability_ack(ill, mp);
15935 		if (reneg_flag)
15936 			ill_capability_probe(ill);
15937 		break;
15938 	}
15939 	case DL_CONTROL_ACK:
15940 		/* We treat all of these as "fire and forget" */
15941 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15942 		break;
15943 	case DL_INFO_ACK:
15944 		/* Call a routine to handle this one. */
15945 		ill_dlpi_done(ill, DL_INFO_REQ);
15946 		ip_ll_subnet_defaults(ill, mp);
15947 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15948 		return;
15949 	case DL_BIND_ACK:
15950 		/*
15951 		 * We should have an IOCTL waiting on this unless
15952 		 * sent by ill_dl_phys, in which case just return
15953 		 */
15954 		ill_dlpi_done(ill, DL_BIND_REQ);
15955 		if (ill->ill_ifname_pending)
15956 			break;
15957 
15958 		if (!ioctl_aborted)
15959 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15960 		if (mp1 == NULL)
15961 			break;
15962 		/*
15963 		 * Because mp1 was added by ill_dl_up(), and it always
15964 		 * passes a valid connp, connp must be valid here.
15965 		 */
15966 		ASSERT(connp != NULL);
15967 		q = CONNP_TO_WQ(connp);
15968 
15969 		/*
15970 		 * We are exclusive. So nothing can change even after
15971 		 * we get the pending mp. If need be we can put it back
15972 		 * and restart, as in calling ipif_arp_up()  below.
15973 		 */
15974 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15975 
15976 		mutex_enter(&ill->ill_lock);
15977 
15978 		ill->ill_dl_up = 1;
15979 
15980 		if ((info = ill->ill_nic_event_info) != NULL) {
15981 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15982 			    "attached for %s\n", info->hne_event,
15983 			    ill->ill_name));
15984 			if (info->hne_data != NULL)
15985 				kmem_free(info->hne_data, info->hne_datalen);
15986 			kmem_free(info, sizeof (hook_nic_event_t));
15987 		}
15988 
15989 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15990 		if (info != NULL) {
15991 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15992 			info->hne_lif = 0;
15993 			info->hne_event = NE_UP;
15994 			info->hne_data = NULL;
15995 			info->hne_datalen = 0;
15996 			info->hne_family = ill->ill_isv6 ?
15997 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15998 		} else
15999 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
16000 			    "event information for %s (ENOMEM)\n",
16001 			    ill->ill_name));
16002 
16003 		ill->ill_nic_event_info = info;
16004 
16005 		mutex_exit(&ill->ill_lock);
16006 
16007 		/*
16008 		 * Now bring up the resolver; when that is complete, we'll
16009 		 * create IREs.  Note that we intentionally mirror what
16010 		 * ipif_up() would have done, because we got here by way of
16011 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16012 		 */
16013 		if (ill->ill_isv6) {
16014 			/*
16015 			 * v6 interfaces.
16016 			 * Unlike ARP which has to do another bind
16017 			 * and attach, once we get here we are
16018 			 * done with NDP. Except in the case of
16019 			 * ILLF_XRESOLV, in which case we send an
16020 			 * AR_INTERFACE_UP to the external resolver.
16021 			 * If all goes well, the ioctl will complete
16022 			 * in ip_rput(). If there's an error, we
16023 			 * complete it here.
16024 			 */
16025 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
16026 			if (err == 0) {
16027 				if (ill->ill_flags & ILLF_XRESOLV) {
16028 					mutex_enter(&connp->conn_lock);
16029 					mutex_enter(&ill->ill_lock);
16030 					success = ipsq_pending_mp_add(
16031 					    connp, ipif, q, mp1, 0);
16032 					mutex_exit(&ill->ill_lock);
16033 					mutex_exit(&connp->conn_lock);
16034 					if (success) {
16035 						err = ipif_resolver_up(ipif,
16036 						    Res_act_initial);
16037 						if (err == EINPROGRESS) {
16038 							freemsg(mp);
16039 							return;
16040 						}
16041 						ASSERT(err != 0);
16042 						mp1 = ipsq_pending_mp_get(ipsq,
16043 						    &connp);
16044 						ASSERT(mp1 != NULL);
16045 					} else {
16046 						/* conn has started closing */
16047 						err = EINTR;
16048 					}
16049 				} else { /* Non XRESOLV interface */
16050 					(void) ipif_resolver_up(ipif,
16051 					    Res_act_initial);
16052 					err = ipif_up_done_v6(ipif);
16053 				}
16054 			}
16055 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16056 			/*
16057 			 * ARP and other v4 external resolvers.
16058 			 * Leave the pending mblk intact so that
16059 			 * the ioctl completes in ip_rput().
16060 			 */
16061 			mutex_enter(&connp->conn_lock);
16062 			mutex_enter(&ill->ill_lock);
16063 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16064 			mutex_exit(&ill->ill_lock);
16065 			mutex_exit(&connp->conn_lock);
16066 			if (success) {
16067 				err = ipif_resolver_up(ipif, Res_act_initial);
16068 				if (err == EINPROGRESS) {
16069 					freemsg(mp);
16070 					return;
16071 				}
16072 				ASSERT(err != 0);
16073 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16074 			} else {
16075 				/* The conn has started closing */
16076 				err = EINTR;
16077 			}
16078 		} else {
16079 			/*
16080 			 * This one is complete. Reply to pending ioctl.
16081 			 */
16082 			(void) ipif_resolver_up(ipif, Res_act_initial);
16083 			err = ipif_up_done(ipif);
16084 		}
16085 
16086 		if ((err == 0) && (ill->ill_up_ipifs)) {
16087 			err = ill_up_ipifs(ill, q, mp1);
16088 			if (err == EINPROGRESS) {
16089 				freemsg(mp);
16090 				return;
16091 			}
16092 		}
16093 
16094 		if (ill->ill_up_ipifs) {
16095 			ill_group_cleanup(ill);
16096 		}
16097 
16098 		break;
16099 	case DL_NOTIFY_IND: {
16100 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16101 		ire_t *ire;
16102 		boolean_t need_ire_walk_v4 = B_FALSE;
16103 		boolean_t need_ire_walk_v6 = B_FALSE;
16104 
16105 		switch (notify->dl_notification) {
16106 		case DL_NOTE_PHYS_ADDR:
16107 			err = ill_set_phys_addr(ill, mp);
16108 			break;
16109 
16110 		case DL_NOTE_FASTPATH_FLUSH:
16111 			ill_fastpath_flush(ill);
16112 			break;
16113 
16114 		case DL_NOTE_SDU_SIZE:
16115 			/*
16116 			 * Change the MTU size of the interface, of all
16117 			 * attached ipif's, and of all relevant ire's.  The
16118 			 * new value's a uint32_t at notify->dl_data.
16119 			 * Mtu change Vs. new ire creation - protocol below.
16120 			 *
16121 			 * a Mark the ipif as IPIF_CHANGING.
16122 			 * b Set the new mtu in the ipif.
16123 			 * c Change the ire_max_frag on all affected ires
16124 			 * d Unmark the IPIF_CHANGING
16125 			 *
16126 			 * To see how the protocol works, assume an interface
16127 			 * route is also being added simultaneously by
16128 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16129 			 * the ire. If the ire is created before step a,
16130 			 * it will be cleaned up by step c. If the ire is
16131 			 * created after step d, it will see the new value of
16132 			 * ipif_mtu. Any attempt to create the ire between
16133 			 * steps a to d will fail because of the IPIF_CHANGING
16134 			 * flag. Note that ire_create() is passed a pointer to
16135 			 * the ipif_mtu, and not the value. During ire_add
16136 			 * under the bucket lock, the ire_max_frag of the
16137 			 * new ire being created is set from the ipif/ire from
16138 			 * which it is being derived.
16139 			 */
16140 			mutex_enter(&ill->ill_lock);
16141 			ill->ill_max_frag = (uint_t)notify->dl_data;
16142 
16143 			/*
16144 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16145 			 * leave it alone
16146 			 */
16147 			if (ill->ill_mtu_userspecified) {
16148 				mutex_exit(&ill->ill_lock);
16149 				break;
16150 			}
16151 			ill->ill_max_mtu = ill->ill_max_frag;
16152 			if (ill->ill_isv6) {
16153 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16154 					ill->ill_max_mtu = IPV6_MIN_MTU;
16155 			} else {
16156 				if (ill->ill_max_mtu < IP_MIN_MTU)
16157 					ill->ill_max_mtu = IP_MIN_MTU;
16158 			}
16159 			for (ipif = ill->ill_ipif; ipif != NULL;
16160 			    ipif = ipif->ipif_next) {
16161 				/*
16162 				 * Don't override the mtu if the user
16163 				 * has explicitly set it.
16164 				 */
16165 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16166 					continue;
16167 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16168 				if (ipif->ipif_isv6)
16169 					ire = ipif_to_ire_v6(ipif);
16170 				else
16171 					ire = ipif_to_ire(ipif);
16172 				if (ire != NULL) {
16173 					ire->ire_max_frag = ipif->ipif_mtu;
16174 					ire_refrele(ire);
16175 				}
16176 				if (ipif->ipif_flags & IPIF_UP) {
16177 					if (ill->ill_isv6)
16178 						need_ire_walk_v6 = B_TRUE;
16179 					else
16180 						need_ire_walk_v4 = B_TRUE;
16181 				}
16182 			}
16183 			mutex_exit(&ill->ill_lock);
16184 			if (need_ire_walk_v4)
16185 				ire_walk_v4(ill_mtu_change, (char *)ill,
16186 				    ALL_ZONES, ipst);
16187 			if (need_ire_walk_v6)
16188 				ire_walk_v6(ill_mtu_change, (char *)ill,
16189 				    ALL_ZONES, ipst);
16190 			break;
16191 		case DL_NOTE_LINK_UP:
16192 		case DL_NOTE_LINK_DOWN: {
16193 			/*
16194 			 * We are writer. ill / phyint / ipsq assocs stable.
16195 			 * The RUNNING flag reflects the state of the link.
16196 			 */
16197 			phyint_t *phyint = ill->ill_phyint;
16198 			uint64_t new_phyint_flags;
16199 			boolean_t changed = B_FALSE;
16200 			boolean_t went_up;
16201 
16202 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16203 			mutex_enter(&phyint->phyint_lock);
16204 			new_phyint_flags = went_up ?
16205 			    phyint->phyint_flags | PHYI_RUNNING :
16206 			    phyint->phyint_flags & ~PHYI_RUNNING;
16207 			if (new_phyint_flags != phyint->phyint_flags) {
16208 				phyint->phyint_flags = new_phyint_flags;
16209 				changed = B_TRUE;
16210 			}
16211 			mutex_exit(&phyint->phyint_lock);
16212 			/*
16213 			 * ill_restart_dad handles the DAD restart and routing
16214 			 * socket notification logic.
16215 			 */
16216 			if (changed) {
16217 				ill_restart_dad(phyint->phyint_illv4, went_up);
16218 				ill_restart_dad(phyint->phyint_illv6, went_up);
16219 			}
16220 			break;
16221 		}
16222 		case DL_NOTE_PROMISC_ON_PHYS:
16223 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16224 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16225 			mutex_enter(&ill->ill_lock);
16226 			ill->ill_promisc_on_phys = B_TRUE;
16227 			mutex_exit(&ill->ill_lock);
16228 			break;
16229 		case DL_NOTE_PROMISC_OFF_PHYS:
16230 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16231 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16232 			mutex_enter(&ill->ill_lock);
16233 			ill->ill_promisc_on_phys = B_FALSE;
16234 			mutex_exit(&ill->ill_lock);
16235 			break;
16236 		case DL_NOTE_CAPAB_RENEG:
16237 			/*
16238 			 * Something changed on the driver side.
16239 			 * It wants us to renegotiate the capabilities
16240 			 * on this ill. The most likely cause is the
16241 			 * aggregation interface under us where a
16242 			 * port got added or went away.
16243 			 *
16244 			 * We reset the capabilities and set the
16245 			 * state to IDS_RENG so that when the ack
16246 			 * comes back, we can start the
16247 			 * renegotiation process.
16248 			 */
16249 			ill_capability_reset(ill);
16250 			ill->ill_dlpi_capab_state = IDS_RENEG;
16251 			break;
16252 		default:
16253 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16254 			    "type 0x%x for DL_NOTIFY_IND\n",
16255 			    notify->dl_notification));
16256 			break;
16257 		}
16258 
16259 		/*
16260 		 * As this is an asynchronous operation, we
16261 		 * should not call ill_dlpi_done
16262 		 */
16263 		break;
16264 	}
16265 	case DL_NOTIFY_ACK: {
16266 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16267 
16268 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16269 			ill->ill_note_link = 1;
16270 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16271 		break;
16272 	}
16273 	case DL_PHYS_ADDR_ACK: {
16274 		/*
16275 		 * As part of plumbing the interface via SIOCSLIFNAME,
16276 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16277 		 * whose answers we receive here.  As each answer is received,
16278 		 * we call ill_dlpi_done() to dispatch the next request as
16279 		 * we're processing the current one.  Once all answers have
16280 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16281 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16282 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16283 		 * available, but we know the ioctl is pending on ill_wq.)
16284 		 */
16285 		uint_t paddrlen, paddroff;
16286 
16287 		paddrreq = ill->ill_phys_addr_pend;
16288 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16289 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16290 
16291 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16292 		if (paddrreq == DL_IPV6_TOKEN) {
16293 			/*
16294 			 * bcopy to low-order bits of ill_token
16295 			 *
16296 			 * XXX Temporary hack - currently, all known tokens
16297 			 * are 64 bits, so I'll cheat for the moment.
16298 			 */
16299 			bcopy(mp->b_rptr + paddroff,
16300 			    &ill->ill_token.s6_addr32[2], paddrlen);
16301 			ill->ill_token_length = paddrlen;
16302 			break;
16303 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16304 			ASSERT(ill->ill_nd_lla_mp == NULL);
16305 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16306 			mp = NULL;
16307 			break;
16308 		}
16309 
16310 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16311 		ASSERT(ill->ill_phys_addr_mp == NULL);
16312 		if (!ill->ill_ifname_pending)
16313 			break;
16314 		ill->ill_ifname_pending = 0;
16315 		if (!ioctl_aborted)
16316 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16317 		if (mp1 != NULL) {
16318 			ASSERT(connp == NULL);
16319 			q = ill->ill_wq;
16320 		}
16321 		/*
16322 		 * If any error acks received during the plumbing sequence,
16323 		 * ill_ifname_pending_err will be set. Break out and send up
16324 		 * the error to the pending ioctl.
16325 		 */
16326 		if (ill->ill_ifname_pending_err != 0) {
16327 			err = ill->ill_ifname_pending_err;
16328 			ill->ill_ifname_pending_err = 0;
16329 			break;
16330 		}
16331 
16332 		ill->ill_phys_addr_mp = mp;
16333 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16334 		mp = NULL;
16335 
16336 		/*
16337 		 * If paddrlen is zero, the DLPI provider doesn't support
16338 		 * physical addresses.  The other two tests were historical
16339 		 * workarounds for bugs in our former PPP implementation, but
16340 		 * now other things have grown dependencies on them -- e.g.,
16341 		 * the tun module specifies a dl_addr_length of zero in its
16342 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16343 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16344 		 * but only after careful testing ensures that all dependent
16345 		 * broken DLPI providers have been fixed.
16346 		 */
16347 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16348 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16349 			ill->ill_phys_addr = NULL;
16350 		} else if (paddrlen != ill->ill_phys_addr_length) {
16351 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16352 			    paddrlen, ill->ill_phys_addr_length));
16353 			err = EINVAL;
16354 			break;
16355 		}
16356 
16357 		if (ill->ill_nd_lla_mp == NULL) {
16358 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16359 				err = ENOMEM;
16360 				break;
16361 			}
16362 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16363 		}
16364 
16365 		/*
16366 		 * Set the interface token.  If the zeroth interface address
16367 		 * is unspecified, then set it to the link local address.
16368 		 */
16369 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16370 			(void) ill_setdefaulttoken(ill);
16371 
16372 		ASSERT(ill->ill_ipif->ipif_id == 0);
16373 		if (ipif != NULL &&
16374 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16375 			(void) ipif_setlinklocal(ipif);
16376 		}
16377 		break;
16378 	}
16379 	case DL_OK_ACK:
16380 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16381 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16382 		    dloa->dl_correct_primitive));
16383 		switch (dloa->dl_correct_primitive) {
16384 		case DL_UNBIND_REQ:
16385 		case DL_ATTACH_REQ:
16386 		case DL_DETACH_REQ:
16387 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16388 			break;
16389 		}
16390 		break;
16391 	default:
16392 		break;
16393 	}
16394 
16395 	freemsg(mp);
16396 	if (mp1 != NULL) {
16397 		/*
16398 		 * The operation must complete without EINPROGRESS
16399 		 * since ipsq_pending_mp_get() has removed the mblk
16400 		 * from ipsq_pending_mp.  Otherwise, the operation
16401 		 * will be stuck forever in the ipsq.
16402 		 */
16403 		ASSERT(err != EINPROGRESS);
16404 
16405 		switch (ipsq->ipsq_current_ioctl) {
16406 		case 0:
16407 			ipsq_current_finish(ipsq);
16408 			break;
16409 
16410 		case SIOCLIFADDIF:
16411 		case SIOCSLIFNAME:
16412 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16413 			break;
16414 
16415 		default:
16416 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16417 			break;
16418 		}
16419 	}
16420 }
16421 
16422 /*
16423  * ip_rput_other is called by ip_rput to handle messages modifying the global
16424  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16425  */
16426 /* ARGSUSED */
16427 void
16428 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16429 {
16430 	ill_t		*ill;
16431 	struct iocblk	*iocp;
16432 	mblk_t		*mp1;
16433 	conn_t		*connp = NULL;
16434 
16435 	ip1dbg(("ip_rput_other "));
16436 	ill = (ill_t *)q->q_ptr;
16437 	/*
16438 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16439 	 * in which case ipsq is NULL.
16440 	 */
16441 	if (ipsq != NULL) {
16442 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16443 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16444 	}
16445 
16446 	switch (mp->b_datap->db_type) {
16447 	case M_ERROR:
16448 	case M_HANGUP:
16449 		/*
16450 		 * The device has a problem.  We force the ILL down.  It can
16451 		 * be brought up again manually using SIOCSIFFLAGS (via
16452 		 * ifconfig or equivalent).
16453 		 */
16454 		ASSERT(ipsq != NULL);
16455 		if (mp->b_rptr < mp->b_wptr)
16456 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16457 		if (ill->ill_error == 0)
16458 			ill->ill_error = ENXIO;
16459 		if (!ill_down_start(q, mp))
16460 			return;
16461 		ipif_all_down_tail(ipsq, q, mp, NULL);
16462 		break;
16463 	case M_IOCACK:
16464 		iocp = (struct iocblk *)mp->b_rptr;
16465 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16466 		switch (iocp->ioc_cmd) {
16467 		case SIOCSTUNPARAM:
16468 		case OSIOCSTUNPARAM:
16469 			ASSERT(ipsq != NULL);
16470 			/*
16471 			 * Finish socket ioctl passed through to tun.
16472 			 * We should have an IOCTL waiting on this.
16473 			 */
16474 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16475 			if (ill->ill_isv6) {
16476 				struct iftun_req *ta;
16477 
16478 				/*
16479 				 * if a source or destination is
16480 				 * being set, try and set the link
16481 				 * local address for the tunnel
16482 				 */
16483 				ta = (struct iftun_req *)mp->b_cont->
16484 				    b_cont->b_rptr;
16485 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16486 					ipif_set_tun_llink(ill, ta);
16487 				}
16488 
16489 			}
16490 			if (mp1 != NULL) {
16491 				/*
16492 				 * Now copy back the b_next/b_prev used by
16493 				 * mi code for the mi_copy* functions.
16494 				 * See ip_sioctl_tunparam() for the reason.
16495 				 * Also protect against missing b_cont.
16496 				 */
16497 				if (mp->b_cont != NULL) {
16498 					mp->b_cont->b_next =
16499 					    mp1->b_cont->b_next;
16500 					mp->b_cont->b_prev =
16501 					    mp1->b_cont->b_prev;
16502 				}
16503 				inet_freemsg(mp1);
16504 				ASSERT(connp != NULL);
16505 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16506 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16507 			} else {
16508 				ASSERT(connp == NULL);
16509 				putnext(q, mp);
16510 			}
16511 			break;
16512 		case SIOCGTUNPARAM:
16513 		case OSIOCGTUNPARAM:
16514 			/*
16515 			 * This is really M_IOCDATA from the tunnel driver.
16516 			 * convert back and complete the ioctl.
16517 			 * We should have an IOCTL waiting on this.
16518 			 */
16519 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16520 			if (mp1) {
16521 				/*
16522 				 * Now copy back the b_next/b_prev used by
16523 				 * mi code for the mi_copy* functions.
16524 				 * See ip_sioctl_tunparam() for the reason.
16525 				 * Also protect against missing b_cont.
16526 				 */
16527 				if (mp->b_cont != NULL) {
16528 					mp->b_cont->b_next =
16529 					    mp1->b_cont->b_next;
16530 					mp->b_cont->b_prev =
16531 					    mp1->b_cont->b_prev;
16532 				}
16533 				inet_freemsg(mp1);
16534 				if (iocp->ioc_error == 0)
16535 					mp->b_datap->db_type = M_IOCDATA;
16536 				ASSERT(connp != NULL);
16537 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16538 				    iocp->ioc_error, COPYOUT, NULL);
16539 			} else {
16540 				ASSERT(connp == NULL);
16541 				putnext(q, mp);
16542 			}
16543 			break;
16544 		default:
16545 			break;
16546 		}
16547 		break;
16548 	case M_IOCNAK:
16549 		iocp = (struct iocblk *)mp->b_rptr;
16550 
16551 		switch (iocp->ioc_cmd) {
16552 		int mode;
16553 
16554 		case DL_IOC_HDR_INFO:
16555 			/*
16556 			 * If this was the first attempt turn of the
16557 			 * fastpath probing.
16558 			 */
16559 			mutex_enter(&ill->ill_lock);
16560 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16561 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16562 				mutex_exit(&ill->ill_lock);
16563 				ill_fastpath_nack(ill);
16564 				ip1dbg(("ip_rput: DLPI fastpath off on "
16565 				    "interface %s\n",
16566 				    ill->ill_name));
16567 			} else {
16568 				mutex_exit(&ill->ill_lock);
16569 			}
16570 			freemsg(mp);
16571 			break;
16572 		case SIOCSTUNPARAM:
16573 		case OSIOCSTUNPARAM:
16574 			ASSERT(ipsq != NULL);
16575 			/*
16576 			 * Finish socket ioctl passed through to tun
16577 			 * We should have an IOCTL waiting on this.
16578 			 */
16579 			/* FALLTHRU */
16580 		case SIOCGTUNPARAM:
16581 		case OSIOCGTUNPARAM:
16582 			/*
16583 			 * This is really M_IOCDATA from the tunnel driver.
16584 			 * convert back and complete the ioctl.
16585 			 * We should have an IOCTL waiting on this.
16586 			 */
16587 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16588 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16589 				mp1 = ill_pending_mp_get(ill, &connp,
16590 				    iocp->ioc_id);
16591 				mode = COPYOUT;
16592 				ipsq = NULL;
16593 			} else {
16594 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16595 				mode = NO_COPYOUT;
16596 			}
16597 			if (mp1 != NULL) {
16598 				/*
16599 				 * Now copy back the b_next/b_prev used by
16600 				 * mi code for the mi_copy* functions.
16601 				 * See ip_sioctl_tunparam() for the reason.
16602 				 * Also protect against missing b_cont.
16603 				 */
16604 				if (mp->b_cont != NULL) {
16605 					mp->b_cont->b_next =
16606 					    mp1->b_cont->b_next;
16607 					mp->b_cont->b_prev =
16608 					    mp1->b_cont->b_prev;
16609 				}
16610 				inet_freemsg(mp1);
16611 				if (iocp->ioc_error == 0)
16612 					iocp->ioc_error = EINVAL;
16613 				ASSERT(connp != NULL);
16614 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16615 				    iocp->ioc_error, mode, ipsq);
16616 			} else {
16617 				ASSERT(connp == NULL);
16618 				putnext(q, mp);
16619 			}
16620 			break;
16621 		default:
16622 			break;
16623 		}
16624 	default:
16625 		break;
16626 	}
16627 }
16628 
16629 /*
16630  * NOTE : This function does not ire_refrele the ire argument passed in.
16631  *
16632  * IPQoS notes
16633  * IP policy is invoked twice for a forwarded packet, once on the read side
16634  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16635  * enabled. An additional parameter, in_ill, has been added for this purpose.
16636  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16637  * because ip_mroute drops this information.
16638  *
16639  */
16640 void
16641 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16642 {
16643 	uint32_t	pkt_len;
16644 	queue_t	*q;
16645 	uint32_t	sum;
16646 #define	rptr	((uchar_t *)ipha)
16647 	uint32_t	max_frag;
16648 	uint32_t	ill_index;
16649 	ill_t		*out_ill;
16650 	mib2_ipIfStatsEntry_t *mibptr;
16651 	ip_stack_t	*ipst = in_ill->ill_ipst;
16652 
16653 	/* Get the ill_index of the incoming ILL */
16654 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16655 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16656 
16657 	/* Initiate Read side IPPF processing */
16658 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16659 		ip_process(IPP_FWD_IN, &mp, ill_index);
16660 		if (mp == NULL) {
16661 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16662 			    "during IPPF processing\n"));
16663 			return;
16664 		}
16665 	}
16666 
16667 	pkt_len = ntohs(ipha->ipha_length);
16668 
16669 	/* Adjust the checksum to reflect the ttl decrement. */
16670 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16671 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16672 
16673 	if (ipha->ipha_ttl-- <= 1) {
16674 		if (ip_csum_hdr(ipha)) {
16675 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16676 			goto drop_pkt;
16677 		}
16678 		/*
16679 		 * Note: ire_stq this will be NULL for multicast
16680 		 * datagrams using the long path through arp (the IRE
16681 		 * is not an IRE_CACHE). This should not cause
16682 		 * problems since we don't generate ICMP errors for
16683 		 * multicast packets.
16684 		 */
16685 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16686 		q = ire->ire_stq;
16687 		if (q != NULL) {
16688 			/* Sent by forwarding path, and router is global zone */
16689 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16690 			    GLOBAL_ZONEID, ipst);
16691 		} else
16692 			freemsg(mp);
16693 		return;
16694 	}
16695 
16696 	/*
16697 	 * Don't forward if the interface is down
16698 	 */
16699 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16700 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16701 		ip2dbg(("ip_rput_forward:interface is down\n"));
16702 		goto drop_pkt;
16703 	}
16704 
16705 	/* Get the ill_index of the outgoing ILL */
16706 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16707 
16708 	out_ill = ire->ire_ipif->ipif_ill;
16709 
16710 	DTRACE_PROBE4(ip4__forwarding__start,
16711 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16712 
16713 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16714 	    ipst->ips_ipv4firewall_forwarding,
16715 	    in_ill, out_ill, ipha, mp, mp, ipst);
16716 
16717 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16718 
16719 	if (mp == NULL)
16720 		return;
16721 	pkt_len = ntohs(ipha->ipha_length);
16722 
16723 	if (is_system_labeled()) {
16724 		mblk_t *mp1;
16725 
16726 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16727 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16728 			goto drop_pkt;
16729 		}
16730 		/* Size may have changed */
16731 		mp = mp1;
16732 		ipha = (ipha_t *)mp->b_rptr;
16733 		pkt_len = ntohs(ipha->ipha_length);
16734 	}
16735 
16736 	/* Check if there are options to update */
16737 	if (!IS_SIMPLE_IPH(ipha)) {
16738 		if (ip_csum_hdr(ipha)) {
16739 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16740 			goto drop_pkt;
16741 		}
16742 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16743 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16744 			return;
16745 		}
16746 
16747 		ipha->ipha_hdr_checksum = 0;
16748 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16749 	}
16750 	max_frag = ire->ire_max_frag;
16751 	if (pkt_len > max_frag) {
16752 		/*
16753 		 * It needs fragging on its way out.  We haven't
16754 		 * verified the header checksum yet.  Since we
16755 		 * are going to put a surely good checksum in the
16756 		 * outgoing header, we have to make sure that it
16757 		 * was good coming in.
16758 		 */
16759 		if (ip_csum_hdr(ipha)) {
16760 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16761 			goto drop_pkt;
16762 		}
16763 		/* Initiate Write side IPPF processing */
16764 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16765 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16766 			if (mp == NULL) {
16767 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16768 				    " during IPPF processing\n"));
16769 				return;
16770 			}
16771 		}
16772 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16773 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16774 		return;
16775 	}
16776 
16777 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16778 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16779 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16780 	    ipst->ips_ipv4firewall_physical_out,
16781 	    NULL, out_ill, ipha, mp, mp, ipst);
16782 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16783 	if (mp == NULL)
16784 		return;
16785 
16786 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16787 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16788 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16789 	/* ip_xmit_v4 always consumes the packet */
16790 	return;
16791 
16792 drop_pkt:;
16793 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16794 	freemsg(mp);
16795 #undef	rptr
16796 }
16797 
16798 void
16799 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16800 {
16801 	ire_t	*ire;
16802 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16803 
16804 	ASSERT(!ipif->ipif_isv6);
16805 	/*
16806 	 * Find an IRE which matches the destination and the outgoing
16807 	 * queue in the cache table. All we need is an IRE_CACHE which
16808 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16809 	 * then it is enough to have some IRE_CACHE in the group.
16810 	 */
16811 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16812 		dst = ipif->ipif_pp_dst_addr;
16813 
16814 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16815 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16816 	if (ire == NULL) {
16817 		/*
16818 		 * Mark this packet to make it be delivered to
16819 		 * ip_rput_forward after the new ire has been
16820 		 * created.
16821 		 */
16822 		mp->b_prev = NULL;
16823 		mp->b_next = mp;
16824 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16825 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16826 	} else {
16827 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16828 		IRE_REFRELE(ire);
16829 	}
16830 }
16831 
16832 /* Update any source route, record route or timestamp options */
16833 static int
16834 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16835 {
16836 	ipoptp_t	opts;
16837 	uchar_t		*opt;
16838 	uint8_t		optval;
16839 	uint8_t		optlen;
16840 	ipaddr_t	dst;
16841 	uint32_t	ts;
16842 	ire_t		*dst_ire = NULL;
16843 	ire_t		*tmp_ire = NULL;
16844 	timestruc_t	now;
16845 
16846 	ip2dbg(("ip_rput_forward_options\n"));
16847 	dst = ipha->ipha_dst;
16848 	for (optval = ipoptp_first(&opts, ipha);
16849 	    optval != IPOPT_EOL;
16850 	    optval = ipoptp_next(&opts)) {
16851 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16852 		opt = opts.ipoptp_cur;
16853 		optlen = opts.ipoptp_len;
16854 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16855 		    optval, opts.ipoptp_len));
16856 		switch (optval) {
16857 			uint32_t off;
16858 		case IPOPT_SSRR:
16859 		case IPOPT_LSRR:
16860 			/* Check if adminstratively disabled */
16861 			if (!ipst->ips_ip_forward_src_routed) {
16862 				if (ire->ire_stq != NULL) {
16863 					/*
16864 					 * Sent by forwarding path, and router
16865 					 * is global zone
16866 					 */
16867 					icmp_unreachable(ire->ire_stq, mp,
16868 					    ICMP_SOURCE_ROUTE_FAILED,
16869 					    GLOBAL_ZONEID, ipst);
16870 				} else {
16871 					ip0dbg(("ip_rput_forward_options: "
16872 					    "unable to send unreach\n"));
16873 					freemsg(mp);
16874 				}
16875 				return (-1);
16876 			}
16877 
16878 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16879 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16880 			if (dst_ire == NULL) {
16881 				/*
16882 				 * Must be partial since ip_rput_options
16883 				 * checked for strict.
16884 				 */
16885 				break;
16886 			}
16887 			off = opt[IPOPT_OFFSET];
16888 			off--;
16889 		redo_srr:
16890 			if (optlen < IP_ADDR_LEN ||
16891 			    off > optlen - IP_ADDR_LEN) {
16892 				/* End of source route */
16893 				ip1dbg((
16894 				    "ip_rput_forward_options: end of SR\n"));
16895 				ire_refrele(dst_ire);
16896 				break;
16897 			}
16898 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16899 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16900 			    IP_ADDR_LEN);
16901 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16902 			    ntohl(dst)));
16903 
16904 			/*
16905 			 * Check if our address is present more than
16906 			 * once as consecutive hops in source route.
16907 			 */
16908 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16909 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16910 			if (tmp_ire != NULL) {
16911 				ire_refrele(tmp_ire);
16912 				off += IP_ADDR_LEN;
16913 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16914 				goto redo_srr;
16915 			}
16916 			ipha->ipha_dst = dst;
16917 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16918 			ire_refrele(dst_ire);
16919 			break;
16920 		case IPOPT_RR:
16921 			off = opt[IPOPT_OFFSET];
16922 			off--;
16923 			if (optlen < IP_ADDR_LEN ||
16924 			    off > optlen - IP_ADDR_LEN) {
16925 				/* No more room - ignore */
16926 				ip1dbg((
16927 				    "ip_rput_forward_options: end of RR\n"));
16928 				break;
16929 			}
16930 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16931 			    IP_ADDR_LEN);
16932 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16933 			break;
16934 		case IPOPT_TS:
16935 			/* Insert timestamp if there is room */
16936 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16937 			case IPOPT_TS_TSONLY:
16938 				off = IPOPT_TS_TIMELEN;
16939 				break;
16940 			case IPOPT_TS_PRESPEC:
16941 			case IPOPT_TS_PRESPEC_RFC791:
16942 				/* Verify that the address matched */
16943 				off = opt[IPOPT_OFFSET] - 1;
16944 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16945 				dst_ire = ire_ctable_lookup(dst, 0,
16946 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16947 				    MATCH_IRE_TYPE, ipst);
16948 				if (dst_ire == NULL) {
16949 					/* Not for us */
16950 					break;
16951 				}
16952 				ire_refrele(dst_ire);
16953 				/* FALLTHRU */
16954 			case IPOPT_TS_TSANDADDR:
16955 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16956 				break;
16957 			default:
16958 				/*
16959 				 * ip_*put_options should have already
16960 				 * dropped this packet.
16961 				 */
16962 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16963 				    "unknown IT - bug in ip_rput_options?\n");
16964 				return (0);	/* Keep "lint" happy */
16965 			}
16966 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16967 				/* Increase overflow counter */
16968 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16969 				opt[IPOPT_POS_OV_FLG] =
16970 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16971 				    (off << 4));
16972 				break;
16973 			}
16974 			off = opt[IPOPT_OFFSET] - 1;
16975 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16976 			case IPOPT_TS_PRESPEC:
16977 			case IPOPT_TS_PRESPEC_RFC791:
16978 			case IPOPT_TS_TSANDADDR:
16979 				bcopy(&ire->ire_src_addr,
16980 				    (char *)opt + off, IP_ADDR_LEN);
16981 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16982 				/* FALLTHRU */
16983 			case IPOPT_TS_TSONLY:
16984 				off = opt[IPOPT_OFFSET] - 1;
16985 				/* Compute # of milliseconds since midnight */
16986 				gethrestime(&now);
16987 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16988 				    now.tv_nsec / (NANOSEC / MILLISEC);
16989 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16990 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16991 				break;
16992 			}
16993 			break;
16994 		}
16995 	}
16996 	return (0);
16997 }
16998 
16999 /*
17000  * This is called after processing at least one of AH/ESP headers.
17001  *
17002  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17003  * the actual, physical interface on which the packet was received,
17004  * but, when ip_strict_dst_multihoming is set to 1, could be the
17005  * interface which had the ipha_dst configured when the packet went
17006  * through ip_rput. The ill_index corresponding to the recv_ill
17007  * is saved in ipsec_in_rill_index
17008  */
17009 void
17010 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17011 {
17012 	mblk_t *mp;
17013 	ipaddr_t dst;
17014 	in6_addr_t *v6dstp;
17015 	ipha_t *ipha;
17016 	ip6_t *ip6h;
17017 	ipsec_in_t *ii;
17018 	boolean_t ill_need_rele = B_FALSE;
17019 	boolean_t rill_need_rele = B_FALSE;
17020 	boolean_t ire_need_rele = B_FALSE;
17021 	netstack_t	*ns;
17022 	ip_stack_t	*ipst;
17023 
17024 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17025 	ASSERT(ii->ipsec_in_ill_index != 0);
17026 	ns = ii->ipsec_in_ns;
17027 	ASSERT(ii->ipsec_in_ns != NULL);
17028 	ipst = ns->netstack_ip;
17029 
17030 	mp = ipsec_mp->b_cont;
17031 	ASSERT(mp != NULL);
17032 
17033 
17034 	if (ill == NULL) {
17035 		ASSERT(recv_ill == NULL);
17036 		/*
17037 		 * We need to get the original queue on which ip_rput_local
17038 		 * or ip_rput_data_v6 was called.
17039 		 */
17040 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17041 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17042 		ill_need_rele = B_TRUE;
17043 
17044 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17045 			recv_ill = ill_lookup_on_ifindex(
17046 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17047 			    NULL, NULL, NULL, NULL, ipst);
17048 			rill_need_rele = B_TRUE;
17049 		} else {
17050 			recv_ill = ill;
17051 		}
17052 
17053 		if ((ill == NULL) || (recv_ill == NULL)) {
17054 			ip0dbg(("ip_fanout_proto_again: interface "
17055 			    "disappeared\n"));
17056 			if (ill != NULL)
17057 				ill_refrele(ill);
17058 			if (recv_ill != NULL)
17059 				ill_refrele(recv_ill);
17060 			freemsg(ipsec_mp);
17061 			return;
17062 		}
17063 	}
17064 
17065 	ASSERT(ill != NULL && recv_ill != NULL);
17066 
17067 	if (mp->b_datap->db_type == M_CTL) {
17068 		/*
17069 		 * AH/ESP is returning the ICMP message after
17070 		 * removing their headers. Fanout again till
17071 		 * it gets to the right protocol.
17072 		 */
17073 		if (ii->ipsec_in_v4) {
17074 			icmph_t *icmph;
17075 			int iph_hdr_length;
17076 			int hdr_length;
17077 
17078 			ipha = (ipha_t *)mp->b_rptr;
17079 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17080 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17081 			ipha = (ipha_t *)&icmph[1];
17082 			hdr_length = IPH_HDR_LENGTH(ipha);
17083 			/*
17084 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17085 			 * Reset the type to M_DATA.
17086 			 */
17087 			mp->b_datap->db_type = M_DATA;
17088 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17089 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17090 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17091 		} else {
17092 			icmp6_t *icmp6;
17093 			int hdr_length;
17094 
17095 			ip6h = (ip6_t *)mp->b_rptr;
17096 			/* Don't call hdr_length_v6() unless you have to. */
17097 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17098 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17099 			else
17100 				hdr_length = IPV6_HDR_LEN;
17101 
17102 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17103 			/*
17104 			 * icmp_inbound_error_fanout_v6 may need to do
17105 			 * pullupmsg.  Reset the type to M_DATA.
17106 			 */
17107 			mp->b_datap->db_type = M_DATA;
17108 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17109 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17110 		}
17111 		if (ill_need_rele)
17112 			ill_refrele(ill);
17113 		if (rill_need_rele)
17114 			ill_refrele(recv_ill);
17115 		return;
17116 	}
17117 
17118 	if (ii->ipsec_in_v4) {
17119 		ipha = (ipha_t *)mp->b_rptr;
17120 		dst = ipha->ipha_dst;
17121 		if (CLASSD(dst)) {
17122 			/*
17123 			 * Multicast has to be delivered to all streams.
17124 			 */
17125 			dst = INADDR_BROADCAST;
17126 		}
17127 
17128 		if (ire == NULL) {
17129 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17130 			    MBLK_GETLABEL(mp), ipst);
17131 			if (ire == NULL) {
17132 				if (ill_need_rele)
17133 					ill_refrele(ill);
17134 				if (rill_need_rele)
17135 					ill_refrele(recv_ill);
17136 				ip1dbg(("ip_fanout_proto_again: "
17137 				    "IRE not found"));
17138 				freemsg(ipsec_mp);
17139 				return;
17140 			}
17141 			ire_need_rele = B_TRUE;
17142 		}
17143 
17144 		switch (ipha->ipha_protocol) {
17145 			case IPPROTO_UDP:
17146 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17147 				    recv_ill);
17148 				if (ire_need_rele)
17149 					ire_refrele(ire);
17150 				break;
17151 			case IPPROTO_TCP:
17152 				if (!ire_need_rele)
17153 					IRE_REFHOLD(ire);
17154 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17155 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17156 				IRE_REFRELE(ire);
17157 				if (mp != NULL)
17158 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17159 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17160 				break;
17161 			case IPPROTO_SCTP:
17162 				if (!ire_need_rele)
17163 					IRE_REFHOLD(ire);
17164 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17165 				    ipsec_mp, 0, ill->ill_rq, dst);
17166 				break;
17167 			default:
17168 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17169 				    recv_ill);
17170 				if (ire_need_rele)
17171 					ire_refrele(ire);
17172 				break;
17173 		}
17174 	} else {
17175 		uint32_t rput_flags = 0;
17176 
17177 		ip6h = (ip6_t *)mp->b_rptr;
17178 		v6dstp = &ip6h->ip6_dst;
17179 		/*
17180 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17181 		 * address.
17182 		 *
17183 		 * Currently, we don't store that state in the IPSEC_IN
17184 		 * message, and we may need to.
17185 		 */
17186 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17187 		    IP6_IN_LLMCAST : 0);
17188 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17189 		    NULL, NULL);
17190 	}
17191 	if (ill_need_rele)
17192 		ill_refrele(ill);
17193 	if (rill_need_rele)
17194 		ill_refrele(recv_ill);
17195 }
17196 
17197 /*
17198  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17199  * returns 'true' if there are still fragments left on the queue, in
17200  * which case we restart the timer.
17201  */
17202 void
17203 ill_frag_timer(void *arg)
17204 {
17205 	ill_t	*ill = (ill_t *)arg;
17206 	boolean_t frag_pending;
17207 	ip_stack_t	*ipst = ill->ill_ipst;
17208 
17209 	mutex_enter(&ill->ill_lock);
17210 	ASSERT(!ill->ill_fragtimer_executing);
17211 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17212 		ill->ill_frag_timer_id = 0;
17213 		mutex_exit(&ill->ill_lock);
17214 		return;
17215 	}
17216 	ill->ill_fragtimer_executing = 1;
17217 	mutex_exit(&ill->ill_lock);
17218 
17219 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17220 
17221 	/*
17222 	 * Restart the timer, if we have fragments pending or if someone
17223 	 * wanted us to be scheduled again.
17224 	 */
17225 	mutex_enter(&ill->ill_lock);
17226 	ill->ill_fragtimer_executing = 0;
17227 	ill->ill_frag_timer_id = 0;
17228 	if (frag_pending || ill->ill_fragtimer_needrestart)
17229 		ill_frag_timer_start(ill);
17230 	mutex_exit(&ill->ill_lock);
17231 }
17232 
17233 void
17234 ill_frag_timer_start(ill_t *ill)
17235 {
17236 	ip_stack_t	*ipst = ill->ill_ipst;
17237 
17238 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17239 
17240 	/* If the ill is closing or opening don't proceed */
17241 	if (ill->ill_state_flags & ILL_CONDEMNED)
17242 		return;
17243 
17244 	if (ill->ill_fragtimer_executing) {
17245 		/*
17246 		 * ill_frag_timer is currently executing. Just record the
17247 		 * the fact that we want the timer to be restarted.
17248 		 * ill_frag_timer will post a timeout before it returns,
17249 		 * ensuring it will be called again.
17250 		 */
17251 		ill->ill_fragtimer_needrestart = 1;
17252 		return;
17253 	}
17254 
17255 	if (ill->ill_frag_timer_id == 0) {
17256 		/*
17257 		 * The timer is neither running nor is the timeout handler
17258 		 * executing. Post a timeout so that ill_frag_timer will be
17259 		 * called
17260 		 */
17261 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17262 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17263 		ill->ill_fragtimer_needrestart = 0;
17264 	}
17265 }
17266 
17267 /*
17268  * This routine is needed for loopback when forwarding multicasts.
17269  *
17270  * IPQoS Notes:
17271  * IPPF processing is done in fanout routines.
17272  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17273  * processing for IPSec packets is done when it comes back in clear.
17274  * NOTE : The callers of this function need to do the ire_refrele for the
17275  *	  ire that is being passed in.
17276  */
17277 void
17278 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17279     ill_t *recv_ill)
17280 {
17281 	ill_t	*ill = (ill_t *)q->q_ptr;
17282 	uint32_t	sum;
17283 	uint32_t	u1;
17284 	uint32_t	u2;
17285 	int		hdr_length;
17286 	boolean_t	mctl_present;
17287 	mblk_t		*first_mp = mp;
17288 	mblk_t		*hada_mp = NULL;
17289 	ipha_t		*inner_ipha;
17290 	ip_stack_t	*ipst;
17291 
17292 	ASSERT(recv_ill != NULL);
17293 	ipst = recv_ill->ill_ipst;
17294 
17295 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17296 	    "ip_rput_locl_start: q %p", q);
17297 
17298 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17299 	ASSERT(ill != NULL);
17300 
17301 
17302 #define	rptr	((uchar_t *)ipha)
17303 #define	iphs	((uint16_t *)ipha)
17304 
17305 	/*
17306 	 * no UDP or TCP packet should come here anymore.
17307 	 */
17308 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17309 	    (ipha->ipha_protocol != IPPROTO_UDP));
17310 
17311 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17312 	if (mctl_present &&
17313 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17314 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17315 
17316 		/*
17317 		 * It's an IPsec accelerated packet.
17318 		 * Keep a pointer to the data attributes around until
17319 		 * we allocate the ipsec_info_t.
17320 		 */
17321 		IPSECHW_DEBUG(IPSECHW_PKT,
17322 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17323 		hada_mp = first_mp;
17324 		hada_mp->b_cont = NULL;
17325 		/*
17326 		 * Since it is accelerated, it comes directly from
17327 		 * the ill and the data attributes is followed by
17328 		 * the packet data.
17329 		 */
17330 		ASSERT(mp->b_datap->db_type != M_CTL);
17331 		first_mp = mp;
17332 		mctl_present = B_FALSE;
17333 	}
17334 
17335 	/*
17336 	 * IF M_CTL is not present, then ipsec_in_is_secure
17337 	 * should return B_TRUE. There is a case where loopback
17338 	 * packets has an M_CTL in the front with all the
17339 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17340 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17341 	 * packets never comes here, it is safe to ASSERT the
17342 	 * following.
17343 	 */
17344 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17345 
17346 
17347 	/* u1 is # words of IP options */
17348 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17349 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17350 
17351 	if (u1) {
17352 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17353 			if (hada_mp != NULL)
17354 				freemsg(hada_mp);
17355 			return;
17356 		}
17357 	} else {
17358 		/* Check the IP header checksum.  */
17359 #define	uph	((uint16_t *)ipha)
17360 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17361 		    uph[6] + uph[7] + uph[8] + uph[9];
17362 #undef  uph
17363 		/* finish doing IP checksum */
17364 		sum = (sum & 0xFFFF) + (sum >> 16);
17365 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17366 		/*
17367 		 * Don't verify header checksum if this packet is coming
17368 		 * back from AH/ESP as we already did it.
17369 		 */
17370 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17371 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17372 			goto drop_pkt;
17373 		}
17374 	}
17375 
17376 	/*
17377 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17378 	 * might be called more than once for secure packets, count only
17379 	 * the first time.
17380 	 */
17381 	if (!mctl_present) {
17382 		UPDATE_IB_PKT_COUNT(ire);
17383 		ire->ire_last_used_time = lbolt;
17384 	}
17385 
17386 	/* Check for fragmentation offset. */
17387 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17388 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17389 	if (u1) {
17390 		/*
17391 		 * We re-assemble fragments before we do the AH/ESP
17392 		 * processing. Thus, M_CTL should not be present
17393 		 * while we are re-assembling.
17394 		 */
17395 		ASSERT(!mctl_present);
17396 		ASSERT(first_mp == mp);
17397 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17398 			return;
17399 		}
17400 		/*
17401 		 * Make sure that first_mp points back to mp as
17402 		 * the mp we came in with could have changed in
17403 		 * ip_rput_fragment().
17404 		 */
17405 		ipha = (ipha_t *)mp->b_rptr;
17406 		first_mp = mp;
17407 	}
17408 
17409 	/*
17410 	 * Clear hardware checksumming flag as it is currently only
17411 	 * used by TCP and UDP.
17412 	 */
17413 	DB_CKSUMFLAGS(mp) = 0;
17414 
17415 	/* Now we have a complete datagram, destined for this machine. */
17416 	u1 = IPH_HDR_LENGTH(ipha);
17417 	switch (ipha->ipha_protocol) {
17418 	case IPPROTO_ICMP: {
17419 		ire_t		*ire_zone;
17420 		ilm_t		*ilm;
17421 		mblk_t		*mp1;
17422 		zoneid_t	last_zoneid;
17423 
17424 		if (CLASSD(ipha->ipha_dst) &&
17425 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17426 			ASSERT(ire->ire_type == IRE_BROADCAST);
17427 			/*
17428 			 * In the multicast case, applications may have joined
17429 			 * the group from different zones, so we need to deliver
17430 			 * the packet to each of them. Loop through the
17431 			 * multicast memberships structures (ilm) on the receive
17432 			 * ill and send a copy of the packet up each matching
17433 			 * one. However, we don't do this for multicasts sent on
17434 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17435 			 * they must stay in the sender's zone.
17436 			 *
17437 			 * ilm_add_v6() ensures that ilms in the same zone are
17438 			 * contiguous in the ill_ilm list. We use this property
17439 			 * to avoid sending duplicates needed when two
17440 			 * applications in the same zone join the same group on
17441 			 * different logical interfaces: we ignore the ilm if
17442 			 * its zoneid is the same as the last matching one.
17443 			 * In addition, the sending of the packet for
17444 			 * ire_zoneid is delayed until all of the other ilms
17445 			 * have been exhausted.
17446 			 */
17447 			last_zoneid = -1;
17448 			ILM_WALKER_HOLD(recv_ill);
17449 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17450 			    ilm = ilm->ilm_next) {
17451 				if ((ilm->ilm_flags & ILM_DELETED) ||
17452 				    ipha->ipha_dst != ilm->ilm_addr ||
17453 				    ilm->ilm_zoneid == last_zoneid ||
17454 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17455 				    ilm->ilm_zoneid == ALL_ZONES ||
17456 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17457 					continue;
17458 				mp1 = ip_copymsg(first_mp);
17459 				if (mp1 == NULL)
17460 					continue;
17461 				icmp_inbound(q, mp1, B_TRUE, ill,
17462 				    0, sum, mctl_present, B_TRUE,
17463 				    recv_ill, ilm->ilm_zoneid);
17464 				last_zoneid = ilm->ilm_zoneid;
17465 			}
17466 			ILM_WALKER_RELE(recv_ill);
17467 		} else if (ire->ire_type == IRE_BROADCAST) {
17468 			/*
17469 			 * In the broadcast case, there may be many zones
17470 			 * which need a copy of the packet delivered to them.
17471 			 * There is one IRE_BROADCAST per broadcast address
17472 			 * and per zone; we walk those using a helper function.
17473 			 * In addition, the sending of the packet for ire is
17474 			 * delayed until all of the other ires have been
17475 			 * processed.
17476 			 */
17477 			IRB_REFHOLD(ire->ire_bucket);
17478 			ire_zone = NULL;
17479 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17480 			    ire)) != NULL) {
17481 				mp1 = ip_copymsg(first_mp);
17482 				if (mp1 == NULL)
17483 					continue;
17484 
17485 				UPDATE_IB_PKT_COUNT(ire_zone);
17486 				ire_zone->ire_last_used_time = lbolt;
17487 				icmp_inbound(q, mp1, B_TRUE, ill,
17488 				    0, sum, mctl_present, B_TRUE,
17489 				    recv_ill, ire_zone->ire_zoneid);
17490 			}
17491 			IRB_REFRELE(ire->ire_bucket);
17492 		}
17493 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17494 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17495 		    ire->ire_zoneid);
17496 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17497 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17498 		return;
17499 	}
17500 	case IPPROTO_IGMP:
17501 		/*
17502 		 * If we are not willing to accept IGMP packets in clear,
17503 		 * then check with global policy.
17504 		 */
17505 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17506 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17507 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17508 			if (first_mp == NULL)
17509 				return;
17510 		}
17511 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17512 			freemsg(first_mp);
17513 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17514 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17515 			return;
17516 		}
17517 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17518 			/* Bad packet - discarded by igmp_input */
17519 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17520 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17521 			if (mctl_present)
17522 				freeb(first_mp);
17523 			return;
17524 		}
17525 		/*
17526 		 * igmp_input() may have returned the pulled up message.
17527 		 * So first_mp and ipha need to be reinitialized.
17528 		 */
17529 		ipha = (ipha_t *)mp->b_rptr;
17530 		if (mctl_present)
17531 			first_mp->b_cont = mp;
17532 		else
17533 			first_mp = mp;
17534 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17535 		    connf_head != NULL) {
17536 			/* No user-level listener for IGMP packets */
17537 			goto drop_pkt;
17538 		}
17539 		/* deliver to local raw users */
17540 		break;
17541 	case IPPROTO_PIM:
17542 		/*
17543 		 * If we are not willing to accept PIM packets in clear,
17544 		 * then check with global policy.
17545 		 */
17546 		if (ipst->ips_pim_accept_clear_messages == 0) {
17547 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17548 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17549 			if (first_mp == NULL)
17550 				return;
17551 		}
17552 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17553 			freemsg(first_mp);
17554 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17555 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17556 			return;
17557 		}
17558 		if (pim_input(q, mp, ill) != 0) {
17559 			/* Bad packet - discarded by pim_input */
17560 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17561 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17562 			if (mctl_present)
17563 				freeb(first_mp);
17564 			return;
17565 		}
17566 
17567 		/*
17568 		 * pim_input() may have pulled up the message so ipha needs to
17569 		 * be reinitialized.
17570 		 */
17571 		ipha = (ipha_t *)mp->b_rptr;
17572 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17573 		    connf_head != NULL) {
17574 			/* No user-level listener for PIM packets */
17575 			goto drop_pkt;
17576 		}
17577 		/* deliver to local raw users */
17578 		break;
17579 	case IPPROTO_ENCAP:
17580 		/*
17581 		 * Handle self-encapsulated packets (IP-in-IP where
17582 		 * the inner addresses == the outer addresses).
17583 		 */
17584 		hdr_length = IPH_HDR_LENGTH(ipha);
17585 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17586 		    mp->b_wptr) {
17587 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17588 			    sizeof (ipha_t) - mp->b_rptr)) {
17589 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17590 				freemsg(first_mp);
17591 				return;
17592 			}
17593 			ipha = (ipha_t *)mp->b_rptr;
17594 		}
17595 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17596 		/*
17597 		 * Check the sanity of the inner IP header.
17598 		 */
17599 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17600 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17601 			freemsg(first_mp);
17602 			return;
17603 		}
17604 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17605 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17606 			freemsg(first_mp);
17607 			return;
17608 		}
17609 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17610 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17611 			ipsec_in_t *ii;
17612 
17613 			/*
17614 			 * Self-encapsulated tunnel packet. Remove
17615 			 * the outer IP header and fanout again.
17616 			 * We also need to make sure that the inner
17617 			 * header is pulled up until options.
17618 			 */
17619 			mp->b_rptr = (uchar_t *)inner_ipha;
17620 			ipha = inner_ipha;
17621 			hdr_length = IPH_HDR_LENGTH(ipha);
17622 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17623 				if (!pullupmsg(mp, (uchar_t *)ipha +
17624 				    + hdr_length - mp->b_rptr)) {
17625 					freemsg(first_mp);
17626 					return;
17627 				}
17628 				ipha = (ipha_t *)mp->b_rptr;
17629 			}
17630 			if (!mctl_present) {
17631 				ASSERT(first_mp == mp);
17632 				/*
17633 				 * This means that somebody is sending
17634 				 * Self-encapsualted packets without AH/ESP.
17635 				 * If AH/ESP was present, we would have already
17636 				 * allocated the first_mp.
17637 				 */
17638 				first_mp = ipsec_in_alloc(B_TRUE,
17639 				    ipst->ips_netstack);
17640 				if (first_mp == NULL) {
17641 					ip1dbg(("ip_proto_input: IPSEC_IN "
17642 					    "allocation failure.\n"));
17643 					BUMP_MIB(ill->ill_ip_mib,
17644 					    ipIfStatsInDiscards);
17645 					freemsg(mp);
17646 					return;
17647 				}
17648 				first_mp->b_cont = mp;
17649 			}
17650 			/*
17651 			 * We generally store the ill_index if we need to
17652 			 * do IPSEC processing as we lose the ill queue when
17653 			 * we come back. But in this case, we never should
17654 			 * have to store the ill_index here as it should have
17655 			 * been stored previously when we processed the
17656 			 * AH/ESP header in this routine or for non-ipsec
17657 			 * cases, we still have the queue. But for some bad
17658 			 * packets from the wire, we can get to IPSEC after
17659 			 * this and we better store the index for that case.
17660 			 */
17661 			ill = (ill_t *)q->q_ptr;
17662 			ii = (ipsec_in_t *)first_mp->b_rptr;
17663 			ii->ipsec_in_ill_index =
17664 			    ill->ill_phyint->phyint_ifindex;
17665 			ii->ipsec_in_rill_index =
17666 			    recv_ill->ill_phyint->phyint_ifindex;
17667 			if (ii->ipsec_in_decaps) {
17668 				/*
17669 				 * This packet is self-encapsulated multiple
17670 				 * times. We don't want to recurse infinitely.
17671 				 * To keep it simple, drop the packet.
17672 				 */
17673 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17674 				freemsg(first_mp);
17675 				return;
17676 			}
17677 			ii->ipsec_in_decaps = B_TRUE;
17678 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17679 			    ire);
17680 			return;
17681 		}
17682 		break;
17683 	case IPPROTO_AH:
17684 	case IPPROTO_ESP: {
17685 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17686 
17687 		/*
17688 		 * Fast path for AH/ESP. If this is the first time
17689 		 * we are sending a datagram to AH/ESP, allocate
17690 		 * a IPSEC_IN message and prepend it. Otherwise,
17691 		 * just fanout.
17692 		 */
17693 
17694 		int ipsec_rc;
17695 		ipsec_in_t *ii;
17696 		netstack_t *ns = ipst->ips_netstack;
17697 
17698 		IP_STAT(ipst, ipsec_proto_ahesp);
17699 		if (!mctl_present) {
17700 			ASSERT(first_mp == mp);
17701 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17702 			if (first_mp == NULL) {
17703 				ip1dbg(("ip_proto_input: IPSEC_IN "
17704 				    "allocation failure.\n"));
17705 				freemsg(hada_mp); /* okay ifnull */
17706 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17707 				freemsg(mp);
17708 				return;
17709 			}
17710 			/*
17711 			 * Store the ill_index so that when we come back
17712 			 * from IPSEC we ride on the same queue.
17713 			 */
17714 			ill = (ill_t *)q->q_ptr;
17715 			ii = (ipsec_in_t *)first_mp->b_rptr;
17716 			ii->ipsec_in_ill_index =
17717 			    ill->ill_phyint->phyint_ifindex;
17718 			ii->ipsec_in_rill_index =
17719 			    recv_ill->ill_phyint->phyint_ifindex;
17720 			first_mp->b_cont = mp;
17721 			/*
17722 			 * Cache hardware acceleration info.
17723 			 */
17724 			if (hada_mp != NULL) {
17725 				IPSECHW_DEBUG(IPSECHW_PKT,
17726 				    ("ip_rput_local: caching data attr.\n"));
17727 				ii->ipsec_in_accelerated = B_TRUE;
17728 				ii->ipsec_in_da = hada_mp;
17729 				hada_mp = NULL;
17730 			}
17731 		} else {
17732 			ii = (ipsec_in_t *)first_mp->b_rptr;
17733 		}
17734 
17735 		if (!ipsec_loaded(ipss)) {
17736 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17737 			    ire->ire_zoneid, ipst);
17738 			return;
17739 		}
17740 
17741 		ns = ipst->ips_netstack;
17742 		/* select inbound SA and have IPsec process the pkt */
17743 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17744 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17745 			if (esph == NULL)
17746 				return;
17747 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17748 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17749 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17750 			    first_mp, esph);
17751 		} else {
17752 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17753 			if (ah == NULL)
17754 				return;
17755 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17756 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17757 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17758 			    first_mp, ah);
17759 		}
17760 
17761 		switch (ipsec_rc) {
17762 		case IPSEC_STATUS_SUCCESS:
17763 			break;
17764 		case IPSEC_STATUS_FAILED:
17765 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17766 			/* FALLTHRU */
17767 		case IPSEC_STATUS_PENDING:
17768 			return;
17769 		}
17770 		/* we're done with IPsec processing, send it up */
17771 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17772 		return;
17773 	}
17774 	default:
17775 		break;
17776 	}
17777 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17778 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17779 		    ire->ire_zoneid));
17780 		goto drop_pkt;
17781 	}
17782 	/*
17783 	 * Handle protocols with which IP is less intimate.  There
17784 	 * can be more than one stream bound to a particular
17785 	 * protocol.  When this is the case, each one gets a copy
17786 	 * of any incoming packets.
17787 	 */
17788 	ip_fanout_proto(q, first_mp, ill, ipha,
17789 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17790 	    B_TRUE, recv_ill, ire->ire_zoneid);
17791 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17792 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17793 	return;
17794 
17795 drop_pkt:
17796 	freemsg(first_mp);
17797 	if (hada_mp != NULL)
17798 		freeb(hada_mp);
17799 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17800 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17801 #undef	rptr
17802 #undef  iphs
17803 
17804 }
17805 
17806 /*
17807  * Update any source route, record route or timestamp options.
17808  * Check that we are at end of strict source route.
17809  * The options have already been checked for sanity in ip_rput_options().
17810  */
17811 static boolean_t
17812 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17813     ip_stack_t *ipst)
17814 {
17815 	ipoptp_t	opts;
17816 	uchar_t		*opt;
17817 	uint8_t		optval;
17818 	uint8_t		optlen;
17819 	ipaddr_t	dst;
17820 	uint32_t	ts;
17821 	ire_t		*dst_ire;
17822 	timestruc_t	now;
17823 	zoneid_t	zoneid;
17824 	ill_t		*ill;
17825 
17826 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17827 
17828 	ip2dbg(("ip_rput_local_options\n"));
17829 
17830 	for (optval = ipoptp_first(&opts, ipha);
17831 	    optval != IPOPT_EOL;
17832 	    optval = ipoptp_next(&opts)) {
17833 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17834 		opt = opts.ipoptp_cur;
17835 		optlen = opts.ipoptp_len;
17836 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17837 		    optval, optlen));
17838 		switch (optval) {
17839 			uint32_t off;
17840 		case IPOPT_SSRR:
17841 		case IPOPT_LSRR:
17842 			off = opt[IPOPT_OFFSET];
17843 			off--;
17844 			if (optlen < IP_ADDR_LEN ||
17845 			    off > optlen - IP_ADDR_LEN) {
17846 				/* End of source route */
17847 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17848 				break;
17849 			}
17850 			/*
17851 			 * This will only happen if two consecutive entries
17852 			 * in the source route contains our address or if
17853 			 * it is a packet with a loose source route which
17854 			 * reaches us before consuming the whole source route
17855 			 */
17856 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17857 			if (optval == IPOPT_SSRR) {
17858 				goto bad_src_route;
17859 			}
17860 			/*
17861 			 * Hack: instead of dropping the packet truncate the
17862 			 * source route to what has been used by filling the
17863 			 * rest with IPOPT_NOP.
17864 			 */
17865 			opt[IPOPT_OLEN] = (uint8_t)off;
17866 			while (off < optlen) {
17867 				opt[off++] = IPOPT_NOP;
17868 			}
17869 			break;
17870 		case IPOPT_RR:
17871 			off = opt[IPOPT_OFFSET];
17872 			off--;
17873 			if (optlen < IP_ADDR_LEN ||
17874 			    off > optlen - IP_ADDR_LEN) {
17875 				/* No more room - ignore */
17876 				ip1dbg((
17877 				    "ip_rput_local_options: end of RR\n"));
17878 				break;
17879 			}
17880 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17881 			    IP_ADDR_LEN);
17882 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17883 			break;
17884 		case IPOPT_TS:
17885 			/* Insert timestamp if there is romm */
17886 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17887 			case IPOPT_TS_TSONLY:
17888 				off = IPOPT_TS_TIMELEN;
17889 				break;
17890 			case IPOPT_TS_PRESPEC:
17891 			case IPOPT_TS_PRESPEC_RFC791:
17892 				/* Verify that the address matched */
17893 				off = opt[IPOPT_OFFSET] - 1;
17894 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17895 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17896 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17897 				    ipst);
17898 				if (dst_ire == NULL) {
17899 					/* Not for us */
17900 					break;
17901 				}
17902 				ire_refrele(dst_ire);
17903 				/* FALLTHRU */
17904 			case IPOPT_TS_TSANDADDR:
17905 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17906 				break;
17907 			default:
17908 				/*
17909 				 * ip_*put_options should have already
17910 				 * dropped this packet.
17911 				 */
17912 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17913 				    "unknown IT - bug in ip_rput_options?\n");
17914 				return (B_TRUE);	/* Keep "lint" happy */
17915 			}
17916 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17917 				/* Increase overflow counter */
17918 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17919 				opt[IPOPT_POS_OV_FLG] =
17920 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17921 				    (off << 4));
17922 				break;
17923 			}
17924 			off = opt[IPOPT_OFFSET] - 1;
17925 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17926 			case IPOPT_TS_PRESPEC:
17927 			case IPOPT_TS_PRESPEC_RFC791:
17928 			case IPOPT_TS_TSANDADDR:
17929 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17930 				    IP_ADDR_LEN);
17931 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17932 				/* FALLTHRU */
17933 			case IPOPT_TS_TSONLY:
17934 				off = opt[IPOPT_OFFSET] - 1;
17935 				/* Compute # of milliseconds since midnight */
17936 				gethrestime(&now);
17937 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17938 				    now.tv_nsec / (NANOSEC / MILLISEC);
17939 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17940 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17941 				break;
17942 			}
17943 			break;
17944 		}
17945 	}
17946 	return (B_TRUE);
17947 
17948 bad_src_route:
17949 	q = WR(q);
17950 	if (q->q_next != NULL)
17951 		ill = q->q_ptr;
17952 	else
17953 		ill = NULL;
17954 
17955 	/* make sure we clear any indication of a hardware checksum */
17956 	DB_CKSUMFLAGS(mp) = 0;
17957 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17958 	if (zoneid == ALL_ZONES)
17959 		freemsg(mp);
17960 	else
17961 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17962 	return (B_FALSE);
17963 
17964 }
17965 
17966 /*
17967  * Process IP options in an inbound packet.  If an option affects the
17968  * effective destination address, return the next hop address via dstp.
17969  * Returns -1 if something fails in which case an ICMP error has been sent
17970  * and mp freed.
17971  */
17972 static int
17973 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17974     ip_stack_t *ipst)
17975 {
17976 	ipoptp_t	opts;
17977 	uchar_t		*opt;
17978 	uint8_t		optval;
17979 	uint8_t		optlen;
17980 	ipaddr_t	dst;
17981 	intptr_t	code = 0;
17982 	ire_t		*ire = NULL;
17983 	zoneid_t	zoneid;
17984 	ill_t		*ill;
17985 
17986 	ip2dbg(("ip_rput_options\n"));
17987 	dst = ipha->ipha_dst;
17988 	for (optval = ipoptp_first(&opts, ipha);
17989 	    optval != IPOPT_EOL;
17990 	    optval = ipoptp_next(&opts)) {
17991 		opt = opts.ipoptp_cur;
17992 		optlen = opts.ipoptp_len;
17993 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17994 		    optval, optlen));
17995 		/*
17996 		 * Note: we need to verify the checksum before we
17997 		 * modify anything thus this routine only extracts the next
17998 		 * hop dst from any source route.
17999 		 */
18000 		switch (optval) {
18001 			uint32_t off;
18002 		case IPOPT_SSRR:
18003 		case IPOPT_LSRR:
18004 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18005 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18006 			if (ire == NULL) {
18007 				if (optval == IPOPT_SSRR) {
18008 					ip1dbg(("ip_rput_options: not next"
18009 					    " strict source route 0x%x\n",
18010 					    ntohl(dst)));
18011 					code = (char *)&ipha->ipha_dst -
18012 					    (char *)ipha;
18013 					goto param_prob; /* RouterReq's */
18014 				}
18015 				ip2dbg(("ip_rput_options: "
18016 				    "not next source route 0x%x\n",
18017 				    ntohl(dst)));
18018 				break;
18019 			}
18020 			ire_refrele(ire);
18021 
18022 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18023 				ip1dbg((
18024 				    "ip_rput_options: bad option offset\n"));
18025 				code = (char *)&opt[IPOPT_OLEN] -
18026 				    (char *)ipha;
18027 				goto param_prob;
18028 			}
18029 			off = opt[IPOPT_OFFSET];
18030 			off--;
18031 		redo_srr:
18032 			if (optlen < IP_ADDR_LEN ||
18033 			    off > optlen - IP_ADDR_LEN) {
18034 				/* End of source route */
18035 				ip1dbg(("ip_rput_options: end of SR\n"));
18036 				break;
18037 			}
18038 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18039 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18040 			    ntohl(dst)));
18041 
18042 			/*
18043 			 * Check if our address is present more than
18044 			 * once as consecutive hops in source route.
18045 			 * XXX verify per-interface ip_forwarding
18046 			 * for source route?
18047 			 */
18048 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18049 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18050 
18051 			if (ire != NULL) {
18052 				ire_refrele(ire);
18053 				off += IP_ADDR_LEN;
18054 				goto redo_srr;
18055 			}
18056 
18057 			if (dst == htonl(INADDR_LOOPBACK)) {
18058 				ip1dbg(("ip_rput_options: loopback addr in "
18059 				    "source route!\n"));
18060 				goto bad_src_route;
18061 			}
18062 			/*
18063 			 * For strict: verify that dst is directly
18064 			 * reachable.
18065 			 */
18066 			if (optval == IPOPT_SSRR) {
18067 				ire = ire_ftable_lookup(dst, 0, 0,
18068 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18069 				    MBLK_GETLABEL(mp),
18070 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18071 				if (ire == NULL) {
18072 					ip1dbg(("ip_rput_options: SSRR not "
18073 					    "directly reachable: 0x%x\n",
18074 					    ntohl(dst)));
18075 					goto bad_src_route;
18076 				}
18077 				ire_refrele(ire);
18078 			}
18079 			/*
18080 			 * Defer update of the offset and the record route
18081 			 * until the packet is forwarded.
18082 			 */
18083 			break;
18084 		case IPOPT_RR:
18085 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18086 				ip1dbg((
18087 				    "ip_rput_options: bad option offset\n"));
18088 				code = (char *)&opt[IPOPT_OLEN] -
18089 				    (char *)ipha;
18090 				goto param_prob;
18091 			}
18092 			break;
18093 		case IPOPT_TS:
18094 			/*
18095 			 * Verify that length >= 5 and that there is either
18096 			 * room for another timestamp or that the overflow
18097 			 * counter is not maxed out.
18098 			 */
18099 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18100 			if (optlen < IPOPT_MINLEN_IT) {
18101 				goto param_prob;
18102 			}
18103 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18104 				ip1dbg((
18105 				    "ip_rput_options: bad option offset\n"));
18106 				code = (char *)&opt[IPOPT_OFFSET] -
18107 				    (char *)ipha;
18108 				goto param_prob;
18109 			}
18110 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18111 			case IPOPT_TS_TSONLY:
18112 				off = IPOPT_TS_TIMELEN;
18113 				break;
18114 			case IPOPT_TS_TSANDADDR:
18115 			case IPOPT_TS_PRESPEC:
18116 			case IPOPT_TS_PRESPEC_RFC791:
18117 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18118 				break;
18119 			default:
18120 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18121 				    (char *)ipha;
18122 				goto param_prob;
18123 			}
18124 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18125 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18126 				/*
18127 				 * No room and the overflow counter is 15
18128 				 * already.
18129 				 */
18130 				goto param_prob;
18131 			}
18132 			break;
18133 		}
18134 	}
18135 
18136 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18137 		*dstp = dst;
18138 		return (0);
18139 	}
18140 
18141 	ip1dbg(("ip_rput_options: error processing IP options."));
18142 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18143 
18144 param_prob:
18145 	q = WR(q);
18146 	if (q->q_next != NULL)
18147 		ill = q->q_ptr;
18148 	else
18149 		ill = NULL;
18150 
18151 	/* make sure we clear any indication of a hardware checksum */
18152 	DB_CKSUMFLAGS(mp) = 0;
18153 	/* Don't know whether this is for non-global or global/forwarding */
18154 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18155 	if (zoneid == ALL_ZONES)
18156 		freemsg(mp);
18157 	else
18158 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18159 	return (-1);
18160 
18161 bad_src_route:
18162 	q = WR(q);
18163 	if (q->q_next != NULL)
18164 		ill = q->q_ptr;
18165 	else
18166 		ill = NULL;
18167 
18168 	/* make sure we clear any indication of a hardware checksum */
18169 	DB_CKSUMFLAGS(mp) = 0;
18170 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18171 	if (zoneid == ALL_ZONES)
18172 		freemsg(mp);
18173 	else
18174 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18175 	return (-1);
18176 }
18177 
18178 /*
18179  * IP & ICMP info in >=14 msg's ...
18180  *  - ip fixed part (mib2_ip_t)
18181  *  - icmp fixed part (mib2_icmp_t)
18182  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18183  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18184  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18185  *  - ipRouteAttributeTable (ip 102)	labeled routes
18186  *  - ip multicast membership (ip_member_t)
18187  *  - ip multicast source filtering (ip_grpsrc_t)
18188  *  - igmp fixed part (struct igmpstat)
18189  *  - multicast routing stats (struct mrtstat)
18190  *  - multicast routing vifs (array of struct vifctl)
18191  *  - multicast routing routes (array of struct mfcctl)
18192  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18193  *					One per ill plus one generic
18194  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18195  *					One per ill plus one generic
18196  *  - ipv6RouteEntry			all IPv6 IREs
18197  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18198  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18199  *  - ipv6AddrEntry			all IPv6 ipifs
18200  *  - ipv6 multicast membership (ipv6_member_t)
18201  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18202  *
18203  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18204  *
18205  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18206  * already filled in by the caller.
18207  * Return value of 0 indicates that no messages were sent and caller
18208  * should free mpctl.
18209  */
18210 int
18211 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18212 {
18213 	ip_stack_t *ipst;
18214 	sctp_stack_t *sctps;
18215 
18216 
18217 	if (q->q_next != NULL) {
18218 		ipst = ILLQ_TO_IPST(q);
18219 	} else {
18220 		ipst = CONNQ_TO_IPST(q);
18221 	}
18222 	ASSERT(ipst != NULL);
18223 	sctps = ipst->ips_netstack->netstack_sctp;
18224 
18225 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18226 		return (0);
18227 	}
18228 
18229 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18230 	    ipst)) == NULL) {
18231 		return (1);
18232 	}
18233 
18234 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18235 		return (1);
18236 	}
18237 
18238 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18239 		return (1);
18240 	}
18241 
18242 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18243 		return (1);
18244 	}
18245 
18246 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18247 		return (1);
18248 	}
18249 
18250 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18251 		return (1);
18252 	}
18253 
18254 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18255 		return (1);
18256 	}
18257 
18258 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18259 		return (1);
18260 	}
18261 
18262 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18263 		return (1);
18264 	}
18265 
18266 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18267 		return (1);
18268 	}
18269 
18270 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18271 		return (1);
18272 	}
18273 
18274 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18275 		return (1);
18276 	}
18277 
18278 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18279 		return (1);
18280 	}
18281 
18282 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18283 		return (1);
18284 	}
18285 
18286 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18287 		return (1);
18288 	}
18289 
18290 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18291 	if (mpctl == NULL) {
18292 		return (1);
18293 	}
18294 
18295 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18296 		return (1);
18297 	}
18298 	freemsg(mpctl);
18299 	return (1);
18300 }
18301 
18302 
18303 /* Get global (legacy) IPv4 statistics */
18304 static mblk_t *
18305 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18306     ip_stack_t *ipst)
18307 {
18308 	mib2_ip_t		old_ip_mib;
18309 	struct opthdr		*optp;
18310 	mblk_t			*mp2ctl;
18311 
18312 	/*
18313 	 * make a copy of the original message
18314 	 */
18315 	mp2ctl = copymsg(mpctl);
18316 
18317 	/* fixed length IP structure... */
18318 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18319 	optp->level = MIB2_IP;
18320 	optp->name = 0;
18321 	SET_MIB(old_ip_mib.ipForwarding,
18322 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18323 	SET_MIB(old_ip_mib.ipDefaultTTL,
18324 	    (uint32_t)ipst->ips_ip_def_ttl);
18325 	SET_MIB(old_ip_mib.ipReasmTimeout,
18326 	    ipst->ips_ip_g_frag_timeout);
18327 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18328 	    sizeof (mib2_ipAddrEntry_t));
18329 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18330 	    sizeof (mib2_ipRouteEntry_t));
18331 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18332 	    sizeof (mib2_ipNetToMediaEntry_t));
18333 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18334 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18335 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18336 	    sizeof (mib2_ipAttributeEntry_t));
18337 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18338 
18339 	/*
18340 	 * Grab the statistics from the new IP MIB
18341 	 */
18342 	SET_MIB(old_ip_mib.ipInReceives,
18343 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18344 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18345 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18346 	SET_MIB(old_ip_mib.ipForwDatagrams,
18347 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18348 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18349 	    ipmib->ipIfStatsInUnknownProtos);
18350 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18351 	SET_MIB(old_ip_mib.ipInDelivers,
18352 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18353 	SET_MIB(old_ip_mib.ipOutRequests,
18354 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18355 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18356 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18357 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18358 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18359 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18360 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18361 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18362 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18363 
18364 	/* ipRoutingDiscards is not being used */
18365 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18366 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18367 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18368 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18369 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18370 	    ipmib->ipIfStatsReasmDuplicates);
18371 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18372 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18373 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18374 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18375 	SET_MIB(old_ip_mib.rawipInOverflows,
18376 	    ipmib->rawipIfStatsInOverflows);
18377 
18378 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18379 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18380 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18381 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18382 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18383 	    ipmib->ipIfStatsOutSwitchIPVersion);
18384 
18385 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18386 	    (int)sizeof (old_ip_mib))) {
18387 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18388 		    (uint_t)sizeof (old_ip_mib)));
18389 	}
18390 
18391 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18392 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18393 	    (int)optp->level, (int)optp->name, (int)optp->len));
18394 	qreply(q, mpctl);
18395 	return (mp2ctl);
18396 }
18397 
18398 /* Per interface IPv4 statistics */
18399 static mblk_t *
18400 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18401 {
18402 	struct opthdr		*optp;
18403 	mblk_t			*mp2ctl;
18404 	ill_t			*ill;
18405 	ill_walk_context_t	ctx;
18406 	mblk_t			*mp_tail = NULL;
18407 	mib2_ipIfStatsEntry_t	global_ip_mib;
18408 
18409 	/*
18410 	 * Make a copy of the original message
18411 	 */
18412 	mp2ctl = copymsg(mpctl);
18413 
18414 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18415 	optp->level = MIB2_IP;
18416 	optp->name = MIB2_IP_TRAFFIC_STATS;
18417 	/* Include "unknown interface" ip_mib */
18418 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18419 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18420 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18421 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18422 	    (ipst->ips_ip_g_forward ? 1 : 2));
18423 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18424 	    (uint32_t)ipst->ips_ip_def_ttl);
18425 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18426 	    sizeof (mib2_ipIfStatsEntry_t));
18427 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18428 	    sizeof (mib2_ipAddrEntry_t));
18429 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18430 	    sizeof (mib2_ipRouteEntry_t));
18431 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18432 	    sizeof (mib2_ipNetToMediaEntry_t));
18433 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18434 	    sizeof (ip_member_t));
18435 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18436 	    sizeof (ip_grpsrc_t));
18437 
18438 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18439 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18440 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18441 		    "failed to allocate %u bytes\n",
18442 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18443 	}
18444 
18445 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18446 
18447 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18448 	ill = ILL_START_WALK_V4(&ctx, ipst);
18449 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18450 		ill->ill_ip_mib->ipIfStatsIfIndex =
18451 		    ill->ill_phyint->phyint_ifindex;
18452 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18453 		    (ipst->ips_ip_g_forward ? 1 : 2));
18454 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18455 		    (uint32_t)ipst->ips_ip_def_ttl);
18456 
18457 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18458 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18459 		    (char *)ill->ill_ip_mib,
18460 		    (int)sizeof (*ill->ill_ip_mib))) {
18461 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18462 			    "failed to allocate %u bytes\n",
18463 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18464 		}
18465 	}
18466 	rw_exit(&ipst->ips_ill_g_lock);
18467 
18468 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18469 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18470 	    "level %d, name %d, len %d\n",
18471 	    (int)optp->level, (int)optp->name, (int)optp->len));
18472 	qreply(q, mpctl);
18473 
18474 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18475 }
18476 
18477 /* Global IPv4 ICMP statistics */
18478 static mblk_t *
18479 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18480 {
18481 	struct opthdr		*optp;
18482 	mblk_t			*mp2ctl;
18483 
18484 	/*
18485 	 * Make a copy of the original message
18486 	 */
18487 	mp2ctl = copymsg(mpctl);
18488 
18489 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18490 	optp->level = MIB2_ICMP;
18491 	optp->name = 0;
18492 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18493 	    (int)sizeof (ipst->ips_icmp_mib))) {
18494 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18495 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18496 	}
18497 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18498 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18499 	    (int)optp->level, (int)optp->name, (int)optp->len));
18500 	qreply(q, mpctl);
18501 	return (mp2ctl);
18502 }
18503 
18504 /* Global IPv4 IGMP statistics */
18505 static mblk_t *
18506 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18507 {
18508 	struct opthdr		*optp;
18509 	mblk_t			*mp2ctl;
18510 
18511 	/*
18512 	 * make a copy of the original message
18513 	 */
18514 	mp2ctl = copymsg(mpctl);
18515 
18516 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18517 	optp->level = EXPER_IGMP;
18518 	optp->name = 0;
18519 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18520 	    (int)sizeof (ipst->ips_igmpstat))) {
18521 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18522 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18523 	}
18524 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18525 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18526 	    (int)optp->level, (int)optp->name, (int)optp->len));
18527 	qreply(q, mpctl);
18528 	return (mp2ctl);
18529 }
18530 
18531 /* Global IPv4 Multicast Routing statistics */
18532 static mblk_t *
18533 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18534 {
18535 	struct opthdr		*optp;
18536 	mblk_t			*mp2ctl;
18537 
18538 	/*
18539 	 * make a copy of the original message
18540 	 */
18541 	mp2ctl = copymsg(mpctl);
18542 
18543 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18544 	optp->level = EXPER_DVMRP;
18545 	optp->name = 0;
18546 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18547 		ip0dbg(("ip_mroute_stats: failed\n"));
18548 	}
18549 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18550 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18551 	    (int)optp->level, (int)optp->name, (int)optp->len));
18552 	qreply(q, mpctl);
18553 	return (mp2ctl);
18554 }
18555 
18556 /* IPv4 address information */
18557 static mblk_t *
18558 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18559 {
18560 	struct opthdr		*optp;
18561 	mblk_t			*mp2ctl;
18562 	mblk_t			*mp_tail = NULL;
18563 	ill_t			*ill;
18564 	ipif_t			*ipif;
18565 	uint_t			bitval;
18566 	mib2_ipAddrEntry_t	mae;
18567 	zoneid_t		zoneid;
18568 	ill_walk_context_t ctx;
18569 
18570 	/*
18571 	 * make a copy of the original message
18572 	 */
18573 	mp2ctl = copymsg(mpctl);
18574 
18575 	/* ipAddrEntryTable */
18576 
18577 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18578 	optp->level = MIB2_IP;
18579 	optp->name = MIB2_IP_ADDR;
18580 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18581 
18582 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18583 	ill = ILL_START_WALK_V4(&ctx, ipst);
18584 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18585 		for (ipif = ill->ill_ipif; ipif != NULL;
18586 		    ipif = ipif->ipif_next) {
18587 			if (ipif->ipif_zoneid != zoneid &&
18588 			    ipif->ipif_zoneid != ALL_ZONES)
18589 				continue;
18590 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18591 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18592 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18593 
18594 			(void) ipif_get_name(ipif,
18595 			    mae.ipAdEntIfIndex.o_bytes,
18596 			    OCTET_LENGTH);
18597 			mae.ipAdEntIfIndex.o_length =
18598 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18599 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18600 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18601 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18602 			mae.ipAdEntInfo.ae_subnet_len =
18603 			    ip_mask_to_plen(ipif->ipif_net_mask);
18604 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18605 			for (bitval = 1;
18606 			    bitval &&
18607 			    !(bitval & ipif->ipif_brd_addr);
18608 			    bitval <<= 1)
18609 				noop;
18610 			mae.ipAdEntBcastAddr = bitval;
18611 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18612 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18613 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18614 			mae.ipAdEntInfo.ae_broadcast_addr =
18615 			    ipif->ipif_brd_addr;
18616 			mae.ipAdEntInfo.ae_pp_dst_addr =
18617 			    ipif->ipif_pp_dst_addr;
18618 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18619 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18620 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18621 
18622 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18623 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18624 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18625 				    "allocate %u bytes\n",
18626 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18627 			}
18628 		}
18629 	}
18630 	rw_exit(&ipst->ips_ill_g_lock);
18631 
18632 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18633 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18634 	    (int)optp->level, (int)optp->name, (int)optp->len));
18635 	qreply(q, mpctl);
18636 	return (mp2ctl);
18637 }
18638 
18639 /* IPv6 address information */
18640 static mblk_t *
18641 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18642 {
18643 	struct opthdr		*optp;
18644 	mblk_t			*mp2ctl;
18645 	mblk_t			*mp_tail = NULL;
18646 	ill_t			*ill;
18647 	ipif_t			*ipif;
18648 	mib2_ipv6AddrEntry_t	mae6;
18649 	zoneid_t		zoneid;
18650 	ill_walk_context_t	ctx;
18651 
18652 	/*
18653 	 * make a copy of the original message
18654 	 */
18655 	mp2ctl = copymsg(mpctl);
18656 
18657 	/* ipv6AddrEntryTable */
18658 
18659 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18660 	optp->level = MIB2_IP6;
18661 	optp->name = MIB2_IP6_ADDR;
18662 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18663 
18664 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18665 	ill = ILL_START_WALK_V6(&ctx, ipst);
18666 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18667 		for (ipif = ill->ill_ipif; ipif != NULL;
18668 		    ipif = ipif->ipif_next) {
18669 			if (ipif->ipif_zoneid != zoneid &&
18670 			    ipif->ipif_zoneid != ALL_ZONES)
18671 				continue;
18672 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18673 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18674 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18675 
18676 			(void) ipif_get_name(ipif,
18677 			    mae6.ipv6AddrIfIndex.o_bytes,
18678 			    OCTET_LENGTH);
18679 			mae6.ipv6AddrIfIndex.o_length =
18680 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18681 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18682 			mae6.ipv6AddrPfxLength =
18683 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18684 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18685 			mae6.ipv6AddrInfo.ae_subnet_len =
18686 			    mae6.ipv6AddrPfxLength;
18687 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18688 
18689 			/* Type: stateless(1), stateful(2), unknown(3) */
18690 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18691 				mae6.ipv6AddrType = 1;
18692 			else
18693 				mae6.ipv6AddrType = 2;
18694 			/* Anycast: true(1), false(2) */
18695 			if (ipif->ipif_flags & IPIF_ANYCAST)
18696 				mae6.ipv6AddrAnycastFlag = 1;
18697 			else
18698 				mae6.ipv6AddrAnycastFlag = 2;
18699 
18700 			/*
18701 			 * Address status: preferred(1), deprecated(2),
18702 			 * invalid(3), inaccessible(4), unknown(5)
18703 			 */
18704 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18705 				mae6.ipv6AddrStatus = 3;
18706 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18707 				mae6.ipv6AddrStatus = 2;
18708 			else
18709 				mae6.ipv6AddrStatus = 1;
18710 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18711 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18712 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18713 						ipif->ipif_v6pp_dst_addr;
18714 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18715 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18716 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18717 			mae6.ipv6AddrIdentifier = ill->ill_token;
18718 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18719 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18720 			mae6.ipv6AddrRetransmitTime =
18721 			    ill->ill_reachable_retrans_time;
18722 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18723 				(char *)&mae6,
18724 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18725 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18726 				    "allocate %u bytes\n",
18727 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18728 			}
18729 		}
18730 	}
18731 	rw_exit(&ipst->ips_ill_g_lock);
18732 
18733 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18734 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18735 	    (int)optp->level, (int)optp->name, (int)optp->len));
18736 	qreply(q, mpctl);
18737 	return (mp2ctl);
18738 }
18739 
18740 /* IPv4 multicast group membership. */
18741 static mblk_t *
18742 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18743 {
18744 	struct opthdr		*optp;
18745 	mblk_t			*mp2ctl;
18746 	ill_t			*ill;
18747 	ipif_t			*ipif;
18748 	ilm_t			*ilm;
18749 	ip_member_t		ipm;
18750 	mblk_t			*mp_tail = NULL;
18751 	ill_walk_context_t	ctx;
18752 	zoneid_t		zoneid;
18753 
18754 	/*
18755 	 * make a copy of the original message
18756 	 */
18757 	mp2ctl = copymsg(mpctl);
18758 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18759 
18760 	/* ipGroupMember table */
18761 	optp = (struct opthdr *)&mpctl->b_rptr[
18762 	    sizeof (struct T_optmgmt_ack)];
18763 	optp->level = MIB2_IP;
18764 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18765 
18766 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18767 	ill = ILL_START_WALK_V4(&ctx, ipst);
18768 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18769 		ILM_WALKER_HOLD(ill);
18770 		for (ipif = ill->ill_ipif; ipif != NULL;
18771 		    ipif = ipif->ipif_next) {
18772 			if (ipif->ipif_zoneid != zoneid &&
18773 			    ipif->ipif_zoneid != ALL_ZONES)
18774 				continue;	/* not this zone */
18775 			(void) ipif_get_name(ipif,
18776 			    ipm.ipGroupMemberIfIndex.o_bytes,
18777 			    OCTET_LENGTH);
18778 			ipm.ipGroupMemberIfIndex.o_length =
18779 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18780 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18781 				ASSERT(ilm->ilm_ipif != NULL);
18782 				ASSERT(ilm->ilm_ill == NULL);
18783 				if (ilm->ilm_ipif != ipif)
18784 					continue;
18785 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18786 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18787 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18788 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18789 				    (char *)&ipm, (int)sizeof (ipm))) {
18790 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18791 					    "failed to allocate %u bytes\n",
18792 						(uint_t)sizeof (ipm)));
18793 				}
18794 			}
18795 		}
18796 		ILM_WALKER_RELE(ill);
18797 	}
18798 	rw_exit(&ipst->ips_ill_g_lock);
18799 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18800 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18801 	    (int)optp->level, (int)optp->name, (int)optp->len));
18802 	qreply(q, mpctl);
18803 	return (mp2ctl);
18804 }
18805 
18806 /* IPv6 multicast group membership. */
18807 static mblk_t *
18808 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18809 {
18810 	struct opthdr		*optp;
18811 	mblk_t			*mp2ctl;
18812 	ill_t			*ill;
18813 	ilm_t			*ilm;
18814 	ipv6_member_t		ipm6;
18815 	mblk_t			*mp_tail = NULL;
18816 	ill_walk_context_t	ctx;
18817 	zoneid_t		zoneid;
18818 
18819 	/*
18820 	 * make a copy of the original message
18821 	 */
18822 	mp2ctl = copymsg(mpctl);
18823 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18824 
18825 	/* ip6GroupMember table */
18826 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18827 	optp->level = MIB2_IP6;
18828 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18829 
18830 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18831 	ill = ILL_START_WALK_V6(&ctx, ipst);
18832 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18833 		ILM_WALKER_HOLD(ill);
18834 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18835 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18836 			ASSERT(ilm->ilm_ipif == NULL);
18837 			ASSERT(ilm->ilm_ill != NULL);
18838 			if (ilm->ilm_zoneid != zoneid)
18839 				continue;	/* not this zone */
18840 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18841 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18842 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18843 			if (!snmp_append_data2(mpctl->b_cont,
18844 			    &mp_tail,
18845 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18846 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18847 				    "failed to allocate %u bytes\n",
18848 				    (uint_t)sizeof (ipm6)));
18849 			}
18850 		}
18851 		ILM_WALKER_RELE(ill);
18852 	}
18853 	rw_exit(&ipst->ips_ill_g_lock);
18854 
18855 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18856 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18857 	    (int)optp->level, (int)optp->name, (int)optp->len));
18858 	qreply(q, mpctl);
18859 	return (mp2ctl);
18860 }
18861 
18862 /* IP multicast filtered sources */
18863 static mblk_t *
18864 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18865 {
18866 	struct opthdr		*optp;
18867 	mblk_t			*mp2ctl;
18868 	ill_t			*ill;
18869 	ipif_t			*ipif;
18870 	ilm_t			*ilm;
18871 	ip_grpsrc_t		ips;
18872 	mblk_t			*mp_tail = NULL;
18873 	ill_walk_context_t	ctx;
18874 	zoneid_t		zoneid;
18875 	int			i;
18876 	slist_t			*sl;
18877 
18878 	/*
18879 	 * make a copy of the original message
18880 	 */
18881 	mp2ctl = copymsg(mpctl);
18882 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18883 
18884 	/* ipGroupSource table */
18885 	optp = (struct opthdr *)&mpctl->b_rptr[
18886 	    sizeof (struct T_optmgmt_ack)];
18887 	optp->level = MIB2_IP;
18888 	optp->name = EXPER_IP_GROUP_SOURCES;
18889 
18890 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18891 	ill = ILL_START_WALK_V4(&ctx, ipst);
18892 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18893 		ILM_WALKER_HOLD(ill);
18894 		for (ipif = ill->ill_ipif; ipif != NULL;
18895 		    ipif = ipif->ipif_next) {
18896 			if (ipif->ipif_zoneid != zoneid)
18897 				continue;	/* not this zone */
18898 			(void) ipif_get_name(ipif,
18899 			    ips.ipGroupSourceIfIndex.o_bytes,
18900 			    OCTET_LENGTH);
18901 			ips.ipGroupSourceIfIndex.o_length =
18902 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18903 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18904 				ASSERT(ilm->ilm_ipif != NULL);
18905 				ASSERT(ilm->ilm_ill == NULL);
18906 				sl = ilm->ilm_filter;
18907 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18908 					continue;
18909 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18910 				for (i = 0; i < sl->sl_numsrc; i++) {
18911 					if (!IN6_IS_ADDR_V4MAPPED(
18912 					    &sl->sl_addr[i]))
18913 						continue;
18914 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18915 					    ips.ipGroupSourceAddress);
18916 					if (snmp_append_data2(mpctl->b_cont,
18917 					    &mp_tail, (char *)&ips,
18918 					    (int)sizeof (ips)) == 0) {
18919 						ip1dbg(("ip_snmp_get_mib2_"
18920 						    "ip_group_src: failed to "
18921 						    "allocate %u bytes\n",
18922 						    (uint_t)sizeof (ips)));
18923 					}
18924 				}
18925 			}
18926 		}
18927 		ILM_WALKER_RELE(ill);
18928 	}
18929 	rw_exit(&ipst->ips_ill_g_lock);
18930 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18931 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18932 	    (int)optp->level, (int)optp->name, (int)optp->len));
18933 	qreply(q, mpctl);
18934 	return (mp2ctl);
18935 }
18936 
18937 /* IPv6 multicast filtered sources. */
18938 static mblk_t *
18939 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18940 {
18941 	struct opthdr		*optp;
18942 	mblk_t			*mp2ctl;
18943 	ill_t			*ill;
18944 	ilm_t			*ilm;
18945 	ipv6_grpsrc_t		ips6;
18946 	mblk_t			*mp_tail = NULL;
18947 	ill_walk_context_t	ctx;
18948 	zoneid_t		zoneid;
18949 	int			i;
18950 	slist_t			*sl;
18951 
18952 	/*
18953 	 * make a copy of the original message
18954 	 */
18955 	mp2ctl = copymsg(mpctl);
18956 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18957 
18958 	/* ip6GroupMember table */
18959 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18960 	optp->level = MIB2_IP6;
18961 	optp->name = EXPER_IP6_GROUP_SOURCES;
18962 
18963 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18964 	ill = ILL_START_WALK_V6(&ctx, ipst);
18965 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18966 		ILM_WALKER_HOLD(ill);
18967 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18968 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18969 			ASSERT(ilm->ilm_ipif == NULL);
18970 			ASSERT(ilm->ilm_ill != NULL);
18971 			sl = ilm->ilm_filter;
18972 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18973 				continue;
18974 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18975 			for (i = 0; i < sl->sl_numsrc; i++) {
18976 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18977 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18978 				    (char *)&ips6, (int)sizeof (ips6))) {
18979 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18980 					    "group_src: failed to allocate "
18981 					    "%u bytes\n",
18982 					    (uint_t)sizeof (ips6)));
18983 				}
18984 			}
18985 		}
18986 		ILM_WALKER_RELE(ill);
18987 	}
18988 	rw_exit(&ipst->ips_ill_g_lock);
18989 
18990 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18991 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18992 	    (int)optp->level, (int)optp->name, (int)optp->len));
18993 	qreply(q, mpctl);
18994 	return (mp2ctl);
18995 }
18996 
18997 /* Multicast routing virtual interface table. */
18998 static mblk_t *
18999 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19000 {
19001 	struct opthdr		*optp;
19002 	mblk_t			*mp2ctl;
19003 
19004 	/*
19005 	 * make a copy of the original message
19006 	 */
19007 	mp2ctl = copymsg(mpctl);
19008 
19009 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19010 	optp->level = EXPER_DVMRP;
19011 	optp->name = EXPER_DVMRP_VIF;
19012 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19013 		ip0dbg(("ip_mroute_vif: failed\n"));
19014 	}
19015 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19016 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19017 	    (int)optp->level, (int)optp->name, (int)optp->len));
19018 	qreply(q, mpctl);
19019 	return (mp2ctl);
19020 }
19021 
19022 /* Multicast routing table. */
19023 static mblk_t *
19024 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19025 {
19026 	struct opthdr		*optp;
19027 	mblk_t			*mp2ctl;
19028 
19029 	/*
19030 	 * make a copy of the original message
19031 	 */
19032 	mp2ctl = copymsg(mpctl);
19033 
19034 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19035 	optp->level = EXPER_DVMRP;
19036 	optp->name = EXPER_DVMRP_MRT;
19037 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19038 		ip0dbg(("ip_mroute_mrt: failed\n"));
19039 	}
19040 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19041 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19042 	    (int)optp->level, (int)optp->name, (int)optp->len));
19043 	qreply(q, mpctl);
19044 	return (mp2ctl);
19045 }
19046 
19047 /*
19048  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19049  * in one IRE walk.
19050  */
19051 static mblk_t *
19052 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19053 {
19054 	struct opthdr	*optp;
19055 	mblk_t		*mp2ctl;	/* Returned */
19056 	mblk_t		*mp3ctl;	/* nettomedia */
19057 	mblk_t		*mp4ctl;	/* routeattrs */
19058 	iproutedata_t	ird;
19059 	zoneid_t	zoneid;
19060 
19061 	/*
19062 	 * make copies of the original message
19063 	 *	- mp2ctl is returned unchanged to the caller for his use
19064 	 *	- mpctl is sent upstream as ipRouteEntryTable
19065 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19066 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19067 	 */
19068 	mp2ctl = copymsg(mpctl);
19069 	mp3ctl = copymsg(mpctl);
19070 	mp4ctl = copymsg(mpctl);
19071 	if (mp3ctl == NULL || mp4ctl == NULL) {
19072 		freemsg(mp4ctl);
19073 		freemsg(mp3ctl);
19074 		freemsg(mp2ctl);
19075 		freemsg(mpctl);
19076 		return (NULL);
19077 	}
19078 
19079 	bzero(&ird, sizeof (ird));
19080 
19081 	ird.ird_route.lp_head = mpctl->b_cont;
19082 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19083 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19084 
19085 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19086 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19087 	if (zoneid == GLOBAL_ZONEID) {
19088 		/*
19089 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19090 		 * requires the sys_net_config or sys_ip_config privilege,
19091 		 * it can only run in the global zone or an exclusive-IP zone,
19092 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19093 		 */
19094 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19095 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19096 	}
19097 
19098 	/* ipRouteEntryTable in mpctl */
19099 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19100 	optp->level = MIB2_IP;
19101 	optp->name = MIB2_IP_ROUTE;
19102 	optp->len = msgdsize(ird.ird_route.lp_head);
19103 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19104 	    (int)optp->level, (int)optp->name, (int)optp->len));
19105 	qreply(q, mpctl);
19106 
19107 	/* ipNetToMediaEntryTable in mp3ctl */
19108 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19109 	optp->level = MIB2_IP;
19110 	optp->name = MIB2_IP_MEDIA;
19111 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19112 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19113 	    (int)optp->level, (int)optp->name, (int)optp->len));
19114 	qreply(q, mp3ctl);
19115 
19116 	/* ipRouteAttributeTable in mp4ctl */
19117 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19118 	optp->level = MIB2_IP;
19119 	optp->name = EXPER_IP_RTATTR;
19120 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19121 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19122 	    (int)optp->level, (int)optp->name, (int)optp->len));
19123 	if (optp->len == 0)
19124 		freemsg(mp4ctl);
19125 	else
19126 		qreply(q, mp4ctl);
19127 
19128 	return (mp2ctl);
19129 }
19130 
19131 /*
19132  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19133  * ipv6NetToMediaEntryTable in an NDP walk.
19134  */
19135 static mblk_t *
19136 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19137 {
19138 	struct opthdr	*optp;
19139 	mblk_t		*mp2ctl;	/* Returned */
19140 	mblk_t		*mp3ctl;	/* nettomedia */
19141 	mblk_t		*mp4ctl;	/* routeattrs */
19142 	iproutedata_t	ird;
19143 	zoneid_t	zoneid;
19144 
19145 	/*
19146 	 * make copies of the original message
19147 	 *	- mp2ctl is returned unchanged to the caller for his use
19148 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19149 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19150 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19151 	 */
19152 	mp2ctl = copymsg(mpctl);
19153 	mp3ctl = copymsg(mpctl);
19154 	mp4ctl = copymsg(mpctl);
19155 	if (mp3ctl == NULL || mp4ctl == NULL) {
19156 		freemsg(mp4ctl);
19157 		freemsg(mp3ctl);
19158 		freemsg(mp2ctl);
19159 		freemsg(mpctl);
19160 		return (NULL);
19161 	}
19162 
19163 	bzero(&ird, sizeof (ird));
19164 
19165 	ird.ird_route.lp_head = mpctl->b_cont;
19166 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19167 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19168 
19169 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19170 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19171 
19172 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19173 	optp->level = MIB2_IP6;
19174 	optp->name = MIB2_IP6_ROUTE;
19175 	optp->len = msgdsize(ird.ird_route.lp_head);
19176 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19177 	    (int)optp->level, (int)optp->name, (int)optp->len));
19178 	qreply(q, mpctl);
19179 
19180 	/* ipv6NetToMediaEntryTable in mp3ctl */
19181 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19182 
19183 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19184 	optp->level = MIB2_IP6;
19185 	optp->name = MIB2_IP6_MEDIA;
19186 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19187 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19188 	    (int)optp->level, (int)optp->name, (int)optp->len));
19189 	qreply(q, mp3ctl);
19190 
19191 	/* ipv6RouteAttributeTable in mp4ctl */
19192 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19193 	optp->level = MIB2_IP6;
19194 	optp->name = EXPER_IP_RTATTR;
19195 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19196 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19197 	    (int)optp->level, (int)optp->name, (int)optp->len));
19198 	if (optp->len == 0)
19199 		freemsg(mp4ctl);
19200 	else
19201 		qreply(q, mp4ctl);
19202 
19203 	return (mp2ctl);
19204 }
19205 
19206 /*
19207  * IPv6 mib: One per ill
19208  */
19209 static mblk_t *
19210 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19211 {
19212 	struct opthdr		*optp;
19213 	mblk_t			*mp2ctl;
19214 	ill_t			*ill;
19215 	ill_walk_context_t	ctx;
19216 	mblk_t			*mp_tail = NULL;
19217 
19218 	/*
19219 	 * Make a copy of the original message
19220 	 */
19221 	mp2ctl = copymsg(mpctl);
19222 
19223 	/* fixed length IPv6 structure ... */
19224 
19225 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19226 	optp->level = MIB2_IP6;
19227 	optp->name = 0;
19228 	/* Include "unknown interface" ip6_mib */
19229 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19230 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19231 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19232 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19233 	    ipst->ips_ipv6_forward ? 1 : 2);
19234 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19235 	    ipst->ips_ipv6_def_hops);
19236 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19237 	    sizeof (mib2_ipIfStatsEntry_t));
19238 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19239 	    sizeof (mib2_ipv6AddrEntry_t));
19240 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19241 	    sizeof (mib2_ipv6RouteEntry_t));
19242 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19243 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19244 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19245 	    sizeof (ipv6_member_t));
19246 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19247 	    sizeof (ipv6_grpsrc_t));
19248 
19249 	/*
19250 	 * Synchronize 64- and 32-bit counters
19251 	 */
19252 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19253 	    ipIfStatsHCInReceives);
19254 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19255 	    ipIfStatsHCInDelivers);
19256 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19257 	    ipIfStatsHCOutRequests);
19258 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19259 	    ipIfStatsHCOutForwDatagrams);
19260 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19261 	    ipIfStatsHCOutMcastPkts);
19262 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19263 	    ipIfStatsHCInMcastPkts);
19264 
19265 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19266 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19267 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19268 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19269 	}
19270 
19271 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19272 	ill = ILL_START_WALK_V6(&ctx, ipst);
19273 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19274 		ill->ill_ip_mib->ipIfStatsIfIndex =
19275 		    ill->ill_phyint->phyint_ifindex;
19276 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19277 		    ipst->ips_ipv6_forward ? 1 : 2);
19278 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19279 		    ill->ill_max_hops);
19280 
19281 		/*
19282 		 * Synchronize 64- and 32-bit counters
19283 		 */
19284 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19285 		    ipIfStatsHCInReceives);
19286 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19287 		    ipIfStatsHCInDelivers);
19288 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19289 		    ipIfStatsHCOutRequests);
19290 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19291 		    ipIfStatsHCOutForwDatagrams);
19292 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19293 		    ipIfStatsHCOutMcastPkts);
19294 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19295 		    ipIfStatsHCInMcastPkts);
19296 
19297 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19298 		    (char *)ill->ill_ip_mib,
19299 		    (int)sizeof (*ill->ill_ip_mib))) {
19300 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19301 				"%u bytes\n",
19302 				(uint_t)sizeof (*ill->ill_ip_mib)));
19303 		}
19304 	}
19305 	rw_exit(&ipst->ips_ill_g_lock);
19306 
19307 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19308 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19309 	    (int)optp->level, (int)optp->name, (int)optp->len));
19310 	qreply(q, mpctl);
19311 	return (mp2ctl);
19312 }
19313 
19314 /*
19315  * ICMPv6 mib: One per ill
19316  */
19317 static mblk_t *
19318 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19319 {
19320 	struct opthdr		*optp;
19321 	mblk_t			*mp2ctl;
19322 	ill_t			*ill;
19323 	ill_walk_context_t	ctx;
19324 	mblk_t			*mp_tail = NULL;
19325 	/*
19326 	 * Make a copy of the original message
19327 	 */
19328 	mp2ctl = copymsg(mpctl);
19329 
19330 	/* fixed length ICMPv6 structure ... */
19331 
19332 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19333 	optp->level = MIB2_ICMP6;
19334 	optp->name = 0;
19335 	/* Include "unknown interface" icmp6_mib */
19336 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19337 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19338 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19339 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19340 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19341 	    (char *)&ipst->ips_icmp6_mib,
19342 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19343 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19344 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19345 	}
19346 
19347 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19348 	ill = ILL_START_WALK_V6(&ctx, ipst);
19349 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19350 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19351 		    ill->ill_phyint->phyint_ifindex;
19352 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19353 		    (char *)ill->ill_icmp6_mib,
19354 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19355 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19356 			    "%u bytes\n",
19357 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19358 		}
19359 	}
19360 	rw_exit(&ipst->ips_ill_g_lock);
19361 
19362 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19363 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19364 	    (int)optp->level, (int)optp->name, (int)optp->len));
19365 	qreply(q, mpctl);
19366 	return (mp2ctl);
19367 }
19368 
19369 /*
19370  * ire_walk routine to create both ipRouteEntryTable and
19371  * ipRouteAttributeTable in one IRE walk
19372  */
19373 static void
19374 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19375 {
19376 	ill_t				*ill;
19377 	ipif_t				*ipif;
19378 	mib2_ipRouteEntry_t		*re;
19379 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19380 	ipaddr_t			gw_addr;
19381 	tsol_ire_gw_secattr_t		*attrp;
19382 	tsol_gc_t			*gc = NULL;
19383 	tsol_gcgrp_t			*gcgrp = NULL;
19384 	uint_t				sacnt = 0;
19385 	int				i;
19386 
19387 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19388 
19389 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19390 		return;
19391 
19392 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19393 		mutex_enter(&attrp->igsa_lock);
19394 		if ((gc = attrp->igsa_gc) != NULL) {
19395 			gcgrp = gc->gc_grp;
19396 			ASSERT(gcgrp != NULL);
19397 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19398 			sacnt = 1;
19399 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19400 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19401 			gc = gcgrp->gcgrp_head;
19402 			sacnt = gcgrp->gcgrp_count;
19403 		}
19404 		mutex_exit(&attrp->igsa_lock);
19405 
19406 		/* do nothing if there's no gc to report */
19407 		if (gc == NULL) {
19408 			ASSERT(sacnt == 0);
19409 			if (gcgrp != NULL) {
19410 				/* we might as well drop the lock now */
19411 				rw_exit(&gcgrp->gcgrp_rwlock);
19412 				gcgrp = NULL;
19413 			}
19414 			attrp = NULL;
19415 		}
19416 
19417 		ASSERT(gc == NULL || (gcgrp != NULL &&
19418 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19419 	}
19420 	ASSERT(sacnt == 0 || gc != NULL);
19421 
19422 	if (sacnt != 0 &&
19423 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19424 		kmem_free(re, sizeof (*re));
19425 		rw_exit(&gcgrp->gcgrp_rwlock);
19426 		return;
19427 	}
19428 
19429 	/*
19430 	 * Return all IRE types for route table... let caller pick and choose
19431 	 */
19432 	re->ipRouteDest = ire->ire_addr;
19433 	ipif = ire->ire_ipif;
19434 	re->ipRouteIfIndex.o_length = 0;
19435 	if (ire->ire_type == IRE_CACHE) {
19436 		ill = (ill_t *)ire->ire_stq->q_ptr;
19437 		re->ipRouteIfIndex.o_length =
19438 		    ill->ill_name_length == 0 ? 0 :
19439 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19440 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19441 		    re->ipRouteIfIndex.o_length);
19442 	} else if (ipif != NULL) {
19443 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19444 		    OCTET_LENGTH);
19445 		re->ipRouteIfIndex.o_length =
19446 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19447 	}
19448 	re->ipRouteMetric1 = -1;
19449 	re->ipRouteMetric2 = -1;
19450 	re->ipRouteMetric3 = -1;
19451 	re->ipRouteMetric4 = -1;
19452 
19453 	gw_addr = ire->ire_gateway_addr;
19454 
19455 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19456 		re->ipRouteNextHop = ire->ire_src_addr;
19457 	else
19458 		re->ipRouteNextHop = gw_addr;
19459 	/* indirect(4), direct(3), or invalid(2) */
19460 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19461 		re->ipRouteType = 2;
19462 	else
19463 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19464 	re->ipRouteProto = -1;
19465 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19466 	re->ipRouteMask = ire->ire_mask;
19467 	re->ipRouteMetric5 = -1;
19468 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19469 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19470 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19471 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19472 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19473 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19474 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19475 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19476 	re->ipRouteInfo.re_in_ill.o_length = 0;
19477 
19478 	if (ire->ire_flags & RTF_DYNAMIC) {
19479 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19480 	} else {
19481 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19482 	}
19483 
19484 	if (ire->ire_in_ill != NULL) {
19485 		re->ipRouteInfo.re_in_ill.o_length =
19486 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19487 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19488 		bcopy(ire->ire_in_ill->ill_name,
19489 		    re->ipRouteInfo.re_in_ill.o_bytes,
19490 		    re->ipRouteInfo.re_in_ill.o_length);
19491 	}
19492 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19493 
19494 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19495 	    (char *)re, (int)sizeof (*re))) {
19496 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19497 		    (uint_t)sizeof (*re)));
19498 	}
19499 
19500 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19501 		iaeptr->iae_routeidx = ird->ird_idx;
19502 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19503 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19504 	}
19505 
19506 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19507 	    (char *)iae, sacnt * sizeof (*iae))) {
19508 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19509 		    (unsigned)(sacnt * sizeof (*iae))));
19510 	}
19511 
19512 	/* bump route index for next pass */
19513 	ird->ird_idx++;
19514 
19515 	kmem_free(re, sizeof (*re));
19516 	if (sacnt != 0)
19517 		kmem_free(iae, sacnt * sizeof (*iae));
19518 
19519 	if (gcgrp != NULL)
19520 		rw_exit(&gcgrp->gcgrp_rwlock);
19521 }
19522 
19523 /*
19524  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19525  */
19526 static void
19527 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19528 {
19529 	ill_t				*ill;
19530 	ipif_t				*ipif;
19531 	mib2_ipv6RouteEntry_t		*re;
19532 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19533 	in6_addr_t			gw_addr_v6;
19534 	tsol_ire_gw_secattr_t		*attrp;
19535 	tsol_gc_t			*gc = NULL;
19536 	tsol_gcgrp_t			*gcgrp = NULL;
19537 	uint_t				sacnt = 0;
19538 	int				i;
19539 
19540 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19541 
19542 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19543 		return;
19544 
19545 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19546 		mutex_enter(&attrp->igsa_lock);
19547 		if ((gc = attrp->igsa_gc) != NULL) {
19548 			gcgrp = gc->gc_grp;
19549 			ASSERT(gcgrp != NULL);
19550 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19551 			sacnt = 1;
19552 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19553 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19554 			gc = gcgrp->gcgrp_head;
19555 			sacnt = gcgrp->gcgrp_count;
19556 		}
19557 		mutex_exit(&attrp->igsa_lock);
19558 
19559 		/* do nothing if there's no gc to report */
19560 		if (gc == NULL) {
19561 			ASSERT(sacnt == 0);
19562 			if (gcgrp != NULL) {
19563 				/* we might as well drop the lock now */
19564 				rw_exit(&gcgrp->gcgrp_rwlock);
19565 				gcgrp = NULL;
19566 			}
19567 			attrp = NULL;
19568 		}
19569 
19570 		ASSERT(gc == NULL || (gcgrp != NULL &&
19571 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19572 	}
19573 	ASSERT(sacnt == 0 || gc != NULL);
19574 
19575 	if (sacnt != 0 &&
19576 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19577 		kmem_free(re, sizeof (*re));
19578 		rw_exit(&gcgrp->gcgrp_rwlock);
19579 		return;
19580 	}
19581 
19582 	/*
19583 	 * Return all IRE types for route table... let caller pick and choose
19584 	 */
19585 	re->ipv6RouteDest = ire->ire_addr_v6;
19586 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19587 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19588 	re->ipv6RouteIfIndex.o_length = 0;
19589 	ipif = ire->ire_ipif;
19590 	if (ire->ire_type == IRE_CACHE) {
19591 		ill = (ill_t *)ire->ire_stq->q_ptr;
19592 		re->ipv6RouteIfIndex.o_length =
19593 		    ill->ill_name_length == 0 ? 0 :
19594 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19595 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19596 		    re->ipv6RouteIfIndex.o_length);
19597 	} else if (ipif != NULL) {
19598 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19599 		    OCTET_LENGTH);
19600 		re->ipv6RouteIfIndex.o_length =
19601 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19602 	}
19603 
19604 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19605 
19606 	mutex_enter(&ire->ire_lock);
19607 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19608 	mutex_exit(&ire->ire_lock);
19609 
19610 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19611 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19612 	else
19613 		re->ipv6RouteNextHop = gw_addr_v6;
19614 
19615 	/* remote(4), local(3), or discard(2) */
19616 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19617 		re->ipv6RouteType = 2;
19618 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19619 		re->ipv6RouteType = 3;
19620 	else
19621 		re->ipv6RouteType = 4;
19622 
19623 	re->ipv6RouteProtocol	= -1;
19624 	re->ipv6RoutePolicy	= 0;
19625 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19626 	re->ipv6RouteNextHopRDI	= 0;
19627 	re->ipv6RouteWeight	= 0;
19628 	re->ipv6RouteMetric	= 0;
19629 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19630 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19631 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19632 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19633 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19634 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19635 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19636 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19637 
19638 	if (ire->ire_flags & RTF_DYNAMIC) {
19639 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19640 	} else {
19641 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19642 	}
19643 
19644 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19645 	    (char *)re, (int)sizeof (*re))) {
19646 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19647 		    (uint_t)sizeof (*re)));
19648 	}
19649 
19650 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19651 		iaeptr->iae_routeidx = ird->ird_idx;
19652 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19653 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19654 	}
19655 
19656 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19657 	    (char *)iae, sacnt * sizeof (*iae))) {
19658 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19659 		    (unsigned)(sacnt * sizeof (*iae))));
19660 	}
19661 
19662 	/* bump route index for next pass */
19663 	ird->ird_idx++;
19664 
19665 	kmem_free(re, sizeof (*re));
19666 	if (sacnt != 0)
19667 		kmem_free(iae, sacnt * sizeof (*iae));
19668 
19669 	if (gcgrp != NULL)
19670 		rw_exit(&gcgrp->gcgrp_rwlock);
19671 }
19672 
19673 /*
19674  * ndp_walk routine to create ipv6NetToMediaEntryTable
19675  */
19676 static int
19677 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19678 {
19679 	ill_t				*ill;
19680 	mib2_ipv6NetToMediaEntry_t	ntme;
19681 	dl_unitdata_req_t		*dl;
19682 
19683 	ill = nce->nce_ill;
19684 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19685 		return (0);
19686 
19687 	/*
19688 	 * Neighbor cache entry attached to IRE with on-link
19689 	 * destination.
19690 	 */
19691 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19692 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19693 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19694 	    (nce->nce_res_mp != NULL)) {
19695 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19696 		ntme.ipv6NetToMediaPhysAddress.o_length =
19697 		    dl->dl_dest_addr_length;
19698 	} else {
19699 		ntme.ipv6NetToMediaPhysAddress.o_length =
19700 		    ill->ill_phys_addr_length;
19701 	}
19702 	if (nce->nce_res_mp != NULL) {
19703 		bcopy((char *)nce->nce_res_mp->b_rptr +
19704 		    NCE_LL_ADDR_OFFSET(ill),
19705 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19706 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19707 	} else {
19708 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19709 		    ill->ill_phys_addr_length);
19710 	}
19711 	/*
19712 	 * Note: Returns ND_* states. Should be:
19713 	 * reachable(1), stale(2), delay(3), probe(4),
19714 	 * invalid(5), unknown(6)
19715 	 */
19716 	ntme.ipv6NetToMediaState = nce->nce_state;
19717 	ntme.ipv6NetToMediaLastUpdated = 0;
19718 
19719 	/* other(1), dynamic(2), static(3), local(4) */
19720 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19721 		ntme.ipv6NetToMediaType = 4;
19722 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19723 		ntme.ipv6NetToMediaType = 1;
19724 	} else {
19725 		ntme.ipv6NetToMediaType = 2;
19726 	}
19727 
19728 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19729 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19730 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19731 		    (uint_t)sizeof (ntme)));
19732 	}
19733 	return (0);
19734 }
19735 
19736 /*
19737  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19738  */
19739 /* ARGSUSED */
19740 int
19741 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19742 {
19743 	switch (level) {
19744 	case MIB2_IP:
19745 	case MIB2_ICMP:
19746 		switch (name) {
19747 		default:
19748 			break;
19749 		}
19750 		return (1);
19751 	default:
19752 		return (1);
19753 	}
19754 }
19755 
19756 /*
19757  * When there exists both a 64- and 32-bit counter of a particular type
19758  * (i.e., InReceives), only the 64-bit counters are added.
19759  */
19760 void
19761 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19762 {
19763 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19764 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19765 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19766 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19767 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19768 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19769 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19770 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19771 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19772 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19773 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19774 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19775 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19776 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19777 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19778 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19779 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19780 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19781 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19782 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19783 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19784 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19785 	    o2->ipIfStatsInWrongIPVersion);
19786 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19787 	    o2->ipIfStatsInWrongIPVersion);
19788 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19789 	    o2->ipIfStatsOutSwitchIPVersion);
19790 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19791 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19792 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19793 	    o2->ipIfStatsHCInForwDatagrams);
19794 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19795 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19796 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19797 	    o2->ipIfStatsHCOutForwDatagrams);
19798 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19799 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19800 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19801 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19802 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19803 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19804 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19805 	    o2->ipIfStatsHCOutMcastOctets);
19806 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19807 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19808 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19809 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19810 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19811 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19812 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19813 }
19814 
19815 void
19816 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19817 {
19818 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19819 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19820 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19821 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19822 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19823 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19824 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19825 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19826 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19827 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19828 	    o2->ipv6IfIcmpInRouterSolicits);
19829 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19830 	    o2->ipv6IfIcmpInRouterAdvertisements);
19831 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19832 	    o2->ipv6IfIcmpInNeighborSolicits);
19833 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19834 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19835 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19836 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19837 	    o2->ipv6IfIcmpInGroupMembQueries);
19838 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19839 	    o2->ipv6IfIcmpInGroupMembResponses);
19840 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19841 	    o2->ipv6IfIcmpInGroupMembReductions);
19842 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19843 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19844 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19845 	    o2->ipv6IfIcmpOutDestUnreachs);
19846 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19847 	    o2->ipv6IfIcmpOutAdminProhibs);
19848 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19849 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19850 	    o2->ipv6IfIcmpOutParmProblems);
19851 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19852 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19853 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19854 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19855 	    o2->ipv6IfIcmpOutRouterSolicits);
19856 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19857 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19858 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19859 	    o2->ipv6IfIcmpOutNeighborSolicits);
19860 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19861 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19862 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19863 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19864 	    o2->ipv6IfIcmpOutGroupMembQueries);
19865 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19866 	    o2->ipv6IfIcmpOutGroupMembResponses);
19867 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19868 	    o2->ipv6IfIcmpOutGroupMembReductions);
19869 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19870 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19871 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19872 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19873 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19874 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19875 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19876 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19877 	    o2->ipv6IfIcmpInGroupMembTotal);
19878 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19879 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19880 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19881 	    o2->ipv6IfIcmpInGroupMembBadReports);
19882 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19883 	    o2->ipv6IfIcmpInGroupMembOurReports);
19884 }
19885 
19886 /*
19887  * Called before the options are updated to check if this packet will
19888  * be source routed from here.
19889  * This routine assumes that the options are well formed i.e. that they
19890  * have already been checked.
19891  */
19892 static boolean_t
19893 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19894 {
19895 	ipoptp_t	opts;
19896 	uchar_t		*opt;
19897 	uint8_t		optval;
19898 	uint8_t		optlen;
19899 	ipaddr_t	dst;
19900 	ire_t		*ire;
19901 
19902 	if (IS_SIMPLE_IPH(ipha)) {
19903 		ip2dbg(("not source routed\n"));
19904 		return (B_FALSE);
19905 	}
19906 	dst = ipha->ipha_dst;
19907 	for (optval = ipoptp_first(&opts, ipha);
19908 	    optval != IPOPT_EOL;
19909 	    optval = ipoptp_next(&opts)) {
19910 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19911 		opt = opts.ipoptp_cur;
19912 		optlen = opts.ipoptp_len;
19913 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19914 		    optval, optlen));
19915 		switch (optval) {
19916 			uint32_t off;
19917 		case IPOPT_SSRR:
19918 		case IPOPT_LSRR:
19919 			/*
19920 			 * If dst is one of our addresses and there are some
19921 			 * entries left in the source route return (true).
19922 			 */
19923 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19924 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19925 			if (ire == NULL) {
19926 				ip2dbg(("ip_source_routed: not next"
19927 				    " source route 0x%x\n",
19928 				    ntohl(dst)));
19929 				return (B_FALSE);
19930 			}
19931 			ire_refrele(ire);
19932 			off = opt[IPOPT_OFFSET];
19933 			off--;
19934 			if (optlen < IP_ADDR_LEN ||
19935 			    off > optlen - IP_ADDR_LEN) {
19936 				/* End of source route */
19937 				ip1dbg(("ip_source_routed: end of SR\n"));
19938 				return (B_FALSE);
19939 			}
19940 			return (B_TRUE);
19941 		}
19942 	}
19943 	ip2dbg(("not source routed\n"));
19944 	return (B_FALSE);
19945 }
19946 
19947 /*
19948  * Check if the packet contains any source route.
19949  */
19950 static boolean_t
19951 ip_source_route_included(ipha_t *ipha)
19952 {
19953 	ipoptp_t	opts;
19954 	uint8_t		optval;
19955 
19956 	if (IS_SIMPLE_IPH(ipha))
19957 		return (B_FALSE);
19958 	for (optval = ipoptp_first(&opts, ipha);
19959 	    optval != IPOPT_EOL;
19960 	    optval = ipoptp_next(&opts)) {
19961 		switch (optval) {
19962 		case IPOPT_SSRR:
19963 		case IPOPT_LSRR:
19964 			return (B_TRUE);
19965 		}
19966 	}
19967 	return (B_FALSE);
19968 }
19969 
19970 /*
19971  * Called when the IRE expiration timer fires.
19972  */
19973 void
19974 ip_trash_timer_expire(void *args)
19975 {
19976 	int			flush_flag = 0;
19977 	ire_expire_arg_t	iea;
19978 	ip_stack_t		*ipst = (ip_stack_t *)args;
19979 
19980 	iea.iea_ipst = ipst;	/* No netstack_hold */
19981 
19982 	/*
19983 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19984 	 * This lock makes sure that a new invocation of this function
19985 	 * that occurs due to an almost immediate timer firing will not
19986 	 * progress beyond this point until the current invocation is done
19987 	 */
19988 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19989 	ipst->ips_ip_ire_expire_id = 0;
19990 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19991 
19992 	/* Periodic timer */
19993 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19994 	    ipst->ips_ip_ire_arp_interval) {
19995 		/*
19996 		 * Remove all IRE_CACHE entries since they might
19997 		 * contain arp information.
19998 		 */
19999 		flush_flag |= FLUSH_ARP_TIME;
20000 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20001 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20002 	}
20003 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20004 	    ipst->ips_ip_ire_redir_interval) {
20005 		/* Remove all redirects */
20006 		flush_flag |= FLUSH_REDIRECT_TIME;
20007 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20008 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20009 	}
20010 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20011 	    ipst->ips_ip_ire_pathmtu_interval) {
20012 		/* Increase path mtu */
20013 		flush_flag |= FLUSH_MTU_TIME;
20014 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20015 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20016 	}
20017 
20018 	/*
20019 	 * Optimize for the case when there are no redirects in the
20020 	 * ftable, that is, no need to walk the ftable in that case.
20021 	 */
20022 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20023 		iea.iea_flush_flag = flush_flag;
20024 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20025 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20026 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20027 		    NULL, ALL_ZONES, ipst);
20028 	}
20029 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20030 	    ipst->ips_ip_redirect_cnt > 0) {
20031 		iea.iea_flush_flag = flush_flag;
20032 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20033 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20034 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20035 	}
20036 	if (flush_flag & FLUSH_MTU_TIME) {
20037 		/*
20038 		 * Walk all IPv6 IRE's and update them
20039 		 * Note that ARP and redirect timers are not
20040 		 * needed since NUD handles stale entries.
20041 		 */
20042 		flush_flag = FLUSH_MTU_TIME;
20043 		iea.iea_flush_flag = flush_flag;
20044 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20045 		    ALL_ZONES, ipst);
20046 	}
20047 
20048 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20049 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20050 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20051 
20052 	/*
20053 	 * Hold the lock to serialize timeout calls and prevent
20054 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20055 	 * for the timer to fire and a new invocation of this function
20056 	 * to start before the return value of timeout has been stored
20057 	 * in ip_ire_expire_id by the current invocation.
20058 	 */
20059 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20060 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20061 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20062 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20063 }
20064 
20065 /*
20066  * Called by the memory allocator subsystem directly, when the system
20067  * is running low on memory.
20068  */
20069 /* ARGSUSED */
20070 void
20071 ip_trash_ire_reclaim(void *args)
20072 {
20073 	netstack_handle_t nh;
20074 	netstack_t *ns;
20075 
20076 	netstack_next_init(&nh);
20077 	while ((ns = netstack_next(&nh)) != NULL) {
20078 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20079 		netstack_rele(ns);
20080 	}
20081 	netstack_next_fini(&nh);
20082 }
20083 
20084 static void
20085 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20086 {
20087 	ire_cache_count_t icc;
20088 	ire_cache_reclaim_t icr;
20089 	ncc_cache_count_t ncc;
20090 	nce_cache_reclaim_t ncr;
20091 	uint_t delete_cnt;
20092 	/*
20093 	 * Memory reclaim call back.
20094 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20095 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20096 	 * entries, determine what fraction to free for
20097 	 * each category of IRE_CACHE entries giving absolute priority
20098 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20099 	 * entry will be freed unless all offlink entries are freed).
20100 	 */
20101 	icc.icc_total = 0;
20102 	icc.icc_unused = 0;
20103 	icc.icc_offlink = 0;
20104 	icc.icc_pmtu = 0;
20105 	icc.icc_onlink = 0;
20106 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20107 
20108 	/*
20109 	 * Free NCEs for IPv6 like the onlink ires.
20110 	 */
20111 	ncc.ncc_total = 0;
20112 	ncc.ncc_host = 0;
20113 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20114 
20115 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20116 	    icc.icc_pmtu + icc.icc_onlink);
20117 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20118 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20119 	if (delete_cnt == 0)
20120 		return;
20121 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20122 	/* Always delete all unused offlink entries */
20123 	icr.icr_ipst = ipst;
20124 	icr.icr_unused = 1;
20125 	if (delete_cnt <= icc.icc_unused) {
20126 		/*
20127 		 * Only need to free unused entries.  In other words,
20128 		 * there are enough unused entries to free to meet our
20129 		 * target number of freed ire cache entries.
20130 		 */
20131 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20132 		ncr.ncr_host = 0;
20133 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20134 		/*
20135 		 * Only need to free unused entries, plus a fraction of offlink
20136 		 * entries.  It follows from the first if statement that
20137 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20138 		 */
20139 		delete_cnt -= icc.icc_unused;
20140 		/* Round up # deleted by truncating fraction */
20141 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20142 		icr.icr_pmtu = icr.icr_onlink = 0;
20143 		ncr.ncr_host = 0;
20144 	} else if (delete_cnt <=
20145 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20146 		/*
20147 		 * Free all unused and offlink entries, plus a fraction of
20148 		 * pmtu entries.  It follows from the previous if statement
20149 		 * that icc_pmtu is non-zero, and that
20150 		 * delete_cnt != icc_unused + icc_offlink.
20151 		 */
20152 		icr.icr_offlink = 1;
20153 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20154 		/* Round up # deleted by truncating fraction */
20155 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20156 		icr.icr_onlink = 0;
20157 		ncr.ncr_host = 0;
20158 	} else {
20159 		/*
20160 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20161 		 * of onlink entries.  If we're here, then we know that
20162 		 * icc_onlink is non-zero, and that
20163 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20164 		 */
20165 		icr.icr_offlink = icr.icr_pmtu = 1;
20166 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20167 		    icc.icc_pmtu;
20168 		/* Round up # deleted by truncating fraction */
20169 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20170 		/* Using the same delete fraction as for onlink IREs */
20171 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20172 	}
20173 #ifdef DEBUG
20174 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20175 	    "fractions %d/%d/%d/%d\n",
20176 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20177 	    icc.icc_unused, icc.icc_offlink,
20178 	    icc.icc_pmtu, icc.icc_onlink,
20179 	    icr.icr_unused, icr.icr_offlink,
20180 	    icr.icr_pmtu, icr.icr_onlink));
20181 #endif
20182 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20183 	if (ncr.ncr_host != 0)
20184 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20185 		    (uchar_t *)&ncr, ipst);
20186 #ifdef DEBUG
20187 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20188 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20189 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20190 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20191 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20192 	    icc.icc_pmtu, icc.icc_onlink));
20193 #endif
20194 }
20195 
20196 /*
20197  * ip_unbind is called when a copy of an unbind request is received from the
20198  * upper level protocol.  We remove this conn from any fanout hash list it is
20199  * on, and zero out the bind information.  No reply is expected up above.
20200  */
20201 mblk_t *
20202 ip_unbind(queue_t *q, mblk_t *mp)
20203 {
20204 	conn_t	*connp = Q_TO_CONN(q);
20205 
20206 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20207 
20208 	if (is_system_labeled() && connp->conn_anon_port) {
20209 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20210 		    connp->conn_mlp_type, connp->conn_ulp,
20211 		    ntohs(connp->conn_lport), B_FALSE);
20212 		connp->conn_anon_port = 0;
20213 	}
20214 	connp->conn_mlp_type = mlptSingle;
20215 
20216 	ipcl_hash_remove(connp);
20217 
20218 	ASSERT(mp->b_cont == NULL);
20219 	/*
20220 	 * Convert mp into a T_OK_ACK
20221 	 */
20222 	mp = mi_tpi_ok_ack_alloc(mp);
20223 
20224 	/*
20225 	 * should not happen in practice... T_OK_ACK is smaller than the
20226 	 * original message.
20227 	 */
20228 	if (mp == NULL)
20229 		return (NULL);
20230 
20231 	/*
20232 	 * Don't bzero the ports if its TCP since TCP still needs the
20233 	 * lport to remove it from its own bind hash. TCP will do the
20234 	 * cleanup.
20235 	 */
20236 	if (!IPCL_IS_TCP(connp))
20237 		bzero(&connp->u_port, sizeof (connp->u_port));
20238 
20239 	return (mp);
20240 }
20241 
20242 /*
20243  * Write side put procedure.  Outbound data, IOCTLs, responses from
20244  * resolvers, etc, come down through here.
20245  *
20246  * arg2 is always a queue_t *.
20247  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20248  * the zoneid.
20249  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20250  */
20251 void
20252 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20253 {
20254 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20255 }
20256 
20257 void
20258 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20259     ip_opt_info_t *infop)
20260 {
20261 	conn_t		*connp = NULL;
20262 	queue_t		*q = (queue_t *)arg2;
20263 	ipha_t		*ipha;
20264 #define	rptr	((uchar_t *)ipha)
20265 	ire_t		*ire = NULL;
20266 	ire_t		*sctp_ire = NULL;
20267 	uint32_t	v_hlen_tos_len;
20268 	ipaddr_t	dst;
20269 	mblk_t		*first_mp = NULL;
20270 	boolean_t	mctl_present;
20271 	ipsec_out_t	*io;
20272 	int		match_flags;
20273 	ill_t		*attach_ill = NULL;
20274 					/* Bind to IPIF_NOFAILOVER ill etc. */
20275 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20276 	ipif_t		*dst_ipif;
20277 	boolean_t	multirt_need_resolve = B_FALSE;
20278 	mblk_t		*copy_mp = NULL;
20279 	int		err;
20280 	zoneid_t	zoneid;
20281 	int	adjust;
20282 	uint16_t iplen;
20283 	boolean_t	need_decref = B_FALSE;
20284 	boolean_t	ignore_dontroute = B_FALSE;
20285 	boolean_t	ignore_nexthop = B_FALSE;
20286 	boolean_t	ip_nexthop = B_FALSE;
20287 	ipaddr_t	nexthop_addr;
20288 	ip_stack_t	*ipst;
20289 
20290 #ifdef	_BIG_ENDIAN
20291 #define	V_HLEN	(v_hlen_tos_len >> 24)
20292 #else
20293 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20294 #endif
20295 
20296 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20297 	    "ip_wput_start: q %p", q);
20298 
20299 	/*
20300 	 * ip_wput fast path
20301 	 */
20302 
20303 	/* is packet from ARP ? */
20304 	if (q->q_next != NULL) {
20305 		zoneid = (zoneid_t)(uintptr_t)arg;
20306 		goto qnext;
20307 	}
20308 
20309 	connp = (conn_t *)arg;
20310 	ASSERT(connp != NULL);
20311 	zoneid = connp->conn_zoneid;
20312 	ipst = connp->conn_netstack->netstack_ip;
20313 
20314 	/* is queue flow controlled? */
20315 	if ((q->q_first != NULL || connp->conn_draining) &&
20316 	    (caller == IP_WPUT)) {
20317 		ASSERT(!need_decref);
20318 		(void) putq(q, mp);
20319 		return;
20320 	}
20321 
20322 	/* Multidata transmit? */
20323 	if (DB_TYPE(mp) == M_MULTIDATA) {
20324 		/*
20325 		 * We should never get here, since all Multidata messages
20326 		 * originating from tcp should have been directed over to
20327 		 * tcp_multisend() in the first place.
20328 		 */
20329 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20330 		freemsg(mp);
20331 		return;
20332 	} else if (DB_TYPE(mp) != M_DATA)
20333 		goto notdata;
20334 
20335 	if (mp->b_flag & MSGHASREF) {
20336 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20337 		mp->b_flag &= ~MSGHASREF;
20338 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20339 		need_decref = B_TRUE;
20340 	}
20341 	ipha = (ipha_t *)mp->b_rptr;
20342 
20343 	/* is IP header non-aligned or mblk smaller than basic IP header */
20344 #ifndef SAFETY_BEFORE_SPEED
20345 	if (!OK_32PTR(rptr) ||
20346 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20347 		goto hdrtoosmall;
20348 #endif
20349 
20350 	ASSERT(OK_32PTR(ipha));
20351 
20352 	/*
20353 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20354 	 * wrong version, we'll catch it again in ip_output_v6.
20355 	 *
20356 	 * Note that this is *only* locally-generated output here, and never
20357 	 * forwarded data, and that we need to deal only with transports that
20358 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20359 	 * label.)
20360 	 */
20361 	if (is_system_labeled() &&
20362 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20363 	    !connp->conn_ulp_labeled) {
20364 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20365 		    connp->conn_mac_exempt, ipst);
20366 		ipha = (ipha_t *)mp->b_rptr;
20367 		if (err != 0) {
20368 			first_mp = mp;
20369 			if (err == EINVAL)
20370 				goto icmp_parameter_problem;
20371 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20372 			goto discard_pkt;
20373 		}
20374 		iplen = ntohs(ipha->ipha_length) + adjust;
20375 		ipha->ipha_length = htons(iplen);
20376 	}
20377 
20378 	ASSERT(infop != NULL);
20379 
20380 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20381 		/*
20382 		 * IP_PKTINFO ancillary option is present.
20383 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20384 		 * allows using address of any zone as the source address.
20385 		 */
20386 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20387 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20388 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20389 		if (ire == NULL)
20390 			goto drop_pkt;
20391 		ire_refrele(ire);
20392 		ire = NULL;
20393 	}
20394 
20395 	/*
20396 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20397 	 * ill index passed in IP_PKTINFO.
20398 	 */
20399 	if (infop->ip_opt_ill_index != 0 &&
20400 	    connp->conn_xmit_if_ill == NULL &&
20401 	    connp->conn_nofailover_ill == NULL) {
20402 
20403 		xmit_ill = ill_lookup_on_ifindex(
20404 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20405 		    ipst);
20406 
20407 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20408 			goto drop_pkt;
20409 		/*
20410 		 * check that there is an ipif belonging
20411 		 * to our zone. IPCL_ZONEID is not used because
20412 		 * IP_ALLZONES option is valid only when the ill is
20413 		 * accessible from all zones i.e has a valid ipif in
20414 		 * all zones.
20415 		 */
20416 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20417 			goto drop_pkt;
20418 		}
20419 	}
20420 
20421 	/*
20422 	 * If there is a policy, try to attach an ipsec_out in
20423 	 * the front. At the end, first_mp either points to a
20424 	 * M_DATA message or IPSEC_OUT message linked to a
20425 	 * M_DATA message. We have to do it now as we might
20426 	 * lose the "conn" if we go through ip_newroute.
20427 	 */
20428 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20429 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
20430 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20431 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20432 			if (need_decref)
20433 				CONN_DEC_REF(connp);
20434 			return;
20435 		} else {
20436 			ASSERT(mp->b_datap->db_type == M_CTL);
20437 			first_mp = mp;
20438 			mp = mp->b_cont;
20439 			mctl_present = B_TRUE;
20440 		}
20441 	} else {
20442 		first_mp = mp;
20443 		mctl_present = B_FALSE;
20444 	}
20445 
20446 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20447 
20448 	/* is wrong version or IP options present */
20449 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20450 		goto version_hdrlen_check;
20451 	dst = ipha->ipha_dst;
20452 
20453 	if (connp->conn_nofailover_ill != NULL) {
20454 		attach_ill = conn_get_held_ill(connp,
20455 		    &connp->conn_nofailover_ill, &err);
20456 		if (err == ILL_LOOKUP_FAILED) {
20457 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20458 			if (need_decref)
20459 				CONN_DEC_REF(connp);
20460 			freemsg(first_mp);
20461 			return;
20462 		}
20463 	}
20464 
20465 
20466 	/* is packet multicast? */
20467 	if (CLASSD(dst))
20468 		goto multicast;
20469 
20470 	/*
20471 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20472 	 * takes precedence over conn_dontroute and conn_nexthop_set
20473 	 */
20474 	if (xmit_ill != NULL) {
20475 		goto send_from_ill;
20476 	}
20477 
20478 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20479 	    (connp->conn_nexthop_set)) {
20480 		/*
20481 		 * If the destination is a broadcast or a loopback
20482 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20483 		 * through the standard path. But in the case of local
20484 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20485 		 * the standard path not IP_XMIT_IF.
20486 		 */
20487 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20488 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20489 		    (ire->ire_type != IRE_LOOPBACK))) {
20490 			if ((connp->conn_dontroute ||
20491 			    connp->conn_nexthop_set) && (ire != NULL) &&
20492 			    (ire->ire_type == IRE_LOCAL))
20493 				goto standard_path;
20494 
20495 			if (ire != NULL) {
20496 				ire_refrele(ire);
20497 				/* No more access to ire */
20498 				ire = NULL;
20499 			}
20500 			/*
20501 			 * bypass routing checks and go directly to
20502 			 * interface.
20503 			 */
20504 			if (connp->conn_dontroute) {
20505 				goto dontroute;
20506 			} else if (connp->conn_nexthop_set) {
20507 				ip_nexthop = B_TRUE;
20508 				nexthop_addr = connp->conn_nexthop_v4;
20509 				goto send_from_ill;
20510 			}
20511 
20512 			/*
20513 			 * If IP_XMIT_IF socket option is set,
20514 			 * then we allow unicast and multicast
20515 			 * packets to go through the ill. It is
20516 			 * quite possible that the destination
20517 			 * is not in the ire cache table and we
20518 			 * do not want to go to ip_newroute()
20519 			 * instead we call ip_newroute_ipif.
20520 			 */
20521 			xmit_ill = conn_get_held_ill(connp,
20522 			    &connp->conn_xmit_if_ill, &err);
20523 			if (err == ILL_LOOKUP_FAILED) {
20524 				BUMP_MIB(&ipst->ips_ip_mib,
20525 				    ipIfStatsOutDiscards);
20526 				if (attach_ill != NULL)
20527 					ill_refrele(attach_ill);
20528 				if (need_decref)
20529 					CONN_DEC_REF(connp);
20530 				freemsg(first_mp);
20531 				return;
20532 			}
20533 			goto send_from_ill;
20534 		}
20535 standard_path:
20536 		/* Must be a broadcast, a loopback or a local ire */
20537 		if (ire != NULL) {
20538 			ire_refrele(ire);
20539 			/* No more access to ire */
20540 			ire = NULL;
20541 		}
20542 	}
20543 
20544 	if (attach_ill != NULL)
20545 		goto send_from_ill;
20546 
20547 	/*
20548 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20549 	 * this for the tcp global queue and listen end point
20550 	 * as it does not really have a real destination to
20551 	 * talk to.  This is also true for SCTP.
20552 	 */
20553 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20554 	    !connp->conn_fully_bound) {
20555 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20556 		if (ire == NULL)
20557 			goto noirefound;
20558 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20559 		    "ip_wput_end: q %p (%S)", q, "end");
20560 
20561 		/*
20562 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20563 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20564 		 */
20565 		if (ire->ire_flags & RTF_MULTIRT) {
20566 
20567 			/*
20568 			 * Force the TTL of multirouted packets if required.
20569 			 * The TTL of such packets is bounded by the
20570 			 * ip_multirt_ttl ndd variable.
20571 			 */
20572 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20573 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20574 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20575 				    "(was %d), dst 0x%08x\n",
20576 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20577 				    ntohl(ire->ire_addr)));
20578 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20579 			}
20580 			/*
20581 			 * We look at this point if there are pending
20582 			 * unresolved routes. ire_multirt_resolvable()
20583 			 * checks in O(n) that all IRE_OFFSUBNET ire
20584 			 * entries for the packet's destination and
20585 			 * flagged RTF_MULTIRT are currently resolved.
20586 			 * If some remain unresolved, we make a copy
20587 			 * of the current message. It will be used
20588 			 * to initiate additional route resolutions.
20589 			 */
20590 			multirt_need_resolve =
20591 			    ire_multirt_need_resolve(ire->ire_addr,
20592 			    MBLK_GETLABEL(first_mp), ipst);
20593 			ip2dbg(("ip_wput[TCP]: ire %p, "
20594 			    "multirt_need_resolve %d, first_mp %p\n",
20595 			    (void *)ire, multirt_need_resolve,
20596 			    (void *)first_mp));
20597 			if (multirt_need_resolve) {
20598 				copy_mp = copymsg(first_mp);
20599 				if (copy_mp != NULL) {
20600 					MULTIRT_DEBUG_TAG(copy_mp);
20601 				}
20602 			}
20603 		}
20604 
20605 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20606 
20607 		/*
20608 		 * Try to resolve another multiroute if
20609 		 * ire_multirt_need_resolve() deemed it necessary.
20610 		 */
20611 		if (copy_mp != NULL) {
20612 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20613 		}
20614 		if (need_decref)
20615 			CONN_DEC_REF(connp);
20616 		return;
20617 	}
20618 
20619 	/*
20620 	 * Access to conn_ire_cache. (protected by conn_lock)
20621 	 *
20622 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20623 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20624 	 * send a packet or two with the IRE_CACHE that is going away.
20625 	 * Access to the ire requires an ire refhold on the ire prior to
20626 	 * its use since an interface unplumb thread may delete the cached
20627 	 * ire and release the refhold at any time.
20628 	 *
20629 	 * Caching an ire in the conn_ire_cache
20630 	 *
20631 	 * o Caching an ire pointer in the conn requires a strict check for
20632 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20633 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20634 	 * in the conn is done after making sure under the bucket lock that the
20635 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20636 	 * caching an ire after the unplumb thread has cleaned up the conn.
20637 	 * If the conn does not send a packet subsequently the unplumb thread
20638 	 * will be hanging waiting for the ire count to drop to zero.
20639 	 *
20640 	 * o We also need to atomically test for a null conn_ire_cache and
20641 	 * set the conn_ire_cache under the the protection of the conn_lock
20642 	 * to avoid races among concurrent threads trying to simultaneously
20643 	 * cache an ire in the conn_ire_cache.
20644 	 */
20645 	mutex_enter(&connp->conn_lock);
20646 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20647 
20648 	if (ire != NULL && ire->ire_addr == dst &&
20649 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20650 
20651 		IRE_REFHOLD(ire);
20652 		mutex_exit(&connp->conn_lock);
20653 
20654 	} else {
20655 		boolean_t cached = B_FALSE;
20656 		connp->conn_ire_cache = NULL;
20657 		mutex_exit(&connp->conn_lock);
20658 		/* Release the old ire */
20659 		if (ire != NULL && sctp_ire == NULL)
20660 			IRE_REFRELE_NOTR(ire);
20661 
20662 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20663 		if (ire == NULL)
20664 			goto noirefound;
20665 		IRE_REFHOLD_NOTR(ire);
20666 
20667 		mutex_enter(&connp->conn_lock);
20668 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20669 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20670 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20671 				connp->conn_ire_cache = ire;
20672 				cached = B_TRUE;
20673 			}
20674 			rw_exit(&ire->ire_bucket->irb_lock);
20675 		}
20676 		mutex_exit(&connp->conn_lock);
20677 
20678 		/*
20679 		 * We can continue to use the ire but since it was
20680 		 * not cached, we should drop the extra reference.
20681 		 */
20682 		if (!cached)
20683 			IRE_REFRELE_NOTR(ire);
20684 	}
20685 
20686 
20687 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20688 	    "ip_wput_end: q %p (%S)", q, "end");
20689 
20690 	/*
20691 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20692 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20693 	 */
20694 	if (ire->ire_flags & RTF_MULTIRT) {
20695 
20696 		/*
20697 		 * Force the TTL of multirouted packets if required.
20698 		 * The TTL of such packets is bounded by the
20699 		 * ip_multirt_ttl ndd variable.
20700 		 */
20701 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20702 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20703 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20704 			    "(was %d), dst 0x%08x\n",
20705 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20706 			    ntohl(ire->ire_addr)));
20707 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20708 		}
20709 
20710 		/*
20711 		 * At this point, we check to see if there are any pending
20712 		 * unresolved routes. ire_multirt_resolvable()
20713 		 * checks in O(n) that all IRE_OFFSUBNET ire
20714 		 * entries for the packet's destination and
20715 		 * flagged RTF_MULTIRT are currently resolved.
20716 		 * If some remain unresolved, we make a copy
20717 		 * of the current message. It will be used
20718 		 * to initiate additional route resolutions.
20719 		 */
20720 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20721 		    MBLK_GETLABEL(first_mp), ipst);
20722 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20723 		    "multirt_need_resolve %d, first_mp %p\n",
20724 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20725 		if (multirt_need_resolve) {
20726 			copy_mp = copymsg(first_mp);
20727 			if (copy_mp != NULL) {
20728 				MULTIRT_DEBUG_TAG(copy_mp);
20729 			}
20730 		}
20731 	}
20732 
20733 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20734 
20735 	/*
20736 	 * Try to resolve another multiroute if
20737 	 * ire_multirt_resolvable() deemed it necessary
20738 	 */
20739 	if (copy_mp != NULL) {
20740 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20741 	}
20742 	if (need_decref)
20743 		CONN_DEC_REF(connp);
20744 	return;
20745 
20746 qnext:
20747 	/*
20748 	 * Upper Level Protocols pass down complete IP datagrams
20749 	 * as M_DATA messages.	Everything else is a sideshow.
20750 	 *
20751 	 * 1) We could be re-entering ip_wput because of ip_neworute
20752 	 *    in which case we could have a IPSEC_OUT message. We
20753 	 *    need to pass through ip_wput like other datagrams and
20754 	 *    hence cannot branch to ip_wput_nondata.
20755 	 *
20756 	 * 2) ARP, AH, ESP, and other clients who are on the module
20757 	 *    instance of IP stream, give us something to deal with.
20758 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20759 	 *
20760 	 * 3) ICMP replies also could come here.
20761 	 */
20762 	ipst = ILLQ_TO_IPST(q);
20763 
20764 	if (DB_TYPE(mp) != M_DATA) {
20765 	    notdata:
20766 		if (DB_TYPE(mp) == M_CTL) {
20767 			/*
20768 			 * M_CTL messages are used by ARP, AH and ESP to
20769 			 * communicate with IP. We deal with IPSEC_IN and
20770 			 * IPSEC_OUT here. ip_wput_nondata handles other
20771 			 * cases.
20772 			 */
20773 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20774 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20775 				first_mp = mp->b_cont;
20776 				first_mp->b_flag &= ~MSGHASREF;
20777 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20778 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20779 				CONN_DEC_REF(connp);
20780 				connp = NULL;
20781 			}
20782 			if (ii->ipsec_info_type == IPSEC_IN) {
20783 				/*
20784 				 * Either this message goes back to
20785 				 * IPSEC for further processing or to
20786 				 * ULP after policy checks.
20787 				 */
20788 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20789 				return;
20790 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20791 				io = (ipsec_out_t *)ii;
20792 				if (io->ipsec_out_proc_begin) {
20793 					/*
20794 					 * IPSEC processing has already started.
20795 					 * Complete it.
20796 					 * IPQoS notes: We don't care what is
20797 					 * in ipsec_out_ill_index since this
20798 					 * won't be processed for IPQoS policies
20799 					 * in ipsec_out_process.
20800 					 */
20801 					ipsec_out_process(q, mp, NULL,
20802 					    io->ipsec_out_ill_index);
20803 					return;
20804 				} else {
20805 					connp = (q->q_next != NULL) ?
20806 					    NULL : Q_TO_CONN(q);
20807 					first_mp = mp;
20808 					mp = mp->b_cont;
20809 					mctl_present = B_TRUE;
20810 				}
20811 				zoneid = io->ipsec_out_zoneid;
20812 				ASSERT(zoneid != ALL_ZONES);
20813 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20814 				/*
20815 				 * It's an IPsec control message requesting
20816 				 * an SADB update to be sent to the IPsec
20817 				 * hardware acceleration capable ills.
20818 				 */
20819 				ipsec_ctl_t *ipsec_ctl =
20820 				    (ipsec_ctl_t *)mp->b_rptr;
20821 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20822 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20823 				mblk_t *cmp = mp->b_cont;
20824 
20825 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20826 				ASSERT(cmp != NULL);
20827 
20828 				freeb(mp);
20829 				ill_ipsec_capab_send_all(satype, cmp, sa,
20830 				    ipst->ips_netstack);
20831 				return;
20832 			} else {
20833 				/*
20834 				 * This must be ARP or special TSOL signaling.
20835 				 */
20836 				ip_wput_nondata(NULL, q, mp, NULL);
20837 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20838 				    "ip_wput_end: q %p (%S)", q, "nondata");
20839 				return;
20840 			}
20841 		} else {
20842 			/*
20843 			 * This must be non-(ARP/AH/ESP) messages.
20844 			 */
20845 			ASSERT(!need_decref);
20846 			ip_wput_nondata(NULL, q, mp, NULL);
20847 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20848 			    "ip_wput_end: q %p (%S)", q, "nondata");
20849 			return;
20850 		}
20851 	} else {
20852 		first_mp = mp;
20853 		mctl_present = B_FALSE;
20854 	}
20855 
20856 	ASSERT(first_mp != NULL);
20857 	/*
20858 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20859 	 * to make sure that this packet goes out on the same interface it
20860 	 * came in. We handle that here.
20861 	 */
20862 	if (mctl_present) {
20863 		uint_t ifindex;
20864 
20865 		io = (ipsec_out_t *)first_mp->b_rptr;
20866 		if (io->ipsec_out_attach_if ||
20867 		    io->ipsec_out_xmit_if ||
20868 		    io->ipsec_out_ip_nexthop) {
20869 			ill_t	*ill;
20870 
20871 			/*
20872 			 * We may have lost the conn context if we are
20873 			 * coming here from ip_newroute(). Copy the
20874 			 * nexthop information.
20875 			 */
20876 			if (io->ipsec_out_ip_nexthop) {
20877 				ip_nexthop = B_TRUE;
20878 				nexthop_addr = io->ipsec_out_nexthop_addr;
20879 
20880 				ipha = (ipha_t *)mp->b_rptr;
20881 				dst = ipha->ipha_dst;
20882 				goto send_from_ill;
20883 			} else {
20884 				ASSERT(io->ipsec_out_ill_index != 0);
20885 				ifindex = io->ipsec_out_ill_index;
20886 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20887 				    NULL, NULL, NULL, NULL, ipst);
20888 				/*
20889 				 * ipsec_out_xmit_if bit is used to tell
20890 				 * ip_wput to use the ill to send outgoing data
20891 				 * as we have no conn when data comes from ICMP
20892 				 * error msg routines. Currently this feature is
20893 				 * only used by ip_mrtun_forward routine.
20894 				 */
20895 				if (io->ipsec_out_xmit_if) {
20896 					xmit_ill = ill;
20897 					if (xmit_ill == NULL) {
20898 						ip1dbg(("ip_output:bad ifindex "
20899 						    "for xmit_ill %d\n",
20900 						    ifindex));
20901 						freemsg(first_mp);
20902 						BUMP_MIB(&ipst->ips_ip_mib,
20903 						    ipIfStatsOutDiscards);
20904 						ASSERT(!need_decref);
20905 						return;
20906 					}
20907 					/* Free up the ipsec_out_t mblk */
20908 					ASSERT(first_mp->b_cont == mp);
20909 					first_mp->b_cont = NULL;
20910 					freeb(first_mp);
20911 					/* Just send the IP header+ICMP+data */
20912 					first_mp = mp;
20913 					ipha = (ipha_t *)mp->b_rptr;
20914 					dst = ipha->ipha_dst;
20915 					goto send_from_ill;
20916 				} else {
20917 					attach_ill = ill;
20918 				}
20919 
20920 				if (attach_ill == NULL) {
20921 					ASSERT(xmit_ill == NULL);
20922 					ip1dbg(("ip_output: bad ifindex for "
20923 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20924 					    ifindex));
20925 					freemsg(first_mp);
20926 					BUMP_MIB(&ipst->ips_ip_mib,
20927 					    ipIfStatsOutDiscards);
20928 					ASSERT(!need_decref);
20929 					return;
20930 				}
20931 			}
20932 		}
20933 	}
20934 
20935 	ASSERT(xmit_ill == NULL);
20936 
20937 	/* We have a complete IP datagram heading outbound. */
20938 	ipha = (ipha_t *)mp->b_rptr;
20939 
20940 #ifndef SPEED_BEFORE_SAFETY
20941 	/*
20942 	 * Make sure we have a full-word aligned message and that at least
20943 	 * a simple IP header is accessible in the first message.  If not,
20944 	 * try a pullup.
20945 	 */
20946 	if (!OK_32PTR(rptr) ||
20947 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20948 	    hdrtoosmall:
20949 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20950 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20951 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20952 			if (first_mp == NULL)
20953 				first_mp = mp;
20954 			goto discard_pkt;
20955 		}
20956 
20957 		/* This function assumes that mp points to an IPv4 packet. */
20958 		if (is_system_labeled() && q->q_next == NULL &&
20959 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20960 		    !connp->conn_ulp_labeled) {
20961 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20962 			    &adjust, connp->conn_mac_exempt, ipst);
20963 			ipha = (ipha_t *)mp->b_rptr;
20964 			if (first_mp != NULL)
20965 				first_mp->b_cont = mp;
20966 			if (err != 0) {
20967 				if (first_mp == NULL)
20968 					first_mp = mp;
20969 				if (err == EINVAL)
20970 					goto icmp_parameter_problem;
20971 				ip2dbg(("ip_wput: label check failed (%d)\n",
20972 				    err));
20973 				goto discard_pkt;
20974 			}
20975 			iplen = ntohs(ipha->ipha_length) + adjust;
20976 			ipha->ipha_length = htons(iplen);
20977 		}
20978 
20979 		ipha = (ipha_t *)mp->b_rptr;
20980 		if (first_mp == NULL) {
20981 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20982 			/*
20983 			 * If we got here because of "goto hdrtoosmall"
20984 			 * We need to attach a IPSEC_OUT.
20985 			 */
20986 			if (connp->conn_out_enforce_policy) {
20987 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20988 				    NULL, ipha->ipha_protocol,
20989 				    ipst->ips_netstack)) == NULL)) {
20990 					BUMP_MIB(&ipst->ips_ip_mib,
20991 					    ipIfStatsOutDiscards);
20992 					if (need_decref)
20993 						CONN_DEC_REF(connp);
20994 					return;
20995 				} else {
20996 					ASSERT(mp->b_datap->db_type == M_CTL);
20997 					first_mp = mp;
20998 					mp = mp->b_cont;
20999 					mctl_present = B_TRUE;
21000 				}
21001 			} else {
21002 				first_mp = mp;
21003 				mctl_present = B_FALSE;
21004 			}
21005 		}
21006 	}
21007 #endif
21008 
21009 	/* Most of the code below is written for speed, not readability */
21010 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21011 
21012 	/*
21013 	 * If ip_newroute() fails, we're going to need a full
21014 	 * header for the icmp wraparound.
21015 	 */
21016 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21017 		uint_t	v_hlen;
21018 	    version_hdrlen_check:
21019 		ASSERT(first_mp != NULL);
21020 		v_hlen = V_HLEN;
21021 		/*
21022 		 * siphon off IPv6 packets coming down from transport
21023 		 * layer modules here.
21024 		 * Note: high-order bit carries NUD reachability confirmation
21025 		 */
21026 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21027 			/*
21028 			 * XXX implement a IPv4 and IPv6 packet counter per
21029 			 * conn and switch when ratio exceeds e.g. 10:1
21030 			 */
21031 #ifdef notyet
21032 			if (q->q_next == NULL) /* Avoid ill queue */
21033 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
21034 #endif
21035 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21036 			ASSERT(xmit_ill == NULL);
21037 			if (attach_ill != NULL)
21038 				ill_refrele(attach_ill);
21039 			if (need_decref)
21040 				mp->b_flag |= MSGHASREF;
21041 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21042 			return;
21043 		}
21044 
21045 		if ((v_hlen >> 4) != IP_VERSION) {
21046 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21047 			    "ip_wput_end: q %p (%S)", q, "badvers");
21048 			goto discard_pkt;
21049 		}
21050 		/*
21051 		 * Is the header length at least 20 bytes?
21052 		 *
21053 		 * Are there enough bytes accessible in the header?  If
21054 		 * not, try a pullup.
21055 		 */
21056 		v_hlen &= 0xF;
21057 		v_hlen <<= 2;
21058 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21059 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21060 			    "ip_wput_end: q %p (%S)", q, "badlen");
21061 			goto discard_pkt;
21062 		}
21063 		if (v_hlen > (mp->b_wptr - rptr)) {
21064 			if (!pullupmsg(mp, v_hlen)) {
21065 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21066 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21067 				goto discard_pkt;
21068 			}
21069 			ipha = (ipha_t *)mp->b_rptr;
21070 		}
21071 		/*
21072 		 * Move first entry from any source route into ipha_dst and
21073 		 * verify the options
21074 		 */
21075 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21076 			zoneid, ipst)) {
21077 			ASSERT(xmit_ill == NULL);
21078 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21079 			if (attach_ill != NULL)
21080 				ill_refrele(attach_ill);
21081 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21082 			    "ip_wput_end: q %p (%S)", q, "badopts");
21083 			if (need_decref)
21084 				CONN_DEC_REF(connp);
21085 			return;
21086 		}
21087 	}
21088 	dst = ipha->ipha_dst;
21089 
21090 	/*
21091 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21092 	 * we have to run the packet through ip_newroute which will take
21093 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21094 	 * a resolver, or assigning a default gateway, etc.
21095 	 */
21096 	if (CLASSD(dst)) {
21097 		ipif_t	*ipif;
21098 		uint32_t setsrc = 0;
21099 
21100 	    multicast:
21101 		ASSERT(first_mp != NULL);
21102 		ip2dbg(("ip_wput: CLASSD\n"));
21103 		if (connp == NULL) {
21104 			/*
21105 			 * Use the first good ipif on the ill.
21106 			 * XXX Should this ever happen? (Appears
21107 			 * to show up with just ppp and no ethernet due
21108 			 * to in.rdisc.)
21109 			 * However, ire_send should be able to
21110 			 * call ip_wput_ire directly.
21111 			 *
21112 			 * XXX Also, this can happen for ICMP and other packets
21113 			 * with multicast source addresses.  Perhaps we should
21114 			 * fix things so that we drop the packet in question,
21115 			 * but for now, just run with it.
21116 			 */
21117 			ill_t *ill = (ill_t *)q->q_ptr;
21118 
21119 			/*
21120 			 * Don't honor attach_if for this case. If ill
21121 			 * is part of the group, ipif could belong to
21122 			 * any ill and we cannot maintain attach_ill
21123 			 * and ipif_ill same anymore and the assert
21124 			 * below would fail.
21125 			 */
21126 			if (mctl_present && io->ipsec_out_attach_if) {
21127 				io->ipsec_out_ill_index = 0;
21128 				io->ipsec_out_attach_if = B_FALSE;
21129 				ASSERT(attach_ill != NULL);
21130 				ill_refrele(attach_ill);
21131 				attach_ill = NULL;
21132 			}
21133 
21134 			ASSERT(attach_ill == NULL);
21135 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21136 			if (ipif == NULL) {
21137 				if (need_decref)
21138 					CONN_DEC_REF(connp);
21139 				freemsg(first_mp);
21140 				return;
21141 			}
21142 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21143 			    ntohl(dst), ill->ill_name));
21144 		} else {
21145 			/*
21146 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21147 			 * and IP_MULTICAST_IF.
21148 			 * Block comment above this function explains the
21149 			 * locking mechanism used here
21150 			 */
21151 			if (xmit_ill == NULL) {
21152 				xmit_ill = conn_get_held_ill(connp,
21153 				    &connp->conn_xmit_if_ill, &err);
21154 				if (err == ILL_LOOKUP_FAILED) {
21155 					ip1dbg(("ip_wput: No ill for "
21156 					    "IP_XMIT_IF\n"));
21157 					BUMP_MIB(&ipst->ips_ip_mib,
21158 					    ipIfStatsOutNoRoutes);
21159 					goto drop_pkt;
21160 				}
21161 			}
21162 
21163 			if (xmit_ill == NULL) {
21164 				ipif = conn_get_held_ipif(connp,
21165 				    &connp->conn_multicast_ipif, &err);
21166 				if (err == IPIF_LOOKUP_FAILED) {
21167 					ip1dbg(("ip_wput: No ipif for "
21168 					    "multicast\n"));
21169 					BUMP_MIB(&ipst->ips_ip_mib,
21170 					    ipIfStatsOutNoRoutes);
21171 					goto drop_pkt;
21172 				}
21173 			}
21174 			if (xmit_ill != NULL) {
21175 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21176 				if (ipif == NULL) {
21177 					ip1dbg(("ip_wput: No ipif for "
21178 					    "IP_XMIT_IF\n"));
21179 					BUMP_MIB(&ipst->ips_ip_mib,
21180 					    ipIfStatsOutNoRoutes);
21181 					goto drop_pkt;
21182 				}
21183 			} else if (ipif == NULL || ipif->ipif_isv6) {
21184 				/*
21185 				 * We must do this ipif determination here
21186 				 * else we could pass through ip_newroute
21187 				 * and come back here without the conn context.
21188 				 *
21189 				 * Note: we do late binding i.e. we bind to
21190 				 * the interface when the first packet is sent.
21191 				 * For performance reasons we do not rebind on
21192 				 * each packet but keep the binding until the
21193 				 * next IP_MULTICAST_IF option.
21194 				 *
21195 				 * conn_multicast_{ipif,ill} are shared between
21196 				 * IPv4 and IPv6 and AF_INET6 sockets can
21197 				 * send both IPv4 and IPv6 packets. Hence
21198 				 * we have to check that "isv6" matches above.
21199 				 */
21200 				if (ipif != NULL)
21201 					ipif_refrele(ipif);
21202 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21203 				if (ipif == NULL) {
21204 					ip1dbg(("ip_wput: No ipif for "
21205 					    "multicast\n"));
21206 					BUMP_MIB(&ipst->ips_ip_mib,
21207 					    ipIfStatsOutNoRoutes);
21208 					goto drop_pkt;
21209 				}
21210 				err = conn_set_held_ipif(connp,
21211 				    &connp->conn_multicast_ipif, ipif);
21212 				if (err == IPIF_LOOKUP_FAILED) {
21213 					ipif_refrele(ipif);
21214 					ip1dbg(("ip_wput: No ipif for "
21215 					    "multicast\n"));
21216 					BUMP_MIB(&ipst->ips_ip_mib,
21217 					    ipIfStatsOutNoRoutes);
21218 					goto drop_pkt;
21219 				}
21220 			}
21221 		}
21222 		ASSERT(!ipif->ipif_isv6);
21223 		/*
21224 		 * As we may lose the conn by the time we reach ip_wput_ire,
21225 		 * we copy conn_multicast_loop and conn_dontroute on to an
21226 		 * ipsec_out. In case if this datagram goes out secure,
21227 		 * we need the ill_index also. Copy that also into the
21228 		 * ipsec_out.
21229 		 */
21230 		if (mctl_present) {
21231 			io = (ipsec_out_t *)first_mp->b_rptr;
21232 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21233 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21234 		} else {
21235 			ASSERT(mp == first_mp);
21236 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21237 			    BPRI_HI)) == NULL) {
21238 				ipif_refrele(ipif);
21239 				first_mp = mp;
21240 				goto discard_pkt;
21241 			}
21242 			first_mp->b_datap->db_type = M_CTL;
21243 			first_mp->b_wptr += sizeof (ipsec_info_t);
21244 			/* ipsec_out_secure is B_FALSE now */
21245 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21246 			io = (ipsec_out_t *)first_mp->b_rptr;
21247 			io->ipsec_out_type = IPSEC_OUT;
21248 			io->ipsec_out_len = sizeof (ipsec_out_t);
21249 			io->ipsec_out_use_global_policy = B_TRUE;
21250 			io->ipsec_out_ns = ipst->ips_netstack;
21251 			first_mp->b_cont = mp;
21252 			mctl_present = B_TRUE;
21253 		}
21254 		if (attach_ill != NULL) {
21255 			ASSERT(attach_ill == ipif->ipif_ill);
21256 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21257 
21258 			/*
21259 			 * Check if we need an ire that will not be
21260 			 * looked up by anybody else i.e. HIDDEN.
21261 			 */
21262 			if (ill_is_probeonly(attach_ill)) {
21263 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21264 			}
21265 			io->ipsec_out_ill_index =
21266 			    attach_ill->ill_phyint->phyint_ifindex;
21267 			io->ipsec_out_attach_if = B_TRUE;
21268 		} else {
21269 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21270 			io->ipsec_out_ill_index =
21271 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21272 		}
21273 		if (connp != NULL) {
21274 			io->ipsec_out_multicast_loop =
21275 			    connp->conn_multicast_loop;
21276 			io->ipsec_out_dontroute = connp->conn_dontroute;
21277 			io->ipsec_out_zoneid = connp->conn_zoneid;
21278 		}
21279 		/*
21280 		 * If the application uses IP_MULTICAST_IF with
21281 		 * different logical addresses of the same ILL, we
21282 		 * need to make sure that the soruce address of
21283 		 * the packet matches the logical IP address used
21284 		 * in the option. We do it by initializing ipha_src
21285 		 * here. This should keep IPSEC also happy as
21286 		 * when we return from IPSEC processing, we don't
21287 		 * have to worry about getting the right address on
21288 		 * the packet. Thus it is sufficient to look for
21289 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21290 		 * MATCH_IRE_IPIF.
21291 		 *
21292 		 * NOTE : We need to do it for non-secure case also as
21293 		 * this might go out secure if there is a global policy
21294 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21295 		 * address, the source should be initialized already and
21296 		 * hence we won't be initializing here.
21297 		 *
21298 		 * As we do not have the ire yet, it is possible that
21299 		 * we set the source address here and then later discover
21300 		 * that the ire implies the source address to be assigned
21301 		 * through the RTF_SETSRC flag.
21302 		 * In that case, the setsrc variable will remind us
21303 		 * that overwritting the source address by the one
21304 		 * of the RTF_SETSRC-flagged ire is allowed.
21305 		 */
21306 		if (ipha->ipha_src == INADDR_ANY &&
21307 		    (connp == NULL || !connp->conn_unspec_src)) {
21308 			ipha->ipha_src = ipif->ipif_src_addr;
21309 			setsrc = RTF_SETSRC;
21310 		}
21311 		/*
21312 		 * Find an IRE which matches the destination and the outgoing
21313 		 * queue (i.e. the outgoing interface.)
21314 		 * For loopback use a unicast IP address for
21315 		 * the ire lookup.
21316 		 */
21317 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
21318 		    PHYI_LOOPBACK) {
21319 			dst = ipif->ipif_lcl_addr;
21320 		}
21321 		/*
21322 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21323 		 * We don't need to lookup ire in ctable as the packet
21324 		 * needs to be sent to the destination through the specified
21325 		 * ill irrespective of ires in the cache table.
21326 		 */
21327 		ire = NULL;
21328 		if (xmit_ill == NULL) {
21329 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21330 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21331 		}
21332 
21333 		/*
21334 		 * refrele attach_ill as its not needed anymore.
21335 		 */
21336 		if (attach_ill != NULL) {
21337 			ill_refrele(attach_ill);
21338 			attach_ill = NULL;
21339 		}
21340 
21341 		if (ire == NULL) {
21342 			/*
21343 			 * Multicast loopback and multicast forwarding is
21344 			 * done in ip_wput_ire.
21345 			 *
21346 			 * Mark this packet to make it be delivered to
21347 			 * ip_wput_ire after the new ire has been
21348 			 * created.
21349 			 *
21350 			 * The call to ip_newroute_ipif takes into account
21351 			 * the setsrc reminder. In any case, we take care
21352 			 * of the RTF_MULTIRT flag.
21353 			 */
21354 			mp->b_prev = mp->b_next = NULL;
21355 			if (xmit_ill == NULL ||
21356 			    xmit_ill->ill_ipif_up_count > 0) {
21357 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21358 				    setsrc | RTF_MULTIRT, zoneid, infop);
21359 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21360 				    "ip_wput_end: q %p (%S)", q, "noire");
21361 			} else {
21362 				freemsg(first_mp);
21363 			}
21364 			ipif_refrele(ipif);
21365 			if (xmit_ill != NULL)
21366 				ill_refrele(xmit_ill);
21367 			if (need_decref)
21368 				CONN_DEC_REF(connp);
21369 			return;
21370 		}
21371 
21372 		ipif_refrele(ipif);
21373 		ipif = NULL;
21374 		ASSERT(xmit_ill == NULL);
21375 
21376 		/*
21377 		 * Honor the RTF_SETSRC flag for multicast packets,
21378 		 * if allowed by the setsrc reminder.
21379 		 */
21380 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21381 			ipha->ipha_src = ire->ire_src_addr;
21382 		}
21383 
21384 		/*
21385 		 * Unconditionally force the TTL to 1 for
21386 		 * multirouted multicast packets:
21387 		 * multirouted multicast should not cross
21388 		 * multicast routers.
21389 		 */
21390 		if (ire->ire_flags & RTF_MULTIRT) {
21391 			if (ipha->ipha_ttl > 1) {
21392 				ip2dbg(("ip_wput: forcing multicast "
21393 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21394 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21395 				ipha->ipha_ttl = 1;
21396 			}
21397 		}
21398 	} else {
21399 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21400 		if ((ire != NULL) && (ire->ire_type &
21401 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21402 			ignore_dontroute = B_TRUE;
21403 			ignore_nexthop = B_TRUE;
21404 		}
21405 		if (ire != NULL) {
21406 			ire_refrele(ire);
21407 			ire = NULL;
21408 		}
21409 		/*
21410 		 * Guard against coming in from arp in which case conn is NULL.
21411 		 * Also guard against non M_DATA with dontroute set but
21412 		 * destined to local, loopback or broadcast addresses.
21413 		 */
21414 		if (connp != NULL && connp->conn_dontroute &&
21415 		    !ignore_dontroute) {
21416 dontroute:
21417 			/*
21418 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21419 			 * routing protocols from seeing false direct
21420 			 * connectivity.
21421 			 */
21422 			ipha->ipha_ttl = 1;
21423 			/*
21424 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21425 			 * along with SO_DONTROUTE, higher precedence is
21426 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21427 			 */
21428 			if (connp->conn_xmit_if_ill == NULL) {
21429 				/* If suitable ipif not found, drop packet */
21430 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21431 				    ipst);
21432 				if (dst_ipif == NULL) {
21433 					ip1dbg(("ip_wput: no route for "
21434 					    "dst using SO_DONTROUTE\n"));
21435 					BUMP_MIB(&ipst->ips_ip_mib,
21436 					    ipIfStatsOutNoRoutes);
21437 					mp->b_prev = mp->b_next = NULL;
21438 					if (first_mp == NULL)
21439 						first_mp = mp;
21440 					goto drop_pkt;
21441 				} else {
21442 					/*
21443 					 * If suitable ipif has been found, set
21444 					 * xmit_ill to the corresponding
21445 					 * ipif_ill because we'll be following
21446 					 * the IP_XMIT_IF logic.
21447 					 */
21448 					ASSERT(xmit_ill == NULL);
21449 					xmit_ill = dst_ipif->ipif_ill;
21450 					mutex_enter(&xmit_ill->ill_lock);
21451 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21452 						mutex_exit(&xmit_ill->ill_lock);
21453 						xmit_ill = NULL;
21454 						ipif_refrele(dst_ipif);
21455 						ip1dbg(("ip_wput: no route for"
21456 						    " dst using"
21457 						    " SO_DONTROUTE\n"));
21458 						BUMP_MIB(&ipst->ips_ip_mib,
21459 						    ipIfStatsOutNoRoutes);
21460 						mp->b_prev = mp->b_next = NULL;
21461 						if (first_mp == NULL)
21462 							first_mp = mp;
21463 						goto drop_pkt;
21464 					}
21465 					ill_refhold_locked(xmit_ill);
21466 					mutex_exit(&xmit_ill->ill_lock);
21467 					ipif_refrele(dst_ipif);
21468 				}
21469 			}
21470 
21471 		}
21472 		/*
21473 		 * If we are bound to IPIF_NOFAILOVER address, look for
21474 		 * an IRE_CACHE matching the ill.
21475 		 */
21476 send_from_ill:
21477 		if (attach_ill != NULL) {
21478 			ipif_t	*attach_ipif;
21479 
21480 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21481 
21482 			/*
21483 			 * Check if we need an ire that will not be
21484 			 * looked up by anybody else i.e. HIDDEN.
21485 			 */
21486 			if (ill_is_probeonly(attach_ill)) {
21487 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21488 			}
21489 
21490 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21491 			if (attach_ipif == NULL) {
21492 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21493 				goto discard_pkt;
21494 			}
21495 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21496 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21497 			ipif_refrele(attach_ipif);
21498 		} else if (xmit_ill != NULL || (connp != NULL &&
21499 			    connp->conn_xmit_if_ill != NULL)) {
21500 			/*
21501 			 * Mark this packet as originated locally
21502 			 */
21503 			mp->b_prev = mp->b_next = NULL;
21504 			/*
21505 			 * xmit_ill could be NULL if SO_DONTROUTE
21506 			 * is also set.
21507 			 */
21508 			if (xmit_ill == NULL) {
21509 				xmit_ill = conn_get_held_ill(connp,
21510 				    &connp->conn_xmit_if_ill, &err);
21511 				if (err == ILL_LOOKUP_FAILED) {
21512 					BUMP_MIB(&ipst->ips_ip_mib,
21513 					    ipIfStatsOutDiscards);
21514 					if (need_decref)
21515 						CONN_DEC_REF(connp);
21516 					freemsg(first_mp);
21517 					return;
21518 				}
21519 				if (xmit_ill == NULL) {
21520 					if (connp->conn_dontroute)
21521 						goto dontroute;
21522 					goto send_from_ill;
21523 				}
21524 			}
21525 			/*
21526 			 * Could be SO_DONTROUTE case also.
21527 			 * check at least one interface is UP as
21528 			 * specified by this ILL
21529 			 */
21530 			if (xmit_ill->ill_ipif_up_count > 0) {
21531 				ipif_t *ipif;
21532 
21533 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21534 				if (ipif == NULL) {
21535 					ip1dbg(("ip_output: "
21536 					    "xmit_ill NULL ipif\n"));
21537 					goto drop_pkt;
21538 				}
21539 				/*
21540 				 * Look for a ire that is part of the group,
21541 				 * if found use it else call ip_newroute_ipif.
21542 				 * IPCL_ZONEID is not used for matching because
21543 				 * IP_ALLZONES option is valid only when the
21544 				 * ill is accessible from all zones i.e has a
21545 				 * valid ipif in all zones.
21546 				 */
21547 				match_flags = MATCH_IRE_ILL_GROUP |
21548 				    MATCH_IRE_SECATTR;
21549 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21550 				    MBLK_GETLABEL(mp), match_flags, ipst);
21551 				/*
21552 				 * If an ire exists use it or else create
21553 				 * an ire but don't add it to the cache.
21554 				 * Adding an ire may cause issues with
21555 				 * asymmetric routing.
21556 				 * In case of multiroute always act as if
21557 				 * ire does not exist.
21558 				 */
21559 				if (ire == NULL ||
21560 				    ire->ire_flags & RTF_MULTIRT) {
21561 					if (ire != NULL)
21562 						ire_refrele(ire);
21563 					ip_newroute_ipif(q, first_mp, ipif,
21564 					    dst, connp, 0, zoneid, infop);
21565 					ipif_refrele(ipif);
21566 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21567 					ill_refrele(xmit_ill);
21568 					if (need_decref)
21569 						CONN_DEC_REF(connp);
21570 					return;
21571 				}
21572 				ipif_refrele(ipif);
21573 			} else {
21574 				goto drop_pkt;
21575 			}
21576 		} else if (ip_nexthop || (connp != NULL &&
21577 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21578 			if (!ip_nexthop) {
21579 				ip_nexthop = B_TRUE;
21580 				nexthop_addr = connp->conn_nexthop_v4;
21581 			}
21582 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21583 			    MATCH_IRE_GW;
21584 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21585 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21586 		} else {
21587 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21588 			    ipst);
21589 		}
21590 		if (!ire) {
21591 			/*
21592 			 * Make sure we don't load spread if this
21593 			 * is IPIF_NOFAILOVER case.
21594 			 */
21595 			if ((attach_ill != NULL) ||
21596 			    (ip_nexthop && !ignore_nexthop)) {
21597 				if (mctl_present) {
21598 					io = (ipsec_out_t *)first_mp->b_rptr;
21599 					ASSERT(first_mp->b_datap->db_type ==
21600 					    M_CTL);
21601 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21602 				} else {
21603 					ASSERT(mp == first_mp);
21604 					first_mp = allocb(
21605 					    sizeof (ipsec_info_t), BPRI_HI);
21606 					if (first_mp == NULL) {
21607 						first_mp = mp;
21608 						goto discard_pkt;
21609 					}
21610 					first_mp->b_datap->db_type = M_CTL;
21611 					first_mp->b_wptr +=
21612 					    sizeof (ipsec_info_t);
21613 					/* ipsec_out_secure is B_FALSE now */
21614 					bzero(first_mp->b_rptr,
21615 					    sizeof (ipsec_info_t));
21616 					io = (ipsec_out_t *)first_mp->b_rptr;
21617 					io->ipsec_out_type = IPSEC_OUT;
21618 					io->ipsec_out_len =
21619 					    sizeof (ipsec_out_t);
21620 					io->ipsec_out_use_global_policy =
21621 					    B_TRUE;
21622 					io->ipsec_out_ns = ipst->ips_netstack;
21623 					first_mp->b_cont = mp;
21624 					mctl_present = B_TRUE;
21625 				}
21626 				if (attach_ill != NULL) {
21627 					io->ipsec_out_ill_index = attach_ill->
21628 					    ill_phyint->phyint_ifindex;
21629 					io->ipsec_out_attach_if = B_TRUE;
21630 				} else {
21631 					io->ipsec_out_ip_nexthop = ip_nexthop;
21632 					io->ipsec_out_nexthop_addr =
21633 					    nexthop_addr;
21634 				}
21635 			}
21636 noirefound:
21637 			/*
21638 			 * Mark this packet as having originated on
21639 			 * this machine.  This will be noted in
21640 			 * ire_add_then_send, which needs to know
21641 			 * whether to run it back through ip_wput or
21642 			 * ip_rput following successful resolution.
21643 			 */
21644 			mp->b_prev = NULL;
21645 			mp->b_next = NULL;
21646 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21647 			    ipst);
21648 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21649 			    "ip_wput_end: q %p (%S)", q, "newroute");
21650 			if (attach_ill != NULL)
21651 				ill_refrele(attach_ill);
21652 			if (xmit_ill != NULL)
21653 				ill_refrele(xmit_ill);
21654 			if (need_decref)
21655 				CONN_DEC_REF(connp);
21656 			return;
21657 		}
21658 	}
21659 
21660 	/* We now know where we are going with it. */
21661 
21662 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21663 	    "ip_wput_end: q %p (%S)", q, "end");
21664 
21665 	/*
21666 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21667 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21668 	 */
21669 	if (ire->ire_flags & RTF_MULTIRT) {
21670 		/*
21671 		 * Force the TTL of multirouted packets if required.
21672 		 * The TTL of such packets is bounded by the
21673 		 * ip_multirt_ttl ndd variable.
21674 		 */
21675 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21676 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21677 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21678 			    "(was %d), dst 0x%08x\n",
21679 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21680 			    ntohl(ire->ire_addr)));
21681 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21682 		}
21683 		/*
21684 		 * At this point, we check to see if there are any pending
21685 		 * unresolved routes. ire_multirt_resolvable()
21686 		 * checks in O(n) that all IRE_OFFSUBNET ire
21687 		 * entries for the packet's destination and
21688 		 * flagged RTF_MULTIRT are currently resolved.
21689 		 * If some remain unresolved, we make a copy
21690 		 * of the current message. It will be used
21691 		 * to initiate additional route resolutions.
21692 		 */
21693 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21694 		    MBLK_GETLABEL(first_mp), ipst);
21695 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21696 		    "multirt_need_resolve %d, first_mp %p\n",
21697 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21698 		if (multirt_need_resolve) {
21699 			copy_mp = copymsg(first_mp);
21700 			if (copy_mp != NULL) {
21701 				MULTIRT_DEBUG_TAG(copy_mp);
21702 			}
21703 		}
21704 	}
21705 
21706 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21707 	/*
21708 	 * Try to resolve another multiroute if
21709 	 * ire_multirt_resolvable() deemed it necessary.
21710 	 * At this point, we need to distinguish
21711 	 * multicasts from other packets. For multicasts,
21712 	 * we call ip_newroute_ipif() and request that both
21713 	 * multirouting and setsrc flags are checked.
21714 	 */
21715 	if (copy_mp != NULL) {
21716 		if (CLASSD(dst)) {
21717 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21718 			if (ipif) {
21719 				ASSERT(infop->ip_opt_ill_index == 0);
21720 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21721 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21722 				ipif_refrele(ipif);
21723 			} else {
21724 				MULTIRT_DEBUG_UNTAG(copy_mp);
21725 				freemsg(copy_mp);
21726 				copy_mp = NULL;
21727 			}
21728 		} else {
21729 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21730 		}
21731 	}
21732 	if (attach_ill != NULL)
21733 		ill_refrele(attach_ill);
21734 	if (xmit_ill != NULL)
21735 		ill_refrele(xmit_ill);
21736 	if (need_decref)
21737 		CONN_DEC_REF(connp);
21738 	return;
21739 
21740 icmp_parameter_problem:
21741 	/* could not have originated externally */
21742 	ASSERT(mp->b_prev == NULL);
21743 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21744 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21745 		/* it's the IP header length that's in trouble */
21746 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21747 		first_mp = NULL;
21748 	}
21749 
21750 discard_pkt:
21751 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21752 drop_pkt:
21753 	ip1dbg(("ip_wput: dropped packet\n"));
21754 	if (ire != NULL)
21755 		ire_refrele(ire);
21756 	if (need_decref)
21757 		CONN_DEC_REF(connp);
21758 	freemsg(first_mp);
21759 	if (attach_ill != NULL)
21760 		ill_refrele(attach_ill);
21761 	if (xmit_ill != NULL)
21762 		ill_refrele(xmit_ill);
21763 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21764 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21765 }
21766 
21767 /*
21768  * If this is a conn_t queue, then we pass in the conn. This includes the
21769  * zoneid.
21770  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21771  * in which case we use the global zoneid since those are all part of
21772  * the global zone.
21773  */
21774 void
21775 ip_wput(queue_t *q, mblk_t *mp)
21776 {
21777 	if (CONN_Q(q))
21778 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21779 	else
21780 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21781 }
21782 
21783 /*
21784  *
21785  * The following rules must be observed when accessing any ipif or ill
21786  * that has been cached in the conn. Typically conn_nofailover_ill,
21787  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21788  *
21789  * Access: The ipif or ill pointed to from the conn can be accessed under
21790  * the protection of the conn_lock or after it has been refheld under the
21791  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21792  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21793  * The reason for this is that a concurrent unplumb could actually be
21794  * cleaning up these cached pointers by walking the conns and might have
21795  * finished cleaning up the conn in question. The macros check that an
21796  * unplumb has not yet started on the ipif or ill.
21797  *
21798  * Caching: An ipif or ill pointer may be cached in the conn only after
21799  * making sure that an unplumb has not started. So the caching is done
21800  * while holding both the conn_lock and the ill_lock and after using the
21801  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21802  * flag before starting the cleanup of conns.
21803  *
21804  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21805  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21806  * or a reference to the ipif or a reference to an ire that references the
21807  * ipif. An ipif does not change its ill except for failover/failback. Since
21808  * failover/failback happens only after bringing down the ipif and making sure
21809  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21810  * the above holds.
21811  */
21812 ipif_t *
21813 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21814 {
21815 	ipif_t	*ipif;
21816 	ill_t	*ill;
21817 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21818 
21819 	*err = 0;
21820 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21821 	mutex_enter(&connp->conn_lock);
21822 	ipif = *ipifp;
21823 	if (ipif != NULL) {
21824 		ill = ipif->ipif_ill;
21825 		mutex_enter(&ill->ill_lock);
21826 		if (IPIF_CAN_LOOKUP(ipif)) {
21827 			ipif_refhold_locked(ipif);
21828 			mutex_exit(&ill->ill_lock);
21829 			mutex_exit(&connp->conn_lock);
21830 			rw_exit(&ipst->ips_ill_g_lock);
21831 			return (ipif);
21832 		} else {
21833 			*err = IPIF_LOOKUP_FAILED;
21834 		}
21835 		mutex_exit(&ill->ill_lock);
21836 	}
21837 	mutex_exit(&connp->conn_lock);
21838 	rw_exit(&ipst->ips_ill_g_lock);
21839 	return (NULL);
21840 }
21841 
21842 ill_t *
21843 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21844 {
21845 	ill_t	*ill;
21846 
21847 	*err = 0;
21848 	mutex_enter(&connp->conn_lock);
21849 	ill = *illp;
21850 	if (ill != NULL) {
21851 		mutex_enter(&ill->ill_lock);
21852 		if (ILL_CAN_LOOKUP(ill)) {
21853 			ill_refhold_locked(ill);
21854 			mutex_exit(&ill->ill_lock);
21855 			mutex_exit(&connp->conn_lock);
21856 			return (ill);
21857 		} else {
21858 			*err = ILL_LOOKUP_FAILED;
21859 		}
21860 		mutex_exit(&ill->ill_lock);
21861 	}
21862 	mutex_exit(&connp->conn_lock);
21863 	return (NULL);
21864 }
21865 
21866 static int
21867 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21868 {
21869 	ill_t	*ill;
21870 
21871 	ill = ipif->ipif_ill;
21872 	mutex_enter(&connp->conn_lock);
21873 	mutex_enter(&ill->ill_lock);
21874 	if (IPIF_CAN_LOOKUP(ipif)) {
21875 		*ipifp = ipif;
21876 		mutex_exit(&ill->ill_lock);
21877 		mutex_exit(&connp->conn_lock);
21878 		return (0);
21879 	}
21880 	mutex_exit(&ill->ill_lock);
21881 	mutex_exit(&connp->conn_lock);
21882 	return (IPIF_LOOKUP_FAILED);
21883 }
21884 
21885 /*
21886  * This is called if the outbound datagram needs fragmentation.
21887  *
21888  * NOTE : This function does not ire_refrele the ire argument passed in.
21889  */
21890 static void
21891 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21892     ip_stack_t *ipst)
21893 {
21894 	ipha_t		*ipha;
21895 	mblk_t		*mp;
21896 	uint32_t	v_hlen_tos_len;
21897 	uint32_t	max_frag;
21898 	uint32_t	frag_flag;
21899 	boolean_t	dont_use;
21900 
21901 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21902 		mp = ipsec_mp->b_cont;
21903 	} else {
21904 		mp = ipsec_mp;
21905 	}
21906 
21907 	ipha = (ipha_t *)mp->b_rptr;
21908 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21909 
21910 #ifdef	_BIG_ENDIAN
21911 #define	V_HLEN	(v_hlen_tos_len >> 24)
21912 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21913 #else
21914 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21915 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21916 #endif
21917 
21918 #ifndef SPEED_BEFORE_SAFETY
21919 	/*
21920 	 * Check that ipha_length is consistent with
21921 	 * the mblk length
21922 	 */
21923 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21924 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21925 		    LENGTH, msgdsize(mp)));
21926 		freemsg(ipsec_mp);
21927 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21928 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21929 		    "packet length mismatch");
21930 		return;
21931 	}
21932 #endif
21933 	/*
21934 	 * Don't use frag_flag if pre-built packet or source
21935 	 * routed or if multicast (since multicast packets do not solicit
21936 	 * ICMP "packet too big" messages). Get the values of
21937 	 * max_frag and frag_flag atomically by acquiring the
21938 	 * ire_lock.
21939 	 */
21940 	mutex_enter(&ire->ire_lock);
21941 	max_frag = ire->ire_max_frag;
21942 	frag_flag = ire->ire_frag_flag;
21943 	mutex_exit(&ire->ire_lock);
21944 
21945 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21946 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21947 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21948 
21949 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21950 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21951 }
21952 
21953 /*
21954  * Used for deciding the MSS size for the upper layer. Thus
21955  * we need to check the outbound policy values in the conn.
21956  */
21957 int
21958 conn_ipsec_length(conn_t *connp)
21959 {
21960 	ipsec_latch_t *ipl;
21961 
21962 	ipl = connp->conn_latch;
21963 	if (ipl == NULL)
21964 		return (0);
21965 
21966 	if (ipl->ipl_out_policy == NULL)
21967 		return (0);
21968 
21969 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21970 }
21971 
21972 /*
21973  * Returns an estimate of the IPSEC headers size. This is used if
21974  * we don't want to call into IPSEC to get the exact size.
21975  */
21976 int
21977 ipsec_out_extra_length(mblk_t *ipsec_mp)
21978 {
21979 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21980 	ipsec_action_t *a;
21981 
21982 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21983 	if (!io->ipsec_out_secure)
21984 		return (0);
21985 
21986 	a = io->ipsec_out_act;
21987 
21988 	if (a == NULL) {
21989 		ASSERT(io->ipsec_out_policy != NULL);
21990 		a = io->ipsec_out_policy->ipsp_act;
21991 	}
21992 	ASSERT(a != NULL);
21993 
21994 	return (a->ipa_ovhd);
21995 }
21996 
21997 /*
21998  * Returns an estimate of the IPSEC headers size. This is used if
21999  * we don't want to call into IPSEC to get the exact size.
22000  */
22001 int
22002 ipsec_in_extra_length(mblk_t *ipsec_mp)
22003 {
22004 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22005 	ipsec_action_t *a;
22006 
22007 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22008 
22009 	a = ii->ipsec_in_action;
22010 	return (a == NULL ? 0 : a->ipa_ovhd);
22011 }
22012 
22013 /*
22014  * If there are any source route options, return the true final
22015  * destination. Otherwise, return the destination.
22016  */
22017 ipaddr_t
22018 ip_get_dst(ipha_t *ipha)
22019 {
22020 	ipoptp_t	opts;
22021 	uchar_t		*opt;
22022 	uint8_t		optval;
22023 	uint8_t		optlen;
22024 	ipaddr_t	dst;
22025 	uint32_t off;
22026 
22027 	dst = ipha->ipha_dst;
22028 
22029 	if (IS_SIMPLE_IPH(ipha))
22030 		return (dst);
22031 
22032 	for (optval = ipoptp_first(&opts, ipha);
22033 	    optval != IPOPT_EOL;
22034 	    optval = ipoptp_next(&opts)) {
22035 		opt = opts.ipoptp_cur;
22036 		optlen = opts.ipoptp_len;
22037 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22038 		switch (optval) {
22039 		case IPOPT_SSRR:
22040 		case IPOPT_LSRR:
22041 			off = opt[IPOPT_OFFSET];
22042 			/*
22043 			 * If one of the conditions is true, it means
22044 			 * end of options and dst already has the right
22045 			 * value.
22046 			 */
22047 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22048 				off = optlen - IP_ADDR_LEN;
22049 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22050 			}
22051 			return (dst);
22052 		default:
22053 			break;
22054 		}
22055 	}
22056 
22057 	return (dst);
22058 }
22059 
22060 mblk_t *
22061 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22062     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22063 {
22064 	ipsec_out_t	*io;
22065 	mblk_t		*first_mp;
22066 	boolean_t policy_present;
22067 	ip_stack_t	*ipst;
22068 	ipsec_stack_t	*ipss;
22069 
22070 	ASSERT(ire != NULL);
22071 	ipst = ire->ire_ipst;
22072 	ipss = ipst->ips_netstack->netstack_ipsec;
22073 
22074 	first_mp = mp;
22075 	if (mp->b_datap->db_type == M_CTL) {
22076 		io = (ipsec_out_t *)first_mp->b_rptr;
22077 		/*
22078 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22079 		 *
22080 		 * 1) There is per-socket policy (including cached global
22081 		 *    policy) or a policy on the IP-in-IP tunnel.
22082 		 * 2) There is no per-socket policy, but it is
22083 		 *    a multicast packet that needs to go out
22084 		 *    on a specific interface. This is the case
22085 		 *    where (ip_wput and ip_wput_multicast) attaches
22086 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22087 		 *
22088 		 * In case (2) we check with global policy to
22089 		 * see if there is a match and set the ill_index
22090 		 * appropriately so that we can lookup the ire
22091 		 * properly in ip_wput_ipsec_out.
22092 		 */
22093 
22094 		/*
22095 		 * ipsec_out_use_global_policy is set to B_FALSE
22096 		 * in ipsec_in_to_out(). Refer to that function for
22097 		 * details.
22098 		 */
22099 		if ((io->ipsec_out_latch == NULL) &&
22100 		    (io->ipsec_out_use_global_policy)) {
22101 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22102 				    ire, connp, unspec_src, zoneid));
22103 		}
22104 		if (!io->ipsec_out_secure) {
22105 			/*
22106 			 * If this is not a secure packet, drop
22107 			 * the IPSEC_OUT mp and treat it as a clear
22108 			 * packet. This happens when we are sending
22109 			 * a ICMP reply back to a clear packet. See
22110 			 * ipsec_in_to_out() for details.
22111 			 */
22112 			mp = first_mp->b_cont;
22113 			freeb(first_mp);
22114 		}
22115 		return (mp);
22116 	}
22117 	/*
22118 	 * See whether we need to attach a global policy here. We
22119 	 * don't depend on the conn (as it could be null) for deciding
22120 	 * what policy this datagram should go through because it
22121 	 * should have happened in ip_wput if there was some
22122 	 * policy. This normally happens for connections which are not
22123 	 * fully bound preventing us from caching policies in
22124 	 * ip_bind. Packets coming from the TCP listener/global queue
22125 	 * - which are non-hard_bound - could also be affected by
22126 	 * applying policy here.
22127 	 *
22128 	 * If this packet is coming from tcp global queue or listener,
22129 	 * we will be applying policy here.  This may not be *right*
22130 	 * if these packets are coming from the detached connection as
22131 	 * it could have gone in clear before. This happens only if a
22132 	 * TCP connection started when there is no policy and somebody
22133 	 * added policy before it became detached. Thus packets of the
22134 	 * detached connection could go out secure and the other end
22135 	 * would drop it because it will be expecting in clear. The
22136 	 * converse is not true i.e if somebody starts a TCP
22137 	 * connection and deletes the policy, all the packets will
22138 	 * still go out with the policy that existed before deleting
22139 	 * because ip_unbind sends up policy information which is used
22140 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22141 	 * TCP to attach a dummy IPSEC_OUT and set
22142 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22143 	 * affect performance for normal cases, we are not doing it.
22144 	 * Thus, set policy before starting any TCP connections.
22145 	 *
22146 	 * NOTE - We might apply policy even for a hard bound connection
22147 	 * - for which we cached policy in ip_bind - if somebody added
22148 	 * global policy after we inherited the policy in ip_bind.
22149 	 * This means that the packets that were going out in clear
22150 	 * previously would start going secure and hence get dropped
22151 	 * on the other side. To fix this, TCP attaches a dummy
22152 	 * ipsec_out and make sure that we don't apply global policy.
22153 	 */
22154 	if (ipha != NULL)
22155 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22156 	else
22157 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22158 	if (!policy_present)
22159 		return (mp);
22160 
22161 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22162 		    zoneid));
22163 }
22164 
22165 ire_t *
22166 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22167 {
22168 	ipaddr_t addr;
22169 	ire_t *save_ire;
22170 	irb_t *irb;
22171 	ill_group_t *illgrp;
22172 	int	err;
22173 
22174 	save_ire = ire;
22175 	addr = ire->ire_addr;
22176 
22177 	ASSERT(ire->ire_type == IRE_BROADCAST);
22178 
22179 	illgrp = connp->conn_outgoing_ill->ill_group;
22180 	if (illgrp == NULL) {
22181 		*conn_outgoing_ill = conn_get_held_ill(connp,
22182 		    &connp->conn_outgoing_ill, &err);
22183 		if (err == ILL_LOOKUP_FAILED) {
22184 			ire_refrele(save_ire);
22185 			return (NULL);
22186 		}
22187 		return (save_ire);
22188 	}
22189 	/*
22190 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22191 	 * If it is part of the group, we need to send on the ire
22192 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22193 	 * to this group. This is okay as IP_BOUND_IF really means
22194 	 * any ill in the group. We depend on the fact that the
22195 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22196 	 * if such an ire exists. This is possible only if you have
22197 	 * at least one ill in the group that has not failed.
22198 	 *
22199 	 * First get to the ire that matches the address and group.
22200 	 *
22201 	 * We don't look for an ire with a matching zoneid because a given zone
22202 	 * won't always have broadcast ires on all ills in the group.
22203 	 */
22204 	irb = ire->ire_bucket;
22205 	rw_enter(&irb->irb_lock, RW_READER);
22206 	if (ire->ire_marks & IRE_MARK_NORECV) {
22207 		/*
22208 		 * If the current zone only has an ire broadcast for this
22209 		 * address marked NORECV, the ire we want is ahead in the
22210 		 * bucket, so we look it up deliberately ignoring the zoneid.
22211 		 */
22212 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22213 			if (ire->ire_addr != addr)
22214 				continue;
22215 			/* skip over deleted ires */
22216 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22217 				continue;
22218 		}
22219 	}
22220 	while (ire != NULL) {
22221 		/*
22222 		 * If a new interface is coming up, we could end up
22223 		 * seeing the loopback ire and the non-loopback ire
22224 		 * may not have been added yet. So check for ire_stq
22225 		 */
22226 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22227 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22228 			break;
22229 		}
22230 		ire = ire->ire_next;
22231 	}
22232 	if (ire != NULL && ire->ire_addr == addr &&
22233 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22234 		IRE_REFHOLD(ire);
22235 		rw_exit(&irb->irb_lock);
22236 		ire_refrele(save_ire);
22237 		*conn_outgoing_ill = ire_to_ill(ire);
22238 		/*
22239 		 * Refhold the ill to make the conn_outgoing_ill
22240 		 * independent of the ire. ip_wput_ire goes in a loop
22241 		 * and may refrele the ire. Since we have an ire at this
22242 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22243 		 */
22244 		ill_refhold(*conn_outgoing_ill);
22245 		return (ire);
22246 	}
22247 	rw_exit(&irb->irb_lock);
22248 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22249 	/*
22250 	 * If we can't find a suitable ire, return the original ire.
22251 	 */
22252 	return (save_ire);
22253 }
22254 
22255 /*
22256  * This function does the ire_refrele of the ire passed in as the
22257  * argument. As this function looks up more ires i.e broadcast ires,
22258  * it needs to REFRELE them. Currently, for simplicity we don't
22259  * differentiate the one passed in and looked up here. We always
22260  * REFRELE.
22261  * IPQoS Notes:
22262  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22263  * IPSec packets are done in ipsec_out_process.
22264  *
22265  */
22266 void
22267 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22268     zoneid_t zoneid)
22269 {
22270 	ipha_t		*ipha;
22271 #define	rptr	((uchar_t *)ipha)
22272 	queue_t		*stq;
22273 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22274 	uint32_t	v_hlen_tos_len;
22275 	uint32_t	ttl_protocol;
22276 	ipaddr_t	src;
22277 	ipaddr_t	dst;
22278 	uint32_t	cksum;
22279 	ipaddr_t	orig_src;
22280 	ire_t		*ire1;
22281 	mblk_t		*next_mp;
22282 	uint_t		hlen;
22283 	uint16_t	*up;
22284 	uint32_t	max_frag = ire->ire_max_frag;
22285 	ill_t		*ill = ire_to_ill(ire);
22286 	int		clusterwide;
22287 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22288 	int		ipsec_len;
22289 	mblk_t		*first_mp;
22290 	ipsec_out_t	*io;
22291 	boolean_t	conn_dontroute;		/* conn value for multicast */
22292 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22293 	boolean_t	multicast_forward;	/* Should we forward ? */
22294 	boolean_t	unspec_src;
22295 	ill_t		*conn_outgoing_ill = NULL;
22296 	ill_t		*ire_ill;
22297 	ill_t		*ire1_ill;
22298 	ill_t		*out_ill;
22299 	uint32_t 	ill_index = 0;
22300 	boolean_t	multirt_send = B_FALSE;
22301 	int		err;
22302 	ipxmit_state_t	pktxmit_state;
22303 	ip_stack_t	*ipst = ire->ire_ipst;
22304 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22305 
22306 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22307 	    "ip_wput_ire_start: q %p", q);
22308 
22309 	multicast_forward = B_FALSE;
22310 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22311 
22312 	if (ire->ire_flags & RTF_MULTIRT) {
22313 		/*
22314 		 * Multirouting case. The bucket where ire is stored
22315 		 * probably holds other RTF_MULTIRT flagged ire
22316 		 * to the destination. In this call to ip_wput_ire,
22317 		 * we attempt to send the packet through all
22318 		 * those ires. Thus, we first ensure that ire is the
22319 		 * first RTF_MULTIRT ire in the bucket,
22320 		 * before walking the ire list.
22321 		 */
22322 		ire_t *first_ire;
22323 		irb_t *irb = ire->ire_bucket;
22324 		ASSERT(irb != NULL);
22325 
22326 		/* Make sure we do not omit any multiroute ire. */
22327 		IRB_REFHOLD(irb);
22328 		for (first_ire = irb->irb_ire;
22329 		    first_ire != NULL;
22330 		    first_ire = first_ire->ire_next) {
22331 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22332 			    (first_ire->ire_addr == ire->ire_addr) &&
22333 			    !(first_ire->ire_marks &
22334 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22335 				break;
22336 		}
22337 
22338 		if ((first_ire != NULL) && (first_ire != ire)) {
22339 			IRE_REFHOLD(first_ire);
22340 			ire_refrele(ire);
22341 			ire = first_ire;
22342 			ill = ire_to_ill(ire);
22343 		}
22344 		IRB_REFRELE(irb);
22345 	}
22346 
22347 	/*
22348 	 * conn_outgoing_ill is used only in the broadcast loop.
22349 	 * for performance we don't grab the mutexs in the fastpath
22350 	 */
22351 	if ((connp != NULL) &&
22352 	    (connp->conn_xmit_if_ill == NULL) &&
22353 	    (ire->ire_type == IRE_BROADCAST) &&
22354 	    ((connp->conn_nofailover_ill != NULL) ||
22355 	    (connp->conn_outgoing_ill != NULL))) {
22356 		/*
22357 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22358 		 * option. So, see if this endpoint is bound to a
22359 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22360 		 * that if the interface is failed, we will still send
22361 		 * the packet on the same ill which is what we want.
22362 		 */
22363 		conn_outgoing_ill = conn_get_held_ill(connp,
22364 		    &connp->conn_nofailover_ill, &err);
22365 		if (err == ILL_LOOKUP_FAILED) {
22366 			ire_refrele(ire);
22367 			freemsg(mp);
22368 			return;
22369 		}
22370 		if (conn_outgoing_ill == NULL) {
22371 			/*
22372 			 * Choose a good ill in the group to send the
22373 			 * packets on.
22374 			 */
22375 			ire = conn_set_outgoing_ill(connp, ire,
22376 			    &conn_outgoing_ill);
22377 			if (ire == NULL) {
22378 				freemsg(mp);
22379 				return;
22380 			}
22381 		}
22382 	}
22383 
22384 	if (mp->b_datap->db_type != M_CTL) {
22385 		ipha = (ipha_t *)mp->b_rptr;
22386 	} else {
22387 		io = (ipsec_out_t *)mp->b_rptr;
22388 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22389 		ASSERT(zoneid == io->ipsec_out_zoneid);
22390 		ASSERT(zoneid != ALL_ZONES);
22391 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22392 		dst = ipha->ipha_dst;
22393 		/*
22394 		 * For the multicast case, ipsec_out carries conn_dontroute and
22395 		 * conn_multicast_loop as conn may not be available here. We
22396 		 * need this for multicast loopback and forwarding which is done
22397 		 * later in the code.
22398 		 */
22399 		if (CLASSD(dst)) {
22400 			conn_dontroute = io->ipsec_out_dontroute;
22401 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22402 			/*
22403 			 * If conn_dontroute is not set or conn_multicast_loop
22404 			 * is set, we need to do forwarding/loopback. For
22405 			 * datagrams from ip_wput_multicast, conn_dontroute is
22406 			 * set to B_TRUE and conn_multicast_loop is set to
22407 			 * B_FALSE so that we neither do forwarding nor
22408 			 * loopback.
22409 			 */
22410 			if (!conn_dontroute || conn_multicast_loop)
22411 				multicast_forward = B_TRUE;
22412 		}
22413 	}
22414 
22415 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22416 	    ire->ire_zoneid != ALL_ZONES) {
22417 		/*
22418 		 * When a zone sends a packet to another zone, we try to deliver
22419 		 * the packet under the same conditions as if the destination
22420 		 * was a real node on the network. To do so, we look for a
22421 		 * matching route in the forwarding table.
22422 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22423 		 * ip_newroute() does.
22424 		 * Note that IRE_LOCAL are special, since they are used
22425 		 * when the zoneid doesn't match in some cases. This means that
22426 		 * we need to handle ipha_src differently since ire_src_addr
22427 		 * belongs to the receiving zone instead of the sending zone.
22428 		 * When ip_restrict_interzone_loopback is set, then
22429 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22430 		 * for loopback between zones when the logical "Ethernet" would
22431 		 * have looped them back.
22432 		 */
22433 		ire_t *src_ire;
22434 
22435 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22436 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22437 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22438 		if (src_ire != NULL &&
22439 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22440 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22441 		    ire_local_same_ill_group(ire, src_ire))) {
22442 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22443 				ipha->ipha_src = src_ire->ire_src_addr;
22444 			ire_refrele(src_ire);
22445 		} else {
22446 			ire_refrele(ire);
22447 			if (conn_outgoing_ill != NULL)
22448 				ill_refrele(conn_outgoing_ill);
22449 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22450 			if (src_ire != NULL) {
22451 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22452 					ire_refrele(src_ire);
22453 					freemsg(mp);
22454 					return;
22455 				}
22456 				ire_refrele(src_ire);
22457 			}
22458 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22459 				/* Failed */
22460 				freemsg(mp);
22461 				return;
22462 			}
22463 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22464 			    ipst);
22465 			return;
22466 		}
22467 	}
22468 
22469 	if (mp->b_datap->db_type == M_CTL ||
22470 	    ipss->ipsec_outbound_v4_policy_present) {
22471 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22472 		    unspec_src, zoneid);
22473 		if (mp == NULL) {
22474 			ire_refrele(ire);
22475 			if (conn_outgoing_ill != NULL)
22476 				ill_refrele(conn_outgoing_ill);
22477 			return;
22478 		}
22479 	}
22480 
22481 	first_mp = mp;
22482 	ipsec_len = 0;
22483 
22484 	if (first_mp->b_datap->db_type == M_CTL) {
22485 		io = (ipsec_out_t *)first_mp->b_rptr;
22486 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22487 		mp = first_mp->b_cont;
22488 		ipsec_len = ipsec_out_extra_length(first_mp);
22489 		ASSERT(ipsec_len >= 0);
22490 		/* We already picked up the zoneid from the M_CTL above */
22491 		ASSERT(zoneid == io->ipsec_out_zoneid);
22492 		ASSERT(zoneid != ALL_ZONES);
22493 
22494 		/*
22495 		 * Drop M_CTL here if IPsec processing is not needed.
22496 		 * (Non-IPsec use of M_CTL extracted any information it
22497 		 * needed above).
22498 		 */
22499 		if (ipsec_len == 0) {
22500 			freeb(first_mp);
22501 			first_mp = mp;
22502 		}
22503 	}
22504 
22505 	/*
22506 	 * Fast path for ip_wput_ire
22507 	 */
22508 
22509 	ipha = (ipha_t *)mp->b_rptr;
22510 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22511 	dst = ipha->ipha_dst;
22512 
22513 	/*
22514 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22515 	 * if the socket is a SOCK_RAW type. The transport checksum should
22516 	 * be provided in the pre-built packet, so we don't need to compute it.
22517 	 * Also, other application set flags, like DF, should not be altered.
22518 	 * Other transport MUST pass down zero.
22519 	 */
22520 	ip_hdr_included = ipha->ipha_ident;
22521 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22522 
22523 	if (CLASSD(dst)) {
22524 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22525 		    ntohl(dst),
22526 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22527 		    ntohl(ire->ire_addr)));
22528 	}
22529 
22530 /* Macros to extract header fields from data already in registers */
22531 #ifdef	_BIG_ENDIAN
22532 #define	V_HLEN	(v_hlen_tos_len >> 24)
22533 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22534 #define	PROTO	(ttl_protocol & 0xFF)
22535 #else
22536 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22537 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22538 #define	PROTO	(ttl_protocol >> 8)
22539 #endif
22540 
22541 
22542 	orig_src = src = ipha->ipha_src;
22543 	/* (The loop back to "another" is explained down below.) */
22544 another:;
22545 	/*
22546 	 * Assign an ident value for this packet.  We assign idents on
22547 	 * a per destination basis out of the IRE.  There could be
22548 	 * other threads targeting the same destination, so we have to
22549 	 * arrange for a atomic increment.  Note that we use a 32-bit
22550 	 * atomic add because it has better performance than its
22551 	 * 16-bit sibling.
22552 	 *
22553 	 * If running in cluster mode and if the source address
22554 	 * belongs to a replicated service then vector through
22555 	 * cl_inet_ipident vector to allocate ip identifier
22556 	 * NOTE: This is a contract private interface with the
22557 	 * clustering group.
22558 	 */
22559 	clusterwide = 0;
22560 	if (cl_inet_ipident) {
22561 		ASSERT(cl_inet_isclusterwide);
22562 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22563 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22564 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22565 			    AF_INET, (uint8_t *)(uintptr_t)src,
22566 			    (uint8_t *)(uintptr_t)dst);
22567 			clusterwide = 1;
22568 		}
22569 	}
22570 	if (!clusterwide) {
22571 		ipha->ipha_ident =
22572 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22573 	}
22574 
22575 #ifndef _BIG_ENDIAN
22576 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22577 #endif
22578 
22579 	/*
22580 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22581 	 * This is needed to obey conn_unspec_src when packets go through
22582 	 * ip_newroute + arp.
22583 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22584 	 */
22585 	if (src == INADDR_ANY && !unspec_src) {
22586 		/*
22587 		 * Assign the appropriate source address from the IRE if none
22588 		 * was specified.
22589 		 */
22590 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22591 
22592 		/*
22593 		 * With IP multipathing, broadcast packets are sent on the ire
22594 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22595 		 * the group. However, this ire might not be in the same zone so
22596 		 * we can't always use its source address. We look for a
22597 		 * broadcast ire in the same group and in the right zone.
22598 		 */
22599 		if (ire->ire_type == IRE_BROADCAST &&
22600 		    ire->ire_zoneid != zoneid) {
22601 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22602 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22603 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22604 			if (src_ire != NULL) {
22605 				src = src_ire->ire_src_addr;
22606 				ire_refrele(src_ire);
22607 			} else {
22608 				ire_refrele(ire);
22609 				if (conn_outgoing_ill != NULL)
22610 					ill_refrele(conn_outgoing_ill);
22611 				freemsg(first_mp);
22612 				if (ill != NULL) {
22613 					BUMP_MIB(ill->ill_ip_mib,
22614 					    ipIfStatsOutDiscards);
22615 				} else {
22616 					BUMP_MIB(&ipst->ips_ip_mib,
22617 					    ipIfStatsOutDiscards);
22618 				}
22619 				return;
22620 			}
22621 		} else {
22622 			src = ire->ire_src_addr;
22623 		}
22624 
22625 		if (connp == NULL) {
22626 			ip1dbg(("ip_wput_ire: no connp and no src "
22627 			    "address for dst 0x%x, using src 0x%x\n",
22628 			    ntohl(dst),
22629 			    ntohl(src)));
22630 		}
22631 		ipha->ipha_src = src;
22632 	}
22633 	stq = ire->ire_stq;
22634 
22635 	/*
22636 	 * We only allow ire chains for broadcasts since there will
22637 	 * be multiple IRE_CACHE entries for the same multicast
22638 	 * address (one per ipif).
22639 	 */
22640 	next_mp = NULL;
22641 
22642 	/* broadcast packet */
22643 	if (ire->ire_type == IRE_BROADCAST)
22644 		goto broadcast;
22645 
22646 	/* loopback ? */
22647 	if (stq == NULL)
22648 		goto nullstq;
22649 
22650 	/* The ill_index for outbound ILL */
22651 	ill_index = Q_TO_INDEX(stq);
22652 
22653 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22654 	ttl_protocol = ((uint16_t *)ipha)[4];
22655 
22656 	/* pseudo checksum (do it in parts for IP header checksum) */
22657 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22658 
22659 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22660 		queue_t *dev_q = stq->q_next;
22661 
22662 		/* flow controlled */
22663 		if ((dev_q->q_next || dev_q->q_first) &&
22664 		    !canput(dev_q))
22665 			goto blocked;
22666 		if ((PROTO == IPPROTO_UDP) &&
22667 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22668 			hlen = (V_HLEN & 0xF) << 2;
22669 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22670 			if (*up != 0) {
22671 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22672 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22673 				/* Software checksum? */
22674 				if (DB_CKSUMFLAGS(mp) == 0) {
22675 					IP_STAT(ipst, ip_out_sw_cksum);
22676 					IP_STAT_UPDATE(ipst,
22677 					    ip_udp_out_sw_cksum_bytes,
22678 					    LENGTH - hlen);
22679 				}
22680 			}
22681 		}
22682 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22683 		hlen = (V_HLEN & 0xF) << 2;
22684 		if (PROTO == IPPROTO_TCP) {
22685 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22686 			/*
22687 			 * The packet header is processed once and for all, even
22688 			 * in the multirouting case. We disable hardware
22689 			 * checksum if the packet is multirouted, as it will be
22690 			 * replicated via several interfaces, and not all of
22691 			 * them may have this capability.
22692 			 */
22693 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22694 			    LENGTH, max_frag, ipsec_len, cksum);
22695 			/* Software checksum? */
22696 			if (DB_CKSUMFLAGS(mp) == 0) {
22697 				IP_STAT(ipst, ip_out_sw_cksum);
22698 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22699 				    LENGTH - hlen);
22700 			}
22701 		} else {
22702 			sctp_hdr_t	*sctph;
22703 
22704 			ASSERT(PROTO == IPPROTO_SCTP);
22705 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22706 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22707 			/*
22708 			 * Zero out the checksum field to ensure proper
22709 			 * checksum calculation.
22710 			 */
22711 			sctph->sh_chksum = 0;
22712 #ifdef	DEBUG
22713 			if (!skip_sctp_cksum)
22714 #endif
22715 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22716 		}
22717 	}
22718 
22719 	/*
22720 	 * If this is a multicast packet and originated from ip_wput
22721 	 * we need to do loopback and forwarding checks. If it comes
22722 	 * from ip_wput_multicast, we SHOULD not do this.
22723 	 */
22724 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22725 
22726 	/* checksum */
22727 	cksum += ttl_protocol;
22728 
22729 	/* fragment the packet */
22730 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22731 		goto fragmentit;
22732 	/*
22733 	 * Don't use frag_flag if packet is pre-built or source
22734 	 * routed or if multicast (since multicast packets do
22735 	 * not solicit ICMP "packet too big" messages).
22736 	 */
22737 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22738 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22739 	    !ip_source_route_included(ipha)) &&
22740 	    !CLASSD(ipha->ipha_dst))
22741 		ipha->ipha_fragment_offset_and_flags |=
22742 		    htons(ire->ire_frag_flag);
22743 
22744 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22745 		/* calculate IP header checksum */
22746 		cksum += ipha->ipha_ident;
22747 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22748 		cksum += ipha->ipha_fragment_offset_and_flags;
22749 
22750 		/* IP options present */
22751 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22752 		if (hlen)
22753 			goto checksumoptions;
22754 
22755 		/* calculate hdr checksum */
22756 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22757 		cksum = ~(cksum + (cksum >> 16));
22758 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22759 	}
22760 	if (ipsec_len != 0) {
22761 		/*
22762 		 * We will do the rest of the processing after
22763 		 * we come back from IPSEC in ip_wput_ipsec_out().
22764 		 */
22765 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22766 
22767 		io = (ipsec_out_t *)first_mp->b_rptr;
22768 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22769 				ill_phyint->phyint_ifindex;
22770 
22771 		ipsec_out_process(q, first_mp, ire, ill_index);
22772 		ire_refrele(ire);
22773 		if (conn_outgoing_ill != NULL)
22774 			ill_refrele(conn_outgoing_ill);
22775 		return;
22776 	}
22777 
22778 	/*
22779 	 * In most cases, the emission loop below is entered only
22780 	 * once. Only in the case where the ire holds the
22781 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22782 	 * flagged ires in the bucket, and send the packet
22783 	 * through all crossed RTF_MULTIRT routes.
22784 	 */
22785 	if (ire->ire_flags & RTF_MULTIRT) {
22786 		multirt_send = B_TRUE;
22787 	}
22788 	do {
22789 		if (multirt_send) {
22790 			irb_t *irb;
22791 			/*
22792 			 * We are in a multiple send case, need to get
22793 			 * the next ire and make a duplicate of the packet.
22794 			 * ire1 holds here the next ire to process in the
22795 			 * bucket. If multirouting is expected,
22796 			 * any non-RTF_MULTIRT ire that has the
22797 			 * right destination address is ignored.
22798 			 */
22799 			irb = ire->ire_bucket;
22800 			ASSERT(irb != NULL);
22801 
22802 			IRB_REFHOLD(irb);
22803 			for (ire1 = ire->ire_next;
22804 			    ire1 != NULL;
22805 			    ire1 = ire1->ire_next) {
22806 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22807 					continue;
22808 				if (ire1->ire_addr != ire->ire_addr)
22809 					continue;
22810 				if (ire1->ire_marks &
22811 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22812 					continue;
22813 
22814 				/* Got one */
22815 				IRE_REFHOLD(ire1);
22816 				break;
22817 			}
22818 			IRB_REFRELE(irb);
22819 
22820 			if (ire1 != NULL) {
22821 				next_mp = copyb(mp);
22822 				if ((next_mp == NULL) ||
22823 				    ((mp->b_cont != NULL) &&
22824 				    ((next_mp->b_cont =
22825 				    dupmsg(mp->b_cont)) == NULL))) {
22826 					freemsg(next_mp);
22827 					next_mp = NULL;
22828 					ire_refrele(ire1);
22829 					ire1 = NULL;
22830 				}
22831 			}
22832 
22833 			/* Last multiroute ire; don't loop anymore. */
22834 			if (ire1 == NULL) {
22835 				multirt_send = B_FALSE;
22836 			}
22837 		}
22838 
22839 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22840 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22841 		    mblk_t *, mp);
22842 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22843 		    ipst->ips_ipv4firewall_physical_out,
22844 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22845 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22846 		if (mp == NULL)
22847 			goto release_ire_and_ill;
22848 
22849 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22850 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22851 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22852 		if ((pktxmit_state == SEND_FAILED) ||
22853 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22854 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22855 			    "- packet dropped\n"));
22856 release_ire_and_ill:
22857 			ire_refrele(ire);
22858 			if (next_mp != NULL) {
22859 				freemsg(next_mp);
22860 				ire_refrele(ire1);
22861 			}
22862 			if (conn_outgoing_ill != NULL)
22863 				ill_refrele(conn_outgoing_ill);
22864 			return;
22865 		}
22866 
22867 		if (CLASSD(dst)) {
22868 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22869 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22870 			    LENGTH);
22871 		}
22872 
22873 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22874 		    "ip_wput_ire_end: q %p (%S)",
22875 		    q, "last copy out");
22876 		IRE_REFRELE(ire);
22877 
22878 		if (multirt_send) {
22879 			ASSERT(ire1);
22880 			/*
22881 			 * Proceed with the next RTF_MULTIRT ire,
22882 			 * Also set up the send-to queue accordingly.
22883 			 */
22884 			ire = ire1;
22885 			ire1 = NULL;
22886 			stq = ire->ire_stq;
22887 			mp = next_mp;
22888 			next_mp = NULL;
22889 			ipha = (ipha_t *)mp->b_rptr;
22890 			ill_index = Q_TO_INDEX(stq);
22891 			ill = (ill_t *)stq->q_ptr;
22892 		}
22893 	} while (multirt_send);
22894 	if (conn_outgoing_ill != NULL)
22895 		ill_refrele(conn_outgoing_ill);
22896 	return;
22897 
22898 	/*
22899 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22900 	 */
22901 broadcast:
22902 	{
22903 		/*
22904 		 * Avoid broadcast storms by setting the ttl to 1
22905 		 * for broadcasts. This parameter can be set
22906 		 * via ndd, so make sure that for the SO_DONTROUTE
22907 		 * case that ipha_ttl is always set to 1.
22908 		 * In the event that we are replying to incoming
22909 		 * ICMP packets, conn could be NULL.
22910 		 */
22911 		if ((connp != NULL) && connp->conn_dontroute)
22912 			ipha->ipha_ttl = 1;
22913 		else
22914 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22915 
22916 		/*
22917 		 * Note that we are not doing a IRB_REFHOLD here.
22918 		 * Actually we don't care if the list changes i.e
22919 		 * if somebody deletes an IRE from the list while
22920 		 * we drop the lock, the next time we come around
22921 		 * ire_next will be NULL and hence we won't send
22922 		 * out multiple copies which is fine.
22923 		 */
22924 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22925 		ire1 = ire->ire_next;
22926 		if (conn_outgoing_ill != NULL) {
22927 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22928 				ASSERT(ire1 == ire->ire_next);
22929 				if (ire1 != NULL && ire1->ire_addr == dst) {
22930 					ire_refrele(ire);
22931 					ire = ire1;
22932 					IRE_REFHOLD(ire);
22933 					ire1 = ire->ire_next;
22934 					continue;
22935 				}
22936 				rw_exit(&ire->ire_bucket->irb_lock);
22937 				/* Did not find a matching ill */
22938 				ip1dbg(("ip_wput_ire: broadcast with no "
22939 				    "matching IP_BOUND_IF ill %s\n",
22940 				    conn_outgoing_ill->ill_name));
22941 				freemsg(first_mp);
22942 				if (ire != NULL)
22943 					ire_refrele(ire);
22944 				ill_refrele(conn_outgoing_ill);
22945 				return;
22946 			}
22947 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22948 			/*
22949 			 * If the next IRE has the same address and is not one
22950 			 * of the two copies that we need to send, try to see
22951 			 * whether this copy should be sent at all. This
22952 			 * assumes that we insert loopbacks first and then
22953 			 * non-loopbacks. This is acheived by inserting the
22954 			 * loopback always before non-loopback.
22955 			 * This is used to send a single copy of a broadcast
22956 			 * packet out all physical interfaces that have an
22957 			 * matching IRE_BROADCAST while also looping
22958 			 * back one copy (to ip_wput_local) for each
22959 			 * matching physical interface. However, we avoid
22960 			 * sending packets out different logical that match by
22961 			 * having ipif_up/ipif_down supress duplicate
22962 			 * IRE_BROADCASTS.
22963 			 *
22964 			 * This feature is currently used to get broadcasts
22965 			 * sent to multiple interfaces, when the broadcast
22966 			 * address being used applies to multiple interfaces.
22967 			 * For example, a whole net broadcast will be
22968 			 * replicated on every connected subnet of
22969 			 * the target net.
22970 			 *
22971 			 * Each zone has its own set of IRE_BROADCASTs, so that
22972 			 * we're able to distribute inbound packets to multiple
22973 			 * zones who share a broadcast address. We avoid looping
22974 			 * back outbound packets in different zones but on the
22975 			 * same ill, as the application would see duplicates.
22976 			 *
22977 			 * If the interfaces are part of the same group,
22978 			 * we would want to send only one copy out for
22979 			 * whole group.
22980 			 *
22981 			 * This logic assumes that ire_add_v4() groups the
22982 			 * IRE_BROADCAST entries so that those with the same
22983 			 * ire_addr and ill_group are kept together.
22984 			 */
22985 			ire_ill = ire->ire_ipif->ipif_ill;
22986 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22987 				if (ire_ill->ill_group != NULL &&
22988 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22989 					/*
22990 					 * If the current zone only has an ire
22991 					 * broadcast for this address marked
22992 					 * NORECV, the ire we want is ahead in
22993 					 * the bucket, so we look it up
22994 					 * deliberately ignoring the zoneid.
22995 					 */
22996 					for (ire1 = ire->ire_bucket->irb_ire;
22997 					    ire1 != NULL;
22998 					    ire1 = ire1->ire_next) {
22999 						ire1_ill =
23000 						    ire1->ire_ipif->ipif_ill;
23001 						if (ire1->ire_addr != dst)
23002 							continue;
23003 						/* skip over the current ire */
23004 						if (ire1 == ire)
23005 							continue;
23006 						/* skip over deleted ires */
23007 						if (ire1->ire_marks &
23008 						    IRE_MARK_CONDEMNED)
23009 							continue;
23010 						/*
23011 						 * non-loopback ire in our
23012 						 * group: use it for the next
23013 						 * pass in the loop
23014 						 */
23015 						if (ire1->ire_stq != NULL &&
23016 						    ire1_ill->ill_group ==
23017 						    ire_ill->ill_group)
23018 							break;
23019 					}
23020 				}
23021 			} else {
23022 				while (ire1 != NULL && ire1->ire_addr == dst) {
23023 					ire1_ill = ire1->ire_ipif->ipif_ill;
23024 					/*
23025 					 * We can have two broadcast ires on the
23026 					 * same ill in different zones; here
23027 					 * we'll send a copy of the packet on
23028 					 * each ill and the fanout code will
23029 					 * call conn_wantpacket() to check that
23030 					 * the zone has the broadcast address
23031 					 * configured on the ill. If the two
23032 					 * ires are in the same group we only
23033 					 * send one copy up.
23034 					 */
23035 					if (ire1_ill != ire_ill &&
23036 					    (ire1_ill->ill_group == NULL ||
23037 					    ire_ill->ill_group == NULL ||
23038 					    ire1_ill->ill_group !=
23039 					    ire_ill->ill_group)) {
23040 						break;
23041 					}
23042 					ire1 = ire1->ire_next;
23043 				}
23044 			}
23045 		}
23046 		ASSERT(multirt_send == B_FALSE);
23047 		if (ire1 != NULL && ire1->ire_addr == dst) {
23048 			if ((ire->ire_flags & RTF_MULTIRT) &&
23049 			    (ire1->ire_flags & RTF_MULTIRT)) {
23050 				/*
23051 				 * We are in the multirouting case.
23052 				 * The message must be sent at least
23053 				 * on both ires. These ires have been
23054 				 * inserted AFTER the standard ones
23055 				 * in ip_rt_add(). There are thus no
23056 				 * other ire entries for the destination
23057 				 * address in the rest of the bucket
23058 				 * that do not have the RTF_MULTIRT
23059 				 * flag. We don't process a copy
23060 				 * of the message here. This will be
23061 				 * done in the final sending loop.
23062 				 */
23063 				multirt_send = B_TRUE;
23064 			} else {
23065 				next_mp = ip_copymsg(first_mp);
23066 				if (next_mp != NULL)
23067 					IRE_REFHOLD(ire1);
23068 			}
23069 		}
23070 		rw_exit(&ire->ire_bucket->irb_lock);
23071 	}
23072 
23073 	if (stq) {
23074 		/*
23075 		 * A non-NULL send-to queue means this packet is going
23076 		 * out of this machine.
23077 		 */
23078 		out_ill = (ill_t *)stq->q_ptr;
23079 
23080 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23081 		ttl_protocol = ((uint16_t *)ipha)[4];
23082 		/*
23083 		 * We accumulate the pseudo header checksum in cksum.
23084 		 * This is pretty hairy code, so watch close.  One
23085 		 * thing to keep in mind is that UDP and TCP have
23086 		 * stored their respective datagram lengths in their
23087 		 * checksum fields.  This lines things up real nice.
23088 		 */
23089 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23090 		    (src >> 16) + (src & 0xFFFF);
23091 		/*
23092 		 * We assume the udp checksum field contains the
23093 		 * length, so to compute the pseudo header checksum,
23094 		 * all we need is the protocol number and src/dst.
23095 		 */
23096 		/* Provide the checksums for UDP and TCP. */
23097 		if ((PROTO == IPPROTO_TCP) &&
23098 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23099 			/* hlen gets the number of uchar_ts in the IP header */
23100 			hlen = (V_HLEN & 0xF) << 2;
23101 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23102 			IP_STAT(ipst, ip_out_sw_cksum);
23103 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23104 			    LENGTH - hlen);
23105 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23106 			if (*up == 0)
23107 				*up = 0xFFFF;
23108 		} else if (PROTO == IPPROTO_SCTP &&
23109 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23110 			sctp_hdr_t	*sctph;
23111 
23112 			hlen = (V_HLEN & 0xF) << 2;
23113 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23114 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23115 			sctph->sh_chksum = 0;
23116 #ifdef	DEBUG
23117 			if (!skip_sctp_cksum)
23118 #endif
23119 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23120 		} else {
23121 			queue_t *dev_q = stq->q_next;
23122 
23123 			if ((dev_q->q_next || dev_q->q_first) &&
23124 			    !canput(dev_q)) {
23125 			    blocked:
23126 				ipha->ipha_ident = ip_hdr_included;
23127 				/*
23128 				 * If we don't have a conn to apply
23129 				 * backpressure, free the message.
23130 				 * In the ire_send path, we don't know
23131 				 * the position to requeue the packet. Rather
23132 				 * than reorder packets, we just drop this
23133 				 * packet.
23134 				 */
23135 				if (ipst->ips_ip_output_queue &&
23136 				    connp != NULL &&
23137 				    caller != IRE_SEND) {
23138 					if (caller == IP_WSRV) {
23139 						connp->conn_did_putbq = 1;
23140 						(void) putbq(connp->conn_wq,
23141 						    first_mp);
23142 						conn_drain_insert(connp);
23143 						/*
23144 						 * This is the service thread,
23145 						 * and the queue is already
23146 						 * noenabled. The check for
23147 						 * canput and the putbq is not
23148 						 * atomic. So we need to check
23149 						 * again.
23150 						 */
23151 						if (canput(stq->q_next))
23152 							connp->conn_did_putbq
23153 							    = 0;
23154 						IP_STAT(ipst, ip_conn_flputbq);
23155 					} else {
23156 						/*
23157 						 * We are not the service proc.
23158 						 * ip_wsrv will be scheduled or
23159 						 * is already running.
23160 						 */
23161 						(void) putq(connp->conn_wq,
23162 						    first_mp);
23163 					}
23164 				} else {
23165 					out_ill = (ill_t *)stq->q_ptr;
23166 					BUMP_MIB(out_ill->ill_ip_mib,
23167 					    ipIfStatsOutDiscards);
23168 					freemsg(first_mp);
23169 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23170 					    "ip_wput_ire_end: q %p (%S)",
23171 					    q, "discard");
23172 				}
23173 				ire_refrele(ire);
23174 				if (next_mp) {
23175 					ire_refrele(ire1);
23176 					freemsg(next_mp);
23177 				}
23178 				if (conn_outgoing_ill != NULL)
23179 					ill_refrele(conn_outgoing_ill);
23180 				return;
23181 			}
23182 			if ((PROTO == IPPROTO_UDP) &&
23183 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23184 				/*
23185 				 * hlen gets the number of uchar_ts in the
23186 				 * IP header
23187 				 */
23188 				hlen = (V_HLEN & 0xF) << 2;
23189 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23190 				max_frag = ire->ire_max_frag;
23191 				if (*up != 0) {
23192 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23193 					    up, PROTO, hlen, LENGTH, max_frag,
23194 					    ipsec_len, cksum);
23195 					/* Software checksum? */
23196 					if (DB_CKSUMFLAGS(mp) == 0) {
23197 						IP_STAT(ipst, ip_out_sw_cksum);
23198 						IP_STAT_UPDATE(ipst,
23199 						    ip_udp_out_sw_cksum_bytes,
23200 						    LENGTH - hlen);
23201 					}
23202 				}
23203 			}
23204 		}
23205 		/*
23206 		 * Need to do this even when fragmenting. The local
23207 		 * loopback can be done without computing checksums
23208 		 * but forwarding out other interface must be done
23209 		 * after the IP checksum (and ULP checksums) have been
23210 		 * computed.
23211 		 *
23212 		 * NOTE : multicast_forward is set only if this packet
23213 		 * originated from ip_wput. For packets originating from
23214 		 * ip_wput_multicast, it is not set.
23215 		 */
23216 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23217 		    multi_loopback:
23218 			ip2dbg(("ip_wput: multicast, loop %d\n",
23219 			    conn_multicast_loop));
23220 
23221 			/*  Forget header checksum offload */
23222 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23223 
23224 			/*
23225 			 * Local loopback of multicasts?  Check the
23226 			 * ill.
23227 			 *
23228 			 * Note that the loopback function will not come
23229 			 * in through ip_rput - it will only do the
23230 			 * client fanout thus we need to do an mforward
23231 			 * as well.  The is different from the BSD
23232 			 * logic.
23233 			 */
23234 			if (ill != NULL) {
23235 				ilm_t	*ilm;
23236 
23237 				ILM_WALKER_HOLD(ill);
23238 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23239 				    ALL_ZONES);
23240 				ILM_WALKER_RELE(ill);
23241 				if (ilm != NULL) {
23242 					/*
23243 					 * Pass along the virtual output q.
23244 					 * ip_wput_local() will distribute the
23245 					 * packet to all the matching zones,
23246 					 * except the sending zone when
23247 					 * IP_MULTICAST_LOOP is false.
23248 					 */
23249 					ip_multicast_loopback(q, ill, first_mp,
23250 					    conn_multicast_loop ? 0 :
23251 					    IP_FF_NO_MCAST_LOOP, zoneid);
23252 				}
23253 			}
23254 			if (ipha->ipha_ttl == 0) {
23255 				/*
23256 				 * 0 => only to this host i.e. we are
23257 				 * done. We are also done if this was the
23258 				 * loopback interface since it is sufficient
23259 				 * to loopback one copy of a multicast packet.
23260 				 */
23261 				freemsg(first_mp);
23262 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23263 				    "ip_wput_ire_end: q %p (%S)",
23264 				    q, "loopback");
23265 				ire_refrele(ire);
23266 				if (conn_outgoing_ill != NULL)
23267 					ill_refrele(conn_outgoing_ill);
23268 				return;
23269 			}
23270 			/*
23271 			 * ILLF_MULTICAST is checked in ip_newroute
23272 			 * i.e. we don't need to check it here since
23273 			 * all IRE_CACHEs come from ip_newroute.
23274 			 * For multicast traffic, SO_DONTROUTE is interpreted
23275 			 * to mean only send the packet out the interface
23276 			 * (optionally specified with IP_MULTICAST_IF)
23277 			 * and do not forward it out additional interfaces.
23278 			 * RSVP and the rsvp daemon is an example of a
23279 			 * protocol and user level process that
23280 			 * handles it's own routing. Hence, it uses the
23281 			 * SO_DONTROUTE option to accomplish this.
23282 			 */
23283 
23284 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23285 			    ill != NULL) {
23286 				/* Unconditionally redo the checksum */
23287 				ipha->ipha_hdr_checksum = 0;
23288 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23289 
23290 				/*
23291 				 * If this needs to go out secure, we need
23292 				 * to wait till we finish the IPSEC
23293 				 * processing.
23294 				 */
23295 				if (ipsec_len == 0 &&
23296 				    ip_mforward(ill, ipha, mp)) {
23297 					freemsg(first_mp);
23298 					ip1dbg(("ip_wput: mforward failed\n"));
23299 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23300 					    "ip_wput_ire_end: q %p (%S)",
23301 					    q, "mforward failed");
23302 					ire_refrele(ire);
23303 					if (conn_outgoing_ill != NULL)
23304 						ill_refrele(conn_outgoing_ill);
23305 					return;
23306 				}
23307 			}
23308 		}
23309 		max_frag = ire->ire_max_frag;
23310 		cksum += ttl_protocol;
23311 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23312 			/* No fragmentation required for this one. */
23313 			/*
23314 			 * Don't use frag_flag if packet is pre-built or source
23315 			 * routed or if multicast (since multicast packets do
23316 			 * not solicit ICMP "packet too big" messages).
23317 			 */
23318 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23319 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23320 			    !ip_source_route_included(ipha)) &&
23321 			    !CLASSD(ipha->ipha_dst))
23322 				ipha->ipha_fragment_offset_and_flags |=
23323 				    htons(ire->ire_frag_flag);
23324 
23325 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23326 				/* Complete the IP header checksum. */
23327 				cksum += ipha->ipha_ident;
23328 				cksum += (v_hlen_tos_len >> 16)+
23329 				    (v_hlen_tos_len & 0xFFFF);
23330 				cksum += ipha->ipha_fragment_offset_and_flags;
23331 				hlen = (V_HLEN & 0xF) -
23332 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23333 				if (hlen) {
23334 				    checksumoptions:
23335 					/*
23336 					 * Account for the IP Options in the IP
23337 					 * header checksum.
23338 					 */
23339 					up = (uint16_t *)(rptr+
23340 					    IP_SIMPLE_HDR_LENGTH);
23341 					do {
23342 						cksum += up[0];
23343 						cksum += up[1];
23344 						up += 2;
23345 					} while (--hlen);
23346 				}
23347 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23348 				cksum = ~(cksum + (cksum >> 16));
23349 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23350 			}
23351 			if (ipsec_len != 0) {
23352 				ipsec_out_process(q, first_mp, ire, ill_index);
23353 				if (!next_mp) {
23354 					ire_refrele(ire);
23355 					if (conn_outgoing_ill != NULL)
23356 						ill_refrele(conn_outgoing_ill);
23357 					return;
23358 				}
23359 				goto next;
23360 			}
23361 
23362 			/*
23363 			 * multirt_send has already been handled
23364 			 * for broadcast, but not yet for multicast
23365 			 * or IP options.
23366 			 */
23367 			if (next_mp == NULL) {
23368 				if (ire->ire_flags & RTF_MULTIRT) {
23369 					multirt_send = B_TRUE;
23370 				}
23371 			}
23372 
23373 			/*
23374 			 * In most cases, the emission loop below is
23375 			 * entered only once. Only in the case where
23376 			 * the ire holds the RTF_MULTIRT flag, do we loop
23377 			 * to process all RTF_MULTIRT ires in the bucket,
23378 			 * and send the packet through all crossed
23379 			 * RTF_MULTIRT routes.
23380 			 */
23381 			do {
23382 				if (multirt_send) {
23383 					irb_t *irb;
23384 
23385 					irb = ire->ire_bucket;
23386 					ASSERT(irb != NULL);
23387 					/*
23388 					 * We are in a multiple send case,
23389 					 * need to get the next IRE and make
23390 					 * a duplicate of the packet.
23391 					 */
23392 					IRB_REFHOLD(irb);
23393 					for (ire1 = ire->ire_next;
23394 					    ire1 != NULL;
23395 					    ire1 = ire1->ire_next) {
23396 						if (!(ire1->ire_flags &
23397 						    RTF_MULTIRT))
23398 							continue;
23399 						if (ire1->ire_addr !=
23400 						    ire->ire_addr)
23401 							continue;
23402 						if (ire1->ire_marks &
23403 						    (IRE_MARK_CONDEMNED|
23404 							IRE_MARK_HIDDEN))
23405 							continue;
23406 
23407 						/* Got one */
23408 						IRE_REFHOLD(ire1);
23409 						break;
23410 					}
23411 					IRB_REFRELE(irb);
23412 
23413 					if (ire1 != NULL) {
23414 						next_mp = copyb(mp);
23415 						if ((next_mp == NULL) ||
23416 						    ((mp->b_cont != NULL) &&
23417 						    ((next_mp->b_cont =
23418 						    dupmsg(mp->b_cont))
23419 						    == NULL))) {
23420 							freemsg(next_mp);
23421 							next_mp = NULL;
23422 							ire_refrele(ire1);
23423 							ire1 = NULL;
23424 						}
23425 					}
23426 
23427 					/*
23428 					 * Last multiroute ire; don't loop
23429 					 * anymore. The emission is over
23430 					 * and next_mp is NULL.
23431 					 */
23432 					if (ire1 == NULL) {
23433 						multirt_send = B_FALSE;
23434 					}
23435 				}
23436 
23437 				out_ill = ire->ire_ipif->ipif_ill;
23438 				DTRACE_PROBE4(ip4__physical__out__start,
23439 				    ill_t *, NULL,
23440 				    ill_t *, out_ill,
23441 				    ipha_t *, ipha, mblk_t *, mp);
23442 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23443 				    ipst->ips_ipv4firewall_physical_out,
23444 				    NULL, out_ill, ipha, mp, mp, ipst);
23445 				DTRACE_PROBE1(ip4__physical__out__end,
23446 				    mblk_t *, mp);
23447 				if (mp == NULL)
23448 					goto release_ire_and_ill_2;
23449 
23450 				ASSERT(ipsec_len == 0);
23451 				mp->b_prev =
23452 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23453 				DTRACE_PROBE2(ip__xmit__2,
23454 				    mblk_t *, mp, ire_t *, ire);
23455 				pktxmit_state = ip_xmit_v4(mp, ire,
23456 				    NULL, B_TRUE);
23457 				if ((pktxmit_state == SEND_FAILED) ||
23458 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23459 release_ire_and_ill_2:
23460 					if (next_mp) {
23461 						freemsg(next_mp);
23462 						ire_refrele(ire1);
23463 					}
23464 					ire_refrele(ire);
23465 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23466 					    "ip_wput_ire_end: q %p (%S)",
23467 					    q, "discard MDATA");
23468 					if (conn_outgoing_ill != NULL)
23469 						ill_refrele(conn_outgoing_ill);
23470 					return;
23471 				}
23472 
23473 				if (CLASSD(dst)) {
23474 					BUMP_MIB(out_ill->ill_ip_mib,
23475 					    ipIfStatsHCOutMcastPkts);
23476 					UPDATE_MIB(out_ill->ill_ip_mib,
23477 					    ipIfStatsHCOutMcastOctets,
23478 					    LENGTH);
23479 				} else if (ire->ire_type == IRE_BROADCAST) {
23480 					BUMP_MIB(out_ill->ill_ip_mib,
23481 					    ipIfStatsHCOutBcastPkts);
23482 				}
23483 
23484 				if (multirt_send) {
23485 					/*
23486 					 * We are in a multiple send case,
23487 					 * need to re-enter the sending loop
23488 					 * using the next ire.
23489 					 */
23490 					ire_refrele(ire);
23491 					ire = ire1;
23492 					stq = ire->ire_stq;
23493 					mp = next_mp;
23494 					next_mp = NULL;
23495 					ipha = (ipha_t *)mp->b_rptr;
23496 					ill_index = Q_TO_INDEX(stq);
23497 				}
23498 			} while (multirt_send);
23499 
23500 			if (!next_mp) {
23501 				/*
23502 				 * Last copy going out (the ultra-common
23503 				 * case).  Note that we intentionally replicate
23504 				 * the putnext rather than calling it before
23505 				 * the next_mp check in hopes of a little
23506 				 * tail-call action out of the compiler.
23507 				 */
23508 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23509 				    "ip_wput_ire_end: q %p (%S)",
23510 				    q, "last copy out(1)");
23511 				ire_refrele(ire);
23512 				if (conn_outgoing_ill != NULL)
23513 					ill_refrele(conn_outgoing_ill);
23514 				return;
23515 			}
23516 			/* More copies going out below. */
23517 		} else {
23518 			int offset;
23519 		    fragmentit:
23520 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23521 			/*
23522 			 * If this would generate a icmp_frag_needed message,
23523 			 * we need to handle it before we do the IPSEC
23524 			 * processing. Otherwise, we need to strip the IPSEC
23525 			 * headers before we send up the message to the ULPs
23526 			 * which becomes messy and difficult.
23527 			 */
23528 			if (ipsec_len != 0) {
23529 				if ((max_frag < (unsigned int)(LENGTH +
23530 				    ipsec_len)) && (offset & IPH_DF)) {
23531 					out_ill = (ill_t *)stq->q_ptr;
23532 					BUMP_MIB(out_ill->ill_ip_mib,
23533 					    ipIfStatsOutFragFails);
23534 					BUMP_MIB(out_ill->ill_ip_mib,
23535 					    ipIfStatsOutFragReqds);
23536 					ipha->ipha_hdr_checksum = 0;
23537 					ipha->ipha_hdr_checksum =
23538 					    (uint16_t)ip_csum_hdr(ipha);
23539 					icmp_frag_needed(ire->ire_stq, first_mp,
23540 					    max_frag, zoneid, ipst);
23541 					if (!next_mp) {
23542 						ire_refrele(ire);
23543 						if (conn_outgoing_ill != NULL) {
23544 							ill_refrele(
23545 							    conn_outgoing_ill);
23546 						}
23547 						return;
23548 					}
23549 				} else {
23550 					/*
23551 					 * This won't cause a icmp_frag_needed
23552 					 * message. to be generated. Send it on
23553 					 * the wire. Note that this could still
23554 					 * cause fragmentation and all we
23555 					 * do is the generation of the message
23556 					 * to the ULP if needed before IPSEC.
23557 					 */
23558 					if (!next_mp) {
23559 						ipsec_out_process(q, first_mp,
23560 						    ire, ill_index);
23561 						TRACE_2(TR_FAC_IP,
23562 						    TR_IP_WPUT_IRE_END,
23563 						    "ip_wput_ire_end: q %p "
23564 						    "(%S)", q,
23565 						    "last ipsec_out_process");
23566 						ire_refrele(ire);
23567 						if (conn_outgoing_ill != NULL) {
23568 							ill_refrele(
23569 							    conn_outgoing_ill);
23570 						}
23571 						return;
23572 					}
23573 					ipsec_out_process(q, first_mp,
23574 					    ire, ill_index);
23575 				}
23576 			} else {
23577 				/*
23578 				 * Initiate IPPF processing. For
23579 				 * fragmentable packets we finish
23580 				 * all QOS packet processing before
23581 				 * calling:
23582 				 * ip_wput_ire_fragmentit->ip_wput_frag
23583 				 */
23584 
23585 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23586 					ip_process(IPP_LOCAL_OUT, &mp,
23587 					    ill_index);
23588 					if (mp == NULL) {
23589 						out_ill = (ill_t *)stq->q_ptr;
23590 						BUMP_MIB(out_ill->ill_ip_mib,
23591 						    ipIfStatsOutDiscards);
23592 						if (next_mp != NULL) {
23593 							freemsg(next_mp);
23594 							ire_refrele(ire1);
23595 						}
23596 						ire_refrele(ire);
23597 						TRACE_2(TR_FAC_IP,
23598 						    TR_IP_WPUT_IRE_END,
23599 						    "ip_wput_ire: q %p (%S)",
23600 						    q, "discard MDATA");
23601 						if (conn_outgoing_ill != NULL) {
23602 							ill_refrele(
23603 							    conn_outgoing_ill);
23604 						}
23605 						return;
23606 					}
23607 				}
23608 				if (!next_mp) {
23609 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23610 					    "ip_wput_ire_end: q %p (%S)",
23611 					    q, "last fragmentation");
23612 					ip_wput_ire_fragmentit(mp, ire,
23613 					    zoneid, ipst);
23614 					ire_refrele(ire);
23615 					if (conn_outgoing_ill != NULL)
23616 						ill_refrele(conn_outgoing_ill);
23617 					return;
23618 				}
23619 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23620 			}
23621 		}
23622 	} else {
23623 	    nullstq:
23624 		/* A NULL stq means the destination address is local. */
23625 		UPDATE_OB_PKT_COUNT(ire);
23626 		ire->ire_last_used_time = lbolt;
23627 		ASSERT(ire->ire_ipif != NULL);
23628 		if (!next_mp) {
23629 			/*
23630 			 * Is there an "in" and "out" for traffic local
23631 			 * to a host (loopback)?  The code in Solaris doesn't
23632 			 * explicitly draw a line in its code for in vs out,
23633 			 * so we've had to draw a line in the sand: ip_wput_ire
23634 			 * is considered to be the "output" side and
23635 			 * ip_wput_local to be the "input" side.
23636 			 */
23637 			out_ill = ire->ire_ipif->ipif_ill;
23638 
23639 			DTRACE_PROBE4(ip4__loopback__out__start,
23640 			    ill_t *, NULL, ill_t *, out_ill,
23641 			    ipha_t *, ipha, mblk_t *, first_mp);
23642 
23643 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23644 			    ipst->ips_ipv4firewall_loopback_out,
23645 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23646 
23647 			DTRACE_PROBE1(ip4__loopback__out_end,
23648 			    mblk_t *, first_mp);
23649 
23650 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23651 			    "ip_wput_ire_end: q %p (%S)",
23652 			    q, "local address");
23653 
23654 			if (first_mp != NULL)
23655 				ip_wput_local(q, out_ill, ipha,
23656 				    first_mp, ire, 0, ire->ire_zoneid);
23657 			ire_refrele(ire);
23658 			if (conn_outgoing_ill != NULL)
23659 				ill_refrele(conn_outgoing_ill);
23660 			return;
23661 		}
23662 
23663 		out_ill = ire->ire_ipif->ipif_ill;
23664 
23665 		DTRACE_PROBE4(ip4__loopback__out__start,
23666 		    ill_t *, NULL, ill_t *, out_ill,
23667 		    ipha_t *, ipha, mblk_t *, first_mp);
23668 
23669 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23670 		    ipst->ips_ipv4firewall_loopback_out,
23671 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23672 
23673 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23674 
23675 		if (first_mp != NULL)
23676 			ip_wput_local(q, out_ill, ipha,
23677 			    first_mp, ire, 0, ire->ire_zoneid);
23678 	}
23679 next:
23680 	/*
23681 	 * More copies going out to additional interfaces.
23682 	 * ire1 has already been held. We don't need the
23683 	 * "ire" anymore.
23684 	 */
23685 	ire_refrele(ire);
23686 	ire = ire1;
23687 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23688 	mp = next_mp;
23689 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23690 	ill = ire_to_ill(ire);
23691 	first_mp = mp;
23692 	if (ipsec_len != 0) {
23693 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23694 		mp = mp->b_cont;
23695 	}
23696 	dst = ire->ire_addr;
23697 	ipha = (ipha_t *)mp->b_rptr;
23698 	/*
23699 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23700 	 * Restore ipha_ident "no checksum" flag.
23701 	 */
23702 	src = orig_src;
23703 	ipha->ipha_ident = ip_hdr_included;
23704 	goto another;
23705 
23706 #undef	rptr
23707 #undef	Q_TO_INDEX
23708 }
23709 
23710 /*
23711  * Routine to allocate a message that is used to notify the ULP about MDT.
23712  * The caller may provide a pointer to the link-layer MDT capabilities,
23713  * or NULL if MDT is to be disabled on the stream.
23714  */
23715 mblk_t *
23716 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23717 {
23718 	mblk_t *mp;
23719 	ip_mdt_info_t *mdti;
23720 	ill_mdt_capab_t *idst;
23721 
23722 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23723 		DB_TYPE(mp) = M_CTL;
23724 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23725 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23726 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23727 		idst = &(mdti->mdt_capab);
23728 
23729 		/*
23730 		 * If the caller provides us with the capability, copy
23731 		 * it over into our notification message; otherwise
23732 		 * we zero out the capability portion.
23733 		 */
23734 		if (isrc != NULL)
23735 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23736 		else
23737 			bzero((caddr_t)idst, sizeof (*idst));
23738 	}
23739 	return (mp);
23740 }
23741 
23742 /*
23743  * Routine which determines whether MDT can be enabled on the destination
23744  * IRE and IPC combination, and if so, allocates and returns the MDT
23745  * notification mblk that may be used by ULP.  We also check if we need to
23746  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23747  * MDT usage in the past have been lifted.  This gets called during IP
23748  * and ULP binding.
23749  */
23750 mblk_t *
23751 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23752     ill_mdt_capab_t *mdt_cap)
23753 {
23754 	mblk_t *mp;
23755 	boolean_t rc = B_FALSE;
23756 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23757 
23758 	ASSERT(dst_ire != NULL);
23759 	ASSERT(connp != NULL);
23760 	ASSERT(mdt_cap != NULL);
23761 
23762 	/*
23763 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23764 	 * Multidata, which is handled in tcp_multisend().  This
23765 	 * is the reason why we do all these checks here, to ensure
23766 	 * that we don't enable Multidata for the cases which we
23767 	 * can't handle at the moment.
23768 	 */
23769 	do {
23770 		/* Only do TCP at the moment */
23771 		if (connp->conn_ulp != IPPROTO_TCP)
23772 			break;
23773 
23774 		/*
23775 		 * IPSEC outbound policy present?  Note that we get here
23776 		 * after calling ipsec_conn_cache_policy() where the global
23777 		 * policy checking is performed.  conn_latch will be
23778 		 * non-NULL as long as there's a policy defined,
23779 		 * i.e. conn_out_enforce_policy may be NULL in such case
23780 		 * when the connection is non-secure, and hence we check
23781 		 * further if the latch refers to an outbound policy.
23782 		 */
23783 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23784 			break;
23785 
23786 		/* CGTP (multiroute) is enabled? */
23787 		if (dst_ire->ire_flags & RTF_MULTIRT)
23788 			break;
23789 
23790 		/* Outbound IPQoS enabled? */
23791 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23792 			/*
23793 			 * In this case, we disable MDT for this and all
23794 			 * future connections going over the interface.
23795 			 */
23796 			mdt_cap->ill_mdt_on = 0;
23797 			break;
23798 		}
23799 
23800 		/* socket option(s) present? */
23801 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23802 			break;
23803 
23804 		rc = B_TRUE;
23805 	/* CONSTCOND */
23806 	} while (0);
23807 
23808 	/* Remember the result */
23809 	connp->conn_mdt_ok = rc;
23810 
23811 	if (!rc)
23812 		return (NULL);
23813 	else if (!mdt_cap->ill_mdt_on) {
23814 		/*
23815 		 * If MDT has been previously turned off in the past, and we
23816 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23817 		 * then enable it for this interface.
23818 		 */
23819 		mdt_cap->ill_mdt_on = 1;
23820 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23821 		    "interface %s\n", ill_name));
23822 	}
23823 
23824 	/* Allocate the MDT info mblk */
23825 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23826 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23827 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23828 		return (NULL);
23829 	}
23830 	return (mp);
23831 }
23832 
23833 /*
23834  * Routine to allocate a message that is used to notify the ULP about LSO.
23835  * The caller may provide a pointer to the link-layer LSO capabilities,
23836  * or NULL if LSO is to be disabled on the stream.
23837  */
23838 mblk_t *
23839 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23840 {
23841 	mblk_t *mp;
23842 	ip_lso_info_t *lsoi;
23843 	ill_lso_capab_t *idst;
23844 
23845 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23846 		DB_TYPE(mp) = M_CTL;
23847 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23848 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23849 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23850 		idst = &(lsoi->lso_capab);
23851 
23852 		/*
23853 		 * If the caller provides us with the capability, copy
23854 		 * it over into our notification message; otherwise
23855 		 * we zero out the capability portion.
23856 		 */
23857 		if (isrc != NULL)
23858 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23859 		else
23860 			bzero((caddr_t)idst, sizeof (*idst));
23861 	}
23862 	return (mp);
23863 }
23864 
23865 /*
23866  * Routine which determines whether LSO can be enabled on the destination
23867  * IRE and IPC combination, and if so, allocates and returns the LSO
23868  * notification mblk that may be used by ULP.  We also check if we need to
23869  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23870  * LSO usage in the past have been lifted.  This gets called during IP
23871  * and ULP binding.
23872  */
23873 mblk_t *
23874 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23875     ill_lso_capab_t *lso_cap)
23876 {
23877 	mblk_t *mp;
23878 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23879 
23880 	ASSERT(dst_ire != NULL);
23881 	ASSERT(connp != NULL);
23882 	ASSERT(lso_cap != NULL);
23883 
23884 	connp->conn_lso_ok = B_TRUE;
23885 
23886 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23887 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23888 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23889 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23890 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23891 		connp->conn_lso_ok = B_FALSE;
23892 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23893 			/*
23894 			 * Disable LSO for this and all future connections going
23895 			 * over the interface.
23896 			 */
23897 			lso_cap->ill_lso_on = 0;
23898 		}
23899 	}
23900 
23901 	if (!connp->conn_lso_ok)
23902 		return (NULL);
23903 	else if (!lso_cap->ill_lso_on) {
23904 		/*
23905 		 * If LSO has been previously turned off in the past, and we
23906 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23907 		 * then enable it for this interface.
23908 		 */
23909 		lso_cap->ill_lso_on = 1;
23910 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23911 		    ill_name));
23912 	}
23913 
23914 	/* Allocate the LSO info mblk */
23915 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23916 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23917 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23918 
23919 	return (mp);
23920 }
23921 
23922 /*
23923  * Create destination address attribute, and fill it with the physical
23924  * destination address and SAP taken from the template DL_UNITDATA_REQ
23925  * message block.
23926  */
23927 boolean_t
23928 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23929 {
23930 	dl_unitdata_req_t *dlurp;
23931 	pattr_t *pa;
23932 	pattrinfo_t pa_info;
23933 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23934 	uint_t das_len, das_off;
23935 
23936 	ASSERT(dlmp != NULL);
23937 
23938 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23939 	das_len = dlurp->dl_dest_addr_length;
23940 	das_off = dlurp->dl_dest_addr_offset;
23941 
23942 	pa_info.type = PATTR_DSTADDRSAP;
23943 	pa_info.len = sizeof (**das) + das_len - 1;
23944 
23945 	/* create and associate the attribute */
23946 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23947 	if (pa != NULL) {
23948 		ASSERT(*das != NULL);
23949 		(*das)->addr_is_group = 0;
23950 		(*das)->addr_len = (uint8_t)das_len;
23951 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23952 	}
23953 
23954 	return (pa != NULL);
23955 }
23956 
23957 /*
23958  * Create hardware checksum attribute and fill it with the values passed.
23959  */
23960 boolean_t
23961 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23962     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23963 {
23964 	pattr_t *pa;
23965 	pattrinfo_t pa_info;
23966 
23967 	ASSERT(mmd != NULL);
23968 
23969 	pa_info.type = PATTR_HCKSUM;
23970 	pa_info.len = sizeof (pattr_hcksum_t);
23971 
23972 	/* create and associate the attribute */
23973 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23974 	if (pa != NULL) {
23975 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23976 
23977 		hck->hcksum_start_offset = start_offset;
23978 		hck->hcksum_stuff_offset = stuff_offset;
23979 		hck->hcksum_end_offset = end_offset;
23980 		hck->hcksum_flags = flags;
23981 	}
23982 	return (pa != NULL);
23983 }
23984 
23985 /*
23986  * Create zerocopy attribute and fill it with the specified flags
23987  */
23988 boolean_t
23989 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23990 {
23991 	pattr_t *pa;
23992 	pattrinfo_t pa_info;
23993 
23994 	ASSERT(mmd != NULL);
23995 	pa_info.type = PATTR_ZCOPY;
23996 	pa_info.len = sizeof (pattr_zcopy_t);
23997 
23998 	/* create and associate the attribute */
23999 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24000 	if (pa != NULL) {
24001 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
24002 
24003 		zcopy->zcopy_flags = flags;
24004 	}
24005 	return (pa != NULL);
24006 }
24007 
24008 /*
24009  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
24010  * block chain. We could rewrite to handle arbitrary message block chains but
24011  * that would make the code complicated and slow. Right now there three
24012  * restrictions:
24013  *
24014  *   1. The first message block must contain the complete IP header and
24015  *	at least 1 byte of payload data.
24016  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
24017  *	so that we can use a single Multidata message.
24018  *   3. No frag must be distributed over two or more message blocks so
24019  *	that we don't need more than two packet descriptors per frag.
24020  *
24021  * The above restrictions allow us to support userland applications (which
24022  * will send down a single message block) and NFS over UDP (which will
24023  * send down a chain of at most three message blocks).
24024  *
24025  * We also don't use MDT for payloads with less than or equal to
24026  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24027  */
24028 boolean_t
24029 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24030 {
24031 	int	blocks;
24032 	ssize_t	total, missing, size;
24033 
24034 	ASSERT(mp != NULL);
24035 	ASSERT(hdr_len > 0);
24036 
24037 	size = MBLKL(mp) - hdr_len;
24038 	if (size <= 0)
24039 		return (B_FALSE);
24040 
24041 	/* The first mblk contains the header and some payload. */
24042 	blocks = 1;
24043 	total = size;
24044 	size %= len;
24045 	missing = (size == 0) ? 0 : (len - size);
24046 	mp = mp->b_cont;
24047 
24048 	while (mp != NULL) {
24049 		/*
24050 		 * Give up if we encounter a zero length message block.
24051 		 * In practice, this should rarely happen and therefore
24052 		 * not worth the trouble of freeing and re-linking the
24053 		 * mblk from the chain to handle such case.
24054 		 */
24055 		if ((size = MBLKL(mp)) == 0)
24056 			return (B_FALSE);
24057 
24058 		/* Too many payload buffers for a single Multidata message? */
24059 		if (++blocks > MULTIDATA_MAX_PBUFS)
24060 			return (B_FALSE);
24061 
24062 		total += size;
24063 		/* Is a frag distributed over two or more message blocks? */
24064 		if (missing > size)
24065 			return (B_FALSE);
24066 		size -= missing;
24067 
24068 		size %= len;
24069 		missing = (size == 0) ? 0 : (len - size);
24070 
24071 		mp = mp->b_cont;
24072 	}
24073 
24074 	return (total > ip_wput_frag_mdt_min);
24075 }
24076 
24077 /*
24078  * Outbound IPv4 fragmentation routine using MDT.
24079  */
24080 static void
24081 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24082     uint32_t frag_flag, int offset)
24083 {
24084 	ipha_t		*ipha_orig;
24085 	int		i1, ip_data_end;
24086 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24087 	mblk_t		*hdr_mp, *md_mp = NULL;
24088 	unsigned char	*hdr_ptr, *pld_ptr;
24089 	multidata_t	*mmd;
24090 	ip_pdescinfo_t	pdi;
24091 	ill_t		*ill;
24092 	ip_stack_t	*ipst = ire->ire_ipst;
24093 
24094 	ASSERT(DB_TYPE(mp) == M_DATA);
24095 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24096 
24097 	ill = ire_to_ill(ire);
24098 	ASSERT(ill != NULL);
24099 
24100 	ipha_orig = (ipha_t *)mp->b_rptr;
24101 	mp->b_rptr += sizeof (ipha_t);
24102 
24103 	/* Calculate how many packets we will send out */
24104 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24105 	pkts = (i1 + len - 1) / len;
24106 	ASSERT(pkts > 1);
24107 
24108 	/* Allocate a message block which will hold all the IP Headers. */
24109 	wroff = ipst->ips_ip_wroff_extra;
24110 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24111 
24112 	i1 = pkts * hdr_chunk_len;
24113 	/*
24114 	 * Create the header buffer, Multidata and destination address
24115 	 * and SAP attribute that should be associated with it.
24116 	 */
24117 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24118 	    ((hdr_mp->b_wptr += i1),
24119 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24120 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24121 		freemsg(mp);
24122 		if (md_mp == NULL) {
24123 			freemsg(hdr_mp);
24124 		} else {
24125 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24126 			freemsg(md_mp);
24127 		}
24128 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24129 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24130 		return;
24131 	}
24132 	IP_STAT(ipst, ip_frag_mdt_allocd);
24133 
24134 	/*
24135 	 * Add a payload buffer to the Multidata; this operation must not
24136 	 * fail, or otherwise our logic in this routine is broken.  There
24137 	 * is no memory allocation done by the routine, so any returned
24138 	 * failure simply tells us that we've done something wrong.
24139 	 *
24140 	 * A failure tells us that either we're adding the same payload
24141 	 * buffer more than once, or we're trying to add more buffers than
24142 	 * allowed.  None of the above cases should happen, and we panic
24143 	 * because either there's horrible heap corruption, and/or
24144 	 * programming mistake.
24145 	 */
24146 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24147 		goto pbuf_panic;
24148 
24149 	hdr_ptr = hdr_mp->b_rptr;
24150 	pld_ptr = mp->b_rptr;
24151 
24152 	/* Establish the ending byte offset, based on the starting offset. */
24153 	offset <<= 3;
24154 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24155 	    IP_SIMPLE_HDR_LENGTH;
24156 
24157 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24158 
24159 	while (pld_ptr < mp->b_wptr) {
24160 		ipha_t		*ipha;
24161 		uint16_t	offset_and_flags;
24162 		uint16_t	ip_len;
24163 		int		error;
24164 
24165 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24166 		ipha = (ipha_t *)(hdr_ptr + wroff);
24167 		ASSERT(OK_32PTR(ipha));
24168 		*ipha = *ipha_orig;
24169 
24170 		if (ip_data_end - offset > len) {
24171 			offset_and_flags = IPH_MF;
24172 		} else {
24173 			/*
24174 			 * Last frag. Set len to the length of this last piece.
24175 			 */
24176 			len = ip_data_end - offset;
24177 			/* A frag of a frag might have IPH_MF non-zero */
24178 			offset_and_flags =
24179 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24180 			    IPH_MF;
24181 		}
24182 		offset_and_flags |= (uint16_t)(offset >> 3);
24183 		offset_and_flags |= (uint16_t)frag_flag;
24184 		/* Store the offset and flags in the IP header. */
24185 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24186 
24187 		/* Store the length in the IP header. */
24188 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24189 		ipha->ipha_length = htons(ip_len);
24190 
24191 		/*
24192 		 * Set the IP header checksum.  Note that mp is just
24193 		 * the header, so this is easy to pass to ip_csum.
24194 		 */
24195 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24196 
24197 		/*
24198 		 * Record offset and size of header and data of the next packet
24199 		 * in the multidata message.
24200 		 */
24201 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24202 		PDESC_PLD_INIT(&pdi);
24203 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24204 		ASSERT(i1 > 0);
24205 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24206 		if (i1 == len) {
24207 			pld_ptr += len;
24208 		} else {
24209 			i1 = len - i1;
24210 			mp = mp->b_cont;
24211 			ASSERT(mp != NULL);
24212 			ASSERT(MBLKL(mp) >= i1);
24213 			/*
24214 			 * Attach the next payload message block to the
24215 			 * multidata message.
24216 			 */
24217 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24218 				goto pbuf_panic;
24219 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24220 			pld_ptr = mp->b_rptr + i1;
24221 		}
24222 
24223 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24224 		    KM_NOSLEEP)) == NULL) {
24225 			/*
24226 			 * Any failure other than ENOMEM indicates that we
24227 			 * have passed in invalid pdesc info or parameters
24228 			 * to mmd_addpdesc, which must not happen.
24229 			 *
24230 			 * EINVAL is a result of failure on boundary checks
24231 			 * against the pdesc info contents.  It should not
24232 			 * happen, and we panic because either there's
24233 			 * horrible heap corruption, and/or programming
24234 			 * mistake.
24235 			 */
24236 			if (error != ENOMEM) {
24237 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24238 				    "pdesc logic error detected for "
24239 				    "mmd %p pinfo %p (%d)\n",
24240 				    (void *)mmd, (void *)&pdi, error);
24241 				/* NOTREACHED */
24242 			}
24243 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24244 			/* Free unattached payload message blocks as well */
24245 			md_mp->b_cont = mp->b_cont;
24246 			goto free_mmd;
24247 		}
24248 
24249 		/* Advance fragment offset. */
24250 		offset += len;
24251 
24252 		/* Advance to location for next header in the buffer. */
24253 		hdr_ptr += hdr_chunk_len;
24254 
24255 		/* Did we reach the next payload message block? */
24256 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24257 			mp = mp->b_cont;
24258 			/*
24259 			 * Attach the next message block with payload
24260 			 * data to the multidata message.
24261 			 */
24262 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24263 				goto pbuf_panic;
24264 			pld_ptr = mp->b_rptr;
24265 		}
24266 	}
24267 
24268 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24269 	ASSERT(mp->b_wptr == pld_ptr);
24270 
24271 	/* Update IP statistics */
24272 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24273 
24274 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24275 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24276 
24277 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24278 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24279 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24280 
24281 	if (pkt_type == OB_PKT) {
24282 		ire->ire_ob_pkt_count += pkts;
24283 		if (ire->ire_ipif != NULL)
24284 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24285 	} else {
24286 		/*
24287 		 * The type is IB_PKT in the forwarding path and in
24288 		 * the mobile IP case when the packet is being reverse-
24289 		 * tunneled to the home agent.
24290 		 */
24291 		ire->ire_ib_pkt_count += pkts;
24292 		ASSERT(!IRE_IS_LOCAL(ire));
24293 		if (ire->ire_type & IRE_BROADCAST) {
24294 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24295 		} else {
24296 			UPDATE_MIB(ill->ill_ip_mib,
24297 			    ipIfStatsHCOutForwDatagrams, pkts);
24298 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24299 		}
24300 	}
24301 	ire->ire_last_used_time = lbolt;
24302 	/* Send it down */
24303 	putnext(ire->ire_stq, md_mp);
24304 	return;
24305 
24306 pbuf_panic:
24307 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24308 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24309 	    pbuf_idx);
24310 	/* NOTREACHED */
24311 }
24312 
24313 /*
24314  * Outbound IP fragmentation routine.
24315  *
24316  * NOTE : This routine does not ire_refrele the ire that is passed in
24317  * as the argument.
24318  */
24319 static void
24320 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24321     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24322 {
24323 	int		i1;
24324 	mblk_t		*ll_hdr_mp;
24325 	int 		ll_hdr_len;
24326 	int		hdr_len;
24327 	mblk_t		*hdr_mp;
24328 	ipha_t		*ipha;
24329 	int		ip_data_end;
24330 	int		len;
24331 	mblk_t		*mp = mp_orig, *mp1;
24332 	int		offset;
24333 	queue_t		*q;
24334 	uint32_t	v_hlen_tos_len;
24335 	mblk_t		*first_mp;
24336 	boolean_t	mctl_present;
24337 	ill_t		*ill;
24338 	ill_t		*out_ill;
24339 	mblk_t		*xmit_mp;
24340 	mblk_t		*carve_mp;
24341 	ire_t		*ire1 = NULL;
24342 	ire_t		*save_ire = NULL;
24343 	mblk_t  	*next_mp = NULL;
24344 	boolean_t	last_frag = B_FALSE;
24345 	boolean_t	multirt_send = B_FALSE;
24346 	ire_t		*first_ire = NULL;
24347 	irb_t		*irb = NULL;
24348 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24349 
24350 	ill = ire_to_ill(ire);
24351 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24352 
24353 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24354 
24355 	/*
24356 	 * IPSEC does not allow hw accelerated packets to be fragmented
24357 	 * This check is made in ip_wput_ipsec_out prior to coming here
24358 	 * via ip_wput_ire_fragmentit.
24359 	 *
24360 	 * If at this point we have an ire whose ARP request has not
24361 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24362 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24363 	 * This packet and all fragmentable packets for this ire will
24364 	 * continue to get dropped while ire_nce->nce_state remains in
24365 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24366 	 * ND_REACHABLE, all subsquent large packets for this ire will
24367 	 * get fragemented and sent out by this function.
24368 	 */
24369 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24370 		/* If nce_state is ND_INITIAL, trigger ARP query */
24371 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24372 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24373 		    " -  dropping packet\n"));
24374 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24375 		freemsg(mp);
24376 		return;
24377 	}
24378 
24379 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24380 	    "ip_wput_frag_start:");
24381 
24382 	if (mp->b_datap->db_type == M_CTL) {
24383 		first_mp = mp;
24384 		mp_orig = mp = mp->b_cont;
24385 		mctl_present = B_TRUE;
24386 	} else {
24387 		first_mp = mp;
24388 		mctl_present = B_FALSE;
24389 	}
24390 
24391 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24392 	ipha = (ipha_t *)mp->b_rptr;
24393 
24394 	/*
24395 	 * If the Don't Fragment flag is on, generate an ICMP destination
24396 	 * unreachable, fragmentation needed.
24397 	 */
24398 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24399 	if (offset & IPH_DF) {
24400 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24401 		/*
24402 		 * Need to compute hdr checksum if called from ip_wput_ire.
24403 		 * Note that ip_rput_forward verifies the checksum before
24404 		 * calling this routine so in that case this is a noop.
24405 		 */
24406 		ipha->ipha_hdr_checksum = 0;
24407 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24408 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24409 		    ipst);
24410 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24411 		    "ip_wput_frag_end:(%S)",
24412 		    "don't fragment");
24413 		return;
24414 	}
24415 	if (mctl_present)
24416 		freeb(first_mp);
24417 	/*
24418 	 * Establish the starting offset.  May not be zero if we are fragging
24419 	 * a fragment that is being forwarded.
24420 	 */
24421 	offset = offset & IPH_OFFSET;
24422 
24423 	/* TODO why is this test needed? */
24424 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24425 	if (((max_frag - LENGTH) & ~7) < 8) {
24426 		/* TODO: notify ulp somehow */
24427 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24428 		freemsg(mp);
24429 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24430 		    "ip_wput_frag_end:(%S)",
24431 		    "len < 8");
24432 		return;
24433 	}
24434 
24435 	hdr_len = (V_HLEN & 0xF) << 2;
24436 
24437 	ipha->ipha_hdr_checksum = 0;
24438 
24439 	/*
24440 	 * Establish the number of bytes maximum per frag, after putting
24441 	 * in the header.
24442 	 */
24443 	len = (max_frag - hdr_len) & ~7;
24444 
24445 	/* Check if we can use MDT to send out the frags. */
24446 	ASSERT(!IRE_IS_LOCAL(ire));
24447 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24448 	    ipst->ips_ip_multidata_outbound &&
24449 	    !(ire->ire_flags & RTF_MULTIRT) &&
24450 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24451 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24452 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24453 		ASSERT(ill->ill_mdt_capab != NULL);
24454 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24455 			/*
24456 			 * If MDT has been previously turned off in the past,
24457 			 * and we currently can do MDT (due to IPQoS policy
24458 			 * removal, etc.) then enable it for this interface.
24459 			 */
24460 			ill->ill_mdt_capab->ill_mdt_on = 1;
24461 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24462 			    ill->ill_name));
24463 		}
24464 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24465 		    offset);
24466 		return;
24467 	}
24468 
24469 	/* Get a copy of the header for the trailing frags */
24470 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24471 	if (!hdr_mp) {
24472 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24473 		freemsg(mp);
24474 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24475 		    "ip_wput_frag_end:(%S)",
24476 		    "couldn't copy hdr");
24477 		return;
24478 	}
24479 	if (DB_CRED(mp) != NULL)
24480 		mblk_setcred(hdr_mp, DB_CRED(mp));
24481 
24482 	/* Store the starting offset, with the MoreFrags flag. */
24483 	i1 = offset | IPH_MF | frag_flag;
24484 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24485 
24486 	/* Establish the ending byte offset, based on the starting offset. */
24487 	offset <<= 3;
24488 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24489 
24490 	/* Store the length of the first fragment in the IP header. */
24491 	i1 = len + hdr_len;
24492 	ASSERT(i1 <= IP_MAXPACKET);
24493 	ipha->ipha_length = htons((uint16_t)i1);
24494 
24495 	/*
24496 	 * Compute the IP header checksum for the first frag.  We have to
24497 	 * watch out that we stop at the end of the header.
24498 	 */
24499 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24500 
24501 	/*
24502 	 * Now carve off the first frag.  Note that this will include the
24503 	 * original IP header.
24504 	 */
24505 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24506 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24507 		freeb(hdr_mp);
24508 		freemsg(mp_orig);
24509 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24510 		    "ip_wput_frag_end:(%S)",
24511 		    "couldn't carve first");
24512 		return;
24513 	}
24514 
24515 	/*
24516 	 * Multirouting case. Each fragment is replicated
24517 	 * via all non-condemned RTF_MULTIRT routes
24518 	 * currently resolved.
24519 	 * We ensure that first_ire is the first RTF_MULTIRT
24520 	 * ire in the bucket.
24521 	 */
24522 	if (ire->ire_flags & RTF_MULTIRT) {
24523 		irb = ire->ire_bucket;
24524 		ASSERT(irb != NULL);
24525 
24526 		multirt_send = B_TRUE;
24527 
24528 		/* Make sure we do not omit any multiroute ire. */
24529 		IRB_REFHOLD(irb);
24530 		for (first_ire = irb->irb_ire;
24531 		    first_ire != NULL;
24532 		    first_ire = first_ire->ire_next) {
24533 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24534 			    (first_ire->ire_addr == ire->ire_addr) &&
24535 			    !(first_ire->ire_marks &
24536 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24537 				break;
24538 		}
24539 
24540 		if (first_ire != NULL) {
24541 			if (first_ire != ire) {
24542 				IRE_REFHOLD(first_ire);
24543 				/*
24544 				 * Do not release the ire passed in
24545 				 * as the argument.
24546 				 */
24547 				ire = first_ire;
24548 			} else {
24549 				first_ire = NULL;
24550 			}
24551 		}
24552 		IRB_REFRELE(irb);
24553 
24554 		/*
24555 		 * Save the first ire; we will need to restore it
24556 		 * for the trailing frags.
24557 		 * We REFHOLD save_ire, as each iterated ire will be
24558 		 * REFRELEd.
24559 		 */
24560 		save_ire = ire;
24561 		IRE_REFHOLD(save_ire);
24562 	}
24563 
24564 	/*
24565 	 * First fragment emission loop.
24566 	 * In most cases, the emission loop below is entered only
24567 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24568 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24569 	 * bucket, and send the fragment through all crossed
24570 	 * RTF_MULTIRT routes.
24571 	 */
24572 	do {
24573 		if (ire->ire_flags & RTF_MULTIRT) {
24574 			/*
24575 			 * We are in a multiple send case, need to get
24576 			 * the next ire and make a copy of the packet.
24577 			 * ire1 holds here the next ire to process in the
24578 			 * bucket. If multirouting is expected,
24579 			 * any non-RTF_MULTIRT ire that has the
24580 			 * right destination address is ignored.
24581 			 *
24582 			 * We have to take into account the MTU of
24583 			 * each walked ire. max_frag is set by the
24584 			 * the caller and generally refers to
24585 			 * the primary ire entry. Here we ensure that
24586 			 * no route with a lower MTU will be used, as
24587 			 * fragments are carved once for all ires,
24588 			 * then replicated.
24589 			 */
24590 			ASSERT(irb != NULL);
24591 			IRB_REFHOLD(irb);
24592 			for (ire1 = ire->ire_next;
24593 			    ire1 != NULL;
24594 			    ire1 = ire1->ire_next) {
24595 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24596 					continue;
24597 				if (ire1->ire_addr != ire->ire_addr)
24598 					continue;
24599 				if (ire1->ire_marks &
24600 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24601 					continue;
24602 				/*
24603 				 * Ensure we do not exceed the MTU
24604 				 * of the next route.
24605 				 */
24606 				if (ire1->ire_max_frag < max_frag) {
24607 					ip_multirt_bad_mtu(ire1, max_frag);
24608 					continue;
24609 				}
24610 
24611 				/* Got one. */
24612 				IRE_REFHOLD(ire1);
24613 				break;
24614 			}
24615 			IRB_REFRELE(irb);
24616 
24617 			if (ire1 != NULL) {
24618 				next_mp = copyb(mp);
24619 				if ((next_mp == NULL) ||
24620 				    ((mp->b_cont != NULL) &&
24621 				    ((next_mp->b_cont =
24622 				    dupmsg(mp->b_cont)) == NULL))) {
24623 					freemsg(next_mp);
24624 					next_mp = NULL;
24625 					ire_refrele(ire1);
24626 					ire1 = NULL;
24627 				}
24628 			}
24629 
24630 			/* Last multiroute ire; don't loop anymore. */
24631 			if (ire1 == NULL) {
24632 				multirt_send = B_FALSE;
24633 			}
24634 		}
24635 
24636 		ll_hdr_len = 0;
24637 		LOCK_IRE_FP_MP(ire);
24638 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24639 		if (ll_hdr_mp != NULL) {
24640 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24641 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24642 		} else {
24643 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24644 		}
24645 
24646 		/* If there is a transmit header, get a copy for this frag. */
24647 		/*
24648 		 * TODO: should check db_ref before calling ip_carve_mp since
24649 		 * it might give us a dup.
24650 		 */
24651 		if (!ll_hdr_mp) {
24652 			/* No xmit header. */
24653 			xmit_mp = mp;
24654 
24655 		/* We have a link-layer header that can fit in our mblk. */
24656 		} else if (mp->b_datap->db_ref == 1 &&
24657 		    ll_hdr_len != 0 &&
24658 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24659 			/* M_DATA fastpath */
24660 			mp->b_rptr -= ll_hdr_len;
24661 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24662 			xmit_mp = mp;
24663 
24664 		/* Corner case if copyb has failed */
24665 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24666 			UNLOCK_IRE_FP_MP(ire);
24667 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24668 			freeb(hdr_mp);
24669 			freemsg(mp);
24670 			freemsg(mp_orig);
24671 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24672 			    "ip_wput_frag_end:(%S)",
24673 			    "discard");
24674 
24675 			if (multirt_send) {
24676 				ASSERT(ire1);
24677 				ASSERT(next_mp);
24678 
24679 				freemsg(next_mp);
24680 				ire_refrele(ire1);
24681 			}
24682 			if (save_ire != NULL)
24683 				IRE_REFRELE(save_ire);
24684 
24685 			if (first_ire != NULL)
24686 				ire_refrele(first_ire);
24687 			return;
24688 
24689 		/*
24690 		 * Case of res_mp OR the fastpath mp can't fit
24691 		 * in the mblk
24692 		 */
24693 		} else {
24694 			xmit_mp->b_cont = mp;
24695 			if (DB_CRED(mp) != NULL)
24696 				mblk_setcred(xmit_mp, DB_CRED(mp));
24697 			/*
24698 			 * Get priority marking, if any.
24699 			 * We propagate the CoS marking from the
24700 			 * original packet that went to QoS processing
24701 			 * in ip_wput_ire to the newly carved mp.
24702 			 */
24703 			if (DB_TYPE(xmit_mp) == M_DATA)
24704 				xmit_mp->b_band = mp->b_band;
24705 		}
24706 		UNLOCK_IRE_FP_MP(ire);
24707 
24708 		q = ire->ire_stq;
24709 		out_ill = (ill_t *)q->q_ptr;
24710 
24711 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24712 
24713 		DTRACE_PROBE4(ip4__physical__out__start,
24714 		    ill_t *, NULL, ill_t *, out_ill,
24715 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24716 
24717 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24718 		    ipst->ips_ipv4firewall_physical_out,
24719 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24720 
24721 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24722 
24723 		if (xmit_mp != NULL) {
24724 			putnext(q, xmit_mp);
24725 
24726 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24727 			UPDATE_MIB(out_ill->ill_ip_mib,
24728 			    ipIfStatsHCOutOctets, i1);
24729 
24730 			if (pkt_type != OB_PKT) {
24731 				/*
24732 				 * Update the packet count and MIB stats
24733 				 * of trailing RTF_MULTIRT ires.
24734 				 */
24735 				UPDATE_OB_PKT_COUNT(ire);
24736 				BUMP_MIB(out_ill->ill_ip_mib,
24737 				    ipIfStatsOutFragReqds);
24738 			}
24739 		}
24740 
24741 		if (multirt_send) {
24742 			/*
24743 			 * We are in a multiple send case; look for
24744 			 * the next ire and re-enter the loop.
24745 			 */
24746 			ASSERT(ire1);
24747 			ASSERT(next_mp);
24748 			/* REFRELE the current ire before looping */
24749 			ire_refrele(ire);
24750 			ire = ire1;
24751 			ire1 = NULL;
24752 			mp = next_mp;
24753 			next_mp = NULL;
24754 		}
24755 	} while (multirt_send);
24756 
24757 	ASSERT(ire1 == NULL);
24758 
24759 	/* Restore the original ire; we need it for the trailing frags */
24760 	if (save_ire != NULL) {
24761 		/* REFRELE the last iterated ire */
24762 		ire_refrele(ire);
24763 		/* save_ire has been REFHOLDed */
24764 		ire = save_ire;
24765 		save_ire = NULL;
24766 		q = ire->ire_stq;
24767 	}
24768 
24769 	if (pkt_type == OB_PKT) {
24770 		UPDATE_OB_PKT_COUNT(ire);
24771 	} else {
24772 		out_ill = (ill_t *)q->q_ptr;
24773 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24774 		UPDATE_IB_PKT_COUNT(ire);
24775 	}
24776 
24777 	/* Advance the offset to the second frag starting point. */
24778 	offset += len;
24779 	/*
24780 	 * Update hdr_len from the copied header - there might be less options
24781 	 * in the later fragments.
24782 	 */
24783 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24784 	/* Loop until done. */
24785 	for (;;) {
24786 		uint16_t	offset_and_flags;
24787 		uint16_t	ip_len;
24788 
24789 		if (ip_data_end - offset > len) {
24790 			/*
24791 			 * Carve off the appropriate amount from the original
24792 			 * datagram.
24793 			 */
24794 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24795 				mp = NULL;
24796 				break;
24797 			}
24798 			/*
24799 			 * More frags after this one.  Get another copy
24800 			 * of the header.
24801 			 */
24802 			if (carve_mp->b_datap->db_ref == 1 &&
24803 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24804 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24805 				/* Inline IP header */
24806 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24807 				    hdr_mp->b_rptr;
24808 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24809 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24810 				mp = carve_mp;
24811 			} else {
24812 				if (!(mp = copyb(hdr_mp))) {
24813 					freemsg(carve_mp);
24814 					break;
24815 				}
24816 				/* Get priority marking, if any. */
24817 				mp->b_band = carve_mp->b_band;
24818 				mp->b_cont = carve_mp;
24819 			}
24820 			ipha = (ipha_t *)mp->b_rptr;
24821 			offset_and_flags = IPH_MF;
24822 		} else {
24823 			/*
24824 			 * Last frag.  Consume the header. Set len to
24825 			 * the length of this last piece.
24826 			 */
24827 			len = ip_data_end - offset;
24828 
24829 			/*
24830 			 * Carve off the appropriate amount from the original
24831 			 * datagram.
24832 			 */
24833 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24834 				mp = NULL;
24835 				break;
24836 			}
24837 			if (carve_mp->b_datap->db_ref == 1 &&
24838 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24839 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24840 				/* Inline IP header */
24841 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24842 				    hdr_mp->b_rptr;
24843 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24844 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24845 				mp = carve_mp;
24846 				freeb(hdr_mp);
24847 				hdr_mp = mp;
24848 			} else {
24849 				mp = hdr_mp;
24850 				/* Get priority marking, if any. */
24851 				mp->b_band = carve_mp->b_band;
24852 				mp->b_cont = carve_mp;
24853 			}
24854 			ipha = (ipha_t *)mp->b_rptr;
24855 			/* A frag of a frag might have IPH_MF non-zero */
24856 			offset_and_flags =
24857 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24858 			    IPH_MF;
24859 		}
24860 		offset_and_flags |= (uint16_t)(offset >> 3);
24861 		offset_and_flags |= (uint16_t)frag_flag;
24862 		/* Store the offset and flags in the IP header. */
24863 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24864 
24865 		/* Store the length in the IP header. */
24866 		ip_len = (uint16_t)(len + hdr_len);
24867 		ipha->ipha_length = htons(ip_len);
24868 
24869 		/*
24870 		 * Set the IP header checksum.	Note that mp is just
24871 		 * the header, so this is easy to pass to ip_csum.
24872 		 */
24873 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24874 
24875 		/* Attach a transmit header, if any, and ship it. */
24876 		if (pkt_type == OB_PKT) {
24877 			UPDATE_OB_PKT_COUNT(ire);
24878 		} else {
24879 			out_ill = (ill_t *)q->q_ptr;
24880 			BUMP_MIB(out_ill->ill_ip_mib,
24881 			    ipIfStatsHCOutForwDatagrams);
24882 			UPDATE_IB_PKT_COUNT(ire);
24883 		}
24884 
24885 		if (ire->ire_flags & RTF_MULTIRT) {
24886 			irb = ire->ire_bucket;
24887 			ASSERT(irb != NULL);
24888 
24889 			multirt_send = B_TRUE;
24890 
24891 			/*
24892 			 * Save the original ire; we will need to restore it
24893 			 * for the tailing frags.
24894 			 */
24895 			save_ire = ire;
24896 			IRE_REFHOLD(save_ire);
24897 		}
24898 		/*
24899 		 * Emission loop for this fragment, similar
24900 		 * to what is done for the first fragment.
24901 		 */
24902 		do {
24903 			if (multirt_send) {
24904 				/*
24905 				 * We are in a multiple send case, need to get
24906 				 * the next ire and make a copy of the packet.
24907 				 */
24908 				ASSERT(irb != NULL);
24909 				IRB_REFHOLD(irb);
24910 				for (ire1 = ire->ire_next;
24911 				    ire1 != NULL;
24912 				    ire1 = ire1->ire_next) {
24913 					if (!(ire1->ire_flags & RTF_MULTIRT))
24914 						continue;
24915 					if (ire1->ire_addr != ire->ire_addr)
24916 						continue;
24917 					if (ire1->ire_marks &
24918 					    (IRE_MARK_CONDEMNED|
24919 						IRE_MARK_HIDDEN))
24920 						continue;
24921 					/*
24922 					 * Ensure we do not exceed the MTU
24923 					 * of the next route.
24924 					 */
24925 					if (ire1->ire_max_frag < max_frag) {
24926 						ip_multirt_bad_mtu(ire1,
24927 						    max_frag);
24928 						continue;
24929 					}
24930 
24931 					/* Got one. */
24932 					IRE_REFHOLD(ire1);
24933 					break;
24934 				}
24935 				IRB_REFRELE(irb);
24936 
24937 				if (ire1 != NULL) {
24938 					next_mp = copyb(mp);
24939 					if ((next_mp == NULL) ||
24940 					    ((mp->b_cont != NULL) &&
24941 					    ((next_mp->b_cont =
24942 					    dupmsg(mp->b_cont)) == NULL))) {
24943 						freemsg(next_mp);
24944 						next_mp = NULL;
24945 						ire_refrele(ire1);
24946 						ire1 = NULL;
24947 					}
24948 				}
24949 
24950 				/* Last multiroute ire; don't loop anymore. */
24951 				if (ire1 == NULL) {
24952 					multirt_send = B_FALSE;
24953 				}
24954 			}
24955 
24956 			/* Update transmit header */
24957 			ll_hdr_len = 0;
24958 			LOCK_IRE_FP_MP(ire);
24959 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24960 			if (ll_hdr_mp != NULL) {
24961 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24962 				ll_hdr_len = MBLKL(ll_hdr_mp);
24963 			} else {
24964 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24965 			}
24966 
24967 			if (!ll_hdr_mp) {
24968 				xmit_mp = mp;
24969 
24970 			/*
24971 			 * We have link-layer header that can fit in
24972 			 * our mblk.
24973 			 */
24974 			} else if (mp->b_datap->db_ref == 1 &&
24975 			    ll_hdr_len != 0 &&
24976 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24977 				/* M_DATA fastpath */
24978 				mp->b_rptr -= ll_hdr_len;
24979 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24980 				    ll_hdr_len);
24981 				xmit_mp = mp;
24982 
24983 			/*
24984 			 * Case of res_mp OR the fastpath mp can't fit
24985 			 * in the mblk
24986 			 */
24987 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24988 				xmit_mp->b_cont = mp;
24989 				if (DB_CRED(mp) != NULL)
24990 					mblk_setcred(xmit_mp, DB_CRED(mp));
24991 				/* Get priority marking, if any. */
24992 				if (DB_TYPE(xmit_mp) == M_DATA)
24993 					xmit_mp->b_band = mp->b_band;
24994 
24995 			/* Corner case if copyb failed */
24996 			} else {
24997 				/*
24998 				 * Exit both the replication and
24999 				 * fragmentation loops.
25000 				 */
25001 				UNLOCK_IRE_FP_MP(ire);
25002 				goto drop_pkt;
25003 			}
25004 			UNLOCK_IRE_FP_MP(ire);
25005 
25006 			mp1 = mp;
25007 			out_ill = (ill_t *)q->q_ptr;
25008 
25009 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
25010 
25011 			DTRACE_PROBE4(ip4__physical__out__start,
25012 			    ill_t *, NULL, ill_t *, out_ill,
25013 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25014 
25015 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25016 			    ipst->ips_ipv4firewall_physical_out,
25017 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25018 
25019 			DTRACE_PROBE1(ip4__physical__out__end,
25020 			    mblk_t *, xmit_mp);
25021 
25022 			if (mp != mp1 && hdr_mp == mp1)
25023 				hdr_mp = mp;
25024 			if (mp != mp1 && mp_orig == mp1)
25025 				mp_orig = mp;
25026 
25027 			if (xmit_mp != NULL) {
25028 				putnext(q, xmit_mp);
25029 
25030 				BUMP_MIB(out_ill->ill_ip_mib,
25031 				    ipIfStatsHCOutTransmits);
25032 				UPDATE_MIB(out_ill->ill_ip_mib,
25033 				    ipIfStatsHCOutOctets, ip_len);
25034 
25035 				if (pkt_type != OB_PKT) {
25036 					/*
25037 					 * Update the packet count of trailing
25038 					 * RTF_MULTIRT ires.
25039 					 */
25040 					UPDATE_OB_PKT_COUNT(ire);
25041 				}
25042 			}
25043 
25044 			/* All done if we just consumed the hdr_mp. */
25045 			if (mp == hdr_mp) {
25046 				last_frag = B_TRUE;
25047 				BUMP_MIB(out_ill->ill_ip_mib,
25048 				    ipIfStatsOutFragOKs);
25049 			}
25050 
25051 			if (multirt_send) {
25052 				/*
25053 				 * We are in a multiple send case; look for
25054 				 * the next ire and re-enter the loop.
25055 				 */
25056 				ASSERT(ire1);
25057 				ASSERT(next_mp);
25058 				/* REFRELE the current ire before looping */
25059 				ire_refrele(ire);
25060 				ire = ire1;
25061 				ire1 = NULL;
25062 				q = ire->ire_stq;
25063 				mp = next_mp;
25064 				next_mp = NULL;
25065 			}
25066 		} while (multirt_send);
25067 		/*
25068 		 * Restore the original ire; we need it for the
25069 		 * trailing frags
25070 		 */
25071 		if (save_ire != NULL) {
25072 			ASSERT(ire1 == NULL);
25073 			/* REFRELE the last iterated ire */
25074 			ire_refrele(ire);
25075 			/* save_ire has been REFHOLDed */
25076 			ire = save_ire;
25077 			q = ire->ire_stq;
25078 			save_ire = NULL;
25079 		}
25080 
25081 		if (last_frag) {
25082 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25083 			    "ip_wput_frag_end:(%S)",
25084 			    "consumed hdr_mp");
25085 
25086 			if (first_ire != NULL)
25087 				ire_refrele(first_ire);
25088 			return;
25089 		}
25090 		/* Otherwise, advance and loop. */
25091 		offset += len;
25092 	}
25093 
25094 drop_pkt:
25095 	/* Clean up following allocation failure. */
25096 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25097 	freemsg(mp);
25098 	if (mp != hdr_mp)
25099 		freeb(hdr_mp);
25100 	if (mp != mp_orig)
25101 		freemsg(mp_orig);
25102 
25103 	if (save_ire != NULL)
25104 		IRE_REFRELE(save_ire);
25105 	if (first_ire != NULL)
25106 		ire_refrele(first_ire);
25107 
25108 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25109 	    "ip_wput_frag_end:(%S)",
25110 	    "end--alloc failure");
25111 }
25112 
25113 /*
25114  * Copy the header plus those options which have the copy bit set
25115  */
25116 static mblk_t *
25117 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25118 {
25119 	mblk_t	*mp;
25120 	uchar_t	*up;
25121 
25122 	/*
25123 	 * Quick check if we need to look for options without the copy bit
25124 	 * set
25125 	 */
25126 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25127 	if (!mp)
25128 		return (mp);
25129 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25130 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25131 		bcopy(rptr, mp->b_rptr, hdr_len);
25132 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25133 		return (mp);
25134 	}
25135 	up  = mp->b_rptr;
25136 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25137 	up += IP_SIMPLE_HDR_LENGTH;
25138 	rptr += IP_SIMPLE_HDR_LENGTH;
25139 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25140 	while (hdr_len > 0) {
25141 		uint32_t optval;
25142 		uint32_t optlen;
25143 
25144 		optval = *rptr;
25145 		if (optval == IPOPT_EOL)
25146 			break;
25147 		if (optval == IPOPT_NOP)
25148 			optlen = 1;
25149 		else
25150 			optlen = rptr[1];
25151 		if (optval & IPOPT_COPY) {
25152 			bcopy(rptr, up, optlen);
25153 			up += optlen;
25154 		}
25155 		rptr += optlen;
25156 		hdr_len -= optlen;
25157 	}
25158 	/*
25159 	 * Make sure that we drop an even number of words by filling
25160 	 * with EOL to the next word boundary.
25161 	 */
25162 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25163 	    hdr_len & 0x3; hdr_len++)
25164 		*up++ = IPOPT_EOL;
25165 	mp->b_wptr = up;
25166 	/* Update header length */
25167 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25168 	return (mp);
25169 }
25170 
25171 /*
25172  * Delivery to local recipients including fanout to multiple recipients.
25173  * Does not do checksumming of UDP/TCP.
25174  * Note: q should be the read side queue for either the ill or conn.
25175  * Note: rq should be the read side q for the lower (ill) stream.
25176  * We don't send packets to IPPF processing, thus the last argument
25177  * to all the fanout calls are B_FALSE.
25178  */
25179 void
25180 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25181     int fanout_flags, zoneid_t zoneid)
25182 {
25183 	uint32_t	protocol;
25184 	mblk_t		*first_mp;
25185 	boolean_t	mctl_present;
25186 	int		ire_type;
25187 #define	rptr	((uchar_t *)ipha)
25188 	ip_stack_t	*ipst = ill->ill_ipst;
25189 
25190 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25191 	    "ip_wput_local_start: q %p", q);
25192 
25193 	if (ire != NULL) {
25194 		ire_type = ire->ire_type;
25195 	} else {
25196 		/*
25197 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25198 		 * packet is not multicast, we can't tell the ire type.
25199 		 */
25200 		ASSERT(CLASSD(ipha->ipha_dst));
25201 		ire_type = IRE_BROADCAST;
25202 	}
25203 
25204 	first_mp = mp;
25205 	if (first_mp->b_datap->db_type == M_CTL) {
25206 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25207 		if (!io->ipsec_out_secure) {
25208 			/*
25209 			 * This ipsec_out_t was allocated in ip_wput
25210 			 * for multicast packets to store the ill_index.
25211 			 * As this is being delivered locally, we don't
25212 			 * need this anymore.
25213 			 */
25214 			mp = first_mp->b_cont;
25215 			freeb(first_mp);
25216 			first_mp = mp;
25217 			mctl_present = B_FALSE;
25218 		} else {
25219 			/*
25220 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25221 			 * security properties for the looped-back packet.
25222 			 */
25223 			mctl_present = B_TRUE;
25224 			mp = first_mp->b_cont;
25225 			ASSERT(mp != NULL);
25226 			ipsec_out_to_in(first_mp);
25227 		}
25228 	} else {
25229 		mctl_present = B_FALSE;
25230 	}
25231 
25232 	DTRACE_PROBE4(ip4__loopback__in__start,
25233 	    ill_t *, ill, ill_t *, NULL,
25234 	    ipha_t *, ipha, mblk_t *, first_mp);
25235 
25236 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25237 	    ipst->ips_ipv4firewall_loopback_in,
25238 	    ill, NULL, ipha, first_mp, mp, ipst);
25239 
25240 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25241 
25242 	if (first_mp == NULL)
25243 		return;
25244 
25245 	ipst->ips_loopback_packets++;
25246 
25247 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25248 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25249 	if (!IS_SIMPLE_IPH(ipha)) {
25250 		ip_wput_local_options(ipha, ipst);
25251 	}
25252 
25253 	protocol = ipha->ipha_protocol;
25254 	switch (protocol) {
25255 	case IPPROTO_ICMP: {
25256 		ire_t		*ire_zone;
25257 		ilm_t		*ilm;
25258 		mblk_t		*mp1;
25259 		zoneid_t	last_zoneid;
25260 
25261 		if (CLASSD(ipha->ipha_dst) &&
25262 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
25263 			ASSERT(ire_type == IRE_BROADCAST);
25264 			/*
25265 			 * In the multicast case, applications may have joined
25266 			 * the group from different zones, so we need to deliver
25267 			 * the packet to each of them. Loop through the
25268 			 * multicast memberships structures (ilm) on the receive
25269 			 * ill and send a copy of the packet up each matching
25270 			 * one. However, we don't do this for multicasts sent on
25271 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25272 			 * they must stay in the sender's zone.
25273 			 *
25274 			 * ilm_add_v6() ensures that ilms in the same zone are
25275 			 * contiguous in the ill_ilm list. We use this property
25276 			 * to avoid sending duplicates needed when two
25277 			 * applications in the same zone join the same group on
25278 			 * different logical interfaces: we ignore the ilm if
25279 			 * it's zoneid is the same as the last matching one.
25280 			 * In addition, the sending of the packet for
25281 			 * ire_zoneid is delayed until all of the other ilms
25282 			 * have been exhausted.
25283 			 */
25284 			last_zoneid = -1;
25285 			ILM_WALKER_HOLD(ill);
25286 			for (ilm = ill->ill_ilm; ilm != NULL;
25287 			    ilm = ilm->ilm_next) {
25288 				if ((ilm->ilm_flags & ILM_DELETED) ||
25289 				    ipha->ipha_dst != ilm->ilm_addr ||
25290 				    ilm->ilm_zoneid == last_zoneid ||
25291 				    ilm->ilm_zoneid == zoneid ||
25292 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25293 					continue;
25294 				mp1 = ip_copymsg(first_mp);
25295 				if (mp1 == NULL)
25296 					continue;
25297 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25298 				    mctl_present, B_FALSE, ill,
25299 				    ilm->ilm_zoneid);
25300 				last_zoneid = ilm->ilm_zoneid;
25301 			}
25302 			ILM_WALKER_RELE(ill);
25303 			/*
25304 			 * Loopback case: the sending endpoint has
25305 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25306 			 * dispatch the multicast packet to the sending zone.
25307 			 */
25308 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25309 				freemsg(first_mp);
25310 				return;
25311 			}
25312 		} else if (ire_type == IRE_BROADCAST) {
25313 			/*
25314 			 * In the broadcast case, there may be many zones
25315 			 * which need a copy of the packet delivered to them.
25316 			 * There is one IRE_BROADCAST per broadcast address
25317 			 * and per zone; we walk those using a helper function.
25318 			 * In addition, the sending of the packet for zoneid is
25319 			 * delayed until all of the other ires have been
25320 			 * processed.
25321 			 */
25322 			IRB_REFHOLD(ire->ire_bucket);
25323 			ire_zone = NULL;
25324 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25325 			    ire)) != NULL) {
25326 				mp1 = ip_copymsg(first_mp);
25327 				if (mp1 == NULL)
25328 					continue;
25329 
25330 				UPDATE_IB_PKT_COUNT(ire_zone);
25331 				ire_zone->ire_last_used_time = lbolt;
25332 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25333 				    mctl_present, B_FALSE, ill,
25334 				    ire_zone->ire_zoneid);
25335 			}
25336 			IRB_REFRELE(ire->ire_bucket);
25337 		}
25338 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25339 		    0, mctl_present, B_FALSE, ill, zoneid);
25340 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25341 		    "ip_wput_local_end: q %p (%S)",
25342 		    q, "icmp");
25343 		return;
25344 	}
25345 	case IPPROTO_IGMP:
25346 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25347 			/* Bad packet - discarded by igmp_input */
25348 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25349 			    "ip_wput_local_end: q %p (%S)",
25350 			    q, "igmp_input--bad packet");
25351 			if (mctl_present)
25352 				freeb(first_mp);
25353 			return;
25354 		}
25355 		/*
25356 		 * igmp_input() may have returned the pulled up message.
25357 		 * So first_mp and ipha need to be reinitialized.
25358 		 */
25359 		ipha = (ipha_t *)mp->b_rptr;
25360 		if (mctl_present)
25361 			first_mp->b_cont = mp;
25362 		else
25363 			first_mp = mp;
25364 		/* deliver to local raw users */
25365 		break;
25366 	case IPPROTO_ENCAP:
25367 		/*
25368 		 * This case is covered by either ip_fanout_proto, or by
25369 		 * the above security processing for self-tunneled packets.
25370 		 */
25371 		break;
25372 	case IPPROTO_UDP: {
25373 		uint16_t	*up;
25374 		uint32_t	ports;
25375 
25376 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25377 		    UDP_PORTS_OFFSET);
25378 		/* Force a 'valid' checksum. */
25379 		up[3] = 0;
25380 
25381 		ports = *(uint32_t *)up;
25382 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25383 		    (ire_type == IRE_BROADCAST),
25384 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25385 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25386 		    ill, zoneid);
25387 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25388 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25389 		return;
25390 	}
25391 	case IPPROTO_TCP: {
25392 
25393 		/*
25394 		 * For TCP, discard broadcast packets.
25395 		 */
25396 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25397 			freemsg(first_mp);
25398 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25399 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25400 			return;
25401 		}
25402 
25403 		if (mp->b_datap->db_type == M_DATA) {
25404 			/*
25405 			 * M_DATA mblk, so init mblk (chain) for no struio().
25406 			 */
25407 			mblk_t	*mp1 = mp;
25408 
25409 			do
25410 				mp1->b_datap->db_struioflag = 0;
25411 			while ((mp1 = mp1->b_cont) != NULL);
25412 		}
25413 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25414 		    <= mp->b_wptr);
25415 		ip_fanout_tcp(q, first_mp, ill, ipha,
25416 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25417 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25418 		    mctl_present, B_FALSE, zoneid);
25419 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25420 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25421 		return;
25422 	}
25423 	case IPPROTO_SCTP:
25424 	{
25425 		uint32_t	ports;
25426 
25427 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25428 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25429 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25430 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25431 		return;
25432 	}
25433 
25434 	default:
25435 		break;
25436 	}
25437 	/*
25438 	 * Find a client for some other protocol.  We give
25439 	 * copies to multiple clients, if more than one is
25440 	 * bound.
25441 	 */
25442 	ip_fanout_proto(q, first_mp, ill, ipha,
25443 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25444 	    mctl_present, B_FALSE, ill, zoneid);
25445 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25446 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25447 #undef	rptr
25448 }
25449 
25450 /*
25451  * Update any source route, record route, or timestamp options.
25452  * Check that we are at end of strict source route.
25453  * The options have been sanity checked by ip_wput_options().
25454  */
25455 static void
25456 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25457 {
25458 	ipoptp_t	opts;
25459 	uchar_t		*opt;
25460 	uint8_t		optval;
25461 	uint8_t		optlen;
25462 	ipaddr_t	dst;
25463 	uint32_t	ts;
25464 	ire_t		*ire;
25465 	timestruc_t	now;
25466 
25467 	ip2dbg(("ip_wput_local_options\n"));
25468 	for (optval = ipoptp_first(&opts, ipha);
25469 	    optval != IPOPT_EOL;
25470 	    optval = ipoptp_next(&opts)) {
25471 		opt = opts.ipoptp_cur;
25472 		optlen = opts.ipoptp_len;
25473 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25474 		switch (optval) {
25475 			uint32_t off;
25476 		case IPOPT_SSRR:
25477 		case IPOPT_LSRR:
25478 			off = opt[IPOPT_OFFSET];
25479 			off--;
25480 			if (optlen < IP_ADDR_LEN ||
25481 			    off > optlen - IP_ADDR_LEN) {
25482 				/* End of source route */
25483 				break;
25484 			}
25485 			/*
25486 			 * This will only happen if two consecutive entries
25487 			 * in the source route contains our address or if
25488 			 * it is a packet with a loose source route which
25489 			 * reaches us before consuming the whole source route
25490 			 */
25491 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25492 			if (optval == IPOPT_SSRR) {
25493 				return;
25494 			}
25495 			/*
25496 			 * Hack: instead of dropping the packet truncate the
25497 			 * source route to what has been used by filling the
25498 			 * rest with IPOPT_NOP.
25499 			 */
25500 			opt[IPOPT_OLEN] = (uint8_t)off;
25501 			while (off < optlen) {
25502 				opt[off++] = IPOPT_NOP;
25503 			}
25504 			break;
25505 		case IPOPT_RR:
25506 			off = opt[IPOPT_OFFSET];
25507 			off--;
25508 			if (optlen < IP_ADDR_LEN ||
25509 			    off > optlen - IP_ADDR_LEN) {
25510 				/* No more room - ignore */
25511 				ip1dbg((
25512 				    "ip_wput_forward_options: end of RR\n"));
25513 				break;
25514 			}
25515 			dst = htonl(INADDR_LOOPBACK);
25516 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25517 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25518 			break;
25519 		case IPOPT_TS:
25520 			/* Insert timestamp if there is romm */
25521 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25522 			case IPOPT_TS_TSONLY:
25523 				off = IPOPT_TS_TIMELEN;
25524 				break;
25525 			case IPOPT_TS_PRESPEC:
25526 			case IPOPT_TS_PRESPEC_RFC791:
25527 				/* Verify that the address matched */
25528 				off = opt[IPOPT_OFFSET] - 1;
25529 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25530 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25531 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25532 				    ipst);
25533 				if (ire == NULL) {
25534 					/* Not for us */
25535 					break;
25536 				}
25537 				ire_refrele(ire);
25538 				/* FALLTHRU */
25539 			case IPOPT_TS_TSANDADDR:
25540 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25541 				break;
25542 			default:
25543 				/*
25544 				 * ip_*put_options should have already
25545 				 * dropped this packet.
25546 				 */
25547 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25548 				    "unknown IT - bug in ip_wput_options?\n");
25549 				return;	/* Keep "lint" happy */
25550 			}
25551 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25552 				/* Increase overflow counter */
25553 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25554 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25555 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25556 				    (off << 4);
25557 				break;
25558 			}
25559 			off = opt[IPOPT_OFFSET] - 1;
25560 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25561 			case IPOPT_TS_PRESPEC:
25562 			case IPOPT_TS_PRESPEC_RFC791:
25563 			case IPOPT_TS_TSANDADDR:
25564 				dst = htonl(INADDR_LOOPBACK);
25565 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25566 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25567 				/* FALLTHRU */
25568 			case IPOPT_TS_TSONLY:
25569 				off = opt[IPOPT_OFFSET] - 1;
25570 				/* Compute # of milliseconds since midnight */
25571 				gethrestime(&now);
25572 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25573 				    now.tv_nsec / (NANOSEC / MILLISEC);
25574 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25575 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25576 				break;
25577 			}
25578 			break;
25579 		}
25580 	}
25581 }
25582 
25583 /*
25584  * Send out a multicast packet on interface ipif.
25585  * The sender does not have an conn.
25586  * Caller verifies that this isn't a PHYI_LOOPBACK.
25587  */
25588 void
25589 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25590 {
25591 	ipha_t	*ipha;
25592 	ire_t	*ire;
25593 	ipaddr_t	dst;
25594 	mblk_t		*first_mp;
25595 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25596 
25597 	/* igmp_sendpkt always allocates a ipsec_out_t */
25598 	ASSERT(mp->b_datap->db_type == M_CTL);
25599 	ASSERT(!ipif->ipif_isv6);
25600 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
25601 
25602 	first_mp = mp;
25603 	mp = first_mp->b_cont;
25604 	ASSERT(mp->b_datap->db_type == M_DATA);
25605 	ipha = (ipha_t *)mp->b_rptr;
25606 
25607 	/*
25608 	 * Find an IRE which matches the destination and the outgoing
25609 	 * queue (i.e. the outgoing interface.)
25610 	 */
25611 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25612 		dst = ipif->ipif_pp_dst_addr;
25613 	else
25614 		dst = ipha->ipha_dst;
25615 	/*
25616 	 * The source address has already been initialized by the
25617 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25618 	 * be sufficient rather than MATCH_IRE_IPIF.
25619 	 *
25620 	 * This function is used for sending IGMP packets. We need
25621 	 * to make sure that we send the packet out of the interface
25622 	 * (ipif->ipif_ill) where we joined the group. This is to
25623 	 * prevent from switches doing IGMP snooping to send us multicast
25624 	 * packets for a given group on the interface we have joined.
25625 	 * If we can't find an ire, igmp_sendpkt has already initialized
25626 	 * ipsec_out_attach_if so that this will not be load spread in
25627 	 * ip_newroute_ipif.
25628 	 */
25629 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25630 	    MATCH_IRE_ILL, ipst);
25631 	if (!ire) {
25632 		/*
25633 		 * Mark this packet to make it be delivered to
25634 		 * ip_wput_ire after the new ire has been
25635 		 * created.
25636 		 */
25637 		mp->b_prev = NULL;
25638 		mp->b_next = NULL;
25639 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25640 		    zoneid, &zero_info);
25641 		return;
25642 	}
25643 
25644 	/*
25645 	 * Honor the RTF_SETSRC flag; this is the only case
25646 	 * where we force this addr whatever the current src addr is,
25647 	 * because this address is set by igmp_sendpkt(), and
25648 	 * cannot be specified by any user.
25649 	 */
25650 	if (ire->ire_flags & RTF_SETSRC) {
25651 		ipha->ipha_src = ire->ire_src_addr;
25652 	}
25653 
25654 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25655 }
25656 
25657 /*
25658  * NOTE : This function does not ire_refrele the ire argument passed in.
25659  *
25660  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25661  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25662  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25663  * the ire_lock to access the nce_fp_mp in this case.
25664  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25665  * prepending a fastpath message IPQoS processing must precede it, we also set
25666  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25667  * (IPQoS might have set the b_band for CoS marking).
25668  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25669  * must follow it so that IPQoS can mark the dl_priority field for CoS
25670  * marking, if needed.
25671  */
25672 static mblk_t *
25673 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25674 {
25675 	uint_t	hlen;
25676 	ipha_t *ipha;
25677 	mblk_t *mp1;
25678 	boolean_t qos_done = B_FALSE;
25679 	uchar_t	*ll_hdr;
25680 	ip_stack_t	*ipst = ire->ire_ipst;
25681 
25682 #define	rptr	((uchar_t *)ipha)
25683 
25684 	ipha = (ipha_t *)mp->b_rptr;
25685 	hlen = 0;
25686 	LOCK_IRE_FP_MP(ire);
25687 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25688 		ASSERT(DB_TYPE(mp1) == M_DATA);
25689 		/* Initiate IPPF processing */
25690 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25691 			UNLOCK_IRE_FP_MP(ire);
25692 			ip_process(proc, &mp, ill_index);
25693 			if (mp == NULL)
25694 				return (NULL);
25695 
25696 			ipha = (ipha_t *)mp->b_rptr;
25697 			LOCK_IRE_FP_MP(ire);
25698 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25699 				qos_done = B_TRUE;
25700 				goto no_fp_mp;
25701 			}
25702 			ASSERT(DB_TYPE(mp1) == M_DATA);
25703 		}
25704 		hlen = MBLKL(mp1);
25705 		/*
25706 		 * Check if we have enough room to prepend fastpath
25707 		 * header
25708 		 */
25709 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25710 			ll_hdr = rptr - hlen;
25711 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25712 			/*
25713 			 * Set the b_rptr to the start of the link layer
25714 			 * header
25715 			 */
25716 			mp->b_rptr = ll_hdr;
25717 			mp1 = mp;
25718 		} else {
25719 			mp1 = copyb(mp1);
25720 			if (mp1 == NULL)
25721 				goto unlock_err;
25722 			mp1->b_band = mp->b_band;
25723 			mp1->b_cont = mp;
25724 			/*
25725 			 * certain system generated traffic may not
25726 			 * have cred/label in ip header block. This
25727 			 * is true even for a labeled system. But for
25728 			 * labeled traffic, inherit the label in the
25729 			 * new header.
25730 			 */
25731 			if (DB_CRED(mp) != NULL)
25732 				mblk_setcred(mp1, DB_CRED(mp));
25733 			/*
25734 			 * XXX disable ICK_VALID and compute checksum
25735 			 * here; can happen if nce_fp_mp changes and
25736 			 * it can't be copied now due to insufficient
25737 			 * space. (unlikely, fp mp can change, but it
25738 			 * does not increase in length)
25739 			 */
25740 		}
25741 		UNLOCK_IRE_FP_MP(ire);
25742 	} else {
25743 no_fp_mp:
25744 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25745 		if (mp1 == NULL) {
25746 unlock_err:
25747 			UNLOCK_IRE_FP_MP(ire);
25748 			freemsg(mp);
25749 			return (NULL);
25750 		}
25751 		UNLOCK_IRE_FP_MP(ire);
25752 		mp1->b_cont = mp;
25753 		/*
25754 		 * certain system generated traffic may not
25755 		 * have cred/label in ip header block. This
25756 		 * is true even for a labeled system. But for
25757 		 * labeled traffic, inherit the label in the
25758 		 * new header.
25759 		 */
25760 		if (DB_CRED(mp) != NULL)
25761 			mblk_setcred(mp1, DB_CRED(mp));
25762 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25763 			ip_process(proc, &mp1, ill_index);
25764 			if (mp1 == NULL)
25765 				return (NULL);
25766 		}
25767 	}
25768 	return (mp1);
25769 #undef rptr
25770 }
25771 
25772 /*
25773  * Finish the outbound IPsec processing for an IPv6 packet. This function
25774  * is called from ipsec_out_process() if the IPsec packet was processed
25775  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25776  * asynchronously.
25777  */
25778 void
25779 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25780     ire_t *ire_arg)
25781 {
25782 	in6_addr_t *v6dstp;
25783 	ire_t *ire;
25784 	mblk_t *mp;
25785 	ip6_t *ip6h1;
25786 	uint_t	ill_index;
25787 	ipsec_out_t *io;
25788 	boolean_t attach_if, hwaccel;
25789 	uint32_t flags = IP6_NO_IPPOLICY;
25790 	int match_flags;
25791 	zoneid_t zoneid;
25792 	boolean_t ill_need_rele = B_FALSE;
25793 	boolean_t ire_need_rele = B_FALSE;
25794 	ip_stack_t	*ipst;
25795 
25796 	mp = ipsec_mp->b_cont;
25797 	ip6h1 = (ip6_t *)mp->b_rptr;
25798 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25799 	ASSERT(io->ipsec_out_ns != NULL);
25800 	ipst = io->ipsec_out_ns->netstack_ip;
25801 	ill_index = io->ipsec_out_ill_index;
25802 	if (io->ipsec_out_reachable) {
25803 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25804 	}
25805 	attach_if = io->ipsec_out_attach_if;
25806 	hwaccel = io->ipsec_out_accelerated;
25807 	zoneid = io->ipsec_out_zoneid;
25808 	ASSERT(zoneid != ALL_ZONES);
25809 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25810 	/* Multicast addresses should have non-zero ill_index. */
25811 	v6dstp = &ip6h->ip6_dst;
25812 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25813 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25814 	ASSERT(!attach_if || ill_index != 0);
25815 	if (ill_index != 0) {
25816 		if (ill == NULL) {
25817 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25818 			    B_TRUE, ipst);
25819 
25820 			/* Failure case frees things for us. */
25821 			if (ill == NULL)
25822 				return;
25823 
25824 			ill_need_rele = B_TRUE;
25825 		}
25826 		/*
25827 		 * If this packet needs to go out on a particular interface
25828 		 * honor it.
25829 		 */
25830 		if (attach_if) {
25831 			match_flags = MATCH_IRE_ILL;
25832 
25833 			/*
25834 			 * Check if we need an ire that will not be
25835 			 * looked up by anybody else i.e. HIDDEN.
25836 			 */
25837 			if (ill_is_probeonly(ill)) {
25838 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25839 			}
25840 		}
25841 	}
25842 	ASSERT(mp != NULL);
25843 
25844 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25845 		boolean_t unspec_src;
25846 		ipif_t	*ipif;
25847 
25848 		/*
25849 		 * Use the ill_index to get the right ill.
25850 		 */
25851 		unspec_src = io->ipsec_out_unspec_src;
25852 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25853 		if (ipif == NULL) {
25854 			if (ill_need_rele)
25855 				ill_refrele(ill);
25856 			freemsg(ipsec_mp);
25857 			return;
25858 		}
25859 
25860 		if (ire_arg != NULL) {
25861 			ire = ire_arg;
25862 		} else {
25863 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25864 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25865 			ire_need_rele = B_TRUE;
25866 		}
25867 		if (ire != NULL) {
25868 			ipif_refrele(ipif);
25869 			/*
25870 			 * XXX Do the multicast forwarding now, as the IPSEC
25871 			 * processing has been done.
25872 			 */
25873 			goto send;
25874 		}
25875 
25876 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25877 		mp->b_prev = NULL;
25878 		mp->b_next = NULL;
25879 
25880 		/*
25881 		 * If the IPsec packet was processed asynchronously,
25882 		 * drop it now.
25883 		 */
25884 		if (q == NULL) {
25885 			if (ill_need_rele)
25886 				ill_refrele(ill);
25887 			freemsg(ipsec_mp);
25888 			return;
25889 		}
25890 
25891 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25892 		    unspec_src, zoneid);
25893 		ipif_refrele(ipif);
25894 	} else {
25895 		if (attach_if) {
25896 			ipif_t	*ipif;
25897 
25898 			ipif = ipif_get_next_ipif(NULL, ill);
25899 			if (ipif == NULL) {
25900 				if (ill_need_rele)
25901 					ill_refrele(ill);
25902 				freemsg(ipsec_mp);
25903 				return;
25904 			}
25905 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25906 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25907 			ire_need_rele = B_TRUE;
25908 			ipif_refrele(ipif);
25909 		} else {
25910 			if (ire_arg != NULL) {
25911 				ire = ire_arg;
25912 			} else {
25913 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25914 				    ipst);
25915 				ire_need_rele = B_TRUE;
25916 			}
25917 		}
25918 		if (ire != NULL)
25919 			goto send;
25920 		/*
25921 		 * ire disappeared underneath.
25922 		 *
25923 		 * What we need to do here is the ip_newroute
25924 		 * logic to get the ire without doing the IPSEC
25925 		 * processing. Follow the same old path. But this
25926 		 * time, ip_wput or ire_add_then_send will call us
25927 		 * directly as all the IPSEC operations are done.
25928 		 */
25929 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25930 		mp->b_prev = NULL;
25931 		mp->b_next = NULL;
25932 
25933 		/*
25934 		 * If the IPsec packet was processed asynchronously,
25935 		 * drop it now.
25936 		 */
25937 		if (q == NULL) {
25938 			if (ill_need_rele)
25939 				ill_refrele(ill);
25940 			freemsg(ipsec_mp);
25941 			return;
25942 		}
25943 
25944 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25945 		    zoneid, ipst);
25946 	}
25947 	if (ill != NULL && ill_need_rele)
25948 		ill_refrele(ill);
25949 	return;
25950 send:
25951 	if (ill != NULL && ill_need_rele)
25952 		ill_refrele(ill);
25953 
25954 	/* Local delivery */
25955 	if (ire->ire_stq == NULL) {
25956 		ill_t	*out_ill;
25957 		ASSERT(q != NULL);
25958 
25959 		/* PFHooks: LOOPBACK_OUT */
25960 		out_ill = ire->ire_ipif->ipif_ill;
25961 
25962 		DTRACE_PROBE4(ip6__loopback__out__start,
25963 		    ill_t *, NULL, ill_t *, out_ill,
25964 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25965 
25966 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25967 		    ipst->ips_ipv6firewall_loopback_out,
25968 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25969 
25970 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25971 
25972 		if (ipsec_mp != NULL)
25973 			ip_wput_local_v6(RD(q), out_ill,
25974 			    ip6h, ipsec_mp, ire, 0);
25975 		if (ire_need_rele)
25976 			ire_refrele(ire);
25977 		return;
25978 	}
25979 	/*
25980 	 * Everything is done. Send it out on the wire.
25981 	 * We force the insertion of a fragment header using the
25982 	 * IPH_FRAG_HDR flag in two cases:
25983 	 * - after reception of an ICMPv6 "packet too big" message
25984 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25985 	 * - for multirouted IPv6 packets, so that the receiver can
25986 	 *   discard duplicates according to their fragment identifier
25987 	 */
25988 	/* XXX fix flow control problems. */
25989 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25990 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25991 		if (hwaccel) {
25992 			/*
25993 			 * hardware acceleration does not handle these
25994 			 * "slow path" cases.
25995 			 */
25996 			/* IPsec KSTATS: should bump bean counter here. */
25997 			if (ire_need_rele)
25998 				ire_refrele(ire);
25999 			freemsg(ipsec_mp);
26000 			return;
26001 		}
26002 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
26003 		    (mp->b_cont ? msgdsize(mp) :
26004 		    mp->b_wptr - (uchar_t *)ip6h)) {
26005 			/* IPsec KSTATS: should bump bean counter here. */
26006 			ip0dbg(("Packet length mismatch: %d, %ld\n",
26007 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
26008 			    msgdsize(mp)));
26009 			if (ire_need_rele)
26010 				ire_refrele(ire);
26011 			freemsg(ipsec_mp);
26012 			return;
26013 		}
26014 		ASSERT(mp->b_prev == NULL);
26015 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26016 		    ntohs(ip6h->ip6_plen) +
26017 		    IPV6_HDR_LEN, ire->ire_max_frag));
26018 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26019 		    ire->ire_max_frag);
26020 	} else {
26021 		UPDATE_OB_PKT_COUNT(ire);
26022 		ire->ire_last_used_time = lbolt;
26023 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26024 	}
26025 	if (ire_need_rele)
26026 		ire_refrele(ire);
26027 	freeb(ipsec_mp);
26028 }
26029 
26030 void
26031 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26032 {
26033 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26034 	da_ipsec_t *hada;	/* data attributes */
26035 	ill_t *ill = (ill_t *)q->q_ptr;
26036 
26037 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26038 
26039 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26040 		/* IPsec KSTATS: Bump lose counter here! */
26041 		freemsg(mp);
26042 		return;
26043 	}
26044 
26045 	/*
26046 	 * It's an IPsec packet that must be
26047 	 * accelerated by the Provider, and the
26048 	 * outbound ill is IPsec acceleration capable.
26049 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26050 	 * to the ill.
26051 	 * IPsec KSTATS: should bump packet counter here.
26052 	 */
26053 
26054 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26055 	if (hada_mp == NULL) {
26056 		/* IPsec KSTATS: should bump packet counter here. */
26057 		freemsg(mp);
26058 		return;
26059 	}
26060 
26061 	hada_mp->b_datap->db_type = M_CTL;
26062 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26063 	hada_mp->b_cont = mp;
26064 
26065 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26066 	bzero(hada, sizeof (da_ipsec_t));
26067 	hada->da_type = IPHADA_M_CTL;
26068 
26069 	putnext(q, hada_mp);
26070 }
26071 
26072 /*
26073  * Finish the outbound IPsec processing. This function is called from
26074  * ipsec_out_process() if the IPsec packet was processed
26075  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26076  * asynchronously.
26077  */
26078 void
26079 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26080     ire_t *ire_arg)
26081 {
26082 	uint32_t v_hlen_tos_len;
26083 	ipaddr_t	dst;
26084 	ipif_t	*ipif = NULL;
26085 	ire_t *ire;
26086 	ire_t *ire1 = NULL;
26087 	mblk_t *next_mp = NULL;
26088 	uint32_t max_frag;
26089 	boolean_t multirt_send = B_FALSE;
26090 	mblk_t *mp;
26091 	mblk_t *mp1;
26092 	ipha_t *ipha1;
26093 	uint_t	ill_index;
26094 	ipsec_out_t *io;
26095 	boolean_t attach_if;
26096 	int match_flags, offset;
26097 	irb_t *irb = NULL;
26098 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26099 	zoneid_t zoneid;
26100 	uint32_t cksum;
26101 	uint16_t *up;
26102 	ipxmit_state_t	pktxmit_state;
26103 	ip_stack_t	*ipst;
26104 
26105 #ifdef	_BIG_ENDIAN
26106 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26107 #else
26108 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26109 #endif
26110 
26111 	mp = ipsec_mp->b_cont;
26112 	ipha1 = (ipha_t *)mp->b_rptr;
26113 	ASSERT(mp != NULL);
26114 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26115 	dst = ipha->ipha_dst;
26116 
26117 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26118 	ill_index = io->ipsec_out_ill_index;
26119 	attach_if = io->ipsec_out_attach_if;
26120 	zoneid = io->ipsec_out_zoneid;
26121 	ASSERT(zoneid != ALL_ZONES);
26122 	ipst = io->ipsec_out_ns->netstack_ip;
26123 	ASSERT(io->ipsec_out_ns != NULL);
26124 
26125 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26126 	if (ill_index != 0) {
26127 		if (ill == NULL) {
26128 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26129 			    ill_index, B_FALSE, ipst);
26130 
26131 			/* Failure case frees things for us. */
26132 			if (ill == NULL)
26133 				return;
26134 
26135 			ill_need_rele = B_TRUE;
26136 		}
26137 		/*
26138 		 * If this packet needs to go out on a particular interface
26139 		 * honor it.
26140 		 */
26141 		if (attach_if) {
26142 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26143 
26144 			/*
26145 			 * Check if we need an ire that will not be
26146 			 * looked up by anybody else i.e. HIDDEN.
26147 			 */
26148 			if (ill_is_probeonly(ill)) {
26149 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26150 			}
26151 		}
26152 	}
26153 
26154 	if (CLASSD(dst)) {
26155 		boolean_t conn_dontroute;
26156 		/*
26157 		 * Use the ill_index to get the right ipif.
26158 		 */
26159 		conn_dontroute = io->ipsec_out_dontroute;
26160 		if (ill_index == 0)
26161 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26162 		else
26163 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26164 		if (ipif == NULL) {
26165 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26166 			    " multicast\n"));
26167 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26168 			freemsg(ipsec_mp);
26169 			goto done;
26170 		}
26171 		/*
26172 		 * ipha_src has already been intialized with the
26173 		 * value of the ipif in ip_wput. All we need now is
26174 		 * an ire to send this downstream.
26175 		 */
26176 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26177 		    MBLK_GETLABEL(mp), match_flags, ipst);
26178 		if (ire != NULL) {
26179 			ill_t *ill1;
26180 			/*
26181 			 * Do the multicast forwarding now, as the IPSEC
26182 			 * processing has been done.
26183 			 */
26184 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26185 			    (ill1 = ire_to_ill(ire))) {
26186 				if (ip_mforward(ill1, ipha, mp)) {
26187 					freemsg(ipsec_mp);
26188 					ip1dbg(("ip_wput_ipsec_out: mforward "
26189 					    "failed\n"));
26190 					ire_refrele(ire);
26191 					goto done;
26192 				}
26193 			}
26194 			goto send;
26195 		}
26196 
26197 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26198 		mp->b_prev = NULL;
26199 		mp->b_next = NULL;
26200 
26201 		/*
26202 		 * If the IPsec packet was processed asynchronously,
26203 		 * drop it now.
26204 		 */
26205 		if (q == NULL) {
26206 			freemsg(ipsec_mp);
26207 			goto done;
26208 		}
26209 
26210 		/*
26211 		 * We may be using a wrong ipif to create the ire.
26212 		 * But it is okay as the source address is assigned
26213 		 * for the packet already. Next outbound packet would
26214 		 * create the IRE with the right IPIF in ip_wput.
26215 		 *
26216 		 * Also handle RTF_MULTIRT routes.
26217 		 */
26218 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26219 		    zoneid, &zero_info);
26220 	} else {
26221 		if (attach_if) {
26222 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26223 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26224 		} else {
26225 			if (ire_arg != NULL) {
26226 				ire = ire_arg;
26227 				ire_need_rele = B_FALSE;
26228 			} else {
26229 				ire = ire_cache_lookup(dst, zoneid,
26230 				    MBLK_GETLABEL(mp), ipst);
26231 			}
26232 		}
26233 		if (ire != NULL) {
26234 			goto send;
26235 		}
26236 
26237 		/*
26238 		 * ire disappeared underneath.
26239 		 *
26240 		 * What we need to do here is the ip_newroute
26241 		 * logic to get the ire without doing the IPSEC
26242 		 * processing. Follow the same old path. But this
26243 		 * time, ip_wput or ire_add_then_put will call us
26244 		 * directly as all the IPSEC operations are done.
26245 		 */
26246 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26247 		mp->b_prev = NULL;
26248 		mp->b_next = NULL;
26249 
26250 		/*
26251 		 * If the IPsec packet was processed asynchronously,
26252 		 * drop it now.
26253 		 */
26254 		if (q == NULL) {
26255 			freemsg(ipsec_mp);
26256 			goto done;
26257 		}
26258 
26259 		/*
26260 		 * Since we're going through ip_newroute() again, we
26261 		 * need to make sure we don't:
26262 		 *
26263 		 *	1.) Trigger the ASSERT() with the ipha_ident
26264 		 *	    overloading.
26265 		 *	2.) Redo transport-layer checksumming, since we've
26266 		 *	    already done all that to get this far.
26267 		 *
26268 		 * The easiest way not do either of the above is to set
26269 		 * the ipha_ident field to IP_HDR_INCLUDED.
26270 		 */
26271 		ipha->ipha_ident = IP_HDR_INCLUDED;
26272 		ip_newroute(q, ipsec_mp, dst, NULL,
26273 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26274 	}
26275 	goto done;
26276 send:
26277 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26278 	    udp_compute_checksum(ipst->ips_netstack)) {
26279 		/*
26280 		 * ESP NAT-Traversal packet.
26281 		 *
26282 		 * Just do software checksum for now.
26283 		 */
26284 
26285 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26286 		IP_STAT(ipst, ip_out_sw_cksum);
26287 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26288 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26289 #define	iphs	((uint16_t *)ipha)
26290 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26291 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26292 		    IP_SIMPLE_HDR_LENGTH);
26293 #undef iphs
26294 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
26295 			cksum = 0xFFFF;
26296 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26297 			if (mp1->b_wptr - mp1->b_rptr >=
26298 			    offset + sizeof (uint16_t)) {
26299 				up = (uint16_t *)(mp1->b_rptr + offset);
26300 				*up = cksum;
26301 				break;	/* out of for loop */
26302 			} else {
26303 				offset -= (mp->b_wptr - mp->b_rptr);
26304 			}
26305 	} /* Otherwise, just keep the all-zero checksum. */
26306 
26307 	if (ire->ire_stq == NULL) {
26308 		ill_t	*out_ill;
26309 		/*
26310 		 * Loopbacks go through ip_wput_local except for one case.
26311 		 * We come here if we generate a icmp_frag_needed message
26312 		 * after IPSEC processing is over. When this function calls
26313 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26314 		 * icmp_frag_needed. The message generated comes back here
26315 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26316 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26317 		 * source address as it is usually set in ip_wput_ire. As
26318 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26319 		 * and we end up here. We can't enter ip_wput_ire once the
26320 		 * IPSEC processing is over and hence we need to do it here.
26321 		 */
26322 		ASSERT(q != NULL);
26323 		UPDATE_OB_PKT_COUNT(ire);
26324 		ire->ire_last_used_time = lbolt;
26325 		if (ipha->ipha_src == 0)
26326 			ipha->ipha_src = ire->ire_src_addr;
26327 
26328 		/* PFHooks: LOOPBACK_OUT */
26329 		out_ill = ire->ire_ipif->ipif_ill;
26330 
26331 		DTRACE_PROBE4(ip4__loopback__out__start,
26332 		    ill_t *, NULL, ill_t *, out_ill,
26333 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26334 
26335 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26336 		    ipst->ips_ipv4firewall_loopback_out,
26337 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26338 
26339 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26340 
26341 		if (ipsec_mp != NULL)
26342 			ip_wput_local(RD(q), out_ill,
26343 			    ipha, ipsec_mp, ire, 0, zoneid);
26344 		if (ire_need_rele)
26345 			ire_refrele(ire);
26346 		goto done;
26347 	}
26348 
26349 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26350 		/*
26351 		 * We are through with IPSEC processing.
26352 		 * Fragment this and send it on the wire.
26353 		 */
26354 		if (io->ipsec_out_accelerated) {
26355 			/*
26356 			 * The packet has been accelerated but must
26357 			 * be fragmented. This should not happen
26358 			 * since AH and ESP must not accelerate
26359 			 * packets that need fragmentation, however
26360 			 * the configuration could have changed
26361 			 * since the AH or ESP processing.
26362 			 * Drop packet.
26363 			 * IPsec KSTATS: bump bean counter here.
26364 			 */
26365 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26366 			    "fragmented accelerated packet!\n"));
26367 			freemsg(ipsec_mp);
26368 		} else {
26369 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26370 		}
26371 		if (ire_need_rele)
26372 			ire_refrele(ire);
26373 		goto done;
26374 	}
26375 
26376 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26377 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26378 	    (void *)ire->ire_ipif, (void *)ipif));
26379 
26380 	/*
26381 	 * Multiroute the secured packet, unless IPsec really
26382 	 * requires the packet to go out only through a particular
26383 	 * interface.
26384 	 */
26385 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26386 		ire_t *first_ire;
26387 		irb = ire->ire_bucket;
26388 		ASSERT(irb != NULL);
26389 		/*
26390 		 * This ire has been looked up as the one that
26391 		 * goes through the given ipif;
26392 		 * make sure we do not omit any other multiroute ire
26393 		 * that may be present in the bucket before this one.
26394 		 */
26395 		IRB_REFHOLD(irb);
26396 		for (first_ire = irb->irb_ire;
26397 		    first_ire != NULL;
26398 		    first_ire = first_ire->ire_next) {
26399 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26400 			    (first_ire->ire_addr == ire->ire_addr) &&
26401 			    !(first_ire->ire_marks &
26402 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
26403 				break;
26404 		}
26405 
26406 		if ((first_ire != NULL) && (first_ire != ire)) {
26407 			/*
26408 			 * Don't change the ire if the packet must
26409 			 * be fragmented if sent via this new one.
26410 			 */
26411 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26412 				IRE_REFHOLD(first_ire);
26413 				if (ire_need_rele)
26414 					ire_refrele(ire);
26415 				else
26416 					ire_need_rele = B_TRUE;
26417 				ire = first_ire;
26418 			}
26419 		}
26420 		IRB_REFRELE(irb);
26421 
26422 		multirt_send = B_TRUE;
26423 		max_frag = ire->ire_max_frag;
26424 	} else {
26425 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26426 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26427 			    "flag, attach_if %d\n", attach_if));
26428 		}
26429 	}
26430 
26431 	/*
26432 	 * In most cases, the emission loop below is entered only once.
26433 	 * Only in the case where the ire holds the RTF_MULTIRT
26434 	 * flag, we loop to process all RTF_MULTIRT ires in the
26435 	 * bucket, and send the packet through all crossed
26436 	 * RTF_MULTIRT routes.
26437 	 */
26438 	do {
26439 		if (multirt_send) {
26440 			/*
26441 			 * ire1 holds here the next ire to process in the
26442 			 * bucket. If multirouting is expected,
26443 			 * any non-RTF_MULTIRT ire that has the
26444 			 * right destination address is ignored.
26445 			 */
26446 			ASSERT(irb != NULL);
26447 			IRB_REFHOLD(irb);
26448 			for (ire1 = ire->ire_next;
26449 			    ire1 != NULL;
26450 			    ire1 = ire1->ire_next) {
26451 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26452 					continue;
26453 				if (ire1->ire_addr != ire->ire_addr)
26454 					continue;
26455 				if (ire1->ire_marks &
26456 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26457 					continue;
26458 				/* No loopback here */
26459 				if (ire1->ire_stq == NULL)
26460 					continue;
26461 				/*
26462 				 * Ensure we do not exceed the MTU
26463 				 * of the next route.
26464 				 */
26465 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26466 					ip_multirt_bad_mtu(ire1, max_frag);
26467 					continue;
26468 				}
26469 
26470 				IRE_REFHOLD(ire1);
26471 				break;
26472 			}
26473 			IRB_REFRELE(irb);
26474 			if (ire1 != NULL) {
26475 				/*
26476 				 * We are in a multiple send case, need to
26477 				 * make a copy of the packet.
26478 				 */
26479 				next_mp = copymsg(ipsec_mp);
26480 				if (next_mp == NULL) {
26481 					ire_refrele(ire1);
26482 					ire1 = NULL;
26483 				}
26484 			}
26485 		}
26486 		/*
26487 		 * Everything is done. Send it out on the wire
26488 		 *
26489 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26490 		 * either send it on the wire or, in the case of
26491 		 * HW acceleration, call ipsec_hw_putnext.
26492 		 */
26493 		if (ire->ire_nce &&
26494 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26495 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26496 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26497 			/*
26498 			 * If ire's link-layer is unresolved (this
26499 			 * would only happen if the incomplete ire
26500 			 * was added to cachetable via forwarding path)
26501 			 * don't bother going to ip_xmit_v4. Just drop the
26502 			 * packet.
26503 			 * There is a slight risk here, in that, if we
26504 			 * have the forwarding path create an incomplete
26505 			 * IRE, then until the IRE is completed, any
26506 			 * transmitted IPSEC packets will be dropped
26507 			 * instead of being queued waiting for resolution.
26508 			 *
26509 			 * But the likelihood of a forwarding packet and a wput
26510 			 * packet sending to the same dst at the same time
26511 			 * and there not yet be an ARP entry for it is small.
26512 			 * Furthermore, if this actually happens, it might
26513 			 * be likely that wput would generate multiple
26514 			 * packets (and forwarding would also have a train
26515 			 * of packets) for that destination. If this is
26516 			 * the case, some of them would have been dropped
26517 			 * anyway, since ARP only queues a few packets while
26518 			 * waiting for resolution
26519 			 *
26520 			 * NOTE: We should really call ip_xmit_v4,
26521 			 * and let it queue the packet and send the
26522 			 * ARP query and have ARP come back thus:
26523 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26524 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26525 			 * hw accel work. But it's too complex to get
26526 			 * the IPsec hw  acceleration approach to fit
26527 			 * well with ip_xmit_v4 doing ARP without
26528 			 * doing IPSEC simplification. For now, we just
26529 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26530 			 * that we can continue with the send on the next
26531 			 * attempt.
26532 			 *
26533 			 * XXX THis should be revisited, when
26534 			 * the IPsec/IP interaction is cleaned up
26535 			 */
26536 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26537 			    " - dropping packet\n"));
26538 			freemsg(ipsec_mp);
26539 			/*
26540 			 * Call ip_xmit_v4() to trigger ARP query
26541 			 * in case the nce_state is ND_INITIAL
26542 			 */
26543 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26544 			goto drop_pkt;
26545 		}
26546 
26547 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26548 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26549 		    mblk_t *, mp);
26550 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26551 		    ipst->ips_ipv4firewall_physical_out,
26552 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp, ipst);
26553 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
26554 		if (mp == NULL)
26555 			goto drop_pkt;
26556 
26557 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26558 		pktxmit_state = ip_xmit_v4(mp, ire,
26559 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26560 
26561 		if ((pktxmit_state ==  SEND_FAILED) ||
26562 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26563 
26564 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26565 drop_pkt:
26566 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26567 			    ipIfStatsOutDiscards);
26568 			if (ire_need_rele)
26569 				ire_refrele(ire);
26570 			if (ire1 != NULL) {
26571 				ire_refrele(ire1);
26572 				freemsg(next_mp);
26573 			}
26574 			goto done;
26575 		}
26576 
26577 		freeb(ipsec_mp);
26578 		if (ire_need_rele)
26579 			ire_refrele(ire);
26580 
26581 		if (ire1 != NULL) {
26582 			ire = ire1;
26583 			ire_need_rele = B_TRUE;
26584 			ASSERT(next_mp);
26585 			ipsec_mp = next_mp;
26586 			mp = ipsec_mp->b_cont;
26587 			ire1 = NULL;
26588 			next_mp = NULL;
26589 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26590 		} else {
26591 			multirt_send = B_FALSE;
26592 		}
26593 	} while (multirt_send);
26594 done:
26595 	if (ill != NULL && ill_need_rele)
26596 		ill_refrele(ill);
26597 	if (ipif != NULL)
26598 		ipif_refrele(ipif);
26599 }
26600 
26601 /*
26602  * Get the ill corresponding to the specified ire, and compare its
26603  * capabilities with the protocol and algorithms specified by the
26604  * the SA obtained from ipsec_out. If they match, annotate the
26605  * ipsec_out structure to indicate that the packet needs acceleration.
26606  *
26607  *
26608  * A packet is eligible for outbound hardware acceleration if the
26609  * following conditions are satisfied:
26610  *
26611  * 1. the packet will not be fragmented
26612  * 2. the provider supports the algorithm
26613  * 3. there is no pending control message being exchanged
26614  * 4. snoop is not attached
26615  * 5. the destination address is not a broadcast or multicast address.
26616  *
26617  * Rationale:
26618  *	- Hardware drivers do not support fragmentation with
26619  *	  the current interface.
26620  *	- snoop, multicast, and broadcast may result in exposure of
26621  *	  a cleartext datagram.
26622  * We check all five of these conditions here.
26623  *
26624  * XXX would like to nuke "ire_t *" parameter here; problem is that
26625  * IRE is only way to figure out if a v4 address is a broadcast and
26626  * thus ineligible for acceleration...
26627  */
26628 static void
26629 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26630 {
26631 	ipsec_out_t *io;
26632 	mblk_t *data_mp;
26633 	uint_t plen, overhead;
26634 	ip_stack_t	*ipst;
26635 
26636 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26637 		return;
26638 
26639 	if (ill == NULL)
26640 		return;
26641 	ipst = ill->ill_ipst;
26642 	/*
26643 	 * Destination address is a broadcast or multicast.  Punt.
26644 	 */
26645 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26646 	    IRE_LOCAL)))
26647 		return;
26648 
26649 	data_mp = ipsec_mp->b_cont;
26650 
26651 	if (ill->ill_isv6) {
26652 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26653 
26654 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26655 			return;
26656 
26657 		plen = ip6h->ip6_plen;
26658 	} else {
26659 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26660 
26661 		if (CLASSD(ipha->ipha_dst))
26662 			return;
26663 
26664 		plen = ipha->ipha_length;
26665 	}
26666 	/*
26667 	 * Is there a pending DLPI control message being exchanged
26668 	 * between IP/IPsec and the DLS Provider? If there is, it
26669 	 * could be a SADB update, and the state of the DLS Provider
26670 	 * SADB might not be in sync with the SADB maintained by
26671 	 * IPsec. To avoid dropping packets or using the wrong keying
26672 	 * material, we do not accelerate this packet.
26673 	 */
26674 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26675 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26676 		    "ill_dlpi_pending! don't accelerate packet\n"));
26677 		return;
26678 	}
26679 
26680 	/*
26681 	 * Is the Provider in promiscous mode? If it does, we don't
26682 	 * accelerate the packet since it will bounce back up to the
26683 	 * listeners in the clear.
26684 	 */
26685 	if (ill->ill_promisc_on_phys) {
26686 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26687 		    "ill in promiscous mode, don't accelerate packet\n"));
26688 		return;
26689 	}
26690 
26691 	/*
26692 	 * Will the packet require fragmentation?
26693 	 */
26694 
26695 	/*
26696 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26697 	 * as is used elsewhere.
26698 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26699 	 *	+ 2-byte trailer
26700 	 */
26701 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26702 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26703 
26704 	if ((plen + overhead) > ill->ill_max_mtu)
26705 		return;
26706 
26707 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26708 
26709 	/*
26710 	 * Can the ill accelerate this IPsec protocol and algorithm
26711 	 * specified by the SA?
26712 	 */
26713 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26714 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26715 		return;
26716 	}
26717 
26718 	/*
26719 	 * Tell AH or ESP that the outbound ill is capable of
26720 	 * accelerating this packet.
26721 	 */
26722 	io->ipsec_out_is_capab_ill = B_TRUE;
26723 }
26724 
26725 /*
26726  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26727  *
26728  * If this function returns B_TRUE, the requested SA's have been filled
26729  * into the ipsec_out_*_sa pointers.
26730  *
26731  * If the function returns B_FALSE, the packet has been "consumed", most
26732  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26733  *
26734  * The SA references created by the protocol-specific "select"
26735  * function will be released when the ipsec_mp is freed, thanks to the
26736  * ipsec_out_free destructor -- see spd.c.
26737  */
26738 static boolean_t
26739 ipsec_out_select_sa(mblk_t *ipsec_mp)
26740 {
26741 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26742 	ipsec_out_t *io;
26743 	ipsec_policy_t *pp;
26744 	ipsec_action_t *ap;
26745 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26746 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26747 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26748 
26749 	if (!io->ipsec_out_secure) {
26750 		/*
26751 		 * We came here by mistake.
26752 		 * Don't bother with ipsec processing
26753 		 * We should "discourage" this path in the future.
26754 		 */
26755 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26756 		return (B_FALSE);
26757 	}
26758 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26759 	ASSERT((io->ipsec_out_policy != NULL) ||
26760 	    (io->ipsec_out_act != NULL));
26761 
26762 	ASSERT(io->ipsec_out_failed == B_FALSE);
26763 
26764 	/*
26765 	 * IPSEC processing has started.
26766 	 */
26767 	io->ipsec_out_proc_begin = B_TRUE;
26768 	ap = io->ipsec_out_act;
26769 	if (ap == NULL) {
26770 		pp = io->ipsec_out_policy;
26771 		ASSERT(pp != NULL);
26772 		ap = pp->ipsp_act;
26773 		ASSERT(ap != NULL);
26774 	}
26775 
26776 	/*
26777 	 * We have an action.  now, let's select SA's.
26778 	 * (In the future, we can cache this in the conn_t..)
26779 	 */
26780 	if (ap->ipa_want_esp) {
26781 		if (io->ipsec_out_esp_sa == NULL) {
26782 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26783 			    IPPROTO_ESP);
26784 		}
26785 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26786 	}
26787 
26788 	if (ap->ipa_want_ah) {
26789 		if (io->ipsec_out_ah_sa == NULL) {
26790 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26791 			    IPPROTO_AH);
26792 		}
26793 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26794 		/*
26795 		 * The ESP and AH processing order needs to be preserved
26796 		 * when both protocols are required (ESP should be applied
26797 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26798 		 * when both ESP and AH are required, and an AH ACQUIRE
26799 		 * is needed.
26800 		 */
26801 		if (ap->ipa_want_esp && need_ah_acquire)
26802 			need_esp_acquire = B_TRUE;
26803 	}
26804 
26805 	/*
26806 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26807 	 * Release SAs that got referenced, but will not be used until we
26808 	 * acquire _all_ of the SAs we need.
26809 	 */
26810 	if (need_ah_acquire || need_esp_acquire) {
26811 		if (io->ipsec_out_ah_sa != NULL) {
26812 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26813 			io->ipsec_out_ah_sa = NULL;
26814 		}
26815 		if (io->ipsec_out_esp_sa != NULL) {
26816 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26817 			io->ipsec_out_esp_sa = NULL;
26818 		}
26819 
26820 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26821 		return (B_FALSE);
26822 	}
26823 
26824 	return (B_TRUE);
26825 }
26826 
26827 /*
26828  * Process an IPSEC_OUT message and see what you can
26829  * do with it.
26830  * IPQoS Notes:
26831  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26832  * IPSec.
26833  * XXX would like to nuke ire_t.
26834  * XXX ill_index better be "real"
26835  */
26836 void
26837 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26838 {
26839 	ipsec_out_t *io;
26840 	ipsec_policy_t *pp;
26841 	ipsec_action_t *ap;
26842 	ipha_t *ipha;
26843 	ip6_t *ip6h;
26844 	mblk_t *mp;
26845 	ill_t *ill;
26846 	zoneid_t zoneid;
26847 	ipsec_status_t ipsec_rc;
26848 	boolean_t ill_need_rele = B_FALSE;
26849 	ip_stack_t	*ipst;
26850 	ipsec_stack_t	*ipss;
26851 
26852 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26853 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26854 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26855 	ipst = io->ipsec_out_ns->netstack_ip;
26856 	mp = ipsec_mp->b_cont;
26857 
26858 	/*
26859 	 * Initiate IPPF processing. We do it here to account for packets
26860 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26861 	 * We can check for ipsec_out_proc_begin even for such packets, as
26862 	 * they will always be false (asserted below).
26863 	 */
26864 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26865 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26866 		    io->ipsec_out_ill_index : ill_index);
26867 		if (mp == NULL) {
26868 			ip2dbg(("ipsec_out_process: packet dropped "\
26869 			    "during IPPF processing\n"));
26870 			freeb(ipsec_mp);
26871 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26872 			return;
26873 		}
26874 	}
26875 
26876 	if (!io->ipsec_out_secure) {
26877 		/*
26878 		 * We came here by mistake.
26879 		 * Don't bother with ipsec processing
26880 		 * Should "discourage" this path in the future.
26881 		 */
26882 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26883 		goto done;
26884 	}
26885 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26886 	ASSERT((io->ipsec_out_policy != NULL) ||
26887 	    (io->ipsec_out_act != NULL));
26888 	ASSERT(io->ipsec_out_failed == B_FALSE);
26889 
26890 	ipss = ipst->ips_netstack->netstack_ipsec;
26891 	if (!ipsec_loaded(ipss)) {
26892 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26893 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26894 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26895 		} else {
26896 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26897 		}
26898 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26899 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26900 		    &ipss->ipsec_dropper);
26901 		return;
26902 	}
26903 
26904 	/*
26905 	 * IPSEC processing has started.
26906 	 */
26907 	io->ipsec_out_proc_begin = B_TRUE;
26908 	ap = io->ipsec_out_act;
26909 	if (ap == NULL) {
26910 		pp = io->ipsec_out_policy;
26911 		ASSERT(pp != NULL);
26912 		ap = pp->ipsp_act;
26913 		ASSERT(ap != NULL);
26914 	}
26915 
26916 	/*
26917 	 * Save the outbound ill index. When the packet comes back
26918 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26919 	 * before sending it the accelerated packet.
26920 	 */
26921 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26922 		int ifindex;
26923 		ill = ire_to_ill(ire);
26924 		ifindex = ill->ill_phyint->phyint_ifindex;
26925 		io->ipsec_out_capab_ill_index = ifindex;
26926 	}
26927 
26928 	/*
26929 	 * The order of processing is first insert a IP header if needed.
26930 	 * Then insert the ESP header and then the AH header.
26931 	 */
26932 	if ((io->ipsec_out_se_done == B_FALSE) &&
26933 	    (ap->ipa_want_se)) {
26934 		/*
26935 		 * First get the outer IP header before sending
26936 		 * it to ESP.
26937 		 */
26938 		ipha_t *oipha, *iipha;
26939 		mblk_t *outer_mp, *inner_mp;
26940 
26941 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26942 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26943 			    "ipsec_out_process: "
26944 			    "Self-Encapsulation failed: Out of memory\n");
26945 			freemsg(ipsec_mp);
26946 			if (ill != NULL) {
26947 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26948 			} else {
26949 				BUMP_MIB(&ipst->ips_ip_mib,
26950 				    ipIfStatsOutDiscards);
26951 			}
26952 			return;
26953 		}
26954 		inner_mp = ipsec_mp->b_cont;
26955 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26956 		oipha = (ipha_t *)outer_mp->b_rptr;
26957 		iipha = (ipha_t *)inner_mp->b_rptr;
26958 		*oipha = *iipha;
26959 		outer_mp->b_wptr += sizeof (ipha_t);
26960 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26961 		    sizeof (ipha_t));
26962 		oipha->ipha_protocol = IPPROTO_ENCAP;
26963 		oipha->ipha_version_and_hdr_length =
26964 		    IP_SIMPLE_HDR_VERSION;
26965 		oipha->ipha_hdr_checksum = 0;
26966 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26967 		outer_mp->b_cont = inner_mp;
26968 		ipsec_mp->b_cont = outer_mp;
26969 
26970 		io->ipsec_out_se_done = B_TRUE;
26971 		io->ipsec_out_tunnel = B_TRUE;
26972 	}
26973 
26974 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26975 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26976 	    !ipsec_out_select_sa(ipsec_mp))
26977 		return;
26978 
26979 	/*
26980 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26981 	 * to do the heavy lifting.
26982 	 */
26983 	zoneid = io->ipsec_out_zoneid;
26984 	ASSERT(zoneid != ALL_ZONES);
26985 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26986 		ASSERT(io->ipsec_out_esp_sa != NULL);
26987 		io->ipsec_out_esp_done = B_TRUE;
26988 		/*
26989 		 * Note that since hw accel can only apply one transform,
26990 		 * not two, we skip hw accel for ESP if we also have AH
26991 		 * This is an design limitation of the interface
26992 		 * which should be revisited.
26993 		 */
26994 		ASSERT(ire != NULL);
26995 		if (io->ipsec_out_ah_sa == NULL) {
26996 			ill = (ill_t *)ire->ire_stq->q_ptr;
26997 			ipsec_out_is_accelerated(ipsec_mp,
26998 			    io->ipsec_out_esp_sa, ill, ire);
26999 		}
27000 
27001 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
27002 		switch (ipsec_rc) {
27003 		case IPSEC_STATUS_SUCCESS:
27004 			break;
27005 		case IPSEC_STATUS_FAILED:
27006 			if (ill != NULL) {
27007 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27008 			} else {
27009 				BUMP_MIB(&ipst->ips_ip_mib,
27010 				    ipIfStatsOutDiscards);
27011 			}
27012 			/* FALLTHRU */
27013 		case IPSEC_STATUS_PENDING:
27014 			return;
27015 		}
27016 	}
27017 
27018 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27019 		ASSERT(io->ipsec_out_ah_sa != NULL);
27020 		io->ipsec_out_ah_done = B_TRUE;
27021 		if (ire == NULL) {
27022 			int idx = io->ipsec_out_capab_ill_index;
27023 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27024 			    NULL, NULL, NULL, NULL, ipst);
27025 			ill_need_rele = B_TRUE;
27026 		} else {
27027 			ill = (ill_t *)ire->ire_stq->q_ptr;
27028 		}
27029 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27030 		    ire);
27031 
27032 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27033 		switch (ipsec_rc) {
27034 		case IPSEC_STATUS_SUCCESS:
27035 			break;
27036 		case IPSEC_STATUS_FAILED:
27037 			if (ill != NULL) {
27038 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27039 			} else {
27040 				BUMP_MIB(&ipst->ips_ip_mib,
27041 				    ipIfStatsOutDiscards);
27042 			}
27043 			/* FALLTHRU */
27044 		case IPSEC_STATUS_PENDING:
27045 			if (ill != NULL && ill_need_rele)
27046 				ill_refrele(ill);
27047 			return;
27048 		}
27049 	}
27050 	/*
27051 	 * We are done with IPSEC processing. Send it over
27052 	 * the wire.
27053 	 */
27054 done:
27055 	mp = ipsec_mp->b_cont;
27056 	ipha = (ipha_t *)mp->b_rptr;
27057 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27058 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27059 	} else {
27060 		ip6h = (ip6_t *)ipha;
27061 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27062 	}
27063 	if (ill != NULL && ill_need_rele)
27064 		ill_refrele(ill);
27065 }
27066 
27067 /* ARGSUSED */
27068 void
27069 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27070 {
27071 	opt_restart_t	*or;
27072 	int	err;
27073 	conn_t	*connp;
27074 
27075 	ASSERT(CONN_Q(q));
27076 	connp = Q_TO_CONN(q);
27077 
27078 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27079 	or = (opt_restart_t *)first_mp->b_rptr;
27080 	/*
27081 	 * We don't need to pass any credentials here since this is just
27082 	 * a restart. The credentials are passed in when svr4_optcom_req
27083 	 * is called the first time (from ip_wput_nondata).
27084 	 */
27085 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27086 		err = svr4_optcom_req(q, first_mp, NULL,
27087 		    &ip_opt_obj);
27088 	} else {
27089 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27090 		err = tpi_optcom_req(q, first_mp, NULL,
27091 		    &ip_opt_obj);
27092 	}
27093 	if (err != EINPROGRESS) {
27094 		/* operation is done */
27095 		CONN_OPER_PENDING_DONE(connp);
27096 	}
27097 }
27098 
27099 /*
27100  * ioctls that go through a down/up sequence may need to wait for the down
27101  * to complete. This involves waiting for the ire and ipif refcnts to go down
27102  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27103  */
27104 /* ARGSUSED */
27105 void
27106 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27107 {
27108 	struct iocblk *iocp;
27109 	mblk_t *mp1;
27110 	ip_ioctl_cmd_t *ipip;
27111 	int err;
27112 	sin_t	*sin;
27113 	struct lifreq *lifr;
27114 	struct ifreq *ifr;
27115 
27116 	iocp = (struct iocblk *)mp->b_rptr;
27117 	ASSERT(ipsq != NULL);
27118 	/* Existence of mp1 verified in ip_wput_nondata */
27119 	mp1 = mp->b_cont->b_cont;
27120 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27121 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27122 		/*
27123 		 * Special case where ipsq_current_ipif is not set:
27124 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27125 		 * ill could also have become part of a ipmp group in the
27126 		 * process, we are here as were not able to complete the
27127 		 * operation in ipif_set_values because we could not become
27128 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27129 		 * will not be set so we need to set it.
27130 		 */
27131 		ill_t *ill = q->q_ptr;
27132 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27133 	}
27134 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27135 
27136 	if (ipip->ipi_cmd_type == IF_CMD) {
27137 		/* This a old style SIOC[GS]IF* command */
27138 		ifr = (struct ifreq *)mp1->b_rptr;
27139 		sin = (sin_t *)&ifr->ifr_addr;
27140 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27141 		/* This a new style SIOC[GS]LIF* command */
27142 		lifr = (struct lifreq *)mp1->b_rptr;
27143 		sin = (sin_t *)&lifr->lifr_addr;
27144 	} else {
27145 		sin = NULL;
27146 	}
27147 
27148 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27149 	    ipip, mp1->b_rptr);
27150 
27151 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27152 }
27153 
27154 /*
27155  * ioctl processing
27156  *
27157  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27158  * the ioctl command in the ioctl tables and determines the copyin data size
27159  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27160  * size.
27161  *
27162  * ioctl processing then continues when the M_IOCDATA makes its way down.
27163  * Now the ioctl is looked up again in the ioctl table, and its properties are
27164  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27165  * and the general ioctl processing function ip_process_ioctl is called.
27166  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27167  * so goes thru the serialization primitive ipsq_try_enter. Then the
27168  * appropriate function to handle the ioctl is called based on the entry in
27169  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27170  * which also refreleases the 'conn' that was refheld at the start of the
27171  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27172  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27173  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27174  *
27175  * Many exclusive ioctls go thru an internal down up sequence as part of
27176  * the operation. For example an attempt to change the IP address of an
27177  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27178  * does all the cleanup such as deleting all ires that use this address.
27179  * Then we need to wait till all references to the interface go away.
27180  */
27181 void
27182 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27183 {
27184 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27185 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27186 	cmd_info_t ci;
27187 	int err;
27188 	boolean_t entered_ipsq = B_FALSE;
27189 
27190 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27191 
27192 	if (ipip == NULL)
27193 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27194 
27195 	/*
27196 	 * SIOCLIFADDIF needs to go thru a special path since the
27197 	 * ill may not exist yet. This happens in the case of lo0
27198 	 * which is created using this ioctl.
27199 	 */
27200 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27201 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27202 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27203 		return;
27204 	}
27205 
27206 	ci.ci_ipif = NULL;
27207 	switch (ipip->ipi_cmd_type) {
27208 	case IF_CMD:
27209 	case LIF_CMD:
27210 		/*
27211 		 * ioctls that pass in a [l]ifreq appear here.
27212 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27213 		 * ci.ci_ipif
27214 		 */
27215 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27216 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27217 		if (err != 0) {
27218 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27219 			return;
27220 		}
27221 		ASSERT(ci.ci_ipif != NULL);
27222 		break;
27223 
27224 	case TUN_CMD:
27225 		/*
27226 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27227 		 * a refheld ipif in ci.ci_ipif
27228 		 */
27229 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27230 		if (err != 0) {
27231 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27232 			return;
27233 		}
27234 		ASSERT(ci.ci_ipif != NULL);
27235 		break;
27236 
27237 	case MISC_CMD:
27238 		/*
27239 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27240 		 * For eg. SIOCGLIFCONF will appear here.
27241 		 */
27242 		switch (ipip->ipi_cmd) {
27243 		case IF_UNITSEL:
27244 			/* ioctl comes down the ill */
27245 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27246 			ipif_refhold(ci.ci_ipif);
27247 			break;
27248 		case SIOCGMSFILTER:
27249 		case SIOCSMSFILTER:
27250 		case SIOCGIPMSFILTER:
27251 		case SIOCSIPMSFILTER:
27252 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27253 			    ip_process_ioctl);
27254 			if (err != 0) {
27255 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27256 				    NULL);
27257 			}
27258 			break;
27259 		}
27260 		err = 0;
27261 		ci.ci_sin = NULL;
27262 		ci.ci_sin6 = NULL;
27263 		ci.ci_lifr = NULL;
27264 		break;
27265 	}
27266 
27267 	/*
27268 	 * If ipsq is non-null, we are already being called exclusively
27269 	 */
27270 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27271 	if (!(ipip->ipi_flags & IPI_WR)) {
27272 		/*
27273 		 * A return value of EINPROGRESS means the ioctl is
27274 		 * either queued and waiting for some reason or has
27275 		 * already completed.
27276 		 */
27277 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27278 		    ci.ci_lifr);
27279 		if (ci.ci_ipif != NULL)
27280 			ipif_refrele(ci.ci_ipif);
27281 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27282 		return;
27283 	}
27284 
27285 	ASSERT(ci.ci_ipif != NULL);
27286 
27287 	if (ipsq == NULL) {
27288 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27289 		    ip_process_ioctl, NEW_OP, B_TRUE);
27290 		entered_ipsq = B_TRUE;
27291 	}
27292 	/*
27293 	 * Release the ipif so that ipif_down and friends that wait for
27294 	 * references to go away are not misled about the current ipif_refcnt
27295 	 * values. We are writer so we can access the ipif even after releasing
27296 	 * the ipif.
27297 	 */
27298 	ipif_refrele(ci.ci_ipif);
27299 	if (ipsq == NULL)
27300 		return;
27301 
27302 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27303 
27304 	/*
27305 	 * For most set ioctls that come here, this serves as a single point
27306 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27307 	 * be any new references to the ipif. This helps functions that go
27308 	 * through this path and end up trying to wait for the refcnts
27309 	 * associated with the ipif to go down to zero. Some exceptions are
27310 	 * Failover, Failback, and Groupname commands that operate on more than
27311 	 * just the ci.ci_ipif. These commands internally determine the
27312 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27313 	 * flags on that set. Another exception is the Removeif command that
27314 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27315 	 * ipif to operate on.
27316 	 */
27317 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27318 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27319 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27320 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27321 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27322 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27323 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27324 
27325 	/*
27326 	 * A return value of EINPROGRESS means the ioctl is
27327 	 * either queued and waiting for some reason or has
27328 	 * already completed.
27329 	 */
27330 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27331 
27332 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27333 
27334 	if (entered_ipsq)
27335 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27336 }
27337 
27338 /*
27339  * Complete the ioctl. Typically ioctls use the mi package and need to
27340  * do mi_copyout/mi_copy_done.
27341  */
27342 void
27343 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27344 {
27345 	conn_t	*connp = NULL;
27346 
27347 	if (err == EINPROGRESS)
27348 		return;
27349 
27350 	if (CONN_Q(q)) {
27351 		connp = Q_TO_CONN(q);
27352 		ASSERT(connp->conn_ref >= 2);
27353 	}
27354 
27355 	switch (mode) {
27356 	case COPYOUT:
27357 		if (err == 0)
27358 			mi_copyout(q, mp);
27359 		else
27360 			mi_copy_done(q, mp, err);
27361 		break;
27362 
27363 	case NO_COPYOUT:
27364 		mi_copy_done(q, mp, err);
27365 		break;
27366 
27367 	default:
27368 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27369 		break;
27370 	}
27371 
27372 	/*
27373 	 * The refhold placed at the start of the ioctl is released here.
27374 	 */
27375 	if (connp != NULL)
27376 		CONN_OPER_PENDING_DONE(connp);
27377 
27378 	if (ipsq != NULL)
27379 		ipsq_current_finish(ipsq);
27380 }
27381 
27382 /*
27383  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27384  */
27385 /* ARGSUSED */
27386 void
27387 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27388 {
27389 	conn_t *connp = arg;
27390 	tcp_t	*tcp;
27391 
27392 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27393 	tcp = connp->conn_tcp;
27394 
27395 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27396 		freemsg(mp);
27397 	else
27398 		tcp_rput_other(tcp, mp);
27399 	CONN_OPER_PENDING_DONE(connp);
27400 }
27401 
27402 /* Called from ip_wput for all non data messages */
27403 /* ARGSUSED */
27404 void
27405 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27406 {
27407 	mblk_t		*mp1;
27408 	ire_t		*ire, *fake_ire;
27409 	ill_t		*ill;
27410 	struct iocblk	*iocp;
27411 	ip_ioctl_cmd_t	*ipip;
27412 	cred_t		*cr;
27413 	conn_t		*connp;
27414 	int		cmd, err;
27415 	nce_t		*nce;
27416 	ipif_t		*ipif;
27417 	ip_stack_t	*ipst;
27418 	char		*proto_str;
27419 
27420 	if (CONN_Q(q)) {
27421 		connp = Q_TO_CONN(q);
27422 		ipst = connp->conn_netstack->netstack_ip;
27423 	} else {
27424 		connp = NULL;
27425 		ipst = ILLQ_TO_IPST(q);
27426 	}
27427 
27428 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27429 
27430 	/* Check if it is a queue to /dev/sctp. */
27431 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27432 	    connp->conn_rq == NULL) {
27433 		sctp_wput(q, mp);
27434 		return;
27435 	}
27436 
27437 	switch (DB_TYPE(mp)) {
27438 	case M_IOCTL:
27439 		/*
27440 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27441 		 * will arrange to copy in associated control structures.
27442 		 */
27443 		ip_sioctl_copyin_setup(q, mp);
27444 		return;
27445 	case M_IOCDATA:
27446 		/*
27447 		 * Ensure that this is associated with one of our trans-
27448 		 * parent ioctls.  If it's not ours, discard it if we're
27449 		 * running as a driver, or pass it on if we're a module.
27450 		 */
27451 		iocp = (struct iocblk *)mp->b_rptr;
27452 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27453 		if (ipip == NULL) {
27454 			if (q->q_next == NULL) {
27455 				goto nak;
27456 			} else {
27457 				putnext(q, mp);
27458 			}
27459 			return;
27460 		} else if ((q->q_next != NULL) &&
27461 		    !(ipip->ipi_flags & IPI_MODOK)) {
27462 			/*
27463 			 * the ioctl is one we recognise, but is not
27464 			 * consumed by IP as a module, pass M_IOCDATA
27465 			 * for processing downstream, but only for
27466 			 * common Streams ioctls.
27467 			 */
27468 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27469 				putnext(q, mp);
27470 				return;
27471 			} else {
27472 				goto nak;
27473 			}
27474 		}
27475 
27476 		/* IOCTL continuation following copyin or copyout. */
27477 		if (mi_copy_state(q, mp, NULL) == -1) {
27478 			/*
27479 			 * The copy operation failed.  mi_copy_state already
27480 			 * cleaned up, so we're out of here.
27481 			 */
27482 			return;
27483 		}
27484 		/*
27485 		 * If we just completed a copy in, we become writer and
27486 		 * continue processing in ip_sioctl_copyin_done.  If it
27487 		 * was a copy out, we call mi_copyout again.  If there is
27488 		 * nothing more to copy out, it will complete the IOCTL.
27489 		 */
27490 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27491 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27492 				mi_copy_done(q, mp, EPROTO);
27493 				return;
27494 			}
27495 			/*
27496 			 * Check for cases that need more copying.  A return
27497 			 * value of 0 means a second copyin has been started,
27498 			 * so we return; a return value of 1 means no more
27499 			 * copying is needed, so we continue.
27500 			 */
27501 			cmd = iocp->ioc_cmd;
27502 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27503 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27504 			    MI_COPY_COUNT(mp) == 1) {
27505 				if (ip_copyin_msfilter(q, mp) == 0)
27506 					return;
27507 			}
27508 			/*
27509 			 * Refhold the conn, till the ioctl completes. This is
27510 			 * needed in case the ioctl ends up in the pending mp
27511 			 * list. Every mp in the ill_pending_mp list and
27512 			 * the ipsq_pending_mp must have a refhold on the conn
27513 			 * to resume processing. The refhold is released when
27514 			 * the ioctl completes. (normally or abnormally)
27515 			 * In all cases ip_ioctl_finish is called to finish
27516 			 * the ioctl.
27517 			 */
27518 			if (connp != NULL) {
27519 				/* This is not a reentry */
27520 				ASSERT(ipsq == NULL);
27521 				CONN_INC_REF(connp);
27522 			} else {
27523 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27524 					mi_copy_done(q, mp, EINVAL);
27525 					return;
27526 				}
27527 			}
27528 
27529 			ip_process_ioctl(ipsq, q, mp, ipip);
27530 
27531 		} else {
27532 			mi_copyout(q, mp);
27533 		}
27534 		return;
27535 nak:
27536 		iocp->ioc_error = EINVAL;
27537 		mp->b_datap->db_type = M_IOCNAK;
27538 		iocp->ioc_count = 0;
27539 		qreply(q, mp);
27540 		return;
27541 
27542 	case M_IOCNAK:
27543 		/*
27544 		 * The only way we could get here is if a resolver didn't like
27545 		 * an IOCTL we sent it.	 This shouldn't happen.
27546 		 */
27547 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27548 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27549 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27550 		freemsg(mp);
27551 		return;
27552 	case M_IOCACK:
27553 		/* /dev/ip shouldn't see this */
27554 		if (CONN_Q(q))
27555 			goto nak;
27556 
27557 		/* Finish socket ioctls passed through to ARP. */
27558 		ip_sioctl_iocack(q, mp);
27559 		return;
27560 	case M_FLUSH:
27561 		if (*mp->b_rptr & FLUSHW)
27562 			flushq(q, FLUSHALL);
27563 		if (q->q_next) {
27564 			/*
27565 			 * M_FLUSH is sent up to IP by some drivers during
27566 			 * unbind. ip_rput has already replied to it. We are
27567 			 * here for the M_FLUSH that we originated in IP
27568 			 * before sending the unbind request to the driver.
27569 			 * Just free it as we don't queue packets in IP
27570 			 * on the write side of the device instance.
27571 			 */
27572 			freemsg(mp);
27573 			return;
27574 		}
27575 		if (*mp->b_rptr & FLUSHR) {
27576 			*mp->b_rptr &= ~FLUSHW;
27577 			qreply(q, mp);
27578 			return;
27579 		}
27580 		freemsg(mp);
27581 		return;
27582 	case IRE_DB_REQ_TYPE:
27583 		if (connp == NULL) {
27584 			proto_str = "IRE_DB_REQ_TYPE";
27585 			goto protonak;
27586 		}
27587 		/* An Upper Level Protocol wants a copy of an IRE. */
27588 		ip_ire_req(q, mp);
27589 		return;
27590 	case M_CTL:
27591 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27592 			break;
27593 
27594 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27595 		    TUN_HELLO) {
27596 			ASSERT(connp != NULL);
27597 			connp->conn_flags |= IPCL_IPTUN;
27598 			freeb(mp);
27599 			return;
27600 		}
27601 
27602 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27603 		    IP_ULP_OUT_LABELED) {
27604 			out_labeled_t *olp;
27605 
27606 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27607 				break;
27608 			olp = (out_labeled_t *)mp->b_rptr;
27609 			connp->conn_ulp_labeled = olp->out_qnext == q;
27610 			freemsg(mp);
27611 			return;
27612 		}
27613 
27614 		/* M_CTL messages are used by ARP to tell us things. */
27615 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27616 			break;
27617 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27618 		case AR_ENTRY_SQUERY:
27619 			ip_wput_ctl(q, mp);
27620 			return;
27621 		case AR_CLIENT_NOTIFY:
27622 			ip_arp_news(q, mp);
27623 			return;
27624 		case AR_DLPIOP_DONE:
27625 			ASSERT(q->q_next != NULL);
27626 			ill = (ill_t *)q->q_ptr;
27627 			/* qwriter_ip releases the refhold */
27628 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27629 			ill_refhold(ill);
27630 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
27631 			    CUR_OP, B_FALSE);
27632 			return;
27633 		case AR_ARP_CLOSING:
27634 			/*
27635 			 * ARP (above us) is closing. If no ARP bringup is
27636 			 * currently pending, ack the message so that ARP
27637 			 * can complete its close. Also mark ill_arp_closing
27638 			 * so that new ARP bringups will fail. If any
27639 			 * ARP bringup is currently in progress, we will
27640 			 * ack this when the current ARP bringup completes.
27641 			 */
27642 			ASSERT(q->q_next != NULL);
27643 			ill = (ill_t *)q->q_ptr;
27644 			mutex_enter(&ill->ill_lock);
27645 			ill->ill_arp_closing = 1;
27646 			if (!ill->ill_arp_bringup_pending) {
27647 				mutex_exit(&ill->ill_lock);
27648 				qreply(q, mp);
27649 			} else {
27650 				mutex_exit(&ill->ill_lock);
27651 				freemsg(mp);
27652 			}
27653 			return;
27654 		case AR_ARP_EXTEND:
27655 			/*
27656 			 * The ARP module above us is capable of duplicate
27657 			 * address detection.  Old ATM drivers will not send
27658 			 * this message.
27659 			 */
27660 			ASSERT(q->q_next != NULL);
27661 			ill = (ill_t *)q->q_ptr;
27662 			ill->ill_arp_extend = B_TRUE;
27663 			freemsg(mp);
27664 			return;
27665 		default:
27666 			break;
27667 		}
27668 		break;
27669 	case M_PROTO:
27670 	case M_PCPROTO:
27671 		/*
27672 		 * The only PROTO messages we expect are ULP binds and
27673 		 * copies of option negotiation acknowledgements.
27674 		 */
27675 		switch (((union T_primitives *)mp->b_rptr)->type) {
27676 		case O_T_BIND_REQ:
27677 		case T_BIND_REQ: {
27678 			/* Request can get queued in bind */
27679 			if (connp == NULL) {
27680 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27681 				goto protonak;
27682 			}
27683 			/*
27684 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27685 			 * instead of going through this path.  We only get
27686 			 * here in the following cases:
27687 			 *
27688 			 * a. Bind retries, where ipsq is non-NULL.
27689 			 * b. T_BIND_REQ is issued from non TCP/UDP
27690 			 *    transport, e.g. icmp for raw socket,
27691 			 *    in which case ipsq will be NULL.
27692 			 */
27693 			ASSERT(ipsq != NULL ||
27694 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27695 
27696 			/* Don't increment refcnt if this is a re-entry */
27697 			if (ipsq == NULL)
27698 				CONN_INC_REF(connp);
27699 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27700 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27701 			if (mp == NULL)
27702 				return;
27703 			if (IPCL_IS_TCP(connp)) {
27704 				/*
27705 				 * In the case of TCP endpoint we
27706 				 * come here only for bind retries
27707 				 */
27708 				ASSERT(ipsq != NULL);
27709 				CONN_INC_REF(connp);
27710 				squeue_fill(connp->conn_sqp, mp,
27711 				    ip_resume_tcp_bind, connp,
27712 				    SQTAG_BIND_RETRY);
27713 				return;
27714 			} else if (IPCL_IS_UDP(connp)) {
27715 				/*
27716 				 * In the case of UDP endpoint we
27717 				 * come here only for bind retries
27718 				 */
27719 				ASSERT(ipsq != NULL);
27720 				udp_resume_bind(connp, mp);
27721 				return;
27722 			}
27723 			qreply(q, mp);
27724 			CONN_OPER_PENDING_DONE(connp);
27725 			return;
27726 		}
27727 		case T_SVR4_OPTMGMT_REQ:
27728 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27729 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27730 
27731 			if (connp == NULL) {
27732 				proto_str = "T_SVR4_OPTMGMT_REQ";
27733 				goto protonak;
27734 			}
27735 
27736 			if (!snmpcom_req(q, mp, ip_snmp_set,
27737 			    ip_snmp_get, cr)) {
27738 				/*
27739 				 * Call svr4_optcom_req so that it can
27740 				 * generate the ack. We don't come here
27741 				 * if this operation is being restarted.
27742 				 * ip_restart_optmgmt will drop the conn ref.
27743 				 * In the case of ipsec option after the ipsec
27744 				 * load is complete conn_restart_ipsec_waiter
27745 				 * drops the conn ref.
27746 				 */
27747 				ASSERT(ipsq == NULL);
27748 				CONN_INC_REF(connp);
27749 				if (ip_check_for_ipsec_opt(q, mp))
27750 					return;
27751 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27752 				if (err != EINPROGRESS) {
27753 					/* Operation is done */
27754 					CONN_OPER_PENDING_DONE(connp);
27755 				}
27756 			}
27757 			return;
27758 		case T_OPTMGMT_REQ:
27759 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27760 			/*
27761 			 * Note: No snmpcom_req support through new
27762 			 * T_OPTMGMT_REQ.
27763 			 * Call tpi_optcom_req so that it can
27764 			 * generate the ack.
27765 			 */
27766 			if (connp == NULL) {
27767 				proto_str = "T_OPTMGMT_REQ";
27768 				goto protonak;
27769 			}
27770 
27771 			ASSERT(ipsq == NULL);
27772 			/*
27773 			 * We don't come here for restart. ip_restart_optmgmt
27774 			 * will drop the conn ref. In the case of ipsec option
27775 			 * after the ipsec load is complete
27776 			 * conn_restart_ipsec_waiter drops the conn ref.
27777 			 */
27778 			CONN_INC_REF(connp);
27779 			if (ip_check_for_ipsec_opt(q, mp))
27780 				return;
27781 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27782 			if (err != EINPROGRESS) {
27783 				/* Operation is done */
27784 				CONN_OPER_PENDING_DONE(connp);
27785 			}
27786 			return;
27787 		case T_UNBIND_REQ:
27788 			if (connp == NULL) {
27789 				proto_str = "T_UNBIND_REQ";
27790 				goto protonak;
27791 			}
27792 			mp = ip_unbind(q, mp);
27793 			qreply(q, mp);
27794 			return;
27795 		default:
27796 			/*
27797 			 * Have to drop any DLPI messages coming down from
27798 			 * arp (such as an info_req which would cause ip
27799 			 * to receive an extra info_ack if it was passed
27800 			 * through.
27801 			 */
27802 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27803 			    (int)*(uint_t *)mp->b_rptr));
27804 			freemsg(mp);
27805 			return;
27806 		}
27807 		/* NOTREACHED */
27808 	case IRE_DB_TYPE: {
27809 		nce_t		*nce;
27810 		ill_t		*ill;
27811 		in6_addr_t	gw_addr_v6;
27812 
27813 
27814 		/*
27815 		 * This is a response back from a resolver.  It
27816 		 * consists of a message chain containing:
27817 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27818 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27819 		 * The LL_HDR_MBLK is the DLPI header to use to get
27820 		 * the attached packet, and subsequent ones for the
27821 		 * same destination, transmitted.
27822 		 */
27823 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27824 			break;
27825 		/*
27826 		 * First, check to make sure the resolution succeeded.
27827 		 * If it failed, the second mblk will be empty.
27828 		 * If it is, free the chain, dropping the packet.
27829 		 * (We must ire_delete the ire; that frees the ire mblk)
27830 		 * We're doing this now to support PVCs for ATM; it's
27831 		 * a partial xresolv implementation. When we fully implement
27832 		 * xresolv interfaces, instead of freeing everything here
27833 		 * we'll initiate neighbor discovery.
27834 		 *
27835 		 * For v4 (ARP and other external resolvers) the resolver
27836 		 * frees the message, so no check is needed. This check
27837 		 * is required, though, for a full xresolve implementation.
27838 		 * Including this code here now both shows how external
27839 		 * resolvers can NACK a resolution request using an
27840 		 * existing design that has no specific provisions for NACKs,
27841 		 * and also takes into account that the current non-ARP
27842 		 * external resolver has been coded to use this method of
27843 		 * NACKing for all IPv6 (xresolv) cases,
27844 		 * whether our xresolv implementation is complete or not.
27845 		 *
27846 		 */
27847 		ire = (ire_t *)mp->b_rptr;
27848 		ill = ire_to_ill(ire);
27849 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27850 		if (mp1->b_rptr == mp1->b_wptr) {
27851 			if (ire->ire_ipversion == IPV6_VERSION) {
27852 				/*
27853 				 * XRESOLV interface.
27854 				 */
27855 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27856 				mutex_enter(&ire->ire_lock);
27857 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27858 				mutex_exit(&ire->ire_lock);
27859 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27860 					nce = ndp_lookup_v6(ill,
27861 					    &ire->ire_addr_v6, B_FALSE);
27862 				} else {
27863 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27864 					    B_FALSE);
27865 				}
27866 				if (nce != NULL) {
27867 					nce_resolv_failed(nce);
27868 					ndp_delete(nce);
27869 					NCE_REFRELE(nce);
27870 				}
27871 			}
27872 			mp->b_cont = NULL;
27873 			freemsg(mp1);		/* frees the pkt as well */
27874 			ASSERT(ire->ire_nce == NULL);
27875 			ire_delete((ire_t *)mp->b_rptr);
27876 			return;
27877 		}
27878 
27879 		/*
27880 		 * Split them into IRE_MBLK and pkt and feed it into
27881 		 * ire_add_then_send. Then in ire_add_then_send
27882 		 * the IRE will be added, and then the packet will be
27883 		 * run back through ip_wput. This time it will make
27884 		 * it to the wire.
27885 		 */
27886 		mp->b_cont = NULL;
27887 		mp = mp1->b_cont;		/* now, mp points to pkt */
27888 		mp1->b_cont = NULL;
27889 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27890 		if (ire->ire_ipversion == IPV6_VERSION) {
27891 			/*
27892 			 * XRESOLV interface. Find the nce and put a copy
27893 			 * of the dl_unitdata_req in nce_res_mp
27894 			 */
27895 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27896 			mutex_enter(&ire->ire_lock);
27897 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27898 			mutex_exit(&ire->ire_lock);
27899 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27900 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27901 				    B_FALSE);
27902 			} else {
27903 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27904 			}
27905 			if (nce != NULL) {
27906 				/*
27907 				 * We have to protect nce_res_mp here
27908 				 * from being accessed by other threads
27909 				 * while we change the mblk pointer.
27910 				 * Other functions will also lock the nce when
27911 				 * accessing nce_res_mp.
27912 				 *
27913 				 * The reason we change the mblk pointer
27914 				 * here rather than copying the resolved address
27915 				 * into the template is that, unlike with
27916 				 * ethernet, we have no guarantee that the
27917 				 * resolved address length will be
27918 				 * smaller than or equal to the lla length
27919 				 * with which the template was allocated,
27920 				 * (for ethernet, they're equal)
27921 				 * so we have to use the actual resolved
27922 				 * address mblk - which holds the real
27923 				 * dl_unitdata_req with the resolved address.
27924 				 *
27925 				 * Doing this is the same behavior as was
27926 				 * previously used in the v4 ARP case.
27927 				 */
27928 				mutex_enter(&nce->nce_lock);
27929 				if (nce->nce_res_mp != NULL)
27930 					freemsg(nce->nce_res_mp);
27931 				nce->nce_res_mp = mp1;
27932 				mutex_exit(&nce->nce_lock);
27933 				/*
27934 				 * We do a fastpath probe here because
27935 				 * we have resolved the address without
27936 				 * using Neighbor Discovery.
27937 				 * In the non-XRESOLV v6 case, the fastpath
27938 				 * probe is done right after neighbor
27939 				 * discovery completes.
27940 				 */
27941 				if (nce->nce_res_mp != NULL) {
27942 					int res;
27943 					nce_fastpath_list_add(nce);
27944 					res = ill_fastpath_probe(ill,
27945 					    nce->nce_res_mp);
27946 					if (res != 0 && res != EAGAIN)
27947 						nce_fastpath_list_delete(nce);
27948 				}
27949 
27950 				ire_add_then_send(q, ire, mp);
27951 				/*
27952 				 * Now we have to clean out any packets
27953 				 * that may have been queued on the nce
27954 				 * while it was waiting for address resolution
27955 				 * to complete.
27956 				 */
27957 				mutex_enter(&nce->nce_lock);
27958 				mp1 = nce->nce_qd_mp;
27959 				nce->nce_qd_mp = NULL;
27960 				mutex_exit(&nce->nce_lock);
27961 				while (mp1 != NULL) {
27962 					mblk_t *nxt_mp;
27963 					queue_t *fwdq = NULL;
27964 					ill_t   *inbound_ill;
27965 					uint_t ifindex;
27966 
27967 					nxt_mp = mp1->b_next;
27968 					mp1->b_next = NULL;
27969 					/*
27970 					 * Retrieve ifindex stored in
27971 					 * ip_rput_data_v6()
27972 					 */
27973 					ifindex =
27974 					    (uint_t)(uintptr_t)mp1->b_prev;
27975 					inbound_ill =
27976 						ill_lookup_on_ifindex(ifindex,
27977 						    B_TRUE, NULL, NULL, NULL,
27978 						    NULL, ipst);
27979 					mp1->b_prev = NULL;
27980 					if (inbound_ill != NULL)
27981 						fwdq = inbound_ill->ill_rq;
27982 
27983 					if (fwdq != NULL) {
27984 						put(fwdq, mp1);
27985 						ill_refrele(inbound_ill);
27986 					} else
27987 						put(WR(ill->ill_rq), mp1);
27988 					mp1 = nxt_mp;
27989 				}
27990 				NCE_REFRELE(nce);
27991 			} else {	/* nce is NULL; clean up */
27992 				ire_delete(ire);
27993 				freemsg(mp);
27994 				freemsg(mp1);
27995 				return;
27996 			}
27997 		} else {
27998 			nce_t *arpce;
27999 			/*
28000 			 * Link layer resolution succeeded. Recompute the
28001 			 * ire_nce.
28002 			 */
28003 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
28004 			if ((arpce = ndp_lookup_v4(ill,
28005 			    (ire->ire_gateway_addr != INADDR_ANY ?
28006 			    &ire->ire_gateway_addr : &ire->ire_addr),
28007 			    B_FALSE)) == NULL) {
28008 				freeb(ire->ire_mp);
28009 				freeb(mp1);
28010 				freemsg(mp);
28011 				return;
28012 			}
28013 			mutex_enter(&arpce->nce_lock);
28014 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
28015 			if (arpce->nce_state == ND_REACHABLE) {
28016 				/*
28017 				 * Someone resolved this before us;
28018 				 * cleanup the res_mp. Since ire has
28019 				 * not been added yet, the call to ire_add_v4
28020 				 * from ire_add_then_send (when a dup is
28021 				 * detected) will clean up the ire.
28022 				 */
28023 				freeb(mp1);
28024 			} else {
28025 				if (arpce->nce_res_mp != NULL)
28026 					freemsg(arpce->nce_res_mp);
28027 				arpce->nce_res_mp = mp1;
28028 				arpce->nce_state = ND_REACHABLE;
28029 			}
28030 			mutex_exit(&arpce->nce_lock);
28031 			if (ire->ire_marks & IRE_MARK_NOADD) {
28032 				/*
28033 				 * this ire will not be added to the ire
28034 				 * cache table, so we can set the ire_nce
28035 				 * here, as there are no atomicity constraints.
28036 				 */
28037 				ire->ire_nce = arpce;
28038 				/*
28039 				 * We are associating this nce with the ire
28040 				 * so change the nce ref taken in
28041 				 * ndp_lookup_v4() from
28042 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28043 				 */
28044 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28045 			} else {
28046 				NCE_REFRELE(arpce);
28047 			}
28048 			ire_add_then_send(q, ire, mp);
28049 		}
28050 		return;	/* All is well, the packet has been sent. */
28051 	}
28052 	case IRE_ARPRESOLVE_TYPE: {
28053 
28054 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28055 			break;
28056 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28057 		mp->b_cont = NULL;
28058 		/*
28059 		 * First, check to make sure the resolution succeeded.
28060 		 * If it failed, the second mblk will be empty.
28061 		 */
28062 		if (mp1->b_rptr == mp1->b_wptr) {
28063 			/* cleanup  the incomplete ire, free queued packets */
28064 			freemsg(mp); /* fake ire */
28065 			freeb(mp1);  /* dl_unitdata response */
28066 			return;
28067 		}
28068 
28069 		/*
28070 		 * update any incomplete nce_t found. we lookup the ctable
28071 		 * and find the nce from the ire->ire_nce because we need
28072 		 * to pass the ire to ip_xmit_v4 later, and can find both
28073 		 * ire and nce in one lookup from the ctable.
28074 		 */
28075 		fake_ire = (ire_t *)mp->b_rptr;
28076 		/*
28077 		 * By the time we come back here from ARP
28078 		 * the logical outgoing interface  of the incomplete ire
28079 		 * we added in ire_forward could have disappeared,
28080 		 * causing the incomplete ire to also have
28081 		 * dissapeared. So we need to retreive the
28082 		 * proper ipif for the ire  before looking
28083 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28084 		 */
28085 		ill = q->q_ptr;
28086 
28087 		/* Get the outgoing ipif */
28088 		mutex_enter(&ill->ill_lock);
28089 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28090 			mutex_exit(&ill->ill_lock);
28091 			freemsg(mp); /* fake ire */
28092 			freeb(mp1);  /* dl_unitdata response */
28093 			return;
28094 		}
28095 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28096 
28097 		if (ipif == NULL) {
28098 			mutex_exit(&ill->ill_lock);
28099 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28100 			freemsg(mp);
28101 			freeb(mp1);
28102 			return;
28103 		}
28104 		ipif_refhold_locked(ipif);
28105 		mutex_exit(&ill->ill_lock);
28106 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28107 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28108 		    ipif, fake_ire->ire_zoneid, NULL,
28109 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28110 		ipif_refrele(ipif);
28111 		if (ire == NULL) {
28112 			/*
28113 			 * no ire was found; check if there is an nce
28114 			 * for this lookup; if it has no ire's pointing at it
28115 			 * cleanup.
28116 			 */
28117 			if ((nce = ndp_lookup_v4(ill,
28118 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28119 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28120 			    B_FALSE)) != NULL) {
28121 				/*
28122 				 * cleanup: just reset nce.
28123 				 * We check for refcnt 2 (one for the nce
28124 				 * hash list + 1 for the ref taken by
28125 				 * ndp_lookup_v4) to ensure that there are
28126 				 * no ire's pointing at the nce.
28127 				 */
28128 				if (nce->nce_refcnt == 2) {
28129 					nce = nce_reinit(nce);
28130 				}
28131 				if (nce != NULL)
28132 					NCE_REFRELE(nce);
28133 			}
28134 			freeb(mp1);  /* dl_unitdata response */
28135 			freemsg(mp); /* fake ire */
28136 			return;
28137 		}
28138 		nce = ire->ire_nce;
28139 		DTRACE_PROBE2(ire__arpresolve__type,
28140 		    ire_t *, ire, nce_t *, nce);
28141 		ASSERT(nce->nce_state != ND_INITIAL);
28142 		mutex_enter(&nce->nce_lock);
28143 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28144 		if (nce->nce_state == ND_REACHABLE) {
28145 			/*
28146 			 * Someone resolved this before us;
28147 			 * our response is not needed any more.
28148 			 */
28149 			mutex_exit(&nce->nce_lock);
28150 			freeb(mp1);  /* dl_unitdata response */
28151 		} else {
28152 			if (nce->nce_res_mp != NULL) {
28153 				freemsg(nce->nce_res_mp);
28154 				/* existing dl_unitdata template */
28155 			}
28156 			nce->nce_res_mp = mp1;
28157 			nce->nce_state = ND_REACHABLE;
28158 			mutex_exit(&nce->nce_lock);
28159 			nce_fastpath(nce);
28160 		}
28161 		/*
28162 		 * The cached nce_t has been updated to be reachable;
28163 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
28164 		 */
28165 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28166 		freemsg(mp);
28167 		/*
28168 		 * send out queued packets.
28169 		 */
28170 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28171 
28172 		IRE_REFRELE(ire);
28173 		return;
28174 	}
28175 	default:
28176 		break;
28177 	}
28178 	if (q->q_next) {
28179 		putnext(q, mp);
28180 	} else
28181 		freemsg(mp);
28182 	return;
28183 
28184 protonak:
28185 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28186 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28187 		qreply(q, mp);
28188 }
28189 
28190 /*
28191  * Process IP options in an outbound packet.  Modify the destination if there
28192  * is a source route option.
28193  * Returns non-zero if something fails in which case an ICMP error has been
28194  * sent and mp freed.
28195  */
28196 static int
28197 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28198     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28199 {
28200 	ipoptp_t	opts;
28201 	uchar_t		*opt;
28202 	uint8_t		optval;
28203 	uint8_t		optlen;
28204 	ipaddr_t	dst;
28205 	intptr_t	code = 0;
28206 	mblk_t		*mp;
28207 	ire_t		*ire = NULL;
28208 
28209 	ip2dbg(("ip_wput_options\n"));
28210 	mp = ipsec_mp;
28211 	if (mctl_present) {
28212 		mp = ipsec_mp->b_cont;
28213 	}
28214 
28215 	dst = ipha->ipha_dst;
28216 	for (optval = ipoptp_first(&opts, ipha);
28217 	    optval != IPOPT_EOL;
28218 	    optval = ipoptp_next(&opts)) {
28219 		opt = opts.ipoptp_cur;
28220 		optlen = opts.ipoptp_len;
28221 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28222 		    optval, optlen));
28223 		switch (optval) {
28224 			uint32_t off;
28225 		case IPOPT_SSRR:
28226 		case IPOPT_LSRR:
28227 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28228 				ip1dbg((
28229 				    "ip_wput_options: bad option offset\n"));
28230 				code = (char *)&opt[IPOPT_OLEN] -
28231 				    (char *)ipha;
28232 				goto param_prob;
28233 			}
28234 			off = opt[IPOPT_OFFSET];
28235 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28236 			    ntohl(dst)));
28237 			/*
28238 			 * For strict: verify that dst is directly
28239 			 * reachable.
28240 			 */
28241 			if (optval == IPOPT_SSRR) {
28242 				ire = ire_ftable_lookup(dst, 0, 0,
28243 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28244 				    MBLK_GETLABEL(mp),
28245 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28246 				if (ire == NULL) {
28247 					ip1dbg(("ip_wput_options: SSRR not"
28248 					    " directly reachable: 0x%x\n",
28249 					    ntohl(dst)));
28250 					goto bad_src_route;
28251 				}
28252 				ire_refrele(ire);
28253 			}
28254 			break;
28255 		case IPOPT_RR:
28256 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28257 				ip1dbg((
28258 				    "ip_wput_options: bad option offset\n"));
28259 				code = (char *)&opt[IPOPT_OLEN] -
28260 				    (char *)ipha;
28261 				goto param_prob;
28262 			}
28263 			break;
28264 		case IPOPT_TS:
28265 			/*
28266 			 * Verify that length >=5 and that there is either
28267 			 * room for another timestamp or that the overflow
28268 			 * counter is not maxed out.
28269 			 */
28270 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28271 			if (optlen < IPOPT_MINLEN_IT) {
28272 				goto param_prob;
28273 			}
28274 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28275 				ip1dbg((
28276 				    "ip_wput_options: bad option offset\n"));
28277 				code = (char *)&opt[IPOPT_OFFSET] -
28278 				    (char *)ipha;
28279 				goto param_prob;
28280 			}
28281 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28282 			case IPOPT_TS_TSONLY:
28283 				off = IPOPT_TS_TIMELEN;
28284 				break;
28285 			case IPOPT_TS_TSANDADDR:
28286 			case IPOPT_TS_PRESPEC:
28287 			case IPOPT_TS_PRESPEC_RFC791:
28288 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28289 				break;
28290 			default:
28291 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28292 				    (char *)ipha;
28293 				goto param_prob;
28294 			}
28295 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28296 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28297 				/*
28298 				 * No room and the overflow counter is 15
28299 				 * already.
28300 				 */
28301 				goto param_prob;
28302 			}
28303 			break;
28304 		}
28305 	}
28306 
28307 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28308 		return (0);
28309 
28310 	ip1dbg(("ip_wput_options: error processing IP options."));
28311 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28312 
28313 param_prob:
28314 	/*
28315 	 * Since ip_wput() isn't close to finished, we fill
28316 	 * in enough of the header for credible error reporting.
28317 	 */
28318 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28319 		/* Failed */
28320 		freemsg(ipsec_mp);
28321 		return (-1);
28322 	}
28323 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28324 	return (-1);
28325 
28326 bad_src_route:
28327 	/*
28328 	 * Since ip_wput() isn't close to finished, we fill
28329 	 * in enough of the header for credible error reporting.
28330 	 */
28331 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28332 		/* Failed */
28333 		freemsg(ipsec_mp);
28334 		return (-1);
28335 	}
28336 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28337 	return (-1);
28338 }
28339 
28340 /*
28341  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28342  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28343  * thru /etc/system.
28344  */
28345 #define	CONN_MAXDRAINCNT	64
28346 
28347 static void
28348 conn_drain_init(ip_stack_t *ipst)
28349 {
28350 	int i;
28351 
28352 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28353 
28354 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28355 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28356 		/*
28357 		 * Default value of the number of drainers is the
28358 		 * number of cpus, subject to maximum of 8 drainers.
28359 		 */
28360 		if (boot_max_ncpus != -1)
28361 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28362 		else
28363 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28364 	}
28365 
28366 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28367 	    sizeof (idl_t), KM_SLEEP);
28368 
28369 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28370 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28371 		    MUTEX_DEFAULT, NULL);
28372 	}
28373 }
28374 
28375 static void
28376 conn_drain_fini(ip_stack_t *ipst)
28377 {
28378 	int i;
28379 
28380 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28381 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28382 	kmem_free(ipst->ips_conn_drain_list,
28383 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28384 	ipst->ips_conn_drain_list = NULL;
28385 }
28386 
28387 /*
28388  * Note: For an overview of how flowcontrol is handled in IP please see the
28389  * IP Flowcontrol notes at the top of this file.
28390  *
28391  * Flow control has blocked us from proceeding. Insert the given conn in one
28392  * of the conn drain lists. These conn wq's will be qenabled later on when
28393  * STREAMS flow control does a backenable. conn_walk_drain will enable
28394  * the first conn in each of these drain lists. Each of these qenabled conns
28395  * in turn enables the next in the list, after it runs, or when it closes,
28396  * thus sustaining the drain process.
28397  *
28398  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28399  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28400  * running at any time, on a given conn, since there can be only 1 service proc
28401  * running on a queue at any time.
28402  */
28403 void
28404 conn_drain_insert(conn_t *connp)
28405 {
28406 	idl_t	*idl;
28407 	uint_t	index;
28408 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28409 
28410 	mutex_enter(&connp->conn_lock);
28411 	if (connp->conn_state_flags & CONN_CLOSING) {
28412 		/*
28413 		 * The conn is closing as a result of which CONN_CLOSING
28414 		 * is set. Return.
28415 		 */
28416 		mutex_exit(&connp->conn_lock);
28417 		return;
28418 	} else if (connp->conn_idl == NULL) {
28419 		/*
28420 		 * Assign the next drain list round robin. We dont' use
28421 		 * a lock, and thus it may not be strictly round robin.
28422 		 * Atomicity of load/stores is enough to make sure that
28423 		 * conn_drain_list_index is always within bounds.
28424 		 */
28425 		index = ipst->ips_conn_drain_list_index;
28426 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28427 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28428 		index++;
28429 		if (index == ipst->ips_conn_drain_list_cnt)
28430 			index = 0;
28431 		ipst->ips_conn_drain_list_index = index;
28432 	}
28433 	mutex_exit(&connp->conn_lock);
28434 
28435 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28436 	if ((connp->conn_drain_prev != NULL) ||
28437 	    (connp->conn_state_flags & CONN_CLOSING)) {
28438 		/*
28439 		 * The conn is already in the drain list, OR
28440 		 * the conn is closing. We need to check again for
28441 		 * the closing case again since close can happen
28442 		 * after we drop the conn_lock, and before we
28443 		 * acquire the CONN_DRAIN_LIST_LOCK.
28444 		 */
28445 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28446 		return;
28447 	} else {
28448 		idl = connp->conn_idl;
28449 	}
28450 
28451 	/*
28452 	 * The conn is not in the drain list. Insert it at the
28453 	 * tail of the drain list. The drain list is circular
28454 	 * and doubly linked. idl_conn points to the 1st element
28455 	 * in the list.
28456 	 */
28457 	if (idl->idl_conn == NULL) {
28458 		idl->idl_conn = connp;
28459 		connp->conn_drain_next = connp;
28460 		connp->conn_drain_prev = connp;
28461 	} else {
28462 		conn_t *head = idl->idl_conn;
28463 
28464 		connp->conn_drain_next = head;
28465 		connp->conn_drain_prev = head->conn_drain_prev;
28466 		head->conn_drain_prev->conn_drain_next = connp;
28467 		head->conn_drain_prev = connp;
28468 	}
28469 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28470 }
28471 
28472 /*
28473  * This conn is closing, and we are called from ip_close. OR
28474  * This conn has been serviced by ip_wsrv, and we need to do the tail
28475  * processing.
28476  * If this conn is part of the drain list, we may need to sustain the drain
28477  * process by qenabling the next conn in the drain list. We may also need to
28478  * remove this conn from the list, if it is done.
28479  */
28480 static void
28481 conn_drain_tail(conn_t *connp, boolean_t closing)
28482 {
28483 	idl_t *idl;
28484 
28485 	/*
28486 	 * connp->conn_idl is stable at this point, and no lock is needed
28487 	 * to check it. If we are called from ip_close, close has already
28488 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28489 	 * called us only because conn_idl is non-null. If we are called thru
28490 	 * service, conn_idl could be null, but it cannot change because
28491 	 * service is single-threaded per queue, and there cannot be another
28492 	 * instance of service trying to call conn_drain_insert on this conn
28493 	 * now.
28494 	 */
28495 	ASSERT(!closing || (connp->conn_idl != NULL));
28496 
28497 	/*
28498 	 * If connp->conn_idl is null, the conn has not been inserted into any
28499 	 * drain list even once since creation of the conn. Just return.
28500 	 */
28501 	if (connp->conn_idl == NULL)
28502 		return;
28503 
28504 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28505 
28506 	if (connp->conn_drain_prev == NULL) {
28507 		/* This conn is currently not in the drain list.  */
28508 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28509 		return;
28510 	}
28511 	idl = connp->conn_idl;
28512 	if (idl->idl_conn_draining == connp) {
28513 		/*
28514 		 * This conn is the current drainer. If this is the last conn
28515 		 * in the drain list, we need to do more checks, in the 'if'
28516 		 * below. Otherwwise we need to just qenable the next conn,
28517 		 * to sustain the draining, and is handled in the 'else'
28518 		 * below.
28519 		 */
28520 		if (connp->conn_drain_next == idl->idl_conn) {
28521 			/*
28522 			 * This conn is the last in this list. This round
28523 			 * of draining is complete. If idl_repeat is set,
28524 			 * it means another flow enabling has happened from
28525 			 * the driver/streams and we need to another round
28526 			 * of draining.
28527 			 * If there are more than 2 conns in the drain list,
28528 			 * do a left rotate by 1, so that all conns except the
28529 			 * conn at the head move towards the head by 1, and the
28530 			 * the conn at the head goes to the tail. This attempts
28531 			 * a more even share for all queues that are being
28532 			 * drained.
28533 			 */
28534 			if ((connp->conn_drain_next != connp) &&
28535 			    (idl->idl_conn->conn_drain_next != connp)) {
28536 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28537 			}
28538 			if (idl->idl_repeat) {
28539 				qenable(idl->idl_conn->conn_wq);
28540 				idl->idl_conn_draining = idl->idl_conn;
28541 				idl->idl_repeat = 0;
28542 			} else {
28543 				idl->idl_conn_draining = NULL;
28544 			}
28545 		} else {
28546 			/*
28547 			 * If the next queue that we are now qenable'ing,
28548 			 * is closing, it will remove itself from this list
28549 			 * and qenable the subsequent queue in ip_close().
28550 			 * Serialization is acheived thru idl_lock.
28551 			 */
28552 			qenable(connp->conn_drain_next->conn_wq);
28553 			idl->idl_conn_draining = connp->conn_drain_next;
28554 		}
28555 	}
28556 	if (!connp->conn_did_putbq || closing) {
28557 		/*
28558 		 * Remove ourself from the drain list, if we did not do
28559 		 * a putbq, or if the conn is closing.
28560 		 * Note: It is possible that q->q_first is non-null. It means
28561 		 * that these messages landed after we did a enableok() in
28562 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28563 		 * service them.
28564 		 */
28565 		if (connp->conn_drain_next == connp) {
28566 			/* Singleton in the list */
28567 			ASSERT(connp->conn_drain_prev == connp);
28568 			idl->idl_conn = NULL;
28569 			idl->idl_conn_draining = NULL;
28570 		} else {
28571 			connp->conn_drain_prev->conn_drain_next =
28572 			    connp->conn_drain_next;
28573 			connp->conn_drain_next->conn_drain_prev =
28574 			    connp->conn_drain_prev;
28575 			if (idl->idl_conn == connp)
28576 				idl->idl_conn = connp->conn_drain_next;
28577 			ASSERT(idl->idl_conn_draining != connp);
28578 
28579 		}
28580 		connp->conn_drain_next = NULL;
28581 		connp->conn_drain_prev = NULL;
28582 	}
28583 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28584 }
28585 
28586 /*
28587  * Write service routine. Shared perimeter entry point.
28588  * ip_wsrv can be called in any of the following ways.
28589  * 1. The device queue's messages has fallen below the low water mark
28590  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28591  *    the drain lists and backenable the first conn in each list.
28592  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28593  *    qenabled non-tcp upper layers. We start dequeing messages and call
28594  *    ip_wput for each message.
28595  */
28596 
28597 void
28598 ip_wsrv(queue_t *q)
28599 {
28600 	conn_t	*connp;
28601 	ill_t	*ill;
28602 	mblk_t	*mp;
28603 
28604 	if (q->q_next) {
28605 		ill = (ill_t *)q->q_ptr;
28606 		if (ill->ill_state_flags == 0) {
28607 			/*
28608 			 * The device flow control has opened up.
28609 			 * Walk through conn drain lists and qenable the
28610 			 * first conn in each list. This makes sense only
28611 			 * if the stream is fully plumbed and setup.
28612 			 * Hence the if check above.
28613 			 */
28614 			ip1dbg(("ip_wsrv: walking\n"));
28615 			conn_walk_drain(ill->ill_ipst);
28616 		}
28617 		return;
28618 	}
28619 
28620 	connp = Q_TO_CONN(q);
28621 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28622 
28623 	/*
28624 	 * 1. Set conn_draining flag to signal that service is active.
28625 	 *
28626 	 * 2. ip_output determines whether it has been called from service,
28627 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28628 	 *    has been called from service.
28629 	 *
28630 	 * 3. Message ordering is preserved by the following logic.
28631 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28632 	 *    the message at the tail, if conn_draining is set (i.e. service
28633 	 *    is running) or if q->q_first is non-null.
28634 	 *
28635 	 *    ii. If ip_output is called from service, and if ip_output cannot
28636 	 *    putnext due to flow control, it does a putbq.
28637 	 *
28638 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28639 	 *    (causing an infinite loop).
28640 	 */
28641 	ASSERT(!connp->conn_did_putbq);
28642 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28643 		connp->conn_draining = 1;
28644 		noenable(q);
28645 		while ((mp = getq(q)) != NULL) {
28646 			ASSERT(CONN_Q(q));
28647 
28648 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28649 			if (connp->conn_did_putbq) {
28650 				/* ip_wput did a putbq */
28651 				break;
28652 			}
28653 		}
28654 		/*
28655 		 * At this point, a thread coming down from top, calling
28656 		 * ip_wput, may end up queueing the message. We have not yet
28657 		 * enabled the queue, so ip_wsrv won't be called again.
28658 		 * To avoid this race, check q->q_first again (in the loop)
28659 		 * If the other thread queued the message before we call
28660 		 * enableok(), we will catch it in the q->q_first check.
28661 		 * If the other thread queues the message after we call
28662 		 * enableok(), ip_wsrv will be called again by STREAMS.
28663 		 */
28664 		connp->conn_draining = 0;
28665 		enableok(q);
28666 	}
28667 
28668 	/* Enable the next conn for draining */
28669 	conn_drain_tail(connp, B_FALSE);
28670 
28671 	connp->conn_did_putbq = 0;
28672 }
28673 
28674 /*
28675  * Walk the list of all conn's calling the function provided with the
28676  * specified argument for each.	 Note that this only walks conn's that
28677  * have been bound.
28678  * Applies to both IPv4 and IPv6.
28679  */
28680 static void
28681 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28682 {
28683 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28684 	    ipst->ips_ipcl_udp_fanout_size,
28685 	    func, arg, zoneid);
28686 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28687 	    ipst->ips_ipcl_conn_fanout_size,
28688 	    func, arg, zoneid);
28689 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28690 	    ipst->ips_ipcl_bind_fanout_size,
28691 	    func, arg, zoneid);
28692 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28693 	    IPPROTO_MAX, func, arg, zoneid);
28694 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28695 	    IPPROTO_MAX, func, arg, zoneid);
28696 }
28697 
28698 /*
28699  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28700  * of conns that need to be drained, check if drain is already in progress.
28701  * If so set the idl_repeat bit, indicating that the last conn in the list
28702  * needs to reinitiate the drain once again, for the list. If drain is not
28703  * in progress for the list, initiate the draining, by qenabling the 1st
28704  * conn in the list. The drain is self-sustaining, each qenabled conn will
28705  * in turn qenable the next conn, when it is done/blocked/closing.
28706  */
28707 static void
28708 conn_walk_drain(ip_stack_t *ipst)
28709 {
28710 	int i;
28711 	idl_t *idl;
28712 
28713 	IP_STAT(ipst, ip_conn_walk_drain);
28714 
28715 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28716 		idl = &ipst->ips_conn_drain_list[i];
28717 		mutex_enter(&idl->idl_lock);
28718 		if (idl->idl_conn == NULL) {
28719 			mutex_exit(&idl->idl_lock);
28720 			continue;
28721 		}
28722 		/*
28723 		 * If this list is not being drained currently by
28724 		 * an ip_wsrv thread, start the process.
28725 		 */
28726 		if (idl->idl_conn_draining == NULL) {
28727 			ASSERT(idl->idl_repeat == 0);
28728 			qenable(idl->idl_conn->conn_wq);
28729 			idl->idl_conn_draining = idl->idl_conn;
28730 		} else {
28731 			idl->idl_repeat = 1;
28732 		}
28733 		mutex_exit(&idl->idl_lock);
28734 	}
28735 }
28736 
28737 /*
28738  * Walk an conn hash table of `count' buckets, calling func for each entry.
28739  */
28740 static void
28741 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28742     zoneid_t zoneid)
28743 {
28744 	conn_t	*connp;
28745 
28746 	while (count-- > 0) {
28747 		mutex_enter(&connfp->connf_lock);
28748 		for (connp = connfp->connf_head; connp != NULL;
28749 		    connp = connp->conn_next) {
28750 			if (zoneid == GLOBAL_ZONEID ||
28751 			    zoneid == connp->conn_zoneid) {
28752 				CONN_INC_REF(connp);
28753 				mutex_exit(&connfp->connf_lock);
28754 				(*func)(connp, arg);
28755 				mutex_enter(&connfp->connf_lock);
28756 				CONN_DEC_REF(connp);
28757 			}
28758 		}
28759 		mutex_exit(&connfp->connf_lock);
28760 		connfp++;
28761 	}
28762 }
28763 
28764 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28765 static void
28766 conn_report1(conn_t *connp, void *mp)
28767 {
28768 	char	buf1[INET6_ADDRSTRLEN];
28769 	char	buf2[INET6_ADDRSTRLEN];
28770 	uint_t	print_len, buf_len;
28771 
28772 	ASSERT(connp != NULL);
28773 
28774 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28775 	if (buf_len <= 0)
28776 		return;
28777 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
28778 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
28779 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28780 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28781 	    "%5d %s/%05d %s/%05d\n",
28782 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28783 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28784 	    buf1, connp->conn_lport,
28785 	    buf2, connp->conn_fport);
28786 	if (print_len < buf_len) {
28787 		((mblk_t *)mp)->b_wptr += print_len;
28788 	} else {
28789 		((mblk_t *)mp)->b_wptr += buf_len;
28790 	}
28791 }
28792 
28793 /*
28794  * Named Dispatch routine to produce a formatted report on all conns
28795  * that are listed in one of the fanout tables.
28796  * This report is accessed by using the ndd utility to "get" ND variable
28797  * "ip_conn_status".
28798  */
28799 /* ARGSUSED */
28800 static int
28801 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28802 {
28803 	conn_t *connp = Q_TO_CONN(q);
28804 
28805 	(void) mi_mpprintf(mp,
28806 	    "CONN      " MI_COL_HDRPAD_STR
28807 	    "rfq      " MI_COL_HDRPAD_STR
28808 	    "stq      " MI_COL_HDRPAD_STR
28809 	    " zone local                 remote");
28810 
28811 	/*
28812 	 * Because of the ndd constraint, at most we can have 64K buffer
28813 	 * to put in all conn info.  So to be more efficient, just
28814 	 * allocate a 64K buffer here, assuming we need that large buffer.
28815 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28816 	 */
28817 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28818 		/* The following may work even if we cannot get a large buf. */
28819 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28820 		return (0);
28821 	}
28822 
28823 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28824 	    connp->conn_netstack->netstack_ip);
28825 	return (0);
28826 }
28827 
28828 /*
28829  * Determine if the ill and multicast aspects of that packets
28830  * "matches" the conn.
28831  */
28832 boolean_t
28833 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28834     zoneid_t zoneid)
28835 {
28836 	ill_t *in_ill;
28837 	boolean_t found;
28838 	ipif_t *ipif;
28839 	ire_t *ire;
28840 	ipaddr_t dst, src;
28841 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28842 
28843 	dst = ipha->ipha_dst;
28844 	src = ipha->ipha_src;
28845 
28846 	/*
28847 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28848 	 * unicast, broadcast and multicast reception to
28849 	 * conn_incoming_ill. conn_wantpacket itself is called
28850 	 * only for BROADCAST and multicast.
28851 	 *
28852 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28853 	 *    is part of a group. Hence, we should be receiving
28854 	 *    just one copy of broadcast for the whole group.
28855 	 *    Thus, if it is part of the group the packet could
28856 	 *    come on any ill of the group and hence we need a
28857 	 *    match on the group. Otherwise, match on ill should
28858 	 *    be sufficient.
28859 	 *
28860 	 * 2) ip_rput does not suppress duplicate multicast packets.
28861 	 *    If there are two interfaces in a ill group and we have
28862 	 *    2 applications (conns) joined a multicast group G on
28863 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28864 	 *    will give us two packets because we join G on both the
28865 	 *    interfaces rather than nominating just one interface
28866 	 *    for receiving multicast like broadcast above. So,
28867 	 *    we have to call ilg_lookup_ill to filter out duplicate
28868 	 *    copies, if ill is part of a group.
28869 	 */
28870 	in_ill = connp->conn_incoming_ill;
28871 	if (in_ill != NULL) {
28872 		if (in_ill->ill_group == NULL) {
28873 			if (in_ill != ill)
28874 				return (B_FALSE);
28875 		} else if (in_ill->ill_group != ill->ill_group) {
28876 			return (B_FALSE);
28877 		}
28878 	}
28879 
28880 	if (!CLASSD(dst)) {
28881 		if (IPCL_ZONE_MATCH(connp, zoneid))
28882 			return (B_TRUE);
28883 		/*
28884 		 * The conn is in a different zone; we need to check that this
28885 		 * broadcast address is configured in the application's zone and
28886 		 * on one ill in the group.
28887 		 */
28888 		ipif = ipif_get_next_ipif(NULL, ill);
28889 		if (ipif == NULL)
28890 			return (B_FALSE);
28891 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28892 		    connp->conn_zoneid, NULL,
28893 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28894 		ipif_refrele(ipif);
28895 		if (ire != NULL) {
28896 			ire_refrele(ire);
28897 			return (B_TRUE);
28898 		} else {
28899 			return (B_FALSE);
28900 		}
28901 	}
28902 
28903 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28904 	    connp->conn_zoneid == zoneid) {
28905 		/*
28906 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28907 		 * disabled, therefore we don't dispatch the multicast packet to
28908 		 * the sending zone.
28909 		 */
28910 		return (B_FALSE);
28911 	}
28912 
28913 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
28914 	    connp->conn_zoneid != zoneid) {
28915 		/*
28916 		 * Multicast packet on the loopback interface: we only match
28917 		 * conns who joined the group in the specified zone.
28918 		 */
28919 		return (B_FALSE);
28920 	}
28921 
28922 	if (connp->conn_multi_router) {
28923 		/* multicast packet and multicast router socket: send up */
28924 		return (B_TRUE);
28925 	}
28926 
28927 	mutex_enter(&connp->conn_lock);
28928 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28929 	mutex_exit(&connp->conn_lock);
28930 	return (found);
28931 }
28932 
28933 /*
28934  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28935  */
28936 /* ARGSUSED */
28937 static void
28938 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28939 {
28940 	ill_t *ill = (ill_t *)q->q_ptr;
28941 	mblk_t	*mp1, *mp2;
28942 	ipif_t  *ipif;
28943 	int err = 0;
28944 	conn_t *connp = NULL;
28945 	ipsq_t	*ipsq;
28946 	arc_t	*arc;
28947 
28948 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28949 
28950 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28951 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28952 
28953 	ASSERT(IAM_WRITER_ILL(ill));
28954 	mp2 = mp->b_cont;
28955 	mp->b_cont = NULL;
28956 
28957 	/*
28958 	 * We have now received the arp bringup completion message
28959 	 * from ARP. Mark the arp bringup as done. Also if the arp
28960 	 * stream has already started closing, send up the AR_ARP_CLOSING
28961 	 * ack now since ARP is waiting in close for this ack.
28962 	 */
28963 	mutex_enter(&ill->ill_lock);
28964 	ill->ill_arp_bringup_pending = 0;
28965 	if (ill->ill_arp_closing) {
28966 		mutex_exit(&ill->ill_lock);
28967 		/* Let's reuse the mp for sending the ack */
28968 		arc = (arc_t *)mp->b_rptr;
28969 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28970 		arc->arc_cmd = AR_ARP_CLOSING;
28971 		qreply(q, mp);
28972 	} else {
28973 		mutex_exit(&ill->ill_lock);
28974 		freeb(mp);
28975 	}
28976 
28977 	ipsq = ill->ill_phyint->phyint_ipsq;
28978 	ipif = ipsq->ipsq_pending_ipif;
28979 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28980 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28981 	if (mp1 == NULL) {
28982 		/* bringup was aborted by the user */
28983 		freemsg(mp2);
28984 		return;
28985 	}
28986 
28987 	/*
28988 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28989 	 * must have an associated conn_t.  Otherwise, we're bringing this
28990 	 * interface back up as part of handling an asynchronous event (e.g.,
28991 	 * physical address change).
28992 	 */
28993 	if (ipsq->ipsq_current_ioctl != 0) {
28994 		ASSERT(connp != NULL);
28995 		q = CONNP_TO_WQ(connp);
28996 	} else {
28997 		ASSERT(connp == NULL);
28998 		q = ill->ill_rq;
28999 	}
29000 
29001 	/*
29002 	 * If the DL_BIND_REQ fails, it is noted
29003 	 * in arc_name_offset.
29004 	 */
29005 	err = *((int *)mp2->b_rptr);
29006 	if (err == 0) {
29007 		if (ipif->ipif_isv6) {
29008 			if ((err = ipif_up_done_v6(ipif)) != 0)
29009 				ip0dbg(("ip_arp_done: init failed\n"));
29010 		} else {
29011 			if ((err = ipif_up_done(ipif)) != 0)
29012 				ip0dbg(("ip_arp_done: init failed\n"));
29013 		}
29014 	} else {
29015 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
29016 	}
29017 
29018 	freemsg(mp2);
29019 
29020 	if ((err == 0) && (ill->ill_up_ipifs)) {
29021 		err = ill_up_ipifs(ill, q, mp1);
29022 		if (err == EINPROGRESS)
29023 			return;
29024 	}
29025 
29026 	if (ill->ill_up_ipifs)
29027 		ill_group_cleanup(ill);
29028 
29029 	/*
29030 	 * The operation must complete without EINPROGRESS since
29031 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29032 	 * Otherwise, the operation will be stuck forever in the ipsq.
29033 	 */
29034 	ASSERT(err != EINPROGRESS);
29035 	if (ipsq->ipsq_current_ioctl != 0)
29036 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29037 	else
29038 		ipsq_current_finish(ipsq);
29039 }
29040 
29041 /* Allocate the private structure */
29042 static int
29043 ip_priv_alloc(void **bufp)
29044 {
29045 	void	*buf;
29046 
29047 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29048 		return (ENOMEM);
29049 
29050 	*bufp = buf;
29051 	return (0);
29052 }
29053 
29054 /* Function to delete the private structure */
29055 void
29056 ip_priv_free(void *buf)
29057 {
29058 	ASSERT(buf != NULL);
29059 	kmem_free(buf, sizeof (ip_priv_t));
29060 }
29061 
29062 /*
29063  * The entry point for IPPF processing.
29064  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29065  * routine just returns.
29066  *
29067  * When called, ip_process generates an ipp_packet_t structure
29068  * which holds the state information for this packet and invokes the
29069  * the classifier (via ipp_packet_process). The classification, depending on
29070  * configured filters, results in a list of actions for this packet. Invoking
29071  * an action may cause the packet to be dropped, in which case the resulting
29072  * mblk (*mpp) is NULL. proc indicates the callout position for
29073  * this packet and ill_index is the interface this packet on or will leave
29074  * on (inbound and outbound resp.).
29075  */
29076 void
29077 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29078 {
29079 	mblk_t		*mp;
29080 	ip_priv_t	*priv;
29081 	ipp_action_id_t	aid;
29082 	int		rc = 0;
29083 	ipp_packet_t	*pp;
29084 #define	IP_CLASS	"ip"
29085 
29086 	/* If the classifier is not loaded, return  */
29087 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29088 		return;
29089 	}
29090 
29091 	mp = *mpp;
29092 	ASSERT(mp != NULL);
29093 
29094 	/* Allocate the packet structure */
29095 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29096 	if (rc != 0) {
29097 		*mpp = NULL;
29098 		freemsg(mp);
29099 		return;
29100 	}
29101 
29102 	/* Allocate the private structure */
29103 	rc = ip_priv_alloc((void **)&priv);
29104 	if (rc != 0) {
29105 		*mpp = NULL;
29106 		freemsg(mp);
29107 		ipp_packet_free(pp);
29108 		return;
29109 	}
29110 	priv->proc = proc;
29111 	priv->ill_index = ill_index;
29112 	ipp_packet_set_private(pp, priv, ip_priv_free);
29113 	ipp_packet_set_data(pp, mp);
29114 
29115 	/* Invoke the classifier */
29116 	rc = ipp_packet_process(&pp);
29117 	if (pp != NULL) {
29118 		mp = ipp_packet_get_data(pp);
29119 		ipp_packet_free(pp);
29120 		if (rc != 0) {
29121 			freemsg(mp);
29122 			*mpp = NULL;
29123 		}
29124 	} else {
29125 		*mpp = NULL;
29126 	}
29127 #undef	IP_CLASS
29128 }
29129 
29130 /*
29131  * Propagate a multicast group membership operation (add/drop) on
29132  * all the interfaces crossed by the related multirt routes.
29133  * The call is considered successful if the operation succeeds
29134  * on at least one interface.
29135  */
29136 static int
29137 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29138     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29139     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29140     mblk_t *first_mp)
29141 {
29142 	ire_t		*ire_gw;
29143 	irb_t		*irb;
29144 	int		error = 0;
29145 	opt_restart_t	*or;
29146 	ip_stack_t	*ipst = ire->ire_ipst;
29147 
29148 	irb = ire->ire_bucket;
29149 	ASSERT(irb != NULL);
29150 
29151 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29152 
29153 	or = (opt_restart_t *)first_mp->b_rptr;
29154 	IRB_REFHOLD(irb);
29155 	for (; ire != NULL; ire = ire->ire_next) {
29156 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29157 			continue;
29158 		if (ire->ire_addr != group)
29159 			continue;
29160 
29161 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29162 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29163 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29164 		/* No resolver exists for the gateway; skip this ire. */
29165 		if (ire_gw == NULL)
29166 			continue;
29167 
29168 		/*
29169 		 * This function can return EINPROGRESS. If so the operation
29170 		 * will be restarted from ip_restart_optmgmt which will
29171 		 * call ip_opt_set and option processing will restart for
29172 		 * this option. So we may end up calling 'fn' more than once.
29173 		 * This requires that 'fn' is idempotent except for the
29174 		 * return value. The operation is considered a success if
29175 		 * it succeeds at least once on any one interface.
29176 		 */
29177 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29178 		    NULL, fmode, src, first_mp);
29179 		if (error == 0)
29180 			or->or_private = CGTP_MCAST_SUCCESS;
29181 
29182 		if (ip_debug > 0) {
29183 			ulong_t	off;
29184 			char	*ksym;
29185 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29186 			ip2dbg(("ip_multirt_apply_membership: "
29187 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29188 			    "error %d [success %u]\n",
29189 			    ksym ? ksym : "?",
29190 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29191 			    error, or->or_private));
29192 		}
29193 
29194 		ire_refrele(ire_gw);
29195 		if (error == EINPROGRESS) {
29196 			IRB_REFRELE(irb);
29197 			return (error);
29198 		}
29199 	}
29200 	IRB_REFRELE(irb);
29201 	/*
29202 	 * Consider the call as successful if we succeeded on at least
29203 	 * one interface. Otherwise, return the last encountered error.
29204 	 */
29205 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29206 }
29207 
29208 
29209 /*
29210  * Issue a warning regarding a route crossing an interface with an
29211  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29212  * amount of time is logged.
29213  */
29214 static void
29215 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29216 {
29217 	hrtime_t	current = gethrtime();
29218 	char		buf[INET_ADDRSTRLEN];
29219 	ip_stack_t	*ipst = ire->ire_ipst;
29220 
29221 	/* Convert interval in ms to hrtime in ns */
29222 	if (ipst->ips_multirt_bad_mtu_last_time +
29223 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29224 	    current) {
29225 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29226 		    "to %s, incorrect MTU %u (expected %u)\n",
29227 		    ip_dot_addr(ire->ire_addr, buf),
29228 		    ire->ire_max_frag, max_frag);
29229 
29230 		ipst->ips_multirt_bad_mtu_last_time = current;
29231 	}
29232 }
29233 
29234 
29235 /*
29236  * Get the CGTP (multirouting) filtering status.
29237  * If 0, the CGTP hooks are transparent.
29238  */
29239 /* ARGSUSED */
29240 static int
29241 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29242 {
29243 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29244 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29245 
29246 	/*
29247 	 * Only applies to the shared stack since the filter_ops
29248 	 * do not carry an ip_stack_t or zoneid.
29249 	 */
29250 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29251 		return (ENOTSUP);
29252 
29253 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29254 	return (0);
29255 }
29256 
29257 
29258 /*
29259  * Set the CGTP (multirouting) filtering status.
29260  * If the status is changed from active to transparent
29261  * or from transparent to active, forward the new status
29262  * to the filtering module (if loaded).
29263  */
29264 /* ARGSUSED */
29265 static int
29266 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29267     cred_t *ioc_cr)
29268 {
29269 	long		new_value;
29270 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29271 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29272 
29273 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
29274 		return (EPERM);
29275 
29276 	/*
29277 	 * Only applies to the shared stack since the filter_ops
29278 	 * do not carry an ip_stack_t or zoneid.
29279 	 */
29280 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29281 		return (ENOTSUP);
29282 
29283 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29284 	    new_value < 0 || new_value > 1) {
29285 		return (EINVAL);
29286 	}
29287 
29288 	/*
29289 	 * Do not enable CGTP filtering - thus preventing the hooks
29290 	 * from being invoked - if the version number of the
29291 	 * filtering module hooks does not match.
29292 	 */
29293 	if ((ip_cgtp_filter_ops != NULL) &&
29294 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29295 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29296 		    "(module hooks version %d, expecting %d)\n",
29297 		    ip_cgtp_filter_ops->cfo_filter_rev,
29298 		    CGTP_FILTER_REV);
29299 		return (ENOTSUP);
29300 	}
29301 
29302 	if ((!*ip_cgtp_filter_value) && new_value) {
29303 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29304 		    ip_cgtp_filter_ops == NULL ?
29305 		    " (module not loaded)" : "");
29306 	}
29307 	if (*ip_cgtp_filter_value && (!new_value)) {
29308 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29309 		    ip_cgtp_filter_ops == NULL ?
29310 		    " (module not loaded)" : "");
29311 	}
29312 
29313 	if (ip_cgtp_filter_ops != NULL) {
29314 		int	res;
29315 
29316 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
29317 		if (res)
29318 			return (res);
29319 	}
29320 
29321 	*ip_cgtp_filter_value = (boolean_t)new_value;
29322 
29323 	return (0);
29324 }
29325 
29326 
29327 /*
29328  * Return the expected CGTP hooks version number.
29329  */
29330 int
29331 ip_cgtp_filter_supported(void)
29332 {
29333 	ip_stack_t *ipst;
29334 	int ret;
29335 
29336 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29337 	if (ipst == NULL)
29338 		return (-1);
29339 	ret = ip_cgtp_filter_rev;
29340 	netstack_rele(ipst->ips_netstack);
29341 	return (ret);
29342 }
29343 
29344 
29345 /*
29346  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29347  * or by invoking this function. In the first case, the version number
29348  * of the registered structure is checked at hooks activation time
29349  * in ip_cgtp_filter_set().
29350  *
29351  * Only applies to the shared stack since the filter_ops
29352  * do not carry an ip_stack_t or zoneid.
29353  */
29354 int
29355 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29356 {
29357 	ip_stack_t *ipst;
29358 
29359 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29360 		return (ENOTSUP);
29361 
29362 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29363 	if (ipst == NULL)
29364 		return (EINVAL);
29365 
29366 	ip_cgtp_filter_ops = ops;
29367 	netstack_rele(ipst->ips_netstack);
29368 	return (0);
29369 }
29370 
29371 static squeue_func_t
29372 ip_squeue_switch(int val)
29373 {
29374 	squeue_func_t rval = squeue_fill;
29375 
29376 	switch (val) {
29377 	case IP_SQUEUE_ENTER_NODRAIN:
29378 		rval = squeue_enter_nodrain;
29379 		break;
29380 	case IP_SQUEUE_ENTER:
29381 		rval = squeue_enter;
29382 		break;
29383 	default:
29384 		break;
29385 	}
29386 	return (rval);
29387 }
29388 
29389 /* ARGSUSED */
29390 static int
29391 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29392     caddr_t addr, cred_t *cr)
29393 {
29394 	int *v = (int *)addr;
29395 	long new_value;
29396 
29397 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29398 		return (EPERM);
29399 
29400 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29401 		return (EINVAL);
29402 
29403 	ip_input_proc = ip_squeue_switch(new_value);
29404 	*v = new_value;
29405 	return (0);
29406 }
29407 
29408 /* ARGSUSED */
29409 static int
29410 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29411     caddr_t addr, cred_t *cr)
29412 {
29413 	int *v = (int *)addr;
29414 	long new_value;
29415 
29416 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29417 		return (EPERM);
29418 
29419 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29420 		return (EINVAL);
29421 
29422 	*v = new_value;
29423 	return (0);
29424 }
29425 
29426 /*
29427  * Handle changes to ipmp_hook_emulation ndd variable.
29428  * Need to update phyint_hook_ifindex.
29429  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29430  */
29431 static void
29432 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29433 {
29434 	phyint_t *phyi;
29435 	phyint_t *phyi_tmp;
29436 	char *groupname;
29437 	int namelen;
29438 	ill_t	*ill;
29439 	boolean_t new_group;
29440 
29441 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29442 	/*
29443 	 * Group indicies are stored in the phyint - a common structure
29444 	 * to both IPv4 and IPv6.
29445 	 */
29446 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29447 	for (; phyi != NULL;
29448 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29449 	    phyi, AVL_AFTER)) {
29450 		/* Ignore the ones that do not have a group */
29451 		if (phyi->phyint_groupname_len == 0)
29452 			continue;
29453 
29454 		/*
29455 		 * Look for other phyint in group.
29456 		 * Clear name/namelen so the lookup doesn't find ourselves.
29457 		 */
29458 		namelen = phyi->phyint_groupname_len;
29459 		groupname = phyi->phyint_groupname;
29460 		phyi->phyint_groupname_len = 0;
29461 		phyi->phyint_groupname = NULL;
29462 
29463 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29464 		/* Restore */
29465 		phyi->phyint_groupname_len = namelen;
29466 		phyi->phyint_groupname = groupname;
29467 
29468 		new_group = B_FALSE;
29469 		if (ipst->ips_ipmp_hook_emulation) {
29470 			/*
29471 			 * If the group already exists and has already
29472 			 * been assigned a group ifindex, we use the existing
29473 			 * group_ifindex, otherwise we pick a new group_ifindex
29474 			 * here.
29475 			 */
29476 			if (phyi_tmp != NULL &&
29477 			    phyi_tmp->phyint_group_ifindex != 0) {
29478 				phyi->phyint_group_ifindex =
29479 				    phyi_tmp->phyint_group_ifindex;
29480 			} else {
29481 				/* XXX We need a recovery strategy here. */
29482 				if (!ip_assign_ifindex(
29483 				    &phyi->phyint_group_ifindex, ipst))
29484 					cmn_err(CE_PANIC,
29485 					    "ip_assign_ifindex() failed");
29486 				new_group = B_TRUE;
29487 			}
29488 		} else {
29489 			phyi->phyint_group_ifindex = 0;
29490 		}
29491 		if (ipst->ips_ipmp_hook_emulation)
29492 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29493 		else
29494 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29495 
29496 		/*
29497 		 * For IP Filter to find out the relationship between
29498 		 * names and interface indicies, we need to generate
29499 		 * a NE_PLUMB event when a new group can appear.
29500 		 * We always generate events when a new interface appears
29501 		 * (even when ipmp_hook_emulation is set) so there
29502 		 * is no need to generate NE_PLUMB events when
29503 		 * ipmp_hook_emulation is turned off.
29504 		 * And since it isn't critical for IP Filter to get
29505 		 * the NE_UNPLUMB events we skip those here.
29506 		 */
29507 		if (new_group) {
29508 			/*
29509 			 * First phyint in group - generate group PLUMB event.
29510 			 * Since we are not running inside the ipsq we do
29511 			 * the dispatch immediately.
29512 			 */
29513 			if (phyi->phyint_illv4 != NULL)
29514 				ill = phyi->phyint_illv4;
29515 			else
29516 				ill = phyi->phyint_illv6;
29517 
29518 			if (ill != NULL) {
29519 				mutex_enter(&ill->ill_lock);
29520 				ill_nic_info_plumb(ill, B_TRUE);
29521 				ill_nic_info_dispatch(ill);
29522 				mutex_exit(&ill->ill_lock);
29523 			}
29524 		}
29525 	}
29526 	rw_exit(&ipst->ips_ill_g_lock);
29527 }
29528 
29529 /* ARGSUSED */
29530 static int
29531 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29532     caddr_t addr, cred_t *cr)
29533 {
29534 	int *v = (int *)addr;
29535 	long new_value;
29536 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29537 
29538 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29539 		return (EINVAL);
29540 
29541 	if (*v != new_value) {
29542 		*v = new_value;
29543 		ipmp_hook_emulation_changed(ipst);
29544 	}
29545 	return (0);
29546 }
29547 
29548 static void *
29549 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29550 {
29551 	kstat_t *ksp;
29552 
29553 	ip_stat_t template = {
29554 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29555 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29556 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29557 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29558 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29559 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29560 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29561 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29562 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29563 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29564 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29565 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29566 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29567 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29568 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29569 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29570 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29571 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29572 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29573 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29574 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29575 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29576 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29577 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29578 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29579 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29580 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29581 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29582 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29583 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29584 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29585 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29586 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29587 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29588 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29589 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29590 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29591 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29592 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29593 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29594 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29595 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29596 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29597 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29598 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29599 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29600 	};
29601 
29602 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29603 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29604 	    KSTAT_FLAG_VIRTUAL, stackid);
29605 
29606 	if (ksp == NULL)
29607 		return (NULL);
29608 
29609 	bcopy(&template, ip_statisticsp, sizeof (template));
29610 	ksp->ks_data = (void *)ip_statisticsp;
29611 	ksp->ks_private = (void *)(uintptr_t)stackid;
29612 
29613 	kstat_install(ksp);
29614 	return (ksp);
29615 }
29616 
29617 static void
29618 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29619 {
29620 	if (ksp != NULL) {
29621 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29622 		kstat_delete_netstack(ksp, stackid);
29623 	}
29624 }
29625 
29626 static void *
29627 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29628 {
29629 	kstat_t	*ksp;
29630 
29631 	ip_named_kstat_t template = {
29632 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29633 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29634 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29635 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29636 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29637 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29638 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29639 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29640 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29641 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29642 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29643 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29644 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29645 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29646 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29647 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29648 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29649 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29650 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29651 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29652 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29653 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29654 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29655 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29656 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29657 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29658 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29659 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29660 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29661 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29662 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29663 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29664 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29665 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29666 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29667 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29668 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29669 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29670 	};
29671 
29672 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29673 					NUM_OF_FIELDS(ip_named_kstat_t),
29674 					0, stackid);
29675 	if (ksp == NULL || ksp->ks_data == NULL)
29676 		return (NULL);
29677 
29678 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29679 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29680 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29681 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29682 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29683 
29684 	template.netToMediaEntrySize.value.i32 =
29685 		sizeof (mib2_ipNetToMediaEntry_t);
29686 
29687 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29688 
29689 	bcopy(&template, ksp->ks_data, sizeof (template));
29690 	ksp->ks_update = ip_kstat_update;
29691 	ksp->ks_private = (void *)(uintptr_t)stackid;
29692 
29693 	kstat_install(ksp);
29694 	return (ksp);
29695 }
29696 
29697 static void
29698 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29699 {
29700 	if (ksp != NULL) {
29701 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29702 		kstat_delete_netstack(ksp, stackid);
29703 	}
29704 }
29705 
29706 static int
29707 ip_kstat_update(kstat_t *kp, int rw)
29708 {
29709 	ip_named_kstat_t *ipkp;
29710 	mib2_ipIfStatsEntry_t ipmib;
29711 	ill_walk_context_t ctx;
29712 	ill_t *ill;
29713 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29714 	netstack_t	*ns;
29715 	ip_stack_t	*ipst;
29716 
29717 	if (kp == NULL || kp->ks_data == NULL)
29718 		return (EIO);
29719 
29720 	if (rw == KSTAT_WRITE)
29721 		return (EACCES);
29722 
29723 	ns = netstack_find_by_stackid(stackid);
29724 	if (ns == NULL)
29725 		return (-1);
29726 	ipst = ns->netstack_ip;
29727 	if (ipst == NULL) {
29728 		netstack_rele(ns);
29729 		return (-1);
29730 	}
29731 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29732 
29733 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29734 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29735 	ill = ILL_START_WALK_V4(&ctx, ipst);
29736 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29737 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29738 	rw_exit(&ipst->ips_ill_g_lock);
29739 
29740 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29741 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29742 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29743 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29744 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29745 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29746 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29747 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29748 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29749 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29750 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29751 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29752 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29753 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29754 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29755 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29756 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29757 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29758 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29759 
29760 	ipkp->routingDiscards.value.ui32 =	0;
29761 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29762 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29763 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29764 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29765 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29766 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29767 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29768 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29769 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29770 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29771 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29772 
29773 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29774 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29775 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29776 
29777 	netstack_rele(ns);
29778 
29779 	return (0);
29780 }
29781 
29782 static void *
29783 icmp_kstat_init(netstackid_t stackid)
29784 {
29785 	kstat_t	*ksp;
29786 
29787 	icmp_named_kstat_t template = {
29788 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29789 		{ "inErrors",		KSTAT_DATA_UINT32 },
29790 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29791 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29792 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29793 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29794 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29795 		{ "inEchos",		KSTAT_DATA_UINT32 },
29796 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29797 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29798 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29799 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29800 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29801 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29802 		{ "outErrors",		KSTAT_DATA_UINT32 },
29803 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29804 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29805 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29806 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29807 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29808 		{ "outEchos",		KSTAT_DATA_UINT32 },
29809 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29810 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29811 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29812 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29813 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29814 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29815 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29816 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29817 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29818 		{ "outDrops",		KSTAT_DATA_UINT32 },
29819 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29820 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29821 	};
29822 
29823 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29824 					NUM_OF_FIELDS(icmp_named_kstat_t),
29825 					0, stackid);
29826 	if (ksp == NULL || ksp->ks_data == NULL)
29827 		return (NULL);
29828 
29829 	bcopy(&template, ksp->ks_data, sizeof (template));
29830 
29831 	ksp->ks_update = icmp_kstat_update;
29832 	ksp->ks_private = (void *)(uintptr_t)stackid;
29833 
29834 	kstat_install(ksp);
29835 	return (ksp);
29836 }
29837 
29838 static void
29839 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29840 {
29841 	if (ksp != NULL) {
29842 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29843 		kstat_delete_netstack(ksp, stackid);
29844 	}
29845 }
29846 
29847 static int
29848 icmp_kstat_update(kstat_t *kp, int rw)
29849 {
29850 	icmp_named_kstat_t *icmpkp;
29851 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29852 	netstack_t	*ns;
29853 	ip_stack_t	*ipst;
29854 
29855 	if ((kp == NULL) || (kp->ks_data == NULL))
29856 		return (EIO);
29857 
29858 	if (rw == KSTAT_WRITE)
29859 		return (EACCES);
29860 
29861 	ns = netstack_find_by_stackid(stackid);
29862 	if (ns == NULL)
29863 		return (-1);
29864 	ipst = ns->netstack_ip;
29865 	if (ipst == NULL) {
29866 		netstack_rele(ns);
29867 		return (-1);
29868 	}
29869 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29870 
29871 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29872 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29873 	icmpkp->inDestUnreachs.value.ui32 =
29874 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29875 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29876 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29877 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29878 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29879 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29880 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29881 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29882 	icmpkp->inTimestampReps.value.ui32 =
29883 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29884 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29885 	icmpkp->inAddrMaskReps.value.ui32 =
29886 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29887 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29888 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29889 	icmpkp->outDestUnreachs.value.ui32 =
29890 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29891 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29892 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29893 	icmpkp->outSrcQuenchs.value.ui32 =
29894 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29895 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29896 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29897 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29898 	icmpkp->outTimestamps.value.ui32 =
29899 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29900 	icmpkp->outTimestampReps.value.ui32 =
29901 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29902 	icmpkp->outAddrMasks.value.ui32 =
29903 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29904 	icmpkp->outAddrMaskReps.value.ui32 =
29905 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29906 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29907 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29908 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29909 	icmpkp->outFragNeeded.value.ui32 =
29910 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29911 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29912 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29913 	icmpkp->inBadRedirects.value.ui32 =
29914 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29915 
29916 	netstack_rele(ns);
29917 	return (0);
29918 }
29919 
29920 /*
29921  * This is the fanout function for raw socket opened for SCTP.  Note
29922  * that it is called after SCTP checks that there is no socket which
29923  * wants a packet.  Then before SCTP handles this out of the blue packet,
29924  * this function is called to see if there is any raw socket for SCTP.
29925  * If there is and it is bound to the correct address, the packet will
29926  * be sent to that socket.  Note that only one raw socket can be bound to
29927  * a port.  This is assured in ipcl_sctp_hash_insert();
29928  */
29929 void
29930 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29931     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29932     zoneid_t zoneid)
29933 {
29934 	conn_t		*connp;
29935 	queue_t		*rq;
29936 	mblk_t		*first_mp;
29937 	boolean_t	secure;
29938 	ip6_t		*ip6h;
29939 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29940 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29941 
29942 	first_mp = mp;
29943 	if (mctl_present) {
29944 		mp = first_mp->b_cont;
29945 		secure = ipsec_in_is_secure(first_mp);
29946 		ASSERT(mp != NULL);
29947 	} else {
29948 		secure = B_FALSE;
29949 	}
29950 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29951 
29952 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29953 	if (connp == NULL) {
29954 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29955 		return;
29956 	}
29957 	rq = connp->conn_rq;
29958 	if (!canputnext(rq)) {
29959 		CONN_DEC_REF(connp);
29960 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29961 		freemsg(first_mp);
29962 		return;
29963 	}
29964 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29965 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29966 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29967 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29968 		if (first_mp == NULL) {
29969 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29970 			CONN_DEC_REF(connp);
29971 			return;
29972 		}
29973 	}
29974 	/*
29975 	 * We probably should not send M_CTL message up to
29976 	 * raw socket.
29977 	 */
29978 	if (mctl_present)
29979 		freeb(first_mp);
29980 
29981 	/* Initiate IPPF processing here if needed. */
29982 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29983 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29984 		ip_process(IPP_LOCAL_IN, &mp,
29985 		    recv_ill->ill_phyint->phyint_ifindex);
29986 		if (mp == NULL) {
29987 			CONN_DEC_REF(connp);
29988 			return;
29989 		}
29990 	}
29991 
29992 	if (connp->conn_recvif || connp->conn_recvslla ||
29993 	    ((connp->conn_ip_recvpktinfo ||
29994 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29995 	    (flags & IP_FF_IPINFO))) {
29996 		int in_flags = 0;
29997 
29998 		/*
29999 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
30000 		 * IPF_RECVIF.
30001 		 */
30002 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
30003 			in_flags = IPF_RECVIF;
30004 		}
30005 		if (connp->conn_recvslla) {
30006 			in_flags |= IPF_RECVSLLA;
30007 		}
30008 		if (isv4) {
30009 			mp = ip_add_info(mp, recv_ill, in_flags,
30010 			    IPCL_ZONEID(connp), ipst);
30011 		} else {
30012 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
30013 			if (mp == NULL) {
30014 				BUMP_MIB(recv_ill->ill_ip_mib,
30015 				    ipIfStatsInDiscards);
30016 				CONN_DEC_REF(connp);
30017 				return;
30018 			}
30019 		}
30020 	}
30021 
30022 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
30023 	/*
30024 	 * We are sending the IPSEC_IN message also up. Refer
30025 	 * to comments above this function.
30026 	 */
30027 	putnext(rq, mp);
30028 	CONN_DEC_REF(connp);
30029 }
30030 
30031 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30032 {									\
30033 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30034 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30035 }
30036 /*
30037  * This function should be called only if all packet processing
30038  * including fragmentation is complete. Callers of this function
30039  * must set mp->b_prev to one of these values:
30040  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30041  * prior to handing over the mp as first argument to this function.
30042  *
30043  * If the ire passed by caller is incomplete, this function
30044  * queues the packet and if necessary, sends ARP request and bails.
30045  * If the ire passed is fully resolved, we simply prepend
30046  * the link-layer header to the packet, do ipsec hw acceleration
30047  * work if necessary, and send the packet out on the wire.
30048  *
30049  * NOTE: IPSEC will only call this function with fully resolved
30050  * ires if hw acceleration is involved.
30051  * TODO list :
30052  * 	a Handle M_MULTIDATA so that
30053  *	  tcp_multisend->tcp_multisend_data can
30054  *	  call ip_xmit_v4 directly
30055  *	b Handle post-ARP work for fragments so that
30056  *	  ip_wput_frag can call this function.
30057  */
30058 ipxmit_state_t
30059 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
30060 {
30061 	nce_t		*arpce;
30062 	queue_t		*q;
30063 	int		ill_index;
30064 	mblk_t		*nxt_mp, *first_mp;
30065 	boolean_t	xmit_drop = B_FALSE;
30066 	ip_proc_t	proc;
30067 	ill_t		*out_ill;
30068 	int		pkt_len;
30069 
30070 	arpce = ire->ire_nce;
30071 	ASSERT(arpce != NULL);
30072 
30073 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30074 
30075 	mutex_enter(&arpce->nce_lock);
30076 	switch (arpce->nce_state) {
30077 	case ND_REACHABLE:
30078 		/* If there are other queued packets, queue this packet */
30079 		if (arpce->nce_qd_mp != NULL) {
30080 			if (mp != NULL)
30081 				nce_queue_mp_common(arpce, mp, B_FALSE);
30082 			mp = arpce->nce_qd_mp;
30083 		}
30084 		arpce->nce_qd_mp = NULL;
30085 		mutex_exit(&arpce->nce_lock);
30086 
30087 		/*
30088 		 * Flush the queue.  In the common case, where the
30089 		 * ARP is already resolved,  it will go through the
30090 		 * while loop only once.
30091 		 */
30092 		while (mp != NULL) {
30093 
30094 			nxt_mp = mp->b_next;
30095 			mp->b_next = NULL;
30096 			ASSERT(mp->b_datap->db_type != M_CTL);
30097 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30098 			/*
30099 			 * This info is needed for IPQOS to do COS marking
30100 			 * in ip_wput_attach_llhdr->ip_process.
30101 			 */
30102 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30103 			mp->b_prev = NULL;
30104 
30105 			/* set up ill index for outbound qos processing */
30106 			out_ill = ire->ire_ipif->ipif_ill;
30107 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30108 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30109 			    ill_index);
30110 			if (first_mp == NULL) {
30111 				xmit_drop = B_TRUE;
30112 				BUMP_MIB(out_ill->ill_ip_mib,
30113 				    ipIfStatsOutDiscards);
30114 				goto next_mp;
30115 			}
30116 			/* non-ipsec hw accel case */
30117 			if (io == NULL || !io->ipsec_out_accelerated) {
30118 				/* send it */
30119 				q = ire->ire_stq;
30120 				if (proc == IPP_FWD_OUT) {
30121 					UPDATE_IB_PKT_COUNT(ire);
30122 				} else {
30123 					UPDATE_OB_PKT_COUNT(ire);
30124 				}
30125 				ire->ire_last_used_time = lbolt;
30126 
30127 				if (flow_ctl_enabled || canputnext(q))  {
30128 					if (proc == IPP_FWD_OUT) {
30129 						BUMP_MIB(out_ill->ill_ip_mib,
30130 						ipIfStatsHCOutForwDatagrams);
30131 					}
30132 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30133 					    pkt_len);
30134 
30135 					putnext(q, first_mp);
30136 				} else {
30137 					BUMP_MIB(out_ill->ill_ip_mib,
30138 					    ipIfStatsOutDiscards);
30139 					xmit_drop = B_TRUE;
30140 					freemsg(first_mp);
30141 				}
30142 			} else {
30143 				/*
30144 				 * Safety Pup says: make sure this
30145 				 *  is going to the right interface!
30146 				 */
30147 				ill_t *ill1 =
30148 				    (ill_t *)ire->ire_stq->q_ptr;
30149 				int ifindex =
30150 				    ill1->ill_phyint->phyint_ifindex;
30151 				if (ifindex !=
30152 				    io->ipsec_out_capab_ill_index) {
30153 					xmit_drop = B_TRUE;
30154 					freemsg(mp);
30155 				} else {
30156 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30157 					    pkt_len);
30158 					ipsec_hw_putnext(ire->ire_stq, mp);
30159 				}
30160 			}
30161 next_mp:
30162 			mp = nxt_mp;
30163 		} /* while (mp != NULL) */
30164 		if (xmit_drop)
30165 			return (SEND_FAILED);
30166 		else
30167 			return (SEND_PASSED);
30168 
30169 	case ND_INITIAL:
30170 	case ND_INCOMPLETE:
30171 
30172 		/*
30173 		 * While we do send off packets to dests that
30174 		 * use fully-resolved CGTP routes, we do not
30175 		 * handle unresolved CGTP routes.
30176 		 */
30177 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30178 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30179 
30180 		if (mp != NULL) {
30181 			/* queue the packet */
30182 			nce_queue_mp_common(arpce, mp, B_FALSE);
30183 		}
30184 
30185 		if (arpce->nce_state == ND_INCOMPLETE) {
30186 			mutex_exit(&arpce->nce_lock);
30187 			DTRACE_PROBE3(ip__xmit__incomplete,
30188 			    (ire_t *), ire, (mblk_t *), mp,
30189 			    (ipsec_out_t *), io);
30190 			return (LOOKUP_IN_PROGRESS);
30191 		}
30192 
30193 		arpce->nce_state = ND_INCOMPLETE;
30194 		mutex_exit(&arpce->nce_lock);
30195 		/*
30196 		 * Note that ire_add() (called from ire_forward())
30197 		 * holds a ref on the ire until ARP is completed.
30198 		 */
30199 
30200 		ire_arpresolve(ire, ire_to_ill(ire));
30201 		return (LOOKUP_IN_PROGRESS);
30202 	default:
30203 		ASSERT(0);
30204 		mutex_exit(&arpce->nce_lock);
30205 		return (LLHDR_RESLV_FAILED);
30206 	}
30207 }
30208 
30209 #undef	UPDATE_IP_MIB_OB_COUNTERS
30210 
30211 /*
30212  * Return B_TRUE if the buffers differ in length or content.
30213  * This is used for comparing extension header buffers.
30214  * Note that an extension header would be declared different
30215  * even if all that changed was the next header value in that header i.e.
30216  * what really changed is the next extension header.
30217  */
30218 boolean_t
30219 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30220     uint_t blen)
30221 {
30222 	if (!b_valid)
30223 		blen = 0;
30224 
30225 	if (alen != blen)
30226 		return (B_TRUE);
30227 	if (alen == 0)
30228 		return (B_FALSE);	/* Both zero length */
30229 	return (bcmp(abuf, bbuf, alen));
30230 }
30231 
30232 /*
30233  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30234  * Return B_FALSE if memory allocation fails - don't change any state!
30235  */
30236 boolean_t
30237 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30238     const void *src, uint_t srclen)
30239 {
30240 	void *dst;
30241 
30242 	if (!src_valid)
30243 		srclen = 0;
30244 
30245 	ASSERT(*dstlenp == 0);
30246 	if (src != NULL && srclen != 0) {
30247 		dst = mi_alloc(srclen, BPRI_MED);
30248 		if (dst == NULL)
30249 			return (B_FALSE);
30250 	} else {
30251 		dst = NULL;
30252 	}
30253 	if (*dstp != NULL)
30254 		mi_free(*dstp);
30255 	*dstp = dst;
30256 	*dstlenp = dst == NULL ? 0 : srclen;
30257 	return (B_TRUE);
30258 }
30259 
30260 /*
30261  * Replace what is in *dst, *dstlen with the source.
30262  * Assumes ip_allocbuf has already been called.
30263  */
30264 void
30265 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30266     const void *src, uint_t srclen)
30267 {
30268 	if (!src_valid)
30269 		srclen = 0;
30270 
30271 	ASSERT(*dstlenp == srclen);
30272 	if (src != NULL && srclen != 0)
30273 		bcopy(src, *dstp, srclen);
30274 }
30275 
30276 /*
30277  * Free the storage pointed to by the members of an ip6_pkt_t.
30278  */
30279 void
30280 ip6_pkt_free(ip6_pkt_t *ipp)
30281 {
30282 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30283 
30284 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30285 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30286 		ipp->ipp_hopopts = NULL;
30287 		ipp->ipp_hopoptslen = 0;
30288 	}
30289 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30290 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30291 		ipp->ipp_rtdstopts = NULL;
30292 		ipp->ipp_rtdstoptslen = 0;
30293 	}
30294 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30295 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30296 		ipp->ipp_dstopts = NULL;
30297 		ipp->ipp_dstoptslen = 0;
30298 	}
30299 	if (ipp->ipp_fields & IPPF_RTHDR) {
30300 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30301 		ipp->ipp_rthdr = NULL;
30302 		ipp->ipp_rthdrlen = 0;
30303 	}
30304 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30305 	    IPPF_RTHDR);
30306 }
30307