xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 3b608f655bd09bfb0ba6b14bb23ec70acc77814c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/optcom.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <sys/sunddi.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
131  * IP_SQUEUE_ENTER: squeue_enter
132  * IP_SQUEUE_FILL: squeue_fill
133  */
134 int ip_squeue_enter = 2;	/* Setable in /etc/system */
135 
136 squeue_func_t ip_input_proc;
137 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
138 
139 #define	TCP6 "tcp6"
140 #define	TCP "tcp"
141 #define	SCTP "sctp"
142 #define	SCTP6 "sctp6"
143 
144 major_t TCP6_MAJ;
145 major_t TCP_MAJ;
146 major_t SCTP_MAJ;
147 major_t SCTP6_MAJ;
148 
149 /*
150  * Setable in /etc/system
151  */
152 int ip_poll_normal_ms = 100;
153 int ip_poll_normal_ticks = 0;
154 int ip_modclose_ackwait_ms = 3000;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	listptr_t	ird_route;	/* ipRouteEntryTable */
174 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
175 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
176 } iproutedata_t;
177 
178 /*
179  * Cluster specific hooks. These should be NULL when booted as a non-cluster
180  */
181 
182 /*
183  * Hook functions to enable cluster networking
184  * On non-clustered systems these vectors must always be NULL.
185  *
186  * Hook function to Check ip specified ip address is a shared ip address
187  * in the cluster
188  *
189  */
190 int (*cl_inet_isclusterwide)(uint8_t protocol,
191     sa_family_t addr_family, uint8_t *laddrp) = NULL;
192 
193 /*
194  * Hook function to generate cluster wide ip fragment identifier
195  */
196 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
197     uint8_t *laddrp, uint8_t *faddrp) = NULL;
198 
199 /*
200  * Synchronization notes:
201  *
202  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
203  * MT level protection given by STREAMS. IP uses a combination of its own
204  * internal serialization mechanism and standard Solaris locking techniques.
205  * The internal serialization is per phyint (no IPMP) or per IPMP group.
206  * This is used to serialize plumbing operations, IPMP operations, certain
207  * multicast operations, most set ioctls, igmp/mld timers etc.
208  *
209  * Plumbing is a long sequence of operations involving message
210  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
211  * involved in plumbing operations. A natural model is to serialize these
212  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
213  * parallel without any interference. But various set ioctls on hme0 are best
214  * serialized. However if the system uses IPMP, the operations are easier if
215  * they are serialized on a per IPMP group basis since IPMP operations
216  * happen across ill's of a group. Thus the lowest common denominator is to
217  * serialize most set ioctls, multicast join/leave operations, IPMP operations
218  * igmp/mld timer operations, and processing of DLPI control messages received
219  * from drivers on a per IPMP group basis. If the system does not employ
220  * IPMP the serialization is on a per phyint basis. This serialization is
221  * provided by the ipsq_t and primitives operating on this. Details can
222  * be found in ip_if.c above the core primitives operating on ipsq_t.
223  *
224  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
225  * Simiarly lookup of an ire by a thread also returns a refheld ire.
226  * In addition ipif's and ill's referenced by the ire are also indirectly
227  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
228  * the ipif's address or netmask change as long as an ipif is refheld
229  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
230  * address of an ipif has to go through the ipsq_t. This ensures that only
231  * 1 such exclusive operation proceeds at any time on the ipif. It then
232  * deletes all ires associated with this ipif, and waits for all refcnts
233  * associated with this ipif to come down to zero. The address is changed
234  * only after the ipif has been quiesced. Then the ipif is brought up again.
235  * More details are described above the comment in ip_sioctl_flags.
236  *
237  * Packet processing is based mostly on IREs and are fully multi-threaded
238  * using standard Solaris MT techniques.
239  *
240  * There are explicit locks in IP to handle:
241  * - The ip_g_head list maintained by mi_open_link() and friends.
242  *
243  * - The reassembly data structures (one lock per hash bucket)
244  *
245  * - conn_lock is meant to protect conn_t fields. The fields actually
246  *   protected by conn_lock are documented in the conn_t definition.
247  *
248  * - ire_lock to protect some of the fields of the ire, IRE tables
249  *   (one lock per hash bucket). Refer to ip_ire.c for details.
250  *
251  * - ndp_g_lock and nce_lock for protecting NCEs.
252  *
253  * - ill_lock protects fields of the ill and ipif. Details in ip.h
254  *
255  * - ill_g_lock: This is a global reader/writer lock. Protects the following
256  *	* The AVL tree based global multi list of all ills.
257  *	* The linked list of all ipifs of an ill
258  *	* The <ill-ipsq> mapping
259  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
260  *	* The illgroup list threaded by ill_group_next.
261  *	* <ill-phyint> association
262  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
263  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
264  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
265  *   will all have to hold the ill_g_lock as writer for the actual duration
266  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
267  *   may be found in the IPMP section.
268  *
269  * - ill_lock:  This is a per ill mutex.
270  *   It protects some members of the ill and is documented below.
271  *   It also protects the <ill-ipsq> mapping
272  *   It also protects the illgroup list threaded by ill_group_next.
273  *   It also protects the <ill-phyint> assoc.
274  *   It also protects the list of ipifs hanging off the ill.
275  *
276  * - ipsq_lock: This is a per ipsq_t mutex lock.
277  *   This protects all the other members of the ipsq struct except
278  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
279  *
280  * - illgrp_lock: This is a per ill_group mutex lock.
281  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
282  *   which dictates which is the next ill in an ill_group that is to be chosen
283  *   for sending outgoing packets, through creation of an IRE_CACHE that
284  *   references this ill.
285  *
286  * - phyint_lock: This is a per phyint mutex lock. Protects just the
287  *   phyint_flags
288  *
289  * - ip_g_nd_lock: This is a global reader/writer lock.
290  *   Any call to nd_load to load a new parameter to the ND table must hold the
291  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
292  *   as reader.
293  *
294  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
295  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
296  *   uniqueness check also done atomically.
297  *
298  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
299  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
300  *   as a writer when adding or deleting elements from these lists, and
301  *   as a reader when walking these lists to send a SADB update to the
302  *   IPsec capable ills.
303  *
304  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
305  *   group list linked by ill_usesrc_grp_next. It also protects the
306  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
307  *   group is being added or deleted.  This lock is taken as a reader when
308  *   walking the list/group(eg: to get the number of members in a usesrc group).
309  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
310  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
311  *   example, it is not necessary to take this lock in the initial portion
312  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
313  *   ip_sioctl_flags since the these operations are executed exclusively and
314  *   that ensures that the "usesrc group state" cannot change. The "usesrc
315  *   group state" change can happen only in the latter part of
316  *   ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
325  * and the ill_lock of the ill in question must be held.
326  *
327  * To change the <ill-illgroup> association the ill_g_lock must be held as
328  * writer and the ill_lock of the ill in question must be held.
329  *
330  * To add or delete an ipif from the list of ipifs hanging off the ill,
331  * ill_g_lock (writer) and ill_lock must be held and the thread must be
332  * a writer on the associated ipsq,.
333  *
334  * To add or delete an ill to the system, the ill_g_lock must be held as
335  * writer and the thread must be a writer on the associated ipsq.
336  *
337  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
338  * must be a writer on the associated ipsq.
339  *
340  * Lock hierarchy
341  *
342  * Some lock hierarchy scenarios are listed below.
343  *
344  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
345  * ill_g_lock -> illgrp_lock -> ill_lock
346  * ill_g_lock -> ill_lock(s) -> phyint_lock
347  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
348  * ill_g_lock -> ip_addr_avail_lock
349  * conn_lock -> irb_lock -> ill_lock -> ire_lock
350  * ill_g_lock -> ip_g_nd_lock
351  *
352  * When more than 1 ill lock is needed to be held, all ill lock addresses
353  * are sorted on address and locked starting from highest addressed lock
354  * downward.
355  *
356  * Mobile-IP scenarios
357  *
358  * irb_lock -> ill_lock -> ire_mrtun_lock
359  * irb_lock -> ill_lock -> ire_srcif_table_lock
360  *
361  * IPsec scenarios
362  *
363  * ipsa_lock -> ill_g_lock -> ill_lock
364  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
365  * ipsec_capab_ills_lock -> ipsa_lock
366  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
367  *
368  * Trusted Solaris scenarios
369  *
370  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
371  * igsa_lock -> gcdb_lock
372  * gcgrp_rwlock -> ire_lock
373  * gcgrp_rwlock -> gcdb_lock
374  *
375  *
376  * Routing/forwarding table locking notes:
377  *
378  * Lock acquisition order: Radix tree lock, irb_lock.
379  * Requirements:
380  * i.  Walker must not hold any locks during the walker callback.
381  * ii  Walker must not see a truncated tree during the walk because of any node
382  *     deletion.
383  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
384  *     in many places in the code to walk the irb list. Thus even if all the
385  *     ires in a bucket have been deleted, we still can't free the radix node
386  *     until the ires have actually been inactive'd (freed).
387  *
388  * Tree traversal - Need to hold the global tree lock in read mode.
389  * Before dropping the global tree lock, need to either increment the ire_refcnt
390  * to ensure that the radix node can't be deleted.
391  *
392  * Tree add - Need to hold the global tree lock in write mode to add a
393  * radix node. To prevent the node from being deleted, increment the
394  * irb_refcnt, after the node is added to the tree. The ire itself is
395  * added later while holding the irb_lock, but not the tree lock.
396  *
397  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
398  * All associated ires must be inactive (i.e. freed), and irb_refcnt
399  * must be zero.
400  *
401  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
402  * global tree lock (read mode) for traversal.
403  *
404  * IPSEC notes :
405  *
406  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
407  * in front of the actual packet. For outbound datagrams, the M_CTL
408  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
409  * information used by the IPSEC code for applying the right level of
410  * protection. The information initialized by IP in the ipsec_out_t
411  * is determined by the per-socket policy or global policy in the system.
412  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
413  * ipsec_info.h) which starts out with nothing in it. It gets filled
414  * with the right information if it goes through the AH/ESP code, which
415  * happens if the incoming packet is secure. The information initialized
416  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
417  * the policy requirements needed by per-socket policy or global policy
418  * is met or not.
419  *
420  * If there is both per-socket policy (set using setsockopt) and there
421  * is also global policy match for the 5 tuples of the socket,
422  * ipsec_override_policy() makes the decision of which one to use.
423  *
424  * For fully connected sockets i.e dst, src [addr, port] is known,
425  * conn_policy_cached is set indicating that policy has been cached.
426  * conn_in_enforce_policy may or may not be set depending on whether
427  * there is a global policy match or per-socket policy match.
428  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
429  * Once the right policy is set on the conn_t, policy cannot change for
430  * this socket. This makes life simpler for TCP (UDP ?) where
431  * re-transmissions go out with the same policy. For symmetry, policy
432  * is cached for fully connected UDP sockets also. Thus if policy is cached,
433  * it also implies that policy is latched i.e policy cannot change
434  * on these sockets. As we have the right policy on the conn, we don't
435  * have to lookup global policy for every outbound and inbound datagram
436  * and thus serving as an optimization. Note that a global policy change
437  * does not affect fully connected sockets if they have policy. If fully
438  * connected sockets did not have any policy associated with it, global
439  * policy change may affect them.
440  *
441  * IP Flow control notes:
442  *
443  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
444  * cannot be sent down to the driver by IP, because of a canput failure, IP
445  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
446  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
447  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
448  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
449  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
450  * the queued messages, and removes the conn from the drain list, if all
451  * messages were drained. It also qenables the next conn in the drain list to
452  * continue the drain process.
453  *
454  * In reality the drain list is not a single list, but a configurable number
455  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
456  * list. If the ip_wsrv of the next qenabled conn does not run, because the
457  * stream closes, ip_close takes responsibility to qenable the next conn in
458  * the drain list. The directly called ip_wput path always does a putq, if
459  * it cannot putnext. Thus synchronization problems are handled between
460  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
461  * functions that manipulate this drain list. Furthermore conn_drain_insert
462  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
463  * running on a queue at any time. conn_drain_tail can be simultaneously called
464  * from both ip_wsrv and ip_close.
465  *
466  * IPQOS notes:
467  *
468  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
469  * and IPQoS modules. IPPF includes hooks in IP at different control points
470  * (callout positions) which direct packets to IPQoS modules for policy
471  * processing. Policies, if present, are global.
472  *
473  * The callout positions are located in the following paths:
474  *		o local_in (packets destined for this host)
475  *		o local_out (packets orginating from this host )
476  *		o fwd_in  (packets forwarded by this m/c - inbound)
477  *		o fwd_out (packets forwarded by this m/c - outbound)
478  * Hooks at these callout points can be enabled/disabled using the ndd variable
479  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
480  * By default all the callout positions are enabled.
481  *
482  * Outbound (local_out)
483  * Hooks are placed in ip_wput_ire and ipsec_out_process.
484  *
485  * Inbound (local_in)
486  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
487  * TCP and UDP fanout routines.
488  *
489  * Forwarding (in and out)
490  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
491  *
492  * IP Policy Framework processing (IPPF processing)
493  * Policy processing for a packet is initiated by ip_process, which ascertains
494  * that the classifier (ipgpc) is loaded and configured, failing which the
495  * packet resumes normal processing in IP. If the clasifier is present, the
496  * packet is acted upon by one or more IPQoS modules (action instances), per
497  * filters configured in ipgpc and resumes normal IP processing thereafter.
498  * An action instance can drop a packet in course of its processing.
499  *
500  * A boolean variable, ip_policy, is used in all the fanout routines that can
501  * invoke ip_process for a packet. This variable indicates if the packet should
502  * to be sent for policy processing. The variable is set to B_TRUE by default,
503  * i.e. when the routines are invoked in the normal ip procesing path for a
504  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
505  * ip_policy is set to B_FALSE for all the routines called in these two
506  * functions because, in the former case,  we don't process loopback traffic
507  * currently while in the latter, the packets have already been processed in
508  * icmp_inbound.
509  *
510  * Zones notes:
511  *
512  * The partitioning rules for networking are as follows:
513  * 1) Packets coming from a zone must have a source address belonging to that
514  * zone.
515  * 2) Packets coming from a zone can only be sent on a physical interface on
516  * which the zone has an IP address.
517  * 3) Between two zones on the same machine, packet delivery is only allowed if
518  * there's a matching route for the destination and zone in the forwarding
519  * table.
520  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
521  * different zones can bind to the same port with the wildcard address
522  * (INADDR_ANY).
523  *
524  * The granularity of interface partitioning is at the logical interface level.
525  * Therefore, every zone has its own IP addresses, and incoming packets can be
526  * attributed to a zone unambiguously. A logical interface is placed into a zone
527  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
528  * structure. Rule (1) is implemented by modifying the source address selection
529  * algorithm so that the list of eligible addresses is filtered based on the
530  * sending process zone.
531  *
532  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
533  * across all zones, depending on their type. Here is the break-up:
534  *
535  * IRE type				Shared/exclusive
536  * --------				----------------
537  * IRE_BROADCAST			Exclusive
538  * IRE_DEFAULT (default routes)		Shared (*)
539  * IRE_LOCAL				Exclusive (x)
540  * IRE_LOOPBACK				Exclusive
541  * IRE_PREFIX (net routes)		Shared (*)
542  * IRE_CACHE				Exclusive
543  * IRE_IF_NORESOLVER (interface routes)	Exclusive
544  * IRE_IF_RESOLVER (interface routes)	Exclusive
545  * IRE_HOST (host routes)		Shared (*)
546  *
547  * (*) A zone can only use a default or off-subnet route if the gateway is
548  * directly reachable from the zone, that is, if the gateway's address matches
549  * one of the zone's logical interfaces.
550  *
551  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
552  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
553  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
554  * address of the zone itself (the destination). Since IRE_LOCAL is used
555  * for communication between zones, ip_wput_ire has special logic to set
556  * the right source address when sending using an IRE_LOCAL.
557  *
558  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
559  * ire_cache_lookup restricts loopback using an IRE_LOCAL
560  * between zone to the case when L2 would have conceptually looped the packet
561  * back, i.e. the loopback which is required since neither Ethernet drivers
562  * nor Ethernet hardware loops them back. This is the case when the normal
563  * routes (ignoring IREs with different zoneids) would send out the packet on
564  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
565  * associated.
566  *
567  * Multiple zones can share a common broadcast address; typically all zones
568  * share the 255.255.255.255 address. Incoming as well as locally originated
569  * broadcast packets must be dispatched to all the zones on the broadcast
570  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
571  * since some zones may not be on the 10.16.72/24 network. To handle this, each
572  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
573  * sent to every zone that has an IRE_BROADCAST entry for the destination
574  * address on the input ill, see conn_wantpacket().
575  *
576  * Applications in different zones can join the same multicast group address.
577  * For IPv4, group memberships are per-logical interface, so they're already
578  * inherently part of a zone. For IPv6, group memberships are per-physical
579  * interface, so we distinguish IPv6 group memberships based on group address,
580  * interface and zoneid. In both cases, received multicast packets are sent to
581  * every zone for which a group membership entry exists. On IPv6 we need to
582  * check that the target zone still has an address on the receiving physical
583  * interface; it could have been removed since the application issued the
584  * IPV6_JOIN_GROUP.
585  */
586 
587 /*
588  * Squeue Fanout flags:
589  *	0: No fanout.
590  *	1: Fanout across all squeues
591  */
592 boolean_t	ip_squeue_fanout = 0;
593 
594 /*
595  * Maximum dups allowed per packet.
596  */
597 uint_t ip_max_frag_dups = 10;
598 
599 #define	IS_SIMPLE_IPH(ipha)						\
600 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
601 
602 /* RFC1122 Conformance */
603 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
604 
605 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
606 
607 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
608 
609 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
610 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
611 
612 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
613 		    ip_stack_t *);
614 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
615 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
616 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
617 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
618 		    mblk_t *, int, ip_stack_t *);
619 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
620 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
621 		    ill_t *, zoneid_t);
622 static void	icmp_options_update(ipha_t *);
623 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
624 		    ip_stack_t *);
625 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
626 		    zoneid_t zoneid, ip_stack_t *);
627 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
628 static void	icmp_redirect(ill_t *, mblk_t *);
629 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
630 		    ip_stack_t *);
631 
632 static void	ip_arp_news(queue_t *, mblk_t *);
633 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
634 		    ip_stack_t *);
635 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
636 char		*ip_dot_addr(ipaddr_t, char *);
637 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
638 int		ip_close(queue_t *, int);
639 static char	*ip_dot_saddr(uchar_t *, char *);
640 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
641 		    boolean_t, boolean_t, ill_t *, zoneid_t);
642 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
643 		    boolean_t, boolean_t, zoneid_t);
644 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
645 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
646 static void	ip_lrput(queue_t *, mblk_t *);
647 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
648 ipaddr_t	ip_net_mask(ipaddr_t);
649 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
650 		    zoneid_t, ip_stack_t *);
651 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
652 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
653 char		*ip_nv_lookup(nv_t *, int);
654 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
655 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
656 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
657 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
658     ipndp_t *, size_t);
659 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
660 void	ip_rput(queue_t *, mblk_t *);
661 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
662 		    void *dummy_arg);
663 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
664 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
665     ip_stack_t *);
666 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
667 			    ire_t *, ip_stack_t *);
668 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
669 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
670 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
671     ip_stack_t *);
672 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
673 		    uint16_t *);
674 int		ip_snmp_get(queue_t *, mblk_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
676 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
678 		    ip_stack_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
680 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
703 		    ip_stack_t *ipst);
704 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
705 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
706 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
707 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
708 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
709 static boolean_t	ip_source_route_included(ipha_t *);
710 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
711 
712 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
713 		    zoneid_t, ip_stack_t *);
714 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
715 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
716 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
717 		    zoneid_t, ip_stack_t *);
718 
719 static void	conn_drain_init(ip_stack_t *);
720 static void	conn_drain_fini(ip_stack_t *);
721 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
722 
723 static void	conn_walk_drain(ip_stack_t *);
724 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
725     zoneid_t);
726 
727 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
728 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
729 static void	ip_stack_fini(netstackid_t stackid, void *arg);
730 
731 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
732     zoneid_t);
733 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
734     void *dummy_arg);
735 
736 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
737 
738 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
739     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
740     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
741 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
742 
743 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
744 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
745     caddr_t, cred_t *);
746 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
747     caddr_t cp, cred_t *cr);
748 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
749     cred_t *);
750 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
751     caddr_t cp, cred_t *cr);
752 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
753     cred_t *);
754 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
755     cred_t *);
756 static squeue_func_t ip_squeue_switch(int);
757 
758 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
759 static void	ip_kstat_fini(netstackid_t, kstat_t *);
760 static int	ip_kstat_update(kstat_t *kp, int rw);
761 static void	*icmp_kstat_init(netstackid_t);
762 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
763 static int	icmp_kstat_update(kstat_t *kp, int rw);
764 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
765 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
766 
767 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
768 
769 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
770     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
771 
772 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
773     ipha_t *, ill_t *, boolean_t);
774 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
775 
776 /* How long, in seconds, we allow frags to hang around. */
777 #define	IP_FRAG_TIMEOUT	60
778 
779 /*
780  * Threshold which determines whether MDT should be used when
781  * generating IP fragments; payload size must be greater than
782  * this threshold for MDT to take place.
783  */
784 #define	IP_WPUT_FRAG_MDT_MIN	32768
785 
786 /* Setable in /etc/system only */
787 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
788 
789 static long ip_rput_pullups;
790 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
791 
792 vmem_t *ip_minor_arena;
793 
794 int	ip_debug;
795 
796 #ifdef DEBUG
797 uint32_t ipsechw_debug = 0;
798 #endif
799 
800 /*
801  * Multirouting/CGTP stuff
802  */
803 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
804 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
805 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
806 
807 /*
808  * XXX following really should only be in a header. Would need more
809  * header and .c clean up first.
810  */
811 extern optdb_obj_t	ip_opt_obj;
812 
813 ulong_t ip_squeue_enter_unbound = 0;
814 
815 /*
816  * Named Dispatch Parameter Table.
817  * All of these are alterable, within the min/max values given, at run time.
818  */
819 static ipparam_t	lcl_param_arr[] = {
820 	/* min	max	value	name */
821 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
822 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
823 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
824 	{  0,	1,	0,	"ip_respond_to_timestamp"},
825 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
826 	{  0,	1,	1,	"ip_send_redirects"},
827 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
828 	{  0,	10,	0,	"ip_debug"},
829 	{  0,	10,	0,	"ip_mrtdebug"},
830 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
831 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
832 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
833 	{  1,	255,	255,	"ip_def_ttl" },
834 	{  0,	1,	0,	"ip_forward_src_routed"},
835 	{  0,	256,	32,	"ip_wroff_extra" },
836 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
837 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
838 	{  0,	1,	1,	"ip_path_mtu_discovery" },
839 	{  0,	240,	30,	"ip_ignore_delete_time" },
840 	{  0,	1,	0,	"ip_ignore_redirect" },
841 	{  0,	1,	1,	"ip_output_queue" },
842 	{  1,	254,	1,	"ip_broadcast_ttl" },
843 	{  0,	99999,	100,	"ip_icmp_err_interval" },
844 	{  1,	99999,	10,	"ip_icmp_err_burst" },
845 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
846 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
847 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
848 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
849 	{  0,	1,	1,	"icmp_accept_clear_messages" },
850 	{  0,	1,	1,	"igmp_accept_clear_messages" },
851 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
852 				"ip_ndp_delay_first_probe_time"},
853 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
854 				"ip_ndp_max_unicast_solicit"},
855 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
856 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
857 	{  0,	1,	0,	"ip6_forward_src_routed"},
858 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
859 	{  0,	1,	1,	"ip6_send_redirects"},
860 	{  0,	1,	0,	"ip6_ignore_redirect" },
861 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
862 
863 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
864 
865 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
866 
867 	{  0,	1,	1,	"pim_accept_clear_messages" },
868 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
869 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
870 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
871 	{  0,	15,	0,	"ip_policy_mask" },
872 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
873 	{  0,	255,	1,	"ip_multirt_ttl" },
874 	{  0,	1,	1,	"ip_multidata_outbound" },
875 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
876 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
877 	{  0,	1000,	1,	"ip_max_temp_defend" },
878 	{  0,	1000,	3,	"ip_max_defend" },
879 	{  0,	999999,	30,	"ip_defend_interval" },
880 	{  0,	3600000, 300000, "ip_dup_recovery" },
881 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
882 	{  0,	1,	1,	"ip_lso_outbound" },
883 #ifdef DEBUG
884 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
885 #else
886 	{  0,	0,	0,	"" },
887 #endif
888 };
889 
890 /*
891  * Extended NDP table
892  * The addresses for the first two are filled in to be ips_ip_g_forward
893  * and ips_ipv6_forward at init time.
894  */
895 static ipndp_t	lcl_ndp_arr[] = {
896 	/* getf			setf		data			name */
897 #define	IPNDP_IP_FORWARDING_OFFSET	0
898 	{  ip_param_generic_get,	ip_forward_set,	NULL,
899 	    "ip_forwarding" },
900 #define	IPNDP_IP6_FORWARDING_OFFSET	1
901 	{  ip_param_generic_get,	ip_forward_set,	NULL,
902 	    "ip6_forwarding" },
903 	{  ip_ill_report,	NULL,		NULL,
904 	    "ip_ill_status" },
905 	{  ip_ipif_report,	NULL,		NULL,
906 	    "ip_ipif_status" },
907 	{  ip_ire_report,	NULL,		NULL,
908 	    "ipv4_ire_status" },
909 	{  ip_ire_report_mrtun,	NULL,		NULL,
910 	    "ipv4_mrtun_ire_status" },
911 	{  ip_ire_report_srcif,	NULL,		NULL,
912 	    "ipv4_srcif_ire_status" },
913 	{  ip_ire_report_v6,	NULL,		NULL,
914 	    "ipv6_ire_status" },
915 	{  ip_conn_report,	NULL,		NULL,
916 	    "ip_conn_status" },
917 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
918 	    "ip_rput_pullups" },
919 	{  ndp_report,		NULL,		NULL,
920 	    "ip_ndp_cache_report" },
921 	{  ip_srcid_report,	NULL,		NULL,
922 	    "ip_srcid_status" },
923 	{ ip_param_generic_get, ip_squeue_profile_set,
924 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
925 	{ ip_param_generic_get, ip_squeue_bind_set,
926 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
927 	{ ip_param_generic_get, ip_input_proc_set,
928 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
929 	{ ip_param_generic_get, ip_int_set,
930 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
931 #define	IPNDP_CGTP_FILTER_OFFSET	16
932 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
933 	    "ip_cgtp_filter" },
934 	{ ip_param_generic_get, ip_int_set,
935 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
936 #define	IPNDP_IPMP_HOOK_OFFSET	18
937 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
938 	    "ipmp_hook_emulation" },
939 };
940 
941 /*
942  * Table of IP ioctls encoding the various properties of the ioctl and
943  * indexed based on the last byte of the ioctl command. Occasionally there
944  * is a clash, and there is more than 1 ioctl with the same last byte.
945  * In such a case 1 ioctl is encoded in the ndx table and the remaining
946  * ioctls are encoded in the misc table. An entry in the ndx table is
947  * retrieved by indexing on the last byte of the ioctl command and comparing
948  * the ioctl command with the value in the ndx table. In the event of a
949  * mismatch the misc table is then searched sequentially for the desired
950  * ioctl command.
951  *
952  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
953  */
954 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
955 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
961 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
962 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
963 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
964 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
965 
966 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
967 			MISC_CMD, ip_siocaddrt, NULL },
968 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
969 			MISC_CMD, ip_siocdelrt, NULL },
970 
971 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
972 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
973 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
974 			IF_CMD, ip_sioctl_get_addr, NULL },
975 
976 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
977 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
978 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
979 			IPI_GET_CMD | IPI_REPL,
980 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
981 
982 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
983 			IPI_PRIV | IPI_WR | IPI_REPL,
984 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
985 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
986 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
987 			IF_CMD, ip_sioctl_get_flags, NULL },
988 
989 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
990 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
991 
992 	/* copyin size cannot be coded for SIOCGIFCONF */
993 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
994 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
995 
996 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
997 			IF_CMD, ip_sioctl_mtu, NULL },
998 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
999 			IF_CMD, ip_sioctl_get_mtu, NULL },
1000 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1001 			IPI_GET_CMD | IPI_REPL,
1002 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1003 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1004 			IF_CMD, ip_sioctl_brdaddr, NULL },
1005 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1006 			IPI_GET_CMD | IPI_REPL,
1007 			IF_CMD, ip_sioctl_get_netmask, NULL },
1008 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1009 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1010 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1011 			IPI_GET_CMD | IPI_REPL,
1012 			IF_CMD, ip_sioctl_get_metric, NULL },
1013 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1014 			IF_CMD, ip_sioctl_metric, NULL },
1015 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 
1017 	/* See 166-168 below for extended SIOC*XARP ioctls */
1018 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1019 			MISC_CMD, ip_sioctl_arp, NULL },
1020 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1021 			MISC_CMD, ip_sioctl_arp, NULL },
1022 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1023 			MISC_CMD, ip_sioctl_arp, NULL },
1024 
1025 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 
1047 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1048 			MISC_CMD, if_unitsel, if_unitsel_restart },
1049 
1050 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 
1069 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1070 			IPI_PRIV | IPI_WR | IPI_MODOK,
1071 			IF_CMD, ip_sioctl_sifname, NULL },
1072 
1073 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 
1087 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1088 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1089 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1090 			IF_CMD, ip_sioctl_get_muxid, NULL },
1091 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1092 			IPI_PRIV | IPI_WR | IPI_REPL,
1093 			IF_CMD, ip_sioctl_muxid, NULL },
1094 
1095 	/* Both if and lif variants share same func */
1096 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1097 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1098 	/* Both if and lif variants share same func */
1099 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1100 			IPI_PRIV | IPI_WR | IPI_REPL,
1101 			IF_CMD, ip_sioctl_slifindex, NULL },
1102 
1103 	/* copyin size cannot be coded for SIOCGIFCONF */
1104 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1105 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1106 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 
1124 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1125 			IPI_PRIV | IPI_WR | IPI_REPL,
1126 			LIF_CMD, ip_sioctl_removeif,
1127 			ip_sioctl_removeif_restart },
1128 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1129 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1130 			LIF_CMD, ip_sioctl_addif, NULL },
1131 #define	SIOCLIFADDR_NDX 112
1132 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1133 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1134 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1135 			IPI_GET_CMD | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_get_addr, NULL },
1137 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1138 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1139 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1140 			IPI_GET_CMD | IPI_REPL,
1141 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1142 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1143 			IPI_PRIV | IPI_WR | IPI_REPL,
1144 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1145 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1146 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1147 			LIF_CMD, ip_sioctl_get_flags, NULL },
1148 
1149 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 
1152 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1153 			ip_sioctl_get_lifconf, NULL },
1154 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1155 			LIF_CMD, ip_sioctl_mtu, NULL },
1156 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1157 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1158 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1159 			IPI_GET_CMD | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1161 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1162 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1163 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1164 			IPI_GET_CMD | IPI_REPL,
1165 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1166 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1167 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1168 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1169 			IPI_GET_CMD | IPI_REPL,
1170 			LIF_CMD, ip_sioctl_get_metric, NULL },
1171 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1172 			LIF_CMD, ip_sioctl_metric, NULL },
1173 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1174 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1175 			LIF_CMD, ip_sioctl_slifname,
1176 			ip_sioctl_slifname_restart },
1177 
1178 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1179 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1180 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1181 			IPI_GET_CMD | IPI_REPL,
1182 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1183 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1184 			IPI_PRIV | IPI_WR | IPI_REPL,
1185 			LIF_CMD, ip_sioctl_muxid, NULL },
1186 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1187 			IPI_GET_CMD | IPI_REPL,
1188 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1189 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1190 			IPI_PRIV | IPI_WR | IPI_REPL,
1191 			LIF_CMD, ip_sioctl_slifindex, 0 },
1192 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_token, NULL },
1194 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1195 			IPI_GET_CMD | IPI_REPL,
1196 			LIF_CMD, ip_sioctl_get_token, NULL },
1197 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1198 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1199 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1200 			IPI_GET_CMD | IPI_REPL,
1201 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1202 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1203 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1204 
1205 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1206 			IPI_GET_CMD | IPI_REPL,
1207 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1208 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1209 			LIF_CMD, ip_siocdelndp_v6, NULL },
1210 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1211 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1212 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1213 			LIF_CMD, ip_siocsetndp_v6, NULL },
1214 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1215 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1216 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1217 			MISC_CMD, ip_sioctl_tonlink, NULL },
1218 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1219 			MISC_CMD, ip_sioctl_tmysite, NULL },
1220 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1221 			TUN_CMD, ip_sioctl_tunparam, NULL },
1222 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1223 			IPI_PRIV | IPI_WR,
1224 			TUN_CMD, ip_sioctl_tunparam, NULL },
1225 
1226 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1227 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1228 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1229 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1230 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1231 
1232 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1233 			IPI_PRIV | IPI_WR | IPI_REPL,
1234 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1235 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1236 			IPI_PRIV | IPI_WR | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1238 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1239 			IPI_PRIV | IPI_WR,
1240 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1241 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1242 			IPI_GET_CMD | IPI_REPL,
1243 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1244 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1245 			IPI_GET_CMD | IPI_REPL,
1246 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1247 
1248 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1249 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1250 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1251 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1252 
1253 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1254 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1255 
1256 	/* These are handled in ip_sioctl_copyin_setup itself */
1257 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1258 			MISC_CMD, NULL, NULL },
1259 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1260 			MISC_CMD, NULL, NULL },
1261 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1262 
1263 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1264 			ip_sioctl_get_lifconf, NULL },
1265 
1266 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1267 			MISC_CMD, ip_sioctl_xarp, NULL },
1268 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1269 			MISC_CMD, ip_sioctl_xarp, NULL },
1270 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1271 			MISC_CMD, ip_sioctl_xarp, NULL },
1272 
1273 	/* SIOCPOPSOCKFS is not handled by IP */
1274 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1275 
1276 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1277 			IPI_GET_CMD | IPI_REPL,
1278 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1279 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1280 			IPI_PRIV | IPI_WR | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_slifzone,
1282 			ip_sioctl_slifzone_restart },
1283 	/* 172-174 are SCTP ioctls and not handled by IP */
1284 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1285 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1286 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1287 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1288 			IPI_GET_CMD, LIF_CMD,
1289 			ip_sioctl_get_lifusesrc, 0 },
1290 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1291 			IPI_PRIV | IPI_WR,
1292 			LIF_CMD, ip_sioctl_slifusesrc,
1293 			NULL },
1294 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1295 			ip_sioctl_get_lifsrcof, NULL },
1296 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1297 			MISC_CMD, ip_sioctl_msfilter, NULL },
1298 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1299 			MISC_CMD, ip_sioctl_msfilter, NULL },
1300 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1301 			MISC_CMD, ip_sioctl_msfilter, NULL },
1302 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1303 			MISC_CMD, ip_sioctl_msfilter, NULL },
1304 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1305 			ip_sioctl_set_ipmpfailback, NULL }
1306 };
1307 
1308 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1309 
1310 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1311 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1312 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1313 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1314 		TUN_CMD, ip_sioctl_tunparam, NULL },
1315 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1317 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1318 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1319 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1320 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1321 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1322 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1323 		MISC_CMD, mrt_ioctl},
1324 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1325 		MISC_CMD, mrt_ioctl},
1326 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1327 		MISC_CMD, mrt_ioctl}
1328 };
1329 
1330 int ip_misc_ioctl_count =
1331     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1332 
1333 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1334 					/* Settable in /etc/system */
1335 /* Defined in ip_ire.c */
1336 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1337 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1338 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1339 
1340 static nv_t	ire_nv_arr[] = {
1341 	{ IRE_BROADCAST, "BROADCAST" },
1342 	{ IRE_LOCAL, "LOCAL" },
1343 	{ IRE_LOOPBACK, "LOOPBACK" },
1344 	{ IRE_CACHE, "CACHE" },
1345 	{ IRE_DEFAULT, "DEFAULT" },
1346 	{ IRE_PREFIX, "PREFIX" },
1347 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1348 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1349 	{ IRE_HOST, "HOST" },
1350 	{ 0 }
1351 };
1352 
1353 nv_t	*ire_nv_tbl = ire_nv_arr;
1354 
1355 /* Defined in ip_netinfo.c */
1356 extern ddi_taskq_t	*eventq_queue_nic;
1357 
1358 /* Simple ICMP IP Header Template */
1359 static ipha_t icmp_ipha = {
1360 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1361 };
1362 
1363 struct module_info ip_mod_info = {
1364 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1365 };
1366 
1367 /*
1368  * Duplicate static symbols within a module confuses mdb; so we avoid the
1369  * problem by making the symbols here distinct from those in udp.c.
1370  */
1371 
1372 static struct qinit iprinit = {
1373 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1374 	&ip_mod_info
1375 };
1376 
1377 static struct qinit ipwinit = {
1378 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1379 	&ip_mod_info
1380 };
1381 
1382 static struct qinit iplrinit = {
1383 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1384 	&ip_mod_info
1385 };
1386 
1387 static struct qinit iplwinit = {
1388 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1389 	&ip_mod_info
1390 };
1391 
1392 struct streamtab ipinfo = {
1393 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1394 };
1395 
1396 #ifdef	DEBUG
1397 static boolean_t skip_sctp_cksum = B_FALSE;
1398 #endif
1399 
1400 /*
1401  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1402  * ip_rput_v6(), ip_output(), etc.  If the message
1403  * block already has a M_CTL at the front of it, then simply set the zoneid
1404  * appropriately.
1405  */
1406 mblk_t *
1407 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1408 {
1409 	mblk_t		*first_mp;
1410 	ipsec_out_t	*io;
1411 
1412 	ASSERT(zoneid != ALL_ZONES);
1413 	if (mp->b_datap->db_type == M_CTL) {
1414 		io = (ipsec_out_t *)mp->b_rptr;
1415 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1416 		io->ipsec_out_zoneid = zoneid;
1417 		return (mp);
1418 	}
1419 
1420 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1421 	if (first_mp == NULL)
1422 		return (NULL);
1423 	io = (ipsec_out_t *)first_mp->b_rptr;
1424 	/* This is not a secure packet */
1425 	io->ipsec_out_secure = B_FALSE;
1426 	io->ipsec_out_zoneid = zoneid;
1427 	first_mp->b_cont = mp;
1428 	return (first_mp);
1429 }
1430 
1431 /*
1432  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1433  */
1434 mblk_t *
1435 ip_copymsg(mblk_t *mp)
1436 {
1437 	mblk_t *nmp;
1438 	ipsec_info_t *in;
1439 
1440 	if (mp->b_datap->db_type != M_CTL)
1441 		return (copymsg(mp));
1442 
1443 	in = (ipsec_info_t *)mp->b_rptr;
1444 
1445 	/*
1446 	 * Note that M_CTL is also used for delivering ICMP error messages
1447 	 * upstream to transport layers.
1448 	 */
1449 	if (in->ipsec_info_type != IPSEC_OUT &&
1450 	    in->ipsec_info_type != IPSEC_IN)
1451 		return (copymsg(mp));
1452 
1453 	nmp = copymsg(mp->b_cont);
1454 
1455 	if (in->ipsec_info_type == IPSEC_OUT) {
1456 		return (ipsec_out_tag(mp, nmp,
1457 			    ((ipsec_out_t *)in)->ipsec_out_ns));
1458 	} else {
1459 		return (ipsec_in_tag(mp, nmp,
1460 			    ((ipsec_in_t *)in)->ipsec_in_ns));
1461 	}
1462 }
1463 
1464 /* Generate an ICMP fragmentation needed message. */
1465 static void
1466 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1467     ip_stack_t *ipst)
1468 {
1469 	icmph_t	icmph;
1470 	mblk_t *first_mp;
1471 	boolean_t mctl_present;
1472 
1473 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1474 
1475 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1476 		if (mctl_present)
1477 			freeb(first_mp);
1478 		return;
1479 	}
1480 
1481 	bzero(&icmph, sizeof (icmph_t));
1482 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1483 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1484 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1485 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1486 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1487 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1488 	    ipst);
1489 }
1490 
1491 /*
1492  * icmp_inbound deals with ICMP messages in the following ways.
1493  *
1494  * 1) It needs to send a reply back and possibly delivering it
1495  *    to the "interested" upper clients.
1496  * 2) It needs to send it to the upper clients only.
1497  * 3) It needs to change some values in IP only.
1498  * 4) It needs to change some values in IP and upper layers e.g TCP.
1499  *
1500  * We need to accomodate icmp messages coming in clear until we get
1501  * everything secure from the wire. If icmp_accept_clear_messages
1502  * is zero we check with the global policy and act accordingly. If
1503  * it is non-zero, we accept the message without any checks. But
1504  * *this does not mean* that this will be delivered to the upper
1505  * clients. By accepting we might send replies back, change our MTU
1506  * value etc. but delivery to the ULP/clients depends on their policy
1507  * dispositions.
1508  *
1509  * We handle the above 4 cases in the context of IPSEC in the
1510  * following way :
1511  *
1512  * 1) Send the reply back in the same way as the request came in.
1513  *    If it came in encrypted, it goes out encrypted. If it came in
1514  *    clear, it goes out in clear. Thus, this will prevent chosen
1515  *    plain text attack.
1516  * 2) The client may or may not expect things to come in secure.
1517  *    If it comes in secure, the policy constraints are checked
1518  *    before delivering it to the upper layers. If it comes in
1519  *    clear, ipsec_inbound_accept_clear will decide whether to
1520  *    accept this in clear or not. In both the cases, if the returned
1521  *    message (IP header + 8 bytes) that caused the icmp message has
1522  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1523  *    sending up. If there are only 8 bytes of returned message, then
1524  *    upper client will not be notified.
1525  * 3) Check with global policy to see whether it matches the constaints.
1526  *    But this will be done only if icmp_accept_messages_in_clear is
1527  *    zero.
1528  * 4) If we need to change both in IP and ULP, then the decision taken
1529  *    while affecting the values in IP and while delivering up to TCP
1530  *    should be the same.
1531  *
1532  * 	There are two cases.
1533  *
1534  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1535  *	   failed), we will not deliver it to the ULP, even though they
1536  *	   are *willing* to accept in *clear*. This is fine as our global
1537  *	   disposition to icmp messages asks us reject the datagram.
1538  *
1539  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1540  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1541  *	   to deliver it to ULP (policy failed), it can lead to
1542  *	   consistency problems. The cases known at this time are
1543  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1544  *	   values :
1545  *
1546  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1547  *	     and Upper layer rejects. Then the communication will
1548  *	     come to a stop. This is solved by making similar decisions
1549  *	     at both levels. Currently, when we are unable to deliver
1550  *	     to the Upper Layer (due to policy failures) while IP has
1551  *	     adjusted ire_max_frag, the next outbound datagram would
1552  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1553  *	     will be with the right level of protection. Thus the right
1554  *	     value will be communicated even if we are not able to
1555  *	     communicate when we get from the wire initially. But this
1556  *	     assumes there would be at least one outbound datagram after
1557  *	     IP has adjusted its ire_max_frag value. To make things
1558  *	     simpler, we accept in clear after the validation of
1559  *	     AH/ESP headers.
1560  *
1561  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1562  *	     upper layer depending on the level of protection the upper
1563  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1564  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1565  *	     should be accepted in clear when the Upper layer expects secure.
1566  *	     Thus the communication may get aborted by some bad ICMP
1567  *	     packets.
1568  *
1569  * IPQoS Notes:
1570  * The only instance when a packet is sent for processing is when there
1571  * isn't an ICMP client and if we are interested in it.
1572  * If there is a client, IPPF processing will take place in the
1573  * ip_fanout_proto routine.
1574  *
1575  * Zones notes:
1576  * The packet is only processed in the context of the specified zone: typically
1577  * only this zone will reply to an echo request, and only interested clients in
1578  * this zone will receive a copy of the packet. This means that the caller must
1579  * call icmp_inbound() for each relevant zone.
1580  */
1581 static void
1582 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1583     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1584     ill_t *recv_ill, zoneid_t zoneid)
1585 {
1586 	icmph_t	*icmph;
1587 	ipha_t	*ipha;
1588 	int	iph_hdr_length;
1589 	int	hdr_length;
1590 	boolean_t	interested;
1591 	uint32_t	ts;
1592 	uchar_t	*wptr;
1593 	ipif_t	*ipif;
1594 	mblk_t *first_mp;
1595 	ipsec_in_t *ii;
1596 	ire_t *src_ire;
1597 	boolean_t onlink;
1598 	timestruc_t now;
1599 	uint32_t ill_index;
1600 	ip_stack_t *ipst;
1601 
1602 	ASSERT(ill != NULL);
1603 	ipst = ill->ill_ipst;
1604 
1605 	first_mp = mp;
1606 	if (mctl_present) {
1607 		mp = first_mp->b_cont;
1608 		ASSERT(mp != NULL);
1609 	}
1610 
1611 	ipha = (ipha_t *)mp->b_rptr;
1612 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1613 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1614 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1615 		if (first_mp == NULL)
1616 			return;
1617 	}
1618 
1619 	/*
1620 	 * On a labeled system, we have to check whether the zone itself is
1621 	 * permitted to receive raw traffic.
1622 	 */
1623 	if (is_system_labeled()) {
1624 		if (zoneid == ALL_ZONES)
1625 			zoneid = tsol_packet_to_zoneid(mp);
1626 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1627 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1628 			    zoneid));
1629 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1630 			freemsg(first_mp);
1631 			return;
1632 		}
1633 	}
1634 
1635 	/*
1636 	 * We have accepted the ICMP message. It means that we will
1637 	 * respond to the packet if needed. It may not be delivered
1638 	 * to the upper client depending on the policy constraints
1639 	 * and the disposition in ipsec_inbound_accept_clear.
1640 	 */
1641 
1642 	ASSERT(ill != NULL);
1643 
1644 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1645 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1646 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1647 		/* Last chance to get real. */
1648 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1649 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1650 			freemsg(first_mp);
1651 			return;
1652 		}
1653 		/* Refresh iph following the pullup. */
1654 		ipha = (ipha_t *)mp->b_rptr;
1655 	}
1656 	/* ICMP header checksum, including checksum field, should be zero. */
1657 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1658 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1659 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1660 		freemsg(first_mp);
1661 		return;
1662 	}
1663 	/* The IP header will always be a multiple of four bytes */
1664 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1665 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1666 	    icmph->icmph_code));
1667 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1668 	/* We will set "interested" to "true" if we want a copy */
1669 	interested = B_FALSE;
1670 	switch (icmph->icmph_type) {
1671 	case ICMP_ECHO_REPLY:
1672 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1673 		break;
1674 	case ICMP_DEST_UNREACHABLE:
1675 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1676 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1677 		interested = B_TRUE;	/* Pass up to transport */
1678 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1679 		break;
1680 	case ICMP_SOURCE_QUENCH:
1681 		interested = B_TRUE;	/* Pass up to transport */
1682 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1683 		break;
1684 	case ICMP_REDIRECT:
1685 		if (!ipst->ips_ip_ignore_redirect)
1686 			interested = B_TRUE;
1687 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1688 		break;
1689 	case ICMP_ECHO_REQUEST:
1690 		/*
1691 		 * Whether to respond to echo requests that come in as IP
1692 		 * broadcasts or as IP multicast is subject to debate
1693 		 * (what isn't?).  We aim to please, you pick it.
1694 		 * Default is do it.
1695 		 */
1696 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1697 			/* unicast: always respond */
1698 			interested = B_TRUE;
1699 		} else if (CLASSD(ipha->ipha_dst)) {
1700 			/* multicast: respond based on tunable */
1701 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1702 		} else if (broadcast) {
1703 			/* broadcast: respond based on tunable */
1704 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1705 		}
1706 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1707 		break;
1708 	case ICMP_ROUTER_ADVERTISEMENT:
1709 	case ICMP_ROUTER_SOLICITATION:
1710 		break;
1711 	case ICMP_TIME_EXCEEDED:
1712 		interested = B_TRUE;	/* Pass up to transport */
1713 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1714 		break;
1715 	case ICMP_PARAM_PROBLEM:
1716 		interested = B_TRUE;	/* Pass up to transport */
1717 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1718 		break;
1719 	case ICMP_TIME_STAMP_REQUEST:
1720 		/* Response to Time Stamp Requests is local policy. */
1721 		if (ipst->ips_ip_g_resp_to_timestamp &&
1722 		    /* So is whether to respond if it was an IP broadcast. */
1723 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1724 			int tstamp_len = 3 * sizeof (uint32_t);
1725 
1726 			if (wptr +  tstamp_len > mp->b_wptr) {
1727 				if (!pullupmsg(mp, wptr + tstamp_len -
1728 				    mp->b_rptr)) {
1729 					BUMP_MIB(ill->ill_ip_mib,
1730 					    ipIfStatsInDiscards);
1731 					freemsg(first_mp);
1732 					return;
1733 				}
1734 				/* Refresh ipha following the pullup. */
1735 				ipha = (ipha_t *)mp->b_rptr;
1736 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1737 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1738 			}
1739 			interested = B_TRUE;
1740 		}
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1742 		break;
1743 	case ICMP_TIME_STAMP_REPLY:
1744 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1745 		break;
1746 	case ICMP_INFO_REQUEST:
1747 		/* Per RFC 1122 3.2.2.7, ignore this. */
1748 	case ICMP_INFO_REPLY:
1749 		break;
1750 	case ICMP_ADDRESS_MASK_REQUEST:
1751 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1752 			!broadcast) &&
1753 		    /* TODO m_pullup of complete header? */
1754 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1755 			interested = B_TRUE;
1756 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1757 		break;
1758 	case ICMP_ADDRESS_MASK_REPLY:
1759 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1760 		break;
1761 	default:
1762 		interested = B_TRUE;	/* Pass up to transport */
1763 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1764 		break;
1765 	}
1766 	/* See if there is an ICMP client. */
1767 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1768 		/* If there is an ICMP client and we want one too, copy it. */
1769 		mblk_t *first_mp1;
1770 
1771 		if (!interested) {
1772 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1773 			    ip_policy, recv_ill, zoneid);
1774 			return;
1775 		}
1776 		first_mp1 = ip_copymsg(first_mp);
1777 		if (first_mp1 != NULL) {
1778 			ip_fanout_proto(q, first_mp1, ill, ipha,
1779 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1780 		}
1781 	} else if (!interested) {
1782 		freemsg(first_mp);
1783 		return;
1784 	} else {
1785 		/*
1786 		 * Initiate policy processing for this packet if ip_policy
1787 		 * is true.
1788 		 */
1789 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1790 			ill_index = ill->ill_phyint->phyint_ifindex;
1791 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1792 			if (mp == NULL) {
1793 				if (mctl_present) {
1794 					freeb(first_mp);
1795 				}
1796 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1797 				return;
1798 			}
1799 		}
1800 	}
1801 	/* We want to do something with it. */
1802 	/* Check db_ref to make sure we can modify the packet. */
1803 	if (mp->b_datap->db_ref > 1) {
1804 		mblk_t	*first_mp1;
1805 
1806 		first_mp1 = ip_copymsg(first_mp);
1807 		freemsg(first_mp);
1808 		if (!first_mp1) {
1809 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1810 			return;
1811 		}
1812 		first_mp = first_mp1;
1813 		if (mctl_present) {
1814 			mp = first_mp->b_cont;
1815 			ASSERT(mp != NULL);
1816 		} else {
1817 			mp = first_mp;
1818 		}
1819 		ipha = (ipha_t *)mp->b_rptr;
1820 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1821 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1822 	}
1823 	switch (icmph->icmph_type) {
1824 	case ICMP_ADDRESS_MASK_REQUEST:
1825 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1826 		if (ipif == NULL) {
1827 			freemsg(first_mp);
1828 			return;
1829 		}
1830 		/*
1831 		 * outging interface must be IPv4
1832 		 */
1833 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1834 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1835 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1836 		ipif_refrele(ipif);
1837 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1838 		break;
1839 	case ICMP_ECHO_REQUEST:
1840 		icmph->icmph_type = ICMP_ECHO_REPLY;
1841 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1842 		break;
1843 	case ICMP_TIME_STAMP_REQUEST: {
1844 		uint32_t *tsp;
1845 
1846 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1847 		tsp = (uint32_t *)wptr;
1848 		tsp++;		/* Skip past 'originate time' */
1849 		/* Compute # of milliseconds since midnight */
1850 		gethrestime(&now);
1851 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1852 		    now.tv_nsec / (NANOSEC / MILLISEC);
1853 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1854 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1855 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1856 		break;
1857 	}
1858 	default:
1859 		ipha = (ipha_t *)&icmph[1];
1860 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1861 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1862 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1863 				freemsg(first_mp);
1864 				return;
1865 			}
1866 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1867 			ipha = (ipha_t *)&icmph[1];
1868 		}
1869 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1870 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1871 			freemsg(first_mp);
1872 			return;
1873 		}
1874 		hdr_length = IPH_HDR_LENGTH(ipha);
1875 		if (hdr_length < sizeof (ipha_t)) {
1876 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1877 			freemsg(first_mp);
1878 			return;
1879 		}
1880 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1881 			if (!pullupmsg(mp,
1882 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1883 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1884 				freemsg(first_mp);
1885 				return;
1886 			}
1887 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1888 			ipha = (ipha_t *)&icmph[1];
1889 		}
1890 		switch (icmph->icmph_type) {
1891 		case ICMP_REDIRECT:
1892 			/*
1893 			 * As there is no upper client to deliver, we don't
1894 			 * need the first_mp any more.
1895 			 */
1896 			if (mctl_present) {
1897 				freeb(first_mp);
1898 			}
1899 			icmp_redirect(ill, mp);
1900 			return;
1901 		case ICMP_DEST_UNREACHABLE:
1902 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1903 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1904 				    zoneid, mp, iph_hdr_length, ipst)) {
1905 					freemsg(first_mp);
1906 					return;
1907 				}
1908 				/*
1909 				 * icmp_inbound_too_big() may alter mp.
1910 				 * Resynch ipha and icmph accordingly.
1911 				 */
1912 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1913 				ipha = (ipha_t *)&icmph[1];
1914 			}
1915 			/* FALLTHRU */
1916 		default :
1917 			/*
1918 			 * IPQoS notes: Since we have already done IPQoS
1919 			 * processing we don't want to do it again in
1920 			 * the fanout routines called by
1921 			 * icmp_inbound_error_fanout, hence the last
1922 			 * argument, ip_policy, is B_FALSE.
1923 			 */
1924 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1925 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1926 			    B_FALSE, recv_ill, zoneid);
1927 		}
1928 		return;
1929 	}
1930 	/* Send out an ICMP packet */
1931 	icmph->icmph_checksum = 0;
1932 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1933 	if (icmph->icmph_checksum == 0)
1934 		icmph->icmph_checksum = 0xFFFF;
1935 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1936 		ipif_t	*ipif_chosen;
1937 		/*
1938 		 * Make it look like it was directed to us, so we don't look
1939 		 * like a fool with a broadcast or multicast source address.
1940 		 */
1941 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1942 		/*
1943 		 * Make sure that we haven't grabbed an interface that's DOWN.
1944 		 */
1945 		if (ipif != NULL) {
1946 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1947 			    ipha->ipha_src, zoneid);
1948 			if (ipif_chosen != NULL) {
1949 				ipif_refrele(ipif);
1950 				ipif = ipif_chosen;
1951 			}
1952 		}
1953 		if (ipif == NULL) {
1954 			ip0dbg(("icmp_inbound: "
1955 			    "No source for broadcast/multicast:\n"
1956 			    "\tsrc 0x%x dst 0x%x ill %p "
1957 			    "ipif_lcl_addr 0x%x\n",
1958 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1959 			    (void *)ill,
1960 			    ill->ill_ipif->ipif_lcl_addr));
1961 			freemsg(first_mp);
1962 			return;
1963 		}
1964 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1965 		ipha->ipha_dst = ipif->ipif_src_addr;
1966 		ipif_refrele(ipif);
1967 	}
1968 	/* Reset time to live. */
1969 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1970 	{
1971 		/* Swap source and destination addresses */
1972 		ipaddr_t tmp;
1973 
1974 		tmp = ipha->ipha_src;
1975 		ipha->ipha_src = ipha->ipha_dst;
1976 		ipha->ipha_dst = tmp;
1977 	}
1978 	ipha->ipha_ident = 0;
1979 	if (!IS_SIMPLE_IPH(ipha))
1980 		icmp_options_update(ipha);
1981 
1982 	/*
1983 	 * ICMP echo replies should go out on the same interface
1984 	 * the request came on as probes used by in.mpathd for detecting
1985 	 * NIC failures are ECHO packets. We turn-off load spreading
1986 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1987 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1988 	 * function. This is in turn handled by ip_wput and ip_newroute
1989 	 * to make sure that the packet goes out on the interface it came
1990 	 * in on. If we don't turnoff load spreading, the packets might get
1991 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1992 	 * to go out and in.mpathd would wrongly detect a failure or
1993 	 * mis-detect a NIC failure for link failure. As load spreading
1994 	 * can happen only if ill_group is not NULL, we do only for
1995 	 * that case and this does not affect the normal case.
1996 	 *
1997 	 * We turn off load spreading only on echo packets that came from
1998 	 * on-link hosts. If the interface route has been deleted, this will
1999 	 * not be enforced as we can't do much. For off-link hosts, as the
2000 	 * default routes in IPv4 does not typically have an ire_ipif
2001 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2002 	 * Moreover, expecting a default route through this interface may
2003 	 * not be correct. We use ipha_dst because of the swap above.
2004 	 */
2005 	onlink = B_FALSE;
2006 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2007 		/*
2008 		 * First, we need to make sure that it is not one of our
2009 		 * local addresses. If we set onlink when it is one of
2010 		 * our local addresses, we will end up creating IRE_CACHES
2011 		 * for one of our local addresses. Then, we will never
2012 		 * accept packets for them afterwards.
2013 		 */
2014 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2015 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2016 		if (src_ire == NULL) {
2017 			ipif = ipif_get_next_ipif(NULL, ill);
2018 			if (ipif == NULL) {
2019 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2020 				freemsg(mp);
2021 				return;
2022 			}
2023 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2024 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2025 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2026 			ipif_refrele(ipif);
2027 			if (src_ire != NULL) {
2028 				onlink = B_TRUE;
2029 				ire_refrele(src_ire);
2030 			}
2031 		} else {
2032 			ire_refrele(src_ire);
2033 		}
2034 	}
2035 	if (!mctl_present) {
2036 		/*
2037 		 * This packet should go out the same way as it
2038 		 * came in i.e in clear. To make sure that global
2039 		 * policy will not be applied to this in ip_wput_ire,
2040 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2041 		 */
2042 		ASSERT(first_mp == mp);
2043 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2044 		if (first_mp == NULL) {
2045 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2046 			freemsg(mp);
2047 			return;
2048 		}
2049 		ii = (ipsec_in_t *)first_mp->b_rptr;
2050 
2051 		/* This is not a secure packet */
2052 		ii->ipsec_in_secure = B_FALSE;
2053 		if (onlink) {
2054 			ii->ipsec_in_attach_if = B_TRUE;
2055 			ii->ipsec_in_ill_index =
2056 			    ill->ill_phyint->phyint_ifindex;
2057 			ii->ipsec_in_rill_index =
2058 			    recv_ill->ill_phyint->phyint_ifindex;
2059 		}
2060 		first_mp->b_cont = mp;
2061 	} else if (onlink) {
2062 		ii = (ipsec_in_t *)first_mp->b_rptr;
2063 		ii->ipsec_in_attach_if = B_TRUE;
2064 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2065 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2066 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2067 	} else {
2068 		ii = (ipsec_in_t *)first_mp->b_rptr;
2069 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2070 	}
2071 	ii->ipsec_in_zoneid = zoneid;
2072 	ASSERT(zoneid != ALL_ZONES);
2073 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2074 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2075 		return;
2076 	}
2077 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2078 	put(WR(q), first_mp);
2079 }
2080 
2081 static ipaddr_t
2082 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2083 {
2084 	conn_t *connp;
2085 	connf_t *connfp;
2086 	ipaddr_t nexthop_addr = INADDR_ANY;
2087 	int hdr_length = IPH_HDR_LENGTH(ipha);
2088 	uint16_t *up;
2089 	uint32_t ports;
2090 	ip_stack_t *ipst = ill->ill_ipst;
2091 
2092 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2093 	switch (ipha->ipha_protocol) {
2094 		case IPPROTO_TCP:
2095 		{
2096 			tcph_t *tcph;
2097 
2098 			/* do a reverse lookup */
2099 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2100 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2101 			    TCPS_LISTEN, ipst);
2102 			break;
2103 		}
2104 		case IPPROTO_UDP:
2105 		{
2106 			uint32_t dstport, srcport;
2107 
2108 			((uint16_t *)&ports)[0] = up[1];
2109 			((uint16_t *)&ports)[1] = up[0];
2110 
2111 			/* Extract ports in net byte order */
2112 			dstport = htons(ntohl(ports) & 0xFFFF);
2113 			srcport = htons(ntohl(ports) >> 16);
2114 
2115 			connfp = &ipst->ips_ipcl_udp_fanout[
2116 			    IPCL_UDP_HASH(dstport, ipst)];
2117 			mutex_enter(&connfp->connf_lock);
2118 			connp = connfp->connf_head;
2119 
2120 			/* do a reverse lookup */
2121 			while ((connp != NULL) &&
2122 			    (!IPCL_UDP_MATCH(connp, dstport,
2123 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2124 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2125 				connp = connp->conn_next;
2126 			}
2127 			if (connp != NULL)
2128 				CONN_INC_REF(connp);
2129 			mutex_exit(&connfp->connf_lock);
2130 			break;
2131 		}
2132 		case IPPROTO_SCTP:
2133 		{
2134 			in6_addr_t map_src, map_dst;
2135 
2136 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2137 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2138 			((uint16_t *)&ports)[0] = up[1];
2139 			((uint16_t *)&ports)[1] = up[0];
2140 
2141 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2142 			    zoneid, ipst->ips_netstack->netstack_sctp);
2143 			if (connp == NULL) {
2144 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2145 				    zoneid, ports, ipha, ipst);
2146 			} else {
2147 				CONN_INC_REF(connp);
2148 				SCTP_REFRELE(CONN2SCTP(connp));
2149 			}
2150 			break;
2151 		}
2152 		default:
2153 		{
2154 			ipha_t ripha;
2155 
2156 			ripha.ipha_src = ipha->ipha_dst;
2157 			ripha.ipha_dst = ipha->ipha_src;
2158 			ripha.ipha_protocol = ipha->ipha_protocol;
2159 
2160 			connfp = &ipst->ips_ipcl_proto_fanout[
2161 			    ipha->ipha_protocol];
2162 			mutex_enter(&connfp->connf_lock);
2163 			connp = connfp->connf_head;
2164 			for (connp = connfp->connf_head; connp != NULL;
2165 			    connp = connp->conn_next) {
2166 				if (IPCL_PROTO_MATCH(connp,
2167 				    ipha->ipha_protocol, &ripha, ill,
2168 				    0, zoneid)) {
2169 					CONN_INC_REF(connp);
2170 					break;
2171 				}
2172 			}
2173 			mutex_exit(&connfp->connf_lock);
2174 		}
2175 	}
2176 	if (connp != NULL) {
2177 		if (connp->conn_nexthop_set)
2178 			nexthop_addr = connp->conn_nexthop_v4;
2179 		CONN_DEC_REF(connp);
2180 	}
2181 	return (nexthop_addr);
2182 }
2183 
2184 /* Table from RFC 1191 */
2185 static int icmp_frag_size_table[] =
2186 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2187 
2188 /*
2189  * Process received ICMP Packet too big.
2190  * After updating any IRE it does the fanout to any matching transport streams.
2191  * Assumes the message has been pulled up till the IP header that caused
2192  * the error.
2193  *
2194  * Returns B_FALSE on failure and B_TRUE on success.
2195  */
2196 static boolean_t
2197 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2198     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2199     ip_stack_t *ipst)
2200 {
2201 	ire_t	*ire, *first_ire;
2202 	int	mtu;
2203 	int	hdr_length;
2204 	ipaddr_t nexthop_addr;
2205 
2206 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2207 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2208 	ASSERT(ill != NULL);
2209 
2210 	hdr_length = IPH_HDR_LENGTH(ipha);
2211 
2212 	/* Drop if the original packet contained a source route */
2213 	if (ip_source_route_included(ipha)) {
2214 		return (B_FALSE);
2215 	}
2216 	/*
2217 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2218 	 * header.
2219 	 */
2220 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2221 	    mp->b_wptr) {
2222 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2223 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2224 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2225 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2226 			return (B_FALSE);
2227 		}
2228 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2229 		ipha = (ipha_t *)&icmph[1];
2230 	}
2231 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2232 	if (nexthop_addr != INADDR_ANY) {
2233 		/* nexthop set */
2234 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2235 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2236 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2237 	} else {
2238 		/* nexthop not set */
2239 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2240 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2241 	}
2242 
2243 	if (!first_ire) {
2244 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2245 		    ntohl(ipha->ipha_dst)));
2246 		return (B_FALSE);
2247 	}
2248 	/* Check for MTU discovery advice as described in RFC 1191 */
2249 	mtu = ntohs(icmph->icmph_du_mtu);
2250 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2251 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2252 	    ire = ire->ire_next) {
2253 		/*
2254 		 * Look for the connection to which this ICMP message is
2255 		 * directed. If it has the IP_NEXTHOP option set, then the
2256 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2257 		 * option. Else the search is limited to regular IREs.
2258 		 */
2259 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2260 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2261 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2262 		    (nexthop_addr != INADDR_ANY)))
2263 			continue;
2264 
2265 		mutex_enter(&ire->ire_lock);
2266 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2267 			/* Reduce the IRE max frag value as advised. */
2268 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2269 			    mtu, ire->ire_max_frag));
2270 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2271 		} else {
2272 			uint32_t length;
2273 			int	i;
2274 
2275 			/*
2276 			 * Use the table from RFC 1191 to figure out
2277 			 * the next "plateau" based on the length in
2278 			 * the original IP packet.
2279 			 */
2280 			length = ntohs(ipha->ipha_length);
2281 			if (ire->ire_max_frag <= length &&
2282 			    ire->ire_max_frag >= length - hdr_length) {
2283 				/*
2284 				 * Handle broken BSD 4.2 systems that
2285 				 * return the wrong iph_length in ICMP
2286 				 * errors.
2287 				 */
2288 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2289 				    length, ire->ire_max_frag));
2290 				length -= hdr_length;
2291 			}
2292 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2293 				if (length > icmp_frag_size_table[i])
2294 					break;
2295 			}
2296 			if (i == A_CNT(icmp_frag_size_table)) {
2297 				/* Smaller than 68! */
2298 				ip1dbg(("Too big for packet size %d\n",
2299 				    length));
2300 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2301 				ire->ire_frag_flag = 0;
2302 			} else {
2303 				mtu = icmp_frag_size_table[i];
2304 				ip1dbg(("Calculated mtu %d, packet size %d, "
2305 				    "before %d", mtu, length,
2306 				    ire->ire_max_frag));
2307 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2308 				ip1dbg((", after %d\n", ire->ire_max_frag));
2309 			}
2310 			/* Record the new max frag size for the ULP. */
2311 			icmph->icmph_du_zero = 0;
2312 			icmph->icmph_du_mtu =
2313 			    htons((uint16_t)ire->ire_max_frag);
2314 		}
2315 		mutex_exit(&ire->ire_lock);
2316 	}
2317 	rw_exit(&first_ire->ire_bucket->irb_lock);
2318 	ire_refrele(first_ire);
2319 	return (B_TRUE);
2320 }
2321 
2322 /*
2323  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2324  * calls this function.
2325  */
2326 static mblk_t *
2327 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2328 {
2329 	ipha_t *ipha;
2330 	icmph_t *icmph;
2331 	ipha_t *in_ipha;
2332 	int length;
2333 
2334 	ASSERT(mp->b_datap->db_type == M_DATA);
2335 
2336 	/*
2337 	 * For Self-encapsulated packets, we added an extra IP header
2338 	 * without the options. Inner IP header is the one from which
2339 	 * the outer IP header was formed. Thus, we need to remove the
2340 	 * outer IP header. To do this, we pullup the whole message
2341 	 * and overlay whatever follows the outer IP header over the
2342 	 * outer IP header.
2343 	 */
2344 
2345 	if (!pullupmsg(mp, -1))
2346 		return (NULL);
2347 
2348 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2349 	ipha = (ipha_t *)&icmph[1];
2350 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2351 
2352 	/*
2353 	 * The length that we want to overlay is following the inner
2354 	 * IP header. Subtracting the IP header + icmp header + outer
2355 	 * IP header's length should give us the length that we want to
2356 	 * overlay.
2357 	 */
2358 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2359 	    hdr_length;
2360 	/*
2361 	 * Overlay whatever follows the inner header over the
2362 	 * outer header.
2363 	 */
2364 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2365 
2366 	/* Set the wptr to account for the outer header */
2367 	mp->b_wptr -= hdr_length;
2368 	return (mp);
2369 }
2370 
2371 /*
2372  * Try to pass the ICMP message upstream in case the ULP cares.
2373  *
2374  * If the packet that caused the ICMP error is secure, we send
2375  * it to AH/ESP to make sure that the attached packet has a
2376  * valid association. ipha in the code below points to the
2377  * IP header of the packet that caused the error.
2378  *
2379  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2380  * in the context of IPSEC. Normally we tell the upper layer
2381  * whenever we send the ire (including ip_bind), the IPSEC header
2382  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2383  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2384  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2385  * same thing. As TCP has the IPSEC options size that needs to be
2386  * adjusted, we just pass the MTU unchanged.
2387  *
2388  * IFN could have been generated locally or by some router.
2389  *
2390  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2391  *	    This happens because IP adjusted its value of MTU on an
2392  *	    earlier IFN message and could not tell the upper layer,
2393  *	    the new adjusted value of MTU e.g. Packet was encrypted
2394  *	    or there was not enough information to fanout to upper
2395  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2396  *	    generates the IFN, where IPSEC processing has *not* been
2397  *	    done.
2398  *
2399  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2400  *	    could have generated this. This happens because ire_max_frag
2401  *	    value in IP was set to a new value, while the IPSEC processing
2402  *	    was being done and after we made the fragmentation check in
2403  *	    ip_wput_ire. Thus on return from IPSEC processing,
2404  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2405  *	    and generates the IFN. As IPSEC processing is over, we fanout
2406  *	    to AH/ESP to remove the header.
2407  *
2408  *	    In both these cases, ipsec_in_loopback will be set indicating
2409  *	    that IFN was generated locally.
2410  *
2411  * ROUTER : IFN could be secure or non-secure.
2412  *
2413  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2414  *	      packet in error has AH/ESP headers to validate the AH/ESP
2415  *	      headers. AH/ESP will verify whether there is a valid SA or
2416  *	      not and send it back. We will fanout again if we have more
2417  *	      data in the packet.
2418  *
2419  *	      If the packet in error does not have AH/ESP, we handle it
2420  *	      like any other case.
2421  *
2422  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2423  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2424  *	      for validation. AH/ESP will verify whether there is a
2425  *	      valid SA or not and send it back. We will fanout again if
2426  *	      we have more data in the packet.
2427  *
2428  *	      If the packet in error does not have AH/ESP, we handle it
2429  *	      like any other case.
2430  */
2431 static void
2432 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2433     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2434     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2435     zoneid_t zoneid)
2436 {
2437 	uint16_t *up;	/* Pointer to ports in ULP header */
2438 	uint32_t ports;	/* reversed ports for fanout */
2439 	ipha_t ripha;	/* With reversed addresses */
2440 	mblk_t *first_mp;
2441 	ipsec_in_t *ii;
2442 	tcph_t	*tcph;
2443 	conn_t	*connp;
2444 	ip_stack_t *ipst;
2445 
2446 	ASSERT(ill != NULL);
2447 
2448 	ASSERT(recv_ill != NULL);
2449 	ipst = recv_ill->ill_ipst;
2450 
2451 	first_mp = mp;
2452 	if (mctl_present) {
2453 		mp = first_mp->b_cont;
2454 		ASSERT(mp != NULL);
2455 
2456 		ii = (ipsec_in_t *)first_mp->b_rptr;
2457 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2458 	} else {
2459 		ii = NULL;
2460 	}
2461 
2462 	switch (ipha->ipha_protocol) {
2463 	case IPPROTO_UDP:
2464 		/*
2465 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2466 		 * transport header.
2467 		 */
2468 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2469 		    mp->b_wptr) {
2470 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2471 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2472 				goto discard_pkt;
2473 			}
2474 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2475 			ipha = (ipha_t *)&icmph[1];
2476 		}
2477 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2478 
2479 		/*
2480 		 * Attempt to find a client stream based on port.
2481 		 * Note that we do a reverse lookup since the header is
2482 		 * in the form we sent it out.
2483 		 * The ripha header is only used for the IP_UDP_MATCH and we
2484 		 * only set the src and dst addresses and protocol.
2485 		 */
2486 		ripha.ipha_src = ipha->ipha_dst;
2487 		ripha.ipha_dst = ipha->ipha_src;
2488 		ripha.ipha_protocol = ipha->ipha_protocol;
2489 		((uint16_t *)&ports)[0] = up[1];
2490 		((uint16_t *)&ports)[1] = up[0];
2491 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2492 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2493 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2494 		    icmph->icmph_type, icmph->icmph_code));
2495 
2496 		/* Have to change db_type after any pullupmsg */
2497 		DB_TYPE(mp) = M_CTL;
2498 
2499 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2500 		    mctl_present, ip_policy, recv_ill, zoneid);
2501 		return;
2502 
2503 	case IPPROTO_TCP:
2504 		/*
2505 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2506 		 * transport header.
2507 		 */
2508 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2509 		    mp->b_wptr) {
2510 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2511 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2512 				goto discard_pkt;
2513 			}
2514 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2515 			ipha = (ipha_t *)&icmph[1];
2516 		}
2517 		/*
2518 		 * Find a TCP client stream for this packet.
2519 		 * Note that we do a reverse lookup since the header is
2520 		 * in the form we sent it out.
2521 		 */
2522 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2523 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2524 		    ipst);
2525 		if (connp == NULL)
2526 			goto discard_pkt;
2527 
2528 		/* Have to change db_type after any pullupmsg */
2529 		DB_TYPE(mp) = M_CTL;
2530 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2531 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2532 		return;
2533 
2534 	case IPPROTO_SCTP:
2535 		/*
2536 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2537 		 * transport header.
2538 		 */
2539 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2540 		    mp->b_wptr) {
2541 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2542 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2543 				goto discard_pkt;
2544 			}
2545 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2546 			ipha = (ipha_t *)&icmph[1];
2547 		}
2548 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2549 		/*
2550 		 * Find a SCTP client stream for this packet.
2551 		 * Note that we do a reverse lookup since the header is
2552 		 * in the form we sent it out.
2553 		 * The ripha header is only used for the matching and we
2554 		 * only set the src and dst addresses, protocol, and version.
2555 		 */
2556 		ripha.ipha_src = ipha->ipha_dst;
2557 		ripha.ipha_dst = ipha->ipha_src;
2558 		ripha.ipha_protocol = ipha->ipha_protocol;
2559 		ripha.ipha_version_and_hdr_length =
2560 		    ipha->ipha_version_and_hdr_length;
2561 		((uint16_t *)&ports)[0] = up[1];
2562 		((uint16_t *)&ports)[1] = up[0];
2563 
2564 		/* Have to change db_type after any pullupmsg */
2565 		DB_TYPE(mp) = M_CTL;
2566 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2567 		    mctl_present, ip_policy, zoneid);
2568 		return;
2569 
2570 	case IPPROTO_ESP:
2571 	case IPPROTO_AH: {
2572 		int ipsec_rc;
2573 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2574 
2575 		/*
2576 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2577 		 * We will re-use the IPSEC_IN if it is already present as
2578 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2579 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2580 		 * one and attach it in the front.
2581 		 */
2582 		if (ii != NULL) {
2583 			/*
2584 			 * ip_fanout_proto_again converts the ICMP errors
2585 			 * that come back from AH/ESP to M_DATA so that
2586 			 * if it is non-AH/ESP and we do a pullupmsg in
2587 			 * this function, it would work. Convert it back
2588 			 * to M_CTL before we send up as this is a ICMP
2589 			 * error. This could have been generated locally or
2590 			 * by some router. Validate the inner IPSEC
2591 			 * headers.
2592 			 *
2593 			 * NOTE : ill_index is used by ip_fanout_proto_again
2594 			 * to locate the ill.
2595 			 */
2596 			ASSERT(ill != NULL);
2597 			ii->ipsec_in_ill_index =
2598 			    ill->ill_phyint->phyint_ifindex;
2599 			ii->ipsec_in_rill_index =
2600 			    recv_ill->ill_phyint->phyint_ifindex;
2601 			DB_TYPE(first_mp->b_cont) = M_CTL;
2602 		} else {
2603 			/*
2604 			 * IPSEC_IN is not present. We attach a ipsec_in
2605 			 * message and send up to IPSEC for validating
2606 			 * and removing the IPSEC headers. Clear
2607 			 * ipsec_in_secure so that when we return
2608 			 * from IPSEC, we don't mistakenly think that this
2609 			 * is a secure packet came from the network.
2610 			 *
2611 			 * NOTE : ill_index is used by ip_fanout_proto_again
2612 			 * to locate the ill.
2613 			 */
2614 			ASSERT(first_mp == mp);
2615 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2616 			if (first_mp == NULL) {
2617 				freemsg(mp);
2618 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2619 				return;
2620 			}
2621 			ii = (ipsec_in_t *)first_mp->b_rptr;
2622 
2623 			/* This is not a secure packet */
2624 			ii->ipsec_in_secure = B_FALSE;
2625 			first_mp->b_cont = mp;
2626 			DB_TYPE(mp) = M_CTL;
2627 			ASSERT(ill != NULL);
2628 			ii->ipsec_in_ill_index =
2629 			    ill->ill_phyint->phyint_ifindex;
2630 			ii->ipsec_in_rill_index =
2631 			    recv_ill->ill_phyint->phyint_ifindex;
2632 		}
2633 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2634 
2635 		if (!ipsec_loaded(ipss)) {
2636 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2637 			return;
2638 		}
2639 
2640 		if (ipha->ipha_protocol == IPPROTO_ESP)
2641 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2642 		else
2643 			ipsec_rc = ipsecah_icmp_error(first_mp);
2644 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2645 			return;
2646 
2647 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2648 		return;
2649 	}
2650 	default:
2651 		/*
2652 		 * The ripha header is only used for the lookup and we
2653 		 * only set the src and dst addresses and protocol.
2654 		 */
2655 		ripha.ipha_src = ipha->ipha_dst;
2656 		ripha.ipha_dst = ipha->ipha_src;
2657 		ripha.ipha_protocol = ipha->ipha_protocol;
2658 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2659 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2660 		    ntohl(ipha->ipha_dst),
2661 		    icmph->icmph_type, icmph->icmph_code));
2662 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2663 			ipha_t *in_ipha;
2664 
2665 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2666 			    mp->b_wptr) {
2667 				if (!pullupmsg(mp, (uchar_t *)ipha +
2668 				    hdr_length + sizeof (ipha_t) -
2669 				    mp->b_rptr)) {
2670 					goto discard_pkt;
2671 				}
2672 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2673 				ipha = (ipha_t *)&icmph[1];
2674 			}
2675 			/*
2676 			 * Caller has verified that length has to be
2677 			 * at least the size of IP header.
2678 			 */
2679 			ASSERT(hdr_length >= sizeof (ipha_t));
2680 			/*
2681 			 * Check the sanity of the inner IP header like
2682 			 * we did for the outer header.
2683 			 */
2684 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2685 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2686 				goto discard_pkt;
2687 			}
2688 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2689 				goto discard_pkt;
2690 			}
2691 			/* Check for Self-encapsulated tunnels */
2692 			if (in_ipha->ipha_src == ipha->ipha_src &&
2693 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2694 
2695 				mp = icmp_inbound_self_encap_error(mp,
2696 				    iph_hdr_length, hdr_length);
2697 				if (mp == NULL)
2698 					goto discard_pkt;
2699 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2700 				ipha = (ipha_t *)&icmph[1];
2701 				hdr_length = IPH_HDR_LENGTH(ipha);
2702 				/*
2703 				 * The packet in error is self-encapsualted.
2704 				 * And we are finding it further encapsulated
2705 				 * which we could not have possibly generated.
2706 				 */
2707 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2708 					goto discard_pkt;
2709 				}
2710 				icmp_inbound_error_fanout(q, ill, first_mp,
2711 				    icmph, ipha, iph_hdr_length, hdr_length,
2712 				    mctl_present, ip_policy, recv_ill, zoneid);
2713 				return;
2714 			}
2715 		}
2716 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2717 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2718 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2719 		    ii != NULL &&
2720 		    ii->ipsec_in_loopback &&
2721 		    ii->ipsec_in_secure) {
2722 			/*
2723 			 * For IP tunnels that get a looped-back
2724 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2725 			 * reported new MTU to take into account the IPsec
2726 			 * headers protecting this configured tunnel.
2727 			 *
2728 			 * This allows the tunnel module (tun.c) to blindly
2729 			 * accept the MTU reported in an ICMP "too big"
2730 			 * message.
2731 			 *
2732 			 * Non-looped back ICMP messages will just be
2733 			 * handled by the security protocols (if needed),
2734 			 * and the first subsequent packet will hit this
2735 			 * path.
2736 			 */
2737 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2738 			    ipsec_in_extra_length(first_mp));
2739 		}
2740 		/* Have to change db_type after any pullupmsg */
2741 		DB_TYPE(mp) = M_CTL;
2742 
2743 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2744 		    ip_policy, recv_ill, zoneid);
2745 		return;
2746 	}
2747 	/* NOTREACHED */
2748 discard_pkt:
2749 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2750 drop_pkt:;
2751 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2752 	freemsg(first_mp);
2753 }
2754 
2755 /*
2756  * Common IP options parser.
2757  *
2758  * Setup routine: fill in *optp with options-parsing state, then
2759  * tail-call ipoptp_next to return the first option.
2760  */
2761 uint8_t
2762 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2763 {
2764 	uint32_t totallen; /* total length of all options */
2765 
2766 	totallen = ipha->ipha_version_and_hdr_length -
2767 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2768 	totallen <<= 2;
2769 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2770 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2771 	optp->ipoptp_flags = 0;
2772 	return (ipoptp_next(optp));
2773 }
2774 
2775 /*
2776  * Common IP options parser: extract next option.
2777  */
2778 uint8_t
2779 ipoptp_next(ipoptp_t *optp)
2780 {
2781 	uint8_t *end = optp->ipoptp_end;
2782 	uint8_t *cur = optp->ipoptp_next;
2783 	uint8_t opt, len, pointer;
2784 
2785 	/*
2786 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2787 	 * has been corrupted.
2788 	 */
2789 	ASSERT(cur <= end);
2790 
2791 	if (cur == end)
2792 		return (IPOPT_EOL);
2793 
2794 	opt = cur[IPOPT_OPTVAL];
2795 
2796 	/*
2797 	 * Skip any NOP options.
2798 	 */
2799 	while (opt == IPOPT_NOP) {
2800 		cur++;
2801 		if (cur == end)
2802 			return (IPOPT_EOL);
2803 		opt = cur[IPOPT_OPTVAL];
2804 	}
2805 
2806 	if (opt == IPOPT_EOL)
2807 		return (IPOPT_EOL);
2808 
2809 	/*
2810 	 * Option requiring a length.
2811 	 */
2812 	if ((cur + 1) >= end) {
2813 		optp->ipoptp_flags |= IPOPTP_ERROR;
2814 		return (IPOPT_EOL);
2815 	}
2816 	len = cur[IPOPT_OLEN];
2817 	if (len < 2) {
2818 		optp->ipoptp_flags |= IPOPTP_ERROR;
2819 		return (IPOPT_EOL);
2820 	}
2821 	optp->ipoptp_cur = cur;
2822 	optp->ipoptp_len = len;
2823 	optp->ipoptp_next = cur + len;
2824 	if (cur + len > end) {
2825 		optp->ipoptp_flags |= IPOPTP_ERROR;
2826 		return (IPOPT_EOL);
2827 	}
2828 
2829 	/*
2830 	 * For the options which require a pointer field, make sure
2831 	 * its there, and make sure it points to either something
2832 	 * inside this option, or the end of the option.
2833 	 */
2834 	switch (opt) {
2835 	case IPOPT_RR:
2836 	case IPOPT_TS:
2837 	case IPOPT_LSRR:
2838 	case IPOPT_SSRR:
2839 		if (len <= IPOPT_OFFSET) {
2840 			optp->ipoptp_flags |= IPOPTP_ERROR;
2841 			return (opt);
2842 		}
2843 		pointer = cur[IPOPT_OFFSET];
2844 		if (pointer - 1 > len) {
2845 			optp->ipoptp_flags |= IPOPTP_ERROR;
2846 			return (opt);
2847 		}
2848 		break;
2849 	}
2850 
2851 	/*
2852 	 * Sanity check the pointer field based on the type of the
2853 	 * option.
2854 	 */
2855 	switch (opt) {
2856 	case IPOPT_RR:
2857 	case IPOPT_SSRR:
2858 	case IPOPT_LSRR:
2859 		if (pointer < IPOPT_MINOFF_SR)
2860 			optp->ipoptp_flags |= IPOPTP_ERROR;
2861 		break;
2862 	case IPOPT_TS:
2863 		if (pointer < IPOPT_MINOFF_IT)
2864 			optp->ipoptp_flags |= IPOPTP_ERROR;
2865 		/*
2866 		 * Note that the Internet Timestamp option also
2867 		 * contains two four bit fields (the Overflow field,
2868 		 * and the Flag field), which follow the pointer
2869 		 * field.  We don't need to check that these fields
2870 		 * fall within the length of the option because this
2871 		 * was implicitely done above.  We've checked that the
2872 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2873 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2874 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2875 		 */
2876 		ASSERT(len > IPOPT_POS_OV_FLG);
2877 		break;
2878 	}
2879 
2880 	return (opt);
2881 }
2882 
2883 /*
2884  * Use the outgoing IP header to create an IP_OPTIONS option the way
2885  * it was passed down from the application.
2886  */
2887 int
2888 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2889 {
2890 	ipoptp_t	opts;
2891 	const uchar_t	*opt;
2892 	uint8_t		optval;
2893 	uint8_t		optlen;
2894 	uint32_t	len = 0;
2895 	uchar_t	*buf1 = buf;
2896 
2897 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2898 	len += IP_ADDR_LEN;
2899 	bzero(buf1, IP_ADDR_LEN);
2900 
2901 	/*
2902 	 * OK to cast away const here, as we don't store through the returned
2903 	 * opts.ipoptp_cur pointer.
2904 	 */
2905 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2906 	    optval != IPOPT_EOL;
2907 	    optval = ipoptp_next(&opts)) {
2908 		int	off;
2909 
2910 		opt = opts.ipoptp_cur;
2911 		optlen = opts.ipoptp_len;
2912 		switch (optval) {
2913 		case IPOPT_SSRR:
2914 		case IPOPT_LSRR:
2915 
2916 			/*
2917 			 * Insert ipha_dst as the first entry in the source
2918 			 * route and move down the entries on step.
2919 			 * The last entry gets placed at buf1.
2920 			 */
2921 			buf[IPOPT_OPTVAL] = optval;
2922 			buf[IPOPT_OLEN] = optlen;
2923 			buf[IPOPT_OFFSET] = optlen;
2924 
2925 			off = optlen - IP_ADDR_LEN;
2926 			if (off < 0) {
2927 				/* No entries in source route */
2928 				break;
2929 			}
2930 			/* Last entry in source route */
2931 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2932 			off -= IP_ADDR_LEN;
2933 
2934 			while (off > 0) {
2935 				bcopy(opt + off,
2936 				    buf + off + IP_ADDR_LEN,
2937 				    IP_ADDR_LEN);
2938 				off -= IP_ADDR_LEN;
2939 			}
2940 			/* ipha_dst into first slot */
2941 			bcopy(&ipha->ipha_dst,
2942 			    buf + off + IP_ADDR_LEN,
2943 			    IP_ADDR_LEN);
2944 			buf += optlen;
2945 			len += optlen;
2946 			break;
2947 
2948 		case IPOPT_COMSEC:
2949 		case IPOPT_SECURITY:
2950 			/* if passing up a label is not ok, then remove */
2951 			if (is_system_labeled())
2952 				break;
2953 			/* FALLTHROUGH */
2954 		default:
2955 			bcopy(opt, buf, optlen);
2956 			buf += optlen;
2957 			len += optlen;
2958 			break;
2959 		}
2960 	}
2961 done:
2962 	/* Pad the resulting options */
2963 	while (len & 0x3) {
2964 		*buf++ = IPOPT_EOL;
2965 		len++;
2966 	}
2967 	return (len);
2968 }
2969 
2970 /*
2971  * Update any record route or timestamp options to include this host.
2972  * Reverse any source route option.
2973  * This routine assumes that the options are well formed i.e. that they
2974  * have already been checked.
2975  */
2976 static void
2977 icmp_options_update(ipha_t *ipha)
2978 {
2979 	ipoptp_t	opts;
2980 	uchar_t		*opt;
2981 	uint8_t		optval;
2982 	ipaddr_t	src;		/* Our local address */
2983 	ipaddr_t	dst;
2984 
2985 	ip2dbg(("icmp_options_update\n"));
2986 	src = ipha->ipha_src;
2987 	dst = ipha->ipha_dst;
2988 
2989 	for (optval = ipoptp_first(&opts, ipha);
2990 	    optval != IPOPT_EOL;
2991 	    optval = ipoptp_next(&opts)) {
2992 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2993 		opt = opts.ipoptp_cur;
2994 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2995 		    optval, opts.ipoptp_len));
2996 		switch (optval) {
2997 			int off1, off2;
2998 		case IPOPT_SSRR:
2999 		case IPOPT_LSRR:
3000 			/*
3001 			 * Reverse the source route.  The first entry
3002 			 * should be the next to last one in the current
3003 			 * source route (the last entry is our address).
3004 			 * The last entry should be the final destination.
3005 			 */
3006 			off1 = IPOPT_MINOFF_SR - 1;
3007 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3008 			if (off2 < 0) {
3009 				/* No entries in source route */
3010 				ip1dbg((
3011 				    "icmp_options_update: bad src route\n"));
3012 				break;
3013 			}
3014 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3015 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3016 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3017 			off2 -= IP_ADDR_LEN;
3018 
3019 			while (off1 < off2) {
3020 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3021 				bcopy((char *)opt + off2, (char *)opt + off1,
3022 				    IP_ADDR_LEN);
3023 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3024 				off1 += IP_ADDR_LEN;
3025 				off2 -= IP_ADDR_LEN;
3026 			}
3027 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3028 			break;
3029 		}
3030 	}
3031 }
3032 
3033 /*
3034  * Process received ICMP Redirect messages.
3035  */
3036 static void
3037 icmp_redirect(ill_t *ill, mblk_t *mp)
3038 {
3039 	ipha_t	*ipha;
3040 	int	iph_hdr_length;
3041 	icmph_t	*icmph;
3042 	ipha_t	*ipha_err;
3043 	ire_t	*ire;
3044 	ire_t	*prev_ire;
3045 	ire_t	*save_ire;
3046 	ipaddr_t  src, dst, gateway;
3047 	iulp_t	ulp_info = { 0 };
3048 	int	error;
3049 	ip_stack_t *ipst;
3050 
3051 	ASSERT(ill != NULL);
3052 	ipst = ill->ill_ipst;
3053 
3054 	ipha = (ipha_t *)mp->b_rptr;
3055 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3056 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3057 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3058 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3059 		freemsg(mp);
3060 		return;
3061 	}
3062 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3063 	ipha_err = (ipha_t *)&icmph[1];
3064 	src = ipha->ipha_src;
3065 	dst = ipha_err->ipha_dst;
3066 	gateway = icmph->icmph_rd_gateway;
3067 	/* Make sure the new gateway is reachable somehow. */
3068 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3069 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3070 	/*
3071 	 * Make sure we had a route for the dest in question and that
3072 	 * that route was pointing to the old gateway (the source of the
3073 	 * redirect packet.)
3074 	 */
3075 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3076 	    NULL, MATCH_IRE_GW, ipst);
3077 	/*
3078 	 * Check that
3079 	 *	the redirect was not from ourselves
3080 	 *	the new gateway and the old gateway are directly reachable
3081 	 */
3082 	if (!prev_ire ||
3083 	    !ire ||
3084 	    ire->ire_type == IRE_LOCAL) {
3085 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3086 		freemsg(mp);
3087 		if (ire != NULL)
3088 			ire_refrele(ire);
3089 		if (prev_ire != NULL)
3090 			ire_refrele(prev_ire);
3091 		return;
3092 	}
3093 
3094 	/*
3095 	 * Should we use the old ULP info to create the new gateway?  From
3096 	 * a user's perspective, we should inherit the info so that it
3097 	 * is a "smooth" transition.  If we do not do that, then new
3098 	 * connections going thru the new gateway will have no route metrics,
3099 	 * which is counter-intuitive to user.  From a network point of
3100 	 * view, this may or may not make sense even though the new gateway
3101 	 * is still directly connected to us so the route metrics should not
3102 	 * change much.
3103 	 *
3104 	 * But if the old ire_uinfo is not initialized, we do another
3105 	 * recursive lookup on the dest using the new gateway.  There may
3106 	 * be a route to that.  If so, use it to initialize the redirect
3107 	 * route.
3108 	 */
3109 	if (prev_ire->ire_uinfo.iulp_set) {
3110 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3111 	} else {
3112 		ire_t *tmp_ire;
3113 		ire_t *sire;
3114 
3115 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3116 		    ALL_ZONES, 0, NULL,
3117 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3118 		    ipst);
3119 		if (sire != NULL) {
3120 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3121 			/*
3122 			 * If sire != NULL, ire_ftable_lookup() should not
3123 			 * return a NULL value.
3124 			 */
3125 			ASSERT(tmp_ire != NULL);
3126 			ire_refrele(tmp_ire);
3127 			ire_refrele(sire);
3128 		} else if (tmp_ire != NULL) {
3129 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3130 			    sizeof (iulp_t));
3131 			ire_refrele(tmp_ire);
3132 		}
3133 	}
3134 	if (prev_ire->ire_type == IRE_CACHE)
3135 		ire_delete(prev_ire);
3136 	ire_refrele(prev_ire);
3137 	/*
3138 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3139 	 * require TOS routing
3140 	 */
3141 	switch (icmph->icmph_code) {
3142 	case 0:
3143 	case 1:
3144 		/* TODO: TOS specificity for cases 2 and 3 */
3145 	case 2:
3146 	case 3:
3147 		break;
3148 	default:
3149 		freemsg(mp);
3150 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3151 		ire_refrele(ire);
3152 		return;
3153 	}
3154 	/*
3155 	 * Create a Route Association.  This will allow us to remember that
3156 	 * someone we believe told us to use the particular gateway.
3157 	 */
3158 	save_ire = ire;
3159 	ire = ire_create(
3160 		(uchar_t *)&dst,			/* dest addr */
3161 		(uchar_t *)&ip_g_all_ones,		/* mask */
3162 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3163 		(uchar_t *)&gateway,			/* gateway addr */
3164 		NULL,					/* no in_srcaddr */
3165 		&save_ire->ire_max_frag,		/* max frag */
3166 		NULL,					/* Fast Path header */
3167 		NULL,					/* no rfq */
3168 		NULL,					/* no stq */
3169 		IRE_HOST,
3170 		NULL,
3171 		NULL,
3172 		NULL,
3173 		0,
3174 		0,
3175 		0,
3176 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3177 		&ulp_info,
3178 		NULL,
3179 		NULL,
3180 		ipst);
3181 
3182 	if (ire == NULL) {
3183 		freemsg(mp);
3184 		ire_refrele(save_ire);
3185 		return;
3186 	}
3187 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3188 	ire_refrele(save_ire);
3189 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3190 
3191 	if (error == 0) {
3192 		ire_refrele(ire);		/* Held in ire_add_v4 */
3193 		/* tell routing sockets that we received a redirect */
3194 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3195 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3196 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3197 	}
3198 
3199 	/*
3200 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3201 	 * This together with the added IRE has the effect of
3202 	 * modifying an existing redirect.
3203 	 */
3204 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3205 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3206 	if (prev_ire != NULL) {
3207 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3208 			ire_delete(prev_ire);
3209 		ire_refrele(prev_ire);
3210 	}
3211 
3212 	freemsg(mp);
3213 }
3214 
3215 /*
3216  * Generate an ICMP parameter problem message.
3217  */
3218 static void
3219 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3220 	ip_stack_t *ipst)
3221 {
3222 	icmph_t	icmph;
3223 	boolean_t mctl_present;
3224 	mblk_t *first_mp;
3225 
3226 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3227 
3228 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3229 		if (mctl_present)
3230 			freeb(first_mp);
3231 		return;
3232 	}
3233 
3234 	bzero(&icmph, sizeof (icmph_t));
3235 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3236 	icmph.icmph_pp_ptr = ptr;
3237 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3238 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3239 	    ipst);
3240 }
3241 
3242 /*
3243  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3244  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3245  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3246  * an icmp error packet can be sent.
3247  * Assigns an appropriate source address to the packet. If ipha_dst is
3248  * one of our addresses use it for source. Otherwise pick a source based
3249  * on a route lookup back to ipha_src.
3250  * Note that ipha_src must be set here since the
3251  * packet is likely to arrive on an ill queue in ip_wput() which will
3252  * not set a source address.
3253  */
3254 static void
3255 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3256     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3257 {
3258 	ipaddr_t dst;
3259 	icmph_t	*icmph;
3260 	ipha_t	*ipha;
3261 	uint_t	len_needed;
3262 	size_t	msg_len;
3263 	mblk_t	*mp1;
3264 	ipaddr_t src;
3265 	ire_t	*ire;
3266 	mblk_t *ipsec_mp;
3267 	ipsec_out_t	*io = NULL;
3268 	boolean_t xmit_if_on = B_FALSE;
3269 
3270 	if (mctl_present) {
3271 		/*
3272 		 * If it is :
3273 		 *
3274 		 * 1) a IPSEC_OUT, then this is caused by outbound
3275 		 *    datagram originating on this host. IPSEC processing
3276 		 *    may or may not have been done. Refer to comments above
3277 		 *    icmp_inbound_error_fanout for details.
3278 		 *
3279 		 * 2) a IPSEC_IN if we are generating a icmp_message
3280 		 *    for an incoming datagram destined for us i.e called
3281 		 *    from ip_fanout_send_icmp.
3282 		 */
3283 		ipsec_info_t *in;
3284 		ipsec_mp = mp;
3285 		mp = ipsec_mp->b_cont;
3286 
3287 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3288 		ipha = (ipha_t *)mp->b_rptr;
3289 
3290 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3291 		    in->ipsec_info_type == IPSEC_IN);
3292 
3293 		if (in->ipsec_info_type == IPSEC_IN) {
3294 			/*
3295 			 * Convert the IPSEC_IN to IPSEC_OUT.
3296 			 */
3297 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3298 				BUMP_MIB(&ipst->ips_ip_mib,
3299 				    ipIfStatsOutDiscards);
3300 				return;
3301 			}
3302 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3303 		} else {
3304 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3305 			io = (ipsec_out_t *)in;
3306 			if (io->ipsec_out_xmit_if)
3307 				xmit_if_on = B_TRUE;
3308 			/*
3309 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3310 			 * ire lookup.
3311 			 */
3312 			io->ipsec_out_proc_begin = B_FALSE;
3313 		}
3314 		ASSERT(zoneid == io->ipsec_out_zoneid);
3315 		ASSERT(zoneid != ALL_ZONES);
3316 	} else {
3317 		/*
3318 		 * This is in clear. The icmp message we are building
3319 		 * here should go out in clear.
3320 		 *
3321 		 * Pardon the convolution of it all, but it's easier to
3322 		 * allocate a "use cleartext" IPSEC_IN message and convert
3323 		 * it than it is to allocate a new one.
3324 		 */
3325 		ipsec_in_t *ii;
3326 		ASSERT(DB_TYPE(mp) == M_DATA);
3327 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3328 		if (ipsec_mp == NULL) {
3329 			freemsg(mp);
3330 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3331 			return;
3332 		}
3333 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3334 
3335 		/* This is not a secure packet */
3336 		ii->ipsec_in_secure = B_FALSE;
3337 		/*
3338 		 * For trusted extensions using a shared IP address we can
3339 		 * send using any zoneid.
3340 		 */
3341 		if (zoneid == ALL_ZONES)
3342 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3343 		else
3344 			ii->ipsec_in_zoneid = zoneid;
3345 		ipsec_mp->b_cont = mp;
3346 		ipha = (ipha_t *)mp->b_rptr;
3347 		/*
3348 		 * Convert the IPSEC_IN to IPSEC_OUT.
3349 		 */
3350 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3351 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3352 			return;
3353 		}
3354 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3355 	}
3356 
3357 	/* Remember our eventual destination */
3358 	dst = ipha->ipha_src;
3359 
3360 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3361 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3362 	if (ire != NULL &&
3363 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3364 		src = ipha->ipha_dst;
3365 	} else if (!xmit_if_on) {
3366 		if (ire != NULL)
3367 			ire_refrele(ire);
3368 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3369 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3370 		    ipst);
3371 		if (ire == NULL) {
3372 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3373 			freemsg(ipsec_mp);
3374 			return;
3375 		}
3376 		src = ire->ire_src_addr;
3377 	} else {
3378 		ipif_t	*ipif = NULL;
3379 		ill_t	*ill;
3380 		/*
3381 		 * This must be an ICMP error coming from
3382 		 * ip_mrtun_forward(). The src addr should
3383 		 * be equal to the IP-addr of the outgoing
3384 		 * interface.
3385 		 */
3386 		if (io == NULL) {
3387 			/* This is not a IPSEC_OUT type control msg */
3388 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3389 			freemsg(ipsec_mp);
3390 			return;
3391 		}
3392 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3393 		    NULL, NULL, NULL, NULL, ipst);
3394 		if (ill != NULL) {
3395 			ipif = ipif_get_next_ipif(NULL, ill);
3396 			ill_refrele(ill);
3397 		}
3398 		if (ipif == NULL) {
3399 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3400 			freemsg(ipsec_mp);
3401 			return;
3402 		}
3403 		src = ipif->ipif_src_addr;
3404 		ipif_refrele(ipif);
3405 	}
3406 
3407 	if (ire != NULL)
3408 		ire_refrele(ire);
3409 
3410 	/*
3411 	 * Check if we can send back more then 8 bytes in addition
3412 	 * to the IP header. We will include as much as 64 bytes.
3413 	 */
3414 	len_needed = IPH_HDR_LENGTH(ipha);
3415 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3416 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3417 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3418 	}
3419 	len_needed += ipst->ips_ip_icmp_return;
3420 	msg_len = msgdsize(mp);
3421 	if (msg_len > len_needed) {
3422 		(void) adjmsg(mp, len_needed - msg_len);
3423 		msg_len = len_needed;
3424 	}
3425 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3426 	if (mp1 == NULL) {
3427 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3428 		freemsg(ipsec_mp);
3429 		return;
3430 	}
3431 	/*
3432 	 * On an unlabeled system, dblks don't necessarily have creds.
3433 	 */
3434 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3435 	if (DB_CRED(mp) != NULL)
3436 		mblk_setcred(mp1, DB_CRED(mp));
3437 	mp1->b_cont = mp;
3438 	mp = mp1;
3439 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3440 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3441 	    io->ipsec_out_type == IPSEC_OUT);
3442 	ipsec_mp->b_cont = mp;
3443 
3444 	/*
3445 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3446 	 * node generates be accepted in peace by all on-host destinations.
3447 	 * If we do NOT assume that all on-host destinations trust
3448 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3449 	 * (Look for ipsec_out_icmp_loopback).
3450 	 */
3451 	io->ipsec_out_icmp_loopback = B_TRUE;
3452 
3453 	ipha = (ipha_t *)mp->b_rptr;
3454 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3455 	*ipha = icmp_ipha;
3456 	ipha->ipha_src = src;
3457 	ipha->ipha_dst = dst;
3458 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3459 	msg_len += sizeof (icmp_ipha) + len;
3460 	if (msg_len > IP_MAXPACKET) {
3461 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3462 		msg_len = IP_MAXPACKET;
3463 	}
3464 	ipha->ipha_length = htons((uint16_t)msg_len);
3465 	icmph = (icmph_t *)&ipha[1];
3466 	bcopy(stuff, icmph, len);
3467 	icmph->icmph_checksum = 0;
3468 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3469 	if (icmph->icmph_checksum == 0)
3470 		icmph->icmph_checksum = 0xFFFF;
3471 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3472 	put(q, ipsec_mp);
3473 }
3474 
3475 /*
3476  * Determine if an ICMP error packet can be sent given the rate limit.
3477  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3478  * in milliseconds) and a burst size. Burst size number of packets can
3479  * be sent arbitrarely closely spaced.
3480  * The state is tracked using two variables to implement an approximate
3481  * token bucket filter:
3482  *	icmp_pkt_err_last - lbolt value when the last burst started
3483  *	icmp_pkt_err_sent - number of packets sent in current burst
3484  */
3485 boolean_t
3486 icmp_err_rate_limit(ip_stack_t *ipst)
3487 {
3488 	clock_t now = TICK_TO_MSEC(lbolt);
3489 	uint_t refilled; /* Number of packets refilled in tbf since last */
3490 	/* Guard against changes by loading into local variable */
3491 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3492 
3493 	if (err_interval == 0)
3494 		return (B_FALSE);
3495 
3496 	if (ipst->ips_icmp_pkt_err_last > now) {
3497 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3498 		ipst->ips_icmp_pkt_err_last = 0;
3499 		ipst->ips_icmp_pkt_err_sent = 0;
3500 	}
3501 	/*
3502 	 * If we are in a burst update the token bucket filter.
3503 	 * Update the "last" time to be close to "now" but make sure
3504 	 * we don't loose precision.
3505 	 */
3506 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3507 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3508 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3509 			ipst->ips_icmp_pkt_err_sent = 0;
3510 		} else {
3511 			ipst->ips_icmp_pkt_err_sent -= refilled;
3512 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3513 		}
3514 	}
3515 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3516 		/* Start of new burst */
3517 		ipst->ips_icmp_pkt_err_last = now;
3518 	}
3519 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3520 		ipst->ips_icmp_pkt_err_sent++;
3521 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3522 			    ipst->ips_icmp_pkt_err_sent));
3523 		return (B_FALSE);
3524 	}
3525 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3526 	return (B_TRUE);
3527 }
3528 
3529 /*
3530  * Check if it is ok to send an IPv4 ICMP error packet in
3531  * response to the IPv4 packet in mp.
3532  * Free the message and return null if no
3533  * ICMP error packet should be sent.
3534  */
3535 static mblk_t *
3536 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3537 {
3538 	icmph_t	*icmph;
3539 	ipha_t	*ipha;
3540 	uint_t	len_needed;
3541 	ire_t	*src_ire;
3542 	ire_t	*dst_ire;
3543 
3544 	if (!mp)
3545 		return (NULL);
3546 	ipha = (ipha_t *)mp->b_rptr;
3547 	if (ip_csum_hdr(ipha)) {
3548 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3549 		freemsg(mp);
3550 		return (NULL);
3551 	}
3552 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3553 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3554 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3555 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3556 	if (src_ire != NULL || dst_ire != NULL ||
3557 	    CLASSD(ipha->ipha_dst) ||
3558 	    CLASSD(ipha->ipha_src) ||
3559 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3560 		/* Note: only errors to the fragment with offset 0 */
3561 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3562 		freemsg(mp);
3563 		if (src_ire != NULL)
3564 			ire_refrele(src_ire);
3565 		if (dst_ire != NULL)
3566 			ire_refrele(dst_ire);
3567 		return (NULL);
3568 	}
3569 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3570 		/*
3571 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3572 		 * errors in response to any ICMP errors.
3573 		 */
3574 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3575 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3576 			if (!pullupmsg(mp, len_needed)) {
3577 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3578 				freemsg(mp);
3579 				return (NULL);
3580 			}
3581 			ipha = (ipha_t *)mp->b_rptr;
3582 		}
3583 		icmph = (icmph_t *)
3584 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3585 		switch (icmph->icmph_type) {
3586 		case ICMP_DEST_UNREACHABLE:
3587 		case ICMP_SOURCE_QUENCH:
3588 		case ICMP_TIME_EXCEEDED:
3589 		case ICMP_PARAM_PROBLEM:
3590 		case ICMP_REDIRECT:
3591 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3592 			freemsg(mp);
3593 			return (NULL);
3594 		default:
3595 			break;
3596 		}
3597 	}
3598 	/*
3599 	 * If this is a labeled system, then check to see if we're allowed to
3600 	 * send a response to this particular sender.  If not, then just drop.
3601 	 */
3602 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3603 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3604 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3605 		freemsg(mp);
3606 		return (NULL);
3607 	}
3608 	if (icmp_err_rate_limit(ipst)) {
3609 		/*
3610 		 * Only send ICMP error packets every so often.
3611 		 * This should be done on a per port/source basis,
3612 		 * but for now this will suffice.
3613 		 */
3614 		freemsg(mp);
3615 		return (NULL);
3616 	}
3617 	return (mp);
3618 }
3619 
3620 /*
3621  * Generate an ICMP redirect message.
3622  */
3623 static void
3624 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3625 {
3626 	icmph_t	icmph;
3627 
3628 	/*
3629 	 * We are called from ip_rput where we could
3630 	 * not have attached an IPSEC_IN.
3631 	 */
3632 	ASSERT(mp->b_datap->db_type == M_DATA);
3633 
3634 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3635 		return;
3636 	}
3637 
3638 	bzero(&icmph, sizeof (icmph_t));
3639 	icmph.icmph_type = ICMP_REDIRECT;
3640 	icmph.icmph_code = 1;
3641 	icmph.icmph_rd_gateway = gateway;
3642 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3643 	/* Redirects sent by router, and router is global zone */
3644 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3645 }
3646 
3647 /*
3648  * Generate an ICMP time exceeded message.
3649  */
3650 void
3651 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3652     ip_stack_t *ipst)
3653 {
3654 	icmph_t	icmph;
3655 	boolean_t mctl_present;
3656 	mblk_t *first_mp;
3657 
3658 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3659 
3660 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3661 		if (mctl_present)
3662 			freeb(first_mp);
3663 		return;
3664 	}
3665 
3666 	bzero(&icmph, sizeof (icmph_t));
3667 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3668 	icmph.icmph_code = code;
3669 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3670 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3671 	    ipst);
3672 }
3673 
3674 /*
3675  * Generate an ICMP unreachable message.
3676  */
3677 void
3678 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3679     ip_stack_t *ipst)
3680 {
3681 	icmph_t	icmph;
3682 	mblk_t *first_mp;
3683 	boolean_t mctl_present;
3684 
3685 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3686 
3687 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3688 		if (mctl_present)
3689 			freeb(first_mp);
3690 		return;
3691 	}
3692 
3693 	bzero(&icmph, sizeof (icmph_t));
3694 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3695 	icmph.icmph_code = code;
3696 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3697 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3698 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3699 	    zoneid, ipst);
3700 }
3701 
3702 /*
3703  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3704  * duplicate.  As long as someone else holds the address, the interface will
3705  * stay down.  When that conflict goes away, the interface is brought back up.
3706  * This is done so that accidental shutdowns of addresses aren't made
3707  * permanent.  Your server will recover from a failure.
3708  *
3709  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3710  * user space process (dhcpagent).
3711  *
3712  * Recovery completes if ARP reports that the address is now ours (via
3713  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3714  *
3715  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3716  */
3717 static void
3718 ipif_dup_recovery(void *arg)
3719 {
3720 	ipif_t *ipif = arg;
3721 	ill_t *ill = ipif->ipif_ill;
3722 	mblk_t *arp_add_mp;
3723 	mblk_t *arp_del_mp;
3724 	area_t *area;
3725 	ip_stack_t *ipst = ill->ill_ipst;
3726 
3727 	ipif->ipif_recovery_id = 0;
3728 
3729 	/*
3730 	 * No lock needed for moving or condemned check, as this is just an
3731 	 * optimization.
3732 	 */
3733 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3734 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3735 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3736 		/* No reason to try to bring this address back. */
3737 		return;
3738 	}
3739 
3740 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3741 		goto alloc_fail;
3742 
3743 	if (ipif->ipif_arp_del_mp == NULL) {
3744 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3745 			goto alloc_fail;
3746 		ipif->ipif_arp_del_mp = arp_del_mp;
3747 	}
3748 
3749 	/* Setting the 'unverified' flag restarts DAD */
3750 	area = (area_t *)arp_add_mp->b_rptr;
3751 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3752 	    ACE_F_UNVERIFIED;
3753 	putnext(ill->ill_rq, arp_add_mp);
3754 	return;
3755 
3756 alloc_fail:
3757 	/*
3758 	 * On allocation failure, just restart the timer.  Note that the ipif
3759 	 * is down here, so no other thread could be trying to start a recovery
3760 	 * timer.  The ill_lock protects the condemned flag and the recovery
3761 	 * timer ID.
3762 	 */
3763 	freemsg(arp_add_mp);
3764 	mutex_enter(&ill->ill_lock);
3765 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3766 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3767 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3768 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3769 	}
3770 	mutex_exit(&ill->ill_lock);
3771 }
3772 
3773 /*
3774  * This is for exclusive changes due to ARP.  Either tear down an interface due
3775  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3776  */
3777 /* ARGSUSED */
3778 static void
3779 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3780 {
3781 	ill_t	*ill = rq->q_ptr;
3782 	arh_t *arh;
3783 	ipaddr_t src;
3784 	ipif_t	*ipif;
3785 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3786 	char hbuf[MAC_STR_LEN];
3787 	char sbuf[INET_ADDRSTRLEN];
3788 	const char *failtype;
3789 	boolean_t bring_up;
3790 	ip_stack_t *ipst = ill->ill_ipst;
3791 
3792 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3793 	case AR_CN_READY:
3794 		failtype = NULL;
3795 		bring_up = B_TRUE;
3796 		break;
3797 	case AR_CN_FAILED:
3798 		failtype = "in use";
3799 		bring_up = B_FALSE;
3800 		break;
3801 	default:
3802 		failtype = "claimed";
3803 		bring_up = B_FALSE;
3804 		break;
3805 	}
3806 
3807 	arh = (arh_t *)mp->b_cont->b_rptr;
3808 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3809 
3810 	/* Handle failures due to probes */
3811 	if (src == 0) {
3812 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3813 		    IP_ADDR_LEN);
3814 	}
3815 
3816 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3817 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3818 	    sizeof (hbuf));
3819 	(void) ip_dot_addr(src, sbuf);
3820 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3821 
3822 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3823 		    ipif->ipif_lcl_addr != src) {
3824 			continue;
3825 		}
3826 
3827 		/*
3828 		 * If we failed on a recovery probe, then restart the timer to
3829 		 * try again later.
3830 		 */
3831 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3832 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3833 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3834 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3835 		    ipst->ips_ip_dup_recovery > 0 &&
3836 		    ipif->ipif_recovery_id == 0) {
3837 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3838 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3839 			continue;
3840 		}
3841 
3842 		/*
3843 		 * If what we're trying to do has already been done, then do
3844 		 * nothing.
3845 		 */
3846 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3847 			continue;
3848 
3849 		if (ipif->ipif_id != 0) {
3850 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3851 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3852 			    ipif->ipif_id);
3853 		}
3854 		if (failtype == NULL) {
3855 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3856 			    ibuf);
3857 		} else {
3858 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3859 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3860 		}
3861 
3862 		if (bring_up) {
3863 			ASSERT(ill->ill_dl_up);
3864 			/*
3865 			 * Free up the ARP delete message so we can allocate
3866 			 * a fresh one through the normal path.
3867 			 */
3868 			freemsg(ipif->ipif_arp_del_mp);
3869 			ipif->ipif_arp_del_mp = NULL;
3870 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3871 			    EINPROGRESS) {
3872 				ipif->ipif_addr_ready = 1;
3873 				(void) ipif_up_done(ipif);
3874 			}
3875 			continue;
3876 		}
3877 
3878 		mutex_enter(&ill->ill_lock);
3879 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3880 		ipif->ipif_flags |= IPIF_DUPLICATE;
3881 		ill->ill_ipif_dup_count++;
3882 		mutex_exit(&ill->ill_lock);
3883 		/*
3884 		 * Already exclusive on the ill; no need to handle deferred
3885 		 * processing here.
3886 		 */
3887 		(void) ipif_down(ipif, NULL, NULL);
3888 		ipif_down_tail(ipif);
3889 		mutex_enter(&ill->ill_lock);
3890 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3891 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3892 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3893 		    ipst->ips_ip_dup_recovery > 0) {
3894 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3895 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3896 		}
3897 		mutex_exit(&ill->ill_lock);
3898 	}
3899 	freemsg(mp);
3900 }
3901 
3902 /* ARGSUSED */
3903 static void
3904 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3905 {
3906 	ill_t	*ill = rq->q_ptr;
3907 	arh_t *arh;
3908 	ipaddr_t src;
3909 	ipif_t	*ipif;
3910 
3911 	arh = (arh_t *)mp->b_cont->b_rptr;
3912 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3913 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3914 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3915 			(void) ipif_resolver_up(ipif, Res_act_defend);
3916 	}
3917 	freemsg(mp);
3918 }
3919 
3920 /*
3921  * News from ARP.  ARP sends notification of interesting events down
3922  * to its clients using M_CTL messages with the interesting ARP packet
3923  * attached via b_cont.
3924  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3925  * queue as opposed to ARP sending the message to all the clients, i.e. all
3926  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3927  * table if a cache IRE is found to delete all the entries for the address in
3928  * the packet.
3929  */
3930 static void
3931 ip_arp_news(queue_t *q, mblk_t *mp)
3932 {
3933 	arcn_t		*arcn;
3934 	arh_t		*arh;
3935 	ire_t		*ire = NULL;
3936 	char		hbuf[MAC_STR_LEN];
3937 	char		sbuf[INET_ADDRSTRLEN];
3938 	ipaddr_t	src;
3939 	in6_addr_t	v6src;
3940 	boolean_t	isv6 = B_FALSE;
3941 	ipif_t		*ipif;
3942 	ill_t		*ill;
3943 	ip_stack_t	*ipst;
3944 
3945 	if (CONN_Q(q)) {
3946 		conn_t *connp = Q_TO_CONN(q);
3947 
3948 		ipst = connp->conn_netstack->netstack_ip;
3949 	} else {
3950 		ill_t *ill = (ill_t *)q->q_ptr;
3951 
3952 		ipst = ill->ill_ipst;
3953 	}
3954 
3955 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3956 		if (q->q_next) {
3957 			putnext(q, mp);
3958 		} else
3959 			freemsg(mp);
3960 		return;
3961 	}
3962 	arh = (arh_t *)mp->b_cont->b_rptr;
3963 	/* Is it one we are interested in? */
3964 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3965 		isv6 = B_TRUE;
3966 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3967 		    IPV6_ADDR_LEN);
3968 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3969 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3970 		    IP_ADDR_LEN);
3971 	} else {
3972 		freemsg(mp);
3973 		return;
3974 	}
3975 
3976 	ill = q->q_ptr;
3977 
3978 	arcn = (arcn_t *)mp->b_rptr;
3979 	switch (arcn->arcn_code) {
3980 	case AR_CN_BOGON:
3981 		/*
3982 		 * Someone is sending ARP packets with a source protocol
3983 		 * address that we have published and for which we believe our
3984 		 * entry is authoritative and (when ill_arp_extend is set)
3985 		 * verified to be unique on the network.
3986 		 *
3987 		 * The ARP module internally handles the cases where the sender
3988 		 * is just probing (for DAD) and where the hardware address of
3989 		 * a non-authoritative entry has changed.  Thus, these are the
3990 		 * real conflicts, and we have to do resolution.
3991 		 *
3992 		 * We back away quickly from the address if it's from DHCP or
3993 		 * otherwise temporary and hasn't been used recently (or at
3994 		 * all).  We'd like to include "deprecated" addresses here as
3995 		 * well (as there's no real reason to defend something we're
3996 		 * discarding), but IPMP "reuses" this flag to mean something
3997 		 * other than the standard meaning.
3998 		 *
3999 		 * If the ARP module above is not extended (meaning that it
4000 		 * doesn't know how to defend the address), then we just log
4001 		 * the problem as we always did and continue on.  It's not
4002 		 * right, but there's little else we can do, and those old ATM
4003 		 * users are going away anyway.
4004 		 */
4005 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4006 		    hbuf, sizeof (hbuf));
4007 		(void) ip_dot_addr(src, sbuf);
4008 		if (isv6) {
4009 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4010 			    ipst);
4011 		} else {
4012 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4013 		}
4014 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4015 			uint32_t now;
4016 			uint32_t maxage;
4017 			clock_t lused;
4018 			uint_t maxdefense;
4019 			uint_t defs;
4020 
4021 			/*
4022 			 * First, figure out if this address hasn't been used
4023 			 * in a while.  If it hasn't, then it's a better
4024 			 * candidate for abandoning.
4025 			 */
4026 			ipif = ire->ire_ipif;
4027 			ASSERT(ipif != NULL);
4028 			now = gethrestime_sec();
4029 			maxage = now - ire->ire_create_time;
4030 			if (maxage > ipst->ips_ip_max_temp_idle)
4031 				maxage = ipst->ips_ip_max_temp_idle;
4032 			lused = drv_hztousec(ddi_get_lbolt() -
4033 			    ire->ire_last_used_time) / MICROSEC + 1;
4034 			if (lused >= maxage && (ipif->ipif_flags &
4035 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4036 				maxdefense = ipst->ips_ip_max_temp_defend;
4037 			else
4038 				maxdefense = ipst->ips_ip_max_defend;
4039 
4040 			/*
4041 			 * Now figure out how many times we've defended
4042 			 * ourselves.  Ignore defenses that happened long in
4043 			 * the past.
4044 			 */
4045 			mutex_enter(&ire->ire_lock);
4046 			if ((defs = ire->ire_defense_count) > 0 &&
4047 			    now - ire->ire_defense_time >
4048 			    ipst->ips_ip_defend_interval) {
4049 				ire->ire_defense_count = defs = 0;
4050 			}
4051 			ire->ire_defense_count++;
4052 			ire->ire_defense_time = now;
4053 			mutex_exit(&ire->ire_lock);
4054 			ill_refhold(ill);
4055 			ire_refrele(ire);
4056 
4057 			/*
4058 			 * If we've defended ourselves too many times already,
4059 			 * then give up and tear down the interface(s) using
4060 			 * this address.  Otherwise, defend by sending out a
4061 			 * gratuitous ARP.
4062 			 */
4063 			if (defs >= maxdefense && ill->ill_arp_extend) {
4064 				(void) qwriter_ip(NULL, ill, q, mp,
4065 				    ip_arp_excl, CUR_OP, B_FALSE);
4066 			} else {
4067 				cmn_err(CE_WARN,
4068 				    "node %s is using our IP address %s on %s",
4069 				    hbuf, sbuf, ill->ill_name);
4070 				/*
4071 				 * If this is an old (ATM) ARP module, then
4072 				 * don't try to defend the address.  Remain
4073 				 * compatible with the old behavior.  Defend
4074 				 * only with new ARP.
4075 				 */
4076 				if (ill->ill_arp_extend) {
4077 					(void) qwriter_ip(NULL, ill, q, mp,
4078 					    ip_arp_defend, CUR_OP, B_FALSE);
4079 				} else {
4080 					ill_refrele(ill);
4081 				}
4082 			}
4083 			return;
4084 		}
4085 		cmn_err(CE_WARN,
4086 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4087 		    hbuf, sbuf, ill->ill_name);
4088 		if (ire != NULL)
4089 			ire_refrele(ire);
4090 		break;
4091 	case AR_CN_ANNOUNCE:
4092 		if (isv6) {
4093 			/*
4094 			 * For XRESOLV interfaces.
4095 			 * Delete the IRE cache entry and NCE for this
4096 			 * v6 address
4097 			 */
4098 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4099 			/*
4100 			 * If v6src is a non-zero, it's a router address
4101 			 * as below. Do the same sort of thing to clean
4102 			 * out off-net IRE_CACHE entries that go through
4103 			 * the router.
4104 			 */
4105 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4106 				ire_walk_v6(ire_delete_cache_gw_v6,
4107 				    (char *)&v6src, ALL_ZONES, ipst);
4108 			}
4109 		} else {
4110 			nce_hw_map_t hwm;
4111 
4112 			/*
4113 			 * ARP gives us a copy of any packet where it thinks
4114 			 * the address has changed, so that we can update our
4115 			 * caches.  We're responsible for caching known answers
4116 			 * in the current design.  We check whether the
4117 			 * hardware address really has changed in all of our
4118 			 * entries that have cached this mapping, and if so, we
4119 			 * blow them away.  This way we will immediately pick
4120 			 * up the rare case of a host changing hardware
4121 			 * address.
4122 			 */
4123 			if (src == 0)
4124 				break;
4125 			hwm.hwm_addr = src;
4126 			hwm.hwm_hwlen = arh->arh_hlen;
4127 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4128 			ndp_walk_common(ipst->ips_ndp4, NULL,
4129 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4130 		}
4131 		break;
4132 	case AR_CN_READY:
4133 		/* No external v6 resolver has a contract to use this */
4134 		if (isv6)
4135 			break;
4136 		/* If the link is down, we'll retry this later */
4137 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4138 			break;
4139 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4140 		    NULL, NULL, ipst);
4141 		if (ipif != NULL) {
4142 			/*
4143 			 * If this is a duplicate recovery, then we now need to
4144 			 * go exclusive to bring this thing back up.
4145 			 */
4146 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4147 			    IPIF_DUPLICATE) {
4148 				ipif_refrele(ipif);
4149 				ill_refhold(ill);
4150 				(void) qwriter_ip(NULL, ill, q, mp,
4151 				    ip_arp_excl, CUR_OP, B_FALSE);
4152 				return;
4153 			}
4154 			/*
4155 			 * If this is the first notice that this address is
4156 			 * ready, then let the user know now.
4157 			 */
4158 			if ((ipif->ipif_flags & IPIF_UP) &&
4159 			    !ipif->ipif_addr_ready) {
4160 				ipif_mask_reply(ipif);
4161 				ip_rts_ifmsg(ipif);
4162 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4163 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4164 			}
4165 			ipif->ipif_addr_ready = 1;
4166 			ipif_refrele(ipif);
4167 		}
4168 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4169 		if (ire != NULL) {
4170 			ire->ire_defense_count = 0;
4171 			ire_refrele(ire);
4172 		}
4173 		break;
4174 	case AR_CN_FAILED:
4175 		/* No external v6 resolver has a contract to use this */
4176 		if (isv6)
4177 			break;
4178 		ill_refhold(ill);
4179 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4180 		    B_FALSE);
4181 		return;
4182 	}
4183 	freemsg(mp);
4184 }
4185 
4186 /*
4187  * Create a mblk suitable for carrying the interface index and/or source link
4188  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4189  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4190  * application.
4191  */
4192 mblk_t *
4193 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4194     ip_stack_t *ipst)
4195 {
4196 	mblk_t		*mp;
4197 	ip_pktinfo_t	*pinfo;
4198 	ipha_t *ipha;
4199 	struct ether_header *pether;
4200 
4201 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4202 	if (mp == NULL) {
4203 		ip1dbg(("ip_add_info: allocation failure.\n"));
4204 		return (data_mp);
4205 	}
4206 
4207 	ipha	= (ipha_t *)data_mp->b_rptr;
4208 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4209 	bzero(pinfo, sizeof (ip_pktinfo_t));
4210 	pinfo->ip_pkt_flags = (uchar_t)flags;
4211 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4212 
4213 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4214 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4215 	if (flags & IPF_RECVADDR) {
4216 		ipif_t	*ipif;
4217 		ire_t	*ire;
4218 
4219 		/*
4220 		 * Only valid for V4
4221 		 */
4222 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4223 		    (IPV4_VERSION << 4));
4224 
4225 		ipif = ipif_get_next_ipif(NULL, ill);
4226 		if (ipif != NULL) {
4227 			/*
4228 			 * Since a decision has already been made to deliver the
4229 			 * packet, there is no need to test for SECATTR and
4230 			 * ZONEONLY.
4231 			 */
4232 			ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0, ipif,
4233 			    zoneid, NULL, MATCH_IRE_ILL_GROUP, ipst);
4234 			if (ire == NULL) {
4235 				/*
4236 				 * packet must have come on a different
4237 				 * interface.
4238 				 * Since a decision has already been made to
4239 				 * deliver the packet, there is no need to test
4240 				 * for SECATTR and ZONEONLY.
4241 				 */
4242 				ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0,
4243 				    ipif, zoneid, NULL, NULL, ipst);
4244 			}
4245 
4246 			if (ire == NULL) {
4247 				/*
4248 				 * This is either a multicast packet or
4249 				 * the address has been removed since
4250 				 * the packet was received.
4251 				 * Return INADDR_ANY so that normal source
4252 				 * selection occurs for the response.
4253 				 */
4254 
4255 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4256 			} else {
4257 				ASSERT(ire->ire_type != IRE_CACHE);
4258 				pinfo->ip_pkt_match_addr.s_addr =
4259 				    ire->ire_src_addr;
4260 				ire_refrele(ire);
4261 			}
4262 			ipif_refrele(ipif);
4263 		} else {
4264 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4265 		}
4266 	}
4267 
4268 	pether = (struct ether_header *)((char *)ipha
4269 	    - sizeof (struct ether_header));
4270 	/*
4271 	 * Make sure the interface is an ethernet type, since this option
4272 	 * is currently supported only on this type of interface. Also make
4273 	 * sure we are pointing correctly above db_base.
4274 	 */
4275 
4276 	if ((flags & IPF_RECVSLLA) &&
4277 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4278 	    (ill->ill_type == IFT_ETHER) &&
4279 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4280 
4281 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4282 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4283 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4284 	} else {
4285 		/*
4286 		 * Clear the bit. Indicate to upper layer that IP is not
4287 		 * sending this ancillary info.
4288 		 */
4289 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4290 	}
4291 
4292 	mp->b_datap->db_type = M_CTL;
4293 	mp->b_wptr += sizeof (ip_pktinfo_t);
4294 	mp->b_cont = data_mp;
4295 
4296 	return (mp);
4297 }
4298 
4299 /*
4300  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4301  * part of the bind request.
4302  */
4303 
4304 boolean_t
4305 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4306 {
4307 	ipsec_in_t *ii;
4308 
4309 	ASSERT(policy_mp != NULL);
4310 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4311 
4312 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4313 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4314 
4315 	connp->conn_policy = ii->ipsec_in_policy;
4316 	ii->ipsec_in_policy = NULL;
4317 
4318 	if (ii->ipsec_in_action != NULL) {
4319 		if (connp->conn_latch == NULL) {
4320 			connp->conn_latch = iplatch_create();
4321 			if (connp->conn_latch == NULL)
4322 				return (B_FALSE);
4323 		}
4324 		ipsec_latch_inbound(connp->conn_latch, ii);
4325 	}
4326 	return (B_TRUE);
4327 }
4328 
4329 /*
4330  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4331  * and to arrange for power-fanout assist.  The ULP is identified by
4332  * adding a single byte at the end of the original bind message.
4333  * A ULP other than UDP or TCP that wishes to be recognized passes
4334  * down a bind with a zero length address.
4335  *
4336  * The binding works as follows:
4337  * - A zero byte address means just bind to the protocol.
4338  * - A four byte address is treated as a request to validate
4339  *   that the address is a valid local address, appropriate for
4340  *   an application to bind to. This does not affect any fanout
4341  *   information in IP.
4342  * - A sizeof sin_t byte address is used to bind to only the local address
4343  *   and port.
4344  * - A sizeof ipa_conn_t byte address contains complete fanout information
4345  *   consisting of local and remote addresses and ports.  In
4346  *   this case, the addresses are both validated as appropriate
4347  *   for this operation, and, if so, the information is retained
4348  *   for use in the inbound fanout.
4349  *
4350  * The ULP (except in the zero-length bind) can append an
4351  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4352  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4353  * a copy of the source or destination IRE (source for local bind;
4354  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4355  * policy information contained should be copied on to the conn.
4356  *
4357  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4358  */
4359 mblk_t *
4360 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4361 {
4362 	ssize_t		len;
4363 	struct T_bind_req	*tbr;
4364 	sin_t		*sin;
4365 	ipa_conn_t	*ac;
4366 	uchar_t		*ucp;
4367 	mblk_t		*mp1;
4368 	boolean_t	ire_requested;
4369 	boolean_t	ipsec_policy_set = B_FALSE;
4370 	int		error = 0;
4371 	int		protocol;
4372 	ipa_conn_x_t	*acx;
4373 
4374 	ASSERT(!connp->conn_af_isv6);
4375 	connp->conn_pkt_isv6 = B_FALSE;
4376 
4377 	len = MBLKL(mp);
4378 	if (len < (sizeof (*tbr) + 1)) {
4379 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4380 		    "ip_bind: bogus msg, len %ld", len);
4381 		/* XXX: Need to return something better */
4382 		goto bad_addr;
4383 	}
4384 	/* Back up and extract the protocol identifier. */
4385 	mp->b_wptr--;
4386 	protocol = *mp->b_wptr & 0xFF;
4387 	tbr = (struct T_bind_req *)mp->b_rptr;
4388 	/* Reset the message type in preparation for shipping it back. */
4389 	DB_TYPE(mp) = M_PCPROTO;
4390 
4391 	connp->conn_ulp = (uint8_t)protocol;
4392 
4393 	/*
4394 	 * Check for a zero length address.  This is from a protocol that
4395 	 * wants to register to receive all packets of its type.
4396 	 */
4397 	if (tbr->ADDR_length == 0) {
4398 		/*
4399 		 * These protocols are now intercepted in ip_bind_v6().
4400 		 * Reject protocol-level binds here for now.
4401 		 *
4402 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4403 		 * so that the protocol type cannot be SCTP.
4404 		 */
4405 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4406 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4407 			goto bad_addr;
4408 		}
4409 
4410 		/*
4411 		 *
4412 		 * The udp module never sends down a zero-length address,
4413 		 * and allowing this on a labeled system will break MLP
4414 		 * functionality.
4415 		 */
4416 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4417 			goto bad_addr;
4418 
4419 		if (connp->conn_mac_exempt)
4420 			goto bad_addr;
4421 
4422 		/* No hash here really.  The table is big enough. */
4423 		connp->conn_srcv6 = ipv6_all_zeros;
4424 
4425 		ipcl_proto_insert(connp, protocol);
4426 
4427 		tbr->PRIM_type = T_BIND_ACK;
4428 		return (mp);
4429 	}
4430 
4431 	/* Extract the address pointer from the message. */
4432 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4433 	    tbr->ADDR_length);
4434 	if (ucp == NULL) {
4435 		ip1dbg(("ip_bind: no address\n"));
4436 		goto bad_addr;
4437 	}
4438 	if (!OK_32PTR(ucp)) {
4439 		ip1dbg(("ip_bind: unaligned address\n"));
4440 		goto bad_addr;
4441 	}
4442 	/*
4443 	 * Check for trailing mps.
4444 	 */
4445 
4446 	mp1 = mp->b_cont;
4447 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4448 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4449 
4450 	switch (tbr->ADDR_length) {
4451 	default:
4452 		ip1dbg(("ip_bind: bad address length %d\n",
4453 		    (int)tbr->ADDR_length));
4454 		goto bad_addr;
4455 
4456 	case IP_ADDR_LEN:
4457 		/* Verification of local address only */
4458 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4459 		    ire_requested, ipsec_policy_set, B_FALSE);
4460 		break;
4461 
4462 	case sizeof (sin_t):
4463 		sin = (sin_t *)ucp;
4464 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4465 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4466 		break;
4467 
4468 	case sizeof (ipa_conn_t):
4469 		ac = (ipa_conn_t *)ucp;
4470 		/* For raw socket, the local port is not set. */
4471 		if (ac->ac_lport == 0)
4472 			ac->ac_lport = connp->conn_lport;
4473 		/* Always verify destination reachability. */
4474 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4475 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4476 		    ipsec_policy_set, B_TRUE, B_TRUE);
4477 		break;
4478 
4479 	case sizeof (ipa_conn_x_t):
4480 		acx = (ipa_conn_x_t *)ucp;
4481 		/*
4482 		 * Whether or not to verify destination reachability depends
4483 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4484 		 */
4485 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4486 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4487 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4488 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4489 		break;
4490 	}
4491 	if (error == EINPROGRESS)
4492 		return (NULL);
4493 	else if (error != 0)
4494 		goto bad_addr;
4495 	/*
4496 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4497 	 * We can't do this in ip_bind_insert_ire because the policy
4498 	 * may not have been inherited at that point in time and hence
4499 	 * conn_out_enforce_policy may not be set.
4500 	 */
4501 	mp1 = mp->b_cont;
4502 	if (ire_requested && connp->conn_out_enforce_policy &&
4503 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4504 		ire_t *ire = (ire_t *)mp1->b_rptr;
4505 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4506 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4507 	}
4508 
4509 	/* Send it home. */
4510 	mp->b_datap->db_type = M_PCPROTO;
4511 	tbr->PRIM_type = T_BIND_ACK;
4512 	return (mp);
4513 
4514 bad_addr:
4515 	/*
4516 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4517 	 * a unix errno.
4518 	 */
4519 	if (error > 0)
4520 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4521 	else
4522 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4523 	return (mp);
4524 }
4525 
4526 /*
4527  * Here address is verified to be a valid local address.
4528  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4529  * address is also considered a valid local address.
4530  * In the case of a broadcast/multicast address, however, the
4531  * upper protocol is expected to reset the src address
4532  * to 0 if it sees a IRE_BROADCAST type returned so that
4533  * no packets are emitted with broadcast/multicast address as
4534  * source address (that violates hosts requirements RFC1122)
4535  * The addresses valid for bind are:
4536  *	(1) - INADDR_ANY (0)
4537  *	(2) - IP address of an UP interface
4538  *	(3) - IP address of a DOWN interface
4539  *	(4) - valid local IP broadcast addresses. In this case
4540  *	the conn will only receive packets destined to
4541  *	the specified broadcast address.
4542  *	(5) - a multicast address. In this case
4543  *	the conn will only receive packets destined to
4544  *	the specified multicast address. Note: the
4545  *	application still has to issue an
4546  *	IP_ADD_MEMBERSHIP socket option.
4547  *
4548  * On error, return -1 for TBADADDR otherwise pass the
4549  * errno with TSYSERR reply.
4550  *
4551  * In all the above cases, the bound address must be valid in the current zone.
4552  * When the address is loopback, multicast or broadcast, there might be many
4553  * matching IREs so bind has to look up based on the zone.
4554  *
4555  * Note: lport is in network byte order.
4556  */
4557 int
4558 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4559     boolean_t ire_requested, boolean_t ipsec_policy_set,
4560     boolean_t fanout_insert)
4561 {
4562 	int		error = 0;
4563 	ire_t		*src_ire;
4564 	mblk_t		*policy_mp;
4565 	ipif_t		*ipif;
4566 	zoneid_t	zoneid;
4567 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4568 
4569 	if (ipsec_policy_set) {
4570 		policy_mp = mp->b_cont;
4571 	}
4572 
4573 	/*
4574 	 * If it was previously connected, conn_fully_bound would have
4575 	 * been set.
4576 	 */
4577 	connp->conn_fully_bound = B_FALSE;
4578 
4579 	src_ire = NULL;
4580 	ipif = NULL;
4581 
4582 	zoneid = IPCL_ZONEID(connp);
4583 
4584 	if (src_addr) {
4585 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4586 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4587 		/*
4588 		 * If an address other than 0.0.0.0 is requested,
4589 		 * we verify that it is a valid address for bind
4590 		 * Note: Following code is in if-else-if form for
4591 		 * readability compared to a condition check.
4592 		 */
4593 		/* LINTED - statement has no consequent */
4594 		if (IRE_IS_LOCAL(src_ire)) {
4595 			/*
4596 			 * (2) Bind to address of local UP interface
4597 			 */
4598 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4599 			/*
4600 			 * (4) Bind to broadcast address
4601 			 * Note: permitted only from transports that
4602 			 * request IRE
4603 			 */
4604 			if (!ire_requested)
4605 				error = EADDRNOTAVAIL;
4606 		} else {
4607 			/*
4608 			 * (3) Bind to address of local DOWN interface
4609 			 * (ipif_lookup_addr() looks up all interfaces
4610 			 * but we do not get here for UP interfaces
4611 			 * - case (2) above)
4612 			 * We put the protocol byte back into the mblk
4613 			 * since we may come back via ip_wput_nondata()
4614 			 * later with this mblk if ipif_lookup_addr chooses
4615 			 * to defer processing.
4616 			 */
4617 			*mp->b_wptr++ = (char)connp->conn_ulp;
4618 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4619 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4620 			    &error, ipst)) != NULL) {
4621 				ipif_refrele(ipif);
4622 			} else if (error == EINPROGRESS) {
4623 				if (src_ire != NULL)
4624 					ire_refrele(src_ire);
4625 				return (EINPROGRESS);
4626 			} else if (CLASSD(src_addr)) {
4627 				error = 0;
4628 				if (src_ire != NULL)
4629 					ire_refrele(src_ire);
4630 				/*
4631 				 * (5) bind to multicast address.
4632 				 * Fake out the IRE returned to upper
4633 				 * layer to be a broadcast IRE.
4634 				 */
4635 				src_ire = ire_ctable_lookup(
4636 				    INADDR_BROADCAST, INADDR_ANY,
4637 				    IRE_BROADCAST, NULL, zoneid, NULL,
4638 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4639 				    ipst);
4640 				if (src_ire == NULL || !ire_requested)
4641 					error = EADDRNOTAVAIL;
4642 			} else {
4643 				/*
4644 				 * Not a valid address for bind
4645 				 */
4646 				error = EADDRNOTAVAIL;
4647 			}
4648 			/*
4649 			 * Just to keep it consistent with the processing in
4650 			 * ip_bind_v4()
4651 			 */
4652 			mp->b_wptr--;
4653 		}
4654 		if (error) {
4655 			/* Red Alert!  Attempting to be a bogon! */
4656 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4657 			    ntohl(src_addr)));
4658 			goto bad_addr;
4659 		}
4660 	}
4661 
4662 	/*
4663 	 * Allow setting new policies. For example, disconnects come
4664 	 * down as ipa_t bind. As we would have set conn_policy_cached
4665 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4666 	 * can change after the disconnect.
4667 	 */
4668 	connp->conn_policy_cached = B_FALSE;
4669 
4670 	/*
4671 	 * If not fanout_insert this was just an address verification
4672 	 */
4673 	if (fanout_insert) {
4674 		/*
4675 		 * The addresses have been verified. Time to insert in
4676 		 * the correct fanout list.
4677 		 */
4678 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4679 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4680 		connp->conn_lport = lport;
4681 		connp->conn_fport = 0;
4682 		/*
4683 		 * Do we need to add a check to reject Multicast packets
4684 		 *
4685 		 * We need to make sure that the conn_recv is set to a non-null
4686 		 * value before we insert the conn into the classifier table.
4687 		 * This is to avoid a race with an incoming packet which does an
4688 		 * ipcl_classify().
4689 		 */
4690 		if (*mp->b_wptr == IPPROTO_TCP)
4691 			connp->conn_recv = tcp_conn_request;
4692 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4693 	}
4694 
4695 	if (error == 0) {
4696 		if (ire_requested) {
4697 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4698 				error = -1;
4699 				/* Falls through to bad_addr */
4700 			}
4701 		} else if (ipsec_policy_set) {
4702 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4703 				error = -1;
4704 				/* Falls through to bad_addr */
4705 			}
4706 		}
4707 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4708 		connp->conn_recv = tcp_input;
4709 	}
4710 bad_addr:
4711 	if (error != 0) {
4712 		if (connp->conn_anon_port) {
4713 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4714 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4715 			    B_FALSE);
4716 		}
4717 		connp->conn_mlp_type = mlptSingle;
4718 	}
4719 	if (src_ire != NULL)
4720 		IRE_REFRELE(src_ire);
4721 	if (ipsec_policy_set) {
4722 		ASSERT(policy_mp == mp->b_cont);
4723 		ASSERT(policy_mp != NULL);
4724 		freeb(policy_mp);
4725 		/*
4726 		 * As of now assume that nothing else accompanies
4727 		 * IPSEC_POLICY_SET.
4728 		 */
4729 		mp->b_cont = NULL;
4730 	}
4731 	return (error);
4732 }
4733 
4734 /*
4735  * Verify that both the source and destination addresses
4736  * are valid.  If verify_dst is false, then the destination address may be
4737  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4738  * destination reachability, while tunnels do not.
4739  * Note that we allow connect to broadcast and multicast
4740  * addresses when ire_requested is set. Thus the ULP
4741  * has to check for IRE_BROADCAST and multicast.
4742  *
4743  * Returns zero if ok.
4744  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4745  * (for use with TSYSERR reply).
4746  *
4747  * Note: lport and fport are in network byte order.
4748  */
4749 int
4750 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4751     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4752     boolean_t ire_requested, boolean_t ipsec_policy_set,
4753     boolean_t fanout_insert, boolean_t verify_dst)
4754 {
4755 	ire_t		*src_ire;
4756 	ire_t		*dst_ire;
4757 	int		error = 0;
4758 	int 		protocol;
4759 	mblk_t		*policy_mp;
4760 	ire_t		*sire = NULL;
4761 	ire_t		*md_dst_ire = NULL;
4762 	ire_t		*lso_dst_ire = NULL;
4763 	ill_t		*ill = NULL;
4764 	zoneid_t	zoneid;
4765 	ipaddr_t	src_addr = *src_addrp;
4766 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4767 
4768 	src_ire = dst_ire = NULL;
4769 	protocol = *mp->b_wptr & 0xFF;
4770 
4771 	/*
4772 	 * If we never got a disconnect before, clear it now.
4773 	 */
4774 	connp->conn_fully_bound = B_FALSE;
4775 
4776 	if (ipsec_policy_set) {
4777 		policy_mp = mp->b_cont;
4778 	}
4779 
4780 	zoneid = IPCL_ZONEID(connp);
4781 
4782 	if (CLASSD(dst_addr)) {
4783 		/* Pick up an IRE_BROADCAST */
4784 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4785 		    NULL, zoneid, MBLK_GETLABEL(mp),
4786 		    (MATCH_IRE_RECURSIVE |
4787 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4788 		    MATCH_IRE_SECATTR), ipst);
4789 	} else {
4790 		/*
4791 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4792 		 * and onlink ipif is not found set ENETUNREACH error.
4793 		 */
4794 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4795 			ipif_t *ipif;
4796 
4797 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4798 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4799 			if (ipif == NULL) {
4800 				error = ENETUNREACH;
4801 				goto bad_addr;
4802 			}
4803 			ipif_refrele(ipif);
4804 		}
4805 
4806 		if (connp->conn_nexthop_set) {
4807 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4808 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4809 			    MATCH_IRE_SECATTR, ipst);
4810 		} else {
4811 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4812 			    &sire, zoneid, MBLK_GETLABEL(mp),
4813 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4814 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4815 			    MATCH_IRE_SECATTR), ipst);
4816 		}
4817 	}
4818 	/*
4819 	 * dst_ire can't be a broadcast when not ire_requested.
4820 	 * We also prevent ire's with src address INADDR_ANY to
4821 	 * be used, which are created temporarily for
4822 	 * sending out packets from endpoints that have
4823 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4824 	 * reachable.  If verify_dst is false, the destination needn't be
4825 	 * reachable.
4826 	 *
4827 	 * If we match on a reject or black hole, then we've got a
4828 	 * local failure.  May as well fail out the connect() attempt,
4829 	 * since it's never going to succeed.
4830 	 */
4831 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4832 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4833 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4834 		/*
4835 		 * If we're verifying destination reachability, we always want
4836 		 * to complain here.
4837 		 *
4838 		 * If we're not verifying destination reachability but the
4839 		 * destination has a route, we still want to fail on the
4840 		 * temporary address and broadcast address tests.
4841 		 */
4842 		if (verify_dst || (dst_ire != NULL)) {
4843 			if (ip_debug > 2) {
4844 				pr_addr_dbg("ip_bind_connected: bad connected "
4845 				    "dst %s\n", AF_INET, &dst_addr);
4846 			}
4847 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4848 				error = ENETUNREACH;
4849 			else
4850 				error = EHOSTUNREACH;
4851 			goto bad_addr;
4852 		}
4853 	}
4854 
4855 	/*
4856 	 * We now know that routing will allow us to reach the destination.
4857 	 * Check whether Trusted Solaris policy allows communication with this
4858 	 * host, and pretend that the destination is unreachable if not.
4859 	 *
4860 	 * This is never a problem for TCP, since that transport is known to
4861 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4862 	 * handling.  If the remote is unreachable, it will be detected at that
4863 	 * point, so there's no reason to check it here.
4864 	 *
4865 	 * Note that for sendto (and other datagram-oriented friends), this
4866 	 * check is done as part of the data path label computation instead.
4867 	 * The check here is just to make non-TCP connect() report the right
4868 	 * error.
4869 	 */
4870 	if (dst_ire != NULL && is_system_labeled() &&
4871 	    !IPCL_IS_TCP(connp) &&
4872 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4873 	    connp->conn_mac_exempt, ipst) != 0) {
4874 		error = EHOSTUNREACH;
4875 		if (ip_debug > 2) {
4876 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4877 			    AF_INET, &dst_addr);
4878 		}
4879 		goto bad_addr;
4880 	}
4881 
4882 	/*
4883 	 * If the app does a connect(), it means that it will most likely
4884 	 * send more than 1 packet to the destination.  It makes sense
4885 	 * to clear the temporary flag.
4886 	 */
4887 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4888 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4889 		irb_t *irb = dst_ire->ire_bucket;
4890 
4891 		rw_enter(&irb->irb_lock, RW_WRITER);
4892 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4893 		irb->irb_tmp_ire_cnt--;
4894 		rw_exit(&irb->irb_lock);
4895 	}
4896 
4897 	/*
4898 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4899 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4900 	 * eligibility tests for passive connects are handled separately
4901 	 * through tcp_adapt_ire().  We do this before the source address
4902 	 * selection, because dst_ire may change after a call to
4903 	 * ipif_select_source().  This is a best-effort check, as the
4904 	 * packet for this connection may not actually go through
4905 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4906 	 * calling ip_newroute().  This is why we further check on the
4907 	 * IRE during LSO/Multidata packet transmission in
4908 	 * tcp_lsosend()/tcp_multisend().
4909 	 */
4910 	if (!ipsec_policy_set && dst_ire != NULL &&
4911 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4912 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4913 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4914 			lso_dst_ire = dst_ire;
4915 			IRE_REFHOLD(lso_dst_ire);
4916 		} else if (ipst->ips_ip_multidata_outbound &&
4917 		    ILL_MDT_CAPABLE(ill)) {
4918 			md_dst_ire = dst_ire;
4919 			IRE_REFHOLD(md_dst_ire);
4920 		}
4921 	}
4922 
4923 	if (dst_ire != NULL &&
4924 	    dst_ire->ire_type == IRE_LOCAL &&
4925 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4926 		/*
4927 		 * If the IRE belongs to a different zone, look for a matching
4928 		 * route in the forwarding table and use the source address from
4929 		 * that route.
4930 		 */
4931 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4932 		    zoneid, 0, NULL,
4933 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4934 		    MATCH_IRE_RJ_BHOLE, ipst);
4935 		if (src_ire == NULL) {
4936 			error = EHOSTUNREACH;
4937 			goto bad_addr;
4938 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4939 			if (!(src_ire->ire_type & IRE_HOST))
4940 				error = ENETUNREACH;
4941 			else
4942 				error = EHOSTUNREACH;
4943 			goto bad_addr;
4944 		}
4945 		if (src_addr == INADDR_ANY)
4946 			src_addr = src_ire->ire_src_addr;
4947 		ire_refrele(src_ire);
4948 		src_ire = NULL;
4949 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4950 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4951 			src_addr = sire->ire_src_addr;
4952 			ire_refrele(dst_ire);
4953 			dst_ire = sire;
4954 			sire = NULL;
4955 		} else {
4956 			/*
4957 			 * Pick a source address so that a proper inbound
4958 			 * load spreading would happen.
4959 			 */
4960 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4961 			ipif_t *src_ipif = NULL;
4962 			ire_t *ipif_ire;
4963 
4964 			/*
4965 			 * Supply a local source address such that inbound
4966 			 * load spreading happens.
4967 			 *
4968 			 * Determine the best source address on this ill for
4969 			 * the destination.
4970 			 *
4971 			 * 1) For broadcast, we should return a broadcast ire
4972 			 *    found above so that upper layers know that the
4973 			 *    destination address is a broadcast address.
4974 			 *
4975 			 * 2) If this is part of a group, select a better
4976 			 *    source address so that better inbound load
4977 			 *    balancing happens. Do the same if the ipif
4978 			 *    is DEPRECATED.
4979 			 *
4980 			 * 3) If the outgoing interface is part of a usesrc
4981 			 *    group, then try selecting a source address from
4982 			 *    the usesrc ILL.
4983 			 */
4984 			if ((dst_ire->ire_zoneid != zoneid &&
4985 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4986 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4987 			    ((dst_ill->ill_group != NULL) ||
4988 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4989 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4990 				/*
4991 				 * If the destination is reachable via a
4992 				 * given gateway, the selected source address
4993 				 * should be in the same subnet as the gateway.
4994 				 * Otherwise, the destination is not reachable.
4995 				 *
4996 				 * If there are no interfaces on the same subnet
4997 				 * as the destination, ipif_select_source gives
4998 				 * first non-deprecated interface which might be
4999 				 * on a different subnet than the gateway.
5000 				 * This is not desirable. Hence pass the dst_ire
5001 				 * source address to ipif_select_source.
5002 				 * It is sure that the destination is reachable
5003 				 * with the dst_ire source address subnet.
5004 				 * So passing dst_ire source address to
5005 				 * ipif_select_source will make sure that the
5006 				 * selected source will be on the same subnet
5007 				 * as dst_ire source address.
5008 				 */
5009 				ipaddr_t saddr =
5010 				    dst_ire->ire_ipif->ipif_src_addr;
5011 				src_ipif = ipif_select_source(dst_ill,
5012 				    saddr, zoneid);
5013 				if (src_ipif != NULL) {
5014 					if (IS_VNI(src_ipif->ipif_ill)) {
5015 						/*
5016 						 * For VNI there is no
5017 						 * interface route
5018 						 */
5019 						src_addr =
5020 						    src_ipif->ipif_src_addr;
5021 					} else {
5022 						ipif_ire =
5023 						    ipif_to_ire(src_ipif);
5024 						if (ipif_ire != NULL) {
5025 							IRE_REFRELE(dst_ire);
5026 							dst_ire = ipif_ire;
5027 						}
5028 						src_addr =
5029 						    dst_ire->ire_src_addr;
5030 					}
5031 					ipif_refrele(src_ipif);
5032 				} else {
5033 					src_addr = dst_ire->ire_src_addr;
5034 				}
5035 			} else {
5036 				src_addr = dst_ire->ire_src_addr;
5037 			}
5038 		}
5039 	}
5040 
5041 	/*
5042 	 * We do ire_route_lookup() here (and not
5043 	 * interface lookup as we assert that
5044 	 * src_addr should only come from an
5045 	 * UP interface for hard binding.
5046 	 */
5047 	ASSERT(src_ire == NULL);
5048 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5049 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5050 	/* src_ire must be a local|loopback */
5051 	if (!IRE_IS_LOCAL(src_ire)) {
5052 		if (ip_debug > 2) {
5053 			pr_addr_dbg("ip_bind_connected: bad connected "
5054 			    "src %s\n", AF_INET, &src_addr);
5055 		}
5056 		error = EADDRNOTAVAIL;
5057 		goto bad_addr;
5058 	}
5059 
5060 	/*
5061 	 * If the source address is a loopback address, the
5062 	 * destination had best be local or multicast.
5063 	 * The transports that can't handle multicast will reject
5064 	 * those addresses.
5065 	 */
5066 	if (src_ire->ire_type == IRE_LOOPBACK &&
5067 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5068 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5069 		error = -1;
5070 		goto bad_addr;
5071 	}
5072 
5073 	/*
5074 	 * Allow setting new policies. For example, disconnects come
5075 	 * down as ipa_t bind. As we would have set conn_policy_cached
5076 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5077 	 * can change after the disconnect.
5078 	 */
5079 	connp->conn_policy_cached = B_FALSE;
5080 
5081 	/*
5082 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5083 	 * can handle their passed-in conn's.
5084 	 */
5085 
5086 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5087 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5088 	connp->conn_lport = lport;
5089 	connp->conn_fport = fport;
5090 	*src_addrp = src_addr;
5091 
5092 	ASSERT(!(ipsec_policy_set && ire_requested));
5093 	if (ire_requested) {
5094 		iulp_t *ulp_info = NULL;
5095 
5096 		/*
5097 		 * Note that sire will not be NULL if this is an off-link
5098 		 * connection and there is not cache for that dest yet.
5099 		 *
5100 		 * XXX Because of an existing bug, if there are multiple
5101 		 * default routes, the IRE returned now may not be the actual
5102 		 * default route used (default routes are chosen in a
5103 		 * round robin fashion).  So if the metrics for different
5104 		 * default routes are different, we may return the wrong
5105 		 * metrics.  This will not be a problem if the existing
5106 		 * bug is fixed.
5107 		 */
5108 		if (sire != NULL) {
5109 			ulp_info = &(sire->ire_uinfo);
5110 		}
5111 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5112 			error = -1;
5113 			goto bad_addr;
5114 		}
5115 	} else if (ipsec_policy_set) {
5116 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5117 			error = -1;
5118 			goto bad_addr;
5119 		}
5120 	}
5121 
5122 	/*
5123 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5124 	 * we'll cache that.  If we don't, we'll inherit global policy.
5125 	 *
5126 	 * We can't insert until the conn reflects the policy. Note that
5127 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5128 	 * connections where we don't have a policy. This is to prevent
5129 	 * global policy lookups in the inbound path.
5130 	 *
5131 	 * If we insert before we set conn_policy_cached,
5132 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5133 	 * because global policy cound be non-empty. We normally call
5134 	 * ipsec_check_policy() for conn_policy_cached connections only if
5135 	 * ipc_in_enforce_policy is set. But in this case,
5136 	 * conn_policy_cached can get set anytime since we made the
5137 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5138 	 * called, which will make the above assumption false.  Thus, we
5139 	 * need to insert after we set conn_policy_cached.
5140 	 */
5141 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5142 		goto bad_addr;
5143 
5144 	if (fanout_insert) {
5145 		/*
5146 		 * The addresses have been verified. Time to insert in
5147 		 * the correct fanout list.
5148 		 * We need to make sure that the conn_recv is set to a non-null
5149 		 * value before we insert into the classifier table to avoid a
5150 		 * race with an incoming packet which does an ipcl_classify().
5151 		 */
5152 		if (protocol == IPPROTO_TCP)
5153 			connp->conn_recv = tcp_input;
5154 		error = ipcl_conn_insert(connp, protocol, src_addr,
5155 		    dst_addr, connp->conn_ports);
5156 	}
5157 
5158 	if (error == 0) {
5159 		connp->conn_fully_bound = B_TRUE;
5160 		/*
5161 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5162 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5163 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5164 		 * ip_xxinfo_return(), which performs further checks
5165 		 * against them and upon success, returns the LSO/MDT info
5166 		 * mblk which we will attach to the bind acknowledgment.
5167 		 */
5168 		if (lso_dst_ire != NULL) {
5169 			mblk_t *lsoinfo_mp;
5170 
5171 			ASSERT(ill->ill_lso_capab != NULL);
5172 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5173 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5174 				linkb(mp, lsoinfo_mp);
5175 		} else if (md_dst_ire != NULL) {
5176 			mblk_t *mdinfo_mp;
5177 
5178 			ASSERT(ill->ill_mdt_capab != NULL);
5179 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5180 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5181 				linkb(mp, mdinfo_mp);
5182 		}
5183 	}
5184 bad_addr:
5185 	if (ipsec_policy_set) {
5186 		ASSERT(policy_mp == mp->b_cont);
5187 		ASSERT(policy_mp != NULL);
5188 		freeb(policy_mp);
5189 		/*
5190 		 * As of now assume that nothing else accompanies
5191 		 * IPSEC_POLICY_SET.
5192 		 */
5193 		mp->b_cont = NULL;
5194 	}
5195 	if (src_ire != NULL)
5196 		IRE_REFRELE(src_ire);
5197 	if (dst_ire != NULL)
5198 		IRE_REFRELE(dst_ire);
5199 	if (sire != NULL)
5200 		IRE_REFRELE(sire);
5201 	if (md_dst_ire != NULL)
5202 		IRE_REFRELE(md_dst_ire);
5203 	if (lso_dst_ire != NULL)
5204 		IRE_REFRELE(lso_dst_ire);
5205 	return (error);
5206 }
5207 
5208 /*
5209  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5210  * Prefers dst_ire over src_ire.
5211  */
5212 static boolean_t
5213 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5214 {
5215 	mblk_t	*mp1;
5216 	ire_t *ret_ire = NULL;
5217 
5218 	mp1 = mp->b_cont;
5219 	ASSERT(mp1 != NULL);
5220 
5221 	if (ire != NULL) {
5222 		/*
5223 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5224 		 * appended mblk. Its <upper protocol>'s
5225 		 * job to make sure there is room.
5226 		 */
5227 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5228 			return (0);
5229 
5230 		mp1->b_datap->db_type = IRE_DB_TYPE;
5231 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5232 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5233 		ret_ire = (ire_t *)mp1->b_rptr;
5234 		/*
5235 		 * Pass the latest setting of the ip_path_mtu_discovery and
5236 		 * copy the ulp info if any.
5237 		 */
5238 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5239 		    IPH_DF : 0;
5240 		if (ulp_info != NULL) {
5241 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5242 			    sizeof (iulp_t));
5243 		}
5244 		ret_ire->ire_mp = mp1;
5245 	} else {
5246 		/*
5247 		 * No IRE was found. Remove IRE mblk.
5248 		 */
5249 		mp->b_cont = mp1->b_cont;
5250 		freeb(mp1);
5251 	}
5252 
5253 	return (1);
5254 }
5255 
5256 /*
5257  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5258  * the final piece where we don't.  Return a pointer to the first mblk in the
5259  * result, and update the pointer to the next mblk to chew on.  If anything
5260  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5261  * NULL pointer.
5262  */
5263 mblk_t *
5264 ip_carve_mp(mblk_t **mpp, ssize_t len)
5265 {
5266 	mblk_t	*mp0;
5267 	mblk_t	*mp1;
5268 	mblk_t	*mp2;
5269 
5270 	if (!len || !mpp || !(mp0 = *mpp))
5271 		return (NULL);
5272 	/* If we aren't going to consume the first mblk, we need a dup. */
5273 	if (mp0->b_wptr - mp0->b_rptr > len) {
5274 		mp1 = dupb(mp0);
5275 		if (mp1) {
5276 			/* Partition the data between the two mblks. */
5277 			mp1->b_wptr = mp1->b_rptr + len;
5278 			mp0->b_rptr = mp1->b_wptr;
5279 			/*
5280 			 * after adjustments if mblk not consumed is now
5281 			 * unaligned, try to align it. If this fails free
5282 			 * all messages and let upper layer recover.
5283 			 */
5284 			if (!OK_32PTR(mp0->b_rptr)) {
5285 				if (!pullupmsg(mp0, -1)) {
5286 					freemsg(mp0);
5287 					freemsg(mp1);
5288 					*mpp = NULL;
5289 					return (NULL);
5290 				}
5291 			}
5292 		}
5293 		return (mp1);
5294 	}
5295 	/* Eat through as many mblks as we need to get len bytes. */
5296 	len -= mp0->b_wptr - mp0->b_rptr;
5297 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5298 		if (mp2->b_wptr - mp2->b_rptr > len) {
5299 			/*
5300 			 * We won't consume the entire last mblk.  Like
5301 			 * above, dup and partition it.
5302 			 */
5303 			mp1->b_cont = dupb(mp2);
5304 			mp1 = mp1->b_cont;
5305 			if (!mp1) {
5306 				/*
5307 				 * Trouble.  Rather than go to a lot of
5308 				 * trouble to clean up, we free the messages.
5309 				 * This won't be any worse than losing it on
5310 				 * the wire.
5311 				 */
5312 				freemsg(mp0);
5313 				freemsg(mp2);
5314 				*mpp = NULL;
5315 				return (NULL);
5316 			}
5317 			mp1->b_wptr = mp1->b_rptr + len;
5318 			mp2->b_rptr = mp1->b_wptr;
5319 			/*
5320 			 * after adjustments if mblk not consumed is now
5321 			 * unaligned, try to align it. If this fails free
5322 			 * all messages and let upper layer recover.
5323 			 */
5324 			if (!OK_32PTR(mp2->b_rptr)) {
5325 				if (!pullupmsg(mp2, -1)) {
5326 					freemsg(mp0);
5327 					freemsg(mp2);
5328 					*mpp = NULL;
5329 					return (NULL);
5330 				}
5331 			}
5332 			*mpp = mp2;
5333 			return (mp0);
5334 		}
5335 		/* Decrement len by the amount we just got. */
5336 		len -= mp2->b_wptr - mp2->b_rptr;
5337 	}
5338 	/*
5339 	 * len should be reduced to zero now.  If not our caller has
5340 	 * screwed up.
5341 	 */
5342 	if (len) {
5343 		/* Shouldn't happen! */
5344 		freemsg(mp0);
5345 		*mpp = NULL;
5346 		return (NULL);
5347 	}
5348 	/*
5349 	 * We consumed up to exactly the end of an mblk.  Detach the part
5350 	 * we are returning from the rest of the chain.
5351 	 */
5352 	mp1->b_cont = NULL;
5353 	*mpp = mp2;
5354 	return (mp0);
5355 }
5356 
5357 /* The ill stream is being unplumbed. Called from ip_close */
5358 int
5359 ip_modclose(ill_t *ill)
5360 {
5361 
5362 	boolean_t success;
5363 	ipsq_t	*ipsq;
5364 	ipif_t	*ipif;
5365 	queue_t	*q = ill->ill_rq;
5366 	ip_stack_t	*ipst = ill->ill_ipst;
5367 	clock_t timeout;
5368 
5369 	/*
5370 	 * Wait for the ACKs of all deferred control messages to be processed.
5371 	 * In particular, we wait for a potential capability reset initiated
5372 	 * in ip_sioctl_plink() to complete before proceeding.
5373 	 *
5374 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5375 	 * in case the driver never replies.
5376 	 */
5377 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5378 	mutex_enter(&ill->ill_lock);
5379 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5380 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5381 			/* Timeout */
5382 			break;
5383 		}
5384 	}
5385 	mutex_exit(&ill->ill_lock);
5386 
5387 	/*
5388 	 * Forcibly enter the ipsq after some delay. This is to take
5389 	 * care of the case when some ioctl does not complete because
5390 	 * we sent a control message to the driver and it did not
5391 	 * send us a reply. We want to be able to at least unplumb
5392 	 * and replumb rather than force the user to reboot the system.
5393 	 */
5394 	success = ipsq_enter(ill, B_FALSE);
5395 
5396 	/*
5397 	 * Open/close/push/pop is guaranteed to be single threaded
5398 	 * per stream by STREAMS. FS guarantees that all references
5399 	 * from top are gone before close is called. So there can't
5400 	 * be another close thread that has set CONDEMNED on this ill.
5401 	 * and cause ipsq_enter to return failure.
5402 	 */
5403 	ASSERT(success);
5404 	ipsq = ill->ill_phyint->phyint_ipsq;
5405 
5406 	/*
5407 	 * Mark it condemned. No new reference will be made to this ill.
5408 	 * Lookup functions will return an error. Threads that try to
5409 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5410 	 * that the refcnt will drop down to zero.
5411 	 */
5412 	mutex_enter(&ill->ill_lock);
5413 	ill->ill_state_flags |= ILL_CONDEMNED;
5414 	for (ipif = ill->ill_ipif; ipif != NULL;
5415 	    ipif = ipif->ipif_next) {
5416 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5417 	}
5418 	/*
5419 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5420 	 * returns  error if ILL_CONDEMNED is set
5421 	 */
5422 	cv_broadcast(&ill->ill_cv);
5423 	mutex_exit(&ill->ill_lock);
5424 
5425 	/*
5426 	 * Send all the deferred control messages downstream which came in
5427 	 * during the small window right before ipsq_enter(). We do this
5428 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5429 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5430 	 */
5431 	ill_send_all_deferred_mp(ill);
5432 
5433 	/*
5434 	 * Shut down fragmentation reassembly.
5435 	 * ill_frag_timer won't start a timer again.
5436 	 * Now cancel any existing timer
5437 	 */
5438 	(void) untimeout(ill->ill_frag_timer_id);
5439 	(void) ill_frag_timeout(ill, 0);
5440 
5441 	/*
5442 	 * If MOVE was in progress, clear the
5443 	 * move_in_progress fields also.
5444 	 */
5445 	if (ill->ill_move_in_progress) {
5446 		ILL_CLEAR_MOVE(ill);
5447 	}
5448 
5449 	/*
5450 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5451 	 * this ill. Then wait for the refcnts to drop to zero.
5452 	 * ill_is_quiescent checks whether the ill is really quiescent.
5453 	 * Then make sure that threads that are waiting to enter the
5454 	 * ipsq have seen the error returned by ipsq_enter and have
5455 	 * gone away. Then we call ill_delete_tail which does the
5456 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5457 	 */
5458 	ill_delete(ill);
5459 	mutex_enter(&ill->ill_lock);
5460 	while (!ill_is_quiescent(ill))
5461 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5462 	while (ill->ill_waiters)
5463 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5464 
5465 	mutex_exit(&ill->ill_lock);
5466 
5467 	/*
5468 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5469 	 * it held until the end of the function since the cleanup
5470 	 * below needs to be able to use the ip_stack_t.
5471 	 */
5472 	netstack_hold(ipst->ips_netstack);
5473 
5474 	/* qprocsoff is called in ill_delete_tail */
5475 	ill_delete_tail(ill);
5476 	ASSERT(ill->ill_ipst == NULL);
5477 
5478 	/*
5479 	 * Walk through all upper (conn) streams and qenable
5480 	 * those that have queued data.
5481 	 * close synchronization needs this to
5482 	 * be done to ensure that all upper layers blocked
5483 	 * due to flow control to the closing device
5484 	 * get unblocked.
5485 	 */
5486 	ip1dbg(("ip_wsrv: walking\n"));
5487 	conn_walk_drain(ipst);
5488 
5489 	mutex_enter(&ipst->ips_ip_mi_lock);
5490 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5491 	mutex_exit(&ipst->ips_ip_mi_lock);
5492 
5493 	/*
5494 	 * credp could be null if the open didn't succeed and ip_modopen
5495 	 * itself calls ip_close.
5496 	 */
5497 	if (ill->ill_credp != NULL)
5498 		crfree(ill->ill_credp);
5499 
5500 	mutex_enter(&ill->ill_lock);
5501 	ill_nic_info_dispatch(ill);
5502 	mutex_exit(&ill->ill_lock);
5503 
5504 	/*
5505 	 * Now we are done with the module close pieces that
5506 	 * need the netstack_t.
5507 	 */
5508 	netstack_rele(ipst->ips_netstack);
5509 
5510 	mi_close_free((IDP)ill);
5511 	q->q_ptr = WR(q)->q_ptr = NULL;
5512 
5513 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5514 
5515 	return (0);
5516 }
5517 
5518 /*
5519  * This is called as part of close() for both IP and UDP
5520  * in order to quiesce the conn.
5521  */
5522 void
5523 ip_quiesce_conn(conn_t *connp)
5524 {
5525 	boolean_t	drain_cleanup_reqd = B_FALSE;
5526 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5527 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5528 	ip_stack_t	*ipst;
5529 
5530 	ASSERT(!IPCL_IS_TCP(connp));
5531 	ipst = connp->conn_netstack->netstack_ip;
5532 
5533 	/*
5534 	 * Mark the conn as closing, and this conn must not be
5535 	 * inserted in future into any list. Eg. conn_drain_insert(),
5536 	 * won't insert this conn into the conn_drain_list.
5537 	 * Similarly ill_pending_mp_add() will not add any mp to
5538 	 * the pending mp list, after this conn has started closing.
5539 	 *
5540 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5541 	 * cannot get set henceforth.
5542 	 */
5543 	mutex_enter(&connp->conn_lock);
5544 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5545 	connp->conn_state_flags |= CONN_CLOSING;
5546 	if (connp->conn_idl != NULL)
5547 		drain_cleanup_reqd = B_TRUE;
5548 	if (connp->conn_oper_pending_ill != NULL)
5549 		conn_ioctl_cleanup_reqd = B_TRUE;
5550 	if (connp->conn_ilg_inuse != 0)
5551 		ilg_cleanup_reqd = B_TRUE;
5552 	mutex_exit(&connp->conn_lock);
5553 
5554 	if (IPCL_IS_UDP(connp))
5555 		udp_quiesce_conn(connp);
5556 
5557 	if (conn_ioctl_cleanup_reqd)
5558 		conn_ioctl_cleanup(connp);
5559 
5560 	if (is_system_labeled() && connp->conn_anon_port) {
5561 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5562 		    connp->conn_mlp_type, connp->conn_ulp,
5563 		    ntohs(connp->conn_lport), B_FALSE);
5564 		connp->conn_anon_port = 0;
5565 	}
5566 	connp->conn_mlp_type = mlptSingle;
5567 
5568 	/*
5569 	 * Remove this conn from any fanout list it is on.
5570 	 * and then wait for any threads currently operating
5571 	 * on this endpoint to finish
5572 	 */
5573 	ipcl_hash_remove(connp);
5574 
5575 	/*
5576 	 * Remove this conn from the drain list, and do
5577 	 * any other cleanup that may be required.
5578 	 * (Only non-tcp streams may have a non-null conn_idl.
5579 	 * TCP streams are never flow controlled, and
5580 	 * conn_idl will be null)
5581 	 */
5582 	if (drain_cleanup_reqd)
5583 		conn_drain_tail(connp, B_TRUE);
5584 
5585 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5586 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5587 		(void) ip_mrouter_done(NULL, ipst);
5588 
5589 	if (ilg_cleanup_reqd)
5590 		ilg_delete_all(connp);
5591 
5592 	conn_delete_ire(connp, NULL);
5593 
5594 	/*
5595 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5596 	 * callers from write side can't be there now because close
5597 	 * is in progress. The only other caller is ipcl_walk
5598 	 * which checks for the condemned flag.
5599 	 */
5600 	mutex_enter(&connp->conn_lock);
5601 	connp->conn_state_flags |= CONN_CONDEMNED;
5602 	while (connp->conn_ref != 1)
5603 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5604 	connp->conn_state_flags |= CONN_QUIESCED;
5605 	mutex_exit(&connp->conn_lock);
5606 }
5607 
5608 /* ARGSUSED */
5609 int
5610 ip_close(queue_t *q, int flags)
5611 {
5612 	conn_t		*connp;
5613 
5614 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5615 
5616 	/*
5617 	 * Call the appropriate delete routine depending on whether this is
5618 	 * a module or device.
5619 	 */
5620 	if (WR(q)->q_next != NULL) {
5621 		/* This is a module close */
5622 		return (ip_modclose((ill_t *)q->q_ptr));
5623 	}
5624 
5625 	connp = q->q_ptr;
5626 	ip_quiesce_conn(connp);
5627 
5628 	qprocsoff(q);
5629 
5630 	/*
5631 	 * Now we are truly single threaded on this stream, and can
5632 	 * delete the things hanging off the connp, and finally the connp.
5633 	 * We removed this connp from the fanout list, it cannot be
5634 	 * accessed thru the fanouts, and we already waited for the
5635 	 * conn_ref to drop to 0. We are already in close, so
5636 	 * there cannot be any other thread from the top. qprocsoff
5637 	 * has completed, and service has completed or won't run in
5638 	 * future.
5639 	 */
5640 	ASSERT(connp->conn_ref == 1);
5641 
5642 	/*
5643 	 * A conn which was previously marked as IPCL_UDP cannot
5644 	 * retain the flag because it would have been cleared by
5645 	 * udp_close().
5646 	 */
5647 	ASSERT(!IPCL_IS_UDP(connp));
5648 
5649 	if (connp->conn_latch != NULL) {
5650 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5651 		connp->conn_latch = NULL;
5652 	}
5653 	if (connp->conn_policy != NULL) {
5654 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5655 		connp->conn_policy = NULL;
5656 	}
5657 	if (connp->conn_ipsec_opt_mp != NULL) {
5658 		freemsg(connp->conn_ipsec_opt_mp);
5659 		connp->conn_ipsec_opt_mp = NULL;
5660 	}
5661 
5662 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5663 
5664 	connp->conn_ref--;
5665 	ipcl_conn_destroy(connp);
5666 
5667 	q->q_ptr = WR(q)->q_ptr = NULL;
5668 	return (0);
5669 }
5670 
5671 int
5672 ip_snmpmod_close(queue_t *q)
5673 {
5674 	conn_t *connp = Q_TO_CONN(q);
5675 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5676 
5677 	qprocsoff(q);
5678 
5679 	if (connp->conn_flags & IPCL_UDPMOD)
5680 		udp_close_free(connp);
5681 
5682 	if (connp->conn_cred != NULL) {
5683 		crfree(connp->conn_cred);
5684 		connp->conn_cred = NULL;
5685 	}
5686 	CONN_DEC_REF(connp);
5687 	q->q_ptr = WR(q)->q_ptr = NULL;
5688 	return (0);
5689 }
5690 
5691 /*
5692  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5693  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5694  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5695  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5696  * queues as we never enqueue messages there and we don't handle any ioctls.
5697  * Everything else is freed.
5698  */
5699 void
5700 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5701 {
5702 	conn_t	*connp = q->q_ptr;
5703 	pfi_t	setfn;
5704 	pfi_t	getfn;
5705 
5706 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5707 
5708 	switch (DB_TYPE(mp)) {
5709 	case M_PROTO:
5710 	case M_PCPROTO:
5711 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5712 		    ((((union T_primitives *)mp->b_rptr)->type ==
5713 			T_SVR4_OPTMGMT_REQ) ||
5714 		    (((union T_primitives *)mp->b_rptr)->type ==
5715 			T_OPTMGMT_REQ))) {
5716 			/*
5717 			 * This is the only TPI primitive supported. Its
5718 			 * handling does not require tcp_t, but it does require
5719 			 * conn_t to check permissions.
5720 			 */
5721 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5722 
5723 			if (connp->conn_flags & IPCL_TCPMOD) {
5724 				setfn = tcp_snmp_set;
5725 				getfn = tcp_snmp_get;
5726 			} else {
5727 				setfn = udp_snmp_set;
5728 				getfn = udp_snmp_get;
5729 			}
5730 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5731 				freemsg(mp);
5732 				return;
5733 			}
5734 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5735 		    != NULL)
5736 			qreply(q, mp);
5737 		break;
5738 	case M_FLUSH:
5739 	case M_IOCTL:
5740 		putnext(q, mp);
5741 		break;
5742 	default:
5743 		freemsg(mp);
5744 		break;
5745 	}
5746 }
5747 
5748 /* Return the IP checksum for the IP header at "iph". */
5749 uint16_t
5750 ip_csum_hdr(ipha_t *ipha)
5751 {
5752 	uint16_t	*uph;
5753 	uint32_t	sum;
5754 	int		opt_len;
5755 
5756 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5757 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5758 	uph = (uint16_t *)ipha;
5759 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5760 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5761 	if (opt_len > 0) {
5762 		do {
5763 			sum += uph[10];
5764 			sum += uph[11];
5765 			uph += 2;
5766 		} while (--opt_len);
5767 	}
5768 	sum = (sum & 0xFFFF) + (sum >> 16);
5769 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5770 	if (sum == 0xffff)
5771 		sum = 0;
5772 	return ((uint16_t)sum);
5773 }
5774 
5775 /*
5776  * Called when the module is about to be unloaded
5777  */
5778 void
5779 ip_ddi_destroy(void)
5780 {
5781 	tnet_fini();
5782 
5783 	sctp_ddi_g_destroy();
5784 	tcp_ddi_g_destroy();
5785 	ipsec_policy_g_destroy();
5786 	ipcl_g_destroy();
5787 	ip_net_g_destroy();
5788 	ip_ire_g_fini();
5789 	inet_minor_destroy(ip_minor_arena);
5790 
5791 	netstack_unregister(NS_IP);
5792 }
5793 
5794 /*
5795  * First step in cleanup.
5796  */
5797 /* ARGSUSED */
5798 static void
5799 ip_stack_shutdown(netstackid_t stackid, void *arg)
5800 {
5801 	ip_stack_t *ipst = (ip_stack_t *)arg;
5802 
5803 #ifdef NS_DEBUG
5804 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5805 #endif
5806 
5807 	/* Get rid of loopback interfaces and their IREs */
5808 	ip_loopback_cleanup(ipst);
5809 }
5810 
5811 /*
5812  * Free the IP stack instance.
5813  */
5814 static void
5815 ip_stack_fini(netstackid_t stackid, void *arg)
5816 {
5817 	ip_stack_t *ipst = (ip_stack_t *)arg;
5818 	int ret;
5819 
5820 #ifdef NS_DEBUG
5821 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5822 #endif
5823 	ipv4_hook_destroy(ipst);
5824 	ipv6_hook_destroy(ipst);
5825 	ip_net_destroy(ipst);
5826 
5827 	rw_destroy(&ipst->ips_srcid_lock);
5828 
5829 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5830 	ipst->ips_ip_mibkp = NULL;
5831 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5832 	ipst->ips_icmp_mibkp = NULL;
5833 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5834 	ipst->ips_ip_kstat = NULL;
5835 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5836 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5837 	ipst->ips_ip6_kstat = NULL;
5838 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5839 
5840 	nd_free(&ipst->ips_ip_g_nd);
5841 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5842 	ipst->ips_param_arr = NULL;
5843 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5844 	ipst->ips_ndp_arr = NULL;
5845 
5846 	ip_mrouter_stack_destroy(ipst);
5847 
5848 	mutex_destroy(&ipst->ips_ip_mi_lock);
5849 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5850 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5851 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5852 
5853 	ret = untimeout(ipst->ips_igmp_timeout_id);
5854 	if (ret == -1) {
5855 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5856 	} else {
5857 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5858 		ipst->ips_igmp_timeout_id = 0;
5859 	}
5860 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5861 	if (ret == -1) {
5862 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5863 	} else {
5864 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5865 		ipst->ips_igmp_slowtimeout_id = 0;
5866 	}
5867 	ret = untimeout(ipst->ips_mld_timeout_id);
5868 	if (ret == -1) {
5869 		ASSERT(ipst->ips_mld_timeout_id == 0);
5870 	} else {
5871 		ASSERT(ipst->ips_mld_timeout_id != 0);
5872 		ipst->ips_mld_timeout_id = 0;
5873 	}
5874 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5875 	if (ret == -1) {
5876 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5877 	} else {
5878 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5879 		ipst->ips_mld_slowtimeout_id = 0;
5880 	}
5881 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5882 	if (ret == -1) {
5883 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5884 	} else {
5885 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5886 		ipst->ips_ip_ire_expire_id = 0;
5887 	}
5888 
5889 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5890 	mutex_destroy(&ipst->ips_mld_timer_lock);
5891 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5892 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5893 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5894 	rw_destroy(&ipst->ips_ill_g_lock);
5895 
5896 	ip_ire_fini(ipst);
5897 	ip6_asp_free(ipst);
5898 	conn_drain_fini(ipst);
5899 	ipcl_destroy(ipst);
5900 
5901 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5902 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5903 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5904 	ipst->ips_ndp4 = NULL;
5905 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5906 	ipst->ips_ndp6 = NULL;
5907 
5908 	if (ipst->ips_loopback_ksp != NULL) {
5909 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5910 		ipst->ips_loopback_ksp = NULL;
5911 	}
5912 
5913 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5914 	ipst->ips_phyint_g_list = NULL;
5915 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5916 	ipst->ips_ill_g_heads = NULL;
5917 
5918 	kmem_free(ipst, sizeof (*ipst));
5919 }
5920 
5921 /*
5922  * Called when the IP kernel module is loaded into the kernel
5923  */
5924 void
5925 ip_ddi_init(void)
5926 {
5927 	TCP6_MAJ = ddi_name_to_major(TCP6);
5928 	TCP_MAJ	= ddi_name_to_major(TCP);
5929 	SCTP_MAJ = ddi_name_to_major(SCTP);
5930 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5931 
5932 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5933 
5934 	/*
5935 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5936 	 * initial devices: ip, ip6, tcp, tcp6.
5937 	 */
5938 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5939 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5940 		cmn_err(CE_PANIC,
5941 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5942 	}
5943 
5944 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5945 
5946 	ipcl_g_init();
5947 	ip_ire_g_init();
5948 	ip_net_g_init();
5949 
5950 	/*
5951 	 * We want to be informed each time a stack is created or
5952 	 * destroyed in the kernel, so we can maintain the
5953 	 * set of udp_stack_t's.
5954 	 */
5955 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5956 	    ip_stack_fini);
5957 
5958 	ipsec_policy_g_init();
5959 	tcp_ddi_g_init();
5960 	sctp_ddi_g_init();
5961 
5962 	tnet_init();
5963 }
5964 
5965 /*
5966  * Initialize the IP stack instance.
5967  */
5968 static void *
5969 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5970 {
5971 	ip_stack_t	*ipst;
5972 	ipparam_t	*pa;
5973 	ipndp_t		*na;
5974 
5975 #ifdef NS_DEBUG
5976 	printf("ip_stack_init(stack %d)\n", stackid);
5977 #endif
5978 
5979 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5980 	ipst->ips_netstack = ns;
5981 
5982 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5983 	    KM_SLEEP);
5984 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5985 	    KM_SLEEP);
5986 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5987 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5988 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5989 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5990 
5991 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5992 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5993 	ipst->ips_igmp_deferred_next = INFINITY;
5994 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5995 	ipst->ips_mld_deferred_next = INFINITY;
5996 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5997 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5998 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5999 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6000 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6001 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6002 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6003 
6004 	ipcl_init(ipst);
6005 	ip_ire_init(ipst);
6006 	ip6_asp_init(ipst);
6007 	ipif_init(ipst);
6008 	conn_drain_init(ipst);
6009 	ip_mrouter_stack_init(ipst);
6010 
6011 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6012 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6013 
6014 	ipst->ips_ip_multirt_log_interval = 1000;
6015 
6016 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6017 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6018 	ipst->ips_ill_index = 1;
6019 
6020 	ipst->ips_saved_ip_g_forward = -1;
6021 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6022 
6023 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6024 	ipst->ips_param_arr = pa;
6025 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6026 
6027 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6028 	ipst->ips_ndp_arr = na;
6029 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6030 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6031 	    (caddr_t)&ipst->ips_ip_g_forward;
6032 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6033 	    (caddr_t)&ipst->ips_ipv6_forward;
6034 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6035 		"ip_cgtp_filter") == 0);
6036 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6037 	    (caddr_t)&ip_cgtp_filter;
6038 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6039 		"ipmp_hook_emulation") == 0);
6040 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6041 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6042 
6043 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6044 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6045 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6046 
6047 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6048 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6049 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6050 	ipst->ips_ip6_kstat =
6051 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6052 
6053 	ipst->ips_ipmp_enable_failback = B_TRUE;
6054 
6055 	ipst->ips_ip_src_id = 1;
6056 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6057 
6058 	ip_net_init(ipst, ns);
6059 	ipv4_hook_init(ipst);
6060 	ipv6_hook_init(ipst);
6061 
6062 	return (ipst);
6063 }
6064 
6065 /*
6066  * Allocate and initialize a DLPI template of the specified length.  (May be
6067  * called as writer.)
6068  */
6069 mblk_t *
6070 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6071 {
6072 	mblk_t	*mp;
6073 
6074 	mp = allocb(len, BPRI_MED);
6075 	if (!mp)
6076 		return (NULL);
6077 
6078 	/*
6079 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6080 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6081 	 * that other DLPI are M_PROTO.
6082 	 */
6083 	if (prim == DL_INFO_REQ) {
6084 		mp->b_datap->db_type = M_PCPROTO;
6085 	} else {
6086 		mp->b_datap->db_type = M_PROTO;
6087 	}
6088 
6089 	mp->b_wptr = mp->b_rptr + len;
6090 	bzero(mp->b_rptr, len);
6091 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6092 	return (mp);
6093 }
6094 
6095 const char *
6096 dlpi_prim_str(int prim)
6097 {
6098 	switch (prim) {
6099 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6100 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6101 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6102 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6103 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6104 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6105 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6106 	case DL_OK_ACK:		return ("DL_OK_ACK");
6107 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6108 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6109 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6110 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6111 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6112 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6113 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6114 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6115 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6116 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6117 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6118 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6119 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6120 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6121 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6122 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6123 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6124 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6125 	default:		return ("<unknown primitive>");
6126 	}
6127 }
6128 
6129 const char *
6130 dlpi_err_str(int err)
6131 {
6132 	switch (err) {
6133 	case DL_ACCESS:		return ("DL_ACCESS");
6134 	case DL_BADADDR:	return ("DL_BADADDR");
6135 	case DL_BADCORR:	return ("DL_BADCORR");
6136 	case DL_BADDATA:	return ("DL_BADDATA");
6137 	case DL_BADPPA:		return ("DL_BADPPA");
6138 	case DL_BADPRIM:	return ("DL_BADPRIM");
6139 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6140 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6141 	case DL_BADSAP:		return ("DL_BADSAP");
6142 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6143 	case DL_BOUND:		return ("DL_BOUND");
6144 	case DL_INITFAILED:	return ("DL_INITFAILED");
6145 	case DL_NOADDR:		return ("DL_NOADDR");
6146 	case DL_NOTINIT:	return ("DL_NOTINIT");
6147 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6148 	case DL_SYSERR:		return ("DL_SYSERR");
6149 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6150 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6151 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6152 	case DL_TOOMANY:	return ("DL_TOOMANY");
6153 	case DL_NOTENAB:	return ("DL_NOTENAB");
6154 	case DL_BUSY:		return ("DL_BUSY");
6155 	case DL_NOAUTO:		return ("DL_NOAUTO");
6156 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6157 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6158 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6159 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6160 	case DL_PENDING:	return ("DL_PENDING");
6161 	default:		return ("<unknown error>");
6162 	}
6163 }
6164 
6165 /*
6166  * Debug formatting routine.  Returns a character string representation of the
6167  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6168  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6169  *
6170  * Once the ndd table-printing interfaces are removed, this can be changed to
6171  * standard dotted-decimal form.
6172  */
6173 char *
6174 ip_dot_addr(ipaddr_t addr, char *buf)
6175 {
6176 	uint8_t *ap = (uint8_t *)&addr;
6177 
6178 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6179 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6180 	return (buf);
6181 }
6182 
6183 /*
6184  * Write the given MAC address as a printable string in the usual colon-
6185  * separated format.
6186  */
6187 const char *
6188 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6189 {
6190 	char *bp;
6191 
6192 	if (alen == 0 || buflen < 4)
6193 		return ("?");
6194 	bp = buf;
6195 	for (;;) {
6196 		/*
6197 		 * If there are more MAC address bytes available, but we won't
6198 		 * have any room to print them, then add "..." to the string
6199 		 * instead.  See below for the 'magic number' explanation.
6200 		 */
6201 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6202 			(void) strcpy(bp, "...");
6203 			break;
6204 		}
6205 		(void) sprintf(bp, "%02x", *addr++);
6206 		bp += 2;
6207 		if (--alen == 0)
6208 			break;
6209 		*bp++ = ':';
6210 		buflen -= 3;
6211 		/*
6212 		 * At this point, based on the first 'if' statement above,
6213 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6214 		 * buflen >= 4.  The first case leaves room for the final "xx"
6215 		 * number and trailing NUL byte.  The second leaves room for at
6216 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6217 		 * that statement.
6218 		 */
6219 	}
6220 	return (buf);
6221 }
6222 
6223 /*
6224  * Send an ICMP error after patching up the packet appropriately.  Returns
6225  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6226  */
6227 static boolean_t
6228 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6229     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6230     zoneid_t zoneid, ip_stack_t *ipst)
6231 {
6232 	ipha_t *ipha;
6233 	mblk_t *first_mp;
6234 	boolean_t secure;
6235 	unsigned char db_type;
6236 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6237 
6238 	first_mp = mp;
6239 	if (mctl_present) {
6240 		mp = mp->b_cont;
6241 		secure = ipsec_in_is_secure(first_mp);
6242 		ASSERT(mp != NULL);
6243 	} else {
6244 		/*
6245 		 * If this is an ICMP error being reported - which goes
6246 		 * up as M_CTLs, we need to convert them to M_DATA till
6247 		 * we finish checking with global policy because
6248 		 * ipsec_check_global_policy() assumes M_DATA as clear
6249 		 * and M_CTL as secure.
6250 		 */
6251 		db_type = DB_TYPE(mp);
6252 		DB_TYPE(mp) = M_DATA;
6253 		secure = B_FALSE;
6254 	}
6255 	/*
6256 	 * We are generating an icmp error for some inbound packet.
6257 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6258 	 * Before we generate an error, check with global policy
6259 	 * to see whether this is allowed to enter the system. As
6260 	 * there is no "conn", we are checking with global policy.
6261 	 */
6262 	ipha = (ipha_t *)mp->b_rptr;
6263 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6264 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6265 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6266 		if (first_mp == NULL)
6267 			return (B_FALSE);
6268 	}
6269 
6270 	if (!mctl_present)
6271 		DB_TYPE(mp) = db_type;
6272 
6273 	if (flags & IP_FF_SEND_ICMP) {
6274 		if (flags & IP_FF_HDR_COMPLETE) {
6275 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6276 				freemsg(first_mp);
6277 				return (B_TRUE);
6278 			}
6279 		}
6280 		if (flags & IP_FF_CKSUM) {
6281 			/*
6282 			 * Have to correct checksum since
6283 			 * the packet might have been
6284 			 * fragmented and the reassembly code in ip_rput
6285 			 * does not restore the IP checksum.
6286 			 */
6287 			ipha->ipha_hdr_checksum = 0;
6288 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6289 		}
6290 		switch (icmp_type) {
6291 		case ICMP_DEST_UNREACHABLE:
6292 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6293 			    ipst);
6294 			break;
6295 		default:
6296 			freemsg(first_mp);
6297 			break;
6298 		}
6299 	} else {
6300 		freemsg(first_mp);
6301 		return (B_FALSE);
6302 	}
6303 
6304 	return (B_TRUE);
6305 }
6306 
6307 /*
6308  * Used to send an ICMP error message when a packet is received for
6309  * a protocol that is not supported. The mblk passed as argument
6310  * is consumed by this function.
6311  */
6312 void
6313 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6314     ip_stack_t *ipst)
6315 {
6316 	mblk_t *mp;
6317 	ipha_t *ipha;
6318 	ill_t *ill;
6319 	ipsec_in_t *ii;
6320 
6321 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6322 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6323 
6324 	mp = ipsec_mp->b_cont;
6325 	ipsec_mp->b_cont = NULL;
6326 	ipha = (ipha_t *)mp->b_rptr;
6327 	/* Get ill from index in ipsec_in_t. */
6328 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6329 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6330 	    ipst);
6331 	if (ill != NULL) {
6332 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6333 			if (ip_fanout_send_icmp(q, mp, flags,
6334 			    ICMP_DEST_UNREACHABLE,
6335 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6336 				BUMP_MIB(ill->ill_ip_mib,
6337 				    ipIfStatsInUnknownProtos);
6338 			}
6339 		} else {
6340 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6341 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6342 			    0, B_FALSE, zoneid, ipst)) {
6343 				BUMP_MIB(ill->ill_ip_mib,
6344 				    ipIfStatsInUnknownProtos);
6345 			}
6346 		}
6347 		ill_refrele(ill);
6348 	} else { /* re-link for the freemsg() below. */
6349 		ipsec_mp->b_cont = mp;
6350 	}
6351 
6352 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6353 	freemsg(ipsec_mp);
6354 }
6355 
6356 /*
6357  * See if the inbound datagram has had IPsec processing applied to it.
6358  */
6359 boolean_t
6360 ipsec_in_is_secure(mblk_t *ipsec_mp)
6361 {
6362 	ipsec_in_t *ii;
6363 
6364 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6365 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6366 
6367 	if (ii->ipsec_in_loopback) {
6368 		return (ii->ipsec_in_secure);
6369 	} else {
6370 		return (ii->ipsec_in_ah_sa != NULL ||
6371 		    ii->ipsec_in_esp_sa != NULL ||
6372 		    ii->ipsec_in_decaps);
6373 	}
6374 }
6375 
6376 /*
6377  * Handle protocols with which IP is less intimate.  There
6378  * can be more than one stream bound to a particular
6379  * protocol.  When this is the case, normally each one gets a copy
6380  * of any incoming packets.
6381  *
6382  * IPSEC NOTE :
6383  *
6384  * Don't allow a secure packet going up a non-secure connection.
6385  * We don't allow this because
6386  *
6387  * 1) Reply might go out in clear which will be dropped at
6388  *    the sending side.
6389  * 2) If the reply goes out in clear it will give the
6390  *    adversary enough information for getting the key in
6391  *    most of the cases.
6392  *
6393  * Moreover getting a secure packet when we expect clear
6394  * implies that SA's were added without checking for
6395  * policy on both ends. This should not happen once ISAKMP
6396  * is used to negotiate SAs as SAs will be added only after
6397  * verifying the policy.
6398  *
6399  * NOTE : If the packet was tunneled and not multicast we only send
6400  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6401  * back to delivering packets to AF_INET6 raw sockets.
6402  *
6403  * IPQoS Notes:
6404  * Once we have determined the client, invoke IPPF processing.
6405  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6406  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6407  * ip_policy will be false.
6408  *
6409  * Zones notes:
6410  * Currently only applications in the global zone can create raw sockets for
6411  * protocols other than ICMP. So unlike the broadcast / multicast case of
6412  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6413  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6414  */
6415 static void
6416 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6417     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6418     zoneid_t zoneid)
6419 {
6420 	queue_t	*rq;
6421 	mblk_t	*mp1, *first_mp1;
6422 	uint_t	protocol = ipha->ipha_protocol;
6423 	ipaddr_t dst;
6424 	boolean_t one_only;
6425 	mblk_t *first_mp = mp;
6426 	boolean_t secure;
6427 	uint32_t ill_index;
6428 	conn_t	*connp, *first_connp, *next_connp;
6429 	connf_t	*connfp;
6430 	boolean_t shared_addr;
6431 	mib2_ipIfStatsEntry_t *mibptr;
6432 	ip_stack_t *ipst = recv_ill->ill_ipst;
6433 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6434 
6435 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6436 	if (mctl_present) {
6437 		mp = first_mp->b_cont;
6438 		secure = ipsec_in_is_secure(first_mp);
6439 		ASSERT(mp != NULL);
6440 	} else {
6441 		secure = B_FALSE;
6442 	}
6443 	dst = ipha->ipha_dst;
6444 	/*
6445 	 * If the packet was tunneled and not multicast we only send to it
6446 	 * the first match.
6447 	 */
6448 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6449 	    !CLASSD(dst));
6450 
6451 	shared_addr = (zoneid == ALL_ZONES);
6452 	if (shared_addr) {
6453 		/*
6454 		 * We don't allow multilevel ports for raw IP, so no need to
6455 		 * check for that here.
6456 		 */
6457 		zoneid = tsol_packet_to_zoneid(mp);
6458 	}
6459 
6460 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6461 	mutex_enter(&connfp->connf_lock);
6462 	connp = connfp->connf_head;
6463 	for (connp = connfp->connf_head; connp != NULL;
6464 		connp = connp->conn_next) {
6465 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6466 		    zoneid) &&
6467 		    (!is_system_labeled() ||
6468 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6469 		    connp)))
6470 			break;
6471 	}
6472 
6473 	if (connp == NULL || connp->conn_upq == NULL) {
6474 		/*
6475 		 * No one bound to these addresses.  Is
6476 		 * there a client that wants all
6477 		 * unclaimed datagrams?
6478 		 */
6479 		mutex_exit(&connfp->connf_lock);
6480 		/*
6481 		 * Check for IPPROTO_ENCAP...
6482 		 */
6483 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6484 			/*
6485 			 * If an IPsec mblk is here on a multicast
6486 			 * tunnel (using ip_mroute stuff), check policy here,
6487 			 * THEN ship off to ip_mroute_decap().
6488 			 *
6489 			 * BTW,  If I match a configured IP-in-IP
6490 			 * tunnel, this path will not be reached, and
6491 			 * ip_mroute_decap will never be called.
6492 			 */
6493 			first_mp = ipsec_check_global_policy(first_mp, connp,
6494 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6495 			if (first_mp != NULL) {
6496 				if (mctl_present)
6497 					freeb(first_mp);
6498 				ip_mroute_decap(q, mp, ill);
6499 			} /* Else we already freed everything! */
6500 		} else {
6501 			/*
6502 			 * Otherwise send an ICMP protocol unreachable.
6503 			 */
6504 			if (ip_fanout_send_icmp(q, first_mp, flags,
6505 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6506 			    mctl_present, zoneid, ipst)) {
6507 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6508 			}
6509 		}
6510 		return;
6511 	}
6512 	CONN_INC_REF(connp);
6513 	first_connp = connp;
6514 
6515 	/*
6516 	 * Only send message to one tunnel driver by immediately
6517 	 * terminating the loop.
6518 	 */
6519 	connp = one_only ? NULL : connp->conn_next;
6520 
6521 	for (;;) {
6522 		while (connp != NULL) {
6523 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6524 			    flags, zoneid) &&
6525 			    (!is_system_labeled() ||
6526 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6527 			    shared_addr, connp)))
6528 				break;
6529 			connp = connp->conn_next;
6530 		}
6531 
6532 		/*
6533 		 * Copy the packet.
6534 		 */
6535 		if (connp == NULL || connp->conn_upq == NULL ||
6536 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6537 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6538 			/*
6539 			 * No more interested clients or memory
6540 			 * allocation failed
6541 			 */
6542 			connp = first_connp;
6543 			break;
6544 		}
6545 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6546 		CONN_INC_REF(connp);
6547 		mutex_exit(&connfp->connf_lock);
6548 		rq = connp->conn_rq;
6549 		if (!canputnext(rq)) {
6550 			if (flags & IP_FF_RAWIP) {
6551 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6552 			} else {
6553 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6554 			}
6555 
6556 			freemsg(first_mp1);
6557 		} else {
6558 			/*
6559 			 * Don't enforce here if we're an actual tunnel -
6560 			 * let "tun" do it instead.
6561 			 */
6562 			if (!IPCL_IS_IPTUN(connp) &&
6563 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6564 			    secure)) {
6565 				first_mp1 = ipsec_check_inbound_policy
6566 				    (first_mp1, connp, ipha, NULL,
6567 				    mctl_present);
6568 			}
6569 			if (first_mp1 != NULL) {
6570 				int in_flags = 0;
6571 				/*
6572 				 * ip_fanout_proto also gets called from
6573 				 * icmp_inbound_error_fanout, in which case
6574 				 * the msg type is M_CTL.  Don't add info
6575 				 * in this case for the time being. In future
6576 				 * when there is a need for knowing the
6577 				 * inbound iface index for ICMP error msgs,
6578 				 * then this can be changed.
6579 				 */
6580 				if (connp->conn_recvif)
6581 					in_flags = IPF_RECVIF;
6582 				/*
6583 				 * The ULP may support IP_RECVPKTINFO for both
6584 				 * IP v4 and v6 so pass the appropriate argument
6585 				 * based on conn IP version.
6586 				 */
6587 				if (connp->conn_ip_recvpktinfo) {
6588 					if (connp->conn_af_isv6) {
6589 						/*
6590 						 * V6 only needs index
6591 						 */
6592 						in_flags |= IPF_RECVIF;
6593 					} else {
6594 						/*
6595 						 * V4 needs index +
6596 						 * matching address.
6597 						 */
6598 						in_flags |= IPF_RECVADDR;
6599 					}
6600 				}
6601 				if ((in_flags != 0) &&
6602 				    (mp->b_datap->db_type != M_CTL)) {
6603 					/*
6604 					 * the actual data will be
6605 					 * contained in b_cont upon
6606 					 * successful return of the
6607 					 * following call else
6608 					 * original mblk is returned
6609 					 */
6610 					ASSERT(recv_ill != NULL);
6611 					mp1 = ip_add_info(mp1, recv_ill,
6612 					    in_flags, IPCL_ZONEID(connp), ipst);
6613 				}
6614 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6615 				if (mctl_present)
6616 					freeb(first_mp1);
6617 				putnext(rq, mp1);
6618 			}
6619 		}
6620 		mutex_enter(&connfp->connf_lock);
6621 		/* Follow the next pointer before releasing the conn. */
6622 		next_connp = connp->conn_next;
6623 		CONN_DEC_REF(connp);
6624 		connp = next_connp;
6625 	}
6626 
6627 	/* Last one.  Send it upstream. */
6628 	mutex_exit(&connfp->connf_lock);
6629 
6630 	/*
6631 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6632 	 * will be set to false.
6633 	 */
6634 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6635 		ill_index = ill->ill_phyint->phyint_ifindex;
6636 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6637 		if (mp == NULL) {
6638 			CONN_DEC_REF(connp);
6639 			if (mctl_present) {
6640 				freeb(first_mp);
6641 			}
6642 			return;
6643 		}
6644 	}
6645 
6646 	rq = connp->conn_rq;
6647 	if (!canputnext(rq)) {
6648 		if (flags & IP_FF_RAWIP) {
6649 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6650 		} else {
6651 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6652 		}
6653 
6654 		freemsg(first_mp);
6655 	} else {
6656 		if (IPCL_IS_IPTUN(connp)) {
6657 			/*
6658 			 * Tunneled packet.  We enforce policy in the tunnel
6659 			 * module itself.
6660 			 *
6661 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6662 			 * a policy check.
6663 			 */
6664 			putnext(rq, first_mp);
6665 			CONN_DEC_REF(connp);
6666 			return;
6667 		}
6668 
6669 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6670 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6671 			    ipha, NULL, mctl_present);
6672 		}
6673 
6674 		if (first_mp != NULL) {
6675 			int in_flags = 0;
6676 
6677 			/*
6678 			 * ip_fanout_proto also gets called
6679 			 * from icmp_inbound_error_fanout, in
6680 			 * which case the msg type is M_CTL.
6681 			 * Don't add info in this case for time
6682 			 * being. In future when there is a
6683 			 * need for knowing the inbound iface
6684 			 * index for ICMP error msgs, then this
6685 			 * can be changed
6686 			 */
6687 			if (connp->conn_recvif)
6688 				in_flags = IPF_RECVIF;
6689 			if (connp->conn_ip_recvpktinfo) {
6690 				if (connp->conn_af_isv6) {
6691 					/*
6692 					 * V6 only needs index
6693 					 */
6694 					in_flags |= IPF_RECVIF;
6695 				} else {
6696 					/*
6697 					 * V4 needs index +
6698 					 * matching address.
6699 					 */
6700 					in_flags |= IPF_RECVADDR;
6701 				}
6702 			}
6703 			if ((in_flags != 0) &&
6704 			    (mp->b_datap->db_type != M_CTL)) {
6705 
6706 				/*
6707 				 * the actual data will be contained in
6708 				 * b_cont upon successful return
6709 				 * of the following call else original
6710 				 * mblk is returned
6711 				 */
6712 				ASSERT(recv_ill != NULL);
6713 				mp = ip_add_info(mp, recv_ill,
6714 				    in_flags, IPCL_ZONEID(connp), ipst);
6715 			}
6716 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6717 			putnext(rq, mp);
6718 			if (mctl_present)
6719 				freeb(first_mp);
6720 		}
6721 	}
6722 	CONN_DEC_REF(connp);
6723 }
6724 
6725 /*
6726  * Fanout for TCP packets
6727  * The caller puts <fport, lport> in the ports parameter.
6728  *
6729  * IPQoS Notes
6730  * Before sending it to the client, invoke IPPF processing.
6731  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6732  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6733  * ip_policy is false.
6734  */
6735 static void
6736 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6737     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6738 {
6739 	mblk_t  *first_mp;
6740 	boolean_t secure;
6741 	uint32_t ill_index;
6742 	int	ip_hdr_len;
6743 	tcph_t	*tcph;
6744 	boolean_t syn_present = B_FALSE;
6745 	conn_t	*connp;
6746 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6747 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6748 
6749 	ASSERT(recv_ill != NULL);
6750 
6751 	first_mp = mp;
6752 	if (mctl_present) {
6753 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6754 		mp = first_mp->b_cont;
6755 		secure = ipsec_in_is_secure(first_mp);
6756 		ASSERT(mp != NULL);
6757 	} else {
6758 		secure = B_FALSE;
6759 	}
6760 
6761 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6762 
6763 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6764 		    zoneid, ipst)) == NULL) {
6765 		/*
6766 		 * No connected connection or listener. Send a
6767 		 * TH_RST via tcp_xmit_listeners_reset.
6768 		 */
6769 
6770 		/* Initiate IPPf processing, if needed. */
6771 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6772 			uint32_t ill_index;
6773 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6774 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6775 			if (first_mp == NULL)
6776 				return;
6777 		}
6778 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6779 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6780 		    zoneid));
6781 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6782 		    ipst->ips_netstack->netstack_tcp);
6783 		return;
6784 	}
6785 
6786 	/*
6787 	 * Allocate the SYN for the TCP connection here itself
6788 	 */
6789 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6790 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6791 		if (IPCL_IS_TCP(connp)) {
6792 			squeue_t *sqp;
6793 
6794 			/*
6795 			 * For fused tcp loopback, assign the eager's
6796 			 * squeue to be that of the active connect's.
6797 			 * Note that we don't check for IP_FF_LOOPBACK
6798 			 * here since this routine gets called only
6799 			 * for loopback (unlike the IPv6 counterpart).
6800 			 */
6801 			ASSERT(Q_TO_CONN(q) != NULL);
6802 			if (do_tcp_fusion &&
6803 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6804 			    !secure &&
6805 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6806 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6807 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6808 				sqp = Q_TO_CONN(q)->conn_sqp;
6809 			} else {
6810 				sqp = IP_SQUEUE_GET(lbolt);
6811 			}
6812 
6813 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6814 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6815 			syn_present = B_TRUE;
6816 		}
6817 	}
6818 
6819 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6820 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6821 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6822 		if ((flags & TH_RST) || (flags & TH_URG)) {
6823 			CONN_DEC_REF(connp);
6824 			freemsg(first_mp);
6825 			return;
6826 		}
6827 		if (flags & TH_ACK) {
6828 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6829 			    ipst->ips_netstack->netstack_tcp);
6830 			CONN_DEC_REF(connp);
6831 			return;
6832 		}
6833 
6834 		CONN_DEC_REF(connp);
6835 		freemsg(first_mp);
6836 		return;
6837 	}
6838 
6839 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6840 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6841 		    NULL, mctl_present);
6842 		if (first_mp == NULL) {
6843 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6844 			CONN_DEC_REF(connp);
6845 			return;
6846 		}
6847 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6848 			ASSERT(syn_present);
6849 			if (mctl_present) {
6850 				ASSERT(first_mp != mp);
6851 				first_mp->b_datap->db_struioflag |=
6852 				    STRUIO_POLICY;
6853 			} else {
6854 				ASSERT(first_mp == mp);
6855 				mp->b_datap->db_struioflag &=
6856 				    ~STRUIO_EAGER;
6857 				mp->b_datap->db_struioflag |=
6858 				    STRUIO_POLICY;
6859 			}
6860 		} else {
6861 			/*
6862 			 * Discard first_mp early since we're dealing with a
6863 			 * fully-connected conn_t and tcp doesn't do policy in
6864 			 * this case.
6865 			 */
6866 			if (mctl_present) {
6867 				freeb(first_mp);
6868 				mctl_present = B_FALSE;
6869 			}
6870 			first_mp = mp;
6871 		}
6872 	}
6873 
6874 	/*
6875 	 * Initiate policy processing here if needed. If we get here from
6876 	 * icmp_inbound_error_fanout, ip_policy is false.
6877 	 */
6878 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6879 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6880 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6881 		if (mp == NULL) {
6882 			CONN_DEC_REF(connp);
6883 			if (mctl_present)
6884 				freeb(first_mp);
6885 			return;
6886 		} else if (mctl_present) {
6887 			ASSERT(first_mp != mp);
6888 			first_mp->b_cont = mp;
6889 		} else {
6890 			first_mp = mp;
6891 		}
6892 	}
6893 
6894 
6895 
6896 	/* Handle socket options. */
6897 	if (!syn_present &&
6898 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6899 		/* Add header */
6900 		ASSERT(recv_ill != NULL);
6901 		/*
6902 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6903 		 * IPF_RECVIF.
6904 		 */
6905 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6906 		    ipst);
6907 		if (mp == NULL) {
6908 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6909 			CONN_DEC_REF(connp);
6910 			if (mctl_present)
6911 				freeb(first_mp);
6912 			return;
6913 		} else if (mctl_present) {
6914 			/*
6915 			 * ip_add_info might return a new mp.
6916 			 */
6917 			ASSERT(first_mp != mp);
6918 			first_mp->b_cont = mp;
6919 		} else {
6920 			first_mp = mp;
6921 		}
6922 	}
6923 
6924 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6925 	if (IPCL_IS_TCP(connp)) {
6926 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6927 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6928 	} else {
6929 		putnext(connp->conn_rq, first_mp);
6930 		CONN_DEC_REF(connp);
6931 	}
6932 }
6933 
6934 /*
6935  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6936  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6937  * Caller is responsible for dropping references to the conn, and freeing
6938  * first_mp.
6939  *
6940  * IPQoS Notes
6941  * Before sending it to the client, invoke IPPF processing. Policy processing
6942  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6943  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6944  * ip_wput_local, ip_policy is false.
6945  */
6946 static void
6947 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6948     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6949     boolean_t ip_policy)
6950 {
6951 	boolean_t	mctl_present = (first_mp != NULL);
6952 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6953 	uint32_t	ill_index;
6954 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6955 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6956 
6957 	ASSERT(ill != NULL);
6958 
6959 	if (mctl_present)
6960 		first_mp->b_cont = mp;
6961 	else
6962 		first_mp = mp;
6963 
6964 	if (CONN_UDP_FLOWCTLD(connp)) {
6965 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6966 		freemsg(first_mp);
6967 		return;
6968 	}
6969 
6970 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6971 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6972 		    NULL, mctl_present);
6973 		if (first_mp == NULL) {
6974 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6975 			return;	/* Freed by ipsec_check_inbound_policy(). */
6976 		}
6977 	}
6978 	if (mctl_present)
6979 		freeb(first_mp);
6980 
6981 	/* Handle options. */
6982 	if (connp->conn_recvif)
6983 		in_flags = IPF_RECVIF;
6984 	/*
6985 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6986 	 * passed to ip_add_info is based on IP version of connp.
6987 	 */
6988 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6989 		if (connp->conn_af_isv6) {
6990 			/*
6991 			 * V6 only needs index
6992 			 */
6993 			in_flags |= IPF_RECVIF;
6994 		} else {
6995 			/*
6996 			 * V4 needs index + matching address.
6997 			 */
6998 			in_flags |= IPF_RECVADDR;
6999 		}
7000 	}
7001 
7002 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7003 		in_flags |= IPF_RECVSLLA;
7004 
7005 	/*
7006 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7007 	 * freed if the packet is dropped. The caller will do so.
7008 	 */
7009 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7010 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7011 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7012 		if (mp == NULL) {
7013 			return;
7014 		}
7015 	}
7016 	if ((in_flags != 0) &&
7017 	    (mp->b_datap->db_type != M_CTL)) {
7018 		/*
7019 		 * The actual data will be contained in b_cont
7020 		 * upon successful return of the following call
7021 		 * else original mblk is returned
7022 		 */
7023 		ASSERT(recv_ill != NULL);
7024 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7025 		    ipst);
7026 	}
7027 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7028 	/* Send it upstream */
7029 	CONN_UDP_RECV(connp, mp);
7030 }
7031 
7032 /*
7033  * Fanout for UDP packets.
7034  * The caller puts <fport, lport> in the ports parameter.
7035  *
7036  * If SO_REUSEADDR is set all multicast and broadcast packets
7037  * will be delivered to all streams bound to the same port.
7038  *
7039  * Zones notes:
7040  * Multicast and broadcast packets will be distributed to streams in all zones.
7041  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7042  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7043  * packets. To maintain this behavior with multiple zones, the conns are grouped
7044  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7045  * each zone. If unset, all the following conns in the same zone are skipped.
7046  */
7047 static void
7048 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7049     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7050     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7051 {
7052 	uint32_t	dstport, srcport;
7053 	ipaddr_t	dst;
7054 	mblk_t		*first_mp;
7055 	boolean_t	secure;
7056 	in6_addr_t	v6src;
7057 	conn_t		*connp;
7058 	connf_t		*connfp;
7059 	conn_t		*first_connp;
7060 	conn_t		*next_connp;
7061 	mblk_t		*mp1, *first_mp1;
7062 	ipaddr_t	src;
7063 	zoneid_t	last_zoneid;
7064 	boolean_t	reuseaddr;
7065 	boolean_t	shared_addr;
7066 	ip_stack_t	*ipst;
7067 
7068 	ASSERT(recv_ill != NULL);
7069 	ipst = recv_ill->ill_ipst;
7070 
7071 	first_mp = mp;
7072 	if (mctl_present) {
7073 		mp = first_mp->b_cont;
7074 		first_mp->b_cont = NULL;
7075 		secure = ipsec_in_is_secure(first_mp);
7076 		ASSERT(mp != NULL);
7077 	} else {
7078 		first_mp = NULL;
7079 		secure = B_FALSE;
7080 	}
7081 
7082 	/* Extract ports in net byte order */
7083 	dstport = htons(ntohl(ports) & 0xFFFF);
7084 	srcport = htons(ntohl(ports) >> 16);
7085 	dst = ipha->ipha_dst;
7086 	src = ipha->ipha_src;
7087 
7088 	shared_addr = (zoneid == ALL_ZONES);
7089 	if (shared_addr) {
7090 		/*
7091 		 * No need to handle exclusive-stack zones since ALL_ZONES
7092 		 * only applies to the shared stack.
7093 		 */
7094 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7095 		if (zoneid == ALL_ZONES)
7096 			zoneid = tsol_packet_to_zoneid(mp);
7097 	}
7098 
7099 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7100 	mutex_enter(&connfp->connf_lock);
7101 	connp = connfp->connf_head;
7102 	if (!broadcast && !CLASSD(dst)) {
7103 		/*
7104 		 * Not broadcast or multicast. Send to the one (first)
7105 		 * client we find. No need to check conn_wantpacket()
7106 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7107 		 * IPv4 unicast packets.
7108 		 */
7109 		while ((connp != NULL) &&
7110 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7111 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7112 			connp = connp->conn_next;
7113 		}
7114 
7115 		if (connp == NULL || connp->conn_upq == NULL)
7116 			goto notfound;
7117 
7118 		if (is_system_labeled() &&
7119 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7120 		    connp))
7121 			goto notfound;
7122 
7123 		CONN_INC_REF(connp);
7124 		mutex_exit(&connfp->connf_lock);
7125 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7126 		    flags, recv_ill, ip_policy);
7127 		IP_STAT(ipst, ip_udp_fannorm);
7128 		CONN_DEC_REF(connp);
7129 		return;
7130 	}
7131 
7132 	/*
7133 	 * Broadcast and multicast case
7134 	 *
7135 	 * Need to check conn_wantpacket().
7136 	 * If SO_REUSEADDR has been set on the first we send the
7137 	 * packet to all clients that have joined the group and
7138 	 * match the port.
7139 	 */
7140 
7141 	while (connp != NULL) {
7142 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7143 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7144 		    (!is_system_labeled() ||
7145 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7146 		    connp)))
7147 			break;
7148 		connp = connp->conn_next;
7149 	}
7150 
7151 	if (connp == NULL || connp->conn_upq == NULL)
7152 		goto notfound;
7153 
7154 	first_connp = connp;
7155 	/*
7156 	 * When SO_REUSEADDR is not set, send the packet only to the first
7157 	 * matching connection in its zone by keeping track of the zoneid.
7158 	 */
7159 	reuseaddr = first_connp->conn_reuseaddr;
7160 	last_zoneid = first_connp->conn_zoneid;
7161 
7162 	CONN_INC_REF(connp);
7163 	connp = connp->conn_next;
7164 	for (;;) {
7165 		while (connp != NULL) {
7166 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7167 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7168 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7169 			    (!is_system_labeled() ||
7170 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7171 			    shared_addr, connp)))
7172 				break;
7173 			connp = connp->conn_next;
7174 		}
7175 		/*
7176 		 * Just copy the data part alone. The mctl part is
7177 		 * needed just for verifying policy and it is never
7178 		 * sent up.
7179 		 */
7180 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7181 		    ((mp1 = copymsg(mp)) == NULL))) {
7182 			/*
7183 			 * No more interested clients or memory
7184 			 * allocation failed
7185 			 */
7186 			connp = first_connp;
7187 			break;
7188 		}
7189 		if (connp->conn_zoneid != last_zoneid) {
7190 			/*
7191 			 * Update the zoneid so that the packet isn't sent to
7192 			 * any more conns in the same zone unless SO_REUSEADDR
7193 			 * is set.
7194 			 */
7195 			reuseaddr = connp->conn_reuseaddr;
7196 			last_zoneid = connp->conn_zoneid;
7197 		}
7198 		if (first_mp != NULL) {
7199 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7200 			    ipsec_info_type == IPSEC_IN);
7201 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7202 			    ipst->ips_netstack);
7203 			if (first_mp1 == NULL) {
7204 				freemsg(mp1);
7205 				connp = first_connp;
7206 				break;
7207 			}
7208 		} else {
7209 			first_mp1 = NULL;
7210 		}
7211 		CONN_INC_REF(connp);
7212 		mutex_exit(&connfp->connf_lock);
7213 		/*
7214 		 * IPQoS notes: We don't send the packet for policy
7215 		 * processing here, will do it for the last one (below).
7216 		 * i.e. we do it per-packet now, but if we do policy
7217 		 * processing per-conn, then we would need to do it
7218 		 * here too.
7219 		 */
7220 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7221 		    ipha, flags, recv_ill, B_FALSE);
7222 		mutex_enter(&connfp->connf_lock);
7223 		/* Follow the next pointer before releasing the conn. */
7224 		next_connp = connp->conn_next;
7225 		IP_STAT(ipst, ip_udp_fanmb);
7226 		CONN_DEC_REF(connp);
7227 		connp = next_connp;
7228 	}
7229 
7230 	/* Last one.  Send it upstream. */
7231 	mutex_exit(&connfp->connf_lock);
7232 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7233 	    recv_ill, ip_policy);
7234 	IP_STAT(ipst, ip_udp_fanmb);
7235 	CONN_DEC_REF(connp);
7236 	return;
7237 
7238 notfound:
7239 
7240 	mutex_exit(&connfp->connf_lock);
7241 	IP_STAT(ipst, ip_udp_fanothers);
7242 	/*
7243 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7244 	 * have already been matched above, since they live in the IPv4
7245 	 * fanout tables. This implies we only need to
7246 	 * check for IPv6 in6addr_any endpoints here.
7247 	 * Thus we compare using ipv6_all_zeros instead of the destination
7248 	 * address, except for the multicast group membership lookup which
7249 	 * uses the IPv4 destination.
7250 	 */
7251 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7252 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7253 	mutex_enter(&connfp->connf_lock);
7254 	connp = connfp->connf_head;
7255 	if (!broadcast && !CLASSD(dst)) {
7256 		while (connp != NULL) {
7257 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7258 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7259 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7260 			    !connp->conn_ipv6_v6only)
7261 				break;
7262 			connp = connp->conn_next;
7263 		}
7264 
7265 		if (connp != NULL && is_system_labeled() &&
7266 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7267 		    connp))
7268 			connp = NULL;
7269 
7270 		if (connp == NULL || connp->conn_upq == NULL) {
7271 			/*
7272 			 * No one bound to this port.  Is
7273 			 * there a client that wants all
7274 			 * unclaimed datagrams?
7275 			 */
7276 			mutex_exit(&connfp->connf_lock);
7277 
7278 			if (mctl_present)
7279 				first_mp->b_cont = mp;
7280 			else
7281 				first_mp = mp;
7282 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7283 			    connf_head != NULL) {
7284 				ip_fanout_proto(q, first_mp, ill, ipha,
7285 				    flags | IP_FF_RAWIP, mctl_present,
7286 				    ip_policy, recv_ill, zoneid);
7287 			} else {
7288 				if (ip_fanout_send_icmp(q, first_mp, flags,
7289 				    ICMP_DEST_UNREACHABLE,
7290 				    ICMP_PORT_UNREACHABLE,
7291 				    mctl_present, zoneid, ipst)) {
7292 					BUMP_MIB(ill->ill_ip_mib,
7293 					    udpIfStatsNoPorts);
7294 				}
7295 			}
7296 			return;
7297 		}
7298 
7299 		CONN_INC_REF(connp);
7300 		mutex_exit(&connfp->connf_lock);
7301 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7302 		    flags, recv_ill, ip_policy);
7303 		CONN_DEC_REF(connp);
7304 		return;
7305 	}
7306 	/*
7307 	 * IPv4 multicast packet being delivered to an AF_INET6
7308 	 * in6addr_any endpoint.
7309 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7310 	 * and not conn_wantpacket_v6() since any multicast membership is
7311 	 * for an IPv4-mapped multicast address.
7312 	 * The packet is sent to all clients in all zones that have joined the
7313 	 * group and match the port.
7314 	 */
7315 	while (connp != NULL) {
7316 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7317 		    srcport, v6src) &&
7318 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7319 		    (!is_system_labeled() ||
7320 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7321 		    connp)))
7322 			break;
7323 		connp = connp->conn_next;
7324 	}
7325 
7326 	if (connp == NULL || connp->conn_upq == NULL) {
7327 		/*
7328 		 * No one bound to this port.  Is
7329 		 * there a client that wants all
7330 		 * unclaimed datagrams?
7331 		 */
7332 		mutex_exit(&connfp->connf_lock);
7333 
7334 		if (mctl_present)
7335 			first_mp->b_cont = mp;
7336 		else
7337 			first_mp = mp;
7338 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7339 		    NULL) {
7340 			ip_fanout_proto(q, first_mp, ill, ipha,
7341 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7342 			    recv_ill, zoneid);
7343 		} else {
7344 			/*
7345 			 * We used to attempt to send an icmp error here, but
7346 			 * since this is known to be a multicast packet
7347 			 * and we don't send icmp errors in response to
7348 			 * multicast, just drop the packet and give up sooner.
7349 			 */
7350 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7351 			freemsg(first_mp);
7352 		}
7353 		return;
7354 	}
7355 
7356 	first_connp = connp;
7357 
7358 	CONN_INC_REF(connp);
7359 	connp = connp->conn_next;
7360 	for (;;) {
7361 		while (connp != NULL) {
7362 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7363 			    ipv6_all_zeros, srcport, v6src) &&
7364 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7365 			    (!is_system_labeled() ||
7366 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7367 			    shared_addr, connp)))
7368 				break;
7369 			connp = connp->conn_next;
7370 		}
7371 		/*
7372 		 * Just copy the data part alone. The mctl part is
7373 		 * needed just for verifying policy and it is never
7374 		 * sent up.
7375 		 */
7376 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7377 		    ((mp1 = copymsg(mp)) == NULL))) {
7378 			/*
7379 			 * No more intested clients or memory
7380 			 * allocation failed
7381 			 */
7382 			connp = first_connp;
7383 			break;
7384 		}
7385 		if (first_mp != NULL) {
7386 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7387 			    ipsec_info_type == IPSEC_IN);
7388 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7389 			    ipst->ips_netstack);
7390 			if (first_mp1 == NULL) {
7391 				freemsg(mp1);
7392 				connp = first_connp;
7393 				break;
7394 			}
7395 		} else {
7396 			first_mp1 = NULL;
7397 		}
7398 		CONN_INC_REF(connp);
7399 		mutex_exit(&connfp->connf_lock);
7400 		/*
7401 		 * IPQoS notes: We don't send the packet for policy
7402 		 * processing here, will do it for the last one (below).
7403 		 * i.e. we do it per-packet now, but if we do policy
7404 		 * processing per-conn, then we would need to do it
7405 		 * here too.
7406 		 */
7407 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7408 		    ipha, flags, recv_ill, B_FALSE);
7409 		mutex_enter(&connfp->connf_lock);
7410 		/* Follow the next pointer before releasing the conn. */
7411 		next_connp = connp->conn_next;
7412 		CONN_DEC_REF(connp);
7413 		connp = next_connp;
7414 	}
7415 
7416 	/* Last one.  Send it upstream. */
7417 	mutex_exit(&connfp->connf_lock);
7418 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7419 	    recv_ill, ip_policy);
7420 	CONN_DEC_REF(connp);
7421 }
7422 
7423 /*
7424  * Complete the ip_wput header so that it
7425  * is possible to generate ICMP
7426  * errors.
7427  */
7428 int
7429 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7430 {
7431 	ire_t *ire;
7432 
7433 	if (ipha->ipha_src == INADDR_ANY) {
7434 		ire = ire_lookup_local(zoneid, ipst);
7435 		if (ire == NULL) {
7436 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7437 			return (1);
7438 		}
7439 		ipha->ipha_src = ire->ire_addr;
7440 		ire_refrele(ire);
7441 	}
7442 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7443 	ipha->ipha_hdr_checksum = 0;
7444 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7445 	return (0);
7446 }
7447 
7448 /*
7449  * Nobody should be sending
7450  * packets up this stream
7451  */
7452 static void
7453 ip_lrput(queue_t *q, mblk_t *mp)
7454 {
7455 	mblk_t *mp1;
7456 
7457 	switch (mp->b_datap->db_type) {
7458 	case M_FLUSH:
7459 		/* Turn around */
7460 		if (*mp->b_rptr & FLUSHW) {
7461 			*mp->b_rptr &= ~FLUSHR;
7462 			qreply(q, mp);
7463 			return;
7464 		}
7465 		break;
7466 	}
7467 	/* Could receive messages that passed through ar_rput */
7468 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7469 		mp1->b_prev = mp1->b_next = NULL;
7470 	freemsg(mp);
7471 }
7472 
7473 /* Nobody should be sending packets down this stream */
7474 /* ARGSUSED */
7475 void
7476 ip_lwput(queue_t *q, mblk_t *mp)
7477 {
7478 	freemsg(mp);
7479 }
7480 
7481 /*
7482  * Move the first hop in any source route to ipha_dst and remove that part of
7483  * the source route.  Called by other protocols.  Errors in option formatting
7484  * are ignored - will be handled by ip_wput_options Return the final
7485  * destination (either ipha_dst or the last entry in a source route.)
7486  */
7487 ipaddr_t
7488 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7489 {
7490 	ipoptp_t	opts;
7491 	uchar_t		*opt;
7492 	uint8_t		optval;
7493 	uint8_t		optlen;
7494 	ipaddr_t	dst;
7495 	int		i;
7496 	ire_t		*ire;
7497 	ip_stack_t	*ipst = ns->netstack_ip;
7498 
7499 	ip2dbg(("ip_massage_options\n"));
7500 	dst = ipha->ipha_dst;
7501 	for (optval = ipoptp_first(&opts, ipha);
7502 	    optval != IPOPT_EOL;
7503 	    optval = ipoptp_next(&opts)) {
7504 		opt = opts.ipoptp_cur;
7505 		switch (optval) {
7506 			uint8_t off;
7507 		case IPOPT_SSRR:
7508 		case IPOPT_LSRR:
7509 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7510 				ip1dbg(("ip_massage_options: bad src route\n"));
7511 				break;
7512 			}
7513 			optlen = opts.ipoptp_len;
7514 			off = opt[IPOPT_OFFSET];
7515 			off--;
7516 		redo_srr:
7517 			if (optlen < IP_ADDR_LEN ||
7518 			    off > optlen - IP_ADDR_LEN) {
7519 				/* End of source route */
7520 				ip1dbg(("ip_massage_options: end of SR\n"));
7521 				break;
7522 			}
7523 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7524 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7525 			    ntohl(dst)));
7526 			/*
7527 			 * Check if our address is present more than
7528 			 * once as consecutive hops in source route.
7529 			 * XXX verify per-interface ip_forwarding
7530 			 * for source route?
7531 			 */
7532 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7533 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7534 			if (ire != NULL) {
7535 				ire_refrele(ire);
7536 				off += IP_ADDR_LEN;
7537 				goto redo_srr;
7538 			}
7539 			if (dst == htonl(INADDR_LOOPBACK)) {
7540 				ip1dbg(("ip_massage_options: loopback addr in "
7541 				    "source route!\n"));
7542 				break;
7543 			}
7544 			/*
7545 			 * Update ipha_dst to be the first hop and remove the
7546 			 * first hop from the source route (by overwriting
7547 			 * part of the option with NOP options).
7548 			 */
7549 			ipha->ipha_dst = dst;
7550 			/* Put the last entry in dst */
7551 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7552 			    3;
7553 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7554 
7555 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7556 			    ntohl(dst)));
7557 			/* Move down and overwrite */
7558 			opt[IP_ADDR_LEN] = opt[0];
7559 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7560 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7561 			for (i = 0; i < IP_ADDR_LEN; i++)
7562 				opt[i] = IPOPT_NOP;
7563 			break;
7564 		}
7565 	}
7566 	return (dst);
7567 }
7568 
7569 /*
7570  * This function's job is to forward data to the reverse tunnel (FA->HA)
7571  * after doing a few checks. It is assumed that the incoming interface
7572  * of the packet is always different than the outgoing interface and the
7573  * ire_type of the found ire has to be a non-resolver type.
7574  *
7575  * IPQoS notes
7576  * IP policy is invoked twice for a forwarded packet, once on the read side
7577  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7578  * enabled.
7579  */
7580 static void
7581 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7582 {
7583 	ipha_t		*ipha;
7584 	queue_t		*q;
7585 	uint32_t 	pkt_len;
7586 #define	rptr    ((uchar_t *)ipha)
7587 	uint32_t 	sum;
7588 	uint32_t 	max_frag;
7589 	mblk_t		*first_mp;
7590 	uint32_t	ill_index;
7591 	ipxmit_state_t	pktxmit_state;
7592 	ill_t		*out_ill;
7593 	ip_stack_t	*ipst = in_ill->ill_ipst;
7594 
7595 	ASSERT(ire != NULL);
7596 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7597 	ASSERT(ire->ire_stq != NULL);
7598 
7599 	/* Initiate read side IPPF processing */
7600 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
7601 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7602 		ip_process(IPP_FWD_IN, &mp, ill_index);
7603 		if (mp == NULL) {
7604 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7605 			    "dropped during IPPF processing\n"));
7606 			return;
7607 		}
7608 	}
7609 
7610 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7611 		ILLF_ROUTER) == 0) ||
7612 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7613 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7614 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7615 		    "forwarding is not turned on\n"));
7616 		goto drop_pkt;
7617 	}
7618 
7619 	/*
7620 	 * Don't forward if the interface is down
7621 	 */
7622 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7623 		goto discard_pkt;
7624 	}
7625 
7626 	ipha = (ipha_t *)mp->b_rptr;
7627 	pkt_len = ntohs(ipha->ipha_length);
7628 	/* Adjust the checksum to reflect the ttl decrement. */
7629 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7630 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7631 	if (ipha->ipha_ttl-- <= 1) {
7632 		if (ip_csum_hdr(ipha)) {
7633 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7634 			goto drop_pkt;
7635 		}
7636 		q = ire->ire_stq;
7637 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7638 		    BPRI_HI)) == NULL) {
7639 			goto discard_pkt;
7640 		}
7641 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7642 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7643 		/* Sent by forwarding path, and router is global zone */
7644 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7645 		    GLOBAL_ZONEID, ipst);
7646 		return;
7647 	}
7648 
7649 	/* Get the ill_index of the ILL */
7650 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7651 
7652 	/*
7653 	 * This location is chosen for the placement of the forwarding hook
7654 	 * because at this point we know that we have a path out for the
7655 	 * packet but haven't yet applied any logic (such as fragmenting)
7656 	 * that happen as part of transmitting the packet out.
7657 	 */
7658 	out_ill = ire->ire_ipif->ipif_ill;
7659 
7660 	DTRACE_PROBE4(ip4__forwarding__start,
7661 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7662 
7663 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
7664 	    ipst->ips_ipv4firewall_forwarding,
7665 	    in_ill, out_ill, ipha, mp, mp, ipst);
7666 
7667 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7668 
7669 	if (mp == NULL)
7670 		return;
7671 	pkt_len = ntohs(ipha->ipha_length);
7672 
7673 	/*
7674 	 * ip_mrtun_forward is only used by foreign agent to reverse
7675 	 * tunnel the incoming packet. So it does not do any option
7676 	 * processing for source routing.
7677 	 */
7678 	max_frag = ire->ire_max_frag;
7679 	if (pkt_len > max_frag) {
7680 		/*
7681 		 * It needs fragging on its way out.  We haven't
7682 		 * verified the header checksum yet.  Since we
7683 		 * are going to put a surely good checksum in the
7684 		 * outgoing header, we have to make sure that it
7685 		 * was good coming in.
7686 		 */
7687 		if (ip_csum_hdr(ipha)) {
7688 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7689 			goto drop_pkt;
7690 		}
7691 
7692 		/* Initiate write side IPPF processing */
7693 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
7694 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7695 			if (mp == NULL) {
7696 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7697 				    "dropped/deferred during ip policy "\
7698 				    "processing\n"));
7699 				return;
7700 			}
7701 		}
7702 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7703 		    BPRI_HI)) == NULL) {
7704 			goto discard_pkt;
7705 		}
7706 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7707 		mp = first_mp;
7708 
7709 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
7710 		return;
7711 	}
7712 
7713 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7714 
7715 	ASSERT(ire->ire_ipif != NULL);
7716 
7717 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7718 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7719 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
7720 	    ipst->ips_ipv4firewall_physical_out,
7721 	    NULL, out_ill, ipha, mp, mp, ipst);
7722 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7723 	if (mp == NULL)
7724 		return;
7725 
7726 	/* Now send the packet to the tunnel interface */
7727 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7728 	q = ire->ire_stq;
7729 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7730 	if ((pktxmit_state == SEND_FAILED) ||
7731 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7732 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7733 		    q->q_ptr));
7734 	}
7735 
7736 	return;
7737 discard_pkt:
7738 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7739 drop_pkt:;
7740 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7741 	freemsg(mp);
7742 #undef	rptr
7743 }
7744 
7745 /*
7746  * Fills the ipsec_out_t data structure with appropriate fields and
7747  * prepends it to mp which contains the IP hdr + data that was meant
7748  * to be forwarded. Please note that ipsec_out_info data structure
7749  * is used here to communicate the outgoing ill path at ip_wput()
7750  * for the ICMP error packet. This has nothing to do with ipsec IP
7751  * security. ipsec_out_t is really used to pass the info to the module
7752  * IP where this information cannot be extracted from conn.
7753  * This functions is called by ip_mrtun_forward().
7754  */
7755 void
7756 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7757 {
7758 	ipsec_out_t	*io;
7759 
7760 	ASSERT(xmit_ill != NULL);
7761 	first_mp->b_datap->db_type = M_CTL;
7762 	first_mp->b_wptr += sizeof (ipsec_info_t);
7763 	/*
7764 	 * This is to pass info to ip_wput in absence of conn.
7765 	 * ipsec_out_secure will be B_FALSE because of this.
7766 	 * Thus ipsec_out_secure being B_FALSE indicates that
7767 	 * this is not IPSEC security related information.
7768 	 */
7769 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7770 	io = (ipsec_out_t *)first_mp->b_rptr;
7771 	io->ipsec_out_type = IPSEC_OUT;
7772 	io->ipsec_out_len = sizeof (ipsec_out_t);
7773 	first_mp->b_cont = mp;
7774 	io->ipsec_out_ill_index =
7775 	    xmit_ill->ill_phyint->phyint_ifindex;
7776 	io->ipsec_out_xmit_if = B_TRUE;
7777 	io->ipsec_out_ns = xmit_ill->ill_ipst->ips_netstack;
7778 }
7779 
7780 /*
7781  * Return the network mask
7782  * associated with the specified address.
7783  */
7784 ipaddr_t
7785 ip_net_mask(ipaddr_t addr)
7786 {
7787 	uchar_t	*up = (uchar_t *)&addr;
7788 	ipaddr_t mask = 0;
7789 	uchar_t	*maskp = (uchar_t *)&mask;
7790 
7791 #if defined(__i386) || defined(__amd64)
7792 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7793 #endif
7794 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7795 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7796 #endif
7797 	if (CLASSD(addr)) {
7798 		maskp[0] = 0xF0;
7799 		return (mask);
7800 	}
7801 	if (addr == 0)
7802 		return (0);
7803 	maskp[0] = 0xFF;
7804 	if ((up[0] & 0x80) == 0)
7805 		return (mask);
7806 
7807 	maskp[1] = 0xFF;
7808 	if ((up[0] & 0xC0) == 0x80)
7809 		return (mask);
7810 
7811 	maskp[2] = 0xFF;
7812 	if ((up[0] & 0xE0) == 0xC0)
7813 		return (mask);
7814 
7815 	/* Must be experimental or multicast, indicate as much */
7816 	return ((ipaddr_t)0);
7817 }
7818 
7819 /*
7820  * Select an ill for the packet by considering load spreading across
7821  * a different ill in the group if dst_ill is part of some group.
7822  */
7823 ill_t *
7824 ip_newroute_get_dst_ill(ill_t *dst_ill)
7825 {
7826 	ill_t *ill;
7827 
7828 	/*
7829 	 * We schedule irrespective of whether the source address is
7830 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7831 	 */
7832 	ill = illgrp_scheduler(dst_ill);
7833 	if (ill == NULL)
7834 		return (NULL);
7835 
7836 	/*
7837 	 * For groups with names ip_sioctl_groupname ensures that all
7838 	 * ills are of same type. For groups without names, ifgrp_insert
7839 	 * ensures this.
7840 	 */
7841 	ASSERT(dst_ill->ill_type == ill->ill_type);
7842 
7843 	return (ill);
7844 }
7845 
7846 /*
7847  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7848  */
7849 ill_t *
7850 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7851     ip_stack_t *ipst)
7852 {
7853 	ill_t *ret_ill;
7854 
7855 	ASSERT(ifindex != 0);
7856 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7857 	    ipst);
7858 	if (ret_ill == NULL ||
7859 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7860 		if (isv6) {
7861 			if (ill != NULL) {
7862 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7863 			} else {
7864 				BUMP_MIB(&ipst->ips_ip6_mib,
7865 				    ipIfStatsOutDiscards);
7866 			}
7867 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7868 			    "bad ifindex %d.\n", ifindex));
7869 		} else {
7870 			if (ill != NULL) {
7871 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7872 			} else {
7873 				BUMP_MIB(&ipst->ips_ip_mib,
7874 				    ipIfStatsOutDiscards);
7875 			}
7876 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7877 			    "bad ifindex %d.\n", ifindex));
7878 		}
7879 		if (ret_ill != NULL)
7880 			ill_refrele(ret_ill);
7881 		freemsg(first_mp);
7882 		return (NULL);
7883 	}
7884 
7885 	return (ret_ill);
7886 }
7887 
7888 /*
7889  * IPv4 -
7890  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7891  * out a packet to a destination address for which we do not have specific
7892  * (or sufficient) routing information.
7893  *
7894  * NOTE : These are the scopes of some of the variables that point at IRE,
7895  *	  which needs to be followed while making any future modifications
7896  *	  to avoid memory leaks.
7897  *
7898  *	- ire and sire are the entries looked up initially by
7899  *	  ire_ftable_lookup.
7900  *	- ipif_ire is used to hold the interface ire associated with
7901  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7902  *	  it before branching out to error paths.
7903  *	- save_ire is initialized before ire_create, so that ire returned
7904  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7905  *	  before breaking out of the switch.
7906  *
7907  *	Thus on failures, we have to REFRELE only ire and sire, if they
7908  *	are not NULL.
7909  */
7910 void
7911 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7912     zoneid_t zoneid, ip_stack_t *ipst)
7913 {
7914 	areq_t	*areq;
7915 	ipaddr_t gw = 0;
7916 	ire_t	*ire = NULL;
7917 	mblk_t	*res_mp;
7918 	ipaddr_t *addrp;
7919 	ipaddr_t nexthop_addr;
7920 	ipif_t  *src_ipif = NULL;
7921 	ill_t	*dst_ill = NULL;
7922 	ipha_t  *ipha;
7923 	ire_t	*sire = NULL;
7924 	mblk_t	*first_mp;
7925 	ire_t	*save_ire;
7926 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7927 	ushort_t ire_marks = 0;
7928 	boolean_t mctl_present;
7929 	ipsec_out_t *io;
7930 	mblk_t	*saved_mp;
7931 	ire_t	*first_sire = NULL;
7932 	mblk_t	*copy_mp = NULL;
7933 	mblk_t	*xmit_mp = NULL;
7934 	ipaddr_t save_dst;
7935 	uint32_t multirt_flags =
7936 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7937 	boolean_t multirt_is_resolvable;
7938 	boolean_t multirt_resolve_next;
7939 	boolean_t do_attach_ill = B_FALSE;
7940 	boolean_t ip_nexthop = B_FALSE;
7941 	tsol_ire_gw_secattr_t *attrp = NULL;
7942 	tsol_gcgrp_t *gcgrp = NULL;
7943 	tsol_gcgrp_addr_t ga;
7944 
7945 	if (ip_debug > 2) {
7946 		/* ip1dbg */
7947 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7948 	}
7949 
7950 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7951 	if (mctl_present) {
7952 		io = (ipsec_out_t *)first_mp->b_rptr;
7953 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7954 		ASSERT(zoneid == io->ipsec_out_zoneid);
7955 		ASSERT(zoneid != ALL_ZONES);
7956 	}
7957 
7958 	ipha = (ipha_t *)mp->b_rptr;
7959 
7960 	/* All multicast lookups come through ip_newroute_ipif() */
7961 	if (CLASSD(dst)) {
7962 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7963 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7964 		freemsg(first_mp);
7965 		return;
7966 	}
7967 
7968 	if (mctl_present && io->ipsec_out_attach_if) {
7969 		/* ip_grab_attach_ill returns a held ill */
7970 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7971 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7972 
7973 		/* Failure case frees things for us. */
7974 		if (attach_ill == NULL)
7975 			return;
7976 
7977 		/*
7978 		 * Check if we need an ire that will not be
7979 		 * looked up by anybody else i.e. HIDDEN.
7980 		 */
7981 		if (ill_is_probeonly(attach_ill))
7982 			ire_marks = IRE_MARK_HIDDEN;
7983 	}
7984 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7985 		ip_nexthop = B_TRUE;
7986 		nexthop_addr = io->ipsec_out_nexthop_addr;
7987 	}
7988 	/*
7989 	 * If this IRE is created for forwarding or it is not for
7990 	 * traffic for congestion controlled protocols, mark it as temporary.
7991 	 */
7992 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7993 		ire_marks |= IRE_MARK_TEMPORARY;
7994 
7995 	/*
7996 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7997 	 * chain until it gets the most specific information available.
7998 	 * For example, we know that there is no IRE_CACHE for this dest,
7999 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
8000 	 * ire_ftable_lookup will look up the gateway, etc.
8001 	 * Check if in_ill != NULL. If it is true, the packet must be
8002 	 * from an incoming interface where RTA_SRCIFP is set.
8003 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
8004 	 * to the destination, of equal netmask length in the forward table,
8005 	 * will be recursively explored. If no information is available
8006 	 * for the final gateway of that route, we force the returned ire
8007 	 * to be equal to sire using MATCH_IRE_PARENT.
8008 	 * At least, in this case we have a starting point (in the buckets)
8009 	 * to look for other routes to the destination in the forward table.
8010 	 * This is actually used only for multirouting, where a list
8011 	 * of routes has to be processed in sequence.
8012 	 *
8013 	 * In the process of coming up with the most specific information,
8014 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8015 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8016 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8017 	 * Two caveats when handling incomplete ire's in ip_newroute:
8018 	 * - we should be careful when accessing its ire_nce (specifically
8019 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8020 	 * - not all legacy code path callers are prepared to handle
8021 	 *   incomplete ire's, so we should not create/add incomplete
8022 	 *   ire_cache entries here. (See discussion about temporary solution
8023 	 *   further below).
8024 	 *
8025 	 * In order to minimize packet dropping, and to preserve existing
8026 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8027 	 * gateway, and instead use the IF_RESOLVER ire to send out
8028 	 * another request to ARP (this is achieved by passing the
8029 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8030 	 * arp response comes back in ip_wput_nondata, we will create
8031 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8032 	 *
8033 	 * Note that this is a temporary solution; the correct solution is
8034 	 * to create an incomplete  per-dst ire_cache entry, and send the
8035 	 * packet out when the gw's nce is resolved. In order to achieve this,
8036 	 * all packet processing must have been completed prior to calling
8037 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8038 	 * to be modified to accomodate this solution.
8039 	 */
8040 	if (in_ill != NULL) {
8041 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
8042 		    in_ill, MATCH_IRE_TYPE);
8043 	} else if (ip_nexthop) {
8044 		/*
8045 		 * The first time we come here, we look for an IRE_INTERFACE
8046 		 * entry for the specified nexthop, set the dst to be the
8047 		 * nexthop address and create an IRE_CACHE entry for the
8048 		 * nexthop. The next time around, we are able to find an
8049 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8050 		 * nexthop address and create an IRE_CACHE entry for the
8051 		 * destination address via the specified nexthop.
8052 		 */
8053 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8054 		    MBLK_GETLABEL(mp), ipst);
8055 		if (ire != NULL) {
8056 			gw = nexthop_addr;
8057 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8058 		} else {
8059 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8060 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8061 			    MBLK_GETLABEL(mp),
8062 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8063 			    ipst);
8064 			if (ire != NULL) {
8065 				dst = nexthop_addr;
8066 			}
8067 		}
8068 	} else if (attach_ill == NULL) {
8069 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8070 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8071 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8072 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8073 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8074 		    ipst);
8075 	} else {
8076 		/*
8077 		 * attach_ill is set only for communicating with
8078 		 * on-link hosts. So, don't look for DEFAULT.
8079 		 */
8080 		ipif_t	*attach_ipif;
8081 
8082 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8083 		if (attach_ipif == NULL) {
8084 			ill_refrele(attach_ill);
8085 			goto icmp_err_ret;
8086 		}
8087 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8088 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8089 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8090 		    MATCH_IRE_SECATTR, ipst);
8091 		ipif_refrele(attach_ipif);
8092 	}
8093 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8094 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8095 
8096 	/*
8097 	 * This loop is run only once in most cases.
8098 	 * We loop to resolve further routes only when the destination
8099 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8100 	 */
8101 	do {
8102 		/* Clear the previous iteration's values */
8103 		if (src_ipif != NULL) {
8104 			ipif_refrele(src_ipif);
8105 			src_ipif = NULL;
8106 		}
8107 		if (dst_ill != NULL) {
8108 			ill_refrele(dst_ill);
8109 			dst_ill = NULL;
8110 		}
8111 
8112 		multirt_resolve_next = B_FALSE;
8113 		/*
8114 		 * We check if packets have to be multirouted.
8115 		 * In this case, given the current <ire, sire> couple,
8116 		 * we look for the next suitable <ire, sire>.
8117 		 * This check is done in ire_multirt_lookup(),
8118 		 * which applies various criteria to find the next route
8119 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8120 		 * unchanged if it detects it has not been tried yet.
8121 		 */
8122 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8123 			ip3dbg(("ip_newroute: starting next_resolution "
8124 			    "with first_mp %p, tag %d\n",
8125 			    (void *)first_mp,
8126 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8127 
8128 			ASSERT(sire != NULL);
8129 			multirt_is_resolvable =
8130 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8131 				MBLK_GETLABEL(mp), ipst);
8132 
8133 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8134 			    "ire %p, sire %p\n",
8135 			    multirt_is_resolvable,
8136 			    (void *)ire, (void *)sire));
8137 
8138 			if (!multirt_is_resolvable) {
8139 				/*
8140 				 * No more multirt route to resolve; give up
8141 				 * (all routes resolved or no more
8142 				 * resolvable routes).
8143 				 */
8144 				if (ire != NULL) {
8145 					ire_refrele(ire);
8146 					ire = NULL;
8147 				}
8148 			} else {
8149 				ASSERT(sire != NULL);
8150 				ASSERT(ire != NULL);
8151 				/*
8152 				 * We simply use first_sire as a flag that
8153 				 * indicates if a resolvable multirt route
8154 				 * has already been found.
8155 				 * If it is not the case, we may have to send
8156 				 * an ICMP error to report that the
8157 				 * destination is unreachable.
8158 				 * We do not IRE_REFHOLD first_sire.
8159 				 */
8160 				if (first_sire == NULL) {
8161 					first_sire = sire;
8162 				}
8163 			}
8164 		}
8165 		if (ire == NULL) {
8166 			if (ip_debug > 3) {
8167 				/* ip2dbg */
8168 				pr_addr_dbg("ip_newroute: "
8169 				    "can't resolve %s\n", AF_INET, &dst);
8170 			}
8171 			ip3dbg(("ip_newroute: "
8172 			    "ire %p, sire %p, first_sire %p\n",
8173 			    (void *)ire, (void *)sire, (void *)first_sire));
8174 
8175 			if (sire != NULL) {
8176 				ire_refrele(sire);
8177 				sire = NULL;
8178 			}
8179 
8180 			if (first_sire != NULL) {
8181 				/*
8182 				 * At least one multirt route has been found
8183 				 * in the same call to ip_newroute();
8184 				 * there is no need to report an ICMP error.
8185 				 * first_sire was not IRE_REFHOLDed.
8186 				 */
8187 				MULTIRT_DEBUG_UNTAG(first_mp);
8188 				freemsg(first_mp);
8189 				return;
8190 			}
8191 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8192 			    RTA_DST, ipst);
8193 			if (attach_ill != NULL)
8194 				ill_refrele(attach_ill);
8195 			goto icmp_err_ret;
8196 		}
8197 
8198 		/*
8199 		 * When RTA_SRCIFP is used to add a route, then an interface
8200 		 * route is added in the source interface's routing table.
8201 		 * If the outgoing interface of this route is of type
8202 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8203 		 * ire_nce->nce_res_mp is set to NULL.
8204 		 * Later, when this route is first used for forwarding
8205 		 * a packet, ip_newroute() is called
8206 		 * to resolve the hardware address of the outgoing ipif.
8207 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8208 		 * source interface based table. We only come here if the
8209 		 * outgoing interface is a resolver interface and we don't
8210 		 * have the ire_nce->nce_res_mp information yet.
8211 		 * If in_ill is not null that means it is called from
8212 		 * ip_rput.
8213 		 */
8214 
8215 		ASSERT(ire->ire_in_ill == NULL ||
8216 		    (ire->ire_type == IRE_IF_RESOLVER &&
8217 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8218 
8219 		/*
8220 		 * Verify that the returned IRE does not have either
8221 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8222 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8223 		 */
8224 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8225 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8226 			if (attach_ill != NULL)
8227 				ill_refrele(attach_ill);
8228 			goto icmp_err_ret;
8229 		}
8230 		/*
8231 		 * Increment the ire_ob_pkt_count field for ire if it is an
8232 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8233 		 * increment the same for the parent IRE, sire, if it is some
8234 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
8235 		 * and HOST_REDIRECT).
8236 		 */
8237 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8238 			UPDATE_OB_PKT_COUNT(ire);
8239 			ire->ire_last_used_time = lbolt;
8240 		}
8241 
8242 		if (sire != NULL) {
8243 			gw = sire->ire_gateway_addr;
8244 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8245 			    IRE_INTERFACE)) == 0);
8246 			UPDATE_OB_PKT_COUNT(sire);
8247 			sire->ire_last_used_time = lbolt;
8248 		}
8249 		/*
8250 		 * We have a route to reach the destination.
8251 		 *
8252 		 * 1) If the interface is part of ill group, try to get a new
8253 		 *    ill taking load spreading into account.
8254 		 *
8255 		 * 2) After selecting the ill, get a source address that
8256 		 *    might create good inbound load spreading.
8257 		 *    ipif_select_source does this for us.
8258 		 *
8259 		 * If the application specified the ill (ifindex), we still
8260 		 * load spread. Only if the packets needs to go out
8261 		 * specifically on a given ill e.g. binding to
8262 		 * IPIF_NOFAILOVER address, then we don't try to use a
8263 		 * different ill for load spreading.
8264 		 */
8265 		if (attach_ill == NULL) {
8266 			/*
8267 			 * Don't perform outbound load spreading in the
8268 			 * case of an RTF_MULTIRT route, as we actually
8269 			 * typically want to replicate outgoing packets
8270 			 * through particular interfaces.
8271 			 */
8272 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8273 				dst_ill = ire->ire_ipif->ipif_ill;
8274 				/* for uniformity */
8275 				ill_refhold(dst_ill);
8276 			} else {
8277 				/*
8278 				 * If we are here trying to create an IRE_CACHE
8279 				 * for an offlink destination and have the
8280 				 * IRE_CACHE for the next hop and the latter is
8281 				 * using virtual IP source address selection i.e
8282 				 * it's ire->ire_ipif is pointing to a virtual
8283 				 * network interface (vni) then
8284 				 * ip_newroute_get_dst_ll() will return the vni
8285 				 * interface as the dst_ill. Since the vni is
8286 				 * virtual i.e not associated with any physical
8287 				 * interface, it cannot be the dst_ill, hence
8288 				 * in such a case call ip_newroute_get_dst_ll()
8289 				 * with the stq_ill instead of the ire_ipif ILL.
8290 				 * The function returns a refheld ill.
8291 				 */
8292 				if ((ire->ire_type == IRE_CACHE) &&
8293 				    IS_VNI(ire->ire_ipif->ipif_ill))
8294 					dst_ill = ip_newroute_get_dst_ill(
8295 						ire->ire_stq->q_ptr);
8296 				else
8297 					dst_ill = ip_newroute_get_dst_ill(
8298 						ire->ire_ipif->ipif_ill);
8299 			}
8300 			if (dst_ill == NULL) {
8301 				if (ip_debug > 2) {
8302 					pr_addr_dbg("ip_newroute: "
8303 					    "no dst ill for dst"
8304 					    " %s\n", AF_INET, &dst);
8305 				}
8306 				goto icmp_err_ret;
8307 			}
8308 		} else {
8309 			dst_ill = ire->ire_ipif->ipif_ill;
8310 			/* for uniformity */
8311 			ill_refhold(dst_ill);
8312 			/*
8313 			 * We should have found a route matching ill as we
8314 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8315 			 * Rather than asserting, when there is a mismatch,
8316 			 * we just drop the packet.
8317 			 */
8318 			if (dst_ill != attach_ill) {
8319 				ip0dbg(("ip_newroute: Packet dropped as "
8320 				    "IPIF_NOFAILOVER ill is %s, "
8321 				    "ire->ire_ipif->ipif_ill is %s\n",
8322 				    attach_ill->ill_name,
8323 				    dst_ill->ill_name));
8324 				ill_refrele(attach_ill);
8325 				goto icmp_err_ret;
8326 			}
8327 		}
8328 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8329 		if (attach_ill != NULL) {
8330 			ill_refrele(attach_ill);
8331 			attach_ill = NULL;
8332 			do_attach_ill = B_TRUE;
8333 		}
8334 		ASSERT(dst_ill != NULL);
8335 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8336 
8337 		/*
8338 		 * Pick the best source address from dst_ill.
8339 		 *
8340 		 * 1) If it is part of a multipathing group, we would
8341 		 *    like to spread the inbound packets across different
8342 		 *    interfaces. ipif_select_source picks a random source
8343 		 *    across the different ills in the group.
8344 		 *
8345 		 * 2) If it is not part of a multipathing group, we try
8346 		 *    to pick the source address from the destination
8347 		 *    route. Clustering assumes that when we have multiple
8348 		 *    prefixes hosted on an interface, the prefix of the
8349 		 *    source address matches the prefix of the destination
8350 		 *    route. We do this only if the address is not
8351 		 *    DEPRECATED.
8352 		 *
8353 		 * 3) If the conn is in a different zone than the ire, we
8354 		 *    need to pick a source address from the right zone.
8355 		 *
8356 		 * NOTE : If we hit case (1) above, the prefix of the source
8357 		 *	  address picked may not match the prefix of the
8358 		 *	  destination routes prefix as ipif_select_source
8359 		 *	  does not look at "dst" while picking a source
8360 		 *	  address.
8361 		 *	  If we want the same behavior as (2), we will need
8362 		 *	  to change the behavior of ipif_select_source.
8363 		 */
8364 		ASSERT(src_ipif == NULL);
8365 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8366 			/*
8367 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8368 			 * Check that the ipif matching the requested source
8369 			 * address still exists.
8370 			 */
8371 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8372 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8373 		}
8374 		if (src_ipif == NULL) {
8375 			ire_marks |= IRE_MARK_USESRC_CHECK;
8376 			if ((dst_ill->ill_group != NULL) ||
8377 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8378 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8379 			    ire->ire_zoneid != ALL_ZONES) ||
8380 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8381 				/*
8382 				 * If the destination is reachable via a
8383 				 * given gateway, the selected source address
8384 				 * should be in the same subnet as the gateway.
8385 				 * Otherwise, the destination is not reachable.
8386 				 *
8387 				 * If there are no interfaces on the same subnet
8388 				 * as the destination, ipif_select_source gives
8389 				 * first non-deprecated interface which might be
8390 				 * on a different subnet than the gateway.
8391 				 * This is not desirable. Hence pass the dst_ire
8392 				 * source address to ipif_select_source.
8393 				 * It is sure that the destination is reachable
8394 				 * with the dst_ire source address subnet.
8395 				 * So passing dst_ire source address to
8396 				 * ipif_select_source will make sure that the
8397 				 * selected source will be on the same subnet
8398 				 * as dst_ire source address.
8399 				 */
8400 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8401 				src_ipif = ipif_select_source(dst_ill, saddr,
8402 				    zoneid);
8403 				if (src_ipif == NULL) {
8404 					if (ip_debug > 2) {
8405 						pr_addr_dbg("ip_newroute: "
8406 						    "no src for dst %s ",
8407 						    AF_INET, &dst);
8408 						printf("through interface %s\n",
8409 						    dst_ill->ill_name);
8410 					}
8411 					goto icmp_err_ret;
8412 				}
8413 			} else {
8414 				src_ipif = ire->ire_ipif;
8415 				ASSERT(src_ipif != NULL);
8416 				/* hold src_ipif for uniformity */
8417 				ipif_refhold(src_ipif);
8418 			}
8419 		}
8420 
8421 		/*
8422 		 * Assign a source address while we have the conn.
8423 		 * We can't have ip_wput_ire pick a source address when the
8424 		 * packet returns from arp since we need to look at
8425 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8426 		 * going through arp.
8427 		 *
8428 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8429 		 *	  it uses ip6i to store this information.
8430 		 */
8431 		if (ipha->ipha_src == INADDR_ANY &&
8432 		    (connp == NULL || !connp->conn_unspec_src)) {
8433 			ipha->ipha_src = src_ipif->ipif_src_addr;
8434 		}
8435 		if (ip_debug > 3) {
8436 			/* ip2dbg */
8437 			pr_addr_dbg("ip_newroute: first hop %s\n",
8438 			    AF_INET, &gw);
8439 		}
8440 		ip2dbg(("\tire type %s (%d)\n",
8441 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8442 
8443 		/*
8444 		 * The TTL of multirouted packets is bounded by the
8445 		 * ip_multirt_ttl ndd variable.
8446 		 */
8447 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8448 			/* Force TTL of multirouted packets */
8449 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8450 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8451 				ip2dbg(("ip_newroute: forcing multirt TTL "
8452 				    "to %d (was %d), dst 0x%08x\n",
8453 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8454 				    ntohl(sire->ire_addr)));
8455 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8456 			}
8457 		}
8458 		/*
8459 		 * At this point in ip_newroute(), ire is either the
8460 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8461 		 * destination or an IRE_INTERFACE type that should be used
8462 		 * to resolve an on-subnet destination or an on-subnet
8463 		 * next-hop gateway.
8464 		 *
8465 		 * In the IRE_CACHE case, we have the following :
8466 		 *
8467 		 * 1) src_ipif - used for getting a source address.
8468 		 *
8469 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8470 		 *    means packets using this IRE_CACHE will go out on
8471 		 *    dst_ill.
8472 		 *
8473 		 * 3) The IRE sire will point to the prefix that is the
8474 		 *    longest  matching route for the destination. These
8475 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8476 		 *
8477 		 *    The newly created IRE_CACHE entry for the off-subnet
8478 		 *    destination is tied to both the prefix route and the
8479 		 *    interface route used to resolve the next-hop gateway
8480 		 *    via the ire_phandle and ire_ihandle fields,
8481 		 *    respectively.
8482 		 *
8483 		 * In the IRE_INTERFACE case, we have the following :
8484 		 *
8485 		 * 1) src_ipif - used for getting a source address.
8486 		 *
8487 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8488 		 *    means packets using the IRE_CACHE that we will build
8489 		 *    here will go out on dst_ill.
8490 		 *
8491 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8492 		 *    to be created will only be tied to the IRE_INTERFACE
8493 		 *    that was derived from the ire_ihandle field.
8494 		 *
8495 		 *    If sire is non-NULL, it means the destination is
8496 		 *    off-link and we will first create the IRE_CACHE for the
8497 		 *    gateway. Next time through ip_newroute, we will create
8498 		 *    the IRE_CACHE for the final destination as described
8499 		 *    above.
8500 		 *
8501 		 * In both cases, after the current resolution has been
8502 		 * completed (or possibly initialised, in the IRE_INTERFACE
8503 		 * case), the loop may be re-entered to attempt the resolution
8504 		 * of another RTF_MULTIRT route.
8505 		 *
8506 		 * When an IRE_CACHE entry for the off-subnet destination is
8507 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8508 		 * for further processing in emission loops.
8509 		 */
8510 		save_ire = ire;
8511 		switch (ire->ire_type) {
8512 		case IRE_CACHE: {
8513 			ire_t	*ipif_ire;
8514 			mblk_t	*ire_fp_mp;
8515 
8516 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8517 			if (gw == 0)
8518 				gw = ire->ire_gateway_addr;
8519 			/*
8520 			 * We need 3 ire's to create a new cache ire for an
8521 			 * off-link destination from the cache ire of the
8522 			 * gateway.
8523 			 *
8524 			 *	1. The prefix ire 'sire' (Note that this does
8525 			 *	   not apply to the conn_nexthop_set case)
8526 			 *	2. The cache ire of the gateway 'ire'
8527 			 *	3. The interface ire 'ipif_ire'
8528 			 *
8529 			 * We have (1) and (2). We lookup (3) below.
8530 			 *
8531 			 * If there is no interface route to the gateway,
8532 			 * it is a race condition, where we found the cache
8533 			 * but the interface route has been deleted.
8534 			 */
8535 			if (ip_nexthop) {
8536 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8537 			} else {
8538 				ipif_ire =
8539 				    ire_ihandle_lookup_offlink(ire, sire);
8540 			}
8541 			if (ipif_ire == NULL) {
8542 				ip1dbg(("ip_newroute: "
8543 				    "ire_ihandle_lookup_offlink failed\n"));
8544 				goto icmp_err_ret;
8545 			}
8546 			/*
8547 			 * XXX We are using the same res_mp
8548 			 * (DL_UNITDATA_REQ) though the save_ire is not
8549 			 * pointing at the same ill.
8550 			 * This is incorrect. We need to send it up to the
8551 			 * resolver to get the right res_mp. For ethernets
8552 			 * this may be okay (ill_type == DL_ETHER).
8553 			 */
8554 			res_mp = save_ire->ire_nce->nce_res_mp;
8555 			ire_fp_mp = NULL;
8556 
8557 			/*
8558 			 * Check cached gateway IRE for any security
8559 			 * attributes; if found, associate the gateway
8560 			 * credentials group to the destination IRE.
8561 			 */
8562 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8563 				mutex_enter(&attrp->igsa_lock);
8564 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8565 					GCGRP_REFHOLD(gcgrp);
8566 				mutex_exit(&attrp->igsa_lock);
8567 			}
8568 
8569 			ire = ire_create(
8570 			    (uchar_t *)&dst,		/* dest address */
8571 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8572 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8573 			    (uchar_t *)&gw,		/* gateway address */
8574 			    NULL,
8575 			    &save_ire->ire_max_frag,
8576 			    ire_fp_mp,			/* Fast Path header */
8577 			    dst_ill->ill_rq,		/* recv-from queue */
8578 			    dst_ill->ill_wq,		/* send-to queue */
8579 			    IRE_CACHE,			/* IRE type */
8580 			    res_mp,
8581 			    src_ipif,
8582 			    in_ill,			/* incoming ill */
8583 			    (sire != NULL) ?
8584 				sire->ire_mask : 0, 	/* Parent mask */
8585 			    (sire != NULL) ?
8586 				sire->ire_phandle : 0,  /* Parent handle */
8587 			    ipif_ire->ire_ihandle,	/* Interface handle */
8588 			    (sire != NULL) ? (sire->ire_flags &
8589 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8590 			    (sire != NULL) ?
8591 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8592 			    NULL,
8593 			    gcgrp,
8594 			    ipst);
8595 
8596 			if (ire == NULL) {
8597 				if (gcgrp != NULL) {
8598 					GCGRP_REFRELE(gcgrp);
8599 					gcgrp = NULL;
8600 				}
8601 				ire_refrele(ipif_ire);
8602 				ire_refrele(save_ire);
8603 				break;
8604 			}
8605 
8606 			/* reference now held by IRE */
8607 			gcgrp = NULL;
8608 
8609 			ire->ire_marks |= ire_marks;
8610 
8611 			/*
8612 			 * Prevent sire and ipif_ire from getting deleted.
8613 			 * The newly created ire is tied to both of them via
8614 			 * the phandle and ihandle respectively.
8615 			 */
8616 			if (sire != NULL) {
8617 				IRB_REFHOLD(sire->ire_bucket);
8618 				/* Has it been removed already ? */
8619 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8620 					IRB_REFRELE(sire->ire_bucket);
8621 					ire_refrele(ipif_ire);
8622 					ire_refrele(save_ire);
8623 					break;
8624 				}
8625 			}
8626 
8627 			IRB_REFHOLD(ipif_ire->ire_bucket);
8628 			/* Has it been removed already ? */
8629 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8630 				IRB_REFRELE(ipif_ire->ire_bucket);
8631 				if (sire != NULL)
8632 					IRB_REFRELE(sire->ire_bucket);
8633 				ire_refrele(ipif_ire);
8634 				ire_refrele(save_ire);
8635 				break;
8636 			}
8637 
8638 			xmit_mp = first_mp;
8639 			/*
8640 			 * In the case of multirouting, a copy
8641 			 * of the packet is done before its sending.
8642 			 * The copy is used to attempt another
8643 			 * route resolution, in a next loop.
8644 			 */
8645 			if (ire->ire_flags & RTF_MULTIRT) {
8646 				copy_mp = copymsg(first_mp);
8647 				if (copy_mp != NULL) {
8648 					xmit_mp = copy_mp;
8649 					MULTIRT_DEBUG_TAG(first_mp);
8650 				}
8651 			}
8652 			ire_add_then_send(q, ire, xmit_mp);
8653 			ire_refrele(save_ire);
8654 
8655 			/* Assert that sire is not deleted yet. */
8656 			if (sire != NULL) {
8657 				ASSERT(sire->ire_ptpn != NULL);
8658 				IRB_REFRELE(sire->ire_bucket);
8659 			}
8660 
8661 			/* Assert that ipif_ire is not deleted yet. */
8662 			ASSERT(ipif_ire->ire_ptpn != NULL);
8663 			IRB_REFRELE(ipif_ire->ire_bucket);
8664 			ire_refrele(ipif_ire);
8665 
8666 			/*
8667 			 * If copy_mp is not NULL, multirouting was
8668 			 * requested. We loop to initiate a next
8669 			 * route resolution attempt, starting from sire.
8670 			 */
8671 			if (copy_mp != NULL) {
8672 				/*
8673 				 * Search for the next unresolved
8674 				 * multirt route.
8675 				 */
8676 				copy_mp = NULL;
8677 				ipif_ire = NULL;
8678 				ire = NULL;
8679 				multirt_resolve_next = B_TRUE;
8680 				continue;
8681 			}
8682 			if (sire != NULL)
8683 				ire_refrele(sire);
8684 			ipif_refrele(src_ipif);
8685 			ill_refrele(dst_ill);
8686 			return;
8687 		}
8688 		case IRE_IF_NORESOLVER: {
8689 			/*
8690 			 * We have what we need to build an IRE_CACHE.
8691 			 *
8692 			 * Create a new res_mp with the IP gateway address
8693 			 * in destination address in the DLPI hdr if the
8694 			 * physical length is exactly 4 bytes.
8695 			 */
8696 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8697 				uchar_t *addr;
8698 
8699 				if (gw)
8700 					addr = (uchar_t *)&gw;
8701 				else
8702 					addr = (uchar_t *)&dst;
8703 
8704 				res_mp = ill_dlur_gen(addr,
8705 				    dst_ill->ill_phys_addr_length,
8706 				    dst_ill->ill_sap,
8707 				    dst_ill->ill_sap_length);
8708 
8709 				if (res_mp == NULL) {
8710 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8711 					break;
8712 				}
8713 			} else if (dst_ill->ill_resolver_mp == NULL) {
8714 				ip1dbg(("ip_newroute: dst_ill %p "
8715 				    "for IF_NORESOLV ire %p has "
8716 				    "no ill_resolver_mp\n",
8717 				    (void *)dst_ill, (void *)ire));
8718 				break;
8719 			} else {
8720 				res_mp = NULL;
8721 			}
8722 
8723 			/*
8724 			 * TSol note: We are creating the ire cache for the
8725 			 * destination 'dst'. If 'dst' is offlink, going
8726 			 * through the first hop 'gw', the security attributes
8727 			 * of 'dst' must be set to point to the gateway
8728 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8729 			 * is possible that 'dst' is a potential gateway that is
8730 			 * referenced by some route that has some security
8731 			 * attributes. Thus in the former case, we need to do a
8732 			 * gcgrp_lookup of 'gw' while in the latter case we
8733 			 * need to do gcgrp_lookup of 'dst' itself.
8734 			 */
8735 			ga.ga_af = AF_INET;
8736 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8737 			    &ga.ga_addr);
8738 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8739 
8740 			ire = ire_create(
8741 			    (uchar_t *)&dst,		/* dest address */
8742 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8743 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8744 			    (uchar_t *)&gw,		/* gateway address */
8745 			    NULL,
8746 			    &save_ire->ire_max_frag,
8747 			    NULL,			/* Fast Path header */
8748 			    dst_ill->ill_rq,		/* recv-from queue */
8749 			    dst_ill->ill_wq,		/* send-to queue */
8750 			    IRE_CACHE,
8751 			    res_mp,
8752 			    src_ipif,
8753 			    in_ill,			/* Incoming ill */
8754 			    save_ire->ire_mask,		/* Parent mask */
8755 			    (sire != NULL) ?		/* Parent handle */
8756 				sire->ire_phandle : 0,
8757 			    save_ire->ire_ihandle,	/* Interface handle */
8758 			    (sire != NULL) ? sire->ire_flags &
8759 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8760 			    &(save_ire->ire_uinfo),
8761 			    NULL,
8762 			    gcgrp,
8763 			    ipst);
8764 
8765 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8766 				freeb(res_mp);
8767 
8768 			if (ire == NULL) {
8769 				if (gcgrp != NULL) {
8770 					GCGRP_REFRELE(gcgrp);
8771 					gcgrp = NULL;
8772 				}
8773 				ire_refrele(save_ire);
8774 				break;
8775 			}
8776 
8777 			/* reference now held by IRE */
8778 			gcgrp = NULL;
8779 
8780 			ire->ire_marks |= ire_marks;
8781 
8782 			/* Prevent save_ire from getting deleted */
8783 			IRB_REFHOLD(save_ire->ire_bucket);
8784 			/* Has it been removed already ? */
8785 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8786 				IRB_REFRELE(save_ire->ire_bucket);
8787 				ire_refrele(save_ire);
8788 				break;
8789 			}
8790 
8791 			/*
8792 			 * In the case of multirouting, a copy
8793 			 * of the packet is made before it is sent.
8794 			 * The copy is used in the next
8795 			 * loop to attempt another resolution.
8796 			 */
8797 			xmit_mp = first_mp;
8798 			if ((sire != NULL) &&
8799 			    (sire->ire_flags & RTF_MULTIRT)) {
8800 				copy_mp = copymsg(first_mp);
8801 				if (copy_mp != NULL) {
8802 					xmit_mp = copy_mp;
8803 					MULTIRT_DEBUG_TAG(first_mp);
8804 				}
8805 			}
8806 			ire_add_then_send(q, ire, xmit_mp);
8807 
8808 			/* Assert that it is not deleted yet. */
8809 			ASSERT(save_ire->ire_ptpn != NULL);
8810 			IRB_REFRELE(save_ire->ire_bucket);
8811 			ire_refrele(save_ire);
8812 
8813 			if (copy_mp != NULL) {
8814 				/*
8815 				 * If we found a (no)resolver, we ignore any
8816 				 * trailing top priority IRE_CACHE in further
8817 				 * loops. This ensures that we do not omit any
8818 				 * (no)resolver.
8819 				 * This IRE_CACHE, if any, will be processed
8820 				 * by another thread entering ip_newroute().
8821 				 * IRE_CACHE entries, if any, will be processed
8822 				 * by another thread entering ip_newroute(),
8823 				 * (upon resolver response, for instance).
8824 				 * This aims to force parallel multirt
8825 				 * resolutions as soon as a packet must be sent.
8826 				 * In the best case, after the tx of only one
8827 				 * packet, all reachable routes are resolved.
8828 				 * Otherwise, the resolution of all RTF_MULTIRT
8829 				 * routes would require several emissions.
8830 				 */
8831 				multirt_flags &= ~MULTIRT_CACHEGW;
8832 
8833 				/*
8834 				 * Search for the next unresolved multirt
8835 				 * route.
8836 				 */
8837 				copy_mp = NULL;
8838 				save_ire = NULL;
8839 				ire = NULL;
8840 				multirt_resolve_next = B_TRUE;
8841 				continue;
8842 			}
8843 
8844 			/*
8845 			 * Don't need sire anymore
8846 			 */
8847 			if (sire != NULL)
8848 				ire_refrele(sire);
8849 
8850 			ipif_refrele(src_ipif);
8851 			ill_refrele(dst_ill);
8852 			return;
8853 		}
8854 		case IRE_IF_RESOLVER:
8855 			/*
8856 			 * We can't build an IRE_CACHE yet, but at least we
8857 			 * found a resolver that can help.
8858 			 */
8859 			res_mp = dst_ill->ill_resolver_mp;
8860 			if (!OK_RESOLVER_MP(res_mp))
8861 				break;
8862 
8863 			/*
8864 			 * To be at this point in the code with a non-zero gw
8865 			 * means that dst is reachable through a gateway that
8866 			 * we have never resolved.  By changing dst to the gw
8867 			 * addr we resolve the gateway first.
8868 			 * When ire_add_then_send() tries to put the IP dg
8869 			 * to dst, it will reenter ip_newroute() at which
8870 			 * time we will find the IRE_CACHE for the gw and
8871 			 * create another IRE_CACHE in case IRE_CACHE above.
8872 			 */
8873 			if (gw != INADDR_ANY) {
8874 				/*
8875 				 * The source ipif that was determined above was
8876 				 * relative to the destination address, not the
8877 				 * gateway's. If src_ipif was not taken out of
8878 				 * the IRE_IF_RESOLVER entry, we'll need to call
8879 				 * ipif_select_source() again.
8880 				 */
8881 				if (src_ipif != ire->ire_ipif) {
8882 					ipif_refrele(src_ipif);
8883 					src_ipif = ipif_select_source(dst_ill,
8884 					    gw, zoneid);
8885 					if (src_ipif == NULL) {
8886 						if (ip_debug > 2) {
8887 							pr_addr_dbg(
8888 							    "ip_newroute: no "
8889 							    "src for gw %s ",
8890 							    AF_INET, &gw);
8891 							printf("through "
8892 							    "interface %s\n",
8893 							    dst_ill->ill_name);
8894 						}
8895 						goto icmp_err_ret;
8896 					}
8897 				}
8898 				save_dst = dst;
8899 				dst = gw;
8900 				gw = INADDR_ANY;
8901 			}
8902 
8903 			/*
8904 			 * We obtain a partial IRE_CACHE which we will pass
8905 			 * along with the resolver query.  When the response
8906 			 * comes back it will be there ready for us to add.
8907 			 * The ire_max_frag is atomically set under the
8908 			 * irebucket lock in ire_add_v[46].
8909 			 */
8910 
8911 			ire = ire_create_mp(
8912 			    (uchar_t *)&dst,		/* dest address */
8913 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8914 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8915 			    (uchar_t *)&gw,		/* gateway address */
8916 			    NULL,			/* no in_src_addr */
8917 			    NULL,			/* ire_max_frag */
8918 			    NULL,			/* Fast Path header */
8919 			    dst_ill->ill_rq,		/* recv-from queue */
8920 			    dst_ill->ill_wq,		/* send-to queue */
8921 			    IRE_CACHE,
8922 			    NULL,
8923 			    src_ipif,			/* Interface ipif */
8924 			    in_ill,			/* Incoming ILL */
8925 			    save_ire->ire_mask,		/* Parent mask */
8926 			    0,
8927 			    save_ire->ire_ihandle,	/* Interface handle */
8928 			    0,				/* flags if any */
8929 			    &(save_ire->ire_uinfo),
8930 			    NULL,
8931 			    NULL,
8932 			    ipst);
8933 
8934 			if (ire == NULL) {
8935 				ire_refrele(save_ire);
8936 				break;
8937 			}
8938 
8939 			if ((sire != NULL) &&
8940 			    (sire->ire_flags & RTF_MULTIRT)) {
8941 				copy_mp = copymsg(first_mp);
8942 				if (copy_mp != NULL)
8943 					MULTIRT_DEBUG_TAG(copy_mp);
8944 			}
8945 
8946 			ire->ire_marks |= ire_marks;
8947 
8948 			/*
8949 			 * Construct message chain for the resolver
8950 			 * of the form:
8951 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8952 			 * Packet could contain a IPSEC_OUT mp.
8953 			 *
8954 			 * NOTE : ire will be added later when the response
8955 			 * comes back from ARP. If the response does not
8956 			 * come back, ARP frees the packet. For this reason,
8957 			 * we can't REFHOLD the bucket of save_ire to prevent
8958 			 * deletions. We may not be able to REFRELE the bucket
8959 			 * if the response never comes back. Thus, before
8960 			 * adding the ire, ire_add_v4 will make sure that the
8961 			 * interface route does not get deleted. This is the
8962 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8963 			 * where we can always prevent deletions because of
8964 			 * the synchronous nature of adding IRES i.e
8965 			 * ire_add_then_send is called after creating the IRE.
8966 			 */
8967 			ASSERT(ire->ire_mp != NULL);
8968 			ire->ire_mp->b_cont = first_mp;
8969 			/* Have saved_mp handy, for cleanup if canput fails */
8970 			saved_mp = mp;
8971 			mp = copyb(res_mp);
8972 			if (mp == NULL) {
8973 				/* Prepare for cleanup */
8974 				mp = saved_mp; /* pkt */
8975 				ire_delete(ire); /* ire_mp */
8976 				ire = NULL;
8977 				ire_refrele(save_ire);
8978 				if (copy_mp != NULL) {
8979 					MULTIRT_DEBUG_UNTAG(copy_mp);
8980 					freemsg(copy_mp);
8981 					copy_mp = NULL;
8982 				}
8983 				break;
8984 			}
8985 			linkb(mp, ire->ire_mp);
8986 
8987 			/*
8988 			 * Fill in the source and dest addrs for the resolver.
8989 			 * NOTE: this depends on memory layouts imposed by
8990 			 * ill_init().
8991 			 */
8992 			areq = (areq_t *)mp->b_rptr;
8993 			addrp = (ipaddr_t *)((char *)areq +
8994 			    areq->areq_sender_addr_offset);
8995 			if (do_attach_ill) {
8996 				/*
8997 				 * This is bind to no failover case.
8998 				 * arp packet also must go out on attach_ill.
8999 				 */
9000 				ASSERT(ipha->ipha_src != NULL);
9001 				*addrp = ipha->ipha_src;
9002 			} else {
9003 				*addrp = save_ire->ire_src_addr;
9004 			}
9005 
9006 			ire_refrele(save_ire);
9007 			addrp = (ipaddr_t *)((char *)areq +
9008 			    areq->areq_target_addr_offset);
9009 			*addrp = dst;
9010 			/* Up to the resolver. */
9011 			if (canputnext(dst_ill->ill_rq) &&
9012 			    !(dst_ill->ill_arp_closing)) {
9013 				putnext(dst_ill->ill_rq, mp);
9014 				ire = NULL;
9015 				if (copy_mp != NULL) {
9016 					/*
9017 					 * If we found a resolver, we ignore
9018 					 * any trailing top priority IRE_CACHE
9019 					 * in the further loops. This ensures
9020 					 * that we do not omit any resolver.
9021 					 * IRE_CACHE entries, if any, will be
9022 					 * processed next time we enter
9023 					 * ip_newroute().
9024 					 */
9025 					multirt_flags &= ~MULTIRT_CACHEGW;
9026 					/*
9027 					 * Search for the next unresolved
9028 					 * multirt route.
9029 					 */
9030 					first_mp = copy_mp;
9031 					copy_mp = NULL;
9032 					/* Prepare the next resolution loop. */
9033 					mp = first_mp;
9034 					EXTRACT_PKT_MP(mp, first_mp,
9035 					    mctl_present);
9036 					if (mctl_present)
9037 						io = (ipsec_out_t *)
9038 						    first_mp->b_rptr;
9039 					ipha = (ipha_t *)mp->b_rptr;
9040 
9041 					ASSERT(sire != NULL);
9042 
9043 					dst = save_dst;
9044 					multirt_resolve_next = B_TRUE;
9045 					continue;
9046 				}
9047 
9048 				if (sire != NULL)
9049 					ire_refrele(sire);
9050 
9051 				/*
9052 				 * The response will come back in ip_wput
9053 				 * with db_type IRE_DB_TYPE.
9054 				 */
9055 				ipif_refrele(src_ipif);
9056 				ill_refrele(dst_ill);
9057 				return;
9058 			} else {
9059 				/* Prepare for cleanup */
9060 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
9061 				    mp);
9062 				mp->b_cont = NULL;
9063 				freeb(mp); /* areq */
9064 				/*
9065 				 * this is an ire that is not added to the
9066 				 * cache. ire_freemblk will handle the release
9067 				 * of any resources associated with the ire.
9068 				 */
9069 				ire_delete(ire); /* ire_mp */
9070 				mp = saved_mp; /* pkt */
9071 				ire = NULL;
9072 				if (copy_mp != NULL) {
9073 					MULTIRT_DEBUG_UNTAG(copy_mp);
9074 					freemsg(copy_mp);
9075 					copy_mp = NULL;
9076 				}
9077 				break;
9078 			}
9079 		default:
9080 			break;
9081 		}
9082 	} while (multirt_resolve_next);
9083 
9084 	ip1dbg(("ip_newroute: dropped\n"));
9085 	/* Did this packet originate externally? */
9086 	if (mp->b_prev) {
9087 		mp->b_next = NULL;
9088 		mp->b_prev = NULL;
9089 		if (in_ill != NULL) {
9090 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
9091 		} else {
9092 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9093 		}
9094 	} else {
9095 		if (dst_ill != NULL) {
9096 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
9097 		} else {
9098 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
9099 		}
9100 	}
9101 	ASSERT(copy_mp == NULL);
9102 	MULTIRT_DEBUG_UNTAG(first_mp);
9103 	freemsg(first_mp);
9104 	if (ire != NULL)
9105 		ire_refrele(ire);
9106 	if (sire != NULL)
9107 		ire_refrele(sire);
9108 	if (src_ipif != NULL)
9109 		ipif_refrele(src_ipif);
9110 	if (dst_ill != NULL)
9111 		ill_refrele(dst_ill);
9112 	return;
9113 
9114 icmp_err_ret:
9115 	ip1dbg(("ip_newroute: no route\n"));
9116 	if (src_ipif != NULL)
9117 		ipif_refrele(src_ipif);
9118 	if (dst_ill != NULL)
9119 		ill_refrele(dst_ill);
9120 	if (sire != NULL)
9121 		ire_refrele(sire);
9122 	/* Did this packet originate externally? */
9123 	if (mp->b_prev) {
9124 		mp->b_next = NULL;
9125 		mp->b_prev = NULL;
9126 		if (in_ill != NULL) {
9127 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
9128 		} else {
9129 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9130 		}
9131 		q = WR(q);
9132 	} else {
9133 		/*
9134 		 * There is no outgoing ill, so just increment the
9135 		 * system MIB.
9136 		 */
9137 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9138 		/*
9139 		 * Since ip_wput() isn't close to finished, we fill
9140 		 * in enough of the header for credible error reporting.
9141 		 */
9142 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9143 			/* Failed */
9144 			MULTIRT_DEBUG_UNTAG(first_mp);
9145 			freemsg(first_mp);
9146 			if (ire != NULL)
9147 				ire_refrele(ire);
9148 			return;
9149 		}
9150 	}
9151 
9152 	/*
9153 	 * At this point we will have ire only if RTF_BLACKHOLE
9154 	 * or RTF_REJECT flags are set on the IRE. It will not
9155 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9156 	 */
9157 	if (ire != NULL) {
9158 		if (ire->ire_flags & RTF_BLACKHOLE) {
9159 			ire_refrele(ire);
9160 			MULTIRT_DEBUG_UNTAG(first_mp);
9161 			freemsg(first_mp);
9162 			return;
9163 		}
9164 		ire_refrele(ire);
9165 	}
9166 	if (ip_source_routed(ipha, ipst)) {
9167 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9168 		    zoneid, ipst);
9169 		return;
9170 	}
9171 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9172 }
9173 
9174 ip_opt_info_t zero_info;
9175 
9176 /*
9177  * IPv4 -
9178  * ip_newroute_ipif is called by ip_wput_multicast and
9179  * ip_rput_forward_multicast whenever we need to send
9180  * out a packet to a destination address for which we do not have specific
9181  * routing information. It is used when the packet will be sent out
9182  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9183  * socket option is set or icmp error message wants to go out on a particular
9184  * interface for a unicast packet.
9185  *
9186  * In most cases, the destination address is resolved thanks to the ipif
9187  * intrinsic resolver. However, there are some cases where the call to
9188  * ip_newroute_ipif must take into account the potential presence of
9189  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9190  * that uses the interface. This is specified through flags,
9191  * which can be a combination of:
9192  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9193  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9194  *   and flags. Additionally, the packet source address has to be set to
9195  *   the specified address. The caller is thus expected to set this flag
9196  *   if the packet has no specific source address yet.
9197  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9198  *   flag, the resulting ire will inherit the flag. All unresolved routes
9199  *   to the destination must be explored in the same call to
9200  *   ip_newroute_ipif().
9201  */
9202 static void
9203 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9204     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9205 {
9206 	areq_t	*areq;
9207 	ire_t	*ire = NULL;
9208 	mblk_t	*res_mp;
9209 	ipaddr_t *addrp;
9210 	mblk_t *first_mp;
9211 	ire_t	*save_ire = NULL;
9212 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9213 	ipif_t	*src_ipif = NULL;
9214 	ushort_t ire_marks = 0;
9215 	ill_t	*dst_ill = NULL;
9216 	boolean_t mctl_present;
9217 	ipsec_out_t *io;
9218 	ipha_t *ipha;
9219 	int	ihandle = 0;
9220 	mblk_t	*saved_mp;
9221 	ire_t   *fire = NULL;
9222 	mblk_t  *copy_mp = NULL;
9223 	boolean_t multirt_resolve_next;
9224 	ipaddr_t ipha_dst;
9225 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9226 
9227 	/*
9228 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9229 	 * here for uniformity
9230 	 */
9231 	ipif_refhold(ipif);
9232 
9233 	/*
9234 	 * This loop is run only once in most cases.
9235 	 * We loop to resolve further routes only when the destination
9236 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9237 	 */
9238 	do {
9239 		if (dst_ill != NULL) {
9240 			ill_refrele(dst_ill);
9241 			dst_ill = NULL;
9242 		}
9243 		if (src_ipif != NULL) {
9244 			ipif_refrele(src_ipif);
9245 			src_ipif = NULL;
9246 		}
9247 		multirt_resolve_next = B_FALSE;
9248 
9249 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9250 		    ipif->ipif_ill->ill_name));
9251 
9252 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9253 		if (mctl_present)
9254 			io = (ipsec_out_t *)first_mp->b_rptr;
9255 
9256 		ipha = (ipha_t *)mp->b_rptr;
9257 
9258 		/*
9259 		 * Save the packet destination address, we may need it after
9260 		 * the packet has been consumed.
9261 		 */
9262 		ipha_dst = ipha->ipha_dst;
9263 
9264 		/*
9265 		 * If the interface is a pt-pt interface we look for an
9266 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9267 		 * local_address and the pt-pt destination address. Otherwise
9268 		 * we just match the local address.
9269 		 * NOTE: dst could be different than ipha->ipha_dst in case
9270 		 * of sending igmp multicast packets over a point-to-point
9271 		 * connection.
9272 		 * Thus we must be careful enough to check ipha_dst to be a
9273 		 * multicast address, otherwise it will take xmit_if path for
9274 		 * multicast packets resulting into kernel stack overflow by
9275 		 * repeated calls to ip_newroute_ipif from ire_send().
9276 		 */
9277 		if (CLASSD(ipha_dst) &&
9278 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9279 			goto err_ret;
9280 		}
9281 
9282 		/*
9283 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9284 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9285 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9286 		 * propagate its flags to the new ire.
9287 		 */
9288 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9289 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9290 			ip2dbg(("ip_newroute_ipif: "
9291 			    "ipif_lookup_multi_ire("
9292 			    "ipif %p, dst %08x) = fire %p\n",
9293 			    (void *)ipif, ntohl(dst), (void *)fire));
9294 		}
9295 
9296 		if (mctl_present && io->ipsec_out_attach_if) {
9297 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9298 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9299 
9300 			/* Failure case frees things for us. */
9301 			if (attach_ill == NULL) {
9302 				ipif_refrele(ipif);
9303 				if (fire != NULL)
9304 					ire_refrele(fire);
9305 				return;
9306 			}
9307 
9308 			/*
9309 			 * Check if we need an ire that will not be
9310 			 * looked up by anybody else i.e. HIDDEN.
9311 			 */
9312 			if (ill_is_probeonly(attach_ill)) {
9313 				ire_marks = IRE_MARK_HIDDEN;
9314 			}
9315 			/*
9316 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9317 			 * case.
9318 			 */
9319 			dst_ill = ipif->ipif_ill;
9320 			/* attach_ill has been refheld by ip_grab_attach_ill */
9321 			ASSERT(dst_ill == attach_ill);
9322 		} else {
9323 			/*
9324 			 * If this is set by IP_XMIT_IF, then make sure that
9325 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9326 			 * specified ill.
9327 			 */
9328 			ASSERT((connp == NULL) ||
9329 			    (connp->conn_xmit_if_ill == NULL) ||
9330 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9331 			/*
9332 			 * If the interface belongs to an interface group,
9333 			 * make sure the next possible interface in the group
9334 			 * is used.  This encourages load spreading among
9335 			 * peers in an interface group.
9336 			 * Note: load spreading is disabled for RTF_MULTIRT
9337 			 * routes.
9338 			 */
9339 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9340 			    (fire->ire_flags & RTF_MULTIRT)) {
9341 				/*
9342 				 * Don't perform outbound load spreading
9343 				 * in the case of an RTF_MULTIRT issued route,
9344 				 * we actually typically want to replicate
9345 				 * outgoing packets through particular
9346 				 * interfaces.
9347 				 */
9348 				dst_ill = ipif->ipif_ill;
9349 				ill_refhold(dst_ill);
9350 			} else {
9351 				dst_ill = ip_newroute_get_dst_ill(
9352 				    ipif->ipif_ill);
9353 			}
9354 			if (dst_ill == NULL) {
9355 				if (ip_debug > 2) {
9356 					pr_addr_dbg("ip_newroute_ipif: "
9357 					    "no dst ill for dst %s\n",
9358 					    AF_INET, &dst);
9359 				}
9360 				goto err_ret;
9361 			}
9362 		}
9363 
9364 		/*
9365 		 * Pick a source address preferring non-deprecated ones.
9366 		 * Unlike ip_newroute, we don't do any source address
9367 		 * selection here since for multicast it really does not help
9368 		 * in inbound load spreading as in the unicast case.
9369 		 */
9370 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9371 		    (fire->ire_flags & RTF_SETSRC)) {
9372 			/*
9373 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9374 			 * on that interface. This ire has RTF_SETSRC flag, so
9375 			 * the source address of the packet must be changed.
9376 			 * Check that the ipif matching the requested source
9377 			 * address still exists.
9378 			 */
9379 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9380 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9381 		}
9382 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9383 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9384 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9385 		    (src_ipif == NULL)) {
9386 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9387 			if (src_ipif == NULL) {
9388 				if (ip_debug > 2) {
9389 					/* ip1dbg */
9390 					pr_addr_dbg("ip_newroute_ipif: "
9391 					    "no src for dst %s",
9392 					    AF_INET, &dst);
9393 				}
9394 				ip1dbg((" through interface %s\n",
9395 				    dst_ill->ill_name));
9396 				goto err_ret;
9397 			}
9398 			ipif_refrele(ipif);
9399 			ipif = src_ipif;
9400 			ipif_refhold(ipif);
9401 		}
9402 		if (src_ipif == NULL) {
9403 			src_ipif = ipif;
9404 			ipif_refhold(src_ipif);
9405 		}
9406 
9407 		/*
9408 		 * Assign a source address while we have the conn.
9409 		 * We can't have ip_wput_ire pick a source address when the
9410 		 * packet returns from arp since conn_unspec_src might be set
9411 		 * and we loose the conn when going through arp.
9412 		 */
9413 		if (ipha->ipha_src == INADDR_ANY &&
9414 		    (connp == NULL || !connp->conn_unspec_src)) {
9415 			ipha->ipha_src = src_ipif->ipif_src_addr;
9416 		}
9417 
9418 		/*
9419 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9420 		 * interface does not have an interface ire.
9421 		 * Example: Thousands of mobileip PPP interfaces to mobile
9422 		 * nodes. We don't want to create interface ires because
9423 		 * packets from other mobile nodes must not take the route
9424 		 * via interface ires to the visiting mobile node without
9425 		 * going through the home agent, in absence of mobileip
9426 		 * route optimization.
9427 		 */
9428 		if (CLASSD(ipha_dst) && (connp == NULL ||
9429 		    connp->conn_xmit_if_ill == NULL) &&
9430 		    infop->ip_opt_ill_index == 0) {
9431 			/* ipif_to_ire returns an held ire */
9432 			ire = ipif_to_ire(ipif);
9433 			if (ire == NULL)
9434 				goto err_ret;
9435 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9436 				goto err_ret;
9437 			/*
9438 			 * ihandle is needed when the ire is added to
9439 			 * cache table.
9440 			 */
9441 			save_ire = ire;
9442 			ihandle = save_ire->ire_ihandle;
9443 
9444 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9445 			    "flags %04x\n",
9446 			    (void *)ire, (void *)ipif, flags));
9447 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9448 			    (fire->ire_flags & RTF_MULTIRT)) {
9449 				/*
9450 				 * As requested by flags, an IRE_OFFSUBNET was
9451 				 * looked up on that interface. This ire has
9452 				 * RTF_MULTIRT flag, so the resolution loop will
9453 				 * be re-entered to resolve additional routes on
9454 				 * other interfaces. For that purpose, a copy of
9455 				 * the packet is performed at this point.
9456 				 */
9457 				fire->ire_last_used_time = lbolt;
9458 				copy_mp = copymsg(first_mp);
9459 				if (copy_mp) {
9460 					MULTIRT_DEBUG_TAG(copy_mp);
9461 				}
9462 			}
9463 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9464 			    (fire->ire_flags & RTF_SETSRC)) {
9465 				/*
9466 				 * As requested by flags, an IRE_OFFSUBET was
9467 				 * looked up on that interface. This ire has
9468 				 * RTF_SETSRC flag, so the source address of the
9469 				 * packet must be changed.
9470 				 */
9471 				ipha->ipha_src = fire->ire_src_addr;
9472 			}
9473 		} else {
9474 			ASSERT((connp == NULL) ||
9475 			    (connp->conn_xmit_if_ill != NULL) ||
9476 			    (connp->conn_dontroute) ||
9477 			    infop->ip_opt_ill_index != 0);
9478 			/*
9479 			 * The only ways we can come here are:
9480 			 * 1) IP_XMIT_IF socket option is set
9481 			 * 2) ICMP error message generated from
9482 			 *    ip_mrtun_forward() routine and it needs
9483 			 *    to go through the specified ill.
9484 			 * 3) SO_DONTROUTE socket option is set
9485 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9486 			 * In all cases, the new ire will not be added
9487 			 * into cache table.
9488 			 */
9489 			ire_marks |= IRE_MARK_NOADD;
9490 		}
9491 
9492 		switch (ipif->ipif_net_type) {
9493 		case IRE_IF_NORESOLVER: {
9494 			/* We have what we need to build an IRE_CACHE. */
9495 			mblk_t	*res_mp;
9496 
9497 			/*
9498 			 * Create a new res_mp with the
9499 			 * IP gateway address as destination address in the
9500 			 * DLPI hdr if the physical length is exactly 4 bytes.
9501 			 */
9502 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9503 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9504 				    dst_ill->ill_phys_addr_length,
9505 				    dst_ill->ill_sap,
9506 				    dst_ill->ill_sap_length);
9507 			} else if (dst_ill->ill_resolver_mp == NULL) {
9508 				ip1dbg(("ip_newroute: dst_ill %p "
9509 				    "for IF_NORESOLV ire %p has "
9510 				    "no ill_resolver_mp\n",
9511 				    (void *)dst_ill, (void *)ire));
9512 				break;
9513 			} else {
9514 				/* use the value set in ip_ll_subnet_defaults */
9515 				res_mp = ill_dlur_gen(NULL,
9516 				    dst_ill->ill_phys_addr_length,
9517 				    dst_ill->ill_sap,
9518 				    dst_ill->ill_sap_length);
9519 			}
9520 
9521 			if (res_mp == NULL)
9522 				break;
9523 			/*
9524 			 * The new ire inherits the IRE_OFFSUBNET flags
9525 			 * and source address, if this was requested.
9526 			 */
9527 			ire = ire_create(
9528 			    (uchar_t *)&dst,		/* dest address */
9529 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9530 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9531 			    NULL,			/* gateway address */
9532 			    NULL,
9533 			    &ipif->ipif_mtu,
9534 			    NULL,			/* Fast Path header */
9535 			    dst_ill->ill_rq,		/* recv-from queue */
9536 			    dst_ill->ill_wq,		/* send-to queue */
9537 			    IRE_CACHE,
9538 			    res_mp,
9539 			    src_ipif,
9540 			    NULL,
9541 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9542 			    (fire != NULL) ?		/* Parent handle */
9543 				fire->ire_phandle : 0,
9544 			    ihandle,			/* Interface handle */
9545 			    (fire != NULL) ?
9546 				(fire->ire_flags &
9547 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9548 			    (save_ire == NULL ? &ire_uinfo_null :
9549 				&save_ire->ire_uinfo),
9550 			    NULL,
9551 			    NULL,
9552 			    ipst);
9553 
9554 			freeb(res_mp);
9555 
9556 			if (ire == NULL) {
9557 				if (save_ire != NULL)
9558 					ire_refrele(save_ire);
9559 				break;
9560 			}
9561 
9562 			ire->ire_marks |= ire_marks;
9563 
9564 			/*
9565 			 * If IRE_MARK_NOADD is set then we need to convert
9566 			 * the max_fragp to a useable value now. This is
9567 			 * normally done in ire_add_v[46]. We also need to
9568 			 * associate the ire with an nce (normally would be
9569 			 * done in ip_wput_nondata()).
9570 			 *
9571 			 * Note that IRE_MARK_NOADD packets created here
9572 			 * do not have a non-null ire_mp pointer. The null
9573 			 * value of ire_bucket indicates that they were
9574 			 * never added.
9575 			 */
9576 			if (ire->ire_marks & IRE_MARK_NOADD) {
9577 				uint_t  max_frag;
9578 
9579 				max_frag = *ire->ire_max_fragp;
9580 				ire->ire_max_fragp = NULL;
9581 				ire->ire_max_frag = max_frag;
9582 
9583 				if ((ire->ire_nce = ndp_lookup_v4(
9584 				    ire_to_ill(ire),
9585 				    (ire->ire_gateway_addr != INADDR_ANY ?
9586 				    &ire->ire_gateway_addr : &ire->ire_addr),
9587 				    B_FALSE)) == NULL) {
9588 					if (save_ire != NULL)
9589 						ire_refrele(save_ire);
9590 					break;
9591 				}
9592 				ASSERT(ire->ire_nce->nce_state ==
9593 				    ND_REACHABLE);
9594 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9595 			}
9596 
9597 			/* Prevent save_ire from getting deleted */
9598 			if (save_ire != NULL) {
9599 				IRB_REFHOLD(save_ire->ire_bucket);
9600 				/* Has it been removed already ? */
9601 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9602 					IRB_REFRELE(save_ire->ire_bucket);
9603 					ire_refrele(save_ire);
9604 					break;
9605 				}
9606 			}
9607 
9608 			ire_add_then_send(q, ire, first_mp);
9609 
9610 			/* Assert that save_ire is not deleted yet. */
9611 			if (save_ire != NULL) {
9612 				ASSERT(save_ire->ire_ptpn != NULL);
9613 				IRB_REFRELE(save_ire->ire_bucket);
9614 				ire_refrele(save_ire);
9615 				save_ire = NULL;
9616 			}
9617 			if (fire != NULL) {
9618 				ire_refrele(fire);
9619 				fire = NULL;
9620 			}
9621 
9622 			/*
9623 			 * the resolution loop is re-entered if this
9624 			 * was requested through flags and if we
9625 			 * actually are in a multirouting case.
9626 			 */
9627 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9628 				boolean_t need_resolve =
9629 				    ire_multirt_need_resolve(ipha_dst,
9630 					MBLK_GETLABEL(copy_mp), ipst);
9631 				if (!need_resolve) {
9632 					MULTIRT_DEBUG_UNTAG(copy_mp);
9633 					freemsg(copy_mp);
9634 					copy_mp = NULL;
9635 				} else {
9636 					/*
9637 					 * ipif_lookup_group() calls
9638 					 * ire_lookup_multi() that uses
9639 					 * ire_ftable_lookup() to find
9640 					 * an IRE_INTERFACE for the group.
9641 					 * In the multirt case,
9642 					 * ire_lookup_multi() then invokes
9643 					 * ire_multirt_lookup() to find
9644 					 * the next resolvable ire.
9645 					 * As a result, we obtain an new
9646 					 * interface, derived from the
9647 					 * next ire.
9648 					 */
9649 					ipif_refrele(ipif);
9650 					ipif = ipif_lookup_group(ipha_dst,
9651 					    zoneid, ipst);
9652 					ip2dbg(("ip_newroute_ipif: "
9653 					    "multirt dst %08x, ipif %p\n",
9654 					    htonl(dst), (void *)ipif));
9655 					if (ipif != NULL) {
9656 						mp = copy_mp;
9657 						copy_mp = NULL;
9658 						multirt_resolve_next = B_TRUE;
9659 						continue;
9660 					} else {
9661 						freemsg(copy_mp);
9662 					}
9663 				}
9664 			}
9665 			if (ipif != NULL)
9666 				ipif_refrele(ipif);
9667 			ill_refrele(dst_ill);
9668 			ipif_refrele(src_ipif);
9669 			return;
9670 		}
9671 		case IRE_IF_RESOLVER:
9672 			/*
9673 			 * We can't build an IRE_CACHE yet, but at least
9674 			 * we found a resolver that can help.
9675 			 */
9676 			res_mp = dst_ill->ill_resolver_mp;
9677 			if (!OK_RESOLVER_MP(res_mp))
9678 				break;
9679 
9680 			/*
9681 			 * We obtain a partial IRE_CACHE which we will pass
9682 			 * along with the resolver query.  When the response
9683 			 * comes back it will be there ready for us to add.
9684 			 * The new ire inherits the IRE_OFFSUBNET flags
9685 			 * and source address, if this was requested.
9686 			 * The ire_max_frag is atomically set under the
9687 			 * irebucket lock in ire_add_v[46]. Only in the
9688 			 * case of IRE_MARK_NOADD, we set it here itself.
9689 			 */
9690 			ire = ire_create_mp(
9691 			    (uchar_t *)&dst,		/* dest address */
9692 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9693 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9694 			    NULL,			/* gateway address */
9695 			    NULL,			/* no in_src_addr */
9696 			    (ire_marks & IRE_MARK_NOADD) ?
9697 				ipif->ipif_mtu : 0,	/* max_frag */
9698 			    NULL,			/* Fast path header */
9699 			    dst_ill->ill_rq,		/* recv-from queue */
9700 			    dst_ill->ill_wq,		/* send-to queue */
9701 			    IRE_CACHE,
9702 			    NULL,	/* let ire_nce_init figure res_mp out */
9703 			    src_ipif,
9704 			    NULL,
9705 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9706 			    (fire != NULL) ?		/* Parent handle */
9707 				fire->ire_phandle : 0,
9708 			    ihandle,			/* Interface handle */
9709 			    (fire != NULL) ?		/* flags if any */
9710 				(fire->ire_flags &
9711 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9712 			    (save_ire == NULL ? &ire_uinfo_null :
9713 				&save_ire->ire_uinfo),
9714 			    NULL,
9715 			    NULL,
9716 			    ipst);
9717 
9718 			if (save_ire != NULL) {
9719 				ire_refrele(save_ire);
9720 				save_ire = NULL;
9721 			}
9722 			if (ire == NULL)
9723 				break;
9724 
9725 			ire->ire_marks |= ire_marks;
9726 			/*
9727 			 * Construct message chain for the resolver of the
9728 			 * form:
9729 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9730 			 *
9731 			 * NOTE : ire will be added later when the response
9732 			 * comes back from ARP. If the response does not
9733 			 * come back, ARP frees the packet. For this reason,
9734 			 * we can't REFHOLD the bucket of save_ire to prevent
9735 			 * deletions. We may not be able to REFRELE the
9736 			 * bucket if the response never comes back.
9737 			 * Thus, before adding the ire, ire_add_v4 will make
9738 			 * sure that the interface route does not get deleted.
9739 			 * This is the only case unlike ip_newroute_v6,
9740 			 * ip_newroute_ipif_v6 where we can always prevent
9741 			 * deletions because ire_add_then_send is called after
9742 			 * creating the IRE.
9743 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9744 			 * does not add this IRE into the IRE CACHE.
9745 			 */
9746 			ASSERT(ire->ire_mp != NULL);
9747 			ire->ire_mp->b_cont = first_mp;
9748 			/* Have saved_mp handy, for cleanup if canput fails */
9749 			saved_mp = mp;
9750 			mp = copyb(res_mp);
9751 			if (mp == NULL) {
9752 				/* Prepare for cleanup */
9753 				mp = saved_mp; /* pkt */
9754 				ire_delete(ire); /* ire_mp */
9755 				ire = NULL;
9756 				if (copy_mp != NULL) {
9757 					MULTIRT_DEBUG_UNTAG(copy_mp);
9758 					freemsg(copy_mp);
9759 					copy_mp = NULL;
9760 				}
9761 				break;
9762 			}
9763 			linkb(mp, ire->ire_mp);
9764 
9765 			/*
9766 			 * Fill in the source and dest addrs for the resolver.
9767 			 * NOTE: this depends on memory layouts imposed by
9768 			 * ill_init().
9769 			 */
9770 			areq = (areq_t *)mp->b_rptr;
9771 			addrp = (ipaddr_t *)((char *)areq +
9772 			    areq->areq_sender_addr_offset);
9773 			*addrp = ire->ire_src_addr;
9774 			addrp = (ipaddr_t *)((char *)areq +
9775 			    areq->areq_target_addr_offset);
9776 			*addrp = dst;
9777 			/* Up to the resolver. */
9778 			if (canputnext(dst_ill->ill_rq) &&
9779 			    !(dst_ill->ill_arp_closing)) {
9780 				putnext(dst_ill->ill_rq, mp);
9781 				/*
9782 				 * The response will come back in ip_wput
9783 				 * with db_type IRE_DB_TYPE.
9784 				 */
9785 			} else {
9786 				mp->b_cont = NULL;
9787 				freeb(mp); /* areq */
9788 				ire_delete(ire); /* ire_mp */
9789 				saved_mp->b_next = NULL;
9790 				saved_mp->b_prev = NULL;
9791 				freemsg(first_mp); /* pkt */
9792 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9793 			}
9794 
9795 			if (fire != NULL) {
9796 				ire_refrele(fire);
9797 				fire = NULL;
9798 			}
9799 
9800 
9801 			/*
9802 			 * The resolution loop is re-entered if this was
9803 			 * requested through flags and we actually are
9804 			 * in a multirouting case.
9805 			 */
9806 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9807 				boolean_t need_resolve =
9808 				    ire_multirt_need_resolve(ipha_dst,
9809 					MBLK_GETLABEL(copy_mp), ipst);
9810 				if (!need_resolve) {
9811 					MULTIRT_DEBUG_UNTAG(copy_mp);
9812 					freemsg(copy_mp);
9813 					copy_mp = NULL;
9814 				} else {
9815 					/*
9816 					 * ipif_lookup_group() calls
9817 					 * ire_lookup_multi() that uses
9818 					 * ire_ftable_lookup() to find
9819 					 * an IRE_INTERFACE for the group.
9820 					 * In the multirt case,
9821 					 * ire_lookup_multi() then invokes
9822 					 * ire_multirt_lookup() to find
9823 					 * the next resolvable ire.
9824 					 * As a result, we obtain an new
9825 					 * interface, derived from the
9826 					 * next ire.
9827 					 */
9828 					ipif_refrele(ipif);
9829 					ipif = ipif_lookup_group(ipha_dst,
9830 					    zoneid, ipst);
9831 					if (ipif != NULL) {
9832 						mp = copy_mp;
9833 						copy_mp = NULL;
9834 						multirt_resolve_next = B_TRUE;
9835 						continue;
9836 					} else {
9837 						freemsg(copy_mp);
9838 					}
9839 				}
9840 			}
9841 			if (ipif != NULL)
9842 				ipif_refrele(ipif);
9843 			ill_refrele(dst_ill);
9844 			ipif_refrele(src_ipif);
9845 			return;
9846 		default:
9847 			break;
9848 		}
9849 	} while (multirt_resolve_next);
9850 
9851 err_ret:
9852 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9853 	if (fire != NULL)
9854 		ire_refrele(fire);
9855 	ipif_refrele(ipif);
9856 	/* Did this packet originate externally? */
9857 	if (dst_ill != NULL)
9858 		ill_refrele(dst_ill);
9859 	if (src_ipif != NULL)
9860 		ipif_refrele(src_ipif);
9861 	if (mp->b_prev || mp->b_next) {
9862 		mp->b_next = NULL;
9863 		mp->b_prev = NULL;
9864 	} else {
9865 		/*
9866 		 * Since ip_wput() isn't close to finished, we fill
9867 		 * in enough of the header for credible error reporting.
9868 		 */
9869 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9870 			/* Failed */
9871 			freemsg(first_mp);
9872 			if (ire != NULL)
9873 				ire_refrele(ire);
9874 			return;
9875 		}
9876 	}
9877 	/*
9878 	 * At this point we will have ire only if RTF_BLACKHOLE
9879 	 * or RTF_REJECT flags are set on the IRE. It will not
9880 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9881 	 */
9882 	if (ire != NULL) {
9883 		if (ire->ire_flags & RTF_BLACKHOLE) {
9884 			ire_refrele(ire);
9885 			freemsg(first_mp);
9886 			return;
9887 		}
9888 		ire_refrele(ire);
9889 	}
9890 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9891 }
9892 
9893 /* Name/Value Table Lookup Routine */
9894 char *
9895 ip_nv_lookup(nv_t *nv, int value)
9896 {
9897 	if (!nv)
9898 		return (NULL);
9899 	for (; nv->nv_name; nv++) {
9900 		if (nv->nv_value == value)
9901 			return (nv->nv_name);
9902 	}
9903 	return ("unknown");
9904 }
9905 
9906 /*
9907  * This is a module open, i.e. this is a control stream for access
9908  * to a DLPI device.  We allocate an ill_t as the instance data in
9909  * this case.
9910  */
9911 int
9912 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9913 {
9914 	ill_t	*ill;
9915 	int	err;
9916 	zoneid_t zoneid;
9917 	netstack_t *ns;
9918 	ip_stack_t *ipst;
9919 
9920 	/*
9921 	 * Prevent unprivileged processes from pushing IP so that
9922 	 * they can't send raw IP.
9923 	 */
9924 	if (secpolicy_net_rawaccess(credp) != 0)
9925 		return (EPERM);
9926 
9927 	ns = netstack_find_by_cred(credp);
9928 	ASSERT(ns != NULL);
9929 	ipst = ns->netstack_ip;
9930 	ASSERT(ipst != NULL);
9931 
9932 	/*
9933 	 * For exclusive stacks we set the zoneid to zero
9934 	 * to make IP operate as if in the global zone.
9935 	 */
9936 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9937 		zoneid = GLOBAL_ZONEID;
9938 	else
9939 		zoneid = crgetzoneid(credp);
9940 
9941 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9942 	q->q_ptr = WR(q)->q_ptr = ill;
9943 	ill->ill_ipst = ipst;
9944 	ill->ill_zoneid = zoneid;
9945 
9946 	/*
9947 	 * ill_init initializes the ill fields and then sends down
9948 	 * down a DL_INFO_REQ after calling qprocson.
9949 	 */
9950 	err = ill_init(q, ill);
9951 	if (err != 0) {
9952 		mi_free(ill);
9953 		netstack_rele(ipst->ips_netstack);
9954 		q->q_ptr = NULL;
9955 		WR(q)->q_ptr = NULL;
9956 		return (err);
9957 	}
9958 
9959 	/* ill_init initializes the ipsq marking this thread as writer */
9960 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9961 	/* Wait for the DL_INFO_ACK */
9962 	mutex_enter(&ill->ill_lock);
9963 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9964 		/*
9965 		 * Return value of 0 indicates a pending signal.
9966 		 */
9967 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9968 		if (err == 0) {
9969 			mutex_exit(&ill->ill_lock);
9970 			(void) ip_close(q, 0);
9971 			return (EINTR);
9972 		}
9973 	}
9974 	mutex_exit(&ill->ill_lock);
9975 
9976 	/*
9977 	 * ip_rput_other could have set an error  in ill_error on
9978 	 * receipt of M_ERROR.
9979 	 */
9980 
9981 	err = ill->ill_error;
9982 	if (err != 0) {
9983 		(void) ip_close(q, 0);
9984 		return (err);
9985 	}
9986 
9987 	ill->ill_credp = credp;
9988 	crhold(credp);
9989 
9990 	mutex_enter(&ipst->ips_ip_mi_lock);
9991 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9992 	    credp);
9993 	mutex_exit(&ipst->ips_ip_mi_lock);
9994 	if (err) {
9995 		(void) ip_close(q, 0);
9996 		return (err);
9997 	}
9998 	return (0);
9999 }
10000 
10001 /* IP open routine. */
10002 int
10003 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
10004 {
10005 	conn_t 		*connp;
10006 	major_t		maj;
10007 	zoneid_t	zoneid;
10008 	netstack_t	*ns;
10009 	ip_stack_t	*ipst;
10010 
10011 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
10012 
10013 	/* Allow reopen. */
10014 	if (q->q_ptr != NULL)
10015 		return (0);
10016 
10017 	if (sflag & MODOPEN) {
10018 		/* This is a module open */
10019 		return (ip_modopen(q, devp, flag, sflag, credp));
10020 	}
10021 
10022 	ns = netstack_find_by_cred(credp);
10023 	ASSERT(ns != NULL);
10024 	ipst = ns->netstack_ip;
10025 	ASSERT(ipst != NULL);
10026 
10027 	/*
10028 	 * For exclusive stacks we set the zoneid to zero
10029 	 * to make IP operate as if in the global zone.
10030 	 */
10031 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
10032 		zoneid = GLOBAL_ZONEID;
10033 	else
10034 		zoneid = crgetzoneid(credp);
10035 
10036 	/*
10037 	 * We are opening as a device. This is an IP client stream, and we
10038 	 * allocate an conn_t as the instance data.
10039 	 */
10040 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
10041 
10042 	/*
10043 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
10044 	 * done by netstack_find_by_cred()
10045 	 */
10046 	netstack_rele(ipst->ips_netstack);
10047 
10048 	connp->conn_zoneid = zoneid;
10049 
10050 	connp->conn_upq = q;
10051 	q->q_ptr = WR(q)->q_ptr = connp;
10052 
10053 	if (flag & SO_SOCKSTR)
10054 		connp->conn_flags |= IPCL_SOCKET;
10055 
10056 	/* Minor tells us which /dev entry was opened */
10057 	if (geteminor(*devp) == IPV6_MINOR) {
10058 		connp->conn_flags |= IPCL_ISV6;
10059 		connp->conn_af_isv6 = B_TRUE;
10060 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
10061 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
10062 	} else {
10063 		connp->conn_af_isv6 = B_FALSE;
10064 		connp->conn_pkt_isv6 = B_FALSE;
10065 	}
10066 
10067 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
10068 		/* CONN_DEC_REF takes care of netstack_rele() */
10069 		q->q_ptr = WR(q)->q_ptr = NULL;
10070 		CONN_DEC_REF(connp);
10071 		return (EBUSY);
10072 	}
10073 
10074 	maj = getemajor(*devp);
10075 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
10076 
10077 	/*
10078 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
10079 	 */
10080 	connp->conn_cred = credp;
10081 	crhold(connp->conn_cred);
10082 
10083 	/*
10084 	 * If the caller has the process-wide flag set, then default to MAC
10085 	 * exempt mode.  This allows read-down to unlabeled hosts.
10086 	 */
10087 	if (getpflags(NET_MAC_AWARE, credp) != 0)
10088 		connp->conn_mac_exempt = B_TRUE;
10089 
10090 	/*
10091 	 * This should only happen for ndd, netstat, raw socket or other SCTP
10092 	 * administrative ops.  In these cases, we just need a normal conn_t
10093 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
10094 	 * an error will be returned.
10095 	 */
10096 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
10097 		connp->conn_rq = q;
10098 		connp->conn_wq = WR(q);
10099 	} else {
10100 		connp->conn_ulp = IPPROTO_SCTP;
10101 		connp->conn_rq = connp->conn_wq = NULL;
10102 	}
10103 	/* Non-zero default values */
10104 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
10105 
10106 	/*
10107 	 * Make the conn globally visible to walkers
10108 	 */
10109 	mutex_enter(&connp->conn_lock);
10110 	connp->conn_state_flags &= ~CONN_INCIPIENT;
10111 	mutex_exit(&connp->conn_lock);
10112 	ASSERT(connp->conn_ref == 1);
10113 
10114 	qprocson(q);
10115 
10116 	return (0);
10117 }
10118 
10119 /*
10120  * Change q_qinfo based on the value of isv6.
10121  * This can not called on an ill queue.
10122  * Note that there is no race since either q_qinfo works for conn queues - it
10123  * is just an optimization to enter the best wput routine directly.
10124  */
10125 void
10126 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
10127 {
10128 	ASSERT(q->q_flag & QREADR);
10129 	ASSERT(WR(q)->q_next == NULL);
10130 	ASSERT(q->q_ptr != NULL);
10131 
10132 	if (minor == IPV6_MINOR)  {
10133 		if (bump_mib) {
10134 			BUMP_MIB(&ipst->ips_ip6_mib,
10135 			    ipIfStatsOutSwitchIPVersion);
10136 		}
10137 		q->q_qinfo = &rinit_ipv6;
10138 		WR(q)->q_qinfo = &winit_ipv6;
10139 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
10140 	} else {
10141 		if (bump_mib) {
10142 			BUMP_MIB(&ipst->ips_ip_mib,
10143 			    ipIfStatsOutSwitchIPVersion);
10144 		}
10145 		q->q_qinfo = &iprinit;
10146 		WR(q)->q_qinfo = &ipwinit;
10147 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
10148 	}
10149 
10150 }
10151 
10152 /*
10153  * See if IPsec needs loading because of the options in mp.
10154  */
10155 static boolean_t
10156 ipsec_opt_present(mblk_t *mp)
10157 {
10158 	uint8_t *optcp, *next_optcp, *opt_endcp;
10159 	struct opthdr *opt;
10160 	struct T_opthdr *topt;
10161 	int opthdr_len;
10162 	t_uscalar_t optname, optlevel;
10163 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10164 	ipsec_req_t *ipsr;
10165 
10166 	/*
10167 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10168 	 * return TRUE.
10169 	 */
10170 
10171 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10172 	opt_endcp = optcp + tor->OPT_length;
10173 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10174 		opthdr_len = sizeof (struct T_opthdr);
10175 	} else {		/* O_OPTMGMT_REQ */
10176 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10177 		opthdr_len = sizeof (struct opthdr);
10178 	}
10179 	for (; optcp < opt_endcp; optcp = next_optcp) {
10180 		if (optcp + opthdr_len > opt_endcp)
10181 			return (B_FALSE);	/* Not enough option header. */
10182 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10183 			topt = (struct T_opthdr *)optcp;
10184 			optlevel = topt->level;
10185 			optname = topt->name;
10186 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10187 		} else {
10188 			opt = (struct opthdr *)optcp;
10189 			optlevel = opt->level;
10190 			optname = opt->name;
10191 			next_optcp = optcp + opthdr_len +
10192 			    _TPI_ALIGN_OPT(opt->len);
10193 		}
10194 		if ((next_optcp < optcp) || /* wraparound pointer space */
10195 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10196 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10197 			return (B_FALSE); /* bad option buffer */
10198 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10199 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10200 			/*
10201 			 * Check to see if it's an all-bypass or all-zeroes
10202 			 * IPsec request.  Don't bother loading IPsec if
10203 			 * the socket doesn't want to use it.  (A good example
10204 			 * is a bypass request.)
10205 			 *
10206 			 * Basically, if any of the non-NEVER bits are set,
10207 			 * load IPsec.
10208 			 */
10209 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10210 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10211 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10212 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10213 			    != 0)
10214 				return (B_TRUE);
10215 		}
10216 	}
10217 	return (B_FALSE);
10218 }
10219 
10220 /*
10221  * If conn is is waiting for ipsec to finish loading, kick it.
10222  */
10223 /* ARGSUSED */
10224 static void
10225 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10226 {
10227 	t_scalar_t	optreq_prim;
10228 	mblk_t		*mp;
10229 	cred_t		*cr;
10230 	int		err = 0;
10231 
10232 	/*
10233 	 * This function is called, after ipsec loading is complete.
10234 	 * Since IP checks exclusively and atomically (i.e it prevents
10235 	 * ipsec load from completing until ip_optcom_req completes)
10236 	 * whether ipsec load is complete, there cannot be a race with IP
10237 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10238 	 */
10239 	mutex_enter(&connp->conn_lock);
10240 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10241 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10242 		mp = connp->conn_ipsec_opt_mp;
10243 		connp->conn_ipsec_opt_mp = NULL;
10244 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10245 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10246 		mutex_exit(&connp->conn_lock);
10247 
10248 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10249 
10250 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10251 		if (optreq_prim == T_OPTMGMT_REQ) {
10252 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10253 			    &ip_opt_obj);
10254 		} else {
10255 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10256 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10257 			    &ip_opt_obj);
10258 		}
10259 		if (err != EINPROGRESS)
10260 			CONN_OPER_PENDING_DONE(connp);
10261 		return;
10262 	}
10263 	mutex_exit(&connp->conn_lock);
10264 }
10265 
10266 /*
10267  * Called from the ipsec_loader thread, outside any perimeter, to tell
10268  * ip qenable any of the queues waiting for the ipsec loader to
10269  * complete.
10270  */
10271 void
10272 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10273 {
10274 	netstack_t *ns = ipss->ipsec_netstack;
10275 
10276 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10277 }
10278 
10279 /*
10280  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10281  * determines the grp on which it has to become exclusive, queues the mp
10282  * and sq draining restarts the optmgmt
10283  */
10284 static boolean_t
10285 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10286 {
10287 	conn_t *connp = Q_TO_CONN(q);
10288 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10289 
10290 	/*
10291 	 * Take IPsec requests and treat them special.
10292 	 */
10293 	if (ipsec_opt_present(mp)) {
10294 		/* First check if IPsec is loaded. */
10295 		mutex_enter(&ipss->ipsec_loader_lock);
10296 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10297 			mutex_exit(&ipss->ipsec_loader_lock);
10298 			return (B_FALSE);
10299 		}
10300 		mutex_enter(&connp->conn_lock);
10301 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10302 
10303 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10304 		connp->conn_ipsec_opt_mp = mp;
10305 		mutex_exit(&connp->conn_lock);
10306 		mutex_exit(&ipss->ipsec_loader_lock);
10307 
10308 		ipsec_loader_loadnow(ipss);
10309 		return (B_TRUE);
10310 	}
10311 	return (B_FALSE);
10312 }
10313 
10314 /*
10315  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10316  * all of them are copied to the conn_t. If the req is "zero", the policy is
10317  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10318  * fields.
10319  * We keep only the latest setting of the policy and thus policy setting
10320  * is not incremental/cumulative.
10321  *
10322  * Requests to set policies with multiple alternative actions will
10323  * go through a different API.
10324  */
10325 int
10326 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10327 {
10328 	uint_t ah_req = 0;
10329 	uint_t esp_req = 0;
10330 	uint_t se_req = 0;
10331 	ipsec_selkey_t sel;
10332 	ipsec_act_t *actp = NULL;
10333 	uint_t nact;
10334 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10335 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10336 	ipsec_policy_root_t *pr;
10337 	ipsec_policy_head_t *ph;
10338 	int fam;
10339 	boolean_t is_pol_reset;
10340 	int error = 0;
10341 	netstack_t	*ns = connp->conn_netstack;
10342 	ip_stack_t	*ipst = ns->netstack_ip;
10343 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10344 
10345 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10346 
10347 	/*
10348 	 * The IP_SEC_OPT option does not allow variable length parameters,
10349 	 * hence a request cannot be NULL.
10350 	 */
10351 	if (req == NULL)
10352 		return (EINVAL);
10353 
10354 	ah_req = req->ipsr_ah_req;
10355 	esp_req = req->ipsr_esp_req;
10356 	se_req = req->ipsr_self_encap_req;
10357 
10358 	/*
10359 	 * Are we dealing with a request to reset the policy (i.e.
10360 	 * zero requests).
10361 	 */
10362 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10363 	    (esp_req & REQ_MASK) == 0 &&
10364 	    (se_req & REQ_MASK) == 0);
10365 
10366 	if (!is_pol_reset) {
10367 		/*
10368 		 * If we couldn't load IPsec, fail with "protocol
10369 		 * not supported".
10370 		 * IPsec may not have been loaded for a request with zero
10371 		 * policies, so we don't fail in this case.
10372 		 */
10373 		mutex_enter(&ipss->ipsec_loader_lock);
10374 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10375 			mutex_exit(&ipss->ipsec_loader_lock);
10376 			return (EPROTONOSUPPORT);
10377 		}
10378 		mutex_exit(&ipss->ipsec_loader_lock);
10379 
10380 		/*
10381 		 * Test for valid requests. Invalid algorithms
10382 		 * need to be tested by IPSEC code because new
10383 		 * algorithms can be added dynamically.
10384 		 */
10385 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10386 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10387 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10388 			return (EINVAL);
10389 		}
10390 
10391 		/*
10392 		 * Only privileged users can issue these
10393 		 * requests.
10394 		 */
10395 		if (((ah_req & IPSEC_PREF_NEVER) ||
10396 		    (esp_req & IPSEC_PREF_NEVER) ||
10397 		    (se_req & IPSEC_PREF_NEVER)) &&
10398 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10399 			return (EPERM);
10400 		}
10401 
10402 		/*
10403 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10404 		 * are mutually exclusive.
10405 		 */
10406 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10407 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10408 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10409 			/* Both of them are set */
10410 			return (EINVAL);
10411 		}
10412 	}
10413 
10414 	mutex_enter(&connp->conn_lock);
10415 
10416 	/*
10417 	 * If we have already cached policies in ip_bind_connected*(), don't
10418 	 * let them change now. We cache policies for connections
10419 	 * whose src,dst [addr, port] is known.
10420 	 */
10421 	if (connp->conn_policy_cached) {
10422 		mutex_exit(&connp->conn_lock);
10423 		return (EINVAL);
10424 	}
10425 
10426 	/*
10427 	 * We have a zero policies, reset the connection policy if already
10428 	 * set. This will cause the connection to inherit the
10429 	 * global policy, if any.
10430 	 */
10431 	if (is_pol_reset) {
10432 		if (connp->conn_policy != NULL) {
10433 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10434 			connp->conn_policy = NULL;
10435 		}
10436 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10437 		connp->conn_in_enforce_policy = B_FALSE;
10438 		connp->conn_out_enforce_policy = B_FALSE;
10439 		mutex_exit(&connp->conn_lock);
10440 		return (0);
10441 	}
10442 
10443 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10444 	    ipst->ips_netstack);
10445 	if (ph == NULL)
10446 		goto enomem;
10447 
10448 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10449 	if (actp == NULL)
10450 		goto enomem;
10451 
10452 	/*
10453 	 * Always allocate IPv4 policy entries, since they can also
10454 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10455 	 */
10456 	bzero(&sel, sizeof (sel));
10457 	sel.ipsl_valid = IPSL_IPV4;
10458 
10459 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10460 	    ipst->ips_netstack);
10461 	if (pin4 == NULL)
10462 		goto enomem;
10463 
10464 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10465 	    ipst->ips_netstack);
10466 	if (pout4 == NULL)
10467 		goto enomem;
10468 
10469 	if (connp->conn_pkt_isv6) {
10470 		/*
10471 		 * We're looking at a v6 socket, also allocate the
10472 		 * v6-specific entries...
10473 		 */
10474 		sel.ipsl_valid = IPSL_IPV6;
10475 		pin6 = ipsec_policy_create(&sel, actp, nact,
10476 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10477 		if (pin6 == NULL)
10478 			goto enomem;
10479 
10480 		pout6 = ipsec_policy_create(&sel, actp, nact,
10481 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10482 		if (pout6 == NULL)
10483 			goto enomem;
10484 
10485 		/*
10486 		 * .. and file them away in the right place.
10487 		 */
10488 		fam = IPSEC_AF_V6;
10489 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10490 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10491 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10492 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10493 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10494 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10495 	}
10496 
10497 	ipsec_actvec_free(actp, nact);
10498 
10499 	/*
10500 	 * File the v4 policies.
10501 	 */
10502 	fam = IPSEC_AF_V4;
10503 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10504 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10505 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10506 
10507 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10508 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10509 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10510 
10511 	/*
10512 	 * If the requests need security, set enforce_policy.
10513 	 * If the requests are IPSEC_PREF_NEVER, one should
10514 	 * still set conn_out_enforce_policy so that an ipsec_out
10515 	 * gets attached in ip_wput. This is needed so that
10516 	 * for connections that we don't cache policy in ip_bind,
10517 	 * if global policy matches in ip_wput_attach_policy, we
10518 	 * don't wrongly inherit global policy. Similarly, we need
10519 	 * to set conn_in_enforce_policy also so that we don't verify
10520 	 * policy wrongly.
10521 	 */
10522 	if ((ah_req & REQ_MASK) != 0 ||
10523 	    (esp_req & REQ_MASK) != 0 ||
10524 	    (se_req & REQ_MASK) != 0) {
10525 		connp->conn_in_enforce_policy = B_TRUE;
10526 		connp->conn_out_enforce_policy = B_TRUE;
10527 		connp->conn_flags |= IPCL_CHECK_POLICY;
10528 	}
10529 
10530 	mutex_exit(&connp->conn_lock);
10531 	return (error);
10532 #undef REQ_MASK
10533 
10534 	/*
10535 	 * Common memory-allocation-failure exit path.
10536 	 */
10537 enomem:
10538 	mutex_exit(&connp->conn_lock);
10539 	if (actp != NULL)
10540 		ipsec_actvec_free(actp, nact);
10541 	if (pin4 != NULL)
10542 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10543 	if (pout4 != NULL)
10544 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10545 	if (pin6 != NULL)
10546 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10547 	if (pout6 != NULL)
10548 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10549 	return (ENOMEM);
10550 }
10551 
10552 /*
10553  * Only for options that pass in an IP addr. Currently only V4 options
10554  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10555  * So this function assumes level is IPPROTO_IP
10556  */
10557 int
10558 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10559     mblk_t *first_mp)
10560 {
10561 	ipif_t *ipif = NULL;
10562 	int error;
10563 	ill_t *ill;
10564 	int zoneid;
10565 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10566 
10567 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10568 
10569 	if (addr != INADDR_ANY || checkonly) {
10570 		ASSERT(connp != NULL);
10571 		zoneid = IPCL_ZONEID(connp);
10572 		if (option == IP_NEXTHOP) {
10573 			ipif = ipif_lookup_onlink_addr(addr,
10574 			    connp->conn_zoneid, ipst);
10575 		} else {
10576 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10577 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10578 			    &error, ipst);
10579 		}
10580 		if (ipif == NULL) {
10581 			if (error == EINPROGRESS)
10582 				return (error);
10583 			else if ((option == IP_MULTICAST_IF) ||
10584 			    (option == IP_NEXTHOP))
10585 				return (EHOSTUNREACH);
10586 			else
10587 				return (EINVAL);
10588 		} else if (checkonly) {
10589 			if (option == IP_MULTICAST_IF) {
10590 				ill = ipif->ipif_ill;
10591 				/* not supported by the virtual network iface */
10592 				if (IS_VNI(ill)) {
10593 					ipif_refrele(ipif);
10594 					return (EINVAL);
10595 				}
10596 			}
10597 			ipif_refrele(ipif);
10598 			return (0);
10599 		}
10600 		ill = ipif->ipif_ill;
10601 		mutex_enter(&connp->conn_lock);
10602 		mutex_enter(&ill->ill_lock);
10603 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10604 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10605 			mutex_exit(&ill->ill_lock);
10606 			mutex_exit(&connp->conn_lock);
10607 			ipif_refrele(ipif);
10608 			return (option == IP_MULTICAST_IF ?
10609 			    EHOSTUNREACH : EINVAL);
10610 		}
10611 	} else {
10612 		mutex_enter(&connp->conn_lock);
10613 	}
10614 
10615 	/* None of the options below are supported on the VNI */
10616 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10617 		mutex_exit(&ill->ill_lock);
10618 		mutex_exit(&connp->conn_lock);
10619 		ipif_refrele(ipif);
10620 		return (EINVAL);
10621 	}
10622 
10623 	switch (option) {
10624 	case IP_DONTFAILOVER_IF:
10625 		/*
10626 		 * This option is used by in.mpathd to ensure
10627 		 * that IPMP probe packets only go out on the
10628 		 * test interfaces. in.mpathd sets this option
10629 		 * on the non-failover interfaces.
10630 		 * For backward compatibility, this option
10631 		 * implicitly sets IP_MULTICAST_IF, as used
10632 		 * be done in bind(), so that ip_wput gets
10633 		 * this ipif to send mcast packets.
10634 		 */
10635 		if (ipif != NULL) {
10636 			ASSERT(addr != INADDR_ANY);
10637 			connp->conn_nofailover_ill = ipif->ipif_ill;
10638 			connp->conn_multicast_ipif = ipif;
10639 		} else {
10640 			ASSERT(addr == INADDR_ANY);
10641 			connp->conn_nofailover_ill = NULL;
10642 			connp->conn_multicast_ipif = NULL;
10643 		}
10644 		break;
10645 
10646 	case IP_MULTICAST_IF:
10647 		connp->conn_multicast_ipif = ipif;
10648 		break;
10649 	case IP_NEXTHOP:
10650 		connp->conn_nexthop_v4 = addr;
10651 		connp->conn_nexthop_set = B_TRUE;
10652 		break;
10653 	}
10654 
10655 	if (ipif != NULL) {
10656 		mutex_exit(&ill->ill_lock);
10657 		mutex_exit(&connp->conn_lock);
10658 		ipif_refrele(ipif);
10659 		return (0);
10660 	}
10661 	mutex_exit(&connp->conn_lock);
10662 	/* We succeded in cleared the option */
10663 	return (0);
10664 }
10665 
10666 /*
10667  * For options that pass in an ifindex specifying the ill. V6 options always
10668  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10669  */
10670 int
10671 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10672     int level, int option, mblk_t *first_mp)
10673 {
10674 	ill_t *ill = NULL;
10675 	int error = 0;
10676 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10677 
10678 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10679 	if (ifindex != 0) {
10680 		ASSERT(connp != NULL);
10681 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10682 		    first_mp, ip_restart_optmgmt, &error, ipst);
10683 		if (ill != NULL) {
10684 			if (checkonly) {
10685 				/* not supported by the virtual network iface */
10686 				if (IS_VNI(ill)) {
10687 					ill_refrele(ill);
10688 					return (EINVAL);
10689 				}
10690 				ill_refrele(ill);
10691 				return (0);
10692 			}
10693 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10694 			    0, NULL)) {
10695 				ill_refrele(ill);
10696 				ill = NULL;
10697 				mutex_enter(&connp->conn_lock);
10698 				goto setit;
10699 			}
10700 			mutex_enter(&connp->conn_lock);
10701 			mutex_enter(&ill->ill_lock);
10702 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10703 				mutex_exit(&ill->ill_lock);
10704 				mutex_exit(&connp->conn_lock);
10705 				ill_refrele(ill);
10706 				ill = NULL;
10707 				mutex_enter(&connp->conn_lock);
10708 			}
10709 			goto setit;
10710 		} else if (error == EINPROGRESS) {
10711 			return (error);
10712 		} else {
10713 			error = 0;
10714 		}
10715 	}
10716 	mutex_enter(&connp->conn_lock);
10717 setit:
10718 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10719 
10720 	/*
10721 	 * The options below assume that the ILL (if any) transmits and/or
10722 	 * receives traffic. Neither of which is true for the virtual network
10723 	 * interface, so fail setting these on a VNI.
10724 	 */
10725 	if (IS_VNI(ill)) {
10726 		ASSERT(ill != NULL);
10727 		mutex_exit(&ill->ill_lock);
10728 		mutex_exit(&connp->conn_lock);
10729 		ill_refrele(ill);
10730 		return (EINVAL);
10731 	}
10732 
10733 	if (level == IPPROTO_IP) {
10734 		switch (option) {
10735 		case IP_BOUND_IF:
10736 			connp->conn_incoming_ill = ill;
10737 			connp->conn_outgoing_ill = ill;
10738 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10739 			    0 : ifindex;
10740 			break;
10741 
10742 		case IP_XMIT_IF:
10743 			/*
10744 			 * Similar to IP_BOUND_IF, but this only
10745 			 * determines the outgoing interface for
10746 			 * unicast packets. Also no IRE_CACHE entry
10747 			 * is added for the destination of the
10748 			 * outgoing packets. This feature is needed
10749 			 * for mobile IP.
10750 			 */
10751 			connp->conn_xmit_if_ill = ill;
10752 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10753 			    0 : ifindex;
10754 			break;
10755 
10756 		case IP_MULTICAST_IF:
10757 			/*
10758 			 * This option is an internal special. The socket
10759 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10760 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10761 			 * specifies an ifindex and we try first on V6 ill's.
10762 			 * If we don't find one, we they try using on v4 ill's
10763 			 * intenally and we come here.
10764 			 */
10765 			if (!checkonly && ill != NULL) {
10766 				ipif_t	*ipif;
10767 				ipif = ill->ill_ipif;
10768 
10769 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10770 					mutex_exit(&ill->ill_lock);
10771 					mutex_exit(&connp->conn_lock);
10772 					ill_refrele(ill);
10773 					ill = NULL;
10774 					mutex_enter(&connp->conn_lock);
10775 				} else {
10776 					connp->conn_multicast_ipif = ipif;
10777 				}
10778 			}
10779 			break;
10780 		}
10781 	} else {
10782 		switch (option) {
10783 		case IPV6_BOUND_IF:
10784 			connp->conn_incoming_ill = ill;
10785 			connp->conn_outgoing_ill = ill;
10786 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10787 			    0 : ifindex;
10788 			break;
10789 
10790 		case IPV6_BOUND_PIF:
10791 			/*
10792 			 * Limit all transmit to this ill.
10793 			 * Unlike IPV6_BOUND_IF, using this option
10794 			 * prevents load spreading and failover from
10795 			 * happening when the interface is part of the
10796 			 * group. That's why we don't need to remember
10797 			 * the ifindex in orig_bound_ifindex as in
10798 			 * IPV6_BOUND_IF.
10799 			 */
10800 			connp->conn_outgoing_pill = ill;
10801 			break;
10802 
10803 		case IPV6_DONTFAILOVER_IF:
10804 			/*
10805 			 * This option is used by in.mpathd to ensure
10806 			 * that IPMP probe packets only go out on the
10807 			 * test interfaces. in.mpathd sets this option
10808 			 * on the non-failover interfaces.
10809 			 */
10810 			connp->conn_nofailover_ill = ill;
10811 			/*
10812 			 * For backward compatibility, this option
10813 			 * implicitly sets ip_multicast_ill as used in
10814 			 * IP_MULTICAST_IF so that ip_wput gets
10815 			 * this ipif to send mcast packets.
10816 			 */
10817 			connp->conn_multicast_ill = ill;
10818 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10819 			    0 : ifindex;
10820 			break;
10821 
10822 		case IPV6_MULTICAST_IF:
10823 			/*
10824 			 * Set conn_multicast_ill to be the IPv6 ill.
10825 			 * Set conn_multicast_ipif to be an IPv4 ipif
10826 			 * for ifindex to make IPv4 mapped addresses
10827 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10828 			 * Even if no IPv6 ill exists for the ifindex
10829 			 * we need to check for an IPv4 ifindex in order
10830 			 * for this to work with mapped addresses. In that
10831 			 * case only set conn_multicast_ipif.
10832 			 */
10833 			if (!checkonly) {
10834 				if (ifindex == 0) {
10835 					connp->conn_multicast_ill = NULL;
10836 					connp->conn_orig_multicast_ifindex = 0;
10837 					connp->conn_multicast_ipif = NULL;
10838 				} else if (ill != NULL) {
10839 					connp->conn_multicast_ill = ill;
10840 					connp->conn_orig_multicast_ifindex =
10841 					    ifindex;
10842 				}
10843 			}
10844 			break;
10845 		}
10846 	}
10847 
10848 	if (ill != NULL) {
10849 		mutex_exit(&ill->ill_lock);
10850 		mutex_exit(&connp->conn_lock);
10851 		ill_refrele(ill);
10852 		return (0);
10853 	}
10854 	mutex_exit(&connp->conn_lock);
10855 	/*
10856 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10857 	 * locate the ill and could not set the option (ifindex != 0)
10858 	 */
10859 	return (ifindex == 0 ? 0 : EINVAL);
10860 }
10861 
10862 /* This routine sets socket options. */
10863 /* ARGSUSED */
10864 int
10865 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10866     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10867     void *dummy, cred_t *cr, mblk_t *first_mp)
10868 {
10869 	int		*i1 = (int *)invalp;
10870 	conn_t		*connp = Q_TO_CONN(q);
10871 	int		error = 0;
10872 	boolean_t	checkonly;
10873 	ire_t		*ire;
10874 	boolean_t	found;
10875 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10876 
10877 	switch (optset_context) {
10878 
10879 	case SETFN_OPTCOM_CHECKONLY:
10880 		checkonly = B_TRUE;
10881 		/*
10882 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10883 		 * inlen != 0 implies value supplied and
10884 		 * 	we have to "pretend" to set it.
10885 		 * inlen == 0 implies that there is no
10886 		 * 	value part in T_CHECK request and just validation
10887 		 * done elsewhere should be enough, we just return here.
10888 		 */
10889 		if (inlen == 0) {
10890 			*outlenp = 0;
10891 			return (0);
10892 		}
10893 		break;
10894 	case SETFN_OPTCOM_NEGOTIATE:
10895 	case SETFN_UD_NEGOTIATE:
10896 	case SETFN_CONN_NEGOTIATE:
10897 		checkonly = B_FALSE;
10898 		break;
10899 	default:
10900 		/*
10901 		 * We should never get here
10902 		 */
10903 		*outlenp = 0;
10904 		return (EINVAL);
10905 	}
10906 
10907 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10908 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10909 
10910 	/*
10911 	 * For fixed length options, no sanity check
10912 	 * of passed in length is done. It is assumed *_optcom_req()
10913 	 * routines do the right thing.
10914 	 */
10915 
10916 	switch (level) {
10917 	case SOL_SOCKET:
10918 		/*
10919 		 * conn_lock protects the bitfields, and is used to
10920 		 * set the fields atomically.
10921 		 */
10922 		switch (name) {
10923 		case SO_BROADCAST:
10924 			if (!checkonly) {
10925 				/* TODO: use value someplace? */
10926 				mutex_enter(&connp->conn_lock);
10927 				connp->conn_broadcast = *i1 ? 1 : 0;
10928 				mutex_exit(&connp->conn_lock);
10929 			}
10930 			break;	/* goto sizeof (int) option return */
10931 		case SO_USELOOPBACK:
10932 			if (!checkonly) {
10933 				/* TODO: use value someplace? */
10934 				mutex_enter(&connp->conn_lock);
10935 				connp->conn_loopback = *i1 ? 1 : 0;
10936 				mutex_exit(&connp->conn_lock);
10937 			}
10938 			break;	/* goto sizeof (int) option return */
10939 		case SO_DONTROUTE:
10940 			if (!checkonly) {
10941 				mutex_enter(&connp->conn_lock);
10942 				connp->conn_dontroute = *i1 ? 1 : 0;
10943 				mutex_exit(&connp->conn_lock);
10944 			}
10945 			break;	/* goto sizeof (int) option return */
10946 		case SO_REUSEADDR:
10947 			if (!checkonly) {
10948 				mutex_enter(&connp->conn_lock);
10949 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10950 				mutex_exit(&connp->conn_lock);
10951 			}
10952 			break;	/* goto sizeof (int) option return */
10953 		case SO_PROTOTYPE:
10954 			if (!checkonly) {
10955 				mutex_enter(&connp->conn_lock);
10956 				connp->conn_proto = *i1;
10957 				mutex_exit(&connp->conn_lock);
10958 			}
10959 			break;	/* goto sizeof (int) option return */
10960 		case SO_ALLZONES:
10961 			if (!checkonly) {
10962 				mutex_enter(&connp->conn_lock);
10963 				if (IPCL_IS_BOUND(connp)) {
10964 					mutex_exit(&connp->conn_lock);
10965 					return (EINVAL);
10966 				}
10967 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10968 				mutex_exit(&connp->conn_lock);
10969 			}
10970 			break;	/* goto sizeof (int) option return */
10971 		case SO_ANON_MLP:
10972 			if (!checkonly) {
10973 				mutex_enter(&connp->conn_lock);
10974 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10975 				mutex_exit(&connp->conn_lock);
10976 			}
10977 			break;	/* goto sizeof (int) option return */
10978 		case SO_MAC_EXEMPT:
10979 			if (secpolicy_net_mac_aware(cr) != 0 ||
10980 			    IPCL_IS_BOUND(connp))
10981 				return (EACCES);
10982 			if (!checkonly) {
10983 				mutex_enter(&connp->conn_lock);
10984 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10985 				mutex_exit(&connp->conn_lock);
10986 			}
10987 			break;	/* goto sizeof (int) option return */
10988 		default:
10989 			/*
10990 			 * "soft" error (negative)
10991 			 * option not handled at this level
10992 			 * Note: Do not modify *outlenp
10993 			 */
10994 			return (-EINVAL);
10995 		}
10996 		break;
10997 	case IPPROTO_IP:
10998 		switch (name) {
10999 		case IP_NEXTHOP:
11000 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
11001 				return (EPERM);
11002 			/* FALLTHRU */
11003 		case IP_MULTICAST_IF:
11004 		case IP_DONTFAILOVER_IF: {
11005 			ipaddr_t addr = *i1;
11006 
11007 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
11008 			    first_mp);
11009 			if (error != 0)
11010 				return (error);
11011 			break;	/* goto sizeof (int) option return */
11012 		}
11013 
11014 		case IP_MULTICAST_TTL:
11015 			/* Recorded in transport above IP */
11016 			*outvalp = *invalp;
11017 			*outlenp = sizeof (uchar_t);
11018 			return (0);
11019 		case IP_MULTICAST_LOOP:
11020 			if (!checkonly) {
11021 				mutex_enter(&connp->conn_lock);
11022 				connp->conn_multicast_loop = *invalp ? 1 : 0;
11023 				mutex_exit(&connp->conn_lock);
11024 			}
11025 			*outvalp = *invalp;
11026 			*outlenp = sizeof (uchar_t);
11027 			return (0);
11028 		case IP_ADD_MEMBERSHIP:
11029 		case MCAST_JOIN_GROUP:
11030 		case IP_DROP_MEMBERSHIP:
11031 		case MCAST_LEAVE_GROUP: {
11032 			struct ip_mreq *mreqp;
11033 			struct group_req *greqp;
11034 			ire_t *ire;
11035 			boolean_t done = B_FALSE;
11036 			ipaddr_t group, ifaddr;
11037 			struct sockaddr_in *sin;
11038 			uint32_t *ifindexp;
11039 			boolean_t mcast_opt = B_TRUE;
11040 			mcast_record_t fmode;
11041 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11042 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11043 
11044 			switch (name) {
11045 			case IP_ADD_MEMBERSHIP:
11046 				mcast_opt = B_FALSE;
11047 				/* FALLTHRU */
11048 			case MCAST_JOIN_GROUP:
11049 				fmode = MODE_IS_EXCLUDE;
11050 				optfn = ip_opt_add_group;
11051 				break;
11052 
11053 			case IP_DROP_MEMBERSHIP:
11054 				mcast_opt = B_FALSE;
11055 				/* FALLTHRU */
11056 			case MCAST_LEAVE_GROUP:
11057 				fmode = MODE_IS_INCLUDE;
11058 				optfn = ip_opt_delete_group;
11059 				break;
11060 			}
11061 
11062 			if (mcast_opt) {
11063 				greqp = (struct group_req *)i1;
11064 				sin = (struct sockaddr_in *)&greqp->gr_group;
11065 				if (sin->sin_family != AF_INET) {
11066 					*outlenp = 0;
11067 					return (ENOPROTOOPT);
11068 				}
11069 				group = (ipaddr_t)sin->sin_addr.s_addr;
11070 				ifaddr = INADDR_ANY;
11071 				ifindexp = &greqp->gr_interface;
11072 			} else {
11073 				mreqp = (struct ip_mreq *)i1;
11074 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
11075 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
11076 				ifindexp = NULL;
11077 			}
11078 
11079 			/*
11080 			 * In the multirouting case, we need to replicate
11081 			 * the request on all interfaces that will take part
11082 			 * in replication.  We do so because multirouting is
11083 			 * reflective, thus we will probably receive multi-
11084 			 * casts on those interfaces.
11085 			 * The ip_multirt_apply_membership() succeeds if the
11086 			 * operation succeeds on at least one interface.
11087 			 */
11088 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
11089 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11090 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11091 			if (ire != NULL) {
11092 				if (ire->ire_flags & RTF_MULTIRT) {
11093 					error = ip_multirt_apply_membership(
11094 					    optfn, ire, connp, checkonly, group,
11095 					    fmode, INADDR_ANY, first_mp);
11096 					done = B_TRUE;
11097 				}
11098 				ire_refrele(ire);
11099 			}
11100 			if (!done) {
11101 				error = optfn(connp, checkonly, group, ifaddr,
11102 				    ifindexp, fmode, INADDR_ANY, first_mp);
11103 			}
11104 			if (error) {
11105 				/*
11106 				 * EINPROGRESS is a soft error, needs retry
11107 				 * so don't make *outlenp zero.
11108 				 */
11109 				if (error != EINPROGRESS)
11110 					*outlenp = 0;
11111 				return (error);
11112 			}
11113 			/* OK return - copy input buffer into output buffer */
11114 			if (invalp != outvalp) {
11115 				/* don't trust bcopy for identical src/dst */
11116 				bcopy(invalp, outvalp, inlen);
11117 			}
11118 			*outlenp = inlen;
11119 			return (0);
11120 		}
11121 		case IP_BLOCK_SOURCE:
11122 		case IP_UNBLOCK_SOURCE:
11123 		case IP_ADD_SOURCE_MEMBERSHIP:
11124 		case IP_DROP_SOURCE_MEMBERSHIP:
11125 		case MCAST_BLOCK_SOURCE:
11126 		case MCAST_UNBLOCK_SOURCE:
11127 		case MCAST_JOIN_SOURCE_GROUP:
11128 		case MCAST_LEAVE_SOURCE_GROUP: {
11129 			struct ip_mreq_source *imreqp;
11130 			struct group_source_req *gsreqp;
11131 			in_addr_t grp, src, ifaddr = INADDR_ANY;
11132 			uint32_t ifindex = 0;
11133 			mcast_record_t fmode;
11134 			struct sockaddr_in *sin;
11135 			ire_t *ire;
11136 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11137 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11138 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11139 
11140 			switch (name) {
11141 			case IP_BLOCK_SOURCE:
11142 				mcast_opt = B_FALSE;
11143 				/* FALLTHRU */
11144 			case MCAST_BLOCK_SOURCE:
11145 				fmode = MODE_IS_EXCLUDE;
11146 				optfn = ip_opt_add_group;
11147 				break;
11148 
11149 			case IP_UNBLOCK_SOURCE:
11150 				mcast_opt = B_FALSE;
11151 				/* FALLTHRU */
11152 			case MCAST_UNBLOCK_SOURCE:
11153 				fmode = MODE_IS_EXCLUDE;
11154 				optfn = ip_opt_delete_group;
11155 				break;
11156 
11157 			case IP_ADD_SOURCE_MEMBERSHIP:
11158 				mcast_opt = B_FALSE;
11159 				/* FALLTHRU */
11160 			case MCAST_JOIN_SOURCE_GROUP:
11161 				fmode = MODE_IS_INCLUDE;
11162 				optfn = ip_opt_add_group;
11163 				break;
11164 
11165 			case IP_DROP_SOURCE_MEMBERSHIP:
11166 				mcast_opt = B_FALSE;
11167 				/* FALLTHRU */
11168 			case MCAST_LEAVE_SOURCE_GROUP:
11169 				fmode = MODE_IS_INCLUDE;
11170 				optfn = ip_opt_delete_group;
11171 				break;
11172 			}
11173 
11174 			if (mcast_opt) {
11175 				gsreqp = (struct group_source_req *)i1;
11176 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11177 					*outlenp = 0;
11178 					return (ENOPROTOOPT);
11179 				}
11180 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11181 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11182 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11183 				src = (ipaddr_t)sin->sin_addr.s_addr;
11184 				ifindex = gsreqp->gsr_interface;
11185 			} else {
11186 				imreqp = (struct ip_mreq_source *)i1;
11187 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11188 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11189 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11190 			}
11191 
11192 			/*
11193 			 * In the multirouting case, we need to replicate
11194 			 * the request as noted in the mcast cases above.
11195 			 */
11196 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11197 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11198 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11199 			if (ire != NULL) {
11200 				if (ire->ire_flags & RTF_MULTIRT) {
11201 					error = ip_multirt_apply_membership(
11202 					    optfn, ire, connp, checkonly, grp,
11203 					    fmode, src, first_mp);
11204 					done = B_TRUE;
11205 				}
11206 				ire_refrele(ire);
11207 			}
11208 			if (!done) {
11209 				error = optfn(connp, checkonly, grp, ifaddr,
11210 				    &ifindex, fmode, src, first_mp);
11211 			}
11212 			if (error != 0) {
11213 				/*
11214 				 * EINPROGRESS is a soft error, needs retry
11215 				 * so don't make *outlenp zero.
11216 				 */
11217 				if (error != EINPROGRESS)
11218 					*outlenp = 0;
11219 				return (error);
11220 			}
11221 			/* OK return - copy input buffer into output buffer */
11222 			if (invalp != outvalp) {
11223 				bcopy(invalp, outvalp, inlen);
11224 			}
11225 			*outlenp = inlen;
11226 			return (0);
11227 		}
11228 		case IP_SEC_OPT:
11229 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11230 			if (error != 0) {
11231 				*outlenp = 0;
11232 				return (error);
11233 			}
11234 			break;
11235 		case IP_HDRINCL:
11236 		case IP_OPTIONS:
11237 		case T_IP_OPTIONS:
11238 		case IP_TOS:
11239 		case T_IP_TOS:
11240 		case IP_TTL:
11241 		case IP_RECVDSTADDR:
11242 		case IP_RECVOPTS:
11243 			/* OK return - copy input buffer into output buffer */
11244 			if (invalp != outvalp) {
11245 				/* don't trust bcopy for identical src/dst */
11246 				bcopy(invalp, outvalp, inlen);
11247 			}
11248 			*outlenp = inlen;
11249 			return (0);
11250 		case IP_RECVIF:
11251 			/* Retrieve the inbound interface index */
11252 			if (!checkonly) {
11253 				mutex_enter(&connp->conn_lock);
11254 				connp->conn_recvif = *i1 ? 1 : 0;
11255 				mutex_exit(&connp->conn_lock);
11256 			}
11257 			break;	/* goto sizeof (int) option return */
11258 		case IP_RECVPKTINFO:
11259 			if (!checkonly) {
11260 				mutex_enter(&connp->conn_lock);
11261 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11262 				mutex_exit(&connp->conn_lock);
11263 			}
11264 			break;	/* goto sizeof (int) option return */
11265 		case IP_RECVSLLA:
11266 			/* Retrieve the source link layer address */
11267 			if (!checkonly) {
11268 				mutex_enter(&connp->conn_lock);
11269 				connp->conn_recvslla = *i1 ? 1 : 0;
11270 				mutex_exit(&connp->conn_lock);
11271 			}
11272 			break;	/* goto sizeof (int) option return */
11273 		case MRT_INIT:
11274 		case MRT_DONE:
11275 		case MRT_ADD_VIF:
11276 		case MRT_DEL_VIF:
11277 		case MRT_ADD_MFC:
11278 		case MRT_DEL_MFC:
11279 		case MRT_ASSERT:
11280 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11281 				*outlenp = 0;
11282 				return (error);
11283 			}
11284 			error = ip_mrouter_set((int)name, q, checkonly,
11285 			    (uchar_t *)invalp, inlen, first_mp);
11286 			if (error) {
11287 				*outlenp = 0;
11288 				return (error);
11289 			}
11290 			/* OK return - copy input buffer into output buffer */
11291 			if (invalp != outvalp) {
11292 				/* don't trust bcopy for identical src/dst */
11293 				bcopy(invalp, outvalp, inlen);
11294 			}
11295 			*outlenp = inlen;
11296 			return (0);
11297 		case IP_BOUND_IF:
11298 		case IP_XMIT_IF:
11299 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11300 			    level, name, first_mp);
11301 			if (error != 0)
11302 				return (error);
11303 			break; 		/* goto sizeof (int) option return */
11304 
11305 		case IP_UNSPEC_SRC:
11306 			/* Allow sending with a zero source address */
11307 			if (!checkonly) {
11308 				mutex_enter(&connp->conn_lock);
11309 				connp->conn_unspec_src = *i1 ? 1 : 0;
11310 				mutex_exit(&connp->conn_lock);
11311 			}
11312 			break;	/* goto sizeof (int) option return */
11313 		default:
11314 			/*
11315 			 * "soft" error (negative)
11316 			 * option not handled at this level
11317 			 * Note: Do not modify *outlenp
11318 			 */
11319 			return (-EINVAL);
11320 		}
11321 		break;
11322 	case IPPROTO_IPV6:
11323 		switch (name) {
11324 		case IPV6_BOUND_IF:
11325 		case IPV6_BOUND_PIF:
11326 		case IPV6_DONTFAILOVER_IF:
11327 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11328 			    level, name, first_mp);
11329 			if (error != 0)
11330 				return (error);
11331 			break; 		/* goto sizeof (int) option return */
11332 
11333 		case IPV6_MULTICAST_IF:
11334 			/*
11335 			 * The only possible errors are EINPROGRESS and
11336 			 * EINVAL. EINPROGRESS will be restarted and is not
11337 			 * a hard error. We call this option on both V4 and V6
11338 			 * If both return EINVAL, then this call returns
11339 			 * EINVAL. If at least one of them succeeds we
11340 			 * return success.
11341 			 */
11342 			found = B_FALSE;
11343 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11344 			    level, name, first_mp);
11345 			if (error == EINPROGRESS)
11346 				return (error);
11347 			if (error == 0)
11348 				found = B_TRUE;
11349 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11350 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11351 			if (error == 0)
11352 				found = B_TRUE;
11353 			if (!found)
11354 				return (error);
11355 			break; 		/* goto sizeof (int) option return */
11356 
11357 		case IPV6_MULTICAST_HOPS:
11358 			/* Recorded in transport above IP */
11359 			break;	/* goto sizeof (int) option return */
11360 		case IPV6_MULTICAST_LOOP:
11361 			if (!checkonly) {
11362 				mutex_enter(&connp->conn_lock);
11363 				connp->conn_multicast_loop = *i1;
11364 				mutex_exit(&connp->conn_lock);
11365 			}
11366 			break;	/* goto sizeof (int) option return */
11367 		case IPV6_JOIN_GROUP:
11368 		case MCAST_JOIN_GROUP:
11369 		case IPV6_LEAVE_GROUP:
11370 		case MCAST_LEAVE_GROUP: {
11371 			struct ipv6_mreq *ip_mreqp;
11372 			struct group_req *greqp;
11373 			ire_t *ire;
11374 			boolean_t done = B_FALSE;
11375 			in6_addr_t groupv6;
11376 			uint32_t ifindex;
11377 			boolean_t mcast_opt = B_TRUE;
11378 			mcast_record_t fmode;
11379 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11380 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11381 
11382 			switch (name) {
11383 			case IPV6_JOIN_GROUP:
11384 				mcast_opt = B_FALSE;
11385 				/* FALLTHRU */
11386 			case MCAST_JOIN_GROUP:
11387 				fmode = MODE_IS_EXCLUDE;
11388 				optfn = ip_opt_add_group_v6;
11389 				break;
11390 
11391 			case IPV6_LEAVE_GROUP:
11392 				mcast_opt = B_FALSE;
11393 				/* FALLTHRU */
11394 			case MCAST_LEAVE_GROUP:
11395 				fmode = MODE_IS_INCLUDE;
11396 				optfn = ip_opt_delete_group_v6;
11397 				break;
11398 			}
11399 
11400 			if (mcast_opt) {
11401 				struct sockaddr_in *sin;
11402 				struct sockaddr_in6 *sin6;
11403 				greqp = (struct group_req *)i1;
11404 				if (greqp->gr_group.ss_family == AF_INET) {
11405 					sin = (struct sockaddr_in *)
11406 					    &(greqp->gr_group);
11407 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11408 					    &groupv6);
11409 				} else {
11410 					sin6 = (struct sockaddr_in6 *)
11411 					    &(greqp->gr_group);
11412 					groupv6 = sin6->sin6_addr;
11413 				}
11414 				ifindex = greqp->gr_interface;
11415 			} else {
11416 				ip_mreqp = (struct ipv6_mreq *)i1;
11417 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11418 				ifindex = ip_mreqp->ipv6mr_interface;
11419 			}
11420 			/*
11421 			 * In the multirouting case, we need to replicate
11422 			 * the request on all interfaces that will take part
11423 			 * in replication.  We do so because multirouting is
11424 			 * reflective, thus we will probably receive multi-
11425 			 * casts on those interfaces.
11426 			 * The ip_multirt_apply_membership_v6() succeeds if
11427 			 * the operation succeeds on at least one interface.
11428 			 */
11429 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11430 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11431 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11432 			if (ire != NULL) {
11433 				if (ire->ire_flags & RTF_MULTIRT) {
11434 					error = ip_multirt_apply_membership_v6(
11435 					    optfn, ire, connp, checkonly,
11436 					    &groupv6, fmode, &ipv6_all_zeros,
11437 					    first_mp);
11438 					done = B_TRUE;
11439 				}
11440 				ire_refrele(ire);
11441 			}
11442 			if (!done) {
11443 				error = optfn(connp, checkonly, &groupv6,
11444 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11445 			}
11446 			if (error) {
11447 				/*
11448 				 * EINPROGRESS is a soft error, needs retry
11449 				 * so don't make *outlenp zero.
11450 				 */
11451 				if (error != EINPROGRESS)
11452 					*outlenp = 0;
11453 				return (error);
11454 			}
11455 			/* OK return - copy input buffer into output buffer */
11456 			if (invalp != outvalp) {
11457 				/* don't trust bcopy for identical src/dst */
11458 				bcopy(invalp, outvalp, inlen);
11459 			}
11460 			*outlenp = inlen;
11461 			return (0);
11462 		}
11463 		case MCAST_BLOCK_SOURCE:
11464 		case MCAST_UNBLOCK_SOURCE:
11465 		case MCAST_JOIN_SOURCE_GROUP:
11466 		case MCAST_LEAVE_SOURCE_GROUP: {
11467 			struct group_source_req *gsreqp;
11468 			in6_addr_t v6grp, v6src;
11469 			uint32_t ifindex;
11470 			mcast_record_t fmode;
11471 			ire_t *ire;
11472 			boolean_t done = B_FALSE;
11473 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11474 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11475 
11476 			switch (name) {
11477 			case MCAST_BLOCK_SOURCE:
11478 				fmode = MODE_IS_EXCLUDE;
11479 				optfn = ip_opt_add_group_v6;
11480 				break;
11481 			case MCAST_UNBLOCK_SOURCE:
11482 				fmode = MODE_IS_EXCLUDE;
11483 				optfn = ip_opt_delete_group_v6;
11484 				break;
11485 			case MCAST_JOIN_SOURCE_GROUP:
11486 				fmode = MODE_IS_INCLUDE;
11487 				optfn = ip_opt_add_group_v6;
11488 				break;
11489 			case MCAST_LEAVE_SOURCE_GROUP:
11490 				fmode = MODE_IS_INCLUDE;
11491 				optfn = ip_opt_delete_group_v6;
11492 				break;
11493 			}
11494 
11495 			gsreqp = (struct group_source_req *)i1;
11496 			ifindex = gsreqp->gsr_interface;
11497 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11498 				struct sockaddr_in *s;
11499 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11500 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11501 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11502 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11503 			} else {
11504 				struct sockaddr_in6 *s6;
11505 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11506 				v6grp = s6->sin6_addr;
11507 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11508 				v6src = s6->sin6_addr;
11509 			}
11510 
11511 			/*
11512 			 * In the multirouting case, we need to replicate
11513 			 * the request as noted in the mcast cases above.
11514 			 */
11515 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11516 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11517 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11518 			if (ire != NULL) {
11519 				if (ire->ire_flags & RTF_MULTIRT) {
11520 					error = ip_multirt_apply_membership_v6(
11521 					    optfn, ire, connp, checkonly,
11522 					    &v6grp, fmode, &v6src, first_mp);
11523 					done = B_TRUE;
11524 				}
11525 				ire_refrele(ire);
11526 			}
11527 			if (!done) {
11528 				error = optfn(connp, checkonly, &v6grp,
11529 				    ifindex, fmode, &v6src, first_mp);
11530 			}
11531 			if (error != 0) {
11532 				/*
11533 				 * EINPROGRESS is a soft error, needs retry
11534 				 * so don't make *outlenp zero.
11535 				 */
11536 				if (error != EINPROGRESS)
11537 					*outlenp = 0;
11538 				return (error);
11539 			}
11540 			/* OK return - copy input buffer into output buffer */
11541 			if (invalp != outvalp) {
11542 				bcopy(invalp, outvalp, inlen);
11543 			}
11544 			*outlenp = inlen;
11545 			return (0);
11546 		}
11547 		case IPV6_UNICAST_HOPS:
11548 			/* Recorded in transport above IP */
11549 			break;	/* goto sizeof (int) option return */
11550 		case IPV6_UNSPEC_SRC:
11551 			/* Allow sending with a zero source address */
11552 			if (!checkonly) {
11553 				mutex_enter(&connp->conn_lock);
11554 				connp->conn_unspec_src = *i1 ? 1 : 0;
11555 				mutex_exit(&connp->conn_lock);
11556 			}
11557 			break;	/* goto sizeof (int) option return */
11558 		case IPV6_RECVPKTINFO:
11559 			if (!checkonly) {
11560 				mutex_enter(&connp->conn_lock);
11561 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11562 				mutex_exit(&connp->conn_lock);
11563 			}
11564 			break;	/* goto sizeof (int) option return */
11565 		case IPV6_RECVTCLASS:
11566 			if (!checkonly) {
11567 				if (*i1 < 0 || *i1 > 1) {
11568 					return (EINVAL);
11569 				}
11570 				mutex_enter(&connp->conn_lock);
11571 				connp->conn_ipv6_recvtclass = *i1;
11572 				mutex_exit(&connp->conn_lock);
11573 			}
11574 			break;
11575 		case IPV6_RECVPATHMTU:
11576 			if (!checkonly) {
11577 				if (*i1 < 0 || *i1 > 1) {
11578 					return (EINVAL);
11579 				}
11580 				mutex_enter(&connp->conn_lock);
11581 				connp->conn_ipv6_recvpathmtu = *i1;
11582 				mutex_exit(&connp->conn_lock);
11583 			}
11584 			break;
11585 		case IPV6_RECVHOPLIMIT:
11586 			if (!checkonly) {
11587 				mutex_enter(&connp->conn_lock);
11588 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11589 				mutex_exit(&connp->conn_lock);
11590 			}
11591 			break;	/* goto sizeof (int) option return */
11592 		case IPV6_RECVHOPOPTS:
11593 			if (!checkonly) {
11594 				mutex_enter(&connp->conn_lock);
11595 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11596 				mutex_exit(&connp->conn_lock);
11597 			}
11598 			break;	/* goto sizeof (int) option return */
11599 		case IPV6_RECVDSTOPTS:
11600 			if (!checkonly) {
11601 				mutex_enter(&connp->conn_lock);
11602 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11603 				mutex_exit(&connp->conn_lock);
11604 			}
11605 			break;	/* goto sizeof (int) option return */
11606 		case IPV6_RECVRTHDR:
11607 			if (!checkonly) {
11608 				mutex_enter(&connp->conn_lock);
11609 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11610 				mutex_exit(&connp->conn_lock);
11611 			}
11612 			break;	/* goto sizeof (int) option return */
11613 		case IPV6_RECVRTHDRDSTOPTS:
11614 			if (!checkonly) {
11615 				mutex_enter(&connp->conn_lock);
11616 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11617 				mutex_exit(&connp->conn_lock);
11618 			}
11619 			break;	/* goto sizeof (int) option return */
11620 		case IPV6_PKTINFO:
11621 			if (inlen == 0)
11622 				return (-EINVAL);	/* clearing option */
11623 			error = ip6_set_pktinfo(cr, connp,
11624 			    (struct in6_pktinfo *)invalp, first_mp);
11625 			if (error != 0)
11626 				*outlenp = 0;
11627 			else
11628 				*outlenp = inlen;
11629 			return (error);
11630 		case IPV6_NEXTHOP: {
11631 			struct sockaddr_in6 *sin6;
11632 
11633 			/* Verify that the nexthop is reachable */
11634 			if (inlen == 0)
11635 				return (-EINVAL);	/* clearing option */
11636 
11637 			sin6 = (struct sockaddr_in6 *)invalp;
11638 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11639 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11640 			    NULL, MATCH_IRE_DEFAULT, ipst);
11641 
11642 			if (ire == NULL) {
11643 				*outlenp = 0;
11644 				return (EHOSTUNREACH);
11645 			}
11646 			ire_refrele(ire);
11647 			return (-EINVAL);
11648 		}
11649 		case IPV6_SEC_OPT:
11650 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11651 			if (error != 0) {
11652 				*outlenp = 0;
11653 				return (error);
11654 			}
11655 			break;
11656 		case IPV6_SRC_PREFERENCES: {
11657 			/*
11658 			 * This is implemented strictly in the ip module
11659 			 * (here and in tcp_opt_*() to accomodate tcp
11660 			 * sockets).  Modules above ip pass this option
11661 			 * down here since ip is the only one that needs to
11662 			 * be aware of source address preferences.
11663 			 *
11664 			 * This socket option only affects connected
11665 			 * sockets that haven't already bound to a specific
11666 			 * IPv6 address.  In other words, sockets that
11667 			 * don't call bind() with an address other than the
11668 			 * unspecified address and that call connect().
11669 			 * ip_bind_connected_v6() passes these preferences
11670 			 * to the ipif_select_source_v6() function.
11671 			 */
11672 			if (inlen != sizeof (uint32_t))
11673 				return (EINVAL);
11674 			error = ip6_set_src_preferences(connp,
11675 			    *(uint32_t *)invalp);
11676 			if (error != 0) {
11677 				*outlenp = 0;
11678 				return (error);
11679 			} else {
11680 				*outlenp = sizeof (uint32_t);
11681 			}
11682 			break;
11683 		}
11684 		case IPV6_V6ONLY:
11685 			if (*i1 < 0 || *i1 > 1) {
11686 				return (EINVAL);
11687 			}
11688 			mutex_enter(&connp->conn_lock);
11689 			connp->conn_ipv6_v6only = *i1;
11690 			mutex_exit(&connp->conn_lock);
11691 			break;
11692 		default:
11693 			return (-EINVAL);
11694 		}
11695 		break;
11696 	default:
11697 		/*
11698 		 * "soft" error (negative)
11699 		 * option not handled at this level
11700 		 * Note: Do not modify *outlenp
11701 		 */
11702 		return (-EINVAL);
11703 	}
11704 	/*
11705 	 * Common case of return from an option that is sizeof (int)
11706 	 */
11707 	*(int *)outvalp = *i1;
11708 	*outlenp = sizeof (int);
11709 	return (0);
11710 }
11711 
11712 /*
11713  * This routine gets default values of certain options whose default
11714  * values are maintained by protocol specific code
11715  */
11716 /* ARGSUSED */
11717 int
11718 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11719 {
11720 	int *i1 = (int *)ptr;
11721 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11722 
11723 	switch (level) {
11724 	case IPPROTO_IP:
11725 		switch (name) {
11726 		case IP_MULTICAST_TTL:
11727 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11728 			return (sizeof (uchar_t));
11729 		case IP_MULTICAST_LOOP:
11730 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11731 			return (sizeof (uchar_t));
11732 		default:
11733 			return (-1);
11734 		}
11735 	case IPPROTO_IPV6:
11736 		switch (name) {
11737 		case IPV6_UNICAST_HOPS:
11738 			*i1 = ipst->ips_ipv6_def_hops;
11739 			return (sizeof (int));
11740 		case IPV6_MULTICAST_HOPS:
11741 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11742 			return (sizeof (int));
11743 		case IPV6_MULTICAST_LOOP:
11744 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11745 			return (sizeof (int));
11746 		case IPV6_V6ONLY:
11747 			*i1 = 1;
11748 			return (sizeof (int));
11749 		default:
11750 			return (-1);
11751 		}
11752 	default:
11753 		return (-1);
11754 	}
11755 	/* NOTREACHED */
11756 }
11757 
11758 /*
11759  * Given a destination address and a pointer to where to put the information
11760  * this routine fills in the mtuinfo.
11761  */
11762 int
11763 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11764     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11765 {
11766 	ire_t *ire;
11767 	ip_stack_t	*ipst = ns->netstack_ip;
11768 
11769 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11770 		return (-1);
11771 
11772 	bzero(mtuinfo, sizeof (*mtuinfo));
11773 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11774 	mtuinfo->ip6m_addr.sin6_port = port;
11775 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11776 
11777 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11778 	if (ire != NULL) {
11779 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11780 		ire_refrele(ire);
11781 	} else {
11782 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11783 	}
11784 	return (sizeof (struct ip6_mtuinfo));
11785 }
11786 
11787 /*
11788  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11789  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11790  * isn't.  This doesn't matter as the error checking is done properly for the
11791  * other MRT options coming in through ip_opt_set.
11792  */
11793 int
11794 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11795 {
11796 	conn_t		*connp = Q_TO_CONN(q);
11797 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11798 
11799 	switch (level) {
11800 	case IPPROTO_IP:
11801 		switch (name) {
11802 		case MRT_VERSION:
11803 		case MRT_ASSERT:
11804 			(void) ip_mrouter_get(name, q, ptr);
11805 			return (sizeof (int));
11806 		case IP_SEC_OPT:
11807 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11808 		case IP_NEXTHOP:
11809 			if (connp->conn_nexthop_set) {
11810 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11811 				return (sizeof (ipaddr_t));
11812 			} else
11813 				return (0);
11814 		case IP_RECVPKTINFO:
11815 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11816 			return (sizeof (int));
11817 		default:
11818 			break;
11819 		}
11820 		break;
11821 	case IPPROTO_IPV6:
11822 		switch (name) {
11823 		case IPV6_SEC_OPT:
11824 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11825 		case IPV6_SRC_PREFERENCES: {
11826 			return (ip6_get_src_preferences(connp,
11827 			    (uint32_t *)ptr));
11828 		}
11829 		case IPV6_V6ONLY:
11830 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11831 			return (sizeof (int));
11832 		case IPV6_PATHMTU:
11833 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11834 				(struct ip6_mtuinfo *)ptr,
11835 				connp->conn_netstack));
11836 		default:
11837 			break;
11838 		}
11839 		break;
11840 	default:
11841 		break;
11842 	}
11843 	return (-1);
11844 }
11845 
11846 /* Named Dispatch routine to get a current value out of our parameter table. */
11847 /* ARGSUSED */
11848 static int
11849 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11850 {
11851 	ipparam_t *ippa = (ipparam_t *)cp;
11852 
11853 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11854 	return (0);
11855 }
11856 
11857 /* ARGSUSED */
11858 static int
11859 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11860 {
11861 
11862 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11863 	return (0);
11864 }
11865 
11866 /*
11867  * Set ip{,6}_forwarding values.  This means walking through all of the
11868  * ill's and toggling their forwarding values.
11869  */
11870 /* ARGSUSED */
11871 static int
11872 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11873 {
11874 	long new_value;
11875 	int *forwarding_value = (int *)cp;
11876 	ill_t *walker;
11877 	boolean_t isv6;
11878 	ill_walk_context_t ctx;
11879 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11880 
11881 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11882 
11883 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11884 	    new_value < 0 || new_value > 1) {
11885 		return (EINVAL);
11886 	}
11887 
11888 	*forwarding_value = new_value;
11889 
11890 	/*
11891 	 * Regardless of the current value of ip_forwarding, set all per-ill
11892 	 * values of ip_forwarding to the value being set.
11893 	 *
11894 	 * Bring all the ill's up to date with the new global value.
11895 	 */
11896 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11897 
11898 	if (isv6)
11899 		walker = ILL_START_WALK_V6(&ctx, ipst);
11900 	else
11901 		walker = ILL_START_WALK_V4(&ctx, ipst);
11902 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11903 		(void) ill_forward_set(q, mp, (new_value != 0),
11904 		    (caddr_t)walker);
11905 	}
11906 	rw_exit(&ipst->ips_ill_g_lock);
11907 
11908 	return (0);
11909 }
11910 
11911 /*
11912  * Walk through the param array specified registering each element with the
11913  * Named Dispatch handler. This is called only during init. So it is ok
11914  * not to acquire any locks
11915  */
11916 static boolean_t
11917 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11918     ipndp_t *ipnd, size_t ipnd_cnt)
11919 {
11920 	for (; ippa_cnt-- > 0; ippa++) {
11921 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11922 			if (!nd_load(ndp, ippa->ip_param_name,
11923 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11924 				nd_free(ndp);
11925 				return (B_FALSE);
11926 			}
11927 		}
11928 	}
11929 
11930 	for (; ipnd_cnt-- > 0; ipnd++) {
11931 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11932 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11933 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11934 			    ipnd->ip_ndp_data)) {
11935 				nd_free(ndp);
11936 				return (B_FALSE);
11937 			}
11938 		}
11939 	}
11940 
11941 	return (B_TRUE);
11942 }
11943 
11944 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11945 /* ARGSUSED */
11946 static int
11947 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11948 {
11949 	long		new_value;
11950 	ipparam_t	*ippa = (ipparam_t *)cp;
11951 
11952 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11953 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11954 		return (EINVAL);
11955 	}
11956 	ippa->ip_param_value = new_value;
11957 	return (0);
11958 }
11959 
11960 /*
11961  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11962  * When an ipf is passed here for the first time, if
11963  * we already have in-order fragments on the queue, we convert from the fast-
11964  * path reassembly scheme to the hard-case scheme.  From then on, additional
11965  * fragments are reassembled here.  We keep track of the start and end offsets
11966  * of each piece, and the number of holes in the chain.  When the hole count
11967  * goes to zero, we are done!
11968  *
11969  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11970  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11971  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11972  * after the call to ip_reassemble().
11973  */
11974 int
11975 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11976     size_t msg_len)
11977 {
11978 	uint_t	end;
11979 	mblk_t	*next_mp;
11980 	mblk_t	*mp1;
11981 	uint_t	offset;
11982 	boolean_t incr_dups = B_TRUE;
11983 	boolean_t offset_zero_seen = B_FALSE;
11984 	boolean_t pkt_boundary_checked = B_FALSE;
11985 
11986 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11987 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11988 
11989 	/* Add in byte count */
11990 	ipf->ipf_count += msg_len;
11991 	if (ipf->ipf_end) {
11992 		/*
11993 		 * We were part way through in-order reassembly, but now there
11994 		 * is a hole.  We walk through messages already queued, and
11995 		 * mark them for hard case reassembly.  We know that up till
11996 		 * now they were in order starting from offset zero.
11997 		 */
11998 		offset = 0;
11999 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12000 			IP_REASS_SET_START(mp1, offset);
12001 			if (offset == 0) {
12002 				ASSERT(ipf->ipf_nf_hdr_len != 0);
12003 				offset = -ipf->ipf_nf_hdr_len;
12004 			}
12005 			offset += mp1->b_wptr - mp1->b_rptr;
12006 			IP_REASS_SET_END(mp1, offset);
12007 		}
12008 		/* One hole at the end. */
12009 		ipf->ipf_hole_cnt = 1;
12010 		/* Brand it as a hard case, forever. */
12011 		ipf->ipf_end = 0;
12012 	}
12013 	/* Walk through all the new pieces. */
12014 	do {
12015 		end = start + (mp->b_wptr - mp->b_rptr);
12016 		/*
12017 		 * If start is 0, decrease 'end' only for the first mblk of
12018 		 * the fragment. Otherwise 'end' can get wrong value in the
12019 		 * second pass of the loop if first mblk is exactly the
12020 		 * size of ipf_nf_hdr_len.
12021 		 */
12022 		if (start == 0 && !offset_zero_seen) {
12023 			/* First segment */
12024 			ASSERT(ipf->ipf_nf_hdr_len != 0);
12025 			end -= ipf->ipf_nf_hdr_len;
12026 			offset_zero_seen = B_TRUE;
12027 		}
12028 		next_mp = mp->b_cont;
12029 		/*
12030 		 * We are checking to see if there is any interesing data
12031 		 * to process.  If there isn't and the mblk isn't the
12032 		 * one which carries the unfragmentable header then we
12033 		 * drop it.  It's possible to have just the unfragmentable
12034 		 * header come through without any data.  That needs to be
12035 		 * saved.
12036 		 *
12037 		 * If the assert at the top of this function holds then the
12038 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
12039 		 * is infrequently traveled enough that the test is left in
12040 		 * to protect against future code changes which break that
12041 		 * invariant.
12042 		 */
12043 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
12044 			/* Empty.  Blast it. */
12045 			IP_REASS_SET_START(mp, 0);
12046 			IP_REASS_SET_END(mp, 0);
12047 			/*
12048 			 * If the ipf points to the mblk we are about to free,
12049 			 * update ipf to point to the next mblk (or NULL
12050 			 * if none).
12051 			 */
12052 			if (ipf->ipf_mp->b_cont == mp)
12053 				ipf->ipf_mp->b_cont = next_mp;
12054 			freeb(mp);
12055 			continue;
12056 		}
12057 		mp->b_cont = NULL;
12058 		IP_REASS_SET_START(mp, start);
12059 		IP_REASS_SET_END(mp, end);
12060 		if (!ipf->ipf_tail_mp) {
12061 			ipf->ipf_tail_mp = mp;
12062 			ipf->ipf_mp->b_cont = mp;
12063 			if (start == 0 || !more) {
12064 				ipf->ipf_hole_cnt = 1;
12065 				/*
12066 				 * if the first fragment comes in more than one
12067 				 * mblk, this loop will be executed for each
12068 				 * mblk. Need to adjust hole count so exiting
12069 				 * this routine will leave hole count at 1.
12070 				 */
12071 				if (next_mp)
12072 					ipf->ipf_hole_cnt++;
12073 			} else
12074 				ipf->ipf_hole_cnt = 2;
12075 			continue;
12076 		} else if (ipf->ipf_last_frag_seen && !more &&
12077 			    !pkt_boundary_checked) {
12078 			/*
12079 			 * We check datagram boundary only if this fragment
12080 			 * claims to be the last fragment and we have seen a
12081 			 * last fragment in the past too. We do this only
12082 			 * once for a given fragment.
12083 			 *
12084 			 * start cannot be 0 here as fragments with start=0
12085 			 * and MF=0 gets handled as a complete packet. These
12086 			 * fragments should not reach here.
12087 			 */
12088 
12089 			if (start + msgdsize(mp) !=
12090 			    IP_REASS_END(ipf->ipf_tail_mp)) {
12091 				/*
12092 				 * We have two fragments both of which claim
12093 				 * to be the last fragment but gives conflicting
12094 				 * information about the whole datagram size.
12095 				 * Something fishy is going on. Drop the
12096 				 * fragment and free up the reassembly list.
12097 				 */
12098 				return (IP_REASS_FAILED);
12099 			}
12100 
12101 			/*
12102 			 * We shouldn't come to this code block again for this
12103 			 * particular fragment.
12104 			 */
12105 			pkt_boundary_checked = B_TRUE;
12106 		}
12107 
12108 		/* New stuff at or beyond tail? */
12109 		offset = IP_REASS_END(ipf->ipf_tail_mp);
12110 		if (start >= offset) {
12111 			if (ipf->ipf_last_frag_seen) {
12112 				/* current fragment is beyond last fragment */
12113 				return (IP_REASS_FAILED);
12114 			}
12115 			/* Link it on end. */
12116 			ipf->ipf_tail_mp->b_cont = mp;
12117 			ipf->ipf_tail_mp = mp;
12118 			if (more) {
12119 				if (start != offset)
12120 					ipf->ipf_hole_cnt++;
12121 			} else if (start == offset && next_mp == NULL)
12122 					ipf->ipf_hole_cnt--;
12123 			continue;
12124 		}
12125 		mp1 = ipf->ipf_mp->b_cont;
12126 		offset = IP_REASS_START(mp1);
12127 		/* New stuff at the front? */
12128 		if (start < offset) {
12129 			if (start == 0) {
12130 				if (end >= offset) {
12131 					/* Nailed the hole at the begining. */
12132 					ipf->ipf_hole_cnt--;
12133 				}
12134 			} else if (end < offset) {
12135 				/*
12136 				 * A hole, stuff, and a hole where there used
12137 				 * to be just a hole.
12138 				 */
12139 				ipf->ipf_hole_cnt++;
12140 			}
12141 			mp->b_cont = mp1;
12142 			/* Check for overlap. */
12143 			while (end > offset) {
12144 				if (end < IP_REASS_END(mp1)) {
12145 					mp->b_wptr -= end - offset;
12146 					IP_REASS_SET_END(mp, offset);
12147 					BUMP_MIB(ill->ill_ip_mib,
12148 					    ipIfStatsReasmPartDups);
12149 					break;
12150 				}
12151 				/* Did we cover another hole? */
12152 				if ((mp1->b_cont &&
12153 				    IP_REASS_END(mp1) !=
12154 				    IP_REASS_START(mp1->b_cont) &&
12155 				    end >= IP_REASS_START(mp1->b_cont)) ||
12156 				    (!ipf->ipf_last_frag_seen && !more)) {
12157 					ipf->ipf_hole_cnt--;
12158 				}
12159 				/* Clip out mp1. */
12160 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12161 					/*
12162 					 * After clipping out mp1, this guy
12163 					 * is now hanging off the end.
12164 					 */
12165 					ipf->ipf_tail_mp = mp;
12166 				}
12167 				IP_REASS_SET_START(mp1, 0);
12168 				IP_REASS_SET_END(mp1, 0);
12169 				/* Subtract byte count */
12170 				ipf->ipf_count -= mp1->b_datap->db_lim -
12171 				    mp1->b_datap->db_base;
12172 				freeb(mp1);
12173 				BUMP_MIB(ill->ill_ip_mib,
12174 				    ipIfStatsReasmPartDups);
12175 				mp1 = mp->b_cont;
12176 				if (!mp1)
12177 					break;
12178 				offset = IP_REASS_START(mp1);
12179 			}
12180 			ipf->ipf_mp->b_cont = mp;
12181 			continue;
12182 		}
12183 		/*
12184 		 * The new piece starts somewhere between the start of the head
12185 		 * and before the end of the tail.
12186 		 */
12187 		for (; mp1; mp1 = mp1->b_cont) {
12188 			offset = IP_REASS_END(mp1);
12189 			if (start < offset) {
12190 				if (end <= offset) {
12191 					/* Nothing new. */
12192 					IP_REASS_SET_START(mp, 0);
12193 					IP_REASS_SET_END(mp, 0);
12194 					/* Subtract byte count */
12195 					ipf->ipf_count -= mp->b_datap->db_lim -
12196 					    mp->b_datap->db_base;
12197 					if (incr_dups) {
12198 						ipf->ipf_num_dups++;
12199 						incr_dups = B_FALSE;
12200 					}
12201 					freeb(mp);
12202 					BUMP_MIB(ill->ill_ip_mib,
12203 					    ipIfStatsReasmDuplicates);
12204 					break;
12205 				}
12206 				/*
12207 				 * Trim redundant stuff off beginning of new
12208 				 * piece.
12209 				 */
12210 				IP_REASS_SET_START(mp, offset);
12211 				mp->b_rptr += offset - start;
12212 				BUMP_MIB(ill->ill_ip_mib,
12213 				    ipIfStatsReasmPartDups);
12214 				start = offset;
12215 				if (!mp1->b_cont) {
12216 					/*
12217 					 * After trimming, this guy is now
12218 					 * hanging off the end.
12219 					 */
12220 					mp1->b_cont = mp;
12221 					ipf->ipf_tail_mp = mp;
12222 					if (!more) {
12223 						ipf->ipf_hole_cnt--;
12224 					}
12225 					break;
12226 				}
12227 			}
12228 			if (start >= IP_REASS_START(mp1->b_cont))
12229 				continue;
12230 			/* Fill a hole */
12231 			if (start > offset)
12232 				ipf->ipf_hole_cnt++;
12233 			mp->b_cont = mp1->b_cont;
12234 			mp1->b_cont = mp;
12235 			mp1 = mp->b_cont;
12236 			offset = IP_REASS_START(mp1);
12237 			if (end >= offset) {
12238 				ipf->ipf_hole_cnt--;
12239 				/* Check for overlap. */
12240 				while (end > offset) {
12241 					if (end < IP_REASS_END(mp1)) {
12242 						mp->b_wptr -= end - offset;
12243 						IP_REASS_SET_END(mp, offset);
12244 						/*
12245 						 * TODO we might bump
12246 						 * this up twice if there is
12247 						 * overlap at both ends.
12248 						 */
12249 						BUMP_MIB(ill->ill_ip_mib,
12250 						    ipIfStatsReasmPartDups);
12251 						break;
12252 					}
12253 					/* Did we cover another hole? */
12254 					if ((mp1->b_cont &&
12255 					    IP_REASS_END(mp1)
12256 					    != IP_REASS_START(mp1->b_cont) &&
12257 					    end >=
12258 					    IP_REASS_START(mp1->b_cont)) ||
12259 					    (!ipf->ipf_last_frag_seen &&
12260 					    !more)) {
12261 						ipf->ipf_hole_cnt--;
12262 					}
12263 					/* Clip out mp1. */
12264 					if ((mp->b_cont = mp1->b_cont) ==
12265 					    NULL) {
12266 						/*
12267 						 * After clipping out mp1,
12268 						 * this guy is now hanging
12269 						 * off the end.
12270 						 */
12271 						ipf->ipf_tail_mp = mp;
12272 					}
12273 					IP_REASS_SET_START(mp1, 0);
12274 					IP_REASS_SET_END(mp1, 0);
12275 					/* Subtract byte count */
12276 					ipf->ipf_count -=
12277 					    mp1->b_datap->db_lim -
12278 					    mp1->b_datap->db_base;
12279 					freeb(mp1);
12280 					BUMP_MIB(ill->ill_ip_mib,
12281 					    ipIfStatsReasmPartDups);
12282 					mp1 = mp->b_cont;
12283 					if (!mp1)
12284 						break;
12285 					offset = IP_REASS_START(mp1);
12286 				}
12287 			}
12288 			break;
12289 		}
12290 	} while (start = end, mp = next_mp);
12291 
12292 	/* Fragment just processed could be the last one. Remember this fact */
12293 	if (!more)
12294 		ipf->ipf_last_frag_seen = B_TRUE;
12295 
12296 	/* Still got holes? */
12297 	if (ipf->ipf_hole_cnt)
12298 		return (IP_REASS_PARTIAL);
12299 	/* Clean up overloaded fields to avoid upstream disasters. */
12300 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12301 		IP_REASS_SET_START(mp1, 0);
12302 		IP_REASS_SET_END(mp1, 0);
12303 	}
12304 	return (IP_REASS_COMPLETE);
12305 }
12306 
12307 /*
12308  * ipsec processing for the fast path, used for input UDP Packets
12309  */
12310 static boolean_t
12311 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12312     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12313 {
12314 	uint32_t	ill_index;
12315 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12316 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12317 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12318 
12319 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12320 	/* The ill_index of the incoming ILL */
12321 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12322 
12323 	/* pass packet up to the transport */
12324 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12325 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12326 		    NULL, mctl_present);
12327 		if (*first_mpp == NULL) {
12328 			return (B_FALSE);
12329 		}
12330 	}
12331 
12332 	/* Initiate IPPF processing for fastpath UDP */
12333 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12334 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12335 		if (*mpp == NULL) {
12336 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12337 			    "deferred/dropped during IPPF processing\n"));
12338 			return (B_FALSE);
12339 		}
12340 	}
12341 	/*
12342 	 * We make the checks as below since we are in the fast path
12343 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12344 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12345 	 */
12346 	if (connp->conn_recvif || connp->conn_recvslla ||
12347 	    connp->conn_ip_recvpktinfo) {
12348 		if (connp->conn_recvif) {
12349 			in_flags = IPF_RECVIF;
12350 		}
12351 		/*
12352 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12353 		 * so the flag passed to ip_add_info is based on IP version
12354 		 * of connp.
12355 		 */
12356 		if (connp->conn_ip_recvpktinfo) {
12357 			if (connp->conn_af_isv6) {
12358 				/*
12359 				 * V6 only needs index
12360 				 */
12361 				in_flags |= IPF_RECVIF;
12362 			} else {
12363 				/*
12364 				 * V4 needs index + matching address.
12365 				 */
12366 				in_flags |= IPF_RECVADDR;
12367 			}
12368 		}
12369 		if (connp->conn_recvslla) {
12370 			in_flags |= IPF_RECVSLLA;
12371 		}
12372 		/*
12373 		 * since in_flags are being set ill will be
12374 		 * referenced in ip_add_info, so it better not
12375 		 * be NULL.
12376 		 */
12377 		/*
12378 		 * the actual data will be contained in b_cont
12379 		 * upon successful return of the following call.
12380 		 * If the call fails then the original mblk is
12381 		 * returned.
12382 		 */
12383 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12384 		    ipst);
12385 	}
12386 
12387 	return (B_TRUE);
12388 }
12389 
12390 /*
12391  * Fragmentation reassembly.  Each ILL has a hash table for
12392  * queuing packets undergoing reassembly for all IPIFs
12393  * associated with the ILL.  The hash is based on the packet
12394  * IP ident field.  The ILL frag hash table was allocated
12395  * as a timer block at the time the ILL was created.  Whenever
12396  * there is anything on the reassembly queue, the timer will
12397  * be running.  Returns B_TRUE if successful else B_FALSE;
12398  * frees mp on failure.
12399  */
12400 static boolean_t
12401 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12402     uint32_t *cksum_val, uint16_t *cksum_flags)
12403 {
12404 	uint32_t	frag_offset_flags;
12405 	ill_t		*ill = (ill_t *)q->q_ptr;
12406 	mblk_t		*mp = *mpp;
12407 	mblk_t		*t_mp;
12408 	ipaddr_t	dst;
12409 	uint8_t		proto = ipha->ipha_protocol;
12410 	uint32_t	sum_val;
12411 	uint16_t	sum_flags;
12412 	ipf_t		*ipf;
12413 	ipf_t		**ipfp;
12414 	ipfb_t		*ipfb;
12415 	uint16_t	ident;
12416 	uint32_t	offset;
12417 	ipaddr_t	src;
12418 	uint_t		hdr_length;
12419 	uint32_t	end;
12420 	mblk_t		*mp1;
12421 	mblk_t		*tail_mp;
12422 	size_t		count;
12423 	size_t		msg_len;
12424 	uint8_t		ecn_info = 0;
12425 	uint32_t	packet_size;
12426 	boolean_t	pruned = B_FALSE;
12427 	ip_stack_t *ipst = ill->ill_ipst;
12428 
12429 	if (cksum_val != NULL)
12430 		*cksum_val = 0;
12431 	if (cksum_flags != NULL)
12432 		*cksum_flags = 0;
12433 
12434 	/*
12435 	 * Drop the fragmented as early as possible, if
12436 	 * we don't have resource(s) to re-assemble.
12437 	 */
12438 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12439 		freemsg(mp);
12440 		return (B_FALSE);
12441 	}
12442 
12443 	/* Check for fragmentation offset; return if there's none */
12444 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12445 	    (IPH_MF | IPH_OFFSET)) == 0)
12446 		return (B_TRUE);
12447 
12448 	/*
12449 	 * We utilize hardware computed checksum info only for UDP since
12450 	 * IP fragmentation is a normal occurence for the protocol.  In
12451 	 * addition, checksum offload support for IP fragments carrying
12452 	 * UDP payload is commonly implemented across network adapters.
12453 	 */
12454 	ASSERT(ill != NULL);
12455 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12456 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12457 		mblk_t *mp1 = mp->b_cont;
12458 		int32_t len;
12459 
12460 		/* Record checksum information from the packet */
12461 		sum_val = (uint32_t)DB_CKSUM16(mp);
12462 		sum_flags = DB_CKSUMFLAGS(mp);
12463 
12464 		/* IP payload offset from beginning of mblk */
12465 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12466 
12467 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12468 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12469 		    offset >= DB_CKSUMSTART(mp) &&
12470 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12471 			uint32_t adj;
12472 			/*
12473 			 * Partial checksum has been calculated by hardware
12474 			 * and attached to the packet; in addition, any
12475 			 * prepended extraneous data is even byte aligned.
12476 			 * If any such data exists, we adjust the checksum;
12477 			 * this would also handle any postpended data.
12478 			 */
12479 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12480 			    mp, mp1, len, adj);
12481 
12482 			/* One's complement subtract extraneous checksum */
12483 			if (adj >= sum_val)
12484 				sum_val = ~(adj - sum_val) & 0xFFFF;
12485 			else
12486 				sum_val -= adj;
12487 		}
12488 	} else {
12489 		sum_val = 0;
12490 		sum_flags = 0;
12491 	}
12492 
12493 	/* Clear hardware checksumming flag */
12494 	DB_CKSUMFLAGS(mp) = 0;
12495 
12496 	ident = ipha->ipha_ident;
12497 	offset = (frag_offset_flags << 3) & 0xFFFF;
12498 	src = ipha->ipha_src;
12499 	dst = ipha->ipha_dst;
12500 	hdr_length = IPH_HDR_LENGTH(ipha);
12501 	end = ntohs(ipha->ipha_length) - hdr_length;
12502 
12503 	/* If end == 0 then we have a packet with no data, so just free it */
12504 	if (end == 0) {
12505 		freemsg(mp);
12506 		return (B_FALSE);
12507 	}
12508 
12509 	/* Record the ECN field info. */
12510 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12511 	if (offset != 0) {
12512 		/*
12513 		 * If this isn't the first piece, strip the header, and
12514 		 * add the offset to the end value.
12515 		 */
12516 		mp->b_rptr += hdr_length;
12517 		end += offset;
12518 	}
12519 
12520 	msg_len = MBLKSIZE(mp);
12521 	tail_mp = mp;
12522 	while (tail_mp->b_cont != NULL) {
12523 		tail_mp = tail_mp->b_cont;
12524 		msg_len += MBLKSIZE(tail_mp);
12525 	}
12526 
12527 	/* If the reassembly list for this ILL will get too big, prune it */
12528 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12529 	    ipst->ips_ip_reass_queue_bytes) {
12530 		ill_frag_prune(ill,
12531 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12532 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12533 		pruned = B_TRUE;
12534 	}
12535 
12536 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12537 	mutex_enter(&ipfb->ipfb_lock);
12538 
12539 	ipfp = &ipfb->ipfb_ipf;
12540 	/* Try to find an existing fragment queue for this packet. */
12541 	for (;;) {
12542 		ipf = ipfp[0];
12543 		if (ipf != NULL) {
12544 			/*
12545 			 * It has to match on ident and src/dst address.
12546 			 */
12547 			if (ipf->ipf_ident == ident &&
12548 			    ipf->ipf_src == src &&
12549 			    ipf->ipf_dst == dst &&
12550 			    ipf->ipf_protocol == proto) {
12551 				/*
12552 				 * If we have received too many
12553 				 * duplicate fragments for this packet
12554 				 * free it.
12555 				 */
12556 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12557 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12558 					freemsg(mp);
12559 					mutex_exit(&ipfb->ipfb_lock);
12560 					return (B_FALSE);
12561 				}
12562 				/* Found it. */
12563 				break;
12564 			}
12565 			ipfp = &ipf->ipf_hash_next;
12566 			continue;
12567 		}
12568 
12569 		/*
12570 		 * If we pruned the list, do we want to store this new
12571 		 * fragment?. We apply an optimization here based on the
12572 		 * fact that most fragments will be received in order.
12573 		 * So if the offset of this incoming fragment is zero,
12574 		 * it is the first fragment of a new packet. We will
12575 		 * keep it.  Otherwise drop the fragment, as we have
12576 		 * probably pruned the packet already (since the
12577 		 * packet cannot be found).
12578 		 */
12579 		if (pruned && offset != 0) {
12580 			mutex_exit(&ipfb->ipfb_lock);
12581 			freemsg(mp);
12582 			return (B_FALSE);
12583 		}
12584 
12585 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12586 			/*
12587 			 * Too many fragmented packets in this hash
12588 			 * bucket. Free the oldest.
12589 			 */
12590 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12591 		}
12592 
12593 		/* New guy.  Allocate a frag message. */
12594 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12595 		if (mp1 == NULL) {
12596 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12597 			freemsg(mp);
12598 reass_done:
12599 			mutex_exit(&ipfb->ipfb_lock);
12600 			return (B_FALSE);
12601 		}
12602 
12603 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12604 		mp1->b_cont = mp;
12605 
12606 		/* Initialize the fragment header. */
12607 		ipf = (ipf_t *)mp1->b_rptr;
12608 		ipf->ipf_mp = mp1;
12609 		ipf->ipf_ptphn = ipfp;
12610 		ipfp[0] = ipf;
12611 		ipf->ipf_hash_next = NULL;
12612 		ipf->ipf_ident = ident;
12613 		ipf->ipf_protocol = proto;
12614 		ipf->ipf_src = src;
12615 		ipf->ipf_dst = dst;
12616 		ipf->ipf_nf_hdr_len = 0;
12617 		/* Record reassembly start time. */
12618 		ipf->ipf_timestamp = gethrestime_sec();
12619 		/* Record ipf generation and account for frag header */
12620 		ipf->ipf_gen = ill->ill_ipf_gen++;
12621 		ipf->ipf_count = MBLKSIZE(mp1);
12622 		ipf->ipf_last_frag_seen = B_FALSE;
12623 		ipf->ipf_ecn = ecn_info;
12624 		ipf->ipf_num_dups = 0;
12625 		ipfb->ipfb_frag_pkts++;
12626 		ipf->ipf_checksum = 0;
12627 		ipf->ipf_checksum_flags = 0;
12628 
12629 		/* Store checksum value in fragment header */
12630 		if (sum_flags != 0) {
12631 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12632 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12633 			ipf->ipf_checksum = sum_val;
12634 			ipf->ipf_checksum_flags = sum_flags;
12635 		}
12636 
12637 		/*
12638 		 * We handle reassembly two ways.  In the easy case,
12639 		 * where all the fragments show up in order, we do
12640 		 * minimal bookkeeping, and just clip new pieces on
12641 		 * the end.  If we ever see a hole, then we go off
12642 		 * to ip_reassemble which has to mark the pieces and
12643 		 * keep track of the number of holes, etc.  Obviously,
12644 		 * the point of having both mechanisms is so we can
12645 		 * handle the easy case as efficiently as possible.
12646 		 */
12647 		if (offset == 0) {
12648 			/* Easy case, in-order reassembly so far. */
12649 			ipf->ipf_count += msg_len;
12650 			ipf->ipf_tail_mp = tail_mp;
12651 			/*
12652 			 * Keep track of next expected offset in
12653 			 * ipf_end.
12654 			 */
12655 			ipf->ipf_end = end;
12656 			ipf->ipf_nf_hdr_len = hdr_length;
12657 		} else {
12658 			/* Hard case, hole at the beginning. */
12659 			ipf->ipf_tail_mp = NULL;
12660 			/*
12661 			 * ipf_end == 0 means that we have given up
12662 			 * on easy reassembly.
12663 			 */
12664 			ipf->ipf_end = 0;
12665 
12666 			/* Forget checksum offload from now on */
12667 			ipf->ipf_checksum_flags = 0;
12668 
12669 			/*
12670 			 * ipf_hole_cnt is set by ip_reassemble.
12671 			 * ipf_count is updated by ip_reassemble.
12672 			 * No need to check for return value here
12673 			 * as we don't expect reassembly to complete
12674 			 * or fail for the first fragment itself.
12675 			 */
12676 			(void) ip_reassemble(mp, ipf,
12677 			    (frag_offset_flags & IPH_OFFSET) << 3,
12678 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12679 		}
12680 		/* Update per ipfb and ill byte counts */
12681 		ipfb->ipfb_count += ipf->ipf_count;
12682 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12683 		ill->ill_frag_count += ipf->ipf_count;
12684 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12685 		/* If the frag timer wasn't already going, start it. */
12686 		mutex_enter(&ill->ill_lock);
12687 		ill_frag_timer_start(ill);
12688 		mutex_exit(&ill->ill_lock);
12689 		goto reass_done;
12690 	}
12691 
12692 	/*
12693 	 * If the packet's flag has changed (it could be coming up
12694 	 * from an interface different than the previous, therefore
12695 	 * possibly different checksum capability), then forget about
12696 	 * any stored checksum states.  Otherwise add the value to
12697 	 * the existing one stored in the fragment header.
12698 	 */
12699 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12700 		sum_val += ipf->ipf_checksum;
12701 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12702 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12703 		ipf->ipf_checksum = sum_val;
12704 	} else if (ipf->ipf_checksum_flags != 0) {
12705 		/* Forget checksum offload from now on */
12706 		ipf->ipf_checksum_flags = 0;
12707 	}
12708 
12709 	/*
12710 	 * We have a new piece of a datagram which is already being
12711 	 * reassembled.  Update the ECN info if all IP fragments
12712 	 * are ECN capable.  If there is one which is not, clear
12713 	 * all the info.  If there is at least one which has CE
12714 	 * code point, IP needs to report that up to transport.
12715 	 */
12716 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12717 		if (ecn_info == IPH_ECN_CE)
12718 			ipf->ipf_ecn = IPH_ECN_CE;
12719 	} else {
12720 		ipf->ipf_ecn = IPH_ECN_NECT;
12721 	}
12722 	if (offset && ipf->ipf_end == offset) {
12723 		/* The new fragment fits at the end */
12724 		ipf->ipf_tail_mp->b_cont = mp;
12725 		/* Update the byte count */
12726 		ipf->ipf_count += msg_len;
12727 		/* Update per ipfb and ill byte counts */
12728 		ipfb->ipfb_count += msg_len;
12729 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12730 		ill->ill_frag_count += msg_len;
12731 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12732 		if (frag_offset_flags & IPH_MF) {
12733 			/* More to come. */
12734 			ipf->ipf_end = end;
12735 			ipf->ipf_tail_mp = tail_mp;
12736 			goto reass_done;
12737 		}
12738 	} else {
12739 		/* Go do the hard cases. */
12740 		int ret;
12741 
12742 		if (offset == 0)
12743 			ipf->ipf_nf_hdr_len = hdr_length;
12744 
12745 		/* Save current byte count */
12746 		count = ipf->ipf_count;
12747 		ret = ip_reassemble(mp, ipf,
12748 		    (frag_offset_flags & IPH_OFFSET) << 3,
12749 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12750 		/* Count of bytes added and subtracted (freeb()ed) */
12751 		count = ipf->ipf_count - count;
12752 		if (count) {
12753 			/* Update per ipfb and ill byte counts */
12754 			ipfb->ipfb_count += count;
12755 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12756 			ill->ill_frag_count += count;
12757 			ASSERT(ill->ill_frag_count > 0);
12758 		}
12759 		if (ret == IP_REASS_PARTIAL) {
12760 			goto reass_done;
12761 		} else if (ret == IP_REASS_FAILED) {
12762 			/* Reassembly failed. Free up all resources */
12763 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12764 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12765 				IP_REASS_SET_START(t_mp, 0);
12766 				IP_REASS_SET_END(t_mp, 0);
12767 			}
12768 			freemsg(mp);
12769 			goto reass_done;
12770 		}
12771 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12772 	}
12773 	/*
12774 	 * We have completed reassembly.  Unhook the frag header from
12775 	 * the reassembly list.
12776 	 *
12777 	 * Before we free the frag header, record the ECN info
12778 	 * to report back to the transport.
12779 	 */
12780 	ecn_info = ipf->ipf_ecn;
12781 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12782 	ipfp = ipf->ipf_ptphn;
12783 
12784 	/* We need to supply these to caller */
12785 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12786 		sum_val = ipf->ipf_checksum;
12787 	else
12788 		sum_val = 0;
12789 
12790 	mp1 = ipf->ipf_mp;
12791 	count = ipf->ipf_count;
12792 	ipf = ipf->ipf_hash_next;
12793 	if (ipf != NULL)
12794 		ipf->ipf_ptphn = ipfp;
12795 	ipfp[0] = ipf;
12796 	ill->ill_frag_count -= count;
12797 	ASSERT(ipfb->ipfb_count >= count);
12798 	ipfb->ipfb_count -= count;
12799 	ipfb->ipfb_frag_pkts--;
12800 	mutex_exit(&ipfb->ipfb_lock);
12801 	/* Ditch the frag header. */
12802 	mp = mp1->b_cont;
12803 
12804 	freeb(mp1);
12805 
12806 	/* Restore original IP length in header. */
12807 	packet_size = (uint32_t)msgdsize(mp);
12808 	if (packet_size > IP_MAXPACKET) {
12809 		freemsg(mp);
12810 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12811 		return (B_FALSE);
12812 	}
12813 
12814 	if (DB_REF(mp) > 1) {
12815 		mblk_t *mp2 = copymsg(mp);
12816 
12817 		freemsg(mp);
12818 		if (mp2 == NULL) {
12819 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12820 			return (B_FALSE);
12821 		}
12822 		mp = mp2;
12823 	}
12824 	ipha = (ipha_t *)mp->b_rptr;
12825 
12826 	ipha->ipha_length = htons((uint16_t)packet_size);
12827 	/* We're now complete, zip the frag state */
12828 	ipha->ipha_fragment_offset_and_flags = 0;
12829 	/* Record the ECN info. */
12830 	ipha->ipha_type_of_service &= 0xFC;
12831 	ipha->ipha_type_of_service |= ecn_info;
12832 	*mpp = mp;
12833 
12834 	/* Reassembly is successful; return checksum information if needed */
12835 	if (cksum_val != NULL)
12836 		*cksum_val = sum_val;
12837 	if (cksum_flags != NULL)
12838 		*cksum_flags = sum_flags;
12839 
12840 	return (B_TRUE);
12841 }
12842 
12843 /*
12844  * Perform ip header check sum update local options.
12845  * return B_TRUE if all is well, else return B_FALSE and release
12846  * the mp. caller is responsible for decrementing ire ref cnt.
12847  */
12848 static boolean_t
12849 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12850     ip_stack_t *ipst)
12851 {
12852 	mblk_t		*first_mp;
12853 	boolean_t	mctl_present;
12854 	uint16_t	sum;
12855 
12856 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12857 	/*
12858 	 * Don't do the checksum if it has gone through AH/ESP
12859 	 * processing.
12860 	 */
12861 	if (!mctl_present) {
12862 		sum = ip_csum_hdr(ipha);
12863 		if (sum != 0) {
12864 			if (ill != NULL) {
12865 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12866 			} else {
12867 				BUMP_MIB(&ipst->ips_ip_mib,
12868 				    ipIfStatsInCksumErrs);
12869 			}
12870 			freemsg(first_mp);
12871 			return (B_FALSE);
12872 		}
12873 	}
12874 
12875 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12876 		if (mctl_present)
12877 			freeb(first_mp);
12878 		return (B_FALSE);
12879 	}
12880 
12881 	return (B_TRUE);
12882 }
12883 
12884 /*
12885  * All udp packet are delivered to the local host via this routine.
12886  */
12887 void
12888 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12889     ill_t *recv_ill)
12890 {
12891 	uint32_t	sum;
12892 	uint32_t	u1;
12893 	boolean_t	mctl_present;
12894 	conn_t		*connp;
12895 	mblk_t		*first_mp;
12896 	uint16_t	*up;
12897 	ill_t		*ill = (ill_t *)q->q_ptr;
12898 	uint16_t	reass_hck_flags = 0;
12899 	ip_stack_t	*ipst;
12900 
12901 	ASSERT(recv_ill != NULL);
12902 	ipst = recv_ill->ill_ipst;
12903 
12904 #define	rptr    ((uchar_t *)ipha)
12905 
12906 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12907 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12908 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12909 	ASSERT(ill != NULL);
12910 
12911 	/*
12912 	 * FAST PATH for udp packets
12913 	 */
12914 
12915 	/* u1 is # words of IP options */
12916 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12917 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12918 
12919 	/* IP options present */
12920 	if (u1 != 0)
12921 		goto ipoptions;
12922 
12923 	/* Check the IP header checksum.  */
12924 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12925 		/* Clear the IP header h/w cksum flag */
12926 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12927 	} else {
12928 #define	uph	((uint16_t *)ipha)
12929 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12930 		    uph[6] + uph[7] + uph[8] + uph[9];
12931 #undef	uph
12932 		/* finish doing IP checksum */
12933 		sum = (sum & 0xFFFF) + (sum >> 16);
12934 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12935 		/*
12936 		 * Don't verify header checksum if this packet is coming
12937 		 * back from AH/ESP as we already did it.
12938 		 */
12939 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12940 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12941 			freemsg(first_mp);
12942 			return;
12943 		}
12944 	}
12945 
12946 	/*
12947 	 * Count for SNMP of inbound packets for ire.
12948 	 * if mctl is present this might be a secure packet and
12949 	 * has already been counted for in ip_proto_input().
12950 	 */
12951 	if (!mctl_present) {
12952 		UPDATE_IB_PKT_COUNT(ire);
12953 		ire->ire_last_used_time = lbolt;
12954 	}
12955 
12956 	/* packet part of fragmented IP packet? */
12957 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12958 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12959 		goto fragmented;
12960 	}
12961 
12962 	/* u1 = IP header length (20 bytes) */
12963 	u1 = IP_SIMPLE_HDR_LENGTH;
12964 
12965 	/* packet does not contain complete IP & UDP headers */
12966 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12967 		goto udppullup;
12968 
12969 	/* up points to UDP header */
12970 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12971 #define	iphs    ((uint16_t *)ipha)
12972 
12973 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12974 	if (up[3] != 0) {
12975 		mblk_t *mp1 = mp->b_cont;
12976 		boolean_t cksum_err;
12977 		uint16_t hck_flags = 0;
12978 
12979 		/* Pseudo-header checksum */
12980 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12981 		    iphs[9] + up[2];
12982 
12983 		/*
12984 		 * Revert to software checksum calculation if the interface
12985 		 * isn't capable of checksum offload or if IPsec is present.
12986 		 */
12987 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12988 			hck_flags = DB_CKSUMFLAGS(mp);
12989 
12990 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12991 			IP_STAT(ipst, ip_in_sw_cksum);
12992 
12993 		IP_CKSUM_RECV(hck_flags, u1,
12994 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12995 		    (int32_t)((uchar_t *)up - rptr),
12996 		    mp, mp1, cksum_err);
12997 
12998 		if (cksum_err) {
12999 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13000 			if (hck_flags & HCK_FULLCKSUM)
13001 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13002 			else if (hck_flags & HCK_PARTIALCKSUM)
13003 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13004 			else
13005 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13006 
13007 			freemsg(first_mp);
13008 			return;
13009 		}
13010 	}
13011 
13012 	/* Non-fragmented broadcast or multicast packet? */
13013 	if (ire->ire_type == IRE_BROADCAST)
13014 		goto udpslowpath;
13015 
13016 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
13017 	    ire->ire_zoneid, ipst)) != NULL) {
13018 		ASSERT(connp->conn_upq != NULL);
13019 		IP_STAT(ipst, ip_udp_fast_path);
13020 
13021 		if (CONN_UDP_FLOWCTLD(connp)) {
13022 			freemsg(mp);
13023 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
13024 		} else {
13025 			if (!mctl_present) {
13026 				BUMP_MIB(ill->ill_ip_mib,
13027 				    ipIfStatsHCInDelivers);
13028 			}
13029 			/*
13030 			 * mp and first_mp can change.
13031 			 */
13032 			if (ip_udp_check(q, connp, recv_ill,
13033 			    ipha, &mp, &first_mp, mctl_present)) {
13034 				/* Send it upstream */
13035 				CONN_UDP_RECV(connp, mp);
13036 			}
13037 		}
13038 		/*
13039 		 * freeb() cannot deal with null mblk being passed
13040 		 * in and first_mp can be set to null in the call
13041 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
13042 		 */
13043 		if (mctl_present && first_mp != NULL) {
13044 			freeb(first_mp);
13045 		}
13046 		CONN_DEC_REF(connp);
13047 		return;
13048 	}
13049 
13050 	/*
13051 	 * if we got here we know the packet is not fragmented and
13052 	 * has no options. The classifier could not find a conn_t and
13053 	 * most likely its an icmp packet so send it through slow path.
13054 	 */
13055 
13056 	goto udpslowpath;
13057 
13058 ipoptions:
13059 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
13060 		goto slow_done;
13061 	}
13062 
13063 	UPDATE_IB_PKT_COUNT(ire);
13064 	ire->ire_last_used_time = lbolt;
13065 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13066 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13067 fragmented:
13068 		/*
13069 		 * "sum" and "reass_hck_flags" are non-zero if the
13070 		 * reassembled packet has a valid hardware computed
13071 		 * checksum information associated with it.
13072 		 */
13073 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
13074 			goto slow_done;
13075 		/*
13076 		 * Make sure that first_mp points back to mp as
13077 		 * the mp we came in with could have changed in
13078 		 * ip_rput_fragment().
13079 		 */
13080 		ASSERT(!mctl_present);
13081 		ipha = (ipha_t *)mp->b_rptr;
13082 		first_mp = mp;
13083 	}
13084 
13085 	/* Now we have a complete datagram, destined for this machine. */
13086 	u1 = IPH_HDR_LENGTH(ipha);
13087 	/* Pull up the UDP header, if necessary. */
13088 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
13089 udppullup:
13090 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
13091 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13092 			freemsg(first_mp);
13093 			goto slow_done;
13094 		}
13095 		ipha = (ipha_t *)mp->b_rptr;
13096 	}
13097 
13098 	/*
13099 	 * Validate the checksum for the reassembled packet; for the
13100 	 * pullup case we calculate the payload checksum in software.
13101 	 */
13102 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
13103 	if (up[3] != 0) {
13104 		boolean_t cksum_err;
13105 
13106 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13107 			IP_STAT(ipst, ip_in_sw_cksum);
13108 
13109 		IP_CKSUM_RECV_REASS(reass_hck_flags,
13110 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
13111 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13112 		    iphs[9] + up[2], sum, cksum_err);
13113 
13114 		if (cksum_err) {
13115 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13116 
13117 			if (reass_hck_flags & HCK_FULLCKSUM)
13118 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13119 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13120 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13121 			else
13122 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13123 
13124 			freemsg(first_mp);
13125 			goto slow_done;
13126 		}
13127 	}
13128 udpslowpath:
13129 
13130 	/* Clear hardware checksum flag to be safe */
13131 	DB_CKSUMFLAGS(mp) = 0;
13132 
13133 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13134 	    (ire->ire_type == IRE_BROADCAST),
13135 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13136 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13137 
13138 slow_done:
13139 	IP_STAT(ipst, ip_udp_slow_path);
13140 	return;
13141 
13142 #undef  iphs
13143 #undef  rptr
13144 }
13145 
13146 /* ARGSUSED */
13147 static mblk_t *
13148 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13149     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13150     ill_rx_ring_t *ill_ring)
13151 {
13152 	conn_t		*connp;
13153 	uint32_t	sum;
13154 	uint32_t	u1;
13155 	uint16_t	*up;
13156 	int		offset;
13157 	ssize_t		len;
13158 	mblk_t		*mp1;
13159 	boolean_t	syn_present = B_FALSE;
13160 	tcph_t		*tcph;
13161 	uint_t		ip_hdr_len;
13162 	ill_t		*ill = (ill_t *)q->q_ptr;
13163 	zoneid_t	zoneid = ire->ire_zoneid;
13164 	boolean_t	cksum_err;
13165 	uint16_t	hck_flags = 0;
13166 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13167 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13168 
13169 #define	rptr	((uchar_t *)ipha)
13170 
13171 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13172 	ASSERT(ill != NULL);
13173 
13174 	/*
13175 	 * FAST PATH for tcp packets
13176 	 */
13177 
13178 	/* u1 is # words of IP options */
13179 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13180 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13181 
13182 	/* IP options present */
13183 	if (u1) {
13184 		goto ipoptions;
13185 	} else {
13186 		/* Check the IP header checksum.  */
13187 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13188 			/* Clear the IP header h/w cksum flag */
13189 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13190 		} else {
13191 #define	uph	((uint16_t *)ipha)
13192 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13193 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13194 #undef	uph
13195 			/* finish doing IP checksum */
13196 			sum = (sum & 0xFFFF) + (sum >> 16);
13197 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13198 			/*
13199 			 * Don't verify header checksum if this packet
13200 			 * is coming back from AH/ESP as we already did it.
13201 			 */
13202 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13203 				BUMP_MIB(ill->ill_ip_mib,
13204 				    ipIfStatsInCksumErrs);
13205 				goto error;
13206 			}
13207 		}
13208 	}
13209 
13210 	if (!mctl_present) {
13211 		UPDATE_IB_PKT_COUNT(ire);
13212 		ire->ire_last_used_time = lbolt;
13213 	}
13214 
13215 	/* packet part of fragmented IP packet? */
13216 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13217 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13218 		goto fragmented;
13219 	}
13220 
13221 	/* u1 = IP header length (20 bytes) */
13222 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13223 
13224 	/* does packet contain IP+TCP headers? */
13225 	len = mp->b_wptr - rptr;
13226 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13227 		IP_STAT(ipst, ip_tcppullup);
13228 		goto tcppullup;
13229 	}
13230 
13231 	/* TCP options present? */
13232 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13233 
13234 	/*
13235 	 * If options need to be pulled up, then goto tcpoptions.
13236 	 * otherwise we are still in the fast path
13237 	 */
13238 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13239 		IP_STAT(ipst, ip_tcpoptions);
13240 		goto tcpoptions;
13241 	}
13242 
13243 	/* multiple mblks of tcp data? */
13244 	if ((mp1 = mp->b_cont) != NULL) {
13245 		/* more then two? */
13246 		if (mp1->b_cont != NULL) {
13247 			IP_STAT(ipst, ip_multipkttcp);
13248 			goto multipkttcp;
13249 		}
13250 		len += mp1->b_wptr - mp1->b_rptr;
13251 	}
13252 
13253 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13254 
13255 	/* part of pseudo checksum */
13256 
13257 	/* TCP datagram length */
13258 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13259 
13260 #define	iphs    ((uint16_t *)ipha)
13261 
13262 #ifdef	_BIG_ENDIAN
13263 	u1 += IPPROTO_TCP;
13264 #else
13265 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13266 #endif
13267 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13268 
13269 	/*
13270 	 * Revert to software checksum calculation if the interface
13271 	 * isn't capable of checksum offload or if IPsec is present.
13272 	 */
13273 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13274 		hck_flags = DB_CKSUMFLAGS(mp);
13275 
13276 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13277 		IP_STAT(ipst, ip_in_sw_cksum);
13278 
13279 	IP_CKSUM_RECV(hck_flags, u1,
13280 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13281 	    (int32_t)((uchar_t *)up - rptr),
13282 	    mp, mp1, cksum_err);
13283 
13284 	if (cksum_err) {
13285 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13286 
13287 		if (hck_flags & HCK_FULLCKSUM)
13288 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13289 		else if (hck_flags & HCK_PARTIALCKSUM)
13290 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13291 		else
13292 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13293 
13294 		goto error;
13295 	}
13296 
13297 try_again:
13298 
13299 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13300 		    zoneid, ipst)) == NULL) {
13301 		/* Send the TH_RST */
13302 		goto no_conn;
13303 	}
13304 
13305 	/*
13306 	 * TCP FAST PATH for AF_INET socket.
13307 	 *
13308 	 * TCP fast path to avoid extra work. An AF_INET socket type
13309 	 * does not have facility to receive extra information via
13310 	 * ip_process or ip_add_info. Also, when the connection was
13311 	 * established, we made a check if this connection is impacted
13312 	 * by any global IPSec policy or per connection policy (a
13313 	 * policy that comes in effect later will not apply to this
13314 	 * connection). Since all this can be determined at the
13315 	 * connection establishment time, a quick check of flags
13316 	 * can avoid extra work.
13317 	 */
13318 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13319 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13320 		ASSERT(first_mp == mp);
13321 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13322 		SET_SQUEUE(mp, tcp_rput_data, connp);
13323 		return (mp);
13324 	}
13325 
13326 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13327 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13328 		if (IPCL_IS_TCP(connp)) {
13329 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13330 			DB_CKSUMSTART(mp) =
13331 			    (intptr_t)ip_squeue_get(ill_ring);
13332 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13333 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13334 				BUMP_MIB(ill->ill_ip_mib,
13335 				    ipIfStatsHCInDelivers);
13336 				SET_SQUEUE(mp, connp->conn_recv, connp);
13337 				return (mp);
13338 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13339 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13340 				BUMP_MIB(ill->ill_ip_mib,
13341 				    ipIfStatsHCInDelivers);
13342 				ip_squeue_enter_unbound++;
13343 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13344 				    connp);
13345 				return (mp);
13346 			}
13347 			syn_present = B_TRUE;
13348 		}
13349 
13350 	}
13351 
13352 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13353 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13354 
13355 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13356 		/* No need to send this packet to TCP */
13357 		if ((flags & TH_RST) || (flags & TH_URG)) {
13358 			CONN_DEC_REF(connp);
13359 			freemsg(first_mp);
13360 			return (NULL);
13361 		}
13362 		if (flags & TH_ACK) {
13363 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13364 			    ipst->ips_netstack->netstack_tcp);
13365 			CONN_DEC_REF(connp);
13366 			return (NULL);
13367 		}
13368 
13369 		CONN_DEC_REF(connp);
13370 		freemsg(first_mp);
13371 		return (NULL);
13372 	}
13373 
13374 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13375 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13376 		    ipha, NULL, mctl_present);
13377 		if (first_mp == NULL) {
13378 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13379 			CONN_DEC_REF(connp);
13380 			return (NULL);
13381 		}
13382 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13383 			ASSERT(syn_present);
13384 			if (mctl_present) {
13385 				ASSERT(first_mp != mp);
13386 				first_mp->b_datap->db_struioflag |=
13387 				    STRUIO_POLICY;
13388 			} else {
13389 				ASSERT(first_mp == mp);
13390 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13391 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13392 			}
13393 		} else {
13394 			/*
13395 			 * Discard first_mp early since we're dealing with a
13396 			 * fully-connected conn_t and tcp doesn't do policy in
13397 			 * this case.
13398 			 */
13399 			if (mctl_present) {
13400 				freeb(first_mp);
13401 				mctl_present = B_FALSE;
13402 			}
13403 			first_mp = mp;
13404 		}
13405 	}
13406 
13407 	/* Initiate IPPF processing for fastpath */
13408 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13409 		uint32_t	ill_index;
13410 
13411 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13412 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13413 		if (mp == NULL) {
13414 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13415 			    "deferred/dropped during IPPF processing\n"));
13416 			CONN_DEC_REF(connp);
13417 			if (mctl_present)
13418 				freeb(first_mp);
13419 			return (NULL);
13420 		} else if (mctl_present) {
13421 			/*
13422 			 * ip_process might return a new mp.
13423 			 */
13424 			ASSERT(first_mp != mp);
13425 			first_mp->b_cont = mp;
13426 		} else {
13427 			first_mp = mp;
13428 		}
13429 
13430 	}
13431 
13432 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13433 		/*
13434 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13435 		 * make sure IPF_RECVIF is passed to ip_add_info.
13436 		 */
13437 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13438 		    IPCL_ZONEID(connp), ipst);
13439 		if (mp == NULL) {
13440 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13441 			CONN_DEC_REF(connp);
13442 			if (mctl_present)
13443 				freeb(first_mp);
13444 			return (NULL);
13445 		} else if (mctl_present) {
13446 			/*
13447 			 * ip_add_info might return a new mp.
13448 			 */
13449 			ASSERT(first_mp != mp);
13450 			first_mp->b_cont = mp;
13451 		} else {
13452 			first_mp = mp;
13453 		}
13454 	}
13455 
13456 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13457 	if (IPCL_IS_TCP(connp)) {
13458 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13459 		return (first_mp);
13460 	} else {
13461 		putnext(connp->conn_rq, first_mp);
13462 		CONN_DEC_REF(connp);
13463 		return (NULL);
13464 	}
13465 
13466 no_conn:
13467 	/* Initiate IPPf processing, if needed. */
13468 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13469 		uint32_t ill_index;
13470 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13471 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13472 		if (first_mp == NULL) {
13473 			return (NULL);
13474 		}
13475 	}
13476 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13477 
13478 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13479 	    ipst->ips_netstack->netstack_tcp);
13480 	return (NULL);
13481 ipoptions:
13482 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13483 		goto slow_done;
13484 	}
13485 
13486 	UPDATE_IB_PKT_COUNT(ire);
13487 	ire->ire_last_used_time = lbolt;
13488 
13489 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13490 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13491 fragmented:
13492 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13493 			if (mctl_present)
13494 				freeb(first_mp);
13495 			goto slow_done;
13496 		}
13497 		/*
13498 		 * Make sure that first_mp points back to mp as
13499 		 * the mp we came in with could have changed in
13500 		 * ip_rput_fragment().
13501 		 */
13502 		ASSERT(!mctl_present);
13503 		ipha = (ipha_t *)mp->b_rptr;
13504 		first_mp = mp;
13505 	}
13506 
13507 	/* Now we have a complete datagram, destined for this machine. */
13508 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13509 
13510 	len = mp->b_wptr - mp->b_rptr;
13511 	/* Pull up a minimal TCP header, if necessary. */
13512 	if (len < (u1 + 20)) {
13513 tcppullup:
13514 		if (!pullupmsg(mp, u1 + 20)) {
13515 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13516 			goto error;
13517 		}
13518 		ipha = (ipha_t *)mp->b_rptr;
13519 		len = mp->b_wptr - mp->b_rptr;
13520 	}
13521 
13522 	/*
13523 	 * Extract the offset field from the TCP header.  As usual, we
13524 	 * try to help the compiler more than the reader.
13525 	 */
13526 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13527 	if (offset != 5) {
13528 tcpoptions:
13529 		if (offset < 5) {
13530 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13531 			goto error;
13532 		}
13533 		/*
13534 		 * There must be TCP options.
13535 		 * Make sure we can grab them.
13536 		 */
13537 		offset <<= 2;
13538 		offset += u1;
13539 		if (len < offset) {
13540 			if (!pullupmsg(mp, offset)) {
13541 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13542 				goto error;
13543 			}
13544 			ipha = (ipha_t *)mp->b_rptr;
13545 			len = mp->b_wptr - rptr;
13546 		}
13547 	}
13548 
13549 	/* Get the total packet length in len, including headers. */
13550 	if (mp->b_cont) {
13551 multipkttcp:
13552 		len = msgdsize(mp);
13553 	}
13554 
13555 	/*
13556 	 * Check the TCP checksum by pulling together the pseudo-
13557 	 * header checksum, and passing it to ip_csum to be added in
13558 	 * with the TCP datagram.
13559 	 *
13560 	 * Since we are not using the hwcksum if available we must
13561 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13562 	 * If either of these fails along the way the mblk is freed.
13563 	 * If this logic ever changes and mblk is reused to say send
13564 	 * ICMP's back, then this flag may need to be cleared in
13565 	 * other places as well.
13566 	 */
13567 	DB_CKSUMFLAGS(mp) = 0;
13568 
13569 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13570 
13571 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13572 #ifdef	_BIG_ENDIAN
13573 	u1 += IPPROTO_TCP;
13574 #else
13575 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13576 #endif
13577 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13578 	/*
13579 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13580 	 */
13581 	IP_STAT(ipst, ip_in_sw_cksum);
13582 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13583 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13584 		goto error;
13585 	}
13586 
13587 	IP_STAT(ipst, ip_tcp_slow_path);
13588 	goto try_again;
13589 #undef  iphs
13590 #undef  rptr
13591 
13592 error:
13593 	freemsg(first_mp);
13594 slow_done:
13595 	return (NULL);
13596 }
13597 
13598 /* ARGSUSED */
13599 static void
13600 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13601     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13602 {
13603 	conn_t		*connp;
13604 	uint32_t	sum;
13605 	uint32_t	u1;
13606 	ssize_t		len;
13607 	sctp_hdr_t	*sctph;
13608 	zoneid_t	zoneid = ire->ire_zoneid;
13609 	uint32_t	pktsum;
13610 	uint32_t	calcsum;
13611 	uint32_t	ports;
13612 	in6_addr_t	map_src, map_dst;
13613 	ill_t		*ill = (ill_t *)q->q_ptr;
13614 	ip_stack_t	*ipst;
13615 	sctp_stack_t	*sctps;
13616 
13617 	ASSERT(recv_ill != NULL);
13618 	ipst = recv_ill->ill_ipst;
13619 	sctps = ipst->ips_netstack->netstack_sctp;
13620 
13621 #define	rptr	((uchar_t *)ipha)
13622 
13623 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13624 	ASSERT(ill != NULL);
13625 
13626 	/* u1 is # words of IP options */
13627 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13628 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13629 
13630 	/* IP options present */
13631 	if (u1 > 0) {
13632 		goto ipoptions;
13633 	} else {
13634 		/* Check the IP header checksum.  */
13635 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13636 #define	uph	((uint16_t *)ipha)
13637 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13638 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13639 #undef	uph
13640 			/* finish doing IP checksum */
13641 			sum = (sum & 0xFFFF) + (sum >> 16);
13642 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13643 			/*
13644 			 * Don't verify header checksum if this packet
13645 			 * is coming back from AH/ESP as we already did it.
13646 			 */
13647 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13648 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13649 				goto error;
13650 			}
13651 		}
13652 		/*
13653 		 * Since there is no SCTP h/w cksum support yet, just
13654 		 * clear the flag.
13655 		 */
13656 		DB_CKSUMFLAGS(mp) = 0;
13657 	}
13658 
13659 	/*
13660 	 * Don't verify header checksum if this packet is coming
13661 	 * back from AH/ESP as we already did it.
13662 	 */
13663 	if (!mctl_present) {
13664 		UPDATE_IB_PKT_COUNT(ire);
13665 		ire->ire_last_used_time = lbolt;
13666 	}
13667 
13668 	/* packet part of fragmented IP packet? */
13669 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13670 	if (u1 & (IPH_MF | IPH_OFFSET))
13671 		goto fragmented;
13672 
13673 	/* u1 = IP header length (20 bytes) */
13674 	u1 = IP_SIMPLE_HDR_LENGTH;
13675 
13676 find_sctp_client:
13677 	/* Pullup if we don't have the sctp common header. */
13678 	len = MBLKL(mp);
13679 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13680 		if (mp->b_cont == NULL ||
13681 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13682 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13683 			goto error;
13684 		}
13685 		ipha = (ipha_t *)mp->b_rptr;
13686 		len = MBLKL(mp);
13687 	}
13688 
13689 	sctph = (sctp_hdr_t *)(rptr + u1);
13690 #ifdef	DEBUG
13691 	if (!skip_sctp_cksum) {
13692 #endif
13693 		pktsum = sctph->sh_chksum;
13694 		sctph->sh_chksum = 0;
13695 		calcsum = sctp_cksum(mp, u1);
13696 		if (calcsum != pktsum) {
13697 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13698 			goto error;
13699 		}
13700 		sctph->sh_chksum = pktsum;
13701 #ifdef	DEBUG	/* skip_sctp_cksum */
13702 	}
13703 #endif
13704 	/* get the ports */
13705 	ports = *(uint32_t *)&sctph->sh_sport;
13706 
13707 	IRE_REFRELE(ire);
13708 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13709 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13710 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13711 	    sctps)) == NULL) {
13712 		/* Check for raw socket or OOTB handling */
13713 		goto no_conn;
13714 	}
13715 
13716 	/* Found a client; up it goes */
13717 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13718 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13719 	return;
13720 
13721 no_conn:
13722 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13723 	    ports, mctl_present, flags, B_TRUE, zoneid);
13724 	return;
13725 
13726 ipoptions:
13727 	DB_CKSUMFLAGS(mp) = 0;
13728 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13729 		goto slow_done;
13730 
13731 	UPDATE_IB_PKT_COUNT(ire);
13732 	ire->ire_last_used_time = lbolt;
13733 
13734 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13735 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13736 fragmented:
13737 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13738 			goto slow_done;
13739 		/*
13740 		 * Make sure that first_mp points back to mp as
13741 		 * the mp we came in with could have changed in
13742 		 * ip_rput_fragment().
13743 		 */
13744 		ASSERT(!mctl_present);
13745 		ipha = (ipha_t *)mp->b_rptr;
13746 		first_mp = mp;
13747 	}
13748 
13749 	/* Now we have a complete datagram, destined for this machine. */
13750 	u1 = IPH_HDR_LENGTH(ipha);
13751 	goto find_sctp_client;
13752 #undef  iphs
13753 #undef  rptr
13754 
13755 error:
13756 	freemsg(first_mp);
13757 slow_done:
13758 	IRE_REFRELE(ire);
13759 }
13760 
13761 #define	VER_BITS	0xF0
13762 #define	VERSION_6	0x60
13763 
13764 static boolean_t
13765 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13766     ipaddr_t *dstp, ip_stack_t *ipst)
13767 {
13768 	uint_t	opt_len;
13769 	ipha_t *ipha;
13770 	ssize_t len;
13771 	uint_t	pkt_len;
13772 
13773 	ASSERT(ill != NULL);
13774 	IP_STAT(ipst, ip_ipoptions);
13775 	ipha = *iphapp;
13776 
13777 #define	rptr    ((uchar_t *)ipha)
13778 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13779 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13780 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13781 		freemsg(mp);
13782 		return (B_FALSE);
13783 	}
13784 
13785 	/* multiple mblk or too short */
13786 	pkt_len = ntohs(ipha->ipha_length);
13787 
13788 	/* Get the number of words of IP options in the IP header. */
13789 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13790 	if (opt_len) {
13791 		/* IP Options present!  Validate and process. */
13792 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13793 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13794 			goto done;
13795 		}
13796 		/*
13797 		 * Recompute complete header length and make sure we
13798 		 * have access to all of it.
13799 		 */
13800 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13801 		if (len > (mp->b_wptr - rptr)) {
13802 			if (len > pkt_len) {
13803 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13804 				goto done;
13805 			}
13806 			if (!pullupmsg(mp, len)) {
13807 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13808 				goto done;
13809 			}
13810 			ipha = (ipha_t *)mp->b_rptr;
13811 		}
13812 		/*
13813 		 * Go off to ip_rput_options which returns the next hop
13814 		 * destination address, which may have been affected
13815 		 * by source routing.
13816 		 */
13817 		IP_STAT(ipst, ip_opt);
13818 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13819 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13820 			return (B_FALSE);
13821 		}
13822 	}
13823 	*iphapp = ipha;
13824 	return (B_TRUE);
13825 done:
13826 	/* clear b_prev - used by ip_mroute_decap */
13827 	mp->b_prev = NULL;
13828 	freemsg(mp);
13829 	return (B_FALSE);
13830 #undef  rptr
13831 }
13832 
13833 /*
13834  * Deal with the fact that there is no ire for the destination.
13835  * The incoming ill (in_ill) is passed in to ip_newroute only
13836  * in the case of packets coming from mobile ip forward tunnel.
13837  * It must be null otherwise.
13838  */
13839 static ire_t *
13840 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13841     ipaddr_t dst)
13842 {
13843 	ipha_t	*ipha;
13844 	ill_t	*ill;
13845 	ire_t	*ire;
13846 	boolean_t	check_multirt = B_FALSE;
13847 	ip_stack_t *ipst;
13848 
13849 	ipha = (ipha_t *)mp->b_rptr;
13850 	ill = (ill_t *)q->q_ptr;
13851 
13852 	ASSERT(ill != NULL);
13853 	ipst = ill->ill_ipst;
13854 
13855 	/*
13856 	 * No IRE for this destination, so it can't be for us.
13857 	 * Unless we are forwarding, drop the packet.
13858 	 * We have to let source routed packets through
13859 	 * since we don't yet know if they are 'ping -l'
13860 	 * packets i.e. if they will go out over the
13861 	 * same interface as they came in on.
13862 	 */
13863 	if (ll_multicast) {
13864 		freemsg(mp);
13865 		return (NULL);
13866 	}
13867 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13868 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13869 		freemsg(mp);
13870 		return (NULL);
13871 	}
13872 
13873 	/*
13874 	 * Mark this packet as having originated externally.
13875 	 *
13876 	 * For non-forwarding code path, ire_send later double
13877 	 * checks this interface to see if it is still exists
13878 	 * post-ARP resolution.
13879 	 *
13880 	 * Also, IPQOS uses this to differentiate between
13881 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13882 	 * QOS packet processing in ip_wput_attach_llhdr().
13883 	 * The QoS module can mark the b_band for a fastpath message
13884 	 * or the dl_priority field in a unitdata_req header for
13885 	 * CoS marking. This info can only be found in
13886 	 * ip_wput_attach_llhdr().
13887 	 */
13888 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13889 	/*
13890 	 * Clear the indication that this may have a hardware checksum
13891 	 * as we are not using it
13892 	 */
13893 	DB_CKSUMFLAGS(mp) = 0;
13894 
13895 	if (in_ill != NULL) {
13896 		/*
13897 		 * Now hand the packet to ip_newroute.
13898 		 */
13899 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13900 		return (NULL);
13901 	}
13902 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13903 	    MBLK_GETLABEL(mp), ipst);
13904 
13905 	if (ire == NULL && check_multirt) {
13906 		/* Let ip_newroute handle CGTP  */
13907 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13908 		return (NULL);
13909 	}
13910 
13911 	if (ire != NULL)
13912 		return (ire);
13913 
13914 	mp->b_prev = mp->b_next = 0;
13915 	/* send icmp unreachable */
13916 	q = WR(q);
13917 	/* Sent by forwarding path, and router is global zone */
13918 	if (ip_source_routed(ipha, ipst)) {
13919 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13920 		    GLOBAL_ZONEID, ipst);
13921 	} else {
13922 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13923 		    ipst);
13924 	}
13925 
13926 	return (NULL);
13927 
13928 }
13929 
13930 /*
13931  * check ip header length and align it.
13932  */
13933 static boolean_t
13934 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13935 {
13936 	ssize_t len;
13937 	ill_t *ill;
13938 	ipha_t	*ipha;
13939 
13940 	len = MBLKL(mp);
13941 
13942 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13943 		ill = (ill_t *)q->q_ptr;
13944 
13945 		if (!OK_32PTR(mp->b_rptr))
13946 			IP_STAT(ipst, ip_notaligned1);
13947 		else
13948 			IP_STAT(ipst, ip_notaligned2);
13949 		/* Guard against bogus device drivers */
13950 		if (len < 0) {
13951 			/* clear b_prev - used by ip_mroute_decap */
13952 			mp->b_prev = NULL;
13953 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13954 			freemsg(mp);
13955 			return (B_FALSE);
13956 		}
13957 
13958 		if (ip_rput_pullups++ == 0) {
13959 			ipha = (ipha_t *)mp->b_rptr;
13960 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13961 			    "ip_check_and_align_header: %s forced us to "
13962 			    " pullup pkt, hdr len %ld, hdr addr %p",
13963 			    ill->ill_name, len, ipha);
13964 		}
13965 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13966 			/* clear b_prev - used by ip_mroute_decap */
13967 			mp->b_prev = NULL;
13968 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13969 			freemsg(mp);
13970 			return (B_FALSE);
13971 		}
13972 	}
13973 	return (B_TRUE);
13974 }
13975 
13976 ire_t *
13977 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13978 {
13979 	ire_t		*new_ire;
13980 	ill_t		*ire_ill;
13981 	uint_t		ifindex;
13982 	ip_stack_t	*ipst = ill->ill_ipst;
13983 	boolean_t	strict_check = B_FALSE;
13984 
13985 	/*
13986 	 * This packet came in on an interface other than the one associated
13987 	 * with the first ire we found for the destination address. We do
13988 	 * another ire lookup here, using the ingress ill, to see if the
13989 	 * interface is in an interface group.
13990 	 * As long as the ills belong to the same group, we don't consider
13991 	 * them to be arriving on the wrong interface. Thus, if the switch
13992 	 * is doing inbound load spreading, we won't drop packets when the
13993 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13994 	 * for 'usesrc groups' where the destination address may belong to
13995 	 * another interface to allow multipathing to happen.
13996 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13997 	 * where the local address may not be unique. In this case we were
13998 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13999 	 * actually returned. The new lookup, which is more specific, should
14000 	 * only find the IRE_LOCAL associated with the ingress ill if one
14001 	 * exists.
14002 	 */
14003 
14004 	if (ire->ire_ipversion == IPV4_VERSION) {
14005 		if (ipst->ips_ip_strict_dst_multihoming)
14006 			strict_check = B_TRUE;
14007 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
14008 		    ill->ill_ipif, ALL_ZONES, NULL,
14009 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14010 	} else {
14011 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
14012 		if (ipst->ips_ipv6_strict_dst_multihoming)
14013 			strict_check = B_TRUE;
14014 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
14015 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
14016 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14017 	}
14018 	/*
14019 	 * If the same ire that was returned in ip_input() is found then this
14020 	 * is an indication that interface groups are in use. The packet
14021 	 * arrived on a different ill in the group than the one associated with
14022 	 * the destination address.  If a different ire was found then the same
14023 	 * IP address must be hosted on multiple ills. This is possible with
14024 	 * unnumbered point2point interfaces. We switch to use this new ire in
14025 	 * order to have accurate interface statistics.
14026 	 */
14027 	if (new_ire != NULL) {
14028 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
14029 			ire_refrele(ire);
14030 			ire = new_ire;
14031 		} else {
14032 			ire_refrele(new_ire);
14033 		}
14034 		return (ire);
14035 	} else if ((ire->ire_rfq == NULL) &&
14036 		    (ire->ire_ipversion == IPV4_VERSION)) {
14037 		/*
14038 		 * The best match could have been the original ire which
14039 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
14040 		 * the strict multihoming checks are irrelevant as we consider
14041 		 * local addresses hosted on lo0 to be interface agnostic. We
14042 		 * only expect a null ire_rfq on IREs which are associated with
14043 		 * lo0 hence we can return now.
14044 		 */
14045 		return (ire);
14046 	}
14047 
14048 	/*
14049 	 * Chase pointers once and store locally.
14050 	 */
14051 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
14052 	    (ill_t *)(ire->ire_rfq->q_ptr);
14053 	ifindex = ill->ill_usesrc_ifindex;
14054 
14055 	/*
14056 	 * Check if it's a legal address on the 'usesrc' interface.
14057 	 */
14058 	if ((ifindex != 0) && (ire_ill != NULL) &&
14059 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
14060 		return (ire);
14061 	}
14062 
14063 	/*
14064 	 * If the ip*_strict_dst_multihoming switch is on then we can
14065 	 * only accept this packet if the interface is marked as routing.
14066 	 */
14067 	if (!(strict_check))
14068 		return (ire);
14069 
14070 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
14071 	    ILLF_ROUTER) != 0) {
14072 		return (ire);
14073 	}
14074 
14075 	ire_refrele(ire);
14076 	return (NULL);
14077 }
14078 
14079 ire_t *
14080 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
14081 {
14082 	ipha_t	*ipha;
14083 	ipaddr_t ip_dst, ip_src;
14084 	ire_t	*src_ire = NULL;
14085 	ill_t	*stq_ill;
14086 	uint_t	hlen;
14087 	uint_t	pkt_len;
14088 	uint32_t sum;
14089 	queue_t	*dev_q;
14090 	boolean_t check_multirt = B_FALSE;
14091 	ip_stack_t *ipst = ill->ill_ipst;
14092 
14093 	ipha = (ipha_t *)mp->b_rptr;
14094 
14095 	/*
14096 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14097 	 * The loopback address check for both src and dst has already
14098 	 * been checked in ip_input
14099 	 */
14100 	ip_dst = ntohl(dst);
14101 	ip_src = ntohl(ipha->ipha_src);
14102 
14103 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
14104 	    IN_CLASSD(ip_src)) {
14105 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14106 		goto drop;
14107 	}
14108 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14109 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14110 
14111 	if (src_ire != NULL) {
14112 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14113 		goto drop;
14114 	}
14115 
14116 
14117 	/* No ire cache of nexthop. So first create one  */
14118 	if (ire == NULL) {
14119 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
14120 		/*
14121 		 * We only come to ip_fast_forward if ip_cgtp_filter is
14122 		 * is not set. So upon return from ire_forward
14123 		 * check_multirt should remain as false.
14124 		 */
14125 		ASSERT(!check_multirt);
14126 		if (ire == NULL) {
14127 			/* An attempt was made to forward the packet */
14128 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14129 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14130 			mp->b_prev = mp->b_next = 0;
14131 			/* send icmp unreachable */
14132 			/* Sent by forwarding path, and router is global zone */
14133 			if (ip_source_routed(ipha, ipst)) {
14134 				icmp_unreachable(ill->ill_wq, mp,
14135 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
14136 				    ipst);
14137 			} else {
14138 				icmp_unreachable(ill->ill_wq, mp,
14139 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
14140 				    ipst);
14141 			}
14142 			return (ire);
14143 		}
14144 	}
14145 
14146 	/*
14147 	 * Forwarding fastpath exception case:
14148 	 * If either of the follwoing case is true, we take
14149 	 * the slowpath
14150 	 *	o forwarding is not enabled
14151 	 *	o incoming and outgoing interface are the same, or the same
14152 	 *	  IPMP group
14153 	 *	o corresponding ire is in incomplete state
14154 	 *	o packet needs fragmentation
14155 	 *
14156 	 * The codeflow from here on is thus:
14157 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14158 	 */
14159 	pkt_len = ntohs(ipha->ipha_length);
14160 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14161 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14162 	    !(ill->ill_flags & ILLF_ROUTER) ||
14163 	    (ill == stq_ill) ||
14164 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14165 	    (ire->ire_nce == NULL) ||
14166 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14167 	    (pkt_len > ire->ire_max_frag) ||
14168 	    ipha->ipha_ttl <= 1) {
14169 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14170 		    ipha, ill, B_FALSE);
14171 		return (ire);
14172 	}
14173 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14174 
14175 	DTRACE_PROBE4(ip4__forwarding__start,
14176 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14177 
14178 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14179 	    ipst->ips_ipv4firewall_forwarding,
14180 	    ill, stq_ill, ipha, mp, mp, ipst);
14181 
14182 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14183 
14184 	if (mp == NULL)
14185 		goto drop;
14186 
14187 	mp->b_datap->db_struioun.cksum.flags = 0;
14188 	/* Adjust the checksum to reflect the ttl decrement. */
14189 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14190 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14191 	ipha->ipha_ttl--;
14192 
14193 	dev_q = ire->ire_stq->q_next;
14194 	if ((dev_q->q_next != NULL ||
14195 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14196 		goto indiscard;
14197 	}
14198 
14199 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14200 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14201 
14202 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14203 		mblk_t *mpip = mp;
14204 
14205 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14206 		if (mp != NULL) {
14207 			DTRACE_PROBE4(ip4__physical__out__start,
14208 			    ill_t *, NULL, ill_t *, stq_ill,
14209 			    ipha_t *, ipha, mblk_t *, mp);
14210 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14211 			    ipst->ips_ipv4firewall_physical_out,
14212 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14213 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14214 			    mp);
14215 			if (mp == NULL)
14216 				goto drop;
14217 
14218 			UPDATE_IB_PKT_COUNT(ire);
14219 			ire->ire_last_used_time = lbolt;
14220 			BUMP_MIB(stq_ill->ill_ip_mib,
14221 			    ipIfStatsHCOutForwDatagrams);
14222 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14223 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14224 			    pkt_len);
14225 			putnext(ire->ire_stq, mp);
14226 			return (ire);
14227 		}
14228 	}
14229 
14230 indiscard:
14231 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14232 drop:
14233 	if (mp != NULL)
14234 		freemsg(mp);
14235 	if (src_ire != NULL)
14236 		ire_refrele(src_ire);
14237 	return (ire);
14238 
14239 }
14240 
14241 /*
14242  * This function is called in the forwarding slowpath, when
14243  * either the ire lacks the link-layer address, or the packet needs
14244  * further processing(eg. fragmentation), before transmission.
14245  */
14246 
14247 static void
14248 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14249     ill_t *ill, boolean_t ll_multicast)
14250 {
14251 	ill_group_t	*ill_group;
14252 	ill_group_t	*ire_group;
14253 	queue_t		*dev_q;
14254 	ire_t		*src_ire;
14255 	ip_stack_t	*ipst = ill->ill_ipst;
14256 
14257 	ASSERT(ire->ire_stq != NULL);
14258 
14259 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14260 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14261 
14262 	if (ll_multicast != 0) {
14263 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14264 		goto drop_pkt;
14265 	}
14266 
14267 	/*
14268 	 * check if ipha_src is a broadcast address. Note that this
14269 	 * check is redundant when we get here from ip_fast_forward()
14270 	 * which has already done this check. However, since we can
14271 	 * also get here from ip_rput_process_broadcast() or, for
14272 	 * for the slow path through ip_fast_forward(), we perform
14273 	 * the check again for code-reusability
14274 	 */
14275 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14276 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14277 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14278 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14279 		if (src_ire != NULL)
14280 			ire_refrele(src_ire);
14281 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14282 		ip2dbg(("ip_rput_process_forward: Received packet with"
14283 		    " bad src/dst address on %s\n", ill->ill_name));
14284 		goto drop_pkt;
14285 	}
14286 
14287 	ill_group = ill->ill_group;
14288 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14289 	/*
14290 	 * Check if we want to forward this one at this time.
14291 	 * We allow source routed packets on a host provided that
14292 	 * they go out the same interface or same interface group
14293 	 * as they came in on.
14294 	 *
14295 	 * XXX To be quicker, we may wish to not chase pointers to
14296 	 * get the ILLF_ROUTER flag and instead store the
14297 	 * forwarding policy in the ire.  An unfortunate
14298 	 * side-effect of that would be requiring an ire flush
14299 	 * whenever the ILLF_ROUTER flag changes.
14300 	 */
14301 	if (((ill->ill_flags &
14302 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14303 	    ILLF_ROUTER) == 0) &&
14304 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14305 	    (ill_group != NULL && ill_group == ire_group)))) {
14306 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14307 		if (ip_source_routed(ipha, ipst)) {
14308 			q = WR(q);
14309 			/*
14310 			 * Clear the indication that this may have
14311 			 * hardware checksum as we are not using it.
14312 			 */
14313 			DB_CKSUMFLAGS(mp) = 0;
14314 			/* Sent by forwarding path, and router is global zone */
14315 			icmp_unreachable(q, mp,
14316 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14317 			return;
14318 		}
14319 		goto drop_pkt;
14320 	}
14321 
14322 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14323 
14324 	/* Packet is being forwarded. Turning off hwcksum flag. */
14325 	DB_CKSUMFLAGS(mp) = 0;
14326 	if (ipst->ips_ip_g_send_redirects) {
14327 		/*
14328 		 * Check whether the incoming interface and outgoing
14329 		 * interface is part of the same group. If so,
14330 		 * send redirects.
14331 		 *
14332 		 * Check the source address to see if it originated
14333 		 * on the same logical subnet it is going back out on.
14334 		 * If so, we should be able to send it a redirect.
14335 		 * Avoid sending a redirect if the destination
14336 		 * is directly connected (i.e., ipha_dst is the same
14337 		 * as ire_gateway_addr or the ire_addr of the
14338 		 * nexthop IRE_CACHE ), or if the packet was source
14339 		 * routed out this interface.
14340 		 */
14341 		ipaddr_t src, nhop;
14342 		mblk_t	*mp1;
14343 		ire_t	*nhop_ire = NULL;
14344 
14345 		/*
14346 		 * Check whether ire_rfq and q are from the same ill
14347 		 * or if they are not same, they at least belong
14348 		 * to the same group. If so, send redirects.
14349 		 */
14350 		if ((ire->ire_rfq == q ||
14351 		    (ill_group != NULL && ill_group == ire_group)) &&
14352 		    !ip_source_routed(ipha, ipst)) {
14353 
14354 			nhop = (ire->ire_gateway_addr != 0 ?
14355 			    ire->ire_gateway_addr : ire->ire_addr);
14356 
14357 			if (ipha->ipha_dst == nhop) {
14358 				/*
14359 				 * We avoid sending a redirect if the
14360 				 * destination is directly connected
14361 				 * because it is possible that multiple
14362 				 * IP subnets may have been configured on
14363 				 * the link, and the source may not
14364 				 * be on the same subnet as ip destination,
14365 				 * even though they are on the same
14366 				 * physical link.
14367 				 */
14368 				goto sendit;
14369 			}
14370 
14371 			src = ipha->ipha_src;
14372 
14373 			/*
14374 			 * We look up the interface ire for the nexthop,
14375 			 * to see if ipha_src is in the same subnet
14376 			 * as the nexthop.
14377 			 *
14378 			 * Note that, if, in the future, IRE_CACHE entries
14379 			 * are obsoleted,  this lookup will not be needed,
14380 			 * as the ire passed to this function will be the
14381 			 * same as the nhop_ire computed below.
14382 			 */
14383 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14384 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14385 			    0, NULL, MATCH_IRE_TYPE, ipst);
14386 
14387 			if (nhop_ire != NULL) {
14388 				if ((src & nhop_ire->ire_mask) ==
14389 				    (nhop & nhop_ire->ire_mask)) {
14390 					/*
14391 					 * The source is directly connected.
14392 					 * Just copy the ip header (which is
14393 					 * in the first mblk)
14394 					 */
14395 					mp1 = copyb(mp);
14396 					if (mp1 != NULL) {
14397 						icmp_send_redirect(WR(q), mp1,
14398 						    nhop, ipst);
14399 					}
14400 				}
14401 				ire_refrele(nhop_ire);
14402 			}
14403 		}
14404 	}
14405 sendit:
14406 	dev_q = ire->ire_stq->q_next;
14407 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14408 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14409 		freemsg(mp);
14410 		return;
14411 	}
14412 
14413 	ip_rput_forward(ire, ipha, mp, ill);
14414 	return;
14415 
14416 drop_pkt:
14417 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14418 	freemsg(mp);
14419 }
14420 
14421 ire_t *
14422 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14423     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14424 {
14425 	queue_t		*q;
14426 	uint16_t	hcksumflags;
14427 	ip_stack_t	*ipst = ill->ill_ipst;
14428 
14429 	q = *qp;
14430 
14431 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14432 
14433 	/*
14434 	 * Clear the indication that this may have hardware
14435 	 * checksum as we are not using it for forwarding.
14436 	 */
14437 	hcksumflags = DB_CKSUMFLAGS(mp);
14438 	DB_CKSUMFLAGS(mp) = 0;
14439 
14440 	/*
14441 	 * Directed broadcast forwarding: if the packet came in over a
14442 	 * different interface then it is routed out over we can forward it.
14443 	 */
14444 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14445 		ire_refrele(ire);
14446 		freemsg(mp);
14447 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14448 		return (NULL);
14449 	}
14450 	/*
14451 	 * For multicast we have set dst to be INADDR_BROADCAST
14452 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14453 	 * only for broadcast packets.
14454 	 */
14455 	if (!CLASSD(ipha->ipha_dst)) {
14456 		ire_t *new_ire;
14457 		ipif_t *ipif;
14458 		/*
14459 		 * For ill groups, as the switch duplicates broadcasts
14460 		 * across all the ports, we need to filter out and
14461 		 * send up only one copy. There is one copy for every
14462 		 * broadcast address on each ill. Thus, we look for a
14463 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14464 		 * later to see whether this ill is eligible to receive
14465 		 * them or not. ill_nominate_bcast_rcv() nominates only
14466 		 * one set of IREs for receiving.
14467 		 */
14468 
14469 		ipif = ipif_get_next_ipif(NULL, ill);
14470 		if (ipif == NULL) {
14471 			ire_refrele(ire);
14472 			freemsg(mp);
14473 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14474 			return (NULL);
14475 		}
14476 		new_ire = ire_ctable_lookup(dst, 0, 0,
14477 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14478 		ipif_refrele(ipif);
14479 
14480 		if (new_ire != NULL) {
14481 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14482 				ire_refrele(ire);
14483 				ire_refrele(new_ire);
14484 				freemsg(mp);
14485 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14486 				return (NULL);
14487 			}
14488 			/*
14489 			 * In the special case of multirouted broadcast
14490 			 * packets, we unconditionally need to "gateway"
14491 			 * them to the appropriate interface here.
14492 			 * In the normal case, this cannot happen, because
14493 			 * there is no broadcast IRE tagged with the
14494 			 * RTF_MULTIRT flag.
14495 			 */
14496 			if (new_ire->ire_flags & RTF_MULTIRT) {
14497 				ire_refrele(new_ire);
14498 				if (ire->ire_rfq != NULL) {
14499 					q = ire->ire_rfq;
14500 					*qp = q;
14501 				}
14502 			} else {
14503 				ire_refrele(ire);
14504 				ire = new_ire;
14505 			}
14506 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14507 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14508 				/*
14509 				 * Free the message if
14510 				 * ip_g_forward_directed_bcast is turned
14511 				 * off for non-local broadcast.
14512 				 */
14513 				ire_refrele(ire);
14514 				freemsg(mp);
14515 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14516 				return (NULL);
14517 			}
14518 		} else {
14519 			/*
14520 			 * This CGTP packet successfully passed the
14521 			 * CGTP filter, but the related CGTP
14522 			 * broadcast IRE has not been found,
14523 			 * meaning that the redundant ipif is
14524 			 * probably down. However, if we discarded
14525 			 * this packet, its duplicate would be
14526 			 * filtered out by the CGTP filter so none
14527 			 * of them would get through. So we keep
14528 			 * going with this one.
14529 			 */
14530 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14531 			if (ire->ire_rfq != NULL) {
14532 				q = ire->ire_rfq;
14533 				*qp = q;
14534 			}
14535 		}
14536 	}
14537 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14538 		/*
14539 		 * Verify that there are not more then one
14540 		 * IRE_BROADCAST with this broadcast address which
14541 		 * has ire_stq set.
14542 		 * TODO: simplify, loop over all IRE's
14543 		 */
14544 		ire_t	*ire1;
14545 		int	num_stq = 0;
14546 		mblk_t	*mp1;
14547 
14548 		/* Find the first one with ire_stq set */
14549 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14550 		for (ire1 = ire; ire1 &&
14551 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14552 		    ire1 = ire1->ire_next)
14553 			;
14554 		if (ire1) {
14555 			ire_refrele(ire);
14556 			ire = ire1;
14557 			IRE_REFHOLD(ire);
14558 		}
14559 
14560 		/* Check if there are additional ones with stq set */
14561 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14562 			if (ire->ire_addr != ire1->ire_addr)
14563 				break;
14564 			if (ire1->ire_stq) {
14565 				num_stq++;
14566 				break;
14567 			}
14568 		}
14569 		rw_exit(&ire->ire_bucket->irb_lock);
14570 		if (num_stq == 1 && ire->ire_stq != NULL) {
14571 			ip1dbg(("ip_rput_process_broadcast: directed "
14572 			    "broadcast to 0x%x\n",
14573 			    ntohl(ire->ire_addr)));
14574 			mp1 = copymsg(mp);
14575 			if (mp1) {
14576 				switch (ipha->ipha_protocol) {
14577 				case IPPROTO_UDP:
14578 					ip_udp_input(q, mp1, ipha, ire, ill);
14579 					break;
14580 				default:
14581 					ip_proto_input(q, mp1, ipha, ire, ill);
14582 					break;
14583 				}
14584 			}
14585 			/*
14586 			 * Adjust ttl to 2 (1+1 - the forward engine
14587 			 * will decrement it by one.
14588 			 */
14589 			if (ip_csum_hdr(ipha)) {
14590 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14591 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14592 				freemsg(mp);
14593 				ire_refrele(ire);
14594 				return (NULL);
14595 			}
14596 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14597 			ipha->ipha_hdr_checksum = 0;
14598 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14599 			ip_rput_process_forward(q, mp, ire, ipha,
14600 			    ill, ll_multicast);
14601 			ire_refrele(ire);
14602 			return (NULL);
14603 		}
14604 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14605 		    ntohl(ire->ire_addr)));
14606 	}
14607 
14608 
14609 	/* Restore any hardware checksum flags */
14610 	DB_CKSUMFLAGS(mp) = hcksumflags;
14611 	return (ire);
14612 }
14613 
14614 /* ARGSUSED */
14615 static boolean_t
14616 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14617     int *ll_multicast, ipaddr_t *dstp)
14618 {
14619 	ip_stack_t	*ipst = ill->ill_ipst;
14620 
14621 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14622 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14623 	    ntohs(ipha->ipha_length));
14624 
14625 	/*
14626 	 * Forward packets only if we have joined the allmulti
14627 	 * group on this interface.
14628 	 */
14629 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14630 		int retval;
14631 
14632 		/*
14633 		 * Clear the indication that this may have hardware
14634 		 * checksum as we are not using it.
14635 		 */
14636 		DB_CKSUMFLAGS(mp) = 0;
14637 		retval = ip_mforward(ill, ipha, mp);
14638 		/* ip_mforward updates mib variables if needed */
14639 		/* clear b_prev - used by ip_mroute_decap */
14640 		mp->b_prev = NULL;
14641 
14642 		switch (retval) {
14643 		case 0:
14644 			/*
14645 			 * pkt is okay and arrived on phyint.
14646 			 *
14647 			 * If we are running as a multicast router
14648 			 * we need to see all IGMP and/or PIM packets.
14649 			 */
14650 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14651 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14652 				goto done;
14653 			}
14654 			break;
14655 		case -1:
14656 			/* pkt is mal-formed, toss it */
14657 			goto drop_pkt;
14658 		case 1:
14659 			/* pkt is okay and arrived on a tunnel */
14660 			/*
14661 			 * If we are running a multicast router
14662 			 *  we need to see all igmp packets.
14663 			 */
14664 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14665 				*dstp = INADDR_BROADCAST;
14666 				*ll_multicast = 1;
14667 				return (B_FALSE);
14668 			}
14669 
14670 			goto drop_pkt;
14671 		}
14672 	}
14673 
14674 	ILM_WALKER_HOLD(ill);
14675 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14676 		/*
14677 		 * This might just be caused by the fact that
14678 		 * multiple IP Multicast addresses map to the same
14679 		 * link layer multicast - no need to increment counter!
14680 		 */
14681 		ILM_WALKER_RELE(ill);
14682 		freemsg(mp);
14683 		return (B_TRUE);
14684 	}
14685 	ILM_WALKER_RELE(ill);
14686 done:
14687 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14688 	/*
14689 	 * This assumes the we deliver to all streams for multicast
14690 	 * and broadcast packets.
14691 	 */
14692 	*dstp = INADDR_BROADCAST;
14693 	*ll_multicast = 1;
14694 	return (B_FALSE);
14695 drop_pkt:
14696 	ip2dbg(("ip_rput: drop pkt\n"));
14697 	freemsg(mp);
14698 	return (B_TRUE);
14699 }
14700 
14701 static boolean_t
14702 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14703     int *ll_multicast, mblk_t **mpp)
14704 {
14705 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14706 	boolean_t must_copy = B_FALSE;
14707 	struct iocblk   *iocp;
14708 	ipha_t		*ipha;
14709 	ip_stack_t	*ipst = ill->ill_ipst;
14710 
14711 #define	rptr    ((uchar_t *)ipha)
14712 
14713 	first_mp = *first_mpp;
14714 	mp = *mpp;
14715 
14716 	ASSERT(first_mp == mp);
14717 
14718 	/*
14719 	 * if db_ref > 1 then copymsg and free original. Packet may be
14720 	 * changed and do not want other entity who has a reference to this
14721 	 * message to trip over the changes. This is a blind change because
14722 	 * trying to catch all places that might change packet is too
14723 	 * difficult (since it may be a module above this one)
14724 	 *
14725 	 * This corresponds to the non-fast path case. We walk down the full
14726 	 * chain in this case, and check the db_ref count of all the dblks,
14727 	 * and do a copymsg if required. It is possible that the db_ref counts
14728 	 * of the data blocks in the mblk chain can be different.
14729 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14730 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14731 	 * 'snoop' is running.
14732 	 */
14733 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14734 		if (mp1->b_datap->db_ref > 1) {
14735 			must_copy = B_TRUE;
14736 			break;
14737 		}
14738 	}
14739 
14740 	if (must_copy) {
14741 		mp1 = copymsg(mp);
14742 		if (mp1 == NULL) {
14743 			for (mp1 = mp; mp1 != NULL;
14744 			    mp1 = mp1->b_cont) {
14745 				mp1->b_next = NULL;
14746 				mp1->b_prev = NULL;
14747 			}
14748 			freemsg(mp);
14749 			if (ill != NULL) {
14750 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14751 			} else {
14752 				BUMP_MIB(&ipst->ips_ip_mib,
14753 				    ipIfStatsInDiscards);
14754 			}
14755 			return (B_TRUE);
14756 		}
14757 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14758 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14759 			/* Copy b_prev - used by ip_mroute_decap */
14760 			to_mp->b_prev = from_mp->b_prev;
14761 			from_mp->b_prev = NULL;
14762 		}
14763 		*first_mpp = first_mp = mp1;
14764 		freemsg(mp);
14765 		mp = mp1;
14766 		*mpp = mp1;
14767 	}
14768 
14769 	ipha = (ipha_t *)mp->b_rptr;
14770 
14771 	/*
14772 	 * previous code has a case for M_DATA.
14773 	 * We want to check how that happens.
14774 	 */
14775 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14776 	switch (first_mp->b_datap->db_type) {
14777 	case M_PROTO:
14778 	case M_PCPROTO:
14779 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14780 		    DL_UNITDATA_IND) {
14781 			/* Go handle anything other than data elsewhere. */
14782 			ip_rput_dlpi(q, mp);
14783 			return (B_TRUE);
14784 		}
14785 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14786 		/* Ditch the DLPI header. */
14787 		mp1 = mp->b_cont;
14788 		ASSERT(first_mp == mp);
14789 		*first_mpp = mp1;
14790 		freeb(mp);
14791 		*mpp = mp1;
14792 		return (B_FALSE);
14793 	case M_IOCACK:
14794 		ip1dbg(("got iocack "));
14795 		iocp = (struct iocblk *)mp->b_rptr;
14796 		switch (iocp->ioc_cmd) {
14797 		case DL_IOC_HDR_INFO:
14798 			ill = (ill_t *)q->q_ptr;
14799 			ill_fastpath_ack(ill, mp);
14800 			return (B_TRUE);
14801 		case SIOCSTUNPARAM:
14802 		case OSIOCSTUNPARAM:
14803 			/* Go through qwriter_ip */
14804 			break;
14805 		case SIOCGTUNPARAM:
14806 		case OSIOCGTUNPARAM:
14807 			ip_rput_other(NULL, q, mp, NULL);
14808 			return (B_TRUE);
14809 		default:
14810 			putnext(q, mp);
14811 			return (B_TRUE);
14812 		}
14813 		/* FALLTHRU */
14814 	case M_ERROR:
14815 	case M_HANGUP:
14816 		/*
14817 		 * Since this is on the ill stream we unconditionally
14818 		 * bump up the refcount
14819 		 */
14820 		ill_refhold(ill);
14821 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14822 		    B_FALSE);
14823 		return (B_TRUE);
14824 	case M_CTL:
14825 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14826 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14827 			IPHADA_M_CTL)) {
14828 			/*
14829 			 * It's an IPsec accelerated packet.
14830 			 * Make sure that the ill from which we received the
14831 			 * packet has enabled IPsec hardware acceleration.
14832 			 */
14833 			if (!(ill->ill_capabilities &
14834 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14835 				/* IPsec kstats: bean counter */
14836 				freemsg(mp);
14837 				return (B_TRUE);
14838 			}
14839 
14840 			/*
14841 			 * Make mp point to the mblk following the M_CTL,
14842 			 * then process according to type of mp.
14843 			 * After this processing, first_mp will point to
14844 			 * the data-attributes and mp to the pkt following
14845 			 * the M_CTL.
14846 			 */
14847 			mp = first_mp->b_cont;
14848 			if (mp == NULL) {
14849 				freemsg(first_mp);
14850 				return (B_TRUE);
14851 			}
14852 			/*
14853 			 * A Hardware Accelerated packet can only be M_DATA
14854 			 * ESP or AH packet.
14855 			 */
14856 			if (mp->b_datap->db_type != M_DATA) {
14857 				/* non-M_DATA IPsec accelerated packet */
14858 				IPSECHW_DEBUG(IPSECHW_PKT,
14859 				    ("non-M_DATA IPsec accelerated pkt\n"));
14860 				freemsg(first_mp);
14861 				return (B_TRUE);
14862 			}
14863 			ipha = (ipha_t *)mp->b_rptr;
14864 			if (ipha->ipha_protocol != IPPROTO_AH &&
14865 			    ipha->ipha_protocol != IPPROTO_ESP) {
14866 				IPSECHW_DEBUG(IPSECHW_PKT,
14867 				    ("non-M_DATA IPsec accelerated pkt\n"));
14868 				freemsg(first_mp);
14869 				return (B_TRUE);
14870 			}
14871 			*mpp = mp;
14872 			return (B_FALSE);
14873 		}
14874 		putnext(q, mp);
14875 		return (B_TRUE);
14876 	case M_FLUSH:
14877 		if (*mp->b_rptr & FLUSHW) {
14878 			*mp->b_rptr &= ~FLUSHR;
14879 			qreply(q, mp);
14880 			return (B_TRUE);
14881 		}
14882 		freemsg(mp);
14883 		return (B_TRUE);
14884 	case M_IOCNAK:
14885 		ip1dbg(("got iocnak "));
14886 		iocp = (struct iocblk *)mp->b_rptr;
14887 		switch (iocp->ioc_cmd) {
14888 		case DL_IOC_HDR_INFO:
14889 		case SIOCSTUNPARAM:
14890 		case OSIOCSTUNPARAM:
14891 			/*
14892 			 * Since this is on the ill stream we unconditionally
14893 			 * bump up the refcount
14894 			 */
14895 			ill_refhold(ill);
14896 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14897 			    CUR_OP, B_FALSE);
14898 			return (B_TRUE);
14899 		case SIOCGTUNPARAM:
14900 		case OSIOCGTUNPARAM:
14901 			ip_rput_other(NULL, q, mp, NULL);
14902 			return (B_TRUE);
14903 		default:
14904 			break;
14905 		}
14906 		/* FALLTHRU */
14907 	default:
14908 		putnext(q, mp);
14909 		return (B_TRUE);
14910 	}
14911 }
14912 
14913 /* Read side put procedure.  Packets coming from the wire arrive here. */
14914 void
14915 ip_rput(queue_t *q, mblk_t *mp)
14916 {
14917 	ill_t	*ill;
14918 	ip_stack_t	*ipst;
14919 
14920 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14921 
14922 	ill = (ill_t *)q->q_ptr;
14923 	ipst = ill->ill_ipst;
14924 
14925 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14926 		union DL_primitives *dl;
14927 
14928 		/*
14929 		 * Things are opening or closing. Only accept DLPI control
14930 		 * messages. In the open case, the ill->ill_ipif has not yet
14931 		 * been created. In the close case, things hanging off the
14932 		 * ill could have been freed already. In either case it
14933 		 * may not be safe to proceed further.
14934 		 */
14935 
14936 		dl = (union DL_primitives *)mp->b_rptr;
14937 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14938 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14939 			/*
14940 			 * Also SIOC[GS]TUN* ioctls can come here.
14941 			 */
14942 			inet_freemsg(mp);
14943 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14944 			    "ip_input_end: q %p (%S)", q, "uninit");
14945 			return;
14946 		}
14947 	}
14948 
14949 	/*
14950 	 * if db_ref > 1 then copymsg and free original. Packet may be
14951 	 * changed and we do not want the other entity who has a reference to
14952 	 * this message to trip over the changes. This is a blind change because
14953 	 * trying to catch all places that might change the packet is too
14954 	 * difficult.
14955 	 *
14956 	 * This corresponds to the fast path case, where we have a chain of
14957 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14958 	 * in the mblk chain. There doesn't seem to be a reason why a device
14959 	 * driver would send up data with varying db_ref counts in the mblk
14960 	 * chain. In any case the Fast path is a private interface, and our
14961 	 * drivers don't do such a thing. Given the above assumption, there is
14962 	 * no need to walk down the entire mblk chain (which could have a
14963 	 * potential performance problem)
14964 	 */
14965 	if (mp->b_datap->db_ref > 1) {
14966 		mblk_t  *mp1;
14967 		boolean_t adjusted = B_FALSE;
14968 		IP_STAT(ipst, ip_db_ref);
14969 
14970 		/*
14971 		 * The IP_RECVSLLA option depends on having the link layer
14972 		 * header. First check that:
14973 		 * a> the underlying device is of type ether, since this
14974 		 * option is currently supported only over ethernet.
14975 		 * b> there is enough room to copy over the link layer header.
14976 		 *
14977 		 * Once the checks are done, adjust rptr so that the link layer
14978 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14979 		 * be returned by some non-ethernet drivers but in this case the
14980 		 * second check will fail.
14981 		 */
14982 		if (ill->ill_type == IFT_ETHER &&
14983 		    (mp->b_rptr - mp->b_datap->db_base) >=
14984 		    sizeof (struct ether_header)) {
14985 			mp->b_rptr -= sizeof (struct ether_header);
14986 			adjusted = B_TRUE;
14987 		}
14988 		mp1 = copymsg(mp);
14989 		if (mp1 == NULL) {
14990 			mp->b_next = NULL;
14991 			/* clear b_prev - used by ip_mroute_decap */
14992 			mp->b_prev = NULL;
14993 			freemsg(mp);
14994 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14995 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14996 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14997 			return;
14998 		}
14999 		if (adjusted) {
15000 			/*
15001 			 * Copy is done. Restore the pointer in the _new_ mblk
15002 			 */
15003 			mp1->b_rptr += sizeof (struct ether_header);
15004 		}
15005 		/* Copy b_prev - used by ip_mroute_decap */
15006 		mp1->b_prev = mp->b_prev;
15007 		mp->b_prev = NULL;
15008 		freemsg(mp);
15009 		mp = mp1;
15010 	}
15011 
15012 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15013 	    "ip_rput_end: q %p (%S)", q, "end");
15014 
15015 	ip_input(ill, NULL, mp, NULL);
15016 }
15017 
15018 /*
15019  * Direct read side procedure capable of dealing with chains. GLDv3 based
15020  * drivers call this function directly with mblk chains while STREAMS
15021  * read side procedure ip_rput() calls this for single packet with ip_ring
15022  * set to NULL to process one packet at a time.
15023  *
15024  * The ill will always be valid if this function is called directly from
15025  * the driver.
15026  *
15027  * If ip_input() is called from GLDv3:
15028  *
15029  *   - This must be a non-VLAN IP stream.
15030  *   - 'mp' is either an untagged or a special priority-tagged packet.
15031  *   - Any VLAN tag that was in the MAC header has been stripped.
15032  *
15033  * If the IP header in packet is not 32-bit aligned, every message in the
15034  * chain will be aligned before further operations. This is required on SPARC
15035  * platform.
15036  */
15037 /* ARGSUSED */
15038 void
15039 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
15040     struct mac_header_info_s *mhip)
15041 {
15042 	ipaddr_t		dst = NULL;
15043 	ipaddr_t		prev_dst;
15044 	ire_t			*ire = NULL;
15045 	ipha_t			*ipha;
15046 	uint_t			pkt_len;
15047 	ssize_t			len;
15048 	uint_t			opt_len;
15049 	int			ll_multicast;
15050 	int			cgtp_flt_pkt;
15051 	queue_t			*q = ill->ill_rq;
15052 	squeue_t		*curr_sqp = NULL;
15053 	mblk_t 			*head = NULL;
15054 	mblk_t			*tail = NULL;
15055 	mblk_t			*first_mp;
15056 	mblk_t 			*mp;
15057 	mblk_t			*dmp;
15058 	int			cnt = 0;
15059 	ip_stack_t		*ipst = ill->ill_ipst;
15060 
15061 	ASSERT(mp_chain != NULL);
15062 	ASSERT(ill != NULL);
15063 
15064 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15065 
15066 #define	rptr	((uchar_t *)ipha)
15067 
15068 	while (mp_chain != NULL) {
15069 		first_mp = mp = mp_chain;
15070 		mp_chain = mp_chain->b_next;
15071 		mp->b_next = NULL;
15072 		ll_multicast = 0;
15073 
15074 		/*
15075 		 * We do ire caching from one iteration to
15076 		 * another. In the event the packet chain contains
15077 		 * all packets from the same dst, this caching saves
15078 		 * an ire_cache_lookup for each of the succeeding
15079 		 * packets in a packet chain.
15080 		 */
15081 		prev_dst = dst;
15082 
15083 		/*
15084 		 * Check and align the IP header.
15085 		 */
15086 		if (DB_TYPE(mp) == M_DATA) {
15087 			dmp = mp;
15088 		} else if (DB_TYPE(mp) == M_PROTO &&
15089 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15090 			dmp = mp->b_cont;
15091 		} else {
15092 			dmp = NULL;
15093 		}
15094 		if (dmp != NULL) {
15095 			/*
15096 			 * IP header ptr not aligned?
15097 			 * OR IP header not complete in first mblk
15098 			 */
15099 			if (!OK_32PTR(dmp->b_rptr) ||
15100 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15101 				if (!ip_check_and_align_header(q, dmp, ipst))
15102 					continue;
15103 			}
15104 		}
15105 
15106 		/*
15107 		 * ip_input fast path
15108 		 */
15109 
15110 		/* mblk type is not M_DATA */
15111 		if (DB_TYPE(mp) != M_DATA) {
15112 			if (ip_rput_process_notdata(q, &first_mp, ill,
15113 			    &ll_multicast, &mp))
15114 				continue;
15115 		}
15116 
15117 		/* Make sure its an M_DATA and that its aligned */
15118 		ASSERT(DB_TYPE(mp) == M_DATA);
15119 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15120 
15121 		ipha = (ipha_t *)mp->b_rptr;
15122 		len = mp->b_wptr - rptr;
15123 		pkt_len = ntohs(ipha->ipha_length);
15124 
15125 		/*
15126 		 * We must count all incoming packets, even if they end
15127 		 * up being dropped later on.
15128 		 */
15129 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15130 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15131 
15132 		/* multiple mblk or too short */
15133 		len -= pkt_len;
15134 		if (len != 0) {
15135 			/*
15136 			 * Make sure we have data length consistent
15137 			 * with the IP header.
15138 			 */
15139 			if (mp->b_cont == NULL) {
15140 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15141 					BUMP_MIB(ill->ill_ip_mib,
15142 					    ipIfStatsInHdrErrors);
15143 					ip2dbg(("ip_input: drop pkt\n"));
15144 					freemsg(mp);
15145 					continue;
15146 				}
15147 				mp->b_wptr = rptr + pkt_len;
15148 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15149 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15150 					BUMP_MIB(ill->ill_ip_mib,
15151 					    ipIfStatsInHdrErrors);
15152 					ip2dbg(("ip_input: drop pkt\n"));
15153 					freemsg(mp);
15154 					continue;
15155 				}
15156 				(void) adjmsg(mp, -len);
15157 				IP_STAT(ipst, ip_multimblk3);
15158 			}
15159 		}
15160 
15161 		/* Obtain the dst of the current packet */
15162 		dst = ipha->ipha_dst;
15163 
15164 		if (IP_LOOPBACK_ADDR(dst) ||
15165 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15166 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15167 			cmn_err(CE_CONT, "dst %X src %X\n",
15168 			    dst, ipha->ipha_src);
15169 			freemsg(mp);
15170 			continue;
15171 		}
15172 
15173 		/*
15174 		 * The event for packets being received from a 'physical'
15175 		 * interface is placed after validation of the source and/or
15176 		 * destination address as being local so that packets can be
15177 		 * redirected to loopback addresses using ipnat.
15178 		 */
15179 		DTRACE_PROBE4(ip4__physical__in__start,
15180 		    ill_t *, ill, ill_t *, NULL,
15181 		    ipha_t *, ipha, mblk_t *, first_mp);
15182 
15183 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15184 		    ipst->ips_ipv4firewall_physical_in,
15185 		    ill, NULL, ipha, first_mp, mp, ipst);
15186 
15187 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15188 
15189 		if (first_mp == NULL) {
15190 			continue;
15191 		}
15192 		dst = ipha->ipha_dst;
15193 
15194 		/*
15195 		 * Attach any necessary label information to
15196 		 * this packet
15197 		 */
15198 		if (is_system_labeled() &&
15199 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15200 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15201 			freemsg(mp);
15202 			continue;
15203 		}
15204 
15205 		/*
15206 		 * Reuse the cached ire only if the ipha_dst of the previous
15207 		 * packet is the same as the current packet AND it is not
15208 		 * INADDR_ANY.
15209 		 */
15210 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15211 		    (ire != NULL)) {
15212 			ire_refrele(ire);
15213 			ire = NULL;
15214 		}
15215 		opt_len = ipha->ipha_version_and_hdr_length -
15216 		    IP_SIMPLE_HDR_VERSION;
15217 
15218 		/*
15219 		 * Check to see if we can take the fastpath.
15220 		 * That is possible if the following conditions are met
15221 		 *	o Tsol disabled
15222 		 *	o CGTP disabled
15223 		 *	o ipp_action_count is 0
15224 		 *	o Mobile IP not running
15225 		 *	o no options in the packet
15226 		 *	o not a RSVP packet
15227 		 * 	o not a multicast packet
15228 		 */
15229 		if (!is_system_labeled() &&
15230 		    !ip_cgtp_filter && ipp_action_count == 0 &&
15231 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
15232 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15233 		    !ll_multicast && !CLASSD(dst)) {
15234 			if (ire == NULL)
15235 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15236 				    ipst);
15237 
15238 			/* incoming packet is for forwarding */
15239 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15240 				ire = ip_fast_forward(ire, dst, ill, mp);
15241 				continue;
15242 			}
15243 			/* incoming packet is for local consumption */
15244 			if (ire->ire_type & IRE_LOCAL)
15245 				goto local;
15246 		}
15247 
15248 		/*
15249 		 * Disable ire caching for anything more complex
15250 		 * than the simple fast path case we checked for above.
15251 		 */
15252 		if (ire != NULL) {
15253 			ire_refrele(ire);
15254 			ire = NULL;
15255 		}
15256 
15257 		/* Full-blown slow path */
15258 		if (opt_len != 0) {
15259 			if (len != 0)
15260 				IP_STAT(ipst, ip_multimblk4);
15261 			else
15262 				IP_STAT(ipst, ip_ipoptions);
15263 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15264 			    &dst, ipst))
15265 				continue;
15266 		}
15267 
15268 		/*
15269 		 * Invoke the CGTP (multirouting) filtering module to process
15270 		 * the incoming packet. Packets identified as duplicates
15271 		 * must be discarded. Filtering is active only if the
15272 		 * the ip_cgtp_filter ndd variable is non-zero.
15273 		 *
15274 		 * Only applies to the shared stack since the filter_ops
15275 		 * do not carry an ip_stack_t or zoneid.
15276 		 */
15277 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15278 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
15279 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
15280 			cgtp_flt_pkt =
15281 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15282 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15283 				freemsg(first_mp);
15284 				continue;
15285 			}
15286 		}
15287 
15288 		/*
15289 		 * If rsvpd is running, let RSVP daemon handle its processing
15290 		 * and forwarding of RSVP multicast/unicast packets.
15291 		 * If rsvpd is not running but mrouted is running, RSVP
15292 		 * multicast packets are forwarded as multicast traffic
15293 		 * and RSVP unicast packets are forwarded by unicast router.
15294 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15295 		 * packets are not forwarded, but the unicast packets are
15296 		 * forwarded like unicast traffic.
15297 		 */
15298 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15299 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15300 		    NULL) {
15301 			/* RSVP packet and rsvpd running. Treat as ours */
15302 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15303 			/*
15304 			 * This assumes that we deliver to all streams for
15305 			 * multicast and broadcast packets.
15306 			 * We have to force ll_multicast to 1 to handle the
15307 			 * M_DATA messages passed in from ip_mroute_decap.
15308 			 */
15309 			dst = INADDR_BROADCAST;
15310 			ll_multicast = 1;
15311 		} else if (CLASSD(dst)) {
15312 			/* packet is multicast */
15313 			mp->b_next = NULL;
15314 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15315 			    &ll_multicast, &dst))
15316 				continue;
15317 		}
15318 
15319 
15320 		/*
15321 		 * Check if the packet is coming from the Mobile IP
15322 		 * forward tunnel interface
15323 		 */
15324 		if (ill->ill_srcif_refcnt > 0) {
15325 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15326 			    NULL, ill, MATCH_IRE_TYPE);
15327 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15328 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15329 
15330 				/* We need to resolve the link layer info */
15331 				ire_refrele(ire);
15332 				ire = NULL;
15333 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15334 				    ll_multicast, dst);
15335 				continue;
15336 			}
15337 		}
15338 
15339 		if (ire == NULL) {
15340 			ire = ire_cache_lookup(dst, ALL_ZONES,
15341 			    MBLK_GETLABEL(mp), ipst);
15342 		}
15343 
15344 		/*
15345 		 * If mipagent is running and reverse tunnel is created as per
15346 		 * mobile node request, then any packet coming through the
15347 		 * incoming interface from the mobile-node, should be reverse
15348 		 * tunneled to it's home agent except those that are destined
15349 		 * to foreign agent only.
15350 		 * This needs source address based ire lookup. The routing
15351 		 * entries for source address based lookup are only created by
15352 		 * mipagent program only when a reverse tunnel is created.
15353 		 * Reference : RFC2002, RFC2344
15354 		 */
15355 		if (ill->ill_mrtun_refcnt > 0) {
15356 			ipaddr_t	srcaddr;
15357 			ire_t		*tmp_ire;
15358 
15359 			tmp_ire = ire;	/* Save, we might need it later */
15360 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15361 			    ire->ire_type != IRE_BROADCAST)) {
15362 				srcaddr = ipha->ipha_src;
15363 				ire = ire_mrtun_lookup(srcaddr, ill);
15364 				if (ire != NULL) {
15365 					/*
15366 					 * Should not be getting iphada packet
15367 					 * here. we should only get those for
15368 					 * IRE_LOCAL traffic, excluded above.
15369 					 * Fail-safe (drop packet) in the event
15370 					 * hardware is misbehaving.
15371 					 */
15372 					if (first_mp != mp) {
15373 						/* IPsec KSTATS: beancount me */
15374 						freemsg(first_mp);
15375 					} else {
15376 						/*
15377 						 * This packet must be forwarded
15378 						 * to Reverse Tunnel
15379 						 */
15380 						ip_mrtun_forward(ire, ill, mp);
15381 					}
15382 					ire_refrele(ire);
15383 					ire = NULL;
15384 					if (tmp_ire != NULL) {
15385 						ire_refrele(tmp_ire);
15386 						tmp_ire = NULL;
15387 					}
15388 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15389 					    "ip_input_end: q %p (%S)",
15390 					    q, "uninit");
15391 					continue;
15392 				}
15393 			}
15394 			/*
15395 			 * If this packet is from a non-mobilenode  or a
15396 			 * mobile-node which does not request reverse
15397 			 * tunnel service
15398 			 */
15399 			ire = tmp_ire;
15400 		}
15401 
15402 
15403 		/*
15404 		 * If we reach here that means the incoming packet satisfies
15405 		 * one of the following conditions:
15406 		 *   - packet is from a mobile node which does not request
15407 		 *	reverse tunnel
15408 		 *   - packet is from a non-mobile node, which is the most
15409 		 *	common case
15410 		 *   - packet is from a reverse tunnel enabled mobile node
15411 		 *	and destined to foreign agent only
15412 		 */
15413 
15414 		if (ire == NULL) {
15415 			/*
15416 			 * No IRE for this destination, so it can't be for us.
15417 			 * Unless we are forwarding, drop the packet.
15418 			 * We have to let source routed packets through
15419 			 * since we don't yet know if they are 'ping -l'
15420 			 * packets i.e. if they will go out over the
15421 			 * same interface as they came in on.
15422 			 */
15423 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15424 			if (ire == NULL)
15425 				continue;
15426 		}
15427 
15428 		/*
15429 		 * Broadcast IRE may indicate either broadcast or
15430 		 * multicast packet
15431 		 */
15432 		if (ire->ire_type == IRE_BROADCAST) {
15433 			/*
15434 			 * Skip broadcast checks if packet is UDP multicast;
15435 			 * we'd rather not enter ip_rput_process_broadcast()
15436 			 * unless the packet is broadcast for real, since
15437 			 * that routine is a no-op for multicast.
15438 			 */
15439 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15440 			    !CLASSD(ipha->ipha_dst)) {
15441 				ire = ip_rput_process_broadcast(&q, mp,
15442 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15443 				    ll_multicast);
15444 				if (ire == NULL)
15445 					continue;
15446 			}
15447 		} else if (ire->ire_stq != NULL) {
15448 			/* fowarding? */
15449 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15450 			    ll_multicast);
15451 			/* ip_rput_process_forward consumed the packet */
15452 			continue;
15453 		}
15454 
15455 local:
15456 		/*
15457 		 * If the queue in the ire is different to the ingress queue
15458 		 * then we need to check to see if we can accept the packet.
15459 		 * Note that for multicast packets and broadcast packets sent
15460 		 * to a broadcast address which is shared between multiple
15461 		 * interfaces we should not do this since we just got a random
15462 		 * broadcast ire.
15463 		 */
15464 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15465 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15466 			    ill)) == NULL) {
15467 				/* Drop packet */
15468 				BUMP_MIB(ill->ill_ip_mib,
15469 				    ipIfStatsForwProhibits);
15470 				freemsg(mp);
15471 				continue;
15472 			}
15473 			if (ire->ire_rfq != NULL)
15474 				q = ire->ire_rfq;
15475 		}
15476 
15477 		switch (ipha->ipha_protocol) {
15478 		case IPPROTO_TCP:
15479 			ASSERT(first_mp == mp);
15480 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15481 				mp, 0, q, ip_ring)) != NULL) {
15482 				if (curr_sqp == NULL) {
15483 					curr_sqp = GET_SQUEUE(mp);
15484 					ASSERT(cnt == 0);
15485 					cnt++;
15486 					head = tail = mp;
15487 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15488 					ASSERT(tail != NULL);
15489 					cnt++;
15490 					tail->b_next = mp;
15491 					tail = mp;
15492 				} else {
15493 					/*
15494 					 * A different squeue. Send the
15495 					 * chain for the previous squeue on
15496 					 * its way. This shouldn't happen
15497 					 * often unless interrupt binding
15498 					 * changes.
15499 					 */
15500 					IP_STAT(ipst, ip_input_multi_squeue);
15501 					squeue_enter_chain(curr_sqp, head,
15502 					    tail, cnt, SQTAG_IP_INPUT);
15503 					curr_sqp = GET_SQUEUE(mp);
15504 					head = mp;
15505 					tail = mp;
15506 					cnt = 1;
15507 				}
15508 			}
15509 			continue;
15510 		case IPPROTO_UDP:
15511 			ASSERT(first_mp == mp);
15512 			ip_udp_input(q, mp, ipha, ire, ill);
15513 			continue;
15514 		case IPPROTO_SCTP:
15515 			ASSERT(first_mp == mp);
15516 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15517 			    q, dst);
15518 			/* ire has been released by ip_sctp_input */
15519 			ire = NULL;
15520 			continue;
15521 		default:
15522 			ip_proto_input(q, first_mp, ipha, ire, ill);
15523 			continue;
15524 		}
15525 	}
15526 
15527 	if (ire != NULL)
15528 		ire_refrele(ire);
15529 
15530 	if (head != NULL)
15531 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15532 
15533 	/*
15534 	 * This code is there just to make netperf/ttcp look good.
15535 	 *
15536 	 * Its possible that after being in polling mode (and having cleared
15537 	 * the backlog), squeues have turned the interrupt frequency higher
15538 	 * to improve latency at the expense of more CPU utilization (less
15539 	 * packets per interrupts or more number of interrupts). Workloads
15540 	 * like ttcp/netperf do manage to tickle polling once in a while
15541 	 * but for the remaining time, stay in higher interrupt mode since
15542 	 * their packet arrival rate is pretty uniform and this shows up
15543 	 * as higher CPU utilization. Since people care about CPU utilization
15544 	 * while running netperf/ttcp, turn the interrupt frequency back to
15545 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15546 	 */
15547 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15548 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15549 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15550 			ip_ring->rr_blank(ip_ring->rr_handle,
15551 			    ip_ring->rr_normal_blank_time,
15552 			    ip_ring->rr_normal_pkt_cnt);
15553 		}
15554 		}
15555 
15556 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15557 	    "ip_input_end: q %p (%S)", q, "end");
15558 #undef  rptr
15559 }
15560 
15561 static void
15562 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15563     t_uscalar_t err)
15564 {
15565 	if (dl_err == DL_SYSERR) {
15566 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15567 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15568 		    ill->ill_name, dlpi_prim_str(prim), err);
15569 		return;
15570 	}
15571 
15572 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15573 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15574 	    dlpi_err_str(dl_err));
15575 }
15576 
15577 /*
15578  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15579  * than DL_UNITDATA_IND messages. If we need to process this message
15580  * exclusively, we call qwriter_ip, in which case we also need to call
15581  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15582  */
15583 void
15584 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15585 {
15586 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15587 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15588 	ill_t		*ill;
15589 
15590 	ip1dbg(("ip_rput_dlpi"));
15591 	ill = (ill_t *)q->q_ptr;
15592 	switch (dloa->dl_primitive) {
15593 	case DL_ERROR_ACK:
15594 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15595 		    "%s (0x%x), unix %u\n", ill->ill_name,
15596 		    dlpi_prim_str(dlea->dl_error_primitive),
15597 		    dlea->dl_error_primitive,
15598 		    dlpi_err_str(dlea->dl_errno),
15599 		    dlea->dl_errno,
15600 		    dlea->dl_unix_errno));
15601 		switch (dlea->dl_error_primitive) {
15602 		case DL_UNBIND_REQ:
15603 			mutex_enter(&ill->ill_lock);
15604 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15605 			cv_signal(&ill->ill_cv);
15606 			mutex_exit(&ill->ill_lock);
15607 			/* FALLTHRU */
15608 		case DL_NOTIFY_REQ:
15609 		case DL_ATTACH_REQ:
15610 		case DL_DETACH_REQ:
15611 		case DL_INFO_REQ:
15612 		case DL_BIND_REQ:
15613 		case DL_ENABMULTI_REQ:
15614 		case DL_PHYS_ADDR_REQ:
15615 		case DL_CAPABILITY_REQ:
15616 		case DL_CONTROL_REQ:
15617 			/*
15618 			 * Refhold the ill to match qwriter_ip which does a
15619 			 * refrele. Since this is on the ill stream we
15620 			 * unconditionally bump up the refcount without
15621 			 * checking for ILL_CAN_LOOKUP
15622 			 */
15623 			ill_refhold(ill);
15624 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15625 			    CUR_OP, B_FALSE);
15626 			return;
15627 		case DL_DISABMULTI_REQ:
15628 			freemsg(mp);	/* Don't want to pass this up */
15629 			return;
15630 		default:
15631 			break;
15632 		}
15633 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15634 		    dlea->dl_errno, dlea->dl_unix_errno);
15635 		freemsg(mp);
15636 		return;
15637 	case DL_INFO_ACK:
15638 	case DL_BIND_ACK:
15639 	case DL_PHYS_ADDR_ACK:
15640 	case DL_NOTIFY_ACK:
15641 	case DL_CAPABILITY_ACK:
15642 	case DL_CONTROL_ACK:
15643 		/*
15644 		 * Refhold the ill to match qwriter_ip which does a refrele
15645 		 * Since this is on the ill stream we unconditionally
15646 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15647 		 */
15648 		ill_refhold(ill);
15649 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15650 		    CUR_OP, B_FALSE);
15651 		return;
15652 	case DL_NOTIFY_IND:
15653 		ill_refhold(ill);
15654 		/*
15655 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15656 		 * relation to the current ioctl in progress (if any). Hence we
15657 		 * pass in NEW_OP in this case.
15658 		 */
15659 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15660 		    NEW_OP, B_FALSE);
15661 		return;
15662 	case DL_OK_ACK:
15663 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15664 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15665 		switch (dloa->dl_correct_primitive) {
15666 		case DL_UNBIND_REQ:
15667 			mutex_enter(&ill->ill_lock);
15668 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15669 			cv_signal(&ill->ill_cv);
15670 			mutex_exit(&ill->ill_lock);
15671 			/* FALLTHRU */
15672 		case DL_ATTACH_REQ:
15673 		case DL_DETACH_REQ:
15674 			/*
15675 			 * Refhold the ill to match qwriter_ip which does a
15676 			 * refrele. Since this is on the ill stream we
15677 			 * unconditionally bump up the refcount
15678 			 */
15679 			ill_refhold(ill);
15680 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15681 			    CUR_OP, B_FALSE);
15682 			return;
15683 		case DL_ENABMULTI_REQ:
15684 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15685 				ill->ill_dlpi_multicast_state = IDS_OK;
15686 			break;
15687 
15688 		}
15689 		break;
15690 	default:
15691 		break;
15692 	}
15693 	freemsg(mp);
15694 }
15695 
15696 /*
15697  * Handling of DLPI messages that require exclusive access to the ipsq.
15698  *
15699  * Need to do ill_pending_mp_release on ioctl completion, which could
15700  * happen here. (along with mi_copy_done)
15701  */
15702 /* ARGSUSED */
15703 static void
15704 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15705 {
15706 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15707 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15708 	int		err = 0;
15709 	ill_t		*ill;
15710 	ipif_t		*ipif = NULL;
15711 	mblk_t		*mp1 = NULL;
15712 	conn_t		*connp = NULL;
15713 	t_uscalar_t	paddrreq;
15714 	mblk_t		*mp_hw;
15715 	boolean_t	success;
15716 	boolean_t	ioctl_aborted = B_FALSE;
15717 	boolean_t	log = B_TRUE;
15718 	hook_nic_event_t	*info;
15719 	ip_stack_t		*ipst;
15720 
15721 	ip1dbg(("ip_rput_dlpi_writer .."));
15722 	ill = (ill_t *)q->q_ptr;
15723 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15724 
15725 	ASSERT(IAM_WRITER_ILL(ill));
15726 
15727 	ipst = ill->ill_ipst;
15728 
15729 	/*
15730 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15731 	 * both are null or non-null. However we can assert that only
15732 	 * after grabbing the ipsq_lock. So we don't make any assertion
15733 	 * here and in other places in the code.
15734 	 */
15735 	ipif = ipsq->ipsq_pending_ipif;
15736 	/*
15737 	 * The current ioctl could have been aborted by the user and a new
15738 	 * ioctl to bring up another ill could have started. We could still
15739 	 * get a response from the driver later.
15740 	 */
15741 	if (ipif != NULL && ipif->ipif_ill != ill)
15742 		ioctl_aborted = B_TRUE;
15743 
15744 	switch (dloa->dl_primitive) {
15745 	case DL_ERROR_ACK:
15746 		switch (dlea->dl_error_primitive) {
15747 		case DL_UNBIND_REQ:
15748 		case DL_ATTACH_REQ:
15749 		case DL_DETACH_REQ:
15750 		case DL_INFO_REQ:
15751 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15752 			break;
15753 		case DL_NOTIFY_REQ:
15754 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15755 			log = B_FALSE;
15756 			break;
15757 		case DL_PHYS_ADDR_REQ:
15758 			/*
15759 			 * For IPv6 only, there are two additional
15760 			 * phys_addr_req's sent to the driver to get the
15761 			 * IPv6 token and lla. This allows IP to acquire
15762 			 * the hardware address format for a given interface
15763 			 * without having built in knowledge of the hardware
15764 			 * address. ill_phys_addr_pend keeps track of the last
15765 			 * DL_PAR sent so we know which response we are
15766 			 * dealing with. ill_dlpi_done will update
15767 			 * ill_phys_addr_pend when it sends the next req.
15768 			 * We don't complete the IOCTL until all three DL_PARs
15769 			 * have been attempted, so set *_len to 0 and break.
15770 			 */
15771 			paddrreq = ill->ill_phys_addr_pend;
15772 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15773 			if (paddrreq == DL_IPV6_TOKEN) {
15774 				ill->ill_token_length = 0;
15775 				log = B_FALSE;
15776 				break;
15777 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15778 				ill->ill_nd_lla_len = 0;
15779 				log = B_FALSE;
15780 				break;
15781 			}
15782 			/*
15783 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15784 			 * We presumably have an IOCTL hanging out waiting
15785 			 * for completion. Find it and complete the IOCTL
15786 			 * with the error noted.
15787 			 * However, ill_dl_phys was called on an ill queue
15788 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15789 			 * set. But the ioctl is known to be pending on ill_wq.
15790 			 */
15791 			if (!ill->ill_ifname_pending)
15792 				break;
15793 			ill->ill_ifname_pending = 0;
15794 			if (!ioctl_aborted)
15795 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15796 			if (mp1 != NULL) {
15797 				/*
15798 				 * This operation (SIOCSLIFNAME) must have
15799 				 * happened on the ill. Assert there is no conn
15800 				 */
15801 				ASSERT(connp == NULL);
15802 				q = ill->ill_wq;
15803 			}
15804 			break;
15805 		case DL_BIND_REQ:
15806 			ill_dlpi_done(ill, DL_BIND_REQ);
15807 			if (ill->ill_ifname_pending)
15808 				break;
15809 			/*
15810 			 * Something went wrong with the bind.  We presumably
15811 			 * have an IOCTL hanging out waiting for completion.
15812 			 * Find it, take down the interface that was coming
15813 			 * up, and complete the IOCTL with the error noted.
15814 			 */
15815 			if (!ioctl_aborted)
15816 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15817 			if (mp1 != NULL) {
15818 				/*
15819 				 * This operation (SIOCSLIFFLAGS) must have
15820 				 * happened from a conn.
15821 				 */
15822 				ASSERT(connp != NULL);
15823 				q = CONNP_TO_WQ(connp);
15824 				if (ill->ill_move_in_progress) {
15825 					ILL_CLEAR_MOVE(ill);
15826 				}
15827 				(void) ipif_down(ipif, NULL, NULL);
15828 				/* error is set below the switch */
15829 			}
15830 			break;
15831 		case DL_ENABMULTI_REQ:
15832 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15833 
15834 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15835 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15836 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15837 				ipif_t *ipif;
15838 
15839 				log = B_FALSE;
15840 				printf("ip: joining multicasts failed (%d)"
15841 				    " on %s - will use link layer "
15842 				    "broadcasts for multicast\n",
15843 				    dlea->dl_errno, ill->ill_name);
15844 
15845 				/*
15846 				 * Set up the multicast mapping alone.
15847 				 * writer, so ok to access ill->ill_ipif
15848 				 * without any lock.
15849 				 */
15850 				ipif = ill->ill_ipif;
15851 				mutex_enter(&ill->ill_phyint->phyint_lock);
15852 				ill->ill_phyint->phyint_flags |=
15853 				    PHYI_MULTI_BCAST;
15854 				mutex_exit(&ill->ill_phyint->phyint_lock);
15855 
15856 				if (!ill->ill_isv6) {
15857 					(void) ipif_arp_setup_multicast(ipif,
15858 					    NULL);
15859 				} else {
15860 					(void) ipif_ndp_setup_multicast(ipif,
15861 					    NULL);
15862 				}
15863 			}
15864 			freemsg(mp);	/* Don't want to pass this up */
15865 			return;
15866 		case DL_CAPABILITY_REQ:
15867 		case DL_CONTROL_REQ:
15868 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15869 			    "DL_CAPABILITY/CONTROL REQ\n"));
15870 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15871 			ill->ill_dlpi_capab_state = IDS_FAILED;
15872 			freemsg(mp);
15873 			return;
15874 		}
15875 		/*
15876 		 * Note the error for IOCTL completion (mp1 is set when
15877 		 * ready to complete ioctl). If ill_ifname_pending_err is
15878 		 * set, an error occured during plumbing (ill_ifname_pending),
15879 		 * so we want to report that error.
15880 		 *
15881 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15882 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15883 		 * expected to get errack'd if the driver doesn't support
15884 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15885 		 * if these error conditions are encountered.
15886 		 */
15887 		if (mp1 != NULL) {
15888 			if (ill->ill_ifname_pending_err != 0)  {
15889 				err = ill->ill_ifname_pending_err;
15890 				ill->ill_ifname_pending_err = 0;
15891 			} else {
15892 				err = dlea->dl_unix_errno ?
15893 				    dlea->dl_unix_errno : ENXIO;
15894 			}
15895 		/*
15896 		 * If we're plumbing an interface and an error hasn't already
15897 		 * been saved, set ill_ifname_pending_err to the error passed
15898 		 * up. Ignore the error if log is B_FALSE (see comment above).
15899 		 */
15900 		} else if (log && ill->ill_ifname_pending &&
15901 		    ill->ill_ifname_pending_err == 0) {
15902 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15903 			dlea->dl_unix_errno : ENXIO;
15904 		}
15905 
15906 		if (log)
15907 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15908 			    dlea->dl_errno, dlea->dl_unix_errno);
15909 		break;
15910 	case DL_CAPABILITY_ACK: {
15911 		boolean_t reneg_flag = B_FALSE;
15912 		/* Call a routine to handle this one. */
15913 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15914 		/*
15915 		 * Check if the ACK is due to renegotiation case since we
15916 		 * will need to send a new CAPABILITY_REQ later.
15917 		 */
15918 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15919 			/* This is the ack for a renogiation case */
15920 			reneg_flag = B_TRUE;
15921 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15922 		}
15923 		ill_capability_ack(ill, mp);
15924 		if (reneg_flag)
15925 			ill_capability_probe(ill);
15926 		break;
15927 	}
15928 	case DL_CONTROL_ACK:
15929 		/* We treat all of these as "fire and forget" */
15930 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15931 		break;
15932 	case DL_INFO_ACK:
15933 		/* Call a routine to handle this one. */
15934 		ill_dlpi_done(ill, DL_INFO_REQ);
15935 		ip_ll_subnet_defaults(ill, mp);
15936 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15937 		return;
15938 	case DL_BIND_ACK:
15939 		/*
15940 		 * We should have an IOCTL waiting on this unless
15941 		 * sent by ill_dl_phys, in which case just return
15942 		 */
15943 		ill_dlpi_done(ill, DL_BIND_REQ);
15944 		if (ill->ill_ifname_pending)
15945 			break;
15946 
15947 		if (!ioctl_aborted)
15948 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15949 		if (mp1 == NULL)
15950 			break;
15951 		/*
15952 		 * Because mp1 was added by ill_dl_up(), and it always
15953 		 * passes a valid connp, connp must be valid here.
15954 		 */
15955 		ASSERT(connp != NULL);
15956 		q = CONNP_TO_WQ(connp);
15957 
15958 		/*
15959 		 * We are exclusive. So nothing can change even after
15960 		 * we get the pending mp. If need be we can put it back
15961 		 * and restart, as in calling ipif_arp_up()  below.
15962 		 */
15963 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15964 
15965 		mutex_enter(&ill->ill_lock);
15966 
15967 		ill->ill_dl_up = 1;
15968 
15969 		if ((info = ill->ill_nic_event_info) != NULL) {
15970 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15971 			    "attached for %s\n", info->hne_event,
15972 			    ill->ill_name));
15973 			if (info->hne_data != NULL)
15974 				kmem_free(info->hne_data, info->hne_datalen);
15975 			kmem_free(info, sizeof (hook_nic_event_t));
15976 		}
15977 
15978 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15979 		if (info != NULL) {
15980 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15981 			info->hne_lif = 0;
15982 			info->hne_event = NE_UP;
15983 			info->hne_data = NULL;
15984 			info->hne_datalen = 0;
15985 			info->hne_family = ill->ill_isv6 ?
15986 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15987 		} else
15988 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15989 			    "event information for %s (ENOMEM)\n",
15990 			    ill->ill_name));
15991 
15992 		ill->ill_nic_event_info = info;
15993 
15994 		mutex_exit(&ill->ill_lock);
15995 
15996 		/*
15997 		 * Now bring up the resolver; when that is complete, we'll
15998 		 * create IREs.  Note that we intentionally mirror what
15999 		 * ipif_up() would have done, because we got here by way of
16000 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16001 		 */
16002 		if (ill->ill_isv6) {
16003 			/*
16004 			 * v6 interfaces.
16005 			 * Unlike ARP which has to do another bind
16006 			 * and attach, once we get here we are
16007 			 * done with NDP. Except in the case of
16008 			 * ILLF_XRESOLV, in which case we send an
16009 			 * AR_INTERFACE_UP to the external resolver.
16010 			 * If all goes well, the ioctl will complete
16011 			 * in ip_rput(). If there's an error, we
16012 			 * complete it here.
16013 			 */
16014 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
16015 			if (err == 0) {
16016 				if (ill->ill_flags & ILLF_XRESOLV) {
16017 					mutex_enter(&connp->conn_lock);
16018 					mutex_enter(&ill->ill_lock);
16019 					success = ipsq_pending_mp_add(
16020 					    connp, ipif, q, mp1, 0);
16021 					mutex_exit(&ill->ill_lock);
16022 					mutex_exit(&connp->conn_lock);
16023 					if (success) {
16024 						err = ipif_resolver_up(ipif,
16025 						    Res_act_initial);
16026 						if (err == EINPROGRESS) {
16027 							freemsg(mp);
16028 							return;
16029 						}
16030 						ASSERT(err != 0);
16031 						mp1 = ipsq_pending_mp_get(ipsq,
16032 						    &connp);
16033 						ASSERT(mp1 != NULL);
16034 					} else {
16035 						/* conn has started closing */
16036 						err = EINTR;
16037 					}
16038 				} else { /* Non XRESOLV interface */
16039 					(void) ipif_resolver_up(ipif,
16040 					    Res_act_initial);
16041 					err = ipif_up_done_v6(ipif);
16042 				}
16043 			}
16044 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16045 			/*
16046 			 * ARP and other v4 external resolvers.
16047 			 * Leave the pending mblk intact so that
16048 			 * the ioctl completes in ip_rput().
16049 			 */
16050 			mutex_enter(&connp->conn_lock);
16051 			mutex_enter(&ill->ill_lock);
16052 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16053 			mutex_exit(&ill->ill_lock);
16054 			mutex_exit(&connp->conn_lock);
16055 			if (success) {
16056 				err = ipif_resolver_up(ipif, Res_act_initial);
16057 				if (err == EINPROGRESS) {
16058 					freemsg(mp);
16059 					return;
16060 				}
16061 				ASSERT(err != 0);
16062 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16063 			} else {
16064 				/* The conn has started closing */
16065 				err = EINTR;
16066 			}
16067 		} else {
16068 			/*
16069 			 * This one is complete. Reply to pending ioctl.
16070 			 */
16071 			(void) ipif_resolver_up(ipif, Res_act_initial);
16072 			err = ipif_up_done(ipif);
16073 		}
16074 
16075 		if ((err == 0) && (ill->ill_up_ipifs)) {
16076 			err = ill_up_ipifs(ill, q, mp1);
16077 			if (err == EINPROGRESS) {
16078 				freemsg(mp);
16079 				return;
16080 			}
16081 		}
16082 
16083 		if (ill->ill_up_ipifs) {
16084 			ill_group_cleanup(ill);
16085 		}
16086 
16087 		break;
16088 	case DL_NOTIFY_IND: {
16089 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16090 		ire_t *ire;
16091 		boolean_t need_ire_walk_v4 = B_FALSE;
16092 		boolean_t need_ire_walk_v6 = B_FALSE;
16093 
16094 		switch (notify->dl_notification) {
16095 		case DL_NOTE_PHYS_ADDR:
16096 			err = ill_set_phys_addr(ill, mp);
16097 			break;
16098 
16099 		case DL_NOTE_FASTPATH_FLUSH:
16100 			ill_fastpath_flush(ill);
16101 			break;
16102 
16103 		case DL_NOTE_SDU_SIZE:
16104 			/*
16105 			 * Change the MTU size of the interface, of all
16106 			 * attached ipif's, and of all relevant ire's.  The
16107 			 * new value's a uint32_t at notify->dl_data.
16108 			 * Mtu change Vs. new ire creation - protocol below.
16109 			 *
16110 			 * a Mark the ipif as IPIF_CHANGING.
16111 			 * b Set the new mtu in the ipif.
16112 			 * c Change the ire_max_frag on all affected ires
16113 			 * d Unmark the IPIF_CHANGING
16114 			 *
16115 			 * To see how the protocol works, assume an interface
16116 			 * route is also being added simultaneously by
16117 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16118 			 * the ire. If the ire is created before step a,
16119 			 * it will be cleaned up by step c. If the ire is
16120 			 * created after step d, it will see the new value of
16121 			 * ipif_mtu. Any attempt to create the ire between
16122 			 * steps a to d will fail because of the IPIF_CHANGING
16123 			 * flag. Note that ire_create() is passed a pointer to
16124 			 * the ipif_mtu, and not the value. During ire_add
16125 			 * under the bucket lock, the ire_max_frag of the
16126 			 * new ire being created is set from the ipif/ire from
16127 			 * which it is being derived.
16128 			 */
16129 			mutex_enter(&ill->ill_lock);
16130 			ill->ill_max_frag = (uint_t)notify->dl_data;
16131 
16132 			/*
16133 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16134 			 * leave it alone
16135 			 */
16136 			if (ill->ill_mtu_userspecified) {
16137 				mutex_exit(&ill->ill_lock);
16138 				break;
16139 			}
16140 			ill->ill_max_mtu = ill->ill_max_frag;
16141 			if (ill->ill_isv6) {
16142 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16143 					ill->ill_max_mtu = IPV6_MIN_MTU;
16144 			} else {
16145 				if (ill->ill_max_mtu < IP_MIN_MTU)
16146 					ill->ill_max_mtu = IP_MIN_MTU;
16147 			}
16148 			for (ipif = ill->ill_ipif; ipif != NULL;
16149 			    ipif = ipif->ipif_next) {
16150 				/*
16151 				 * Don't override the mtu if the user
16152 				 * has explicitly set it.
16153 				 */
16154 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16155 					continue;
16156 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16157 				if (ipif->ipif_isv6)
16158 					ire = ipif_to_ire_v6(ipif);
16159 				else
16160 					ire = ipif_to_ire(ipif);
16161 				if (ire != NULL) {
16162 					ire->ire_max_frag = ipif->ipif_mtu;
16163 					ire_refrele(ire);
16164 				}
16165 				if (ipif->ipif_flags & IPIF_UP) {
16166 					if (ill->ill_isv6)
16167 						need_ire_walk_v6 = B_TRUE;
16168 					else
16169 						need_ire_walk_v4 = B_TRUE;
16170 				}
16171 			}
16172 			mutex_exit(&ill->ill_lock);
16173 			if (need_ire_walk_v4)
16174 				ire_walk_v4(ill_mtu_change, (char *)ill,
16175 				    ALL_ZONES, ipst);
16176 			if (need_ire_walk_v6)
16177 				ire_walk_v6(ill_mtu_change, (char *)ill,
16178 				    ALL_ZONES, ipst);
16179 			break;
16180 		case DL_NOTE_LINK_UP:
16181 		case DL_NOTE_LINK_DOWN: {
16182 			/*
16183 			 * We are writer. ill / phyint / ipsq assocs stable.
16184 			 * The RUNNING flag reflects the state of the link.
16185 			 */
16186 			phyint_t *phyint = ill->ill_phyint;
16187 			uint64_t new_phyint_flags;
16188 			boolean_t changed = B_FALSE;
16189 			boolean_t went_up;
16190 
16191 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16192 			mutex_enter(&phyint->phyint_lock);
16193 			new_phyint_flags = went_up ?
16194 			    phyint->phyint_flags | PHYI_RUNNING :
16195 			    phyint->phyint_flags & ~PHYI_RUNNING;
16196 			if (new_phyint_flags != phyint->phyint_flags) {
16197 				phyint->phyint_flags = new_phyint_flags;
16198 				changed = B_TRUE;
16199 			}
16200 			mutex_exit(&phyint->phyint_lock);
16201 			/*
16202 			 * ill_restart_dad handles the DAD restart and routing
16203 			 * socket notification logic.
16204 			 */
16205 			if (changed) {
16206 				ill_restart_dad(phyint->phyint_illv4, went_up);
16207 				ill_restart_dad(phyint->phyint_illv6, went_up);
16208 			}
16209 			break;
16210 		}
16211 		case DL_NOTE_PROMISC_ON_PHYS:
16212 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16213 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16214 			mutex_enter(&ill->ill_lock);
16215 			ill->ill_promisc_on_phys = B_TRUE;
16216 			mutex_exit(&ill->ill_lock);
16217 			break;
16218 		case DL_NOTE_PROMISC_OFF_PHYS:
16219 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16220 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16221 			mutex_enter(&ill->ill_lock);
16222 			ill->ill_promisc_on_phys = B_FALSE;
16223 			mutex_exit(&ill->ill_lock);
16224 			break;
16225 		case DL_NOTE_CAPAB_RENEG:
16226 			/*
16227 			 * Something changed on the driver side.
16228 			 * It wants us to renegotiate the capabilities
16229 			 * on this ill. The most likely cause is the
16230 			 * aggregation interface under us where a
16231 			 * port got added or went away.
16232 			 *
16233 			 * We reset the capabilities and set the
16234 			 * state to IDS_RENG so that when the ack
16235 			 * comes back, we can start the
16236 			 * renegotiation process.
16237 			 */
16238 			ill_capability_reset(ill);
16239 			ill->ill_dlpi_capab_state = IDS_RENEG;
16240 			break;
16241 		default:
16242 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16243 			    "type 0x%x for DL_NOTIFY_IND\n",
16244 			    notify->dl_notification));
16245 			break;
16246 		}
16247 
16248 		/*
16249 		 * As this is an asynchronous operation, we
16250 		 * should not call ill_dlpi_done
16251 		 */
16252 		break;
16253 	}
16254 	case DL_NOTIFY_ACK: {
16255 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16256 
16257 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16258 			ill->ill_note_link = 1;
16259 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16260 		break;
16261 	}
16262 	case DL_PHYS_ADDR_ACK: {
16263 		/*
16264 		 * As part of plumbing the interface via SIOCSLIFNAME,
16265 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16266 		 * whose answers we receive here.  As each answer is received,
16267 		 * we call ill_dlpi_done() to dispatch the next request as
16268 		 * we're processing the current one.  Once all answers have
16269 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16270 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16271 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16272 		 * available, but we know the ioctl is pending on ill_wq.)
16273 		 */
16274 		uint_t paddrlen, paddroff;
16275 
16276 		paddrreq = ill->ill_phys_addr_pend;
16277 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16278 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16279 
16280 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16281 		if (paddrreq == DL_IPV6_TOKEN) {
16282 			/*
16283 			 * bcopy to low-order bits of ill_token
16284 			 *
16285 			 * XXX Temporary hack - currently, all known tokens
16286 			 * are 64 bits, so I'll cheat for the moment.
16287 			 */
16288 			bcopy(mp->b_rptr + paddroff,
16289 			    &ill->ill_token.s6_addr32[2], paddrlen);
16290 			ill->ill_token_length = paddrlen;
16291 			break;
16292 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16293 			ASSERT(ill->ill_nd_lla_mp == NULL);
16294 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16295 			mp = NULL;
16296 			break;
16297 		}
16298 
16299 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16300 		ASSERT(ill->ill_phys_addr_mp == NULL);
16301 		if (!ill->ill_ifname_pending)
16302 			break;
16303 		ill->ill_ifname_pending = 0;
16304 		if (!ioctl_aborted)
16305 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16306 		if (mp1 != NULL) {
16307 			ASSERT(connp == NULL);
16308 			q = ill->ill_wq;
16309 		}
16310 		/*
16311 		 * If any error acks received during the plumbing sequence,
16312 		 * ill_ifname_pending_err will be set. Break out and send up
16313 		 * the error to the pending ioctl.
16314 		 */
16315 		if (ill->ill_ifname_pending_err != 0) {
16316 			err = ill->ill_ifname_pending_err;
16317 			ill->ill_ifname_pending_err = 0;
16318 			break;
16319 		}
16320 
16321 		ill->ill_phys_addr_mp = mp;
16322 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16323 		mp = NULL;
16324 
16325 		/*
16326 		 * If paddrlen is zero, the DLPI provider doesn't support
16327 		 * physical addresses.  The other two tests were historical
16328 		 * workarounds for bugs in our former PPP implementation, but
16329 		 * now other things have grown dependencies on them -- e.g.,
16330 		 * the tun module specifies a dl_addr_length of zero in its
16331 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16332 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16333 		 * but only after careful testing ensures that all dependent
16334 		 * broken DLPI providers have been fixed.
16335 		 */
16336 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16337 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16338 			ill->ill_phys_addr = NULL;
16339 		} else if (paddrlen != ill->ill_phys_addr_length) {
16340 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16341 			    paddrlen, ill->ill_phys_addr_length));
16342 			err = EINVAL;
16343 			break;
16344 		}
16345 
16346 		if (ill->ill_nd_lla_mp == NULL) {
16347 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16348 				err = ENOMEM;
16349 				break;
16350 			}
16351 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16352 		}
16353 
16354 		/*
16355 		 * Set the interface token.  If the zeroth interface address
16356 		 * is unspecified, then set it to the link local address.
16357 		 */
16358 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16359 			(void) ill_setdefaulttoken(ill);
16360 
16361 		ASSERT(ill->ill_ipif->ipif_id == 0);
16362 		if (ipif != NULL &&
16363 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16364 			(void) ipif_setlinklocal(ipif);
16365 		}
16366 		break;
16367 	}
16368 	case DL_OK_ACK:
16369 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16370 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16371 		    dloa->dl_correct_primitive));
16372 		switch (dloa->dl_correct_primitive) {
16373 		case DL_UNBIND_REQ:
16374 		case DL_ATTACH_REQ:
16375 		case DL_DETACH_REQ:
16376 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16377 			break;
16378 		}
16379 		break;
16380 	default:
16381 		break;
16382 	}
16383 
16384 	freemsg(mp);
16385 	if (mp1 != NULL) {
16386 		/*
16387 		 * The operation must complete without EINPROGRESS
16388 		 * since ipsq_pending_mp_get() has removed the mblk
16389 		 * from ipsq_pending_mp.  Otherwise, the operation
16390 		 * will be stuck forever in the ipsq.
16391 		 */
16392 		ASSERT(err != EINPROGRESS);
16393 
16394 		switch (ipsq->ipsq_current_ioctl) {
16395 		case 0:
16396 			ipsq_current_finish(ipsq);
16397 			break;
16398 
16399 		case SIOCLIFADDIF:
16400 		case SIOCSLIFNAME:
16401 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16402 			break;
16403 
16404 		default:
16405 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16406 			break;
16407 		}
16408 	}
16409 }
16410 
16411 /*
16412  * ip_rput_other is called by ip_rput to handle messages modifying the global
16413  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16414  */
16415 /* ARGSUSED */
16416 void
16417 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16418 {
16419 	ill_t		*ill;
16420 	struct iocblk	*iocp;
16421 	mblk_t		*mp1;
16422 	conn_t		*connp = NULL;
16423 
16424 	ip1dbg(("ip_rput_other "));
16425 	ill = (ill_t *)q->q_ptr;
16426 	/*
16427 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16428 	 * in which case ipsq is NULL.
16429 	 */
16430 	if (ipsq != NULL) {
16431 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16432 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16433 	}
16434 
16435 	switch (mp->b_datap->db_type) {
16436 	case M_ERROR:
16437 	case M_HANGUP:
16438 		/*
16439 		 * The device has a problem.  We force the ILL down.  It can
16440 		 * be brought up again manually using SIOCSIFFLAGS (via
16441 		 * ifconfig or equivalent).
16442 		 */
16443 		ASSERT(ipsq != NULL);
16444 		if (mp->b_rptr < mp->b_wptr)
16445 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16446 		if (ill->ill_error == 0)
16447 			ill->ill_error = ENXIO;
16448 		if (!ill_down_start(q, mp))
16449 			return;
16450 		ipif_all_down_tail(ipsq, q, mp, NULL);
16451 		break;
16452 	case M_IOCACK:
16453 		iocp = (struct iocblk *)mp->b_rptr;
16454 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16455 		switch (iocp->ioc_cmd) {
16456 		case SIOCSTUNPARAM:
16457 		case OSIOCSTUNPARAM:
16458 			ASSERT(ipsq != NULL);
16459 			/*
16460 			 * Finish socket ioctl passed through to tun.
16461 			 * We should have an IOCTL waiting on this.
16462 			 */
16463 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16464 			if (ill->ill_isv6) {
16465 				struct iftun_req *ta;
16466 
16467 				/*
16468 				 * if a source or destination is
16469 				 * being set, try and set the link
16470 				 * local address for the tunnel
16471 				 */
16472 				ta = (struct iftun_req *)mp->b_cont->
16473 				    b_cont->b_rptr;
16474 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16475 					ipif_set_tun_llink(ill, ta);
16476 				}
16477 
16478 			}
16479 			if (mp1 != NULL) {
16480 				/*
16481 				 * Now copy back the b_next/b_prev used by
16482 				 * mi code for the mi_copy* functions.
16483 				 * See ip_sioctl_tunparam() for the reason.
16484 				 * Also protect against missing b_cont.
16485 				 */
16486 				if (mp->b_cont != NULL) {
16487 					mp->b_cont->b_next =
16488 					    mp1->b_cont->b_next;
16489 					mp->b_cont->b_prev =
16490 					    mp1->b_cont->b_prev;
16491 				}
16492 				inet_freemsg(mp1);
16493 				ASSERT(connp != NULL);
16494 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16495 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16496 			} else {
16497 				ASSERT(connp == NULL);
16498 				putnext(q, mp);
16499 			}
16500 			break;
16501 		case SIOCGTUNPARAM:
16502 		case OSIOCGTUNPARAM:
16503 			/*
16504 			 * This is really M_IOCDATA from the tunnel driver.
16505 			 * convert back and complete the ioctl.
16506 			 * We should have an IOCTL waiting on this.
16507 			 */
16508 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16509 			if (mp1) {
16510 				/*
16511 				 * Now copy back the b_next/b_prev used by
16512 				 * mi code for the mi_copy* functions.
16513 				 * See ip_sioctl_tunparam() for the reason.
16514 				 * Also protect against missing b_cont.
16515 				 */
16516 				if (mp->b_cont != NULL) {
16517 					mp->b_cont->b_next =
16518 					    mp1->b_cont->b_next;
16519 					mp->b_cont->b_prev =
16520 					    mp1->b_cont->b_prev;
16521 				}
16522 				inet_freemsg(mp1);
16523 				if (iocp->ioc_error == 0)
16524 					mp->b_datap->db_type = M_IOCDATA;
16525 				ASSERT(connp != NULL);
16526 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16527 				    iocp->ioc_error, COPYOUT, NULL);
16528 			} else {
16529 				ASSERT(connp == NULL);
16530 				putnext(q, mp);
16531 			}
16532 			break;
16533 		default:
16534 			break;
16535 		}
16536 		break;
16537 	case M_IOCNAK:
16538 		iocp = (struct iocblk *)mp->b_rptr;
16539 
16540 		switch (iocp->ioc_cmd) {
16541 		int mode;
16542 
16543 		case DL_IOC_HDR_INFO:
16544 			/*
16545 			 * If this was the first attempt turn of the
16546 			 * fastpath probing.
16547 			 */
16548 			mutex_enter(&ill->ill_lock);
16549 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16550 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16551 				mutex_exit(&ill->ill_lock);
16552 				ill_fastpath_nack(ill);
16553 				ip1dbg(("ip_rput: DLPI fastpath off on "
16554 				    "interface %s\n",
16555 				    ill->ill_name));
16556 			} else {
16557 				mutex_exit(&ill->ill_lock);
16558 			}
16559 			freemsg(mp);
16560 			break;
16561 		case SIOCSTUNPARAM:
16562 		case OSIOCSTUNPARAM:
16563 			ASSERT(ipsq != NULL);
16564 			/*
16565 			 * Finish socket ioctl passed through to tun
16566 			 * We should have an IOCTL waiting on this.
16567 			 */
16568 			/* FALLTHRU */
16569 		case SIOCGTUNPARAM:
16570 		case OSIOCGTUNPARAM:
16571 			/*
16572 			 * This is really M_IOCDATA from the tunnel driver.
16573 			 * convert back and complete the ioctl.
16574 			 * We should have an IOCTL waiting on this.
16575 			 */
16576 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16577 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16578 				mp1 = ill_pending_mp_get(ill, &connp,
16579 				    iocp->ioc_id);
16580 				mode = COPYOUT;
16581 				ipsq = NULL;
16582 			} else {
16583 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16584 				mode = NO_COPYOUT;
16585 			}
16586 			if (mp1 != NULL) {
16587 				/*
16588 				 * Now copy back the b_next/b_prev used by
16589 				 * mi code for the mi_copy* functions.
16590 				 * See ip_sioctl_tunparam() for the reason.
16591 				 * Also protect against missing b_cont.
16592 				 */
16593 				if (mp->b_cont != NULL) {
16594 					mp->b_cont->b_next =
16595 					    mp1->b_cont->b_next;
16596 					mp->b_cont->b_prev =
16597 					    mp1->b_cont->b_prev;
16598 				}
16599 				inet_freemsg(mp1);
16600 				if (iocp->ioc_error == 0)
16601 					iocp->ioc_error = EINVAL;
16602 				ASSERT(connp != NULL);
16603 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16604 				    iocp->ioc_error, mode, ipsq);
16605 			} else {
16606 				ASSERT(connp == NULL);
16607 				putnext(q, mp);
16608 			}
16609 			break;
16610 		default:
16611 			break;
16612 		}
16613 	default:
16614 		break;
16615 	}
16616 }
16617 
16618 /*
16619  * NOTE : This function does not ire_refrele the ire argument passed in.
16620  *
16621  * IPQoS notes
16622  * IP policy is invoked twice for a forwarded packet, once on the read side
16623  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16624  * enabled. An additional parameter, in_ill, has been added for this purpose.
16625  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16626  * because ip_mroute drops this information.
16627  *
16628  */
16629 void
16630 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16631 {
16632 	uint32_t	pkt_len;
16633 	queue_t	*q;
16634 	uint32_t	sum;
16635 #define	rptr	((uchar_t *)ipha)
16636 	uint32_t	max_frag;
16637 	uint32_t	ill_index;
16638 	ill_t		*out_ill;
16639 	mib2_ipIfStatsEntry_t *mibptr;
16640 	ip_stack_t	*ipst = in_ill->ill_ipst;
16641 
16642 	/* Get the ill_index of the incoming ILL */
16643 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16644 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16645 
16646 	/* Initiate Read side IPPF processing */
16647 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16648 		ip_process(IPP_FWD_IN, &mp, ill_index);
16649 		if (mp == NULL) {
16650 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16651 			    "during IPPF processing\n"));
16652 			return;
16653 		}
16654 	}
16655 
16656 	pkt_len = ntohs(ipha->ipha_length);
16657 
16658 	/* Adjust the checksum to reflect the ttl decrement. */
16659 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16660 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16661 
16662 	if (ipha->ipha_ttl-- <= 1) {
16663 		if (ip_csum_hdr(ipha)) {
16664 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16665 			goto drop_pkt;
16666 		}
16667 		/*
16668 		 * Note: ire_stq this will be NULL for multicast
16669 		 * datagrams using the long path through arp (the IRE
16670 		 * is not an IRE_CACHE). This should not cause
16671 		 * problems since we don't generate ICMP errors for
16672 		 * multicast packets.
16673 		 */
16674 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16675 		q = ire->ire_stq;
16676 		if (q != NULL) {
16677 			/* Sent by forwarding path, and router is global zone */
16678 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16679 			    GLOBAL_ZONEID, ipst);
16680 		} else
16681 			freemsg(mp);
16682 		return;
16683 	}
16684 
16685 	/*
16686 	 * Don't forward if the interface is down
16687 	 */
16688 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16689 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16690 		ip2dbg(("ip_rput_forward:interface is down\n"));
16691 		goto drop_pkt;
16692 	}
16693 
16694 	/* Get the ill_index of the outgoing ILL */
16695 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16696 
16697 	out_ill = ire->ire_ipif->ipif_ill;
16698 
16699 	DTRACE_PROBE4(ip4__forwarding__start,
16700 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16701 
16702 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16703 	    ipst->ips_ipv4firewall_forwarding,
16704 	    in_ill, out_ill, ipha, mp, mp, ipst);
16705 
16706 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16707 
16708 	if (mp == NULL)
16709 		return;
16710 	pkt_len = ntohs(ipha->ipha_length);
16711 
16712 	if (is_system_labeled()) {
16713 		mblk_t *mp1;
16714 
16715 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16716 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16717 			goto drop_pkt;
16718 		}
16719 		/* Size may have changed */
16720 		mp = mp1;
16721 		ipha = (ipha_t *)mp->b_rptr;
16722 		pkt_len = ntohs(ipha->ipha_length);
16723 	}
16724 
16725 	/* Check if there are options to update */
16726 	if (!IS_SIMPLE_IPH(ipha)) {
16727 		if (ip_csum_hdr(ipha)) {
16728 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16729 			goto drop_pkt;
16730 		}
16731 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16732 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16733 			return;
16734 		}
16735 
16736 		ipha->ipha_hdr_checksum = 0;
16737 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16738 	}
16739 	max_frag = ire->ire_max_frag;
16740 	if (pkt_len > max_frag) {
16741 		/*
16742 		 * It needs fragging on its way out.  We haven't
16743 		 * verified the header checksum yet.  Since we
16744 		 * are going to put a surely good checksum in the
16745 		 * outgoing header, we have to make sure that it
16746 		 * was good coming in.
16747 		 */
16748 		if (ip_csum_hdr(ipha)) {
16749 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16750 			goto drop_pkt;
16751 		}
16752 		/* Initiate Write side IPPF processing */
16753 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16754 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16755 			if (mp == NULL) {
16756 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16757 				    " during IPPF processing\n"));
16758 				return;
16759 			}
16760 		}
16761 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16762 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16763 		return;
16764 	}
16765 
16766 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16767 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16768 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16769 	    ipst->ips_ipv4firewall_physical_out,
16770 	    NULL, out_ill, ipha, mp, mp, ipst);
16771 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16772 	if (mp == NULL)
16773 		return;
16774 
16775 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16776 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16777 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16778 	/* ip_xmit_v4 always consumes the packet */
16779 	return;
16780 
16781 drop_pkt:;
16782 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16783 	freemsg(mp);
16784 #undef	rptr
16785 }
16786 
16787 void
16788 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16789 {
16790 	ire_t	*ire;
16791 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16792 
16793 	ASSERT(!ipif->ipif_isv6);
16794 	/*
16795 	 * Find an IRE which matches the destination and the outgoing
16796 	 * queue in the cache table. All we need is an IRE_CACHE which
16797 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16798 	 * then it is enough to have some IRE_CACHE in the group.
16799 	 */
16800 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16801 		dst = ipif->ipif_pp_dst_addr;
16802 
16803 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16804 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16805 	if (ire == NULL) {
16806 		/*
16807 		 * Mark this packet to make it be delivered to
16808 		 * ip_rput_forward after the new ire has been
16809 		 * created.
16810 		 */
16811 		mp->b_prev = NULL;
16812 		mp->b_next = mp;
16813 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16814 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16815 	} else {
16816 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16817 		IRE_REFRELE(ire);
16818 	}
16819 }
16820 
16821 /* Update any source route, record route or timestamp options */
16822 static int
16823 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16824 {
16825 	ipoptp_t	opts;
16826 	uchar_t		*opt;
16827 	uint8_t		optval;
16828 	uint8_t		optlen;
16829 	ipaddr_t	dst;
16830 	uint32_t	ts;
16831 	ire_t		*dst_ire = NULL;
16832 	ire_t		*tmp_ire = NULL;
16833 	timestruc_t	now;
16834 
16835 	ip2dbg(("ip_rput_forward_options\n"));
16836 	dst = ipha->ipha_dst;
16837 	for (optval = ipoptp_first(&opts, ipha);
16838 	    optval != IPOPT_EOL;
16839 	    optval = ipoptp_next(&opts)) {
16840 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16841 		opt = opts.ipoptp_cur;
16842 		optlen = opts.ipoptp_len;
16843 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16844 		    optval, opts.ipoptp_len));
16845 		switch (optval) {
16846 			uint32_t off;
16847 		case IPOPT_SSRR:
16848 		case IPOPT_LSRR:
16849 			/* Check if adminstratively disabled */
16850 			if (!ipst->ips_ip_forward_src_routed) {
16851 				if (ire->ire_stq != NULL) {
16852 					/*
16853 					 * Sent by forwarding path, and router
16854 					 * is global zone
16855 					 */
16856 					icmp_unreachable(ire->ire_stq, mp,
16857 					    ICMP_SOURCE_ROUTE_FAILED,
16858 					    GLOBAL_ZONEID, ipst);
16859 				} else {
16860 					ip0dbg(("ip_rput_forward_options: "
16861 					    "unable to send unreach\n"));
16862 					freemsg(mp);
16863 				}
16864 				return (-1);
16865 			}
16866 
16867 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16868 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16869 			if (dst_ire == NULL) {
16870 				/*
16871 				 * Must be partial since ip_rput_options
16872 				 * checked for strict.
16873 				 */
16874 				break;
16875 			}
16876 			off = opt[IPOPT_OFFSET];
16877 			off--;
16878 		redo_srr:
16879 			if (optlen < IP_ADDR_LEN ||
16880 			    off > optlen - IP_ADDR_LEN) {
16881 				/* End of source route */
16882 				ip1dbg((
16883 				    "ip_rput_forward_options: end of SR\n"));
16884 				ire_refrele(dst_ire);
16885 				break;
16886 			}
16887 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16888 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16889 			    IP_ADDR_LEN);
16890 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16891 			    ntohl(dst)));
16892 
16893 			/*
16894 			 * Check if our address is present more than
16895 			 * once as consecutive hops in source route.
16896 			 */
16897 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16898 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16899 			if (tmp_ire != NULL) {
16900 				ire_refrele(tmp_ire);
16901 				off += IP_ADDR_LEN;
16902 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16903 				goto redo_srr;
16904 			}
16905 			ipha->ipha_dst = dst;
16906 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16907 			ire_refrele(dst_ire);
16908 			break;
16909 		case IPOPT_RR:
16910 			off = opt[IPOPT_OFFSET];
16911 			off--;
16912 			if (optlen < IP_ADDR_LEN ||
16913 			    off > optlen - IP_ADDR_LEN) {
16914 				/* No more room - ignore */
16915 				ip1dbg((
16916 				    "ip_rput_forward_options: end of RR\n"));
16917 				break;
16918 			}
16919 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16920 			    IP_ADDR_LEN);
16921 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16922 			break;
16923 		case IPOPT_TS:
16924 			/* Insert timestamp if there is room */
16925 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16926 			case IPOPT_TS_TSONLY:
16927 				off = IPOPT_TS_TIMELEN;
16928 				break;
16929 			case IPOPT_TS_PRESPEC:
16930 			case IPOPT_TS_PRESPEC_RFC791:
16931 				/* Verify that the address matched */
16932 				off = opt[IPOPT_OFFSET] - 1;
16933 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16934 				dst_ire = ire_ctable_lookup(dst, 0,
16935 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16936 				    MATCH_IRE_TYPE, ipst);
16937 				if (dst_ire == NULL) {
16938 					/* Not for us */
16939 					break;
16940 				}
16941 				ire_refrele(dst_ire);
16942 				/* FALLTHRU */
16943 			case IPOPT_TS_TSANDADDR:
16944 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16945 				break;
16946 			default:
16947 				/*
16948 				 * ip_*put_options should have already
16949 				 * dropped this packet.
16950 				 */
16951 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16952 				    "unknown IT - bug in ip_rput_options?\n");
16953 				return (0);	/* Keep "lint" happy */
16954 			}
16955 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16956 				/* Increase overflow counter */
16957 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16958 				opt[IPOPT_POS_OV_FLG] =
16959 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16960 				    (off << 4));
16961 				break;
16962 			}
16963 			off = opt[IPOPT_OFFSET] - 1;
16964 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16965 			case IPOPT_TS_PRESPEC:
16966 			case IPOPT_TS_PRESPEC_RFC791:
16967 			case IPOPT_TS_TSANDADDR:
16968 				bcopy(&ire->ire_src_addr,
16969 				    (char *)opt + off, IP_ADDR_LEN);
16970 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16971 				/* FALLTHRU */
16972 			case IPOPT_TS_TSONLY:
16973 				off = opt[IPOPT_OFFSET] - 1;
16974 				/* Compute # of milliseconds since midnight */
16975 				gethrestime(&now);
16976 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16977 				    now.tv_nsec / (NANOSEC / MILLISEC);
16978 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16979 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16980 				break;
16981 			}
16982 			break;
16983 		}
16984 	}
16985 	return (0);
16986 }
16987 
16988 /*
16989  * This is called after processing at least one of AH/ESP headers.
16990  *
16991  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16992  * the actual, physical interface on which the packet was received,
16993  * but, when ip_strict_dst_multihoming is set to 1, could be the
16994  * interface which had the ipha_dst configured when the packet went
16995  * through ip_rput. The ill_index corresponding to the recv_ill
16996  * is saved in ipsec_in_rill_index
16997  */
16998 void
16999 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17000 {
17001 	mblk_t *mp;
17002 	ipaddr_t dst;
17003 	in6_addr_t *v6dstp;
17004 	ipha_t *ipha;
17005 	ip6_t *ip6h;
17006 	ipsec_in_t *ii;
17007 	boolean_t ill_need_rele = B_FALSE;
17008 	boolean_t rill_need_rele = B_FALSE;
17009 	boolean_t ire_need_rele = B_FALSE;
17010 	netstack_t	*ns;
17011 	ip_stack_t	*ipst;
17012 
17013 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17014 	ASSERT(ii->ipsec_in_ill_index != 0);
17015 	ns = ii->ipsec_in_ns;
17016 	ASSERT(ii->ipsec_in_ns != NULL);
17017 	ipst = ns->netstack_ip;
17018 
17019 	mp = ipsec_mp->b_cont;
17020 	ASSERT(mp != NULL);
17021 
17022 
17023 	if (ill == NULL) {
17024 		ASSERT(recv_ill == NULL);
17025 		/*
17026 		 * We need to get the original queue on which ip_rput_local
17027 		 * or ip_rput_data_v6 was called.
17028 		 */
17029 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17030 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17031 		ill_need_rele = B_TRUE;
17032 
17033 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17034 			recv_ill = ill_lookup_on_ifindex(
17035 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17036 			    NULL, NULL, NULL, NULL, ipst);
17037 			rill_need_rele = B_TRUE;
17038 		} else {
17039 			recv_ill = ill;
17040 		}
17041 
17042 		if ((ill == NULL) || (recv_ill == NULL)) {
17043 			ip0dbg(("ip_fanout_proto_again: interface "
17044 			    "disappeared\n"));
17045 			if (ill != NULL)
17046 				ill_refrele(ill);
17047 			if (recv_ill != NULL)
17048 				ill_refrele(recv_ill);
17049 			freemsg(ipsec_mp);
17050 			return;
17051 		}
17052 	}
17053 
17054 	ASSERT(ill != NULL && recv_ill != NULL);
17055 
17056 	if (mp->b_datap->db_type == M_CTL) {
17057 		/*
17058 		 * AH/ESP is returning the ICMP message after
17059 		 * removing their headers. Fanout again till
17060 		 * it gets to the right protocol.
17061 		 */
17062 		if (ii->ipsec_in_v4) {
17063 			icmph_t *icmph;
17064 			int iph_hdr_length;
17065 			int hdr_length;
17066 
17067 			ipha = (ipha_t *)mp->b_rptr;
17068 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17069 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17070 			ipha = (ipha_t *)&icmph[1];
17071 			hdr_length = IPH_HDR_LENGTH(ipha);
17072 			/*
17073 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17074 			 * Reset the type to M_DATA.
17075 			 */
17076 			mp->b_datap->db_type = M_DATA;
17077 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17078 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17079 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17080 		} else {
17081 			icmp6_t *icmp6;
17082 			int hdr_length;
17083 
17084 			ip6h = (ip6_t *)mp->b_rptr;
17085 			/* Don't call hdr_length_v6() unless you have to. */
17086 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17087 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17088 			else
17089 				hdr_length = IPV6_HDR_LEN;
17090 
17091 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17092 			/*
17093 			 * icmp_inbound_error_fanout_v6 may need to do
17094 			 * pullupmsg.  Reset the type to M_DATA.
17095 			 */
17096 			mp->b_datap->db_type = M_DATA;
17097 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17098 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17099 		}
17100 		if (ill_need_rele)
17101 			ill_refrele(ill);
17102 		if (rill_need_rele)
17103 			ill_refrele(recv_ill);
17104 		return;
17105 	}
17106 
17107 	if (ii->ipsec_in_v4) {
17108 		ipha = (ipha_t *)mp->b_rptr;
17109 		dst = ipha->ipha_dst;
17110 		if (CLASSD(dst)) {
17111 			/*
17112 			 * Multicast has to be delivered to all streams.
17113 			 */
17114 			dst = INADDR_BROADCAST;
17115 		}
17116 
17117 		if (ire == NULL) {
17118 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17119 			    MBLK_GETLABEL(mp), ipst);
17120 			if (ire == NULL) {
17121 				if (ill_need_rele)
17122 					ill_refrele(ill);
17123 				if (rill_need_rele)
17124 					ill_refrele(recv_ill);
17125 				ip1dbg(("ip_fanout_proto_again: "
17126 				    "IRE not found"));
17127 				freemsg(ipsec_mp);
17128 				return;
17129 			}
17130 			ire_need_rele = B_TRUE;
17131 		}
17132 
17133 		switch (ipha->ipha_protocol) {
17134 			case IPPROTO_UDP:
17135 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17136 				    recv_ill);
17137 				if (ire_need_rele)
17138 					ire_refrele(ire);
17139 				break;
17140 			case IPPROTO_TCP:
17141 				if (!ire_need_rele)
17142 					IRE_REFHOLD(ire);
17143 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17144 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17145 				IRE_REFRELE(ire);
17146 				if (mp != NULL)
17147 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17148 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17149 				break;
17150 			case IPPROTO_SCTP:
17151 				if (!ire_need_rele)
17152 					IRE_REFHOLD(ire);
17153 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17154 				    ipsec_mp, 0, ill->ill_rq, dst);
17155 				break;
17156 			default:
17157 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17158 				    recv_ill);
17159 				if (ire_need_rele)
17160 					ire_refrele(ire);
17161 				break;
17162 		}
17163 	} else {
17164 		uint32_t rput_flags = 0;
17165 
17166 		ip6h = (ip6_t *)mp->b_rptr;
17167 		v6dstp = &ip6h->ip6_dst;
17168 		/*
17169 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17170 		 * address.
17171 		 *
17172 		 * Currently, we don't store that state in the IPSEC_IN
17173 		 * message, and we may need to.
17174 		 */
17175 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17176 		    IP6_IN_LLMCAST : 0);
17177 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17178 		    NULL, NULL);
17179 	}
17180 	if (ill_need_rele)
17181 		ill_refrele(ill);
17182 	if (rill_need_rele)
17183 		ill_refrele(recv_ill);
17184 }
17185 
17186 /*
17187  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17188  * returns 'true' if there are still fragments left on the queue, in
17189  * which case we restart the timer.
17190  */
17191 void
17192 ill_frag_timer(void *arg)
17193 {
17194 	ill_t	*ill = (ill_t *)arg;
17195 	boolean_t frag_pending;
17196 	ip_stack_t	*ipst = ill->ill_ipst;
17197 
17198 	mutex_enter(&ill->ill_lock);
17199 	ASSERT(!ill->ill_fragtimer_executing);
17200 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17201 		ill->ill_frag_timer_id = 0;
17202 		mutex_exit(&ill->ill_lock);
17203 		return;
17204 	}
17205 	ill->ill_fragtimer_executing = 1;
17206 	mutex_exit(&ill->ill_lock);
17207 
17208 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17209 
17210 	/*
17211 	 * Restart the timer, if we have fragments pending or if someone
17212 	 * wanted us to be scheduled again.
17213 	 */
17214 	mutex_enter(&ill->ill_lock);
17215 	ill->ill_fragtimer_executing = 0;
17216 	ill->ill_frag_timer_id = 0;
17217 	if (frag_pending || ill->ill_fragtimer_needrestart)
17218 		ill_frag_timer_start(ill);
17219 	mutex_exit(&ill->ill_lock);
17220 }
17221 
17222 void
17223 ill_frag_timer_start(ill_t *ill)
17224 {
17225 	ip_stack_t	*ipst = ill->ill_ipst;
17226 
17227 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17228 
17229 	/* If the ill is closing or opening don't proceed */
17230 	if (ill->ill_state_flags & ILL_CONDEMNED)
17231 		return;
17232 
17233 	if (ill->ill_fragtimer_executing) {
17234 		/*
17235 		 * ill_frag_timer is currently executing. Just record the
17236 		 * the fact that we want the timer to be restarted.
17237 		 * ill_frag_timer will post a timeout before it returns,
17238 		 * ensuring it will be called again.
17239 		 */
17240 		ill->ill_fragtimer_needrestart = 1;
17241 		return;
17242 	}
17243 
17244 	if (ill->ill_frag_timer_id == 0) {
17245 		/*
17246 		 * The timer is neither running nor is the timeout handler
17247 		 * executing. Post a timeout so that ill_frag_timer will be
17248 		 * called
17249 		 */
17250 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17251 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17252 		ill->ill_fragtimer_needrestart = 0;
17253 	}
17254 }
17255 
17256 /*
17257  * This routine is needed for loopback when forwarding multicasts.
17258  *
17259  * IPQoS Notes:
17260  * IPPF processing is done in fanout routines.
17261  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17262  * processing for IPSec packets is done when it comes back in clear.
17263  * NOTE : The callers of this function need to do the ire_refrele for the
17264  *	  ire that is being passed in.
17265  */
17266 void
17267 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17268     ill_t *recv_ill)
17269 {
17270 	ill_t	*ill = (ill_t *)q->q_ptr;
17271 	uint32_t	sum;
17272 	uint32_t	u1;
17273 	uint32_t	u2;
17274 	int		hdr_length;
17275 	boolean_t	mctl_present;
17276 	mblk_t		*first_mp = mp;
17277 	mblk_t		*hada_mp = NULL;
17278 	ipha_t		*inner_ipha;
17279 	ip_stack_t	*ipst;
17280 
17281 	ASSERT(recv_ill != NULL);
17282 	ipst = recv_ill->ill_ipst;
17283 
17284 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17285 	    "ip_rput_locl_start: q %p", q);
17286 
17287 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17288 	ASSERT(ill != NULL);
17289 
17290 
17291 #define	rptr	((uchar_t *)ipha)
17292 #define	iphs	((uint16_t *)ipha)
17293 
17294 	/*
17295 	 * no UDP or TCP packet should come here anymore.
17296 	 */
17297 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17298 	    (ipha->ipha_protocol != IPPROTO_UDP));
17299 
17300 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17301 	if (mctl_present &&
17302 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17303 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17304 
17305 		/*
17306 		 * It's an IPsec accelerated packet.
17307 		 * Keep a pointer to the data attributes around until
17308 		 * we allocate the ipsec_info_t.
17309 		 */
17310 		IPSECHW_DEBUG(IPSECHW_PKT,
17311 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17312 		hada_mp = first_mp;
17313 		hada_mp->b_cont = NULL;
17314 		/*
17315 		 * Since it is accelerated, it comes directly from
17316 		 * the ill and the data attributes is followed by
17317 		 * the packet data.
17318 		 */
17319 		ASSERT(mp->b_datap->db_type != M_CTL);
17320 		first_mp = mp;
17321 		mctl_present = B_FALSE;
17322 	}
17323 
17324 	/*
17325 	 * IF M_CTL is not present, then ipsec_in_is_secure
17326 	 * should return B_TRUE. There is a case where loopback
17327 	 * packets has an M_CTL in the front with all the
17328 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17329 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17330 	 * packets never comes here, it is safe to ASSERT the
17331 	 * following.
17332 	 */
17333 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17334 
17335 
17336 	/* u1 is # words of IP options */
17337 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17338 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17339 
17340 	if (u1) {
17341 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17342 			if (hada_mp != NULL)
17343 				freemsg(hada_mp);
17344 			return;
17345 		}
17346 	} else {
17347 		/* Check the IP header checksum.  */
17348 #define	uph	((uint16_t *)ipha)
17349 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17350 		    uph[6] + uph[7] + uph[8] + uph[9];
17351 #undef  uph
17352 		/* finish doing IP checksum */
17353 		sum = (sum & 0xFFFF) + (sum >> 16);
17354 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17355 		/*
17356 		 * Don't verify header checksum if this packet is coming
17357 		 * back from AH/ESP as we already did it.
17358 		 */
17359 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17360 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17361 			goto drop_pkt;
17362 		}
17363 	}
17364 
17365 	/*
17366 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17367 	 * might be called more than once for secure packets, count only
17368 	 * the first time.
17369 	 */
17370 	if (!mctl_present) {
17371 		UPDATE_IB_PKT_COUNT(ire);
17372 		ire->ire_last_used_time = lbolt;
17373 	}
17374 
17375 	/* Check for fragmentation offset. */
17376 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17377 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17378 	if (u1) {
17379 		/*
17380 		 * We re-assemble fragments before we do the AH/ESP
17381 		 * processing. Thus, M_CTL should not be present
17382 		 * while we are re-assembling.
17383 		 */
17384 		ASSERT(!mctl_present);
17385 		ASSERT(first_mp == mp);
17386 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17387 			return;
17388 		}
17389 		/*
17390 		 * Make sure that first_mp points back to mp as
17391 		 * the mp we came in with could have changed in
17392 		 * ip_rput_fragment().
17393 		 */
17394 		ipha = (ipha_t *)mp->b_rptr;
17395 		first_mp = mp;
17396 	}
17397 
17398 	/*
17399 	 * Clear hardware checksumming flag as it is currently only
17400 	 * used by TCP and UDP.
17401 	 */
17402 	DB_CKSUMFLAGS(mp) = 0;
17403 
17404 	/* Now we have a complete datagram, destined for this machine. */
17405 	u1 = IPH_HDR_LENGTH(ipha);
17406 	switch (ipha->ipha_protocol) {
17407 	case IPPROTO_ICMP: {
17408 		ire_t		*ire_zone;
17409 		ilm_t		*ilm;
17410 		mblk_t		*mp1;
17411 		zoneid_t	last_zoneid;
17412 
17413 		if (CLASSD(ipha->ipha_dst) &&
17414 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17415 			ASSERT(ire->ire_type == IRE_BROADCAST);
17416 			/*
17417 			 * In the multicast case, applications may have joined
17418 			 * the group from different zones, so we need to deliver
17419 			 * the packet to each of them. Loop through the
17420 			 * multicast memberships structures (ilm) on the receive
17421 			 * ill and send a copy of the packet up each matching
17422 			 * one. However, we don't do this for multicasts sent on
17423 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17424 			 * they must stay in the sender's zone.
17425 			 *
17426 			 * ilm_add_v6() ensures that ilms in the same zone are
17427 			 * contiguous in the ill_ilm list. We use this property
17428 			 * to avoid sending duplicates needed when two
17429 			 * applications in the same zone join the same group on
17430 			 * different logical interfaces: we ignore the ilm if
17431 			 * its zoneid is the same as the last matching one.
17432 			 * In addition, the sending of the packet for
17433 			 * ire_zoneid is delayed until all of the other ilms
17434 			 * have been exhausted.
17435 			 */
17436 			last_zoneid = -1;
17437 			ILM_WALKER_HOLD(recv_ill);
17438 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17439 			    ilm = ilm->ilm_next) {
17440 				if ((ilm->ilm_flags & ILM_DELETED) ||
17441 				    ipha->ipha_dst != ilm->ilm_addr ||
17442 				    ilm->ilm_zoneid == last_zoneid ||
17443 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17444 				    ilm->ilm_zoneid == ALL_ZONES ||
17445 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17446 					continue;
17447 				mp1 = ip_copymsg(first_mp);
17448 				if (mp1 == NULL)
17449 					continue;
17450 				icmp_inbound(q, mp1, B_TRUE, ill,
17451 				    0, sum, mctl_present, B_TRUE,
17452 				    recv_ill, ilm->ilm_zoneid);
17453 				last_zoneid = ilm->ilm_zoneid;
17454 			}
17455 			ILM_WALKER_RELE(recv_ill);
17456 		} else if (ire->ire_type == IRE_BROADCAST) {
17457 			/*
17458 			 * In the broadcast case, there may be many zones
17459 			 * which need a copy of the packet delivered to them.
17460 			 * There is one IRE_BROADCAST per broadcast address
17461 			 * and per zone; we walk those using a helper function.
17462 			 * In addition, the sending of the packet for ire is
17463 			 * delayed until all of the other ires have been
17464 			 * processed.
17465 			 */
17466 			IRB_REFHOLD(ire->ire_bucket);
17467 			ire_zone = NULL;
17468 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17469 			    ire)) != NULL) {
17470 				mp1 = ip_copymsg(first_mp);
17471 				if (mp1 == NULL)
17472 					continue;
17473 
17474 				UPDATE_IB_PKT_COUNT(ire_zone);
17475 				ire_zone->ire_last_used_time = lbolt;
17476 				icmp_inbound(q, mp1, B_TRUE, ill,
17477 				    0, sum, mctl_present, B_TRUE,
17478 				    recv_ill, ire_zone->ire_zoneid);
17479 			}
17480 			IRB_REFRELE(ire->ire_bucket);
17481 		}
17482 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17483 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17484 		    ire->ire_zoneid);
17485 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17486 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17487 		return;
17488 	}
17489 	case IPPROTO_IGMP:
17490 		/*
17491 		 * If we are not willing to accept IGMP packets in clear,
17492 		 * then check with global policy.
17493 		 */
17494 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17495 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17496 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17497 			if (first_mp == NULL)
17498 				return;
17499 		}
17500 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17501 			freemsg(first_mp);
17502 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17503 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17504 			return;
17505 		}
17506 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17507 			/* Bad packet - discarded by igmp_input */
17508 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17509 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17510 			if (mctl_present)
17511 				freeb(first_mp);
17512 			return;
17513 		}
17514 		/*
17515 		 * igmp_input() may have returned the pulled up message.
17516 		 * So first_mp and ipha need to be reinitialized.
17517 		 */
17518 		ipha = (ipha_t *)mp->b_rptr;
17519 		if (mctl_present)
17520 			first_mp->b_cont = mp;
17521 		else
17522 			first_mp = mp;
17523 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17524 		    connf_head != NULL) {
17525 			/* No user-level listener for IGMP packets */
17526 			goto drop_pkt;
17527 		}
17528 		/* deliver to local raw users */
17529 		break;
17530 	case IPPROTO_PIM:
17531 		/*
17532 		 * If we are not willing to accept PIM packets in clear,
17533 		 * then check with global policy.
17534 		 */
17535 		if (ipst->ips_pim_accept_clear_messages == 0) {
17536 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17537 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17538 			if (first_mp == NULL)
17539 				return;
17540 		}
17541 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17542 			freemsg(first_mp);
17543 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17544 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17545 			return;
17546 		}
17547 		if (pim_input(q, mp, ill) != 0) {
17548 			/* Bad packet - discarded by pim_input */
17549 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17550 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17551 			if (mctl_present)
17552 				freeb(first_mp);
17553 			return;
17554 		}
17555 
17556 		/*
17557 		 * pim_input() may have pulled up the message so ipha needs to
17558 		 * be reinitialized.
17559 		 */
17560 		ipha = (ipha_t *)mp->b_rptr;
17561 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17562 		    connf_head != NULL) {
17563 			/* No user-level listener for PIM packets */
17564 			goto drop_pkt;
17565 		}
17566 		/* deliver to local raw users */
17567 		break;
17568 	case IPPROTO_ENCAP:
17569 		/*
17570 		 * Handle self-encapsulated packets (IP-in-IP where
17571 		 * the inner addresses == the outer addresses).
17572 		 */
17573 		hdr_length = IPH_HDR_LENGTH(ipha);
17574 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17575 		    mp->b_wptr) {
17576 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17577 			    sizeof (ipha_t) - mp->b_rptr)) {
17578 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17579 				freemsg(first_mp);
17580 				return;
17581 			}
17582 			ipha = (ipha_t *)mp->b_rptr;
17583 		}
17584 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17585 		/*
17586 		 * Check the sanity of the inner IP header.
17587 		 */
17588 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17589 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17590 			freemsg(first_mp);
17591 			return;
17592 		}
17593 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17594 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17595 			freemsg(first_mp);
17596 			return;
17597 		}
17598 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17599 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17600 			ipsec_in_t *ii;
17601 
17602 			/*
17603 			 * Self-encapsulated tunnel packet. Remove
17604 			 * the outer IP header and fanout again.
17605 			 * We also need to make sure that the inner
17606 			 * header is pulled up until options.
17607 			 */
17608 			mp->b_rptr = (uchar_t *)inner_ipha;
17609 			ipha = inner_ipha;
17610 			hdr_length = IPH_HDR_LENGTH(ipha);
17611 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17612 				if (!pullupmsg(mp, (uchar_t *)ipha +
17613 				    + hdr_length - mp->b_rptr)) {
17614 					freemsg(first_mp);
17615 					return;
17616 				}
17617 				ipha = (ipha_t *)mp->b_rptr;
17618 			}
17619 			if (!mctl_present) {
17620 				ASSERT(first_mp == mp);
17621 				/*
17622 				 * This means that somebody is sending
17623 				 * Self-encapsualted packets without AH/ESP.
17624 				 * If AH/ESP was present, we would have already
17625 				 * allocated the first_mp.
17626 				 */
17627 				first_mp = ipsec_in_alloc(B_TRUE,
17628 				    ipst->ips_netstack);
17629 				if (first_mp == NULL) {
17630 					ip1dbg(("ip_proto_input: IPSEC_IN "
17631 					    "allocation failure.\n"));
17632 					BUMP_MIB(ill->ill_ip_mib,
17633 					    ipIfStatsInDiscards);
17634 					freemsg(mp);
17635 					return;
17636 				}
17637 				first_mp->b_cont = mp;
17638 			}
17639 			/*
17640 			 * We generally store the ill_index if we need to
17641 			 * do IPSEC processing as we lose the ill queue when
17642 			 * we come back. But in this case, we never should
17643 			 * have to store the ill_index here as it should have
17644 			 * been stored previously when we processed the
17645 			 * AH/ESP header in this routine or for non-ipsec
17646 			 * cases, we still have the queue. But for some bad
17647 			 * packets from the wire, we can get to IPSEC after
17648 			 * this and we better store the index for that case.
17649 			 */
17650 			ill = (ill_t *)q->q_ptr;
17651 			ii = (ipsec_in_t *)first_mp->b_rptr;
17652 			ii->ipsec_in_ill_index =
17653 			    ill->ill_phyint->phyint_ifindex;
17654 			ii->ipsec_in_rill_index =
17655 			    recv_ill->ill_phyint->phyint_ifindex;
17656 			if (ii->ipsec_in_decaps) {
17657 				/*
17658 				 * This packet is self-encapsulated multiple
17659 				 * times. We don't want to recurse infinitely.
17660 				 * To keep it simple, drop the packet.
17661 				 */
17662 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17663 				freemsg(first_mp);
17664 				return;
17665 			}
17666 			ii->ipsec_in_decaps = B_TRUE;
17667 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17668 			    ire);
17669 			return;
17670 		}
17671 		break;
17672 	case IPPROTO_AH:
17673 	case IPPROTO_ESP: {
17674 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17675 
17676 		/*
17677 		 * Fast path for AH/ESP. If this is the first time
17678 		 * we are sending a datagram to AH/ESP, allocate
17679 		 * a IPSEC_IN message and prepend it. Otherwise,
17680 		 * just fanout.
17681 		 */
17682 
17683 		int ipsec_rc;
17684 		ipsec_in_t *ii;
17685 		netstack_t *ns = ipst->ips_netstack;
17686 
17687 		IP_STAT(ipst, ipsec_proto_ahesp);
17688 		if (!mctl_present) {
17689 			ASSERT(first_mp == mp);
17690 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17691 			if (first_mp == NULL) {
17692 				ip1dbg(("ip_proto_input: IPSEC_IN "
17693 				    "allocation failure.\n"));
17694 				freemsg(hada_mp); /* okay ifnull */
17695 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17696 				freemsg(mp);
17697 				return;
17698 			}
17699 			/*
17700 			 * Store the ill_index so that when we come back
17701 			 * from IPSEC we ride on the same queue.
17702 			 */
17703 			ill = (ill_t *)q->q_ptr;
17704 			ii = (ipsec_in_t *)first_mp->b_rptr;
17705 			ii->ipsec_in_ill_index =
17706 			    ill->ill_phyint->phyint_ifindex;
17707 			ii->ipsec_in_rill_index =
17708 			    recv_ill->ill_phyint->phyint_ifindex;
17709 			first_mp->b_cont = mp;
17710 			/*
17711 			 * Cache hardware acceleration info.
17712 			 */
17713 			if (hada_mp != NULL) {
17714 				IPSECHW_DEBUG(IPSECHW_PKT,
17715 				    ("ip_rput_local: caching data attr.\n"));
17716 				ii->ipsec_in_accelerated = B_TRUE;
17717 				ii->ipsec_in_da = hada_mp;
17718 				hada_mp = NULL;
17719 			}
17720 		} else {
17721 			ii = (ipsec_in_t *)first_mp->b_rptr;
17722 		}
17723 
17724 		if (!ipsec_loaded(ipss)) {
17725 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17726 			    ire->ire_zoneid, ipst);
17727 			return;
17728 		}
17729 
17730 		ns = ipst->ips_netstack;
17731 		/* select inbound SA and have IPsec process the pkt */
17732 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17733 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17734 			if (esph == NULL)
17735 				return;
17736 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17737 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17738 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17739 			    first_mp, esph);
17740 		} else {
17741 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17742 			if (ah == NULL)
17743 				return;
17744 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17745 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17746 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17747 			    first_mp, ah);
17748 		}
17749 
17750 		switch (ipsec_rc) {
17751 		case IPSEC_STATUS_SUCCESS:
17752 			break;
17753 		case IPSEC_STATUS_FAILED:
17754 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17755 			/* FALLTHRU */
17756 		case IPSEC_STATUS_PENDING:
17757 			return;
17758 		}
17759 		/* we're done with IPsec processing, send it up */
17760 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17761 		return;
17762 	}
17763 	default:
17764 		break;
17765 	}
17766 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17767 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17768 		    ire->ire_zoneid));
17769 		goto drop_pkt;
17770 	}
17771 	/*
17772 	 * Handle protocols with which IP is less intimate.  There
17773 	 * can be more than one stream bound to a particular
17774 	 * protocol.  When this is the case, each one gets a copy
17775 	 * of any incoming packets.
17776 	 */
17777 	ip_fanout_proto(q, first_mp, ill, ipha,
17778 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17779 	    B_TRUE, recv_ill, ire->ire_zoneid);
17780 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17781 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17782 	return;
17783 
17784 drop_pkt:
17785 	freemsg(first_mp);
17786 	if (hada_mp != NULL)
17787 		freeb(hada_mp);
17788 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17789 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17790 #undef	rptr
17791 #undef  iphs
17792 
17793 }
17794 
17795 /*
17796  * Update any source route, record route or timestamp options.
17797  * Check that we are at end of strict source route.
17798  * The options have already been checked for sanity in ip_rput_options().
17799  */
17800 static boolean_t
17801 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17802     ip_stack_t *ipst)
17803 {
17804 	ipoptp_t	opts;
17805 	uchar_t		*opt;
17806 	uint8_t		optval;
17807 	uint8_t		optlen;
17808 	ipaddr_t	dst;
17809 	uint32_t	ts;
17810 	ire_t		*dst_ire;
17811 	timestruc_t	now;
17812 	zoneid_t	zoneid;
17813 	ill_t		*ill;
17814 
17815 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17816 
17817 	ip2dbg(("ip_rput_local_options\n"));
17818 
17819 	for (optval = ipoptp_first(&opts, ipha);
17820 	    optval != IPOPT_EOL;
17821 	    optval = ipoptp_next(&opts)) {
17822 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17823 		opt = opts.ipoptp_cur;
17824 		optlen = opts.ipoptp_len;
17825 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17826 		    optval, optlen));
17827 		switch (optval) {
17828 			uint32_t off;
17829 		case IPOPT_SSRR:
17830 		case IPOPT_LSRR:
17831 			off = opt[IPOPT_OFFSET];
17832 			off--;
17833 			if (optlen < IP_ADDR_LEN ||
17834 			    off > optlen - IP_ADDR_LEN) {
17835 				/* End of source route */
17836 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17837 				break;
17838 			}
17839 			/*
17840 			 * This will only happen if two consecutive entries
17841 			 * in the source route contains our address or if
17842 			 * it is a packet with a loose source route which
17843 			 * reaches us before consuming the whole source route
17844 			 */
17845 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17846 			if (optval == IPOPT_SSRR) {
17847 				goto bad_src_route;
17848 			}
17849 			/*
17850 			 * Hack: instead of dropping the packet truncate the
17851 			 * source route to what has been used by filling the
17852 			 * rest with IPOPT_NOP.
17853 			 */
17854 			opt[IPOPT_OLEN] = (uint8_t)off;
17855 			while (off < optlen) {
17856 				opt[off++] = IPOPT_NOP;
17857 			}
17858 			break;
17859 		case IPOPT_RR:
17860 			off = opt[IPOPT_OFFSET];
17861 			off--;
17862 			if (optlen < IP_ADDR_LEN ||
17863 			    off > optlen - IP_ADDR_LEN) {
17864 				/* No more room - ignore */
17865 				ip1dbg((
17866 				    "ip_rput_local_options: end of RR\n"));
17867 				break;
17868 			}
17869 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17870 			    IP_ADDR_LEN);
17871 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17872 			break;
17873 		case IPOPT_TS:
17874 			/* Insert timestamp if there is romm */
17875 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17876 			case IPOPT_TS_TSONLY:
17877 				off = IPOPT_TS_TIMELEN;
17878 				break;
17879 			case IPOPT_TS_PRESPEC:
17880 			case IPOPT_TS_PRESPEC_RFC791:
17881 				/* Verify that the address matched */
17882 				off = opt[IPOPT_OFFSET] - 1;
17883 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17884 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17885 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17886 				    ipst);
17887 				if (dst_ire == NULL) {
17888 					/* Not for us */
17889 					break;
17890 				}
17891 				ire_refrele(dst_ire);
17892 				/* FALLTHRU */
17893 			case IPOPT_TS_TSANDADDR:
17894 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17895 				break;
17896 			default:
17897 				/*
17898 				 * ip_*put_options should have already
17899 				 * dropped this packet.
17900 				 */
17901 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17902 				    "unknown IT - bug in ip_rput_options?\n");
17903 				return (B_TRUE);	/* Keep "lint" happy */
17904 			}
17905 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17906 				/* Increase overflow counter */
17907 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17908 				opt[IPOPT_POS_OV_FLG] =
17909 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17910 				    (off << 4));
17911 				break;
17912 			}
17913 			off = opt[IPOPT_OFFSET] - 1;
17914 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17915 			case IPOPT_TS_PRESPEC:
17916 			case IPOPT_TS_PRESPEC_RFC791:
17917 			case IPOPT_TS_TSANDADDR:
17918 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17919 				    IP_ADDR_LEN);
17920 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17921 				/* FALLTHRU */
17922 			case IPOPT_TS_TSONLY:
17923 				off = opt[IPOPT_OFFSET] - 1;
17924 				/* Compute # of milliseconds since midnight */
17925 				gethrestime(&now);
17926 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17927 				    now.tv_nsec / (NANOSEC / MILLISEC);
17928 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17929 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17930 				break;
17931 			}
17932 			break;
17933 		}
17934 	}
17935 	return (B_TRUE);
17936 
17937 bad_src_route:
17938 	q = WR(q);
17939 	if (q->q_next != NULL)
17940 		ill = q->q_ptr;
17941 	else
17942 		ill = NULL;
17943 
17944 	/* make sure we clear any indication of a hardware checksum */
17945 	DB_CKSUMFLAGS(mp) = 0;
17946 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17947 	if (zoneid == ALL_ZONES)
17948 		freemsg(mp);
17949 	else
17950 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17951 	return (B_FALSE);
17952 
17953 }
17954 
17955 /*
17956  * Process IP options in an inbound packet.  If an option affects the
17957  * effective destination address, return the next hop address via dstp.
17958  * Returns -1 if something fails in which case an ICMP error has been sent
17959  * and mp freed.
17960  */
17961 static int
17962 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17963     ip_stack_t *ipst)
17964 {
17965 	ipoptp_t	opts;
17966 	uchar_t		*opt;
17967 	uint8_t		optval;
17968 	uint8_t		optlen;
17969 	ipaddr_t	dst;
17970 	intptr_t	code = 0;
17971 	ire_t		*ire = NULL;
17972 	zoneid_t	zoneid;
17973 	ill_t		*ill;
17974 
17975 	ip2dbg(("ip_rput_options\n"));
17976 	dst = ipha->ipha_dst;
17977 	for (optval = ipoptp_first(&opts, ipha);
17978 	    optval != IPOPT_EOL;
17979 	    optval = ipoptp_next(&opts)) {
17980 		opt = opts.ipoptp_cur;
17981 		optlen = opts.ipoptp_len;
17982 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17983 		    optval, optlen));
17984 		/*
17985 		 * Note: we need to verify the checksum before we
17986 		 * modify anything thus this routine only extracts the next
17987 		 * hop dst from any source route.
17988 		 */
17989 		switch (optval) {
17990 			uint32_t off;
17991 		case IPOPT_SSRR:
17992 		case IPOPT_LSRR:
17993 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17994 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17995 			if (ire == NULL) {
17996 				if (optval == IPOPT_SSRR) {
17997 					ip1dbg(("ip_rput_options: not next"
17998 					    " strict source route 0x%x\n",
17999 					    ntohl(dst)));
18000 					code = (char *)&ipha->ipha_dst -
18001 					    (char *)ipha;
18002 					goto param_prob; /* RouterReq's */
18003 				}
18004 				ip2dbg(("ip_rput_options: "
18005 				    "not next source route 0x%x\n",
18006 				    ntohl(dst)));
18007 				break;
18008 			}
18009 			ire_refrele(ire);
18010 
18011 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18012 				ip1dbg((
18013 				    "ip_rput_options: bad option offset\n"));
18014 				code = (char *)&opt[IPOPT_OLEN] -
18015 				    (char *)ipha;
18016 				goto param_prob;
18017 			}
18018 			off = opt[IPOPT_OFFSET];
18019 			off--;
18020 		redo_srr:
18021 			if (optlen < IP_ADDR_LEN ||
18022 			    off > optlen - IP_ADDR_LEN) {
18023 				/* End of source route */
18024 				ip1dbg(("ip_rput_options: end of SR\n"));
18025 				break;
18026 			}
18027 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18028 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18029 			    ntohl(dst)));
18030 
18031 			/*
18032 			 * Check if our address is present more than
18033 			 * once as consecutive hops in source route.
18034 			 * XXX verify per-interface ip_forwarding
18035 			 * for source route?
18036 			 */
18037 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18038 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18039 
18040 			if (ire != NULL) {
18041 				ire_refrele(ire);
18042 				off += IP_ADDR_LEN;
18043 				goto redo_srr;
18044 			}
18045 
18046 			if (dst == htonl(INADDR_LOOPBACK)) {
18047 				ip1dbg(("ip_rput_options: loopback addr in "
18048 				    "source route!\n"));
18049 				goto bad_src_route;
18050 			}
18051 			/*
18052 			 * For strict: verify that dst is directly
18053 			 * reachable.
18054 			 */
18055 			if (optval == IPOPT_SSRR) {
18056 				ire = ire_ftable_lookup(dst, 0, 0,
18057 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18058 				    MBLK_GETLABEL(mp),
18059 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18060 				if (ire == NULL) {
18061 					ip1dbg(("ip_rput_options: SSRR not "
18062 					    "directly reachable: 0x%x\n",
18063 					    ntohl(dst)));
18064 					goto bad_src_route;
18065 				}
18066 				ire_refrele(ire);
18067 			}
18068 			/*
18069 			 * Defer update of the offset and the record route
18070 			 * until the packet is forwarded.
18071 			 */
18072 			break;
18073 		case IPOPT_RR:
18074 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18075 				ip1dbg((
18076 				    "ip_rput_options: bad option offset\n"));
18077 				code = (char *)&opt[IPOPT_OLEN] -
18078 				    (char *)ipha;
18079 				goto param_prob;
18080 			}
18081 			break;
18082 		case IPOPT_TS:
18083 			/*
18084 			 * Verify that length >= 5 and that there is either
18085 			 * room for another timestamp or that the overflow
18086 			 * counter is not maxed out.
18087 			 */
18088 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18089 			if (optlen < IPOPT_MINLEN_IT) {
18090 				goto param_prob;
18091 			}
18092 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18093 				ip1dbg((
18094 				    "ip_rput_options: bad option offset\n"));
18095 				code = (char *)&opt[IPOPT_OFFSET] -
18096 				    (char *)ipha;
18097 				goto param_prob;
18098 			}
18099 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18100 			case IPOPT_TS_TSONLY:
18101 				off = IPOPT_TS_TIMELEN;
18102 				break;
18103 			case IPOPT_TS_TSANDADDR:
18104 			case IPOPT_TS_PRESPEC:
18105 			case IPOPT_TS_PRESPEC_RFC791:
18106 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18107 				break;
18108 			default:
18109 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18110 				    (char *)ipha;
18111 				goto param_prob;
18112 			}
18113 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18114 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18115 				/*
18116 				 * No room and the overflow counter is 15
18117 				 * already.
18118 				 */
18119 				goto param_prob;
18120 			}
18121 			break;
18122 		}
18123 	}
18124 
18125 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18126 		*dstp = dst;
18127 		return (0);
18128 	}
18129 
18130 	ip1dbg(("ip_rput_options: error processing IP options."));
18131 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18132 
18133 param_prob:
18134 	q = WR(q);
18135 	if (q->q_next != NULL)
18136 		ill = q->q_ptr;
18137 	else
18138 		ill = NULL;
18139 
18140 	/* make sure we clear any indication of a hardware checksum */
18141 	DB_CKSUMFLAGS(mp) = 0;
18142 	/* Don't know whether this is for non-global or global/forwarding */
18143 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18144 	if (zoneid == ALL_ZONES)
18145 		freemsg(mp);
18146 	else
18147 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18148 	return (-1);
18149 
18150 bad_src_route:
18151 	q = WR(q);
18152 	if (q->q_next != NULL)
18153 		ill = q->q_ptr;
18154 	else
18155 		ill = NULL;
18156 
18157 	/* make sure we clear any indication of a hardware checksum */
18158 	DB_CKSUMFLAGS(mp) = 0;
18159 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18160 	if (zoneid == ALL_ZONES)
18161 		freemsg(mp);
18162 	else
18163 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18164 	return (-1);
18165 }
18166 
18167 /*
18168  * IP & ICMP info in >=14 msg's ...
18169  *  - ip fixed part (mib2_ip_t)
18170  *  - icmp fixed part (mib2_icmp_t)
18171  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18172  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18173  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18174  *  - ipRouteAttributeTable (ip 102)	labeled routes
18175  *  - ip multicast membership (ip_member_t)
18176  *  - ip multicast source filtering (ip_grpsrc_t)
18177  *  - igmp fixed part (struct igmpstat)
18178  *  - multicast routing stats (struct mrtstat)
18179  *  - multicast routing vifs (array of struct vifctl)
18180  *  - multicast routing routes (array of struct mfcctl)
18181  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18182  *					One per ill plus one generic
18183  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18184  *					One per ill plus one generic
18185  *  - ipv6RouteEntry			all IPv6 IREs
18186  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18187  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18188  *  - ipv6AddrEntry			all IPv6 ipifs
18189  *  - ipv6 multicast membership (ipv6_member_t)
18190  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18191  *
18192  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18193  *
18194  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18195  * already filled in by the caller.
18196  * Return value of 0 indicates that no messages were sent and caller
18197  * should free mpctl.
18198  */
18199 int
18200 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18201 {
18202 	ip_stack_t *ipst;
18203 	sctp_stack_t *sctps;
18204 
18205 
18206 	if (q->q_next != NULL) {
18207 		ipst = ILLQ_TO_IPST(q);
18208 	} else {
18209 		ipst = CONNQ_TO_IPST(q);
18210 	}
18211 	ASSERT(ipst != NULL);
18212 	sctps = ipst->ips_netstack->netstack_sctp;
18213 
18214 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18215 		return (0);
18216 	}
18217 
18218 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18219 	    ipst)) == NULL) {
18220 		return (1);
18221 	}
18222 
18223 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18224 		return (1);
18225 	}
18226 
18227 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18228 		return (1);
18229 	}
18230 
18231 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18232 		return (1);
18233 	}
18234 
18235 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18236 		return (1);
18237 	}
18238 
18239 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18240 		return (1);
18241 	}
18242 
18243 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18244 		return (1);
18245 	}
18246 
18247 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18248 		return (1);
18249 	}
18250 
18251 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18252 		return (1);
18253 	}
18254 
18255 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18256 		return (1);
18257 	}
18258 
18259 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18260 		return (1);
18261 	}
18262 
18263 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18264 		return (1);
18265 	}
18266 
18267 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18268 		return (1);
18269 	}
18270 
18271 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18272 		return (1);
18273 	}
18274 
18275 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18276 		return (1);
18277 	}
18278 
18279 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18280 	if (mpctl == NULL) {
18281 		return (1);
18282 	}
18283 
18284 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18285 		return (1);
18286 	}
18287 	freemsg(mpctl);
18288 	return (1);
18289 }
18290 
18291 
18292 /* Get global (legacy) IPv4 statistics */
18293 static mblk_t *
18294 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18295     ip_stack_t *ipst)
18296 {
18297 	mib2_ip_t		old_ip_mib;
18298 	struct opthdr		*optp;
18299 	mblk_t			*mp2ctl;
18300 
18301 	/*
18302 	 * make a copy of the original message
18303 	 */
18304 	mp2ctl = copymsg(mpctl);
18305 
18306 	/* fixed length IP structure... */
18307 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18308 	optp->level = MIB2_IP;
18309 	optp->name = 0;
18310 	SET_MIB(old_ip_mib.ipForwarding,
18311 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18312 	SET_MIB(old_ip_mib.ipDefaultTTL,
18313 	    (uint32_t)ipst->ips_ip_def_ttl);
18314 	SET_MIB(old_ip_mib.ipReasmTimeout,
18315 	    ipst->ips_ip_g_frag_timeout);
18316 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18317 	    sizeof (mib2_ipAddrEntry_t));
18318 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18319 	    sizeof (mib2_ipRouteEntry_t));
18320 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18321 	    sizeof (mib2_ipNetToMediaEntry_t));
18322 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18323 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18324 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18325 	    sizeof (mib2_ipAttributeEntry_t));
18326 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18327 
18328 	/*
18329 	 * Grab the statistics from the new IP MIB
18330 	 */
18331 	SET_MIB(old_ip_mib.ipInReceives,
18332 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18333 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18334 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18335 	SET_MIB(old_ip_mib.ipForwDatagrams,
18336 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18337 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18338 	    ipmib->ipIfStatsInUnknownProtos);
18339 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18340 	SET_MIB(old_ip_mib.ipInDelivers,
18341 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18342 	SET_MIB(old_ip_mib.ipOutRequests,
18343 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18344 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18345 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18346 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18347 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18348 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18349 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18350 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18351 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18352 
18353 	/* ipRoutingDiscards is not being used */
18354 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18355 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18356 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18357 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18358 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18359 	    ipmib->ipIfStatsReasmDuplicates);
18360 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18361 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18362 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18363 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18364 	SET_MIB(old_ip_mib.rawipInOverflows,
18365 	    ipmib->rawipIfStatsInOverflows);
18366 
18367 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18368 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18369 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18370 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18371 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18372 	    ipmib->ipIfStatsOutSwitchIPVersion);
18373 
18374 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18375 	    (int)sizeof (old_ip_mib))) {
18376 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18377 		    (uint_t)sizeof (old_ip_mib)));
18378 	}
18379 
18380 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18381 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18382 	    (int)optp->level, (int)optp->name, (int)optp->len));
18383 	qreply(q, mpctl);
18384 	return (mp2ctl);
18385 }
18386 
18387 /* Per interface IPv4 statistics */
18388 static mblk_t *
18389 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18390 {
18391 	struct opthdr		*optp;
18392 	mblk_t			*mp2ctl;
18393 	ill_t			*ill;
18394 	ill_walk_context_t	ctx;
18395 	mblk_t			*mp_tail = NULL;
18396 	mib2_ipIfStatsEntry_t	global_ip_mib;
18397 
18398 	/*
18399 	 * Make a copy of the original message
18400 	 */
18401 	mp2ctl = copymsg(mpctl);
18402 
18403 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18404 	optp->level = MIB2_IP;
18405 	optp->name = MIB2_IP_TRAFFIC_STATS;
18406 	/* Include "unknown interface" ip_mib */
18407 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18408 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18409 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18410 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18411 	    (ipst->ips_ip_g_forward ? 1 : 2));
18412 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18413 	    (uint32_t)ipst->ips_ip_def_ttl);
18414 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18415 	    sizeof (mib2_ipIfStatsEntry_t));
18416 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18417 	    sizeof (mib2_ipAddrEntry_t));
18418 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18419 	    sizeof (mib2_ipRouteEntry_t));
18420 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18421 	    sizeof (mib2_ipNetToMediaEntry_t));
18422 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18423 	    sizeof (ip_member_t));
18424 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18425 	    sizeof (ip_grpsrc_t));
18426 
18427 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18428 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18429 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18430 		    "failed to allocate %u bytes\n",
18431 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18432 	}
18433 
18434 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18435 
18436 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18437 	ill = ILL_START_WALK_V4(&ctx, ipst);
18438 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18439 		ill->ill_ip_mib->ipIfStatsIfIndex =
18440 		    ill->ill_phyint->phyint_ifindex;
18441 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18442 		    (ipst->ips_ip_g_forward ? 1 : 2));
18443 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18444 		    (uint32_t)ipst->ips_ip_def_ttl);
18445 
18446 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18447 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18448 		    (char *)ill->ill_ip_mib,
18449 		    (int)sizeof (*ill->ill_ip_mib))) {
18450 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18451 			    "failed to allocate %u bytes\n",
18452 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18453 		}
18454 	}
18455 	rw_exit(&ipst->ips_ill_g_lock);
18456 
18457 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18458 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18459 	    "level %d, name %d, len %d\n",
18460 	    (int)optp->level, (int)optp->name, (int)optp->len));
18461 	qreply(q, mpctl);
18462 
18463 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18464 }
18465 
18466 /* Global IPv4 ICMP statistics */
18467 static mblk_t *
18468 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18469 {
18470 	struct opthdr		*optp;
18471 	mblk_t			*mp2ctl;
18472 
18473 	/*
18474 	 * Make a copy of the original message
18475 	 */
18476 	mp2ctl = copymsg(mpctl);
18477 
18478 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18479 	optp->level = MIB2_ICMP;
18480 	optp->name = 0;
18481 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18482 	    (int)sizeof (ipst->ips_icmp_mib))) {
18483 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18484 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18485 	}
18486 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18487 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18488 	    (int)optp->level, (int)optp->name, (int)optp->len));
18489 	qreply(q, mpctl);
18490 	return (mp2ctl);
18491 }
18492 
18493 /* Global IPv4 IGMP statistics */
18494 static mblk_t *
18495 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18496 {
18497 	struct opthdr		*optp;
18498 	mblk_t			*mp2ctl;
18499 
18500 	/*
18501 	 * make a copy of the original message
18502 	 */
18503 	mp2ctl = copymsg(mpctl);
18504 
18505 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18506 	optp->level = EXPER_IGMP;
18507 	optp->name = 0;
18508 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18509 	    (int)sizeof (ipst->ips_igmpstat))) {
18510 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18511 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18512 	}
18513 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18514 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18515 	    (int)optp->level, (int)optp->name, (int)optp->len));
18516 	qreply(q, mpctl);
18517 	return (mp2ctl);
18518 }
18519 
18520 /* Global IPv4 Multicast Routing statistics */
18521 static mblk_t *
18522 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18523 {
18524 	struct opthdr		*optp;
18525 	mblk_t			*mp2ctl;
18526 
18527 	/*
18528 	 * make a copy of the original message
18529 	 */
18530 	mp2ctl = copymsg(mpctl);
18531 
18532 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18533 	optp->level = EXPER_DVMRP;
18534 	optp->name = 0;
18535 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18536 		ip0dbg(("ip_mroute_stats: failed\n"));
18537 	}
18538 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18539 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18540 	    (int)optp->level, (int)optp->name, (int)optp->len));
18541 	qreply(q, mpctl);
18542 	return (mp2ctl);
18543 }
18544 
18545 /* IPv4 address information */
18546 static mblk_t *
18547 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18548 {
18549 	struct opthdr		*optp;
18550 	mblk_t			*mp2ctl;
18551 	mblk_t			*mp_tail = NULL;
18552 	ill_t			*ill;
18553 	ipif_t			*ipif;
18554 	uint_t			bitval;
18555 	mib2_ipAddrEntry_t	mae;
18556 	zoneid_t		zoneid;
18557 	ill_walk_context_t ctx;
18558 
18559 	/*
18560 	 * make a copy of the original message
18561 	 */
18562 	mp2ctl = copymsg(mpctl);
18563 
18564 	/* ipAddrEntryTable */
18565 
18566 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18567 	optp->level = MIB2_IP;
18568 	optp->name = MIB2_IP_ADDR;
18569 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18570 
18571 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18572 	ill = ILL_START_WALK_V4(&ctx, ipst);
18573 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18574 		for (ipif = ill->ill_ipif; ipif != NULL;
18575 		    ipif = ipif->ipif_next) {
18576 			if (ipif->ipif_zoneid != zoneid &&
18577 			    ipif->ipif_zoneid != ALL_ZONES)
18578 				continue;
18579 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18580 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18581 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18582 
18583 			(void) ipif_get_name(ipif,
18584 			    mae.ipAdEntIfIndex.o_bytes,
18585 			    OCTET_LENGTH);
18586 			mae.ipAdEntIfIndex.o_length =
18587 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18588 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18589 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18590 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18591 			mae.ipAdEntInfo.ae_subnet_len =
18592 			    ip_mask_to_plen(ipif->ipif_net_mask);
18593 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18594 			for (bitval = 1;
18595 			    bitval &&
18596 			    !(bitval & ipif->ipif_brd_addr);
18597 			    bitval <<= 1)
18598 				noop;
18599 			mae.ipAdEntBcastAddr = bitval;
18600 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18601 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18602 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18603 			mae.ipAdEntInfo.ae_broadcast_addr =
18604 			    ipif->ipif_brd_addr;
18605 			mae.ipAdEntInfo.ae_pp_dst_addr =
18606 			    ipif->ipif_pp_dst_addr;
18607 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18608 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18609 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18610 
18611 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18612 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18613 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18614 				    "allocate %u bytes\n",
18615 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18616 			}
18617 		}
18618 	}
18619 	rw_exit(&ipst->ips_ill_g_lock);
18620 
18621 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18622 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18623 	    (int)optp->level, (int)optp->name, (int)optp->len));
18624 	qreply(q, mpctl);
18625 	return (mp2ctl);
18626 }
18627 
18628 /* IPv6 address information */
18629 static mblk_t *
18630 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18631 {
18632 	struct opthdr		*optp;
18633 	mblk_t			*mp2ctl;
18634 	mblk_t			*mp_tail = NULL;
18635 	ill_t			*ill;
18636 	ipif_t			*ipif;
18637 	mib2_ipv6AddrEntry_t	mae6;
18638 	zoneid_t		zoneid;
18639 	ill_walk_context_t	ctx;
18640 
18641 	/*
18642 	 * make a copy of the original message
18643 	 */
18644 	mp2ctl = copymsg(mpctl);
18645 
18646 	/* ipv6AddrEntryTable */
18647 
18648 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18649 	optp->level = MIB2_IP6;
18650 	optp->name = MIB2_IP6_ADDR;
18651 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18652 
18653 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18654 	ill = ILL_START_WALK_V6(&ctx, ipst);
18655 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18656 		for (ipif = ill->ill_ipif; ipif != NULL;
18657 		    ipif = ipif->ipif_next) {
18658 			if (ipif->ipif_zoneid != zoneid &&
18659 			    ipif->ipif_zoneid != ALL_ZONES)
18660 				continue;
18661 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18662 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18663 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18664 
18665 			(void) ipif_get_name(ipif,
18666 			    mae6.ipv6AddrIfIndex.o_bytes,
18667 			    OCTET_LENGTH);
18668 			mae6.ipv6AddrIfIndex.o_length =
18669 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18670 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18671 			mae6.ipv6AddrPfxLength =
18672 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18673 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18674 			mae6.ipv6AddrInfo.ae_subnet_len =
18675 			    mae6.ipv6AddrPfxLength;
18676 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18677 
18678 			/* Type: stateless(1), stateful(2), unknown(3) */
18679 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18680 				mae6.ipv6AddrType = 1;
18681 			else
18682 				mae6.ipv6AddrType = 2;
18683 			/* Anycast: true(1), false(2) */
18684 			if (ipif->ipif_flags & IPIF_ANYCAST)
18685 				mae6.ipv6AddrAnycastFlag = 1;
18686 			else
18687 				mae6.ipv6AddrAnycastFlag = 2;
18688 
18689 			/*
18690 			 * Address status: preferred(1), deprecated(2),
18691 			 * invalid(3), inaccessible(4), unknown(5)
18692 			 */
18693 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18694 				mae6.ipv6AddrStatus = 3;
18695 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18696 				mae6.ipv6AddrStatus = 2;
18697 			else
18698 				mae6.ipv6AddrStatus = 1;
18699 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18700 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18701 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18702 						ipif->ipif_v6pp_dst_addr;
18703 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18704 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18705 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18706 			mae6.ipv6AddrIdentifier = ill->ill_token;
18707 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18708 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18709 			mae6.ipv6AddrRetransmitTime =
18710 			    ill->ill_reachable_retrans_time;
18711 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18712 				(char *)&mae6,
18713 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18714 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18715 				    "allocate %u bytes\n",
18716 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18717 			}
18718 		}
18719 	}
18720 	rw_exit(&ipst->ips_ill_g_lock);
18721 
18722 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18723 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18724 	    (int)optp->level, (int)optp->name, (int)optp->len));
18725 	qreply(q, mpctl);
18726 	return (mp2ctl);
18727 }
18728 
18729 /* IPv4 multicast group membership. */
18730 static mblk_t *
18731 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18732 {
18733 	struct opthdr		*optp;
18734 	mblk_t			*mp2ctl;
18735 	ill_t			*ill;
18736 	ipif_t			*ipif;
18737 	ilm_t			*ilm;
18738 	ip_member_t		ipm;
18739 	mblk_t			*mp_tail = NULL;
18740 	ill_walk_context_t	ctx;
18741 	zoneid_t		zoneid;
18742 
18743 	/*
18744 	 * make a copy of the original message
18745 	 */
18746 	mp2ctl = copymsg(mpctl);
18747 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18748 
18749 	/* ipGroupMember table */
18750 	optp = (struct opthdr *)&mpctl->b_rptr[
18751 	    sizeof (struct T_optmgmt_ack)];
18752 	optp->level = MIB2_IP;
18753 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18754 
18755 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18756 	ill = ILL_START_WALK_V4(&ctx, ipst);
18757 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18758 		ILM_WALKER_HOLD(ill);
18759 		for (ipif = ill->ill_ipif; ipif != NULL;
18760 		    ipif = ipif->ipif_next) {
18761 			if (ipif->ipif_zoneid != zoneid &&
18762 			    ipif->ipif_zoneid != ALL_ZONES)
18763 				continue;	/* not this zone */
18764 			(void) ipif_get_name(ipif,
18765 			    ipm.ipGroupMemberIfIndex.o_bytes,
18766 			    OCTET_LENGTH);
18767 			ipm.ipGroupMemberIfIndex.o_length =
18768 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18769 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18770 				ASSERT(ilm->ilm_ipif != NULL);
18771 				ASSERT(ilm->ilm_ill == NULL);
18772 				if (ilm->ilm_ipif != ipif)
18773 					continue;
18774 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18775 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18776 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18777 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18778 				    (char *)&ipm, (int)sizeof (ipm))) {
18779 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18780 					    "failed to allocate %u bytes\n",
18781 						(uint_t)sizeof (ipm)));
18782 				}
18783 			}
18784 		}
18785 		ILM_WALKER_RELE(ill);
18786 	}
18787 	rw_exit(&ipst->ips_ill_g_lock);
18788 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18789 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18790 	    (int)optp->level, (int)optp->name, (int)optp->len));
18791 	qreply(q, mpctl);
18792 	return (mp2ctl);
18793 }
18794 
18795 /* IPv6 multicast group membership. */
18796 static mblk_t *
18797 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18798 {
18799 	struct opthdr		*optp;
18800 	mblk_t			*mp2ctl;
18801 	ill_t			*ill;
18802 	ilm_t			*ilm;
18803 	ipv6_member_t		ipm6;
18804 	mblk_t			*mp_tail = NULL;
18805 	ill_walk_context_t	ctx;
18806 	zoneid_t		zoneid;
18807 
18808 	/*
18809 	 * make a copy of the original message
18810 	 */
18811 	mp2ctl = copymsg(mpctl);
18812 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18813 
18814 	/* ip6GroupMember table */
18815 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18816 	optp->level = MIB2_IP6;
18817 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18818 
18819 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18820 	ill = ILL_START_WALK_V6(&ctx, ipst);
18821 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18822 		ILM_WALKER_HOLD(ill);
18823 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18824 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18825 			ASSERT(ilm->ilm_ipif == NULL);
18826 			ASSERT(ilm->ilm_ill != NULL);
18827 			if (ilm->ilm_zoneid != zoneid)
18828 				continue;	/* not this zone */
18829 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18830 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18831 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18832 			if (!snmp_append_data2(mpctl->b_cont,
18833 			    &mp_tail,
18834 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18835 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18836 				    "failed to allocate %u bytes\n",
18837 				    (uint_t)sizeof (ipm6)));
18838 			}
18839 		}
18840 		ILM_WALKER_RELE(ill);
18841 	}
18842 	rw_exit(&ipst->ips_ill_g_lock);
18843 
18844 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18845 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18846 	    (int)optp->level, (int)optp->name, (int)optp->len));
18847 	qreply(q, mpctl);
18848 	return (mp2ctl);
18849 }
18850 
18851 /* IP multicast filtered sources */
18852 static mblk_t *
18853 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18854 {
18855 	struct opthdr		*optp;
18856 	mblk_t			*mp2ctl;
18857 	ill_t			*ill;
18858 	ipif_t			*ipif;
18859 	ilm_t			*ilm;
18860 	ip_grpsrc_t		ips;
18861 	mblk_t			*mp_tail = NULL;
18862 	ill_walk_context_t	ctx;
18863 	zoneid_t		zoneid;
18864 	int			i;
18865 	slist_t			*sl;
18866 
18867 	/*
18868 	 * make a copy of the original message
18869 	 */
18870 	mp2ctl = copymsg(mpctl);
18871 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18872 
18873 	/* ipGroupSource table */
18874 	optp = (struct opthdr *)&mpctl->b_rptr[
18875 	    sizeof (struct T_optmgmt_ack)];
18876 	optp->level = MIB2_IP;
18877 	optp->name = EXPER_IP_GROUP_SOURCES;
18878 
18879 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18880 	ill = ILL_START_WALK_V4(&ctx, ipst);
18881 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18882 		ILM_WALKER_HOLD(ill);
18883 		for (ipif = ill->ill_ipif; ipif != NULL;
18884 		    ipif = ipif->ipif_next) {
18885 			if (ipif->ipif_zoneid != zoneid)
18886 				continue;	/* not this zone */
18887 			(void) ipif_get_name(ipif,
18888 			    ips.ipGroupSourceIfIndex.o_bytes,
18889 			    OCTET_LENGTH);
18890 			ips.ipGroupSourceIfIndex.o_length =
18891 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18892 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18893 				ASSERT(ilm->ilm_ipif != NULL);
18894 				ASSERT(ilm->ilm_ill == NULL);
18895 				sl = ilm->ilm_filter;
18896 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18897 					continue;
18898 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18899 				for (i = 0; i < sl->sl_numsrc; i++) {
18900 					if (!IN6_IS_ADDR_V4MAPPED(
18901 					    &sl->sl_addr[i]))
18902 						continue;
18903 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18904 					    ips.ipGroupSourceAddress);
18905 					if (snmp_append_data2(mpctl->b_cont,
18906 					    &mp_tail, (char *)&ips,
18907 					    (int)sizeof (ips)) == 0) {
18908 						ip1dbg(("ip_snmp_get_mib2_"
18909 						    "ip_group_src: failed to "
18910 						    "allocate %u bytes\n",
18911 						    (uint_t)sizeof (ips)));
18912 					}
18913 				}
18914 			}
18915 		}
18916 		ILM_WALKER_RELE(ill);
18917 	}
18918 	rw_exit(&ipst->ips_ill_g_lock);
18919 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18920 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18921 	    (int)optp->level, (int)optp->name, (int)optp->len));
18922 	qreply(q, mpctl);
18923 	return (mp2ctl);
18924 }
18925 
18926 /* IPv6 multicast filtered sources. */
18927 static mblk_t *
18928 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18929 {
18930 	struct opthdr		*optp;
18931 	mblk_t			*mp2ctl;
18932 	ill_t			*ill;
18933 	ilm_t			*ilm;
18934 	ipv6_grpsrc_t		ips6;
18935 	mblk_t			*mp_tail = NULL;
18936 	ill_walk_context_t	ctx;
18937 	zoneid_t		zoneid;
18938 	int			i;
18939 	slist_t			*sl;
18940 
18941 	/*
18942 	 * make a copy of the original message
18943 	 */
18944 	mp2ctl = copymsg(mpctl);
18945 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18946 
18947 	/* ip6GroupMember table */
18948 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18949 	optp->level = MIB2_IP6;
18950 	optp->name = EXPER_IP6_GROUP_SOURCES;
18951 
18952 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18953 	ill = ILL_START_WALK_V6(&ctx, ipst);
18954 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18955 		ILM_WALKER_HOLD(ill);
18956 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18957 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18958 			ASSERT(ilm->ilm_ipif == NULL);
18959 			ASSERT(ilm->ilm_ill != NULL);
18960 			sl = ilm->ilm_filter;
18961 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18962 				continue;
18963 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18964 			for (i = 0; i < sl->sl_numsrc; i++) {
18965 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18966 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18967 				    (char *)&ips6, (int)sizeof (ips6))) {
18968 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18969 					    "group_src: failed to allocate "
18970 					    "%u bytes\n",
18971 					    (uint_t)sizeof (ips6)));
18972 				}
18973 			}
18974 		}
18975 		ILM_WALKER_RELE(ill);
18976 	}
18977 	rw_exit(&ipst->ips_ill_g_lock);
18978 
18979 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18980 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18981 	    (int)optp->level, (int)optp->name, (int)optp->len));
18982 	qreply(q, mpctl);
18983 	return (mp2ctl);
18984 }
18985 
18986 /* Multicast routing virtual interface table. */
18987 static mblk_t *
18988 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18989 {
18990 	struct opthdr		*optp;
18991 	mblk_t			*mp2ctl;
18992 
18993 	/*
18994 	 * make a copy of the original message
18995 	 */
18996 	mp2ctl = copymsg(mpctl);
18997 
18998 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18999 	optp->level = EXPER_DVMRP;
19000 	optp->name = EXPER_DVMRP_VIF;
19001 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19002 		ip0dbg(("ip_mroute_vif: failed\n"));
19003 	}
19004 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19005 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19006 	    (int)optp->level, (int)optp->name, (int)optp->len));
19007 	qreply(q, mpctl);
19008 	return (mp2ctl);
19009 }
19010 
19011 /* Multicast routing table. */
19012 static mblk_t *
19013 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19014 {
19015 	struct opthdr		*optp;
19016 	mblk_t			*mp2ctl;
19017 
19018 	/*
19019 	 * make a copy of the original message
19020 	 */
19021 	mp2ctl = copymsg(mpctl);
19022 
19023 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19024 	optp->level = EXPER_DVMRP;
19025 	optp->name = EXPER_DVMRP_MRT;
19026 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19027 		ip0dbg(("ip_mroute_mrt: failed\n"));
19028 	}
19029 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19030 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19031 	    (int)optp->level, (int)optp->name, (int)optp->len));
19032 	qreply(q, mpctl);
19033 	return (mp2ctl);
19034 }
19035 
19036 /*
19037  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19038  * in one IRE walk.
19039  */
19040 static mblk_t *
19041 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19042 {
19043 	struct opthdr	*optp;
19044 	mblk_t		*mp2ctl;	/* Returned */
19045 	mblk_t		*mp3ctl;	/* nettomedia */
19046 	mblk_t		*mp4ctl;	/* routeattrs */
19047 	iproutedata_t	ird;
19048 	zoneid_t	zoneid;
19049 
19050 	/*
19051 	 * make copies of the original message
19052 	 *	- mp2ctl is returned unchanged to the caller for his use
19053 	 *	- mpctl is sent upstream as ipRouteEntryTable
19054 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19055 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19056 	 */
19057 	mp2ctl = copymsg(mpctl);
19058 	mp3ctl = copymsg(mpctl);
19059 	mp4ctl = copymsg(mpctl);
19060 	if (mp3ctl == NULL || mp4ctl == NULL) {
19061 		freemsg(mp4ctl);
19062 		freemsg(mp3ctl);
19063 		freemsg(mp2ctl);
19064 		freemsg(mpctl);
19065 		return (NULL);
19066 	}
19067 
19068 	bzero(&ird, sizeof (ird));
19069 
19070 	ird.ird_route.lp_head = mpctl->b_cont;
19071 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19072 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19073 
19074 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19075 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19076 	if (zoneid == GLOBAL_ZONEID) {
19077 		/*
19078 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19079 		 * requires the sys_net_config or sys_ip_config privilege,
19080 		 * it can only run in the global zone or an exclusive-IP zone,
19081 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19082 		 */
19083 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19084 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19085 	}
19086 
19087 	/* ipRouteEntryTable in mpctl */
19088 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19089 	optp->level = MIB2_IP;
19090 	optp->name = MIB2_IP_ROUTE;
19091 	optp->len = msgdsize(ird.ird_route.lp_head);
19092 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19093 	    (int)optp->level, (int)optp->name, (int)optp->len));
19094 	qreply(q, mpctl);
19095 
19096 	/* ipNetToMediaEntryTable in mp3ctl */
19097 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19098 	optp->level = MIB2_IP;
19099 	optp->name = MIB2_IP_MEDIA;
19100 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19101 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19102 	    (int)optp->level, (int)optp->name, (int)optp->len));
19103 	qreply(q, mp3ctl);
19104 
19105 	/* ipRouteAttributeTable in mp4ctl */
19106 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19107 	optp->level = MIB2_IP;
19108 	optp->name = EXPER_IP_RTATTR;
19109 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19110 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19111 	    (int)optp->level, (int)optp->name, (int)optp->len));
19112 	if (optp->len == 0)
19113 		freemsg(mp4ctl);
19114 	else
19115 		qreply(q, mp4ctl);
19116 
19117 	return (mp2ctl);
19118 }
19119 
19120 /*
19121  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19122  * ipv6NetToMediaEntryTable in an NDP walk.
19123  */
19124 static mblk_t *
19125 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19126 {
19127 	struct opthdr	*optp;
19128 	mblk_t		*mp2ctl;	/* Returned */
19129 	mblk_t		*mp3ctl;	/* nettomedia */
19130 	mblk_t		*mp4ctl;	/* routeattrs */
19131 	iproutedata_t	ird;
19132 	zoneid_t	zoneid;
19133 
19134 	/*
19135 	 * make copies of the original message
19136 	 *	- mp2ctl is returned unchanged to the caller for his use
19137 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19138 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19139 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19140 	 */
19141 	mp2ctl = copymsg(mpctl);
19142 	mp3ctl = copymsg(mpctl);
19143 	mp4ctl = copymsg(mpctl);
19144 	if (mp3ctl == NULL || mp4ctl == NULL) {
19145 		freemsg(mp4ctl);
19146 		freemsg(mp3ctl);
19147 		freemsg(mp2ctl);
19148 		freemsg(mpctl);
19149 		return (NULL);
19150 	}
19151 
19152 	bzero(&ird, sizeof (ird));
19153 
19154 	ird.ird_route.lp_head = mpctl->b_cont;
19155 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19156 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19157 
19158 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19159 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19160 
19161 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19162 	optp->level = MIB2_IP6;
19163 	optp->name = MIB2_IP6_ROUTE;
19164 	optp->len = msgdsize(ird.ird_route.lp_head);
19165 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19166 	    (int)optp->level, (int)optp->name, (int)optp->len));
19167 	qreply(q, mpctl);
19168 
19169 	/* ipv6NetToMediaEntryTable in mp3ctl */
19170 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19171 
19172 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19173 	optp->level = MIB2_IP6;
19174 	optp->name = MIB2_IP6_MEDIA;
19175 	optp->len = msgdsize(ird.ird_netmedia.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, mp3ctl);
19179 
19180 	/* ipv6RouteAttributeTable in mp4ctl */
19181 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19182 	optp->level = MIB2_IP6;
19183 	optp->name = EXPER_IP_RTATTR;
19184 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19185 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19186 	    (int)optp->level, (int)optp->name, (int)optp->len));
19187 	if (optp->len == 0)
19188 		freemsg(mp4ctl);
19189 	else
19190 		qreply(q, mp4ctl);
19191 
19192 	return (mp2ctl);
19193 }
19194 
19195 /*
19196  * IPv6 mib: One per ill
19197  */
19198 static mblk_t *
19199 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19200 {
19201 	struct opthdr		*optp;
19202 	mblk_t			*mp2ctl;
19203 	ill_t			*ill;
19204 	ill_walk_context_t	ctx;
19205 	mblk_t			*mp_tail = NULL;
19206 
19207 	/*
19208 	 * Make a copy of the original message
19209 	 */
19210 	mp2ctl = copymsg(mpctl);
19211 
19212 	/* fixed length IPv6 structure ... */
19213 
19214 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19215 	optp->level = MIB2_IP6;
19216 	optp->name = 0;
19217 	/* Include "unknown interface" ip6_mib */
19218 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19219 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19220 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19221 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19222 	    ipst->ips_ipv6_forward ? 1 : 2);
19223 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19224 	    ipst->ips_ipv6_def_hops);
19225 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19226 	    sizeof (mib2_ipIfStatsEntry_t));
19227 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19228 	    sizeof (mib2_ipv6AddrEntry_t));
19229 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19230 	    sizeof (mib2_ipv6RouteEntry_t));
19231 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19232 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19233 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19234 	    sizeof (ipv6_member_t));
19235 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19236 	    sizeof (ipv6_grpsrc_t));
19237 
19238 	/*
19239 	 * Synchronize 64- and 32-bit counters
19240 	 */
19241 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19242 	    ipIfStatsHCInReceives);
19243 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19244 	    ipIfStatsHCInDelivers);
19245 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19246 	    ipIfStatsHCOutRequests);
19247 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19248 	    ipIfStatsHCOutForwDatagrams);
19249 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19250 	    ipIfStatsHCOutMcastPkts);
19251 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19252 	    ipIfStatsHCInMcastPkts);
19253 
19254 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19255 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19256 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19257 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19258 	}
19259 
19260 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19261 	ill = ILL_START_WALK_V6(&ctx, ipst);
19262 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19263 		ill->ill_ip_mib->ipIfStatsIfIndex =
19264 		    ill->ill_phyint->phyint_ifindex;
19265 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19266 		    ipst->ips_ipv6_forward ? 1 : 2);
19267 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19268 		    ill->ill_max_hops);
19269 
19270 		/*
19271 		 * Synchronize 64- and 32-bit counters
19272 		 */
19273 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19274 		    ipIfStatsHCInReceives);
19275 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19276 		    ipIfStatsHCInDelivers);
19277 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19278 		    ipIfStatsHCOutRequests);
19279 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19280 		    ipIfStatsHCOutForwDatagrams);
19281 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19282 		    ipIfStatsHCOutMcastPkts);
19283 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19284 		    ipIfStatsHCInMcastPkts);
19285 
19286 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19287 		    (char *)ill->ill_ip_mib,
19288 		    (int)sizeof (*ill->ill_ip_mib))) {
19289 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19290 				"%u bytes\n",
19291 				(uint_t)sizeof (*ill->ill_ip_mib)));
19292 		}
19293 	}
19294 	rw_exit(&ipst->ips_ill_g_lock);
19295 
19296 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19297 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19298 	    (int)optp->level, (int)optp->name, (int)optp->len));
19299 	qreply(q, mpctl);
19300 	return (mp2ctl);
19301 }
19302 
19303 /*
19304  * ICMPv6 mib: One per ill
19305  */
19306 static mblk_t *
19307 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19308 {
19309 	struct opthdr		*optp;
19310 	mblk_t			*mp2ctl;
19311 	ill_t			*ill;
19312 	ill_walk_context_t	ctx;
19313 	mblk_t			*mp_tail = NULL;
19314 	/*
19315 	 * Make a copy of the original message
19316 	 */
19317 	mp2ctl = copymsg(mpctl);
19318 
19319 	/* fixed length ICMPv6 structure ... */
19320 
19321 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19322 	optp->level = MIB2_ICMP6;
19323 	optp->name = 0;
19324 	/* Include "unknown interface" icmp6_mib */
19325 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19326 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19327 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19328 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19329 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19330 	    (char *)&ipst->ips_icmp6_mib,
19331 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19332 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19333 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19334 	}
19335 
19336 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19337 	ill = ILL_START_WALK_V6(&ctx, ipst);
19338 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19339 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19340 		    ill->ill_phyint->phyint_ifindex;
19341 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19342 		    (char *)ill->ill_icmp6_mib,
19343 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19344 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19345 			    "%u bytes\n",
19346 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19347 		}
19348 	}
19349 	rw_exit(&ipst->ips_ill_g_lock);
19350 
19351 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19352 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19353 	    (int)optp->level, (int)optp->name, (int)optp->len));
19354 	qreply(q, mpctl);
19355 	return (mp2ctl);
19356 }
19357 
19358 /*
19359  * ire_walk routine to create both ipRouteEntryTable and
19360  * ipRouteAttributeTable in one IRE walk
19361  */
19362 static void
19363 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19364 {
19365 	ill_t				*ill;
19366 	ipif_t				*ipif;
19367 	mib2_ipRouteEntry_t		*re;
19368 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19369 	ipaddr_t			gw_addr;
19370 	tsol_ire_gw_secattr_t		*attrp;
19371 	tsol_gc_t			*gc = NULL;
19372 	tsol_gcgrp_t			*gcgrp = NULL;
19373 	uint_t				sacnt = 0;
19374 	int				i;
19375 
19376 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19377 
19378 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19379 		return;
19380 
19381 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19382 		mutex_enter(&attrp->igsa_lock);
19383 		if ((gc = attrp->igsa_gc) != NULL) {
19384 			gcgrp = gc->gc_grp;
19385 			ASSERT(gcgrp != NULL);
19386 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19387 			sacnt = 1;
19388 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19389 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19390 			gc = gcgrp->gcgrp_head;
19391 			sacnt = gcgrp->gcgrp_count;
19392 		}
19393 		mutex_exit(&attrp->igsa_lock);
19394 
19395 		/* do nothing if there's no gc to report */
19396 		if (gc == NULL) {
19397 			ASSERT(sacnt == 0);
19398 			if (gcgrp != NULL) {
19399 				/* we might as well drop the lock now */
19400 				rw_exit(&gcgrp->gcgrp_rwlock);
19401 				gcgrp = NULL;
19402 			}
19403 			attrp = NULL;
19404 		}
19405 
19406 		ASSERT(gc == NULL || (gcgrp != NULL &&
19407 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19408 	}
19409 	ASSERT(sacnt == 0 || gc != NULL);
19410 
19411 	if (sacnt != 0 &&
19412 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19413 		kmem_free(re, sizeof (*re));
19414 		rw_exit(&gcgrp->gcgrp_rwlock);
19415 		return;
19416 	}
19417 
19418 	/*
19419 	 * Return all IRE types for route table... let caller pick and choose
19420 	 */
19421 	re->ipRouteDest = ire->ire_addr;
19422 	ipif = ire->ire_ipif;
19423 	re->ipRouteIfIndex.o_length = 0;
19424 	if (ire->ire_type == IRE_CACHE) {
19425 		ill = (ill_t *)ire->ire_stq->q_ptr;
19426 		re->ipRouteIfIndex.o_length =
19427 		    ill->ill_name_length == 0 ? 0 :
19428 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19429 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19430 		    re->ipRouteIfIndex.o_length);
19431 	} else if (ipif != NULL) {
19432 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19433 		    OCTET_LENGTH);
19434 		re->ipRouteIfIndex.o_length =
19435 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19436 	}
19437 	re->ipRouteMetric1 = -1;
19438 	re->ipRouteMetric2 = -1;
19439 	re->ipRouteMetric3 = -1;
19440 	re->ipRouteMetric4 = -1;
19441 
19442 	gw_addr = ire->ire_gateway_addr;
19443 
19444 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19445 		re->ipRouteNextHop = ire->ire_src_addr;
19446 	else
19447 		re->ipRouteNextHop = gw_addr;
19448 	/* indirect(4), direct(3), or invalid(2) */
19449 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19450 		re->ipRouteType = 2;
19451 	else
19452 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19453 	re->ipRouteProto = -1;
19454 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19455 	re->ipRouteMask = ire->ire_mask;
19456 	re->ipRouteMetric5 = -1;
19457 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19458 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19459 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19460 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19461 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19462 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19463 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19464 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19465 	re->ipRouteInfo.re_in_ill.o_length = 0;
19466 
19467 	if (ire->ire_flags & RTF_DYNAMIC) {
19468 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19469 	} else {
19470 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19471 	}
19472 
19473 	if (ire->ire_in_ill != NULL) {
19474 		re->ipRouteInfo.re_in_ill.o_length =
19475 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19476 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19477 		bcopy(ire->ire_in_ill->ill_name,
19478 		    re->ipRouteInfo.re_in_ill.o_bytes,
19479 		    re->ipRouteInfo.re_in_ill.o_length);
19480 	}
19481 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19482 
19483 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19484 	    (char *)re, (int)sizeof (*re))) {
19485 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19486 		    (uint_t)sizeof (*re)));
19487 	}
19488 
19489 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19490 		iaeptr->iae_routeidx = ird->ird_idx;
19491 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19492 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19493 	}
19494 
19495 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19496 	    (char *)iae, sacnt * sizeof (*iae))) {
19497 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19498 		    (unsigned)(sacnt * sizeof (*iae))));
19499 	}
19500 
19501 	/* bump route index for next pass */
19502 	ird->ird_idx++;
19503 
19504 	kmem_free(re, sizeof (*re));
19505 	if (sacnt != 0)
19506 		kmem_free(iae, sacnt * sizeof (*iae));
19507 
19508 	if (gcgrp != NULL)
19509 		rw_exit(&gcgrp->gcgrp_rwlock);
19510 }
19511 
19512 /*
19513  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19514  */
19515 static void
19516 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19517 {
19518 	ill_t				*ill;
19519 	ipif_t				*ipif;
19520 	mib2_ipv6RouteEntry_t		*re;
19521 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19522 	in6_addr_t			gw_addr_v6;
19523 	tsol_ire_gw_secattr_t		*attrp;
19524 	tsol_gc_t			*gc = NULL;
19525 	tsol_gcgrp_t			*gcgrp = NULL;
19526 	uint_t				sacnt = 0;
19527 	int				i;
19528 
19529 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19530 
19531 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19532 		return;
19533 
19534 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19535 		mutex_enter(&attrp->igsa_lock);
19536 		if ((gc = attrp->igsa_gc) != NULL) {
19537 			gcgrp = gc->gc_grp;
19538 			ASSERT(gcgrp != NULL);
19539 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19540 			sacnt = 1;
19541 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19542 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19543 			gc = gcgrp->gcgrp_head;
19544 			sacnt = gcgrp->gcgrp_count;
19545 		}
19546 		mutex_exit(&attrp->igsa_lock);
19547 
19548 		/* do nothing if there's no gc to report */
19549 		if (gc == NULL) {
19550 			ASSERT(sacnt == 0);
19551 			if (gcgrp != NULL) {
19552 				/* we might as well drop the lock now */
19553 				rw_exit(&gcgrp->gcgrp_rwlock);
19554 				gcgrp = NULL;
19555 			}
19556 			attrp = NULL;
19557 		}
19558 
19559 		ASSERT(gc == NULL || (gcgrp != NULL &&
19560 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19561 	}
19562 	ASSERT(sacnt == 0 || gc != NULL);
19563 
19564 	if (sacnt != 0 &&
19565 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19566 		kmem_free(re, sizeof (*re));
19567 		rw_exit(&gcgrp->gcgrp_rwlock);
19568 		return;
19569 	}
19570 
19571 	/*
19572 	 * Return all IRE types for route table... let caller pick and choose
19573 	 */
19574 	re->ipv6RouteDest = ire->ire_addr_v6;
19575 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19576 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19577 	re->ipv6RouteIfIndex.o_length = 0;
19578 	ipif = ire->ire_ipif;
19579 	if (ire->ire_type == IRE_CACHE) {
19580 		ill = (ill_t *)ire->ire_stq->q_ptr;
19581 		re->ipv6RouteIfIndex.o_length =
19582 		    ill->ill_name_length == 0 ? 0 :
19583 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19584 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19585 		    re->ipv6RouteIfIndex.o_length);
19586 	} else if (ipif != NULL) {
19587 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19588 		    OCTET_LENGTH);
19589 		re->ipv6RouteIfIndex.o_length =
19590 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19591 	}
19592 
19593 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19594 
19595 	mutex_enter(&ire->ire_lock);
19596 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19597 	mutex_exit(&ire->ire_lock);
19598 
19599 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19600 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19601 	else
19602 		re->ipv6RouteNextHop = gw_addr_v6;
19603 
19604 	/* remote(4), local(3), or discard(2) */
19605 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19606 		re->ipv6RouteType = 2;
19607 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19608 		re->ipv6RouteType = 3;
19609 	else
19610 		re->ipv6RouteType = 4;
19611 
19612 	re->ipv6RouteProtocol	= -1;
19613 	re->ipv6RoutePolicy	= 0;
19614 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19615 	re->ipv6RouteNextHopRDI	= 0;
19616 	re->ipv6RouteWeight	= 0;
19617 	re->ipv6RouteMetric	= 0;
19618 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19619 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19620 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19621 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19622 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19623 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19624 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19625 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19626 
19627 	if (ire->ire_flags & RTF_DYNAMIC) {
19628 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19629 	} else {
19630 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19631 	}
19632 
19633 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19634 	    (char *)re, (int)sizeof (*re))) {
19635 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19636 		    (uint_t)sizeof (*re)));
19637 	}
19638 
19639 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19640 		iaeptr->iae_routeidx = ird->ird_idx;
19641 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19642 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19643 	}
19644 
19645 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19646 	    (char *)iae, sacnt * sizeof (*iae))) {
19647 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19648 		    (unsigned)(sacnt * sizeof (*iae))));
19649 	}
19650 
19651 	/* bump route index for next pass */
19652 	ird->ird_idx++;
19653 
19654 	kmem_free(re, sizeof (*re));
19655 	if (sacnt != 0)
19656 		kmem_free(iae, sacnt * sizeof (*iae));
19657 
19658 	if (gcgrp != NULL)
19659 		rw_exit(&gcgrp->gcgrp_rwlock);
19660 }
19661 
19662 /*
19663  * ndp_walk routine to create ipv6NetToMediaEntryTable
19664  */
19665 static int
19666 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19667 {
19668 	ill_t				*ill;
19669 	mib2_ipv6NetToMediaEntry_t	ntme;
19670 	dl_unitdata_req_t		*dl;
19671 
19672 	ill = nce->nce_ill;
19673 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19674 		return (0);
19675 
19676 	/*
19677 	 * Neighbor cache entry attached to IRE with on-link
19678 	 * destination.
19679 	 */
19680 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19681 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19682 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19683 	    (nce->nce_res_mp != NULL)) {
19684 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19685 		ntme.ipv6NetToMediaPhysAddress.o_length =
19686 		    dl->dl_dest_addr_length;
19687 	} else {
19688 		ntme.ipv6NetToMediaPhysAddress.o_length =
19689 		    ill->ill_phys_addr_length;
19690 	}
19691 	if (nce->nce_res_mp != NULL) {
19692 		bcopy((char *)nce->nce_res_mp->b_rptr +
19693 		    NCE_LL_ADDR_OFFSET(ill),
19694 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19695 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19696 	} else {
19697 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19698 		    ill->ill_phys_addr_length);
19699 	}
19700 	/*
19701 	 * Note: Returns ND_* states. Should be:
19702 	 * reachable(1), stale(2), delay(3), probe(4),
19703 	 * invalid(5), unknown(6)
19704 	 */
19705 	ntme.ipv6NetToMediaState = nce->nce_state;
19706 	ntme.ipv6NetToMediaLastUpdated = 0;
19707 
19708 	/* other(1), dynamic(2), static(3), local(4) */
19709 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19710 		ntme.ipv6NetToMediaType = 4;
19711 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19712 		ntme.ipv6NetToMediaType = 1;
19713 	} else {
19714 		ntme.ipv6NetToMediaType = 2;
19715 	}
19716 
19717 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19718 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19719 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19720 		    (uint_t)sizeof (ntme)));
19721 	}
19722 	return (0);
19723 }
19724 
19725 /*
19726  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19727  */
19728 /* ARGSUSED */
19729 int
19730 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19731 {
19732 	switch (level) {
19733 	case MIB2_IP:
19734 	case MIB2_ICMP:
19735 		switch (name) {
19736 		default:
19737 			break;
19738 		}
19739 		return (1);
19740 	default:
19741 		return (1);
19742 	}
19743 }
19744 
19745 /*
19746  * When there exists both a 64- and 32-bit counter of a particular type
19747  * (i.e., InReceives), only the 64-bit counters are added.
19748  */
19749 void
19750 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19751 {
19752 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19753 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19754 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19755 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19756 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19757 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19758 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19759 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19760 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19761 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19762 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19763 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19764 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19765 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19766 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19767 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19768 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19769 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19770 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19771 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19772 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19773 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19774 	    o2->ipIfStatsInWrongIPVersion);
19775 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19776 	    o2->ipIfStatsInWrongIPVersion);
19777 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19778 	    o2->ipIfStatsOutSwitchIPVersion);
19779 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19780 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19781 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19782 	    o2->ipIfStatsHCInForwDatagrams);
19783 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19784 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19785 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19786 	    o2->ipIfStatsHCOutForwDatagrams);
19787 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19788 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19789 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19790 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19791 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19792 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19793 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19794 	    o2->ipIfStatsHCOutMcastOctets);
19795 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19796 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19797 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19798 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19799 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19800 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19801 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19802 }
19803 
19804 void
19805 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19806 {
19807 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19808 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19809 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19810 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19811 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19812 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19813 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19814 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19815 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19816 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19817 	    o2->ipv6IfIcmpInRouterSolicits);
19818 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19819 	    o2->ipv6IfIcmpInRouterAdvertisements);
19820 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19821 	    o2->ipv6IfIcmpInNeighborSolicits);
19822 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19823 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19824 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19825 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19826 	    o2->ipv6IfIcmpInGroupMembQueries);
19827 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19828 	    o2->ipv6IfIcmpInGroupMembResponses);
19829 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19830 	    o2->ipv6IfIcmpInGroupMembReductions);
19831 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19832 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19833 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19834 	    o2->ipv6IfIcmpOutDestUnreachs);
19835 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19836 	    o2->ipv6IfIcmpOutAdminProhibs);
19837 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19838 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19839 	    o2->ipv6IfIcmpOutParmProblems);
19840 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19841 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19842 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19843 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19844 	    o2->ipv6IfIcmpOutRouterSolicits);
19845 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19846 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19847 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19848 	    o2->ipv6IfIcmpOutNeighborSolicits);
19849 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19850 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19851 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19852 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19853 	    o2->ipv6IfIcmpOutGroupMembQueries);
19854 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19855 	    o2->ipv6IfIcmpOutGroupMembResponses);
19856 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19857 	    o2->ipv6IfIcmpOutGroupMembReductions);
19858 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19859 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19860 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19861 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19862 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19863 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19864 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19865 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19866 	    o2->ipv6IfIcmpInGroupMembTotal);
19867 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19868 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19869 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19870 	    o2->ipv6IfIcmpInGroupMembBadReports);
19871 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19872 	    o2->ipv6IfIcmpInGroupMembOurReports);
19873 }
19874 
19875 /*
19876  * Called before the options are updated to check if this packet will
19877  * be source routed from here.
19878  * This routine assumes that the options are well formed i.e. that they
19879  * have already been checked.
19880  */
19881 static boolean_t
19882 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19883 {
19884 	ipoptp_t	opts;
19885 	uchar_t		*opt;
19886 	uint8_t		optval;
19887 	uint8_t		optlen;
19888 	ipaddr_t	dst;
19889 	ire_t		*ire;
19890 
19891 	if (IS_SIMPLE_IPH(ipha)) {
19892 		ip2dbg(("not source routed\n"));
19893 		return (B_FALSE);
19894 	}
19895 	dst = ipha->ipha_dst;
19896 	for (optval = ipoptp_first(&opts, ipha);
19897 	    optval != IPOPT_EOL;
19898 	    optval = ipoptp_next(&opts)) {
19899 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19900 		opt = opts.ipoptp_cur;
19901 		optlen = opts.ipoptp_len;
19902 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19903 		    optval, optlen));
19904 		switch (optval) {
19905 			uint32_t off;
19906 		case IPOPT_SSRR:
19907 		case IPOPT_LSRR:
19908 			/*
19909 			 * If dst is one of our addresses and there are some
19910 			 * entries left in the source route return (true).
19911 			 */
19912 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19913 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19914 			if (ire == NULL) {
19915 				ip2dbg(("ip_source_routed: not next"
19916 				    " source route 0x%x\n",
19917 				    ntohl(dst)));
19918 				return (B_FALSE);
19919 			}
19920 			ire_refrele(ire);
19921 			off = opt[IPOPT_OFFSET];
19922 			off--;
19923 			if (optlen < IP_ADDR_LEN ||
19924 			    off > optlen - IP_ADDR_LEN) {
19925 				/* End of source route */
19926 				ip1dbg(("ip_source_routed: end of SR\n"));
19927 				return (B_FALSE);
19928 			}
19929 			return (B_TRUE);
19930 		}
19931 	}
19932 	ip2dbg(("not source routed\n"));
19933 	return (B_FALSE);
19934 }
19935 
19936 /*
19937  * Check if the packet contains any source route.
19938  */
19939 static boolean_t
19940 ip_source_route_included(ipha_t *ipha)
19941 {
19942 	ipoptp_t	opts;
19943 	uint8_t		optval;
19944 
19945 	if (IS_SIMPLE_IPH(ipha))
19946 		return (B_FALSE);
19947 	for (optval = ipoptp_first(&opts, ipha);
19948 	    optval != IPOPT_EOL;
19949 	    optval = ipoptp_next(&opts)) {
19950 		switch (optval) {
19951 		case IPOPT_SSRR:
19952 		case IPOPT_LSRR:
19953 			return (B_TRUE);
19954 		}
19955 	}
19956 	return (B_FALSE);
19957 }
19958 
19959 /*
19960  * Called when the IRE expiration timer fires.
19961  */
19962 void
19963 ip_trash_timer_expire(void *args)
19964 {
19965 	int			flush_flag = 0;
19966 	ire_expire_arg_t	iea;
19967 	ip_stack_t		*ipst = (ip_stack_t *)args;
19968 
19969 	iea.iea_ipst = ipst;	/* No netstack_hold */
19970 
19971 	/*
19972 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19973 	 * This lock makes sure that a new invocation of this function
19974 	 * that occurs due to an almost immediate timer firing will not
19975 	 * progress beyond this point until the current invocation is done
19976 	 */
19977 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19978 	ipst->ips_ip_ire_expire_id = 0;
19979 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19980 
19981 	/* Periodic timer */
19982 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19983 	    ipst->ips_ip_ire_arp_interval) {
19984 		/*
19985 		 * Remove all IRE_CACHE entries since they might
19986 		 * contain arp information.
19987 		 */
19988 		flush_flag |= FLUSH_ARP_TIME;
19989 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19990 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19991 	}
19992 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19993 	    ipst->ips_ip_ire_redir_interval) {
19994 		/* Remove all redirects */
19995 		flush_flag |= FLUSH_REDIRECT_TIME;
19996 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19997 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19998 	}
19999 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20000 	    ipst->ips_ip_ire_pathmtu_interval) {
20001 		/* Increase path mtu */
20002 		flush_flag |= FLUSH_MTU_TIME;
20003 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20004 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20005 	}
20006 
20007 	/*
20008 	 * Optimize for the case when there are no redirects in the
20009 	 * ftable, that is, no need to walk the ftable in that case.
20010 	 */
20011 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20012 		iea.iea_flush_flag = flush_flag;
20013 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20014 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20015 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20016 		    NULL, ALL_ZONES, ipst);
20017 	}
20018 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20019 	    ipst->ips_ip_redirect_cnt > 0) {
20020 		iea.iea_flush_flag = flush_flag;
20021 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20022 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20023 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20024 	}
20025 	if (flush_flag & FLUSH_MTU_TIME) {
20026 		/*
20027 		 * Walk all IPv6 IRE's and update them
20028 		 * Note that ARP and redirect timers are not
20029 		 * needed since NUD handles stale entries.
20030 		 */
20031 		flush_flag = FLUSH_MTU_TIME;
20032 		iea.iea_flush_flag = flush_flag;
20033 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20034 		    ALL_ZONES, ipst);
20035 	}
20036 
20037 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20038 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20039 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20040 
20041 	/*
20042 	 * Hold the lock to serialize timeout calls and prevent
20043 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20044 	 * for the timer to fire and a new invocation of this function
20045 	 * to start before the return value of timeout has been stored
20046 	 * in ip_ire_expire_id by the current invocation.
20047 	 */
20048 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20049 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20050 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20051 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20052 }
20053 
20054 /*
20055  * Called by the memory allocator subsystem directly, when the system
20056  * is running low on memory.
20057  */
20058 /* ARGSUSED */
20059 void
20060 ip_trash_ire_reclaim(void *args)
20061 {
20062 	netstack_handle_t nh;
20063 	netstack_t *ns;
20064 
20065 	netstack_next_init(&nh);
20066 	while ((ns = netstack_next(&nh)) != NULL) {
20067 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20068 		netstack_rele(ns);
20069 	}
20070 	netstack_next_fini(&nh);
20071 }
20072 
20073 static void
20074 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20075 {
20076 	ire_cache_count_t icc;
20077 	ire_cache_reclaim_t icr;
20078 	ncc_cache_count_t ncc;
20079 	nce_cache_reclaim_t ncr;
20080 	uint_t delete_cnt;
20081 	/*
20082 	 * Memory reclaim call back.
20083 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20084 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20085 	 * entries, determine what fraction to free for
20086 	 * each category of IRE_CACHE entries giving absolute priority
20087 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20088 	 * entry will be freed unless all offlink entries are freed).
20089 	 */
20090 	icc.icc_total = 0;
20091 	icc.icc_unused = 0;
20092 	icc.icc_offlink = 0;
20093 	icc.icc_pmtu = 0;
20094 	icc.icc_onlink = 0;
20095 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20096 
20097 	/*
20098 	 * Free NCEs for IPv6 like the onlink ires.
20099 	 */
20100 	ncc.ncc_total = 0;
20101 	ncc.ncc_host = 0;
20102 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20103 
20104 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20105 	    icc.icc_pmtu + icc.icc_onlink);
20106 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20107 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20108 	if (delete_cnt == 0)
20109 		return;
20110 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20111 	/* Always delete all unused offlink entries */
20112 	icr.icr_ipst = ipst;
20113 	icr.icr_unused = 1;
20114 	if (delete_cnt <= icc.icc_unused) {
20115 		/*
20116 		 * Only need to free unused entries.  In other words,
20117 		 * there are enough unused entries to free to meet our
20118 		 * target number of freed ire cache entries.
20119 		 */
20120 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20121 		ncr.ncr_host = 0;
20122 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20123 		/*
20124 		 * Only need to free unused entries, plus a fraction of offlink
20125 		 * entries.  It follows from the first if statement that
20126 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20127 		 */
20128 		delete_cnt -= icc.icc_unused;
20129 		/* Round up # deleted by truncating fraction */
20130 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20131 		icr.icr_pmtu = icr.icr_onlink = 0;
20132 		ncr.ncr_host = 0;
20133 	} else if (delete_cnt <=
20134 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20135 		/*
20136 		 * Free all unused and offlink entries, plus a fraction of
20137 		 * pmtu entries.  It follows from the previous if statement
20138 		 * that icc_pmtu is non-zero, and that
20139 		 * delete_cnt != icc_unused + icc_offlink.
20140 		 */
20141 		icr.icr_offlink = 1;
20142 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20143 		/* Round up # deleted by truncating fraction */
20144 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20145 		icr.icr_onlink = 0;
20146 		ncr.ncr_host = 0;
20147 	} else {
20148 		/*
20149 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20150 		 * of onlink entries.  If we're here, then we know that
20151 		 * icc_onlink is non-zero, and that
20152 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20153 		 */
20154 		icr.icr_offlink = icr.icr_pmtu = 1;
20155 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20156 		    icc.icc_pmtu;
20157 		/* Round up # deleted by truncating fraction */
20158 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20159 		/* Using the same delete fraction as for onlink IREs */
20160 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20161 	}
20162 #ifdef DEBUG
20163 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20164 	    "fractions %d/%d/%d/%d\n",
20165 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20166 	    icc.icc_unused, icc.icc_offlink,
20167 	    icc.icc_pmtu, icc.icc_onlink,
20168 	    icr.icr_unused, icr.icr_offlink,
20169 	    icr.icr_pmtu, icr.icr_onlink));
20170 #endif
20171 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20172 	if (ncr.ncr_host != 0)
20173 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20174 		    (uchar_t *)&ncr, ipst);
20175 #ifdef DEBUG
20176 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20177 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20178 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20179 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20180 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20181 	    icc.icc_pmtu, icc.icc_onlink));
20182 #endif
20183 }
20184 
20185 /*
20186  * ip_unbind is called when a copy of an unbind request is received from the
20187  * upper level protocol.  We remove this conn from any fanout hash list it is
20188  * on, and zero out the bind information.  No reply is expected up above.
20189  */
20190 mblk_t *
20191 ip_unbind(queue_t *q, mblk_t *mp)
20192 {
20193 	conn_t	*connp = Q_TO_CONN(q);
20194 
20195 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20196 
20197 	if (is_system_labeled() && connp->conn_anon_port) {
20198 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20199 		    connp->conn_mlp_type, connp->conn_ulp,
20200 		    ntohs(connp->conn_lport), B_FALSE);
20201 		connp->conn_anon_port = 0;
20202 	}
20203 	connp->conn_mlp_type = mlptSingle;
20204 
20205 	ipcl_hash_remove(connp);
20206 
20207 	ASSERT(mp->b_cont == NULL);
20208 	/*
20209 	 * Convert mp into a T_OK_ACK
20210 	 */
20211 	mp = mi_tpi_ok_ack_alloc(mp);
20212 
20213 	/*
20214 	 * should not happen in practice... T_OK_ACK is smaller than the
20215 	 * original message.
20216 	 */
20217 	if (mp == NULL)
20218 		return (NULL);
20219 
20220 	/*
20221 	 * Don't bzero the ports if its TCP since TCP still needs the
20222 	 * lport to remove it from its own bind hash. TCP will do the
20223 	 * cleanup.
20224 	 */
20225 	if (!IPCL_IS_TCP(connp))
20226 		bzero(&connp->u_port, sizeof (connp->u_port));
20227 
20228 	return (mp);
20229 }
20230 
20231 /*
20232  * Write side put procedure.  Outbound data, IOCTLs, responses from
20233  * resolvers, etc, come down through here.
20234  *
20235  * arg2 is always a queue_t *.
20236  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20237  * the zoneid.
20238  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20239  */
20240 void
20241 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20242 {
20243 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20244 }
20245 
20246 void
20247 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20248     ip_opt_info_t *infop)
20249 {
20250 	conn_t		*connp = NULL;
20251 	queue_t		*q = (queue_t *)arg2;
20252 	ipha_t		*ipha;
20253 #define	rptr	((uchar_t *)ipha)
20254 	ire_t		*ire = NULL;
20255 	ire_t		*sctp_ire = NULL;
20256 	uint32_t	v_hlen_tos_len;
20257 	ipaddr_t	dst;
20258 	mblk_t		*first_mp = NULL;
20259 	boolean_t	mctl_present;
20260 	ipsec_out_t	*io;
20261 	int		match_flags;
20262 	ill_t		*attach_ill = NULL;
20263 					/* Bind to IPIF_NOFAILOVER ill etc. */
20264 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20265 	ipif_t		*dst_ipif;
20266 	boolean_t	multirt_need_resolve = B_FALSE;
20267 	mblk_t		*copy_mp = NULL;
20268 	int		err;
20269 	zoneid_t	zoneid;
20270 	int	adjust;
20271 	uint16_t iplen;
20272 	boolean_t	need_decref = B_FALSE;
20273 	boolean_t	ignore_dontroute = B_FALSE;
20274 	boolean_t	ignore_nexthop = B_FALSE;
20275 	boolean_t	ip_nexthop = B_FALSE;
20276 	ipaddr_t	nexthop_addr;
20277 	ip_stack_t	*ipst;
20278 
20279 #ifdef	_BIG_ENDIAN
20280 #define	V_HLEN	(v_hlen_tos_len >> 24)
20281 #else
20282 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20283 #endif
20284 
20285 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20286 	    "ip_wput_start: q %p", q);
20287 
20288 	/*
20289 	 * ip_wput fast path
20290 	 */
20291 
20292 	/* is packet from ARP ? */
20293 	if (q->q_next != NULL) {
20294 		zoneid = (zoneid_t)(uintptr_t)arg;
20295 		goto qnext;
20296 	}
20297 
20298 	connp = (conn_t *)arg;
20299 	ASSERT(connp != NULL);
20300 	zoneid = connp->conn_zoneid;
20301 	ipst = connp->conn_netstack->netstack_ip;
20302 
20303 	/* is queue flow controlled? */
20304 	if ((q->q_first != NULL || connp->conn_draining) &&
20305 	    (caller == IP_WPUT)) {
20306 		ASSERT(!need_decref);
20307 		(void) putq(q, mp);
20308 		return;
20309 	}
20310 
20311 	/* Multidata transmit? */
20312 	if (DB_TYPE(mp) == M_MULTIDATA) {
20313 		/*
20314 		 * We should never get here, since all Multidata messages
20315 		 * originating from tcp should have been directed over to
20316 		 * tcp_multisend() in the first place.
20317 		 */
20318 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20319 		freemsg(mp);
20320 		return;
20321 	} else if (DB_TYPE(mp) != M_DATA)
20322 		goto notdata;
20323 
20324 	if (mp->b_flag & MSGHASREF) {
20325 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20326 		mp->b_flag &= ~MSGHASREF;
20327 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20328 		need_decref = B_TRUE;
20329 	}
20330 	ipha = (ipha_t *)mp->b_rptr;
20331 
20332 	/* is IP header non-aligned or mblk smaller than basic IP header */
20333 #ifndef SAFETY_BEFORE_SPEED
20334 	if (!OK_32PTR(rptr) ||
20335 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20336 		goto hdrtoosmall;
20337 #endif
20338 
20339 	ASSERT(OK_32PTR(ipha));
20340 
20341 	/*
20342 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20343 	 * wrong version, we'll catch it again in ip_output_v6.
20344 	 *
20345 	 * Note that this is *only* locally-generated output here, and never
20346 	 * forwarded data, and that we need to deal only with transports that
20347 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20348 	 * label.)
20349 	 */
20350 	if (is_system_labeled() &&
20351 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20352 	    !connp->conn_ulp_labeled) {
20353 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20354 		    connp->conn_mac_exempt, ipst);
20355 		ipha = (ipha_t *)mp->b_rptr;
20356 		if (err != 0) {
20357 			first_mp = mp;
20358 			if (err == EINVAL)
20359 				goto icmp_parameter_problem;
20360 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20361 			goto discard_pkt;
20362 		}
20363 		iplen = ntohs(ipha->ipha_length) + adjust;
20364 		ipha->ipha_length = htons(iplen);
20365 	}
20366 
20367 	ASSERT(infop != NULL);
20368 
20369 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20370 		/*
20371 		 * IP_PKTINFO ancillary option is present.
20372 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20373 		 * allows using address of any zone as the source address.
20374 		 */
20375 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20376 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20377 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20378 		if (ire == NULL)
20379 			goto drop_pkt;
20380 		ire_refrele(ire);
20381 		ire = NULL;
20382 	}
20383 
20384 	/*
20385 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20386 	 * ill index passed in IP_PKTINFO.
20387 	 */
20388 	if (infop->ip_opt_ill_index != 0 &&
20389 	    connp->conn_xmit_if_ill == NULL &&
20390 	    connp->conn_nofailover_ill == NULL) {
20391 
20392 		xmit_ill = ill_lookup_on_ifindex(
20393 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20394 		    ipst);
20395 
20396 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20397 			goto drop_pkt;
20398 		/*
20399 		 * check that there is an ipif belonging
20400 		 * to our zone. IPCL_ZONEID is not used because
20401 		 * IP_ALLZONES option is valid only when the ill is
20402 		 * accessible from all zones i.e has a valid ipif in
20403 		 * all zones.
20404 		 */
20405 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20406 			goto drop_pkt;
20407 		}
20408 	}
20409 
20410 	/*
20411 	 * If there is a policy, try to attach an ipsec_out in
20412 	 * the front. At the end, first_mp either points to a
20413 	 * M_DATA message or IPSEC_OUT message linked to a
20414 	 * M_DATA message. We have to do it now as we might
20415 	 * lose the "conn" if we go through ip_newroute.
20416 	 */
20417 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20418 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
20419 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20420 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20421 			if (need_decref)
20422 				CONN_DEC_REF(connp);
20423 			return;
20424 		} else {
20425 			ASSERT(mp->b_datap->db_type == M_CTL);
20426 			first_mp = mp;
20427 			mp = mp->b_cont;
20428 			mctl_present = B_TRUE;
20429 		}
20430 	} else {
20431 		first_mp = mp;
20432 		mctl_present = B_FALSE;
20433 	}
20434 
20435 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20436 
20437 	/* is wrong version or IP options present */
20438 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20439 		goto version_hdrlen_check;
20440 	dst = ipha->ipha_dst;
20441 
20442 	if (connp->conn_nofailover_ill != NULL) {
20443 		attach_ill = conn_get_held_ill(connp,
20444 		    &connp->conn_nofailover_ill, &err);
20445 		if (err == ILL_LOOKUP_FAILED) {
20446 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20447 			if (need_decref)
20448 				CONN_DEC_REF(connp);
20449 			freemsg(first_mp);
20450 			return;
20451 		}
20452 	}
20453 
20454 
20455 	/* is packet multicast? */
20456 	if (CLASSD(dst))
20457 		goto multicast;
20458 
20459 	/*
20460 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20461 	 * takes precedence over conn_dontroute and conn_nexthop_set
20462 	 */
20463 	if (xmit_ill != NULL) {
20464 		goto send_from_ill;
20465 	}
20466 
20467 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20468 	    (connp->conn_nexthop_set)) {
20469 		/*
20470 		 * If the destination is a broadcast or a loopback
20471 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20472 		 * through the standard path. But in the case of local
20473 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20474 		 * the standard path not IP_XMIT_IF.
20475 		 */
20476 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20477 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20478 		    (ire->ire_type != IRE_LOOPBACK))) {
20479 			if ((connp->conn_dontroute ||
20480 			    connp->conn_nexthop_set) && (ire != NULL) &&
20481 			    (ire->ire_type == IRE_LOCAL))
20482 				goto standard_path;
20483 
20484 			if (ire != NULL) {
20485 				ire_refrele(ire);
20486 				/* No more access to ire */
20487 				ire = NULL;
20488 			}
20489 			/*
20490 			 * bypass routing checks and go directly to
20491 			 * interface.
20492 			 */
20493 			if (connp->conn_dontroute) {
20494 				goto dontroute;
20495 			} else if (connp->conn_nexthop_set) {
20496 				ip_nexthop = B_TRUE;
20497 				nexthop_addr = connp->conn_nexthop_v4;
20498 				goto send_from_ill;
20499 			}
20500 
20501 			/*
20502 			 * If IP_XMIT_IF socket option is set,
20503 			 * then we allow unicast and multicast
20504 			 * packets to go through the ill. It is
20505 			 * quite possible that the destination
20506 			 * is not in the ire cache table and we
20507 			 * do not want to go to ip_newroute()
20508 			 * instead we call ip_newroute_ipif.
20509 			 */
20510 			xmit_ill = conn_get_held_ill(connp,
20511 			    &connp->conn_xmit_if_ill, &err);
20512 			if (err == ILL_LOOKUP_FAILED) {
20513 				BUMP_MIB(&ipst->ips_ip_mib,
20514 				    ipIfStatsOutDiscards);
20515 				if (attach_ill != NULL)
20516 					ill_refrele(attach_ill);
20517 				if (need_decref)
20518 					CONN_DEC_REF(connp);
20519 				freemsg(first_mp);
20520 				return;
20521 			}
20522 			goto send_from_ill;
20523 		}
20524 standard_path:
20525 		/* Must be a broadcast, a loopback or a local ire */
20526 		if (ire != NULL) {
20527 			ire_refrele(ire);
20528 			/* No more access to ire */
20529 			ire = NULL;
20530 		}
20531 	}
20532 
20533 	if (attach_ill != NULL)
20534 		goto send_from_ill;
20535 
20536 	/*
20537 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20538 	 * this for the tcp global queue and listen end point
20539 	 * as it does not really have a real destination to
20540 	 * talk to.  This is also true for SCTP.
20541 	 */
20542 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20543 	    !connp->conn_fully_bound) {
20544 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20545 		if (ire == NULL)
20546 			goto noirefound;
20547 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20548 		    "ip_wput_end: q %p (%S)", q, "end");
20549 
20550 		/*
20551 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20552 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20553 		 */
20554 		if (ire->ire_flags & RTF_MULTIRT) {
20555 
20556 			/*
20557 			 * Force the TTL of multirouted packets if required.
20558 			 * The TTL of such packets is bounded by the
20559 			 * ip_multirt_ttl ndd variable.
20560 			 */
20561 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20562 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20563 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20564 				    "(was %d), dst 0x%08x\n",
20565 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20566 				    ntohl(ire->ire_addr)));
20567 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20568 			}
20569 			/*
20570 			 * We look at this point if there are pending
20571 			 * unresolved routes. ire_multirt_resolvable()
20572 			 * checks in O(n) that all IRE_OFFSUBNET ire
20573 			 * entries for the packet's destination and
20574 			 * flagged RTF_MULTIRT are currently resolved.
20575 			 * If some remain unresolved, we make a copy
20576 			 * of the current message. It will be used
20577 			 * to initiate additional route resolutions.
20578 			 */
20579 			multirt_need_resolve =
20580 			    ire_multirt_need_resolve(ire->ire_addr,
20581 			    MBLK_GETLABEL(first_mp), ipst);
20582 			ip2dbg(("ip_wput[TCP]: ire %p, "
20583 			    "multirt_need_resolve %d, first_mp %p\n",
20584 			    (void *)ire, multirt_need_resolve,
20585 			    (void *)first_mp));
20586 			if (multirt_need_resolve) {
20587 				copy_mp = copymsg(first_mp);
20588 				if (copy_mp != NULL) {
20589 					MULTIRT_DEBUG_TAG(copy_mp);
20590 				}
20591 			}
20592 		}
20593 
20594 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20595 
20596 		/*
20597 		 * Try to resolve another multiroute if
20598 		 * ire_multirt_need_resolve() deemed it necessary.
20599 		 */
20600 		if (copy_mp != NULL) {
20601 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20602 		}
20603 		if (need_decref)
20604 			CONN_DEC_REF(connp);
20605 		return;
20606 	}
20607 
20608 	/*
20609 	 * Access to conn_ire_cache. (protected by conn_lock)
20610 	 *
20611 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20612 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20613 	 * send a packet or two with the IRE_CACHE that is going away.
20614 	 * Access to the ire requires an ire refhold on the ire prior to
20615 	 * its use since an interface unplumb thread may delete the cached
20616 	 * ire and release the refhold at any time.
20617 	 *
20618 	 * Caching an ire in the conn_ire_cache
20619 	 *
20620 	 * o Caching an ire pointer in the conn requires a strict check for
20621 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20622 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20623 	 * in the conn is done after making sure under the bucket lock that the
20624 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20625 	 * caching an ire after the unplumb thread has cleaned up the conn.
20626 	 * If the conn does not send a packet subsequently the unplumb thread
20627 	 * will be hanging waiting for the ire count to drop to zero.
20628 	 *
20629 	 * o We also need to atomically test for a null conn_ire_cache and
20630 	 * set the conn_ire_cache under the the protection of the conn_lock
20631 	 * to avoid races among concurrent threads trying to simultaneously
20632 	 * cache an ire in the conn_ire_cache.
20633 	 */
20634 	mutex_enter(&connp->conn_lock);
20635 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20636 
20637 	if (ire != NULL && ire->ire_addr == dst &&
20638 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20639 
20640 		IRE_REFHOLD(ire);
20641 		mutex_exit(&connp->conn_lock);
20642 
20643 	} else {
20644 		boolean_t cached = B_FALSE;
20645 		connp->conn_ire_cache = NULL;
20646 		mutex_exit(&connp->conn_lock);
20647 		/* Release the old ire */
20648 		if (ire != NULL && sctp_ire == NULL)
20649 			IRE_REFRELE_NOTR(ire);
20650 
20651 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20652 		if (ire == NULL)
20653 			goto noirefound;
20654 		IRE_REFHOLD_NOTR(ire);
20655 
20656 		mutex_enter(&connp->conn_lock);
20657 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20658 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20659 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20660 				connp->conn_ire_cache = ire;
20661 				cached = B_TRUE;
20662 			}
20663 			rw_exit(&ire->ire_bucket->irb_lock);
20664 		}
20665 		mutex_exit(&connp->conn_lock);
20666 
20667 		/*
20668 		 * We can continue to use the ire but since it was
20669 		 * not cached, we should drop the extra reference.
20670 		 */
20671 		if (!cached)
20672 			IRE_REFRELE_NOTR(ire);
20673 	}
20674 
20675 
20676 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20677 	    "ip_wput_end: q %p (%S)", q, "end");
20678 
20679 	/*
20680 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20681 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20682 	 */
20683 	if (ire->ire_flags & RTF_MULTIRT) {
20684 
20685 		/*
20686 		 * Force the TTL of multirouted packets if required.
20687 		 * The TTL of such packets is bounded by the
20688 		 * ip_multirt_ttl ndd variable.
20689 		 */
20690 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20691 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20692 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20693 			    "(was %d), dst 0x%08x\n",
20694 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20695 			    ntohl(ire->ire_addr)));
20696 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20697 		}
20698 
20699 		/*
20700 		 * At this point, we check to see if there are any pending
20701 		 * unresolved routes. ire_multirt_resolvable()
20702 		 * checks in O(n) that all IRE_OFFSUBNET ire
20703 		 * entries for the packet's destination and
20704 		 * flagged RTF_MULTIRT are currently resolved.
20705 		 * If some remain unresolved, we make a copy
20706 		 * of the current message. It will be used
20707 		 * to initiate additional route resolutions.
20708 		 */
20709 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20710 		    MBLK_GETLABEL(first_mp), ipst);
20711 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20712 		    "multirt_need_resolve %d, first_mp %p\n",
20713 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20714 		if (multirt_need_resolve) {
20715 			copy_mp = copymsg(first_mp);
20716 			if (copy_mp != NULL) {
20717 				MULTIRT_DEBUG_TAG(copy_mp);
20718 			}
20719 		}
20720 	}
20721 
20722 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20723 
20724 	/*
20725 	 * Try to resolve another multiroute if
20726 	 * ire_multirt_resolvable() deemed it necessary
20727 	 */
20728 	if (copy_mp != NULL) {
20729 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20730 	}
20731 	if (need_decref)
20732 		CONN_DEC_REF(connp);
20733 	return;
20734 
20735 qnext:
20736 	/*
20737 	 * Upper Level Protocols pass down complete IP datagrams
20738 	 * as M_DATA messages.	Everything else is a sideshow.
20739 	 *
20740 	 * 1) We could be re-entering ip_wput because of ip_neworute
20741 	 *    in which case we could have a IPSEC_OUT message. We
20742 	 *    need to pass through ip_wput like other datagrams and
20743 	 *    hence cannot branch to ip_wput_nondata.
20744 	 *
20745 	 * 2) ARP, AH, ESP, and other clients who are on the module
20746 	 *    instance of IP stream, give us something to deal with.
20747 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20748 	 *
20749 	 * 3) ICMP replies also could come here.
20750 	 */
20751 	ipst = ILLQ_TO_IPST(q);
20752 
20753 	if (DB_TYPE(mp) != M_DATA) {
20754 	    notdata:
20755 		if (DB_TYPE(mp) == M_CTL) {
20756 			/*
20757 			 * M_CTL messages are used by ARP, AH and ESP to
20758 			 * communicate with IP. We deal with IPSEC_IN and
20759 			 * IPSEC_OUT here. ip_wput_nondata handles other
20760 			 * cases.
20761 			 */
20762 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20763 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20764 				first_mp = mp->b_cont;
20765 				first_mp->b_flag &= ~MSGHASREF;
20766 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20767 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20768 				CONN_DEC_REF(connp);
20769 				connp = NULL;
20770 			}
20771 			if (ii->ipsec_info_type == IPSEC_IN) {
20772 				/*
20773 				 * Either this message goes back to
20774 				 * IPSEC for further processing or to
20775 				 * ULP after policy checks.
20776 				 */
20777 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20778 				return;
20779 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20780 				io = (ipsec_out_t *)ii;
20781 				if (io->ipsec_out_proc_begin) {
20782 					/*
20783 					 * IPSEC processing has already started.
20784 					 * Complete it.
20785 					 * IPQoS notes: We don't care what is
20786 					 * in ipsec_out_ill_index since this
20787 					 * won't be processed for IPQoS policies
20788 					 * in ipsec_out_process.
20789 					 */
20790 					ipsec_out_process(q, mp, NULL,
20791 					    io->ipsec_out_ill_index);
20792 					return;
20793 				} else {
20794 					connp = (q->q_next != NULL) ?
20795 					    NULL : Q_TO_CONN(q);
20796 					first_mp = mp;
20797 					mp = mp->b_cont;
20798 					mctl_present = B_TRUE;
20799 				}
20800 				zoneid = io->ipsec_out_zoneid;
20801 				ASSERT(zoneid != ALL_ZONES);
20802 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20803 				/*
20804 				 * It's an IPsec control message requesting
20805 				 * an SADB update to be sent to the IPsec
20806 				 * hardware acceleration capable ills.
20807 				 */
20808 				ipsec_ctl_t *ipsec_ctl =
20809 				    (ipsec_ctl_t *)mp->b_rptr;
20810 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20811 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20812 				mblk_t *cmp = mp->b_cont;
20813 
20814 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20815 				ASSERT(cmp != NULL);
20816 
20817 				freeb(mp);
20818 				ill_ipsec_capab_send_all(satype, cmp, sa,
20819 				    ipst->ips_netstack);
20820 				return;
20821 			} else {
20822 				/*
20823 				 * This must be ARP or special TSOL signaling.
20824 				 */
20825 				ip_wput_nondata(NULL, q, mp, NULL);
20826 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20827 				    "ip_wput_end: q %p (%S)", q, "nondata");
20828 				return;
20829 			}
20830 		} else {
20831 			/*
20832 			 * This must be non-(ARP/AH/ESP) messages.
20833 			 */
20834 			ASSERT(!need_decref);
20835 			ip_wput_nondata(NULL, q, mp, NULL);
20836 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20837 			    "ip_wput_end: q %p (%S)", q, "nondata");
20838 			return;
20839 		}
20840 	} else {
20841 		first_mp = mp;
20842 		mctl_present = B_FALSE;
20843 	}
20844 
20845 	ASSERT(first_mp != NULL);
20846 	/*
20847 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20848 	 * to make sure that this packet goes out on the same interface it
20849 	 * came in. We handle that here.
20850 	 */
20851 	if (mctl_present) {
20852 		uint_t ifindex;
20853 
20854 		io = (ipsec_out_t *)first_mp->b_rptr;
20855 		if (io->ipsec_out_attach_if ||
20856 		    io->ipsec_out_xmit_if ||
20857 		    io->ipsec_out_ip_nexthop) {
20858 			ill_t	*ill;
20859 
20860 			/*
20861 			 * We may have lost the conn context if we are
20862 			 * coming here from ip_newroute(). Copy the
20863 			 * nexthop information.
20864 			 */
20865 			if (io->ipsec_out_ip_nexthop) {
20866 				ip_nexthop = B_TRUE;
20867 				nexthop_addr = io->ipsec_out_nexthop_addr;
20868 
20869 				ipha = (ipha_t *)mp->b_rptr;
20870 				dst = ipha->ipha_dst;
20871 				goto send_from_ill;
20872 			} else {
20873 				ASSERT(io->ipsec_out_ill_index != 0);
20874 				ifindex = io->ipsec_out_ill_index;
20875 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20876 				    NULL, NULL, NULL, NULL, ipst);
20877 				/*
20878 				 * ipsec_out_xmit_if bit is used to tell
20879 				 * ip_wput to use the ill to send outgoing data
20880 				 * as we have no conn when data comes from ICMP
20881 				 * error msg routines. Currently this feature is
20882 				 * only used by ip_mrtun_forward routine.
20883 				 */
20884 				if (io->ipsec_out_xmit_if) {
20885 					xmit_ill = ill;
20886 					if (xmit_ill == NULL) {
20887 						ip1dbg(("ip_output:bad ifindex "
20888 						    "for xmit_ill %d\n",
20889 						    ifindex));
20890 						freemsg(first_mp);
20891 						BUMP_MIB(&ipst->ips_ip_mib,
20892 						    ipIfStatsOutDiscards);
20893 						ASSERT(!need_decref);
20894 						return;
20895 					}
20896 					/* Free up the ipsec_out_t mblk */
20897 					ASSERT(first_mp->b_cont == mp);
20898 					first_mp->b_cont = NULL;
20899 					freeb(first_mp);
20900 					/* Just send the IP header+ICMP+data */
20901 					first_mp = mp;
20902 					ipha = (ipha_t *)mp->b_rptr;
20903 					dst = ipha->ipha_dst;
20904 					goto send_from_ill;
20905 				} else {
20906 					attach_ill = ill;
20907 				}
20908 
20909 				if (attach_ill == NULL) {
20910 					ASSERT(xmit_ill == NULL);
20911 					ip1dbg(("ip_output: bad ifindex for "
20912 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20913 					    ifindex));
20914 					freemsg(first_mp);
20915 					BUMP_MIB(&ipst->ips_ip_mib,
20916 					    ipIfStatsOutDiscards);
20917 					ASSERT(!need_decref);
20918 					return;
20919 				}
20920 			}
20921 		}
20922 	}
20923 
20924 	ASSERT(xmit_ill == NULL);
20925 
20926 	/* We have a complete IP datagram heading outbound. */
20927 	ipha = (ipha_t *)mp->b_rptr;
20928 
20929 #ifndef SPEED_BEFORE_SAFETY
20930 	/*
20931 	 * Make sure we have a full-word aligned message and that at least
20932 	 * a simple IP header is accessible in the first message.  If not,
20933 	 * try a pullup.
20934 	 */
20935 	if (!OK_32PTR(rptr) ||
20936 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20937 	    hdrtoosmall:
20938 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20939 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20940 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20941 			if (first_mp == NULL)
20942 				first_mp = mp;
20943 			goto discard_pkt;
20944 		}
20945 
20946 		/* This function assumes that mp points to an IPv4 packet. */
20947 		if (is_system_labeled() && q->q_next == NULL &&
20948 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20949 		    !connp->conn_ulp_labeled) {
20950 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20951 			    &adjust, connp->conn_mac_exempt, ipst);
20952 			ipha = (ipha_t *)mp->b_rptr;
20953 			if (first_mp != NULL)
20954 				first_mp->b_cont = mp;
20955 			if (err != 0) {
20956 				if (first_mp == NULL)
20957 					first_mp = mp;
20958 				if (err == EINVAL)
20959 					goto icmp_parameter_problem;
20960 				ip2dbg(("ip_wput: label check failed (%d)\n",
20961 				    err));
20962 				goto discard_pkt;
20963 			}
20964 			iplen = ntohs(ipha->ipha_length) + adjust;
20965 			ipha->ipha_length = htons(iplen);
20966 		}
20967 
20968 		ipha = (ipha_t *)mp->b_rptr;
20969 		if (first_mp == NULL) {
20970 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20971 			/*
20972 			 * If we got here because of "goto hdrtoosmall"
20973 			 * We need to attach a IPSEC_OUT.
20974 			 */
20975 			if (connp->conn_out_enforce_policy) {
20976 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20977 				    NULL, ipha->ipha_protocol,
20978 				    ipst->ips_netstack)) == NULL)) {
20979 					BUMP_MIB(&ipst->ips_ip_mib,
20980 					    ipIfStatsOutDiscards);
20981 					if (need_decref)
20982 						CONN_DEC_REF(connp);
20983 					return;
20984 				} else {
20985 					ASSERT(mp->b_datap->db_type == M_CTL);
20986 					first_mp = mp;
20987 					mp = mp->b_cont;
20988 					mctl_present = B_TRUE;
20989 				}
20990 			} else {
20991 				first_mp = mp;
20992 				mctl_present = B_FALSE;
20993 			}
20994 		}
20995 	}
20996 #endif
20997 
20998 	/* Most of the code below is written for speed, not readability */
20999 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21000 
21001 	/*
21002 	 * If ip_newroute() fails, we're going to need a full
21003 	 * header for the icmp wraparound.
21004 	 */
21005 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21006 		uint_t	v_hlen;
21007 	    version_hdrlen_check:
21008 		ASSERT(first_mp != NULL);
21009 		v_hlen = V_HLEN;
21010 		/*
21011 		 * siphon off IPv6 packets coming down from transport
21012 		 * layer modules here.
21013 		 * Note: high-order bit carries NUD reachability confirmation
21014 		 */
21015 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21016 			/*
21017 			 * XXX implement a IPv4 and IPv6 packet counter per
21018 			 * conn and switch when ratio exceeds e.g. 10:1
21019 			 */
21020 #ifdef notyet
21021 			if (q->q_next == NULL) /* Avoid ill queue */
21022 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
21023 #endif
21024 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21025 			ASSERT(xmit_ill == NULL);
21026 			if (attach_ill != NULL)
21027 				ill_refrele(attach_ill);
21028 			if (need_decref)
21029 				mp->b_flag |= MSGHASREF;
21030 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21031 			return;
21032 		}
21033 
21034 		if ((v_hlen >> 4) != IP_VERSION) {
21035 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21036 			    "ip_wput_end: q %p (%S)", q, "badvers");
21037 			goto discard_pkt;
21038 		}
21039 		/*
21040 		 * Is the header length at least 20 bytes?
21041 		 *
21042 		 * Are there enough bytes accessible in the header?  If
21043 		 * not, try a pullup.
21044 		 */
21045 		v_hlen &= 0xF;
21046 		v_hlen <<= 2;
21047 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21048 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21049 			    "ip_wput_end: q %p (%S)", q, "badlen");
21050 			goto discard_pkt;
21051 		}
21052 		if (v_hlen > (mp->b_wptr - rptr)) {
21053 			if (!pullupmsg(mp, v_hlen)) {
21054 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21055 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21056 				goto discard_pkt;
21057 			}
21058 			ipha = (ipha_t *)mp->b_rptr;
21059 		}
21060 		/*
21061 		 * Move first entry from any source route into ipha_dst and
21062 		 * verify the options
21063 		 */
21064 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21065 			zoneid, ipst)) {
21066 			ASSERT(xmit_ill == NULL);
21067 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21068 			if (attach_ill != NULL)
21069 				ill_refrele(attach_ill);
21070 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21071 			    "ip_wput_end: q %p (%S)", q, "badopts");
21072 			if (need_decref)
21073 				CONN_DEC_REF(connp);
21074 			return;
21075 		}
21076 	}
21077 	dst = ipha->ipha_dst;
21078 
21079 	/*
21080 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21081 	 * we have to run the packet through ip_newroute which will take
21082 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21083 	 * a resolver, or assigning a default gateway, etc.
21084 	 */
21085 	if (CLASSD(dst)) {
21086 		ipif_t	*ipif;
21087 		uint32_t setsrc = 0;
21088 
21089 	    multicast:
21090 		ASSERT(first_mp != NULL);
21091 		ip2dbg(("ip_wput: CLASSD\n"));
21092 		if (connp == NULL) {
21093 			/*
21094 			 * Use the first good ipif on the ill.
21095 			 * XXX Should this ever happen? (Appears
21096 			 * to show up with just ppp and no ethernet due
21097 			 * to in.rdisc.)
21098 			 * However, ire_send should be able to
21099 			 * call ip_wput_ire directly.
21100 			 *
21101 			 * XXX Also, this can happen for ICMP and other packets
21102 			 * with multicast source addresses.  Perhaps we should
21103 			 * fix things so that we drop the packet in question,
21104 			 * but for now, just run with it.
21105 			 */
21106 			ill_t *ill = (ill_t *)q->q_ptr;
21107 
21108 			/*
21109 			 * Don't honor attach_if for this case. If ill
21110 			 * is part of the group, ipif could belong to
21111 			 * any ill and we cannot maintain attach_ill
21112 			 * and ipif_ill same anymore and the assert
21113 			 * below would fail.
21114 			 */
21115 			if (mctl_present && io->ipsec_out_attach_if) {
21116 				io->ipsec_out_ill_index = 0;
21117 				io->ipsec_out_attach_if = B_FALSE;
21118 				ASSERT(attach_ill != NULL);
21119 				ill_refrele(attach_ill);
21120 				attach_ill = NULL;
21121 			}
21122 
21123 			ASSERT(attach_ill == NULL);
21124 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21125 			if (ipif == NULL) {
21126 				if (need_decref)
21127 					CONN_DEC_REF(connp);
21128 				freemsg(first_mp);
21129 				return;
21130 			}
21131 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21132 			    ntohl(dst), ill->ill_name));
21133 		} else {
21134 			/*
21135 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21136 			 * and IP_MULTICAST_IF.
21137 			 * Block comment above this function explains the
21138 			 * locking mechanism used here
21139 			 */
21140 			if (xmit_ill == NULL) {
21141 				xmit_ill = conn_get_held_ill(connp,
21142 				    &connp->conn_xmit_if_ill, &err);
21143 				if (err == ILL_LOOKUP_FAILED) {
21144 					ip1dbg(("ip_wput: No ill for "
21145 					    "IP_XMIT_IF\n"));
21146 					BUMP_MIB(&ipst->ips_ip_mib,
21147 					    ipIfStatsOutNoRoutes);
21148 					goto drop_pkt;
21149 				}
21150 			}
21151 
21152 			if (xmit_ill == NULL) {
21153 				ipif = conn_get_held_ipif(connp,
21154 				    &connp->conn_multicast_ipif, &err);
21155 				if (err == IPIF_LOOKUP_FAILED) {
21156 					ip1dbg(("ip_wput: No ipif for "
21157 					    "multicast\n"));
21158 					BUMP_MIB(&ipst->ips_ip_mib,
21159 					    ipIfStatsOutNoRoutes);
21160 					goto drop_pkt;
21161 				}
21162 			}
21163 			if (xmit_ill != NULL) {
21164 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21165 				if (ipif == NULL) {
21166 					ip1dbg(("ip_wput: No ipif for "
21167 					    "IP_XMIT_IF\n"));
21168 					BUMP_MIB(&ipst->ips_ip_mib,
21169 					    ipIfStatsOutNoRoutes);
21170 					goto drop_pkt;
21171 				}
21172 			} else if (ipif == NULL || ipif->ipif_isv6) {
21173 				/*
21174 				 * We must do this ipif determination here
21175 				 * else we could pass through ip_newroute
21176 				 * and come back here without the conn context.
21177 				 *
21178 				 * Note: we do late binding i.e. we bind to
21179 				 * the interface when the first packet is sent.
21180 				 * For performance reasons we do not rebind on
21181 				 * each packet but keep the binding until the
21182 				 * next IP_MULTICAST_IF option.
21183 				 *
21184 				 * conn_multicast_{ipif,ill} are shared between
21185 				 * IPv4 and IPv6 and AF_INET6 sockets can
21186 				 * send both IPv4 and IPv6 packets. Hence
21187 				 * we have to check that "isv6" matches above.
21188 				 */
21189 				if (ipif != NULL)
21190 					ipif_refrele(ipif);
21191 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21192 				if (ipif == NULL) {
21193 					ip1dbg(("ip_wput: No ipif for "
21194 					    "multicast\n"));
21195 					BUMP_MIB(&ipst->ips_ip_mib,
21196 					    ipIfStatsOutNoRoutes);
21197 					goto drop_pkt;
21198 				}
21199 				err = conn_set_held_ipif(connp,
21200 				    &connp->conn_multicast_ipif, ipif);
21201 				if (err == IPIF_LOOKUP_FAILED) {
21202 					ipif_refrele(ipif);
21203 					ip1dbg(("ip_wput: No ipif for "
21204 					    "multicast\n"));
21205 					BUMP_MIB(&ipst->ips_ip_mib,
21206 					    ipIfStatsOutNoRoutes);
21207 					goto drop_pkt;
21208 				}
21209 			}
21210 		}
21211 		ASSERT(!ipif->ipif_isv6);
21212 		/*
21213 		 * As we may lose the conn by the time we reach ip_wput_ire,
21214 		 * we copy conn_multicast_loop and conn_dontroute on to an
21215 		 * ipsec_out. In case if this datagram goes out secure,
21216 		 * we need the ill_index also. Copy that also into the
21217 		 * ipsec_out.
21218 		 */
21219 		if (mctl_present) {
21220 			io = (ipsec_out_t *)first_mp->b_rptr;
21221 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21222 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21223 		} else {
21224 			ASSERT(mp == first_mp);
21225 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21226 			    BPRI_HI)) == NULL) {
21227 				ipif_refrele(ipif);
21228 				first_mp = mp;
21229 				goto discard_pkt;
21230 			}
21231 			first_mp->b_datap->db_type = M_CTL;
21232 			first_mp->b_wptr += sizeof (ipsec_info_t);
21233 			/* ipsec_out_secure is B_FALSE now */
21234 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21235 			io = (ipsec_out_t *)first_mp->b_rptr;
21236 			io->ipsec_out_type = IPSEC_OUT;
21237 			io->ipsec_out_len = sizeof (ipsec_out_t);
21238 			io->ipsec_out_use_global_policy = B_TRUE;
21239 			io->ipsec_out_ns = ipst->ips_netstack;
21240 			first_mp->b_cont = mp;
21241 			mctl_present = B_TRUE;
21242 		}
21243 		if (attach_ill != NULL) {
21244 			ASSERT(attach_ill == ipif->ipif_ill);
21245 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21246 
21247 			/*
21248 			 * Check if we need an ire that will not be
21249 			 * looked up by anybody else i.e. HIDDEN.
21250 			 */
21251 			if (ill_is_probeonly(attach_ill)) {
21252 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21253 			}
21254 			io->ipsec_out_ill_index =
21255 			    attach_ill->ill_phyint->phyint_ifindex;
21256 			io->ipsec_out_attach_if = B_TRUE;
21257 		} else {
21258 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21259 			io->ipsec_out_ill_index =
21260 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21261 		}
21262 		if (connp != NULL) {
21263 			io->ipsec_out_multicast_loop =
21264 			    connp->conn_multicast_loop;
21265 			io->ipsec_out_dontroute = connp->conn_dontroute;
21266 			io->ipsec_out_zoneid = connp->conn_zoneid;
21267 		}
21268 		/*
21269 		 * If the application uses IP_MULTICAST_IF with
21270 		 * different logical addresses of the same ILL, we
21271 		 * need to make sure that the soruce address of
21272 		 * the packet matches the logical IP address used
21273 		 * in the option. We do it by initializing ipha_src
21274 		 * here. This should keep IPSEC also happy as
21275 		 * when we return from IPSEC processing, we don't
21276 		 * have to worry about getting the right address on
21277 		 * the packet. Thus it is sufficient to look for
21278 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21279 		 * MATCH_IRE_IPIF.
21280 		 *
21281 		 * NOTE : We need to do it for non-secure case also as
21282 		 * this might go out secure if there is a global policy
21283 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21284 		 * address, the source should be initialized already and
21285 		 * hence we won't be initializing here.
21286 		 *
21287 		 * As we do not have the ire yet, it is possible that
21288 		 * we set the source address here and then later discover
21289 		 * that the ire implies the source address to be assigned
21290 		 * through the RTF_SETSRC flag.
21291 		 * In that case, the setsrc variable will remind us
21292 		 * that overwritting the source address by the one
21293 		 * of the RTF_SETSRC-flagged ire is allowed.
21294 		 */
21295 		if (ipha->ipha_src == INADDR_ANY &&
21296 		    (connp == NULL || !connp->conn_unspec_src)) {
21297 			ipha->ipha_src = ipif->ipif_src_addr;
21298 			setsrc = RTF_SETSRC;
21299 		}
21300 		/*
21301 		 * Find an IRE which matches the destination and the outgoing
21302 		 * queue (i.e. the outgoing interface.)
21303 		 * For loopback use a unicast IP address for
21304 		 * the ire lookup.
21305 		 */
21306 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
21307 		    PHYI_LOOPBACK) {
21308 			dst = ipif->ipif_lcl_addr;
21309 		}
21310 		/*
21311 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21312 		 * We don't need to lookup ire in ctable as the packet
21313 		 * needs to be sent to the destination through the specified
21314 		 * ill irrespective of ires in the cache table.
21315 		 */
21316 		ire = NULL;
21317 		if (xmit_ill == NULL) {
21318 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21319 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21320 		}
21321 
21322 		/*
21323 		 * refrele attach_ill as its not needed anymore.
21324 		 */
21325 		if (attach_ill != NULL) {
21326 			ill_refrele(attach_ill);
21327 			attach_ill = NULL;
21328 		}
21329 
21330 		if (ire == NULL) {
21331 			/*
21332 			 * Multicast loopback and multicast forwarding is
21333 			 * done in ip_wput_ire.
21334 			 *
21335 			 * Mark this packet to make it be delivered to
21336 			 * ip_wput_ire after the new ire has been
21337 			 * created.
21338 			 *
21339 			 * The call to ip_newroute_ipif takes into account
21340 			 * the setsrc reminder. In any case, we take care
21341 			 * of the RTF_MULTIRT flag.
21342 			 */
21343 			mp->b_prev = mp->b_next = NULL;
21344 			if (xmit_ill == NULL ||
21345 			    xmit_ill->ill_ipif_up_count > 0) {
21346 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21347 				    setsrc | RTF_MULTIRT, zoneid, infop);
21348 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21349 				    "ip_wput_end: q %p (%S)", q, "noire");
21350 			} else {
21351 				freemsg(first_mp);
21352 			}
21353 			ipif_refrele(ipif);
21354 			if (xmit_ill != NULL)
21355 				ill_refrele(xmit_ill);
21356 			if (need_decref)
21357 				CONN_DEC_REF(connp);
21358 			return;
21359 		}
21360 
21361 		ipif_refrele(ipif);
21362 		ipif = NULL;
21363 		ASSERT(xmit_ill == NULL);
21364 
21365 		/*
21366 		 * Honor the RTF_SETSRC flag for multicast packets,
21367 		 * if allowed by the setsrc reminder.
21368 		 */
21369 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21370 			ipha->ipha_src = ire->ire_src_addr;
21371 		}
21372 
21373 		/*
21374 		 * Unconditionally force the TTL to 1 for
21375 		 * multirouted multicast packets:
21376 		 * multirouted multicast should not cross
21377 		 * multicast routers.
21378 		 */
21379 		if (ire->ire_flags & RTF_MULTIRT) {
21380 			if (ipha->ipha_ttl > 1) {
21381 				ip2dbg(("ip_wput: forcing multicast "
21382 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21383 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21384 				ipha->ipha_ttl = 1;
21385 			}
21386 		}
21387 	} else {
21388 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21389 		if ((ire != NULL) && (ire->ire_type &
21390 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21391 			ignore_dontroute = B_TRUE;
21392 			ignore_nexthop = B_TRUE;
21393 		}
21394 		if (ire != NULL) {
21395 			ire_refrele(ire);
21396 			ire = NULL;
21397 		}
21398 		/*
21399 		 * Guard against coming in from arp in which case conn is NULL.
21400 		 * Also guard against non M_DATA with dontroute set but
21401 		 * destined to local, loopback or broadcast addresses.
21402 		 */
21403 		if (connp != NULL && connp->conn_dontroute &&
21404 		    !ignore_dontroute) {
21405 dontroute:
21406 			/*
21407 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21408 			 * routing protocols from seeing false direct
21409 			 * connectivity.
21410 			 */
21411 			ipha->ipha_ttl = 1;
21412 			/*
21413 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21414 			 * along with SO_DONTROUTE, higher precedence is
21415 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21416 			 */
21417 			if (connp->conn_xmit_if_ill == NULL) {
21418 				/* If suitable ipif not found, drop packet */
21419 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21420 				    ipst);
21421 				if (dst_ipif == NULL) {
21422 					ip1dbg(("ip_wput: no route for "
21423 					    "dst using SO_DONTROUTE\n"));
21424 					BUMP_MIB(&ipst->ips_ip_mib,
21425 					    ipIfStatsOutNoRoutes);
21426 					mp->b_prev = mp->b_next = NULL;
21427 					if (first_mp == NULL)
21428 						first_mp = mp;
21429 					goto drop_pkt;
21430 				} else {
21431 					/*
21432 					 * If suitable ipif has been found, set
21433 					 * xmit_ill to the corresponding
21434 					 * ipif_ill because we'll be following
21435 					 * the IP_XMIT_IF logic.
21436 					 */
21437 					ASSERT(xmit_ill == NULL);
21438 					xmit_ill = dst_ipif->ipif_ill;
21439 					mutex_enter(&xmit_ill->ill_lock);
21440 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21441 						mutex_exit(&xmit_ill->ill_lock);
21442 						xmit_ill = NULL;
21443 						ipif_refrele(dst_ipif);
21444 						ip1dbg(("ip_wput: no route for"
21445 						    " dst using"
21446 						    " SO_DONTROUTE\n"));
21447 						BUMP_MIB(&ipst->ips_ip_mib,
21448 						    ipIfStatsOutNoRoutes);
21449 						mp->b_prev = mp->b_next = NULL;
21450 						if (first_mp == NULL)
21451 							first_mp = mp;
21452 						goto drop_pkt;
21453 					}
21454 					ill_refhold_locked(xmit_ill);
21455 					mutex_exit(&xmit_ill->ill_lock);
21456 					ipif_refrele(dst_ipif);
21457 				}
21458 			}
21459 
21460 		}
21461 		/*
21462 		 * If we are bound to IPIF_NOFAILOVER address, look for
21463 		 * an IRE_CACHE matching the ill.
21464 		 */
21465 send_from_ill:
21466 		if (attach_ill != NULL) {
21467 			ipif_t	*attach_ipif;
21468 
21469 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21470 
21471 			/*
21472 			 * Check if we need an ire that will not be
21473 			 * looked up by anybody else i.e. HIDDEN.
21474 			 */
21475 			if (ill_is_probeonly(attach_ill)) {
21476 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21477 			}
21478 
21479 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21480 			if (attach_ipif == NULL) {
21481 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21482 				goto discard_pkt;
21483 			}
21484 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21485 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21486 			ipif_refrele(attach_ipif);
21487 		} else if (xmit_ill != NULL || (connp != NULL &&
21488 			    connp->conn_xmit_if_ill != NULL)) {
21489 			/*
21490 			 * Mark this packet as originated locally
21491 			 */
21492 			mp->b_prev = mp->b_next = NULL;
21493 			/*
21494 			 * xmit_ill could be NULL if SO_DONTROUTE
21495 			 * is also set.
21496 			 */
21497 			if (xmit_ill == NULL) {
21498 				xmit_ill = conn_get_held_ill(connp,
21499 				    &connp->conn_xmit_if_ill, &err);
21500 				if (err == ILL_LOOKUP_FAILED) {
21501 					BUMP_MIB(&ipst->ips_ip_mib,
21502 					    ipIfStatsOutDiscards);
21503 					if (need_decref)
21504 						CONN_DEC_REF(connp);
21505 					freemsg(first_mp);
21506 					return;
21507 				}
21508 				if (xmit_ill == NULL) {
21509 					if (connp->conn_dontroute)
21510 						goto dontroute;
21511 					goto send_from_ill;
21512 				}
21513 			}
21514 			/*
21515 			 * Could be SO_DONTROUTE case also.
21516 			 * check at least one interface is UP as
21517 			 * specified by this ILL
21518 			 */
21519 			if (xmit_ill->ill_ipif_up_count > 0) {
21520 				ipif_t *ipif;
21521 
21522 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21523 				if (ipif == NULL) {
21524 					ip1dbg(("ip_output: "
21525 					    "xmit_ill NULL ipif\n"));
21526 					goto drop_pkt;
21527 				}
21528 				/*
21529 				 * Look for a ire that is part of the group,
21530 				 * if found use it else call ip_newroute_ipif.
21531 				 * IPCL_ZONEID is not used for matching because
21532 				 * IP_ALLZONES option is valid only when the
21533 				 * ill is accessible from all zones i.e has a
21534 				 * valid ipif in all zones.
21535 				 */
21536 				match_flags = MATCH_IRE_ILL_GROUP |
21537 				    MATCH_IRE_SECATTR;
21538 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21539 				    MBLK_GETLABEL(mp), match_flags, ipst);
21540 				/*
21541 				 * If an ire exists use it or else create
21542 				 * an ire but don't add it to the cache.
21543 				 * Adding an ire may cause issues with
21544 				 * asymmetric routing.
21545 				 * In case of multiroute always act as if
21546 				 * ire does not exist.
21547 				 */
21548 				if (ire == NULL ||
21549 				    ire->ire_flags & RTF_MULTIRT) {
21550 					if (ire != NULL)
21551 						ire_refrele(ire);
21552 					ip_newroute_ipif(q, first_mp, ipif,
21553 					    dst, connp, 0, zoneid, infop);
21554 					ipif_refrele(ipif);
21555 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21556 					ill_refrele(xmit_ill);
21557 					if (need_decref)
21558 						CONN_DEC_REF(connp);
21559 					return;
21560 				}
21561 				ipif_refrele(ipif);
21562 			} else {
21563 				goto drop_pkt;
21564 			}
21565 		} else if (ip_nexthop || (connp != NULL &&
21566 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21567 			if (!ip_nexthop) {
21568 				ip_nexthop = B_TRUE;
21569 				nexthop_addr = connp->conn_nexthop_v4;
21570 			}
21571 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21572 			    MATCH_IRE_GW;
21573 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21574 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21575 		} else {
21576 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21577 			    ipst);
21578 		}
21579 		if (!ire) {
21580 			/*
21581 			 * Make sure we don't load spread if this
21582 			 * is IPIF_NOFAILOVER case.
21583 			 */
21584 			if ((attach_ill != NULL) ||
21585 			    (ip_nexthop && !ignore_nexthop)) {
21586 				if (mctl_present) {
21587 					io = (ipsec_out_t *)first_mp->b_rptr;
21588 					ASSERT(first_mp->b_datap->db_type ==
21589 					    M_CTL);
21590 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21591 				} else {
21592 					ASSERT(mp == first_mp);
21593 					first_mp = allocb(
21594 					    sizeof (ipsec_info_t), BPRI_HI);
21595 					if (first_mp == NULL) {
21596 						first_mp = mp;
21597 						goto discard_pkt;
21598 					}
21599 					first_mp->b_datap->db_type = M_CTL;
21600 					first_mp->b_wptr +=
21601 					    sizeof (ipsec_info_t);
21602 					/* ipsec_out_secure is B_FALSE now */
21603 					bzero(first_mp->b_rptr,
21604 					    sizeof (ipsec_info_t));
21605 					io = (ipsec_out_t *)first_mp->b_rptr;
21606 					io->ipsec_out_type = IPSEC_OUT;
21607 					io->ipsec_out_len =
21608 					    sizeof (ipsec_out_t);
21609 					io->ipsec_out_use_global_policy =
21610 					    B_TRUE;
21611 					io->ipsec_out_ns = ipst->ips_netstack;
21612 					first_mp->b_cont = mp;
21613 					mctl_present = B_TRUE;
21614 				}
21615 				if (attach_ill != NULL) {
21616 					io->ipsec_out_ill_index = attach_ill->
21617 					    ill_phyint->phyint_ifindex;
21618 					io->ipsec_out_attach_if = B_TRUE;
21619 				} else {
21620 					io->ipsec_out_ip_nexthop = ip_nexthop;
21621 					io->ipsec_out_nexthop_addr =
21622 					    nexthop_addr;
21623 				}
21624 			}
21625 noirefound:
21626 			/*
21627 			 * Mark this packet as having originated on
21628 			 * this machine.  This will be noted in
21629 			 * ire_add_then_send, which needs to know
21630 			 * whether to run it back through ip_wput or
21631 			 * ip_rput following successful resolution.
21632 			 */
21633 			mp->b_prev = NULL;
21634 			mp->b_next = NULL;
21635 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21636 			    ipst);
21637 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21638 			    "ip_wput_end: q %p (%S)", q, "newroute");
21639 			if (attach_ill != NULL)
21640 				ill_refrele(attach_ill);
21641 			if (xmit_ill != NULL)
21642 				ill_refrele(xmit_ill);
21643 			if (need_decref)
21644 				CONN_DEC_REF(connp);
21645 			return;
21646 		}
21647 	}
21648 
21649 	/* We now know where we are going with it. */
21650 
21651 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21652 	    "ip_wput_end: q %p (%S)", q, "end");
21653 
21654 	/*
21655 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21656 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21657 	 */
21658 	if (ire->ire_flags & RTF_MULTIRT) {
21659 		/*
21660 		 * Force the TTL of multirouted packets if required.
21661 		 * The TTL of such packets is bounded by the
21662 		 * ip_multirt_ttl ndd variable.
21663 		 */
21664 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21665 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21666 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21667 			    "(was %d), dst 0x%08x\n",
21668 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21669 			    ntohl(ire->ire_addr)));
21670 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21671 		}
21672 		/*
21673 		 * At this point, we check to see if there are any pending
21674 		 * unresolved routes. ire_multirt_resolvable()
21675 		 * checks in O(n) that all IRE_OFFSUBNET ire
21676 		 * entries for the packet's destination and
21677 		 * flagged RTF_MULTIRT are currently resolved.
21678 		 * If some remain unresolved, we make a copy
21679 		 * of the current message. It will be used
21680 		 * to initiate additional route resolutions.
21681 		 */
21682 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21683 		    MBLK_GETLABEL(first_mp), ipst);
21684 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21685 		    "multirt_need_resolve %d, first_mp %p\n",
21686 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21687 		if (multirt_need_resolve) {
21688 			copy_mp = copymsg(first_mp);
21689 			if (copy_mp != NULL) {
21690 				MULTIRT_DEBUG_TAG(copy_mp);
21691 			}
21692 		}
21693 	}
21694 
21695 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21696 	/*
21697 	 * Try to resolve another multiroute if
21698 	 * ire_multirt_resolvable() deemed it necessary.
21699 	 * At this point, we need to distinguish
21700 	 * multicasts from other packets. For multicasts,
21701 	 * we call ip_newroute_ipif() and request that both
21702 	 * multirouting and setsrc flags are checked.
21703 	 */
21704 	if (copy_mp != NULL) {
21705 		if (CLASSD(dst)) {
21706 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21707 			if (ipif) {
21708 				ASSERT(infop->ip_opt_ill_index == 0);
21709 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21710 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21711 				ipif_refrele(ipif);
21712 			} else {
21713 				MULTIRT_DEBUG_UNTAG(copy_mp);
21714 				freemsg(copy_mp);
21715 				copy_mp = NULL;
21716 			}
21717 		} else {
21718 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21719 		}
21720 	}
21721 	if (attach_ill != NULL)
21722 		ill_refrele(attach_ill);
21723 	if (xmit_ill != NULL)
21724 		ill_refrele(xmit_ill);
21725 	if (need_decref)
21726 		CONN_DEC_REF(connp);
21727 	return;
21728 
21729 icmp_parameter_problem:
21730 	/* could not have originated externally */
21731 	ASSERT(mp->b_prev == NULL);
21732 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21733 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21734 		/* it's the IP header length that's in trouble */
21735 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21736 		first_mp = NULL;
21737 	}
21738 
21739 discard_pkt:
21740 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21741 drop_pkt:
21742 	ip1dbg(("ip_wput: dropped packet\n"));
21743 	if (ire != NULL)
21744 		ire_refrele(ire);
21745 	if (need_decref)
21746 		CONN_DEC_REF(connp);
21747 	freemsg(first_mp);
21748 	if (attach_ill != NULL)
21749 		ill_refrele(attach_ill);
21750 	if (xmit_ill != NULL)
21751 		ill_refrele(xmit_ill);
21752 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21753 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21754 }
21755 
21756 /*
21757  * If this is a conn_t queue, then we pass in the conn. This includes the
21758  * zoneid.
21759  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21760  * in which case we use the global zoneid since those are all part of
21761  * the global zone.
21762  */
21763 void
21764 ip_wput(queue_t *q, mblk_t *mp)
21765 {
21766 	if (CONN_Q(q))
21767 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21768 	else
21769 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21770 }
21771 
21772 /*
21773  *
21774  * The following rules must be observed when accessing any ipif or ill
21775  * that has been cached in the conn. Typically conn_nofailover_ill,
21776  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21777  *
21778  * Access: The ipif or ill pointed to from the conn can be accessed under
21779  * the protection of the conn_lock or after it has been refheld under the
21780  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21781  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21782  * The reason for this is that a concurrent unplumb could actually be
21783  * cleaning up these cached pointers by walking the conns and might have
21784  * finished cleaning up the conn in question. The macros check that an
21785  * unplumb has not yet started on the ipif or ill.
21786  *
21787  * Caching: An ipif or ill pointer may be cached in the conn only after
21788  * making sure that an unplumb has not started. So the caching is done
21789  * while holding both the conn_lock and the ill_lock and after using the
21790  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21791  * flag before starting the cleanup of conns.
21792  *
21793  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21794  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21795  * or a reference to the ipif or a reference to an ire that references the
21796  * ipif. An ipif does not change its ill except for failover/failback. Since
21797  * failover/failback happens only after bringing down the ipif and making sure
21798  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21799  * the above holds.
21800  */
21801 ipif_t *
21802 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21803 {
21804 	ipif_t	*ipif;
21805 	ill_t	*ill;
21806 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21807 
21808 	*err = 0;
21809 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21810 	mutex_enter(&connp->conn_lock);
21811 	ipif = *ipifp;
21812 	if (ipif != NULL) {
21813 		ill = ipif->ipif_ill;
21814 		mutex_enter(&ill->ill_lock);
21815 		if (IPIF_CAN_LOOKUP(ipif)) {
21816 			ipif_refhold_locked(ipif);
21817 			mutex_exit(&ill->ill_lock);
21818 			mutex_exit(&connp->conn_lock);
21819 			rw_exit(&ipst->ips_ill_g_lock);
21820 			return (ipif);
21821 		} else {
21822 			*err = IPIF_LOOKUP_FAILED;
21823 		}
21824 		mutex_exit(&ill->ill_lock);
21825 	}
21826 	mutex_exit(&connp->conn_lock);
21827 	rw_exit(&ipst->ips_ill_g_lock);
21828 	return (NULL);
21829 }
21830 
21831 ill_t *
21832 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21833 {
21834 	ill_t	*ill;
21835 
21836 	*err = 0;
21837 	mutex_enter(&connp->conn_lock);
21838 	ill = *illp;
21839 	if (ill != NULL) {
21840 		mutex_enter(&ill->ill_lock);
21841 		if (ILL_CAN_LOOKUP(ill)) {
21842 			ill_refhold_locked(ill);
21843 			mutex_exit(&ill->ill_lock);
21844 			mutex_exit(&connp->conn_lock);
21845 			return (ill);
21846 		} else {
21847 			*err = ILL_LOOKUP_FAILED;
21848 		}
21849 		mutex_exit(&ill->ill_lock);
21850 	}
21851 	mutex_exit(&connp->conn_lock);
21852 	return (NULL);
21853 }
21854 
21855 static int
21856 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21857 {
21858 	ill_t	*ill;
21859 
21860 	ill = ipif->ipif_ill;
21861 	mutex_enter(&connp->conn_lock);
21862 	mutex_enter(&ill->ill_lock);
21863 	if (IPIF_CAN_LOOKUP(ipif)) {
21864 		*ipifp = ipif;
21865 		mutex_exit(&ill->ill_lock);
21866 		mutex_exit(&connp->conn_lock);
21867 		return (0);
21868 	}
21869 	mutex_exit(&ill->ill_lock);
21870 	mutex_exit(&connp->conn_lock);
21871 	return (IPIF_LOOKUP_FAILED);
21872 }
21873 
21874 /*
21875  * This is called if the outbound datagram needs fragmentation.
21876  *
21877  * NOTE : This function does not ire_refrele the ire argument passed in.
21878  */
21879 static void
21880 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21881     ip_stack_t *ipst)
21882 {
21883 	ipha_t		*ipha;
21884 	mblk_t		*mp;
21885 	uint32_t	v_hlen_tos_len;
21886 	uint32_t	max_frag;
21887 	uint32_t	frag_flag;
21888 	boolean_t	dont_use;
21889 
21890 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21891 		mp = ipsec_mp->b_cont;
21892 	} else {
21893 		mp = ipsec_mp;
21894 	}
21895 
21896 	ipha = (ipha_t *)mp->b_rptr;
21897 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21898 
21899 #ifdef	_BIG_ENDIAN
21900 #define	V_HLEN	(v_hlen_tos_len >> 24)
21901 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21902 #else
21903 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21904 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21905 #endif
21906 
21907 #ifndef SPEED_BEFORE_SAFETY
21908 	/*
21909 	 * Check that ipha_length is consistent with
21910 	 * the mblk length
21911 	 */
21912 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21913 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21914 		    LENGTH, msgdsize(mp)));
21915 		freemsg(ipsec_mp);
21916 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21917 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21918 		    "packet length mismatch");
21919 		return;
21920 	}
21921 #endif
21922 	/*
21923 	 * Don't use frag_flag if pre-built packet or source
21924 	 * routed or if multicast (since multicast packets do not solicit
21925 	 * ICMP "packet too big" messages). Get the values of
21926 	 * max_frag and frag_flag atomically by acquiring the
21927 	 * ire_lock.
21928 	 */
21929 	mutex_enter(&ire->ire_lock);
21930 	max_frag = ire->ire_max_frag;
21931 	frag_flag = ire->ire_frag_flag;
21932 	mutex_exit(&ire->ire_lock);
21933 
21934 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21935 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21936 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21937 
21938 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21939 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21940 }
21941 
21942 /*
21943  * Used for deciding the MSS size for the upper layer. Thus
21944  * we need to check the outbound policy values in the conn.
21945  */
21946 int
21947 conn_ipsec_length(conn_t *connp)
21948 {
21949 	ipsec_latch_t *ipl;
21950 
21951 	ipl = connp->conn_latch;
21952 	if (ipl == NULL)
21953 		return (0);
21954 
21955 	if (ipl->ipl_out_policy == NULL)
21956 		return (0);
21957 
21958 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21959 }
21960 
21961 /*
21962  * Returns an estimate of the IPSEC headers size. This is used if
21963  * we don't want to call into IPSEC to get the exact size.
21964  */
21965 int
21966 ipsec_out_extra_length(mblk_t *ipsec_mp)
21967 {
21968 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21969 	ipsec_action_t *a;
21970 
21971 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21972 	if (!io->ipsec_out_secure)
21973 		return (0);
21974 
21975 	a = io->ipsec_out_act;
21976 
21977 	if (a == NULL) {
21978 		ASSERT(io->ipsec_out_policy != NULL);
21979 		a = io->ipsec_out_policy->ipsp_act;
21980 	}
21981 	ASSERT(a != NULL);
21982 
21983 	return (a->ipa_ovhd);
21984 }
21985 
21986 /*
21987  * Returns an estimate of the IPSEC headers size. This is used if
21988  * we don't want to call into IPSEC to get the exact size.
21989  */
21990 int
21991 ipsec_in_extra_length(mblk_t *ipsec_mp)
21992 {
21993 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21994 	ipsec_action_t *a;
21995 
21996 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21997 
21998 	a = ii->ipsec_in_action;
21999 	return (a == NULL ? 0 : a->ipa_ovhd);
22000 }
22001 
22002 /*
22003  * If there are any source route options, return the true final
22004  * destination. Otherwise, return the destination.
22005  */
22006 ipaddr_t
22007 ip_get_dst(ipha_t *ipha)
22008 {
22009 	ipoptp_t	opts;
22010 	uchar_t		*opt;
22011 	uint8_t		optval;
22012 	uint8_t		optlen;
22013 	ipaddr_t	dst;
22014 	uint32_t off;
22015 
22016 	dst = ipha->ipha_dst;
22017 
22018 	if (IS_SIMPLE_IPH(ipha))
22019 		return (dst);
22020 
22021 	for (optval = ipoptp_first(&opts, ipha);
22022 	    optval != IPOPT_EOL;
22023 	    optval = ipoptp_next(&opts)) {
22024 		opt = opts.ipoptp_cur;
22025 		optlen = opts.ipoptp_len;
22026 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22027 		switch (optval) {
22028 		case IPOPT_SSRR:
22029 		case IPOPT_LSRR:
22030 			off = opt[IPOPT_OFFSET];
22031 			/*
22032 			 * If one of the conditions is true, it means
22033 			 * end of options and dst already has the right
22034 			 * value.
22035 			 */
22036 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22037 				off = optlen - IP_ADDR_LEN;
22038 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22039 			}
22040 			return (dst);
22041 		default:
22042 			break;
22043 		}
22044 	}
22045 
22046 	return (dst);
22047 }
22048 
22049 mblk_t *
22050 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22051     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22052 {
22053 	ipsec_out_t	*io;
22054 	mblk_t		*first_mp;
22055 	boolean_t policy_present;
22056 	ip_stack_t	*ipst;
22057 	ipsec_stack_t	*ipss;
22058 
22059 	ASSERT(ire != NULL);
22060 	ipst = ire->ire_ipst;
22061 	ipss = ipst->ips_netstack->netstack_ipsec;
22062 
22063 	first_mp = mp;
22064 	if (mp->b_datap->db_type == M_CTL) {
22065 		io = (ipsec_out_t *)first_mp->b_rptr;
22066 		/*
22067 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22068 		 *
22069 		 * 1) There is per-socket policy (including cached global
22070 		 *    policy) or a policy on the IP-in-IP tunnel.
22071 		 * 2) There is no per-socket policy, but it is
22072 		 *    a multicast packet that needs to go out
22073 		 *    on a specific interface. This is the case
22074 		 *    where (ip_wput and ip_wput_multicast) attaches
22075 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22076 		 *
22077 		 * In case (2) we check with global policy to
22078 		 * see if there is a match and set the ill_index
22079 		 * appropriately so that we can lookup the ire
22080 		 * properly in ip_wput_ipsec_out.
22081 		 */
22082 
22083 		/*
22084 		 * ipsec_out_use_global_policy is set to B_FALSE
22085 		 * in ipsec_in_to_out(). Refer to that function for
22086 		 * details.
22087 		 */
22088 		if ((io->ipsec_out_latch == NULL) &&
22089 		    (io->ipsec_out_use_global_policy)) {
22090 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22091 				    ire, connp, unspec_src, zoneid));
22092 		}
22093 		if (!io->ipsec_out_secure) {
22094 			/*
22095 			 * If this is not a secure packet, drop
22096 			 * the IPSEC_OUT mp and treat it as a clear
22097 			 * packet. This happens when we are sending
22098 			 * a ICMP reply back to a clear packet. See
22099 			 * ipsec_in_to_out() for details.
22100 			 */
22101 			mp = first_mp->b_cont;
22102 			freeb(first_mp);
22103 		}
22104 		return (mp);
22105 	}
22106 	/*
22107 	 * See whether we need to attach a global policy here. We
22108 	 * don't depend on the conn (as it could be null) for deciding
22109 	 * what policy this datagram should go through because it
22110 	 * should have happened in ip_wput if there was some
22111 	 * policy. This normally happens for connections which are not
22112 	 * fully bound preventing us from caching policies in
22113 	 * ip_bind. Packets coming from the TCP listener/global queue
22114 	 * - which are non-hard_bound - could also be affected by
22115 	 * applying policy here.
22116 	 *
22117 	 * If this packet is coming from tcp global queue or listener,
22118 	 * we will be applying policy here.  This may not be *right*
22119 	 * if these packets are coming from the detached connection as
22120 	 * it could have gone in clear before. This happens only if a
22121 	 * TCP connection started when there is no policy and somebody
22122 	 * added policy before it became detached. Thus packets of the
22123 	 * detached connection could go out secure and the other end
22124 	 * would drop it because it will be expecting in clear. The
22125 	 * converse is not true i.e if somebody starts a TCP
22126 	 * connection and deletes the policy, all the packets will
22127 	 * still go out with the policy that existed before deleting
22128 	 * because ip_unbind sends up policy information which is used
22129 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22130 	 * TCP to attach a dummy IPSEC_OUT and set
22131 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22132 	 * affect performance for normal cases, we are not doing it.
22133 	 * Thus, set policy before starting any TCP connections.
22134 	 *
22135 	 * NOTE - We might apply policy even for a hard bound connection
22136 	 * - for which we cached policy in ip_bind - if somebody added
22137 	 * global policy after we inherited the policy in ip_bind.
22138 	 * This means that the packets that were going out in clear
22139 	 * previously would start going secure and hence get dropped
22140 	 * on the other side. To fix this, TCP attaches a dummy
22141 	 * ipsec_out and make sure that we don't apply global policy.
22142 	 */
22143 	if (ipha != NULL)
22144 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22145 	else
22146 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22147 	if (!policy_present)
22148 		return (mp);
22149 
22150 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22151 		    zoneid));
22152 }
22153 
22154 ire_t *
22155 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22156 {
22157 	ipaddr_t addr;
22158 	ire_t *save_ire;
22159 	irb_t *irb;
22160 	ill_group_t *illgrp;
22161 	int	err;
22162 
22163 	save_ire = ire;
22164 	addr = ire->ire_addr;
22165 
22166 	ASSERT(ire->ire_type == IRE_BROADCAST);
22167 
22168 	illgrp = connp->conn_outgoing_ill->ill_group;
22169 	if (illgrp == NULL) {
22170 		*conn_outgoing_ill = conn_get_held_ill(connp,
22171 		    &connp->conn_outgoing_ill, &err);
22172 		if (err == ILL_LOOKUP_FAILED) {
22173 			ire_refrele(save_ire);
22174 			return (NULL);
22175 		}
22176 		return (save_ire);
22177 	}
22178 	/*
22179 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22180 	 * If it is part of the group, we need to send on the ire
22181 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22182 	 * to this group. This is okay as IP_BOUND_IF really means
22183 	 * any ill in the group. We depend on the fact that the
22184 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22185 	 * if such an ire exists. This is possible only if you have
22186 	 * at least one ill in the group that has not failed.
22187 	 *
22188 	 * First get to the ire that matches the address and group.
22189 	 *
22190 	 * We don't look for an ire with a matching zoneid because a given zone
22191 	 * won't always have broadcast ires on all ills in the group.
22192 	 */
22193 	irb = ire->ire_bucket;
22194 	rw_enter(&irb->irb_lock, RW_READER);
22195 	if (ire->ire_marks & IRE_MARK_NORECV) {
22196 		/*
22197 		 * If the current zone only has an ire broadcast for this
22198 		 * address marked NORECV, the ire we want is ahead in the
22199 		 * bucket, so we look it up deliberately ignoring the zoneid.
22200 		 */
22201 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22202 			if (ire->ire_addr != addr)
22203 				continue;
22204 			/* skip over deleted ires */
22205 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22206 				continue;
22207 		}
22208 	}
22209 	while (ire != NULL) {
22210 		/*
22211 		 * If a new interface is coming up, we could end up
22212 		 * seeing the loopback ire and the non-loopback ire
22213 		 * may not have been added yet. So check for ire_stq
22214 		 */
22215 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22216 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22217 			break;
22218 		}
22219 		ire = ire->ire_next;
22220 	}
22221 	if (ire != NULL && ire->ire_addr == addr &&
22222 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22223 		IRE_REFHOLD(ire);
22224 		rw_exit(&irb->irb_lock);
22225 		ire_refrele(save_ire);
22226 		*conn_outgoing_ill = ire_to_ill(ire);
22227 		/*
22228 		 * Refhold the ill to make the conn_outgoing_ill
22229 		 * independent of the ire. ip_wput_ire goes in a loop
22230 		 * and may refrele the ire. Since we have an ire at this
22231 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22232 		 */
22233 		ill_refhold(*conn_outgoing_ill);
22234 		return (ire);
22235 	}
22236 	rw_exit(&irb->irb_lock);
22237 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22238 	/*
22239 	 * If we can't find a suitable ire, return the original ire.
22240 	 */
22241 	return (save_ire);
22242 }
22243 
22244 /*
22245  * This function does the ire_refrele of the ire passed in as the
22246  * argument. As this function looks up more ires i.e broadcast ires,
22247  * it needs to REFRELE them. Currently, for simplicity we don't
22248  * differentiate the one passed in and looked up here. We always
22249  * REFRELE.
22250  * IPQoS Notes:
22251  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22252  * IPSec packets are done in ipsec_out_process.
22253  *
22254  */
22255 void
22256 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22257     zoneid_t zoneid)
22258 {
22259 	ipha_t		*ipha;
22260 #define	rptr	((uchar_t *)ipha)
22261 	queue_t		*stq;
22262 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22263 	uint32_t	v_hlen_tos_len;
22264 	uint32_t	ttl_protocol;
22265 	ipaddr_t	src;
22266 	ipaddr_t	dst;
22267 	uint32_t	cksum;
22268 	ipaddr_t	orig_src;
22269 	ire_t		*ire1;
22270 	mblk_t		*next_mp;
22271 	uint_t		hlen;
22272 	uint16_t	*up;
22273 	uint32_t	max_frag = ire->ire_max_frag;
22274 	ill_t		*ill = ire_to_ill(ire);
22275 	int		clusterwide;
22276 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22277 	int		ipsec_len;
22278 	mblk_t		*first_mp;
22279 	ipsec_out_t	*io;
22280 	boolean_t	conn_dontroute;		/* conn value for multicast */
22281 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22282 	boolean_t	multicast_forward;	/* Should we forward ? */
22283 	boolean_t	unspec_src;
22284 	ill_t		*conn_outgoing_ill = NULL;
22285 	ill_t		*ire_ill;
22286 	ill_t		*ire1_ill;
22287 	ill_t		*out_ill;
22288 	uint32_t 	ill_index = 0;
22289 	boolean_t	multirt_send = B_FALSE;
22290 	int		err;
22291 	ipxmit_state_t	pktxmit_state;
22292 	ip_stack_t	*ipst = ire->ire_ipst;
22293 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22294 
22295 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22296 	    "ip_wput_ire_start: q %p", q);
22297 
22298 	multicast_forward = B_FALSE;
22299 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22300 
22301 	if (ire->ire_flags & RTF_MULTIRT) {
22302 		/*
22303 		 * Multirouting case. The bucket where ire is stored
22304 		 * probably holds other RTF_MULTIRT flagged ire
22305 		 * to the destination. In this call to ip_wput_ire,
22306 		 * we attempt to send the packet through all
22307 		 * those ires. Thus, we first ensure that ire is the
22308 		 * first RTF_MULTIRT ire in the bucket,
22309 		 * before walking the ire list.
22310 		 */
22311 		ire_t *first_ire;
22312 		irb_t *irb = ire->ire_bucket;
22313 		ASSERT(irb != NULL);
22314 
22315 		/* Make sure we do not omit any multiroute ire. */
22316 		IRB_REFHOLD(irb);
22317 		for (first_ire = irb->irb_ire;
22318 		    first_ire != NULL;
22319 		    first_ire = first_ire->ire_next) {
22320 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22321 			    (first_ire->ire_addr == ire->ire_addr) &&
22322 			    !(first_ire->ire_marks &
22323 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22324 				break;
22325 		}
22326 
22327 		if ((first_ire != NULL) && (first_ire != ire)) {
22328 			IRE_REFHOLD(first_ire);
22329 			ire_refrele(ire);
22330 			ire = first_ire;
22331 			ill = ire_to_ill(ire);
22332 		}
22333 		IRB_REFRELE(irb);
22334 	}
22335 
22336 	/*
22337 	 * conn_outgoing_ill is used only in the broadcast loop.
22338 	 * for performance we don't grab the mutexs in the fastpath
22339 	 */
22340 	if ((connp != NULL) &&
22341 	    (connp->conn_xmit_if_ill == NULL) &&
22342 	    (ire->ire_type == IRE_BROADCAST) &&
22343 	    ((connp->conn_nofailover_ill != NULL) ||
22344 	    (connp->conn_outgoing_ill != NULL))) {
22345 		/*
22346 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22347 		 * option. So, see if this endpoint is bound to a
22348 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22349 		 * that if the interface is failed, we will still send
22350 		 * the packet on the same ill which is what we want.
22351 		 */
22352 		conn_outgoing_ill = conn_get_held_ill(connp,
22353 		    &connp->conn_nofailover_ill, &err);
22354 		if (err == ILL_LOOKUP_FAILED) {
22355 			ire_refrele(ire);
22356 			freemsg(mp);
22357 			return;
22358 		}
22359 		if (conn_outgoing_ill == NULL) {
22360 			/*
22361 			 * Choose a good ill in the group to send the
22362 			 * packets on.
22363 			 */
22364 			ire = conn_set_outgoing_ill(connp, ire,
22365 			    &conn_outgoing_ill);
22366 			if (ire == NULL) {
22367 				freemsg(mp);
22368 				return;
22369 			}
22370 		}
22371 	}
22372 
22373 	if (mp->b_datap->db_type != M_CTL) {
22374 		ipha = (ipha_t *)mp->b_rptr;
22375 	} else {
22376 		io = (ipsec_out_t *)mp->b_rptr;
22377 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22378 		ASSERT(zoneid == io->ipsec_out_zoneid);
22379 		ASSERT(zoneid != ALL_ZONES);
22380 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22381 		dst = ipha->ipha_dst;
22382 		/*
22383 		 * For the multicast case, ipsec_out carries conn_dontroute and
22384 		 * conn_multicast_loop as conn may not be available here. We
22385 		 * need this for multicast loopback and forwarding which is done
22386 		 * later in the code.
22387 		 */
22388 		if (CLASSD(dst)) {
22389 			conn_dontroute = io->ipsec_out_dontroute;
22390 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22391 			/*
22392 			 * If conn_dontroute is not set or conn_multicast_loop
22393 			 * is set, we need to do forwarding/loopback. For
22394 			 * datagrams from ip_wput_multicast, conn_dontroute is
22395 			 * set to B_TRUE and conn_multicast_loop is set to
22396 			 * B_FALSE so that we neither do forwarding nor
22397 			 * loopback.
22398 			 */
22399 			if (!conn_dontroute || conn_multicast_loop)
22400 				multicast_forward = B_TRUE;
22401 		}
22402 	}
22403 
22404 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22405 	    ire->ire_zoneid != ALL_ZONES) {
22406 		/*
22407 		 * When a zone sends a packet to another zone, we try to deliver
22408 		 * the packet under the same conditions as if the destination
22409 		 * was a real node on the network. To do so, we look for a
22410 		 * matching route in the forwarding table.
22411 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22412 		 * ip_newroute() does.
22413 		 * Note that IRE_LOCAL are special, since they are used
22414 		 * when the zoneid doesn't match in some cases. This means that
22415 		 * we need to handle ipha_src differently since ire_src_addr
22416 		 * belongs to the receiving zone instead of the sending zone.
22417 		 * When ip_restrict_interzone_loopback is set, then
22418 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22419 		 * for loopback between zones when the logical "Ethernet" would
22420 		 * have looped them back.
22421 		 */
22422 		ire_t *src_ire;
22423 
22424 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22425 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22426 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22427 		if (src_ire != NULL &&
22428 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22429 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22430 		    ire_local_same_ill_group(ire, src_ire))) {
22431 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22432 				ipha->ipha_src = src_ire->ire_src_addr;
22433 			ire_refrele(src_ire);
22434 		} else {
22435 			ire_refrele(ire);
22436 			if (conn_outgoing_ill != NULL)
22437 				ill_refrele(conn_outgoing_ill);
22438 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22439 			if (src_ire != NULL) {
22440 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22441 					ire_refrele(src_ire);
22442 					freemsg(mp);
22443 					return;
22444 				}
22445 				ire_refrele(src_ire);
22446 			}
22447 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22448 				/* Failed */
22449 				freemsg(mp);
22450 				return;
22451 			}
22452 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22453 			    ipst);
22454 			return;
22455 		}
22456 	}
22457 
22458 	if (mp->b_datap->db_type == M_CTL ||
22459 	    ipss->ipsec_outbound_v4_policy_present) {
22460 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22461 		    unspec_src, zoneid);
22462 		if (mp == NULL) {
22463 			ire_refrele(ire);
22464 			if (conn_outgoing_ill != NULL)
22465 				ill_refrele(conn_outgoing_ill);
22466 			return;
22467 		}
22468 	}
22469 
22470 	first_mp = mp;
22471 	ipsec_len = 0;
22472 
22473 	if (first_mp->b_datap->db_type == M_CTL) {
22474 		io = (ipsec_out_t *)first_mp->b_rptr;
22475 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22476 		mp = first_mp->b_cont;
22477 		ipsec_len = ipsec_out_extra_length(first_mp);
22478 		ASSERT(ipsec_len >= 0);
22479 		/* We already picked up the zoneid from the M_CTL above */
22480 		ASSERT(zoneid == io->ipsec_out_zoneid);
22481 		ASSERT(zoneid != ALL_ZONES);
22482 
22483 		/*
22484 		 * Drop M_CTL here if IPsec processing is not needed.
22485 		 * (Non-IPsec use of M_CTL extracted any information it
22486 		 * needed above).
22487 		 */
22488 		if (ipsec_len == 0) {
22489 			freeb(first_mp);
22490 			first_mp = mp;
22491 		}
22492 	}
22493 
22494 	/*
22495 	 * Fast path for ip_wput_ire
22496 	 */
22497 
22498 	ipha = (ipha_t *)mp->b_rptr;
22499 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22500 	dst = ipha->ipha_dst;
22501 
22502 	/*
22503 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22504 	 * if the socket is a SOCK_RAW type. The transport checksum should
22505 	 * be provided in the pre-built packet, so we don't need to compute it.
22506 	 * Also, other application set flags, like DF, should not be altered.
22507 	 * Other transport MUST pass down zero.
22508 	 */
22509 	ip_hdr_included = ipha->ipha_ident;
22510 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22511 
22512 	if (CLASSD(dst)) {
22513 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22514 		    ntohl(dst),
22515 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22516 		    ntohl(ire->ire_addr)));
22517 	}
22518 
22519 /* Macros to extract header fields from data already in registers */
22520 #ifdef	_BIG_ENDIAN
22521 #define	V_HLEN	(v_hlen_tos_len >> 24)
22522 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22523 #define	PROTO	(ttl_protocol & 0xFF)
22524 #else
22525 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22526 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22527 #define	PROTO	(ttl_protocol >> 8)
22528 #endif
22529 
22530 
22531 	orig_src = src = ipha->ipha_src;
22532 	/* (The loop back to "another" is explained down below.) */
22533 another:;
22534 	/*
22535 	 * Assign an ident value for this packet.  We assign idents on
22536 	 * a per destination basis out of the IRE.  There could be
22537 	 * other threads targeting the same destination, so we have to
22538 	 * arrange for a atomic increment.  Note that we use a 32-bit
22539 	 * atomic add because it has better performance than its
22540 	 * 16-bit sibling.
22541 	 *
22542 	 * If running in cluster mode and if the source address
22543 	 * belongs to a replicated service then vector through
22544 	 * cl_inet_ipident vector to allocate ip identifier
22545 	 * NOTE: This is a contract private interface with the
22546 	 * clustering group.
22547 	 */
22548 	clusterwide = 0;
22549 	if (cl_inet_ipident) {
22550 		ASSERT(cl_inet_isclusterwide);
22551 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22552 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22553 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22554 			    AF_INET, (uint8_t *)(uintptr_t)src,
22555 			    (uint8_t *)(uintptr_t)dst);
22556 			clusterwide = 1;
22557 		}
22558 	}
22559 	if (!clusterwide) {
22560 		ipha->ipha_ident =
22561 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22562 	}
22563 
22564 #ifndef _BIG_ENDIAN
22565 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22566 #endif
22567 
22568 	/*
22569 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22570 	 * This is needed to obey conn_unspec_src when packets go through
22571 	 * ip_newroute + arp.
22572 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22573 	 */
22574 	if (src == INADDR_ANY && !unspec_src) {
22575 		/*
22576 		 * Assign the appropriate source address from the IRE if none
22577 		 * was specified.
22578 		 */
22579 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22580 
22581 		/*
22582 		 * With IP multipathing, broadcast packets are sent on the ire
22583 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22584 		 * the group. However, this ire might not be in the same zone so
22585 		 * we can't always use its source address. We look for a
22586 		 * broadcast ire in the same group and in the right zone.
22587 		 */
22588 		if (ire->ire_type == IRE_BROADCAST &&
22589 		    ire->ire_zoneid != zoneid) {
22590 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22591 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22592 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22593 			if (src_ire != NULL) {
22594 				src = src_ire->ire_src_addr;
22595 				ire_refrele(src_ire);
22596 			} else {
22597 				ire_refrele(ire);
22598 				if (conn_outgoing_ill != NULL)
22599 					ill_refrele(conn_outgoing_ill);
22600 				freemsg(first_mp);
22601 				if (ill != NULL) {
22602 					BUMP_MIB(ill->ill_ip_mib,
22603 					    ipIfStatsOutDiscards);
22604 				} else {
22605 					BUMP_MIB(&ipst->ips_ip_mib,
22606 					    ipIfStatsOutDiscards);
22607 				}
22608 				return;
22609 			}
22610 		} else {
22611 			src = ire->ire_src_addr;
22612 		}
22613 
22614 		if (connp == NULL) {
22615 			ip1dbg(("ip_wput_ire: no connp and no src "
22616 			    "address for dst 0x%x, using src 0x%x\n",
22617 			    ntohl(dst),
22618 			    ntohl(src)));
22619 		}
22620 		ipha->ipha_src = src;
22621 	}
22622 	stq = ire->ire_stq;
22623 
22624 	/*
22625 	 * We only allow ire chains for broadcasts since there will
22626 	 * be multiple IRE_CACHE entries for the same multicast
22627 	 * address (one per ipif).
22628 	 */
22629 	next_mp = NULL;
22630 
22631 	/* broadcast packet */
22632 	if (ire->ire_type == IRE_BROADCAST)
22633 		goto broadcast;
22634 
22635 	/* loopback ? */
22636 	if (stq == NULL)
22637 		goto nullstq;
22638 
22639 	/* The ill_index for outbound ILL */
22640 	ill_index = Q_TO_INDEX(stq);
22641 
22642 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22643 	ttl_protocol = ((uint16_t *)ipha)[4];
22644 
22645 	/* pseudo checksum (do it in parts for IP header checksum) */
22646 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22647 
22648 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22649 		queue_t *dev_q = stq->q_next;
22650 
22651 		/* flow controlled */
22652 		if ((dev_q->q_next || dev_q->q_first) &&
22653 		    !canput(dev_q))
22654 			goto blocked;
22655 		if ((PROTO == IPPROTO_UDP) &&
22656 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22657 			hlen = (V_HLEN & 0xF) << 2;
22658 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22659 			if (*up != 0) {
22660 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22661 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22662 				/* Software checksum? */
22663 				if (DB_CKSUMFLAGS(mp) == 0) {
22664 					IP_STAT(ipst, ip_out_sw_cksum);
22665 					IP_STAT_UPDATE(ipst,
22666 					    ip_udp_out_sw_cksum_bytes,
22667 					    LENGTH - hlen);
22668 				}
22669 			}
22670 		}
22671 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22672 		hlen = (V_HLEN & 0xF) << 2;
22673 		if (PROTO == IPPROTO_TCP) {
22674 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22675 			/*
22676 			 * The packet header is processed once and for all, even
22677 			 * in the multirouting case. We disable hardware
22678 			 * checksum if the packet is multirouted, as it will be
22679 			 * replicated via several interfaces, and not all of
22680 			 * them may have this capability.
22681 			 */
22682 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22683 			    LENGTH, max_frag, ipsec_len, cksum);
22684 			/* Software checksum? */
22685 			if (DB_CKSUMFLAGS(mp) == 0) {
22686 				IP_STAT(ipst, ip_out_sw_cksum);
22687 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22688 				    LENGTH - hlen);
22689 			}
22690 		} else {
22691 			sctp_hdr_t	*sctph;
22692 
22693 			ASSERT(PROTO == IPPROTO_SCTP);
22694 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22695 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22696 			/*
22697 			 * Zero out the checksum field to ensure proper
22698 			 * checksum calculation.
22699 			 */
22700 			sctph->sh_chksum = 0;
22701 #ifdef	DEBUG
22702 			if (!skip_sctp_cksum)
22703 #endif
22704 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22705 		}
22706 	}
22707 
22708 	/*
22709 	 * If this is a multicast packet and originated from ip_wput
22710 	 * we need to do loopback and forwarding checks. If it comes
22711 	 * from ip_wput_multicast, we SHOULD not do this.
22712 	 */
22713 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22714 
22715 	/* checksum */
22716 	cksum += ttl_protocol;
22717 
22718 	/* fragment the packet */
22719 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22720 		goto fragmentit;
22721 	/*
22722 	 * Don't use frag_flag if packet is pre-built or source
22723 	 * routed or if multicast (since multicast packets do
22724 	 * not solicit ICMP "packet too big" messages).
22725 	 */
22726 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22727 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22728 	    !ip_source_route_included(ipha)) &&
22729 	    !CLASSD(ipha->ipha_dst))
22730 		ipha->ipha_fragment_offset_and_flags |=
22731 		    htons(ire->ire_frag_flag);
22732 
22733 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22734 		/* calculate IP header checksum */
22735 		cksum += ipha->ipha_ident;
22736 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22737 		cksum += ipha->ipha_fragment_offset_and_flags;
22738 
22739 		/* IP options present */
22740 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22741 		if (hlen)
22742 			goto checksumoptions;
22743 
22744 		/* calculate hdr checksum */
22745 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22746 		cksum = ~(cksum + (cksum >> 16));
22747 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22748 	}
22749 	if (ipsec_len != 0) {
22750 		/*
22751 		 * We will do the rest of the processing after
22752 		 * we come back from IPSEC in ip_wput_ipsec_out().
22753 		 */
22754 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22755 
22756 		io = (ipsec_out_t *)first_mp->b_rptr;
22757 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22758 				ill_phyint->phyint_ifindex;
22759 
22760 		ipsec_out_process(q, first_mp, ire, ill_index);
22761 		ire_refrele(ire);
22762 		if (conn_outgoing_ill != NULL)
22763 			ill_refrele(conn_outgoing_ill);
22764 		return;
22765 	}
22766 
22767 	/*
22768 	 * In most cases, the emission loop below is entered only
22769 	 * once. Only in the case where the ire holds the
22770 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22771 	 * flagged ires in the bucket, and send the packet
22772 	 * through all crossed RTF_MULTIRT routes.
22773 	 */
22774 	if (ire->ire_flags & RTF_MULTIRT) {
22775 		multirt_send = B_TRUE;
22776 	}
22777 	do {
22778 		if (multirt_send) {
22779 			irb_t *irb;
22780 			/*
22781 			 * We are in a multiple send case, need to get
22782 			 * the next ire and make a duplicate of the packet.
22783 			 * ire1 holds here the next ire to process in the
22784 			 * bucket. If multirouting is expected,
22785 			 * any non-RTF_MULTIRT ire that has the
22786 			 * right destination address is ignored.
22787 			 */
22788 			irb = ire->ire_bucket;
22789 			ASSERT(irb != NULL);
22790 
22791 			IRB_REFHOLD(irb);
22792 			for (ire1 = ire->ire_next;
22793 			    ire1 != NULL;
22794 			    ire1 = ire1->ire_next) {
22795 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22796 					continue;
22797 				if (ire1->ire_addr != ire->ire_addr)
22798 					continue;
22799 				if (ire1->ire_marks &
22800 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22801 					continue;
22802 
22803 				/* Got one */
22804 				IRE_REFHOLD(ire1);
22805 				break;
22806 			}
22807 			IRB_REFRELE(irb);
22808 
22809 			if (ire1 != NULL) {
22810 				next_mp = copyb(mp);
22811 				if ((next_mp == NULL) ||
22812 				    ((mp->b_cont != NULL) &&
22813 				    ((next_mp->b_cont =
22814 				    dupmsg(mp->b_cont)) == NULL))) {
22815 					freemsg(next_mp);
22816 					next_mp = NULL;
22817 					ire_refrele(ire1);
22818 					ire1 = NULL;
22819 				}
22820 			}
22821 
22822 			/* Last multiroute ire; don't loop anymore. */
22823 			if (ire1 == NULL) {
22824 				multirt_send = B_FALSE;
22825 			}
22826 		}
22827 
22828 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22829 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22830 		    mblk_t *, mp);
22831 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22832 		    ipst->ips_ipv4firewall_physical_out,
22833 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22834 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22835 		if (mp == NULL)
22836 			goto release_ire_and_ill;
22837 
22838 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22839 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22840 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22841 		if ((pktxmit_state == SEND_FAILED) ||
22842 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22843 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22844 			    "- packet dropped\n"));
22845 release_ire_and_ill:
22846 			ire_refrele(ire);
22847 			if (next_mp != NULL) {
22848 				freemsg(next_mp);
22849 				ire_refrele(ire1);
22850 			}
22851 			if (conn_outgoing_ill != NULL)
22852 				ill_refrele(conn_outgoing_ill);
22853 			return;
22854 		}
22855 
22856 		if (CLASSD(dst)) {
22857 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22858 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22859 			    LENGTH);
22860 		}
22861 
22862 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22863 		    "ip_wput_ire_end: q %p (%S)",
22864 		    q, "last copy out");
22865 		IRE_REFRELE(ire);
22866 
22867 		if (multirt_send) {
22868 			ASSERT(ire1);
22869 			/*
22870 			 * Proceed with the next RTF_MULTIRT ire,
22871 			 * Also set up the send-to queue accordingly.
22872 			 */
22873 			ire = ire1;
22874 			ire1 = NULL;
22875 			stq = ire->ire_stq;
22876 			mp = next_mp;
22877 			next_mp = NULL;
22878 			ipha = (ipha_t *)mp->b_rptr;
22879 			ill_index = Q_TO_INDEX(stq);
22880 			ill = (ill_t *)stq->q_ptr;
22881 		}
22882 	} while (multirt_send);
22883 	if (conn_outgoing_ill != NULL)
22884 		ill_refrele(conn_outgoing_ill);
22885 	return;
22886 
22887 	/*
22888 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22889 	 */
22890 broadcast:
22891 	{
22892 		/*
22893 		 * Avoid broadcast storms by setting the ttl to 1
22894 		 * for broadcasts. This parameter can be set
22895 		 * via ndd, so make sure that for the SO_DONTROUTE
22896 		 * case that ipha_ttl is always set to 1.
22897 		 * In the event that we are replying to incoming
22898 		 * ICMP packets, conn could be NULL.
22899 		 */
22900 		if ((connp != NULL) && connp->conn_dontroute)
22901 			ipha->ipha_ttl = 1;
22902 		else
22903 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22904 
22905 		/*
22906 		 * Note that we are not doing a IRB_REFHOLD here.
22907 		 * Actually we don't care if the list changes i.e
22908 		 * if somebody deletes an IRE from the list while
22909 		 * we drop the lock, the next time we come around
22910 		 * ire_next will be NULL and hence we won't send
22911 		 * out multiple copies which is fine.
22912 		 */
22913 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22914 		ire1 = ire->ire_next;
22915 		if (conn_outgoing_ill != NULL) {
22916 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22917 				ASSERT(ire1 == ire->ire_next);
22918 				if (ire1 != NULL && ire1->ire_addr == dst) {
22919 					ire_refrele(ire);
22920 					ire = ire1;
22921 					IRE_REFHOLD(ire);
22922 					ire1 = ire->ire_next;
22923 					continue;
22924 				}
22925 				rw_exit(&ire->ire_bucket->irb_lock);
22926 				/* Did not find a matching ill */
22927 				ip1dbg(("ip_wput_ire: broadcast with no "
22928 				    "matching IP_BOUND_IF ill %s\n",
22929 				    conn_outgoing_ill->ill_name));
22930 				freemsg(first_mp);
22931 				if (ire != NULL)
22932 					ire_refrele(ire);
22933 				ill_refrele(conn_outgoing_ill);
22934 				return;
22935 			}
22936 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22937 			/*
22938 			 * If the next IRE has the same address and is not one
22939 			 * of the two copies that we need to send, try to see
22940 			 * whether this copy should be sent at all. This
22941 			 * assumes that we insert loopbacks first and then
22942 			 * non-loopbacks. This is acheived by inserting the
22943 			 * loopback always before non-loopback.
22944 			 * This is used to send a single copy of a broadcast
22945 			 * packet out all physical interfaces that have an
22946 			 * matching IRE_BROADCAST while also looping
22947 			 * back one copy (to ip_wput_local) for each
22948 			 * matching physical interface. However, we avoid
22949 			 * sending packets out different logical that match by
22950 			 * having ipif_up/ipif_down supress duplicate
22951 			 * IRE_BROADCASTS.
22952 			 *
22953 			 * This feature is currently used to get broadcasts
22954 			 * sent to multiple interfaces, when the broadcast
22955 			 * address being used applies to multiple interfaces.
22956 			 * For example, a whole net broadcast will be
22957 			 * replicated on every connected subnet of
22958 			 * the target net.
22959 			 *
22960 			 * Each zone has its own set of IRE_BROADCASTs, so that
22961 			 * we're able to distribute inbound packets to multiple
22962 			 * zones who share a broadcast address. We avoid looping
22963 			 * back outbound packets in different zones but on the
22964 			 * same ill, as the application would see duplicates.
22965 			 *
22966 			 * If the interfaces are part of the same group,
22967 			 * we would want to send only one copy out for
22968 			 * whole group.
22969 			 *
22970 			 * This logic assumes that ire_add_v4() groups the
22971 			 * IRE_BROADCAST entries so that those with the same
22972 			 * ire_addr and ill_group are kept together.
22973 			 */
22974 			ire_ill = ire->ire_ipif->ipif_ill;
22975 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22976 				if (ire_ill->ill_group != NULL &&
22977 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22978 					/*
22979 					 * If the current zone only has an ire
22980 					 * broadcast for this address marked
22981 					 * NORECV, the ire we want is ahead in
22982 					 * the bucket, so we look it up
22983 					 * deliberately ignoring the zoneid.
22984 					 */
22985 					for (ire1 = ire->ire_bucket->irb_ire;
22986 					    ire1 != NULL;
22987 					    ire1 = ire1->ire_next) {
22988 						ire1_ill =
22989 						    ire1->ire_ipif->ipif_ill;
22990 						if (ire1->ire_addr != dst)
22991 							continue;
22992 						/* skip over the current ire */
22993 						if (ire1 == ire)
22994 							continue;
22995 						/* skip over deleted ires */
22996 						if (ire1->ire_marks &
22997 						    IRE_MARK_CONDEMNED)
22998 							continue;
22999 						/*
23000 						 * non-loopback ire in our
23001 						 * group: use it for the next
23002 						 * pass in the loop
23003 						 */
23004 						if (ire1->ire_stq != NULL &&
23005 						    ire1_ill->ill_group ==
23006 						    ire_ill->ill_group)
23007 							break;
23008 					}
23009 				}
23010 			} else {
23011 				while (ire1 != NULL && ire1->ire_addr == dst) {
23012 					ire1_ill = ire1->ire_ipif->ipif_ill;
23013 					/*
23014 					 * We can have two broadcast ires on the
23015 					 * same ill in different zones; here
23016 					 * we'll send a copy of the packet on
23017 					 * each ill and the fanout code will
23018 					 * call conn_wantpacket() to check that
23019 					 * the zone has the broadcast address
23020 					 * configured on the ill. If the two
23021 					 * ires are in the same group we only
23022 					 * send one copy up.
23023 					 */
23024 					if (ire1_ill != ire_ill &&
23025 					    (ire1_ill->ill_group == NULL ||
23026 					    ire_ill->ill_group == NULL ||
23027 					    ire1_ill->ill_group !=
23028 					    ire_ill->ill_group)) {
23029 						break;
23030 					}
23031 					ire1 = ire1->ire_next;
23032 				}
23033 			}
23034 		}
23035 		ASSERT(multirt_send == B_FALSE);
23036 		if (ire1 != NULL && ire1->ire_addr == dst) {
23037 			if ((ire->ire_flags & RTF_MULTIRT) &&
23038 			    (ire1->ire_flags & RTF_MULTIRT)) {
23039 				/*
23040 				 * We are in the multirouting case.
23041 				 * The message must be sent at least
23042 				 * on both ires. These ires have been
23043 				 * inserted AFTER the standard ones
23044 				 * in ip_rt_add(). There are thus no
23045 				 * other ire entries for the destination
23046 				 * address in the rest of the bucket
23047 				 * that do not have the RTF_MULTIRT
23048 				 * flag. We don't process a copy
23049 				 * of the message here. This will be
23050 				 * done in the final sending loop.
23051 				 */
23052 				multirt_send = B_TRUE;
23053 			} else {
23054 				next_mp = ip_copymsg(first_mp);
23055 				if (next_mp != NULL)
23056 					IRE_REFHOLD(ire1);
23057 			}
23058 		}
23059 		rw_exit(&ire->ire_bucket->irb_lock);
23060 	}
23061 
23062 	if (stq) {
23063 		/*
23064 		 * A non-NULL send-to queue means this packet is going
23065 		 * out of this machine.
23066 		 */
23067 		out_ill = (ill_t *)stq->q_ptr;
23068 
23069 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23070 		ttl_protocol = ((uint16_t *)ipha)[4];
23071 		/*
23072 		 * We accumulate the pseudo header checksum in cksum.
23073 		 * This is pretty hairy code, so watch close.  One
23074 		 * thing to keep in mind is that UDP and TCP have
23075 		 * stored their respective datagram lengths in their
23076 		 * checksum fields.  This lines things up real nice.
23077 		 */
23078 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23079 		    (src >> 16) + (src & 0xFFFF);
23080 		/*
23081 		 * We assume the udp checksum field contains the
23082 		 * length, so to compute the pseudo header checksum,
23083 		 * all we need is the protocol number and src/dst.
23084 		 */
23085 		/* Provide the checksums for UDP and TCP. */
23086 		if ((PROTO == IPPROTO_TCP) &&
23087 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23088 			/* hlen gets the number of uchar_ts in the IP header */
23089 			hlen = (V_HLEN & 0xF) << 2;
23090 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23091 			IP_STAT(ipst, ip_out_sw_cksum);
23092 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23093 			    LENGTH - hlen);
23094 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23095 			if (*up == 0)
23096 				*up = 0xFFFF;
23097 		} else if (PROTO == IPPROTO_SCTP &&
23098 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23099 			sctp_hdr_t	*sctph;
23100 
23101 			hlen = (V_HLEN & 0xF) << 2;
23102 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23103 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23104 			sctph->sh_chksum = 0;
23105 #ifdef	DEBUG
23106 			if (!skip_sctp_cksum)
23107 #endif
23108 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23109 		} else {
23110 			queue_t *dev_q = stq->q_next;
23111 
23112 			if ((dev_q->q_next || dev_q->q_first) &&
23113 			    !canput(dev_q)) {
23114 			    blocked:
23115 				ipha->ipha_ident = ip_hdr_included;
23116 				/*
23117 				 * If we don't have a conn to apply
23118 				 * backpressure, free the message.
23119 				 * In the ire_send path, we don't know
23120 				 * the position to requeue the packet. Rather
23121 				 * than reorder packets, we just drop this
23122 				 * packet.
23123 				 */
23124 				if (ipst->ips_ip_output_queue &&
23125 				    connp != NULL &&
23126 				    caller != IRE_SEND) {
23127 					if (caller == IP_WSRV) {
23128 						connp->conn_did_putbq = 1;
23129 						(void) putbq(connp->conn_wq,
23130 						    first_mp);
23131 						conn_drain_insert(connp);
23132 						/*
23133 						 * This is the service thread,
23134 						 * and the queue is already
23135 						 * noenabled. The check for
23136 						 * canput and the putbq is not
23137 						 * atomic. So we need to check
23138 						 * again.
23139 						 */
23140 						if (canput(stq->q_next))
23141 							connp->conn_did_putbq
23142 							    = 0;
23143 						IP_STAT(ipst, ip_conn_flputbq);
23144 					} else {
23145 						/*
23146 						 * We are not the service proc.
23147 						 * ip_wsrv will be scheduled or
23148 						 * is already running.
23149 						 */
23150 						(void) putq(connp->conn_wq,
23151 						    first_mp);
23152 					}
23153 				} else {
23154 					out_ill = (ill_t *)stq->q_ptr;
23155 					BUMP_MIB(out_ill->ill_ip_mib,
23156 					    ipIfStatsOutDiscards);
23157 					freemsg(first_mp);
23158 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23159 					    "ip_wput_ire_end: q %p (%S)",
23160 					    q, "discard");
23161 				}
23162 				ire_refrele(ire);
23163 				if (next_mp) {
23164 					ire_refrele(ire1);
23165 					freemsg(next_mp);
23166 				}
23167 				if (conn_outgoing_ill != NULL)
23168 					ill_refrele(conn_outgoing_ill);
23169 				return;
23170 			}
23171 			if ((PROTO == IPPROTO_UDP) &&
23172 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23173 				/*
23174 				 * hlen gets the number of uchar_ts in the
23175 				 * IP header
23176 				 */
23177 				hlen = (V_HLEN & 0xF) << 2;
23178 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23179 				max_frag = ire->ire_max_frag;
23180 				if (*up != 0) {
23181 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23182 					    up, PROTO, hlen, LENGTH, max_frag,
23183 					    ipsec_len, cksum);
23184 					/* Software checksum? */
23185 					if (DB_CKSUMFLAGS(mp) == 0) {
23186 						IP_STAT(ipst, ip_out_sw_cksum);
23187 						IP_STAT_UPDATE(ipst,
23188 						    ip_udp_out_sw_cksum_bytes,
23189 						    LENGTH - hlen);
23190 					}
23191 				}
23192 			}
23193 		}
23194 		/*
23195 		 * Need to do this even when fragmenting. The local
23196 		 * loopback can be done without computing checksums
23197 		 * but forwarding out other interface must be done
23198 		 * after the IP checksum (and ULP checksums) have been
23199 		 * computed.
23200 		 *
23201 		 * NOTE : multicast_forward is set only if this packet
23202 		 * originated from ip_wput. For packets originating from
23203 		 * ip_wput_multicast, it is not set.
23204 		 */
23205 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23206 		    multi_loopback:
23207 			ip2dbg(("ip_wput: multicast, loop %d\n",
23208 			    conn_multicast_loop));
23209 
23210 			/*  Forget header checksum offload */
23211 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23212 
23213 			/*
23214 			 * Local loopback of multicasts?  Check the
23215 			 * ill.
23216 			 *
23217 			 * Note that the loopback function will not come
23218 			 * in through ip_rput - it will only do the
23219 			 * client fanout thus we need to do an mforward
23220 			 * as well.  The is different from the BSD
23221 			 * logic.
23222 			 */
23223 			if (ill != NULL) {
23224 				ilm_t	*ilm;
23225 
23226 				ILM_WALKER_HOLD(ill);
23227 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23228 				    ALL_ZONES);
23229 				ILM_WALKER_RELE(ill);
23230 				if (ilm != NULL) {
23231 					/*
23232 					 * Pass along the virtual output q.
23233 					 * ip_wput_local() will distribute the
23234 					 * packet to all the matching zones,
23235 					 * except the sending zone when
23236 					 * IP_MULTICAST_LOOP is false.
23237 					 */
23238 					ip_multicast_loopback(q, ill, first_mp,
23239 					    conn_multicast_loop ? 0 :
23240 					    IP_FF_NO_MCAST_LOOP, zoneid);
23241 				}
23242 			}
23243 			if (ipha->ipha_ttl == 0) {
23244 				/*
23245 				 * 0 => only to this host i.e. we are
23246 				 * done. We are also done if this was the
23247 				 * loopback interface since it is sufficient
23248 				 * to loopback one copy of a multicast packet.
23249 				 */
23250 				freemsg(first_mp);
23251 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23252 				    "ip_wput_ire_end: q %p (%S)",
23253 				    q, "loopback");
23254 				ire_refrele(ire);
23255 				if (conn_outgoing_ill != NULL)
23256 					ill_refrele(conn_outgoing_ill);
23257 				return;
23258 			}
23259 			/*
23260 			 * ILLF_MULTICAST is checked in ip_newroute
23261 			 * i.e. we don't need to check it here since
23262 			 * all IRE_CACHEs come from ip_newroute.
23263 			 * For multicast traffic, SO_DONTROUTE is interpreted
23264 			 * to mean only send the packet out the interface
23265 			 * (optionally specified with IP_MULTICAST_IF)
23266 			 * and do not forward it out additional interfaces.
23267 			 * RSVP and the rsvp daemon is an example of a
23268 			 * protocol and user level process that
23269 			 * handles it's own routing. Hence, it uses the
23270 			 * SO_DONTROUTE option to accomplish this.
23271 			 */
23272 
23273 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23274 			    ill != NULL) {
23275 				/* Unconditionally redo the checksum */
23276 				ipha->ipha_hdr_checksum = 0;
23277 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23278 
23279 				/*
23280 				 * If this needs to go out secure, we need
23281 				 * to wait till we finish the IPSEC
23282 				 * processing.
23283 				 */
23284 				if (ipsec_len == 0 &&
23285 				    ip_mforward(ill, ipha, mp)) {
23286 					freemsg(first_mp);
23287 					ip1dbg(("ip_wput: mforward failed\n"));
23288 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23289 					    "ip_wput_ire_end: q %p (%S)",
23290 					    q, "mforward failed");
23291 					ire_refrele(ire);
23292 					if (conn_outgoing_ill != NULL)
23293 						ill_refrele(conn_outgoing_ill);
23294 					return;
23295 				}
23296 			}
23297 		}
23298 		max_frag = ire->ire_max_frag;
23299 		cksum += ttl_protocol;
23300 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23301 			/* No fragmentation required for this one. */
23302 			/*
23303 			 * Don't use frag_flag if packet is pre-built or source
23304 			 * routed or if multicast (since multicast packets do
23305 			 * not solicit ICMP "packet too big" messages).
23306 			 */
23307 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23308 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23309 			    !ip_source_route_included(ipha)) &&
23310 			    !CLASSD(ipha->ipha_dst))
23311 				ipha->ipha_fragment_offset_and_flags |=
23312 				    htons(ire->ire_frag_flag);
23313 
23314 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23315 				/* Complete the IP header checksum. */
23316 				cksum += ipha->ipha_ident;
23317 				cksum += (v_hlen_tos_len >> 16)+
23318 				    (v_hlen_tos_len & 0xFFFF);
23319 				cksum += ipha->ipha_fragment_offset_and_flags;
23320 				hlen = (V_HLEN & 0xF) -
23321 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23322 				if (hlen) {
23323 				    checksumoptions:
23324 					/*
23325 					 * Account for the IP Options in the IP
23326 					 * header checksum.
23327 					 */
23328 					up = (uint16_t *)(rptr+
23329 					    IP_SIMPLE_HDR_LENGTH);
23330 					do {
23331 						cksum += up[0];
23332 						cksum += up[1];
23333 						up += 2;
23334 					} while (--hlen);
23335 				}
23336 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23337 				cksum = ~(cksum + (cksum >> 16));
23338 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23339 			}
23340 			if (ipsec_len != 0) {
23341 				ipsec_out_process(q, first_mp, ire, ill_index);
23342 				if (!next_mp) {
23343 					ire_refrele(ire);
23344 					if (conn_outgoing_ill != NULL)
23345 						ill_refrele(conn_outgoing_ill);
23346 					return;
23347 				}
23348 				goto next;
23349 			}
23350 
23351 			/*
23352 			 * multirt_send has already been handled
23353 			 * for broadcast, but not yet for multicast
23354 			 * or IP options.
23355 			 */
23356 			if (next_mp == NULL) {
23357 				if (ire->ire_flags & RTF_MULTIRT) {
23358 					multirt_send = B_TRUE;
23359 				}
23360 			}
23361 
23362 			/*
23363 			 * In most cases, the emission loop below is
23364 			 * entered only once. Only in the case where
23365 			 * the ire holds the RTF_MULTIRT flag, do we loop
23366 			 * to process all RTF_MULTIRT ires in the bucket,
23367 			 * and send the packet through all crossed
23368 			 * RTF_MULTIRT routes.
23369 			 */
23370 			do {
23371 				if (multirt_send) {
23372 					irb_t *irb;
23373 
23374 					irb = ire->ire_bucket;
23375 					ASSERT(irb != NULL);
23376 					/*
23377 					 * We are in a multiple send case,
23378 					 * need to get the next IRE and make
23379 					 * a duplicate of the packet.
23380 					 */
23381 					IRB_REFHOLD(irb);
23382 					for (ire1 = ire->ire_next;
23383 					    ire1 != NULL;
23384 					    ire1 = ire1->ire_next) {
23385 						if (!(ire1->ire_flags &
23386 						    RTF_MULTIRT))
23387 							continue;
23388 						if (ire1->ire_addr !=
23389 						    ire->ire_addr)
23390 							continue;
23391 						if (ire1->ire_marks &
23392 						    (IRE_MARK_CONDEMNED|
23393 							IRE_MARK_HIDDEN))
23394 							continue;
23395 
23396 						/* Got one */
23397 						IRE_REFHOLD(ire1);
23398 						break;
23399 					}
23400 					IRB_REFRELE(irb);
23401 
23402 					if (ire1 != NULL) {
23403 						next_mp = copyb(mp);
23404 						if ((next_mp == NULL) ||
23405 						    ((mp->b_cont != NULL) &&
23406 						    ((next_mp->b_cont =
23407 						    dupmsg(mp->b_cont))
23408 						    == NULL))) {
23409 							freemsg(next_mp);
23410 							next_mp = NULL;
23411 							ire_refrele(ire1);
23412 							ire1 = NULL;
23413 						}
23414 					}
23415 
23416 					/*
23417 					 * Last multiroute ire; don't loop
23418 					 * anymore. The emission is over
23419 					 * and next_mp is NULL.
23420 					 */
23421 					if (ire1 == NULL) {
23422 						multirt_send = B_FALSE;
23423 					}
23424 				}
23425 
23426 				out_ill = ire->ire_ipif->ipif_ill;
23427 				DTRACE_PROBE4(ip4__physical__out__start,
23428 				    ill_t *, NULL,
23429 				    ill_t *, out_ill,
23430 				    ipha_t *, ipha, mblk_t *, mp);
23431 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23432 				    ipst->ips_ipv4firewall_physical_out,
23433 				    NULL, out_ill, ipha, mp, mp, ipst);
23434 				DTRACE_PROBE1(ip4__physical__out__end,
23435 				    mblk_t *, mp);
23436 				if (mp == NULL)
23437 					goto release_ire_and_ill_2;
23438 
23439 				ASSERT(ipsec_len == 0);
23440 				mp->b_prev =
23441 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23442 				DTRACE_PROBE2(ip__xmit__2,
23443 				    mblk_t *, mp, ire_t *, ire);
23444 				pktxmit_state = ip_xmit_v4(mp, ire,
23445 				    NULL, B_TRUE);
23446 				if ((pktxmit_state == SEND_FAILED) ||
23447 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23448 release_ire_and_ill_2:
23449 					if (next_mp) {
23450 						freemsg(next_mp);
23451 						ire_refrele(ire1);
23452 					}
23453 					ire_refrele(ire);
23454 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23455 					    "ip_wput_ire_end: q %p (%S)",
23456 					    q, "discard MDATA");
23457 					if (conn_outgoing_ill != NULL)
23458 						ill_refrele(conn_outgoing_ill);
23459 					return;
23460 				}
23461 
23462 				if (CLASSD(dst)) {
23463 					BUMP_MIB(out_ill->ill_ip_mib,
23464 					    ipIfStatsHCOutMcastPkts);
23465 					UPDATE_MIB(out_ill->ill_ip_mib,
23466 					    ipIfStatsHCOutMcastOctets,
23467 					    LENGTH);
23468 				} else if (ire->ire_type == IRE_BROADCAST) {
23469 					BUMP_MIB(out_ill->ill_ip_mib,
23470 					    ipIfStatsHCOutBcastPkts);
23471 				}
23472 
23473 				if (multirt_send) {
23474 					/*
23475 					 * We are in a multiple send case,
23476 					 * need to re-enter the sending loop
23477 					 * using the next ire.
23478 					 */
23479 					ire_refrele(ire);
23480 					ire = ire1;
23481 					stq = ire->ire_stq;
23482 					mp = next_mp;
23483 					next_mp = NULL;
23484 					ipha = (ipha_t *)mp->b_rptr;
23485 					ill_index = Q_TO_INDEX(stq);
23486 				}
23487 			} while (multirt_send);
23488 
23489 			if (!next_mp) {
23490 				/*
23491 				 * Last copy going out (the ultra-common
23492 				 * case).  Note that we intentionally replicate
23493 				 * the putnext rather than calling it before
23494 				 * the next_mp check in hopes of a little
23495 				 * tail-call action out of the compiler.
23496 				 */
23497 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23498 				    "ip_wput_ire_end: q %p (%S)",
23499 				    q, "last copy out(1)");
23500 				ire_refrele(ire);
23501 				if (conn_outgoing_ill != NULL)
23502 					ill_refrele(conn_outgoing_ill);
23503 				return;
23504 			}
23505 			/* More copies going out below. */
23506 		} else {
23507 			int offset;
23508 		    fragmentit:
23509 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23510 			/*
23511 			 * If this would generate a icmp_frag_needed message,
23512 			 * we need to handle it before we do the IPSEC
23513 			 * processing. Otherwise, we need to strip the IPSEC
23514 			 * headers before we send up the message to the ULPs
23515 			 * which becomes messy and difficult.
23516 			 */
23517 			if (ipsec_len != 0) {
23518 				if ((max_frag < (unsigned int)(LENGTH +
23519 				    ipsec_len)) && (offset & IPH_DF)) {
23520 					out_ill = (ill_t *)stq->q_ptr;
23521 					BUMP_MIB(out_ill->ill_ip_mib,
23522 					    ipIfStatsOutFragFails);
23523 					BUMP_MIB(out_ill->ill_ip_mib,
23524 					    ipIfStatsOutFragReqds);
23525 					ipha->ipha_hdr_checksum = 0;
23526 					ipha->ipha_hdr_checksum =
23527 					    (uint16_t)ip_csum_hdr(ipha);
23528 					icmp_frag_needed(ire->ire_stq, first_mp,
23529 					    max_frag, zoneid, ipst);
23530 					if (!next_mp) {
23531 						ire_refrele(ire);
23532 						if (conn_outgoing_ill != NULL) {
23533 							ill_refrele(
23534 							    conn_outgoing_ill);
23535 						}
23536 						return;
23537 					}
23538 				} else {
23539 					/*
23540 					 * This won't cause a icmp_frag_needed
23541 					 * message. to be generated. Send it on
23542 					 * the wire. Note that this could still
23543 					 * cause fragmentation and all we
23544 					 * do is the generation of the message
23545 					 * to the ULP if needed before IPSEC.
23546 					 */
23547 					if (!next_mp) {
23548 						ipsec_out_process(q, first_mp,
23549 						    ire, ill_index);
23550 						TRACE_2(TR_FAC_IP,
23551 						    TR_IP_WPUT_IRE_END,
23552 						    "ip_wput_ire_end: q %p "
23553 						    "(%S)", q,
23554 						    "last ipsec_out_process");
23555 						ire_refrele(ire);
23556 						if (conn_outgoing_ill != NULL) {
23557 							ill_refrele(
23558 							    conn_outgoing_ill);
23559 						}
23560 						return;
23561 					}
23562 					ipsec_out_process(q, first_mp,
23563 					    ire, ill_index);
23564 				}
23565 			} else {
23566 				/*
23567 				 * Initiate IPPF processing. For
23568 				 * fragmentable packets we finish
23569 				 * all QOS packet processing before
23570 				 * calling:
23571 				 * ip_wput_ire_fragmentit->ip_wput_frag
23572 				 */
23573 
23574 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23575 					ip_process(IPP_LOCAL_OUT, &mp,
23576 					    ill_index);
23577 					if (mp == NULL) {
23578 						out_ill = (ill_t *)stq->q_ptr;
23579 						BUMP_MIB(out_ill->ill_ip_mib,
23580 						    ipIfStatsOutDiscards);
23581 						if (next_mp != NULL) {
23582 							freemsg(next_mp);
23583 							ire_refrele(ire1);
23584 						}
23585 						ire_refrele(ire);
23586 						TRACE_2(TR_FAC_IP,
23587 						    TR_IP_WPUT_IRE_END,
23588 						    "ip_wput_ire: q %p (%S)",
23589 						    q, "discard MDATA");
23590 						if (conn_outgoing_ill != NULL) {
23591 							ill_refrele(
23592 							    conn_outgoing_ill);
23593 						}
23594 						return;
23595 					}
23596 				}
23597 				if (!next_mp) {
23598 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23599 					    "ip_wput_ire_end: q %p (%S)",
23600 					    q, "last fragmentation");
23601 					ip_wput_ire_fragmentit(mp, ire,
23602 					    zoneid, ipst);
23603 					ire_refrele(ire);
23604 					if (conn_outgoing_ill != NULL)
23605 						ill_refrele(conn_outgoing_ill);
23606 					return;
23607 				}
23608 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23609 			}
23610 		}
23611 	} else {
23612 	    nullstq:
23613 		/* A NULL stq means the destination address is local. */
23614 		UPDATE_OB_PKT_COUNT(ire);
23615 		ire->ire_last_used_time = lbolt;
23616 		ASSERT(ire->ire_ipif != NULL);
23617 		if (!next_mp) {
23618 			/*
23619 			 * Is there an "in" and "out" for traffic local
23620 			 * to a host (loopback)?  The code in Solaris doesn't
23621 			 * explicitly draw a line in its code for in vs out,
23622 			 * so we've had to draw a line in the sand: ip_wput_ire
23623 			 * is considered to be the "output" side and
23624 			 * ip_wput_local to be the "input" side.
23625 			 */
23626 			out_ill = ire->ire_ipif->ipif_ill;
23627 
23628 			DTRACE_PROBE4(ip4__loopback__out__start,
23629 			    ill_t *, NULL, ill_t *, out_ill,
23630 			    ipha_t *, ipha, mblk_t *, first_mp);
23631 
23632 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23633 			    ipst->ips_ipv4firewall_loopback_out,
23634 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23635 
23636 			DTRACE_PROBE1(ip4__loopback__out_end,
23637 			    mblk_t *, first_mp);
23638 
23639 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23640 			    "ip_wput_ire_end: q %p (%S)",
23641 			    q, "local address");
23642 
23643 			if (first_mp != NULL)
23644 				ip_wput_local(q, out_ill, ipha,
23645 				    first_mp, ire, 0, ire->ire_zoneid);
23646 			ire_refrele(ire);
23647 			if (conn_outgoing_ill != NULL)
23648 				ill_refrele(conn_outgoing_ill);
23649 			return;
23650 		}
23651 
23652 		out_ill = ire->ire_ipif->ipif_ill;
23653 
23654 		DTRACE_PROBE4(ip4__loopback__out__start,
23655 		    ill_t *, NULL, ill_t *, out_ill,
23656 		    ipha_t *, ipha, mblk_t *, first_mp);
23657 
23658 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23659 		    ipst->ips_ipv4firewall_loopback_out,
23660 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23661 
23662 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23663 
23664 		if (first_mp != NULL)
23665 			ip_wput_local(q, out_ill, ipha,
23666 			    first_mp, ire, 0, ire->ire_zoneid);
23667 	}
23668 next:
23669 	/*
23670 	 * More copies going out to additional interfaces.
23671 	 * ire1 has already been held. We don't need the
23672 	 * "ire" anymore.
23673 	 */
23674 	ire_refrele(ire);
23675 	ire = ire1;
23676 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23677 	mp = next_mp;
23678 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23679 	ill = ire_to_ill(ire);
23680 	first_mp = mp;
23681 	if (ipsec_len != 0) {
23682 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23683 		mp = mp->b_cont;
23684 	}
23685 	dst = ire->ire_addr;
23686 	ipha = (ipha_t *)mp->b_rptr;
23687 	/*
23688 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23689 	 * Restore ipha_ident "no checksum" flag.
23690 	 */
23691 	src = orig_src;
23692 	ipha->ipha_ident = ip_hdr_included;
23693 	goto another;
23694 
23695 #undef	rptr
23696 #undef	Q_TO_INDEX
23697 }
23698 
23699 /*
23700  * Routine to allocate a message that is used to notify the ULP about MDT.
23701  * The caller may provide a pointer to the link-layer MDT capabilities,
23702  * or NULL if MDT is to be disabled on the stream.
23703  */
23704 mblk_t *
23705 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23706 {
23707 	mblk_t *mp;
23708 	ip_mdt_info_t *mdti;
23709 	ill_mdt_capab_t *idst;
23710 
23711 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23712 		DB_TYPE(mp) = M_CTL;
23713 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23714 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23715 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23716 		idst = &(mdti->mdt_capab);
23717 
23718 		/*
23719 		 * If the caller provides us with the capability, copy
23720 		 * it over into our notification message; otherwise
23721 		 * we zero out the capability portion.
23722 		 */
23723 		if (isrc != NULL)
23724 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23725 		else
23726 			bzero((caddr_t)idst, sizeof (*idst));
23727 	}
23728 	return (mp);
23729 }
23730 
23731 /*
23732  * Routine which determines whether MDT can be enabled on the destination
23733  * IRE and IPC combination, and if so, allocates and returns the MDT
23734  * notification mblk that may be used by ULP.  We also check if we need to
23735  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23736  * MDT usage in the past have been lifted.  This gets called during IP
23737  * and ULP binding.
23738  */
23739 mblk_t *
23740 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23741     ill_mdt_capab_t *mdt_cap)
23742 {
23743 	mblk_t *mp;
23744 	boolean_t rc = B_FALSE;
23745 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23746 
23747 	ASSERT(dst_ire != NULL);
23748 	ASSERT(connp != NULL);
23749 	ASSERT(mdt_cap != NULL);
23750 
23751 	/*
23752 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23753 	 * Multidata, which is handled in tcp_multisend().  This
23754 	 * is the reason why we do all these checks here, to ensure
23755 	 * that we don't enable Multidata for the cases which we
23756 	 * can't handle at the moment.
23757 	 */
23758 	do {
23759 		/* Only do TCP at the moment */
23760 		if (connp->conn_ulp != IPPROTO_TCP)
23761 			break;
23762 
23763 		/*
23764 		 * IPSEC outbound policy present?  Note that we get here
23765 		 * after calling ipsec_conn_cache_policy() where the global
23766 		 * policy checking is performed.  conn_latch will be
23767 		 * non-NULL as long as there's a policy defined,
23768 		 * i.e. conn_out_enforce_policy may be NULL in such case
23769 		 * when the connection is non-secure, and hence we check
23770 		 * further if the latch refers to an outbound policy.
23771 		 */
23772 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23773 			break;
23774 
23775 		/* CGTP (multiroute) is enabled? */
23776 		if (dst_ire->ire_flags & RTF_MULTIRT)
23777 			break;
23778 
23779 		/* Outbound IPQoS enabled? */
23780 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23781 			/*
23782 			 * In this case, we disable MDT for this and all
23783 			 * future connections going over the interface.
23784 			 */
23785 			mdt_cap->ill_mdt_on = 0;
23786 			break;
23787 		}
23788 
23789 		/* socket option(s) present? */
23790 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23791 			break;
23792 
23793 		rc = B_TRUE;
23794 	/* CONSTCOND */
23795 	} while (0);
23796 
23797 	/* Remember the result */
23798 	connp->conn_mdt_ok = rc;
23799 
23800 	if (!rc)
23801 		return (NULL);
23802 	else if (!mdt_cap->ill_mdt_on) {
23803 		/*
23804 		 * If MDT has been previously turned off in the past, and we
23805 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23806 		 * then enable it for this interface.
23807 		 */
23808 		mdt_cap->ill_mdt_on = 1;
23809 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23810 		    "interface %s\n", ill_name));
23811 	}
23812 
23813 	/* Allocate the MDT info mblk */
23814 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23815 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23816 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23817 		return (NULL);
23818 	}
23819 	return (mp);
23820 }
23821 
23822 /*
23823  * Routine to allocate a message that is used to notify the ULP about LSO.
23824  * The caller may provide a pointer to the link-layer LSO capabilities,
23825  * or NULL if LSO is to be disabled on the stream.
23826  */
23827 mblk_t *
23828 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23829 {
23830 	mblk_t *mp;
23831 	ip_lso_info_t *lsoi;
23832 	ill_lso_capab_t *idst;
23833 
23834 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23835 		DB_TYPE(mp) = M_CTL;
23836 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23837 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23838 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23839 		idst = &(lsoi->lso_capab);
23840 
23841 		/*
23842 		 * If the caller provides us with the capability, copy
23843 		 * it over into our notification message; otherwise
23844 		 * we zero out the capability portion.
23845 		 */
23846 		if (isrc != NULL)
23847 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23848 		else
23849 			bzero((caddr_t)idst, sizeof (*idst));
23850 	}
23851 	return (mp);
23852 }
23853 
23854 /*
23855  * Routine which determines whether LSO can be enabled on the destination
23856  * IRE and IPC combination, and if so, allocates and returns the LSO
23857  * notification mblk that may be used by ULP.  We also check if we need to
23858  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23859  * LSO usage in the past have been lifted.  This gets called during IP
23860  * and ULP binding.
23861  */
23862 mblk_t *
23863 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23864     ill_lso_capab_t *lso_cap)
23865 {
23866 	mblk_t *mp;
23867 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23868 
23869 	ASSERT(dst_ire != NULL);
23870 	ASSERT(connp != NULL);
23871 	ASSERT(lso_cap != NULL);
23872 
23873 	connp->conn_lso_ok = B_TRUE;
23874 
23875 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23876 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23877 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23878 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23879 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23880 		connp->conn_lso_ok = B_FALSE;
23881 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23882 			/*
23883 			 * Disable LSO for this and all future connections going
23884 			 * over the interface.
23885 			 */
23886 			lso_cap->ill_lso_on = 0;
23887 		}
23888 	}
23889 
23890 	if (!connp->conn_lso_ok)
23891 		return (NULL);
23892 	else if (!lso_cap->ill_lso_on) {
23893 		/*
23894 		 * If LSO has been previously turned off in the past, and we
23895 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23896 		 * then enable it for this interface.
23897 		 */
23898 		lso_cap->ill_lso_on = 1;
23899 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23900 		    ill_name));
23901 	}
23902 
23903 	/* Allocate the LSO info mblk */
23904 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23905 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23906 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23907 
23908 	return (mp);
23909 }
23910 
23911 /*
23912  * Create destination address attribute, and fill it with the physical
23913  * destination address and SAP taken from the template DL_UNITDATA_REQ
23914  * message block.
23915  */
23916 boolean_t
23917 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23918 {
23919 	dl_unitdata_req_t *dlurp;
23920 	pattr_t *pa;
23921 	pattrinfo_t pa_info;
23922 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23923 	uint_t das_len, das_off;
23924 
23925 	ASSERT(dlmp != NULL);
23926 
23927 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23928 	das_len = dlurp->dl_dest_addr_length;
23929 	das_off = dlurp->dl_dest_addr_offset;
23930 
23931 	pa_info.type = PATTR_DSTADDRSAP;
23932 	pa_info.len = sizeof (**das) + das_len - 1;
23933 
23934 	/* create and associate the attribute */
23935 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23936 	if (pa != NULL) {
23937 		ASSERT(*das != NULL);
23938 		(*das)->addr_is_group = 0;
23939 		(*das)->addr_len = (uint8_t)das_len;
23940 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23941 	}
23942 
23943 	return (pa != NULL);
23944 }
23945 
23946 /*
23947  * Create hardware checksum attribute and fill it with the values passed.
23948  */
23949 boolean_t
23950 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23951     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23952 {
23953 	pattr_t *pa;
23954 	pattrinfo_t pa_info;
23955 
23956 	ASSERT(mmd != NULL);
23957 
23958 	pa_info.type = PATTR_HCKSUM;
23959 	pa_info.len = sizeof (pattr_hcksum_t);
23960 
23961 	/* create and associate the attribute */
23962 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23963 	if (pa != NULL) {
23964 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23965 
23966 		hck->hcksum_start_offset = start_offset;
23967 		hck->hcksum_stuff_offset = stuff_offset;
23968 		hck->hcksum_end_offset = end_offset;
23969 		hck->hcksum_flags = flags;
23970 	}
23971 	return (pa != NULL);
23972 }
23973 
23974 /*
23975  * Create zerocopy attribute and fill it with the specified flags
23976  */
23977 boolean_t
23978 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23979 {
23980 	pattr_t *pa;
23981 	pattrinfo_t pa_info;
23982 
23983 	ASSERT(mmd != NULL);
23984 	pa_info.type = PATTR_ZCOPY;
23985 	pa_info.len = sizeof (pattr_zcopy_t);
23986 
23987 	/* create and associate the attribute */
23988 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23989 	if (pa != NULL) {
23990 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23991 
23992 		zcopy->zcopy_flags = flags;
23993 	}
23994 	return (pa != NULL);
23995 }
23996 
23997 /*
23998  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23999  * block chain. We could rewrite to handle arbitrary message block chains but
24000  * that would make the code complicated and slow. Right now there three
24001  * restrictions:
24002  *
24003  *   1. The first message block must contain the complete IP header and
24004  *	at least 1 byte of payload data.
24005  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
24006  *	so that we can use a single Multidata message.
24007  *   3. No frag must be distributed over two or more message blocks so
24008  *	that we don't need more than two packet descriptors per frag.
24009  *
24010  * The above restrictions allow us to support userland applications (which
24011  * will send down a single message block) and NFS over UDP (which will
24012  * send down a chain of at most three message blocks).
24013  *
24014  * We also don't use MDT for payloads with less than or equal to
24015  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24016  */
24017 boolean_t
24018 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24019 {
24020 	int	blocks;
24021 	ssize_t	total, missing, size;
24022 
24023 	ASSERT(mp != NULL);
24024 	ASSERT(hdr_len > 0);
24025 
24026 	size = MBLKL(mp) - hdr_len;
24027 	if (size <= 0)
24028 		return (B_FALSE);
24029 
24030 	/* The first mblk contains the header and some payload. */
24031 	blocks = 1;
24032 	total = size;
24033 	size %= len;
24034 	missing = (size == 0) ? 0 : (len - size);
24035 	mp = mp->b_cont;
24036 
24037 	while (mp != NULL) {
24038 		/*
24039 		 * Give up if we encounter a zero length message block.
24040 		 * In practice, this should rarely happen and therefore
24041 		 * not worth the trouble of freeing and re-linking the
24042 		 * mblk from the chain to handle such case.
24043 		 */
24044 		if ((size = MBLKL(mp)) == 0)
24045 			return (B_FALSE);
24046 
24047 		/* Too many payload buffers for a single Multidata message? */
24048 		if (++blocks > MULTIDATA_MAX_PBUFS)
24049 			return (B_FALSE);
24050 
24051 		total += size;
24052 		/* Is a frag distributed over two or more message blocks? */
24053 		if (missing > size)
24054 			return (B_FALSE);
24055 		size -= missing;
24056 
24057 		size %= len;
24058 		missing = (size == 0) ? 0 : (len - size);
24059 
24060 		mp = mp->b_cont;
24061 	}
24062 
24063 	return (total > ip_wput_frag_mdt_min);
24064 }
24065 
24066 /*
24067  * Outbound IPv4 fragmentation routine using MDT.
24068  */
24069 static void
24070 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24071     uint32_t frag_flag, int offset)
24072 {
24073 	ipha_t		*ipha_orig;
24074 	int		i1, ip_data_end;
24075 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24076 	mblk_t		*hdr_mp, *md_mp = NULL;
24077 	unsigned char	*hdr_ptr, *pld_ptr;
24078 	multidata_t	*mmd;
24079 	ip_pdescinfo_t	pdi;
24080 	ill_t		*ill;
24081 	ip_stack_t	*ipst = ire->ire_ipst;
24082 
24083 	ASSERT(DB_TYPE(mp) == M_DATA);
24084 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24085 
24086 	ill = ire_to_ill(ire);
24087 	ASSERT(ill != NULL);
24088 
24089 	ipha_orig = (ipha_t *)mp->b_rptr;
24090 	mp->b_rptr += sizeof (ipha_t);
24091 
24092 	/* Calculate how many packets we will send out */
24093 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24094 	pkts = (i1 + len - 1) / len;
24095 	ASSERT(pkts > 1);
24096 
24097 	/* Allocate a message block which will hold all the IP Headers. */
24098 	wroff = ipst->ips_ip_wroff_extra;
24099 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24100 
24101 	i1 = pkts * hdr_chunk_len;
24102 	/*
24103 	 * Create the header buffer, Multidata and destination address
24104 	 * and SAP attribute that should be associated with it.
24105 	 */
24106 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24107 	    ((hdr_mp->b_wptr += i1),
24108 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24109 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24110 		freemsg(mp);
24111 		if (md_mp == NULL) {
24112 			freemsg(hdr_mp);
24113 		} else {
24114 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24115 			freemsg(md_mp);
24116 		}
24117 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24118 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24119 		return;
24120 	}
24121 	IP_STAT(ipst, ip_frag_mdt_allocd);
24122 
24123 	/*
24124 	 * Add a payload buffer to the Multidata; this operation must not
24125 	 * fail, or otherwise our logic in this routine is broken.  There
24126 	 * is no memory allocation done by the routine, so any returned
24127 	 * failure simply tells us that we've done something wrong.
24128 	 *
24129 	 * A failure tells us that either we're adding the same payload
24130 	 * buffer more than once, or we're trying to add more buffers than
24131 	 * allowed.  None of the above cases should happen, and we panic
24132 	 * because either there's horrible heap corruption, and/or
24133 	 * programming mistake.
24134 	 */
24135 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24136 		goto pbuf_panic;
24137 
24138 	hdr_ptr = hdr_mp->b_rptr;
24139 	pld_ptr = mp->b_rptr;
24140 
24141 	/* Establish the ending byte offset, based on the starting offset. */
24142 	offset <<= 3;
24143 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24144 	    IP_SIMPLE_HDR_LENGTH;
24145 
24146 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24147 
24148 	while (pld_ptr < mp->b_wptr) {
24149 		ipha_t		*ipha;
24150 		uint16_t	offset_and_flags;
24151 		uint16_t	ip_len;
24152 		int		error;
24153 
24154 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24155 		ipha = (ipha_t *)(hdr_ptr + wroff);
24156 		ASSERT(OK_32PTR(ipha));
24157 		*ipha = *ipha_orig;
24158 
24159 		if (ip_data_end - offset > len) {
24160 			offset_and_flags = IPH_MF;
24161 		} else {
24162 			/*
24163 			 * Last frag. Set len to the length of this last piece.
24164 			 */
24165 			len = ip_data_end - offset;
24166 			/* A frag of a frag might have IPH_MF non-zero */
24167 			offset_and_flags =
24168 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24169 			    IPH_MF;
24170 		}
24171 		offset_and_flags |= (uint16_t)(offset >> 3);
24172 		offset_and_flags |= (uint16_t)frag_flag;
24173 		/* Store the offset and flags in the IP header. */
24174 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24175 
24176 		/* Store the length in the IP header. */
24177 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24178 		ipha->ipha_length = htons(ip_len);
24179 
24180 		/*
24181 		 * Set the IP header checksum.  Note that mp is just
24182 		 * the header, so this is easy to pass to ip_csum.
24183 		 */
24184 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24185 
24186 		/*
24187 		 * Record offset and size of header and data of the next packet
24188 		 * in the multidata message.
24189 		 */
24190 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24191 		PDESC_PLD_INIT(&pdi);
24192 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24193 		ASSERT(i1 > 0);
24194 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24195 		if (i1 == len) {
24196 			pld_ptr += len;
24197 		} else {
24198 			i1 = len - i1;
24199 			mp = mp->b_cont;
24200 			ASSERT(mp != NULL);
24201 			ASSERT(MBLKL(mp) >= i1);
24202 			/*
24203 			 * Attach the next payload message block to the
24204 			 * multidata message.
24205 			 */
24206 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24207 				goto pbuf_panic;
24208 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24209 			pld_ptr = mp->b_rptr + i1;
24210 		}
24211 
24212 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24213 		    KM_NOSLEEP)) == NULL) {
24214 			/*
24215 			 * Any failure other than ENOMEM indicates that we
24216 			 * have passed in invalid pdesc info or parameters
24217 			 * to mmd_addpdesc, which must not happen.
24218 			 *
24219 			 * EINVAL is a result of failure on boundary checks
24220 			 * against the pdesc info contents.  It should not
24221 			 * happen, and we panic because either there's
24222 			 * horrible heap corruption, and/or programming
24223 			 * mistake.
24224 			 */
24225 			if (error != ENOMEM) {
24226 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24227 				    "pdesc logic error detected for "
24228 				    "mmd %p pinfo %p (%d)\n",
24229 				    (void *)mmd, (void *)&pdi, error);
24230 				/* NOTREACHED */
24231 			}
24232 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24233 			/* Free unattached payload message blocks as well */
24234 			md_mp->b_cont = mp->b_cont;
24235 			goto free_mmd;
24236 		}
24237 
24238 		/* Advance fragment offset. */
24239 		offset += len;
24240 
24241 		/* Advance to location for next header in the buffer. */
24242 		hdr_ptr += hdr_chunk_len;
24243 
24244 		/* Did we reach the next payload message block? */
24245 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24246 			mp = mp->b_cont;
24247 			/*
24248 			 * Attach the next message block with payload
24249 			 * data to the multidata message.
24250 			 */
24251 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24252 				goto pbuf_panic;
24253 			pld_ptr = mp->b_rptr;
24254 		}
24255 	}
24256 
24257 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24258 	ASSERT(mp->b_wptr == pld_ptr);
24259 
24260 	/* Update IP statistics */
24261 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24262 
24263 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24264 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24265 
24266 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24267 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24268 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24269 
24270 	if (pkt_type == OB_PKT) {
24271 		ire->ire_ob_pkt_count += pkts;
24272 		if (ire->ire_ipif != NULL)
24273 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24274 	} else {
24275 		/*
24276 		 * The type is IB_PKT in the forwarding path and in
24277 		 * the mobile IP case when the packet is being reverse-
24278 		 * tunneled to the home agent.
24279 		 */
24280 		ire->ire_ib_pkt_count += pkts;
24281 		ASSERT(!IRE_IS_LOCAL(ire));
24282 		if (ire->ire_type & IRE_BROADCAST) {
24283 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24284 		} else {
24285 			UPDATE_MIB(ill->ill_ip_mib,
24286 			    ipIfStatsHCOutForwDatagrams, pkts);
24287 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24288 		}
24289 	}
24290 	ire->ire_last_used_time = lbolt;
24291 	/* Send it down */
24292 	putnext(ire->ire_stq, md_mp);
24293 	return;
24294 
24295 pbuf_panic:
24296 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24297 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24298 	    pbuf_idx);
24299 	/* NOTREACHED */
24300 }
24301 
24302 /*
24303  * Outbound IP fragmentation routine.
24304  *
24305  * NOTE : This routine does not ire_refrele the ire that is passed in
24306  * as the argument.
24307  */
24308 static void
24309 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24310     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24311 {
24312 	int		i1;
24313 	mblk_t		*ll_hdr_mp;
24314 	int 		ll_hdr_len;
24315 	int		hdr_len;
24316 	mblk_t		*hdr_mp;
24317 	ipha_t		*ipha;
24318 	int		ip_data_end;
24319 	int		len;
24320 	mblk_t		*mp = mp_orig, *mp1;
24321 	int		offset;
24322 	queue_t		*q;
24323 	uint32_t	v_hlen_tos_len;
24324 	mblk_t		*first_mp;
24325 	boolean_t	mctl_present;
24326 	ill_t		*ill;
24327 	ill_t		*out_ill;
24328 	mblk_t		*xmit_mp;
24329 	mblk_t		*carve_mp;
24330 	ire_t		*ire1 = NULL;
24331 	ire_t		*save_ire = NULL;
24332 	mblk_t  	*next_mp = NULL;
24333 	boolean_t	last_frag = B_FALSE;
24334 	boolean_t	multirt_send = B_FALSE;
24335 	ire_t		*first_ire = NULL;
24336 	irb_t		*irb = NULL;
24337 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24338 
24339 	ill = ire_to_ill(ire);
24340 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24341 
24342 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24343 
24344 	/*
24345 	 * IPSEC does not allow hw accelerated packets to be fragmented
24346 	 * This check is made in ip_wput_ipsec_out prior to coming here
24347 	 * via ip_wput_ire_fragmentit.
24348 	 *
24349 	 * If at this point we have an ire whose ARP request has not
24350 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24351 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24352 	 * This packet and all fragmentable packets for this ire will
24353 	 * continue to get dropped while ire_nce->nce_state remains in
24354 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24355 	 * ND_REACHABLE, all subsquent large packets for this ire will
24356 	 * get fragemented and sent out by this function.
24357 	 */
24358 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24359 		/* If nce_state is ND_INITIAL, trigger ARP query */
24360 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24361 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24362 		    " -  dropping packet\n"));
24363 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24364 		freemsg(mp);
24365 		return;
24366 	}
24367 
24368 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24369 	    "ip_wput_frag_start:");
24370 
24371 	if (mp->b_datap->db_type == M_CTL) {
24372 		first_mp = mp;
24373 		mp_orig = mp = mp->b_cont;
24374 		mctl_present = B_TRUE;
24375 	} else {
24376 		first_mp = mp;
24377 		mctl_present = B_FALSE;
24378 	}
24379 
24380 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24381 	ipha = (ipha_t *)mp->b_rptr;
24382 
24383 	/*
24384 	 * If the Don't Fragment flag is on, generate an ICMP destination
24385 	 * unreachable, fragmentation needed.
24386 	 */
24387 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24388 	if (offset & IPH_DF) {
24389 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24390 		/*
24391 		 * Need to compute hdr checksum if called from ip_wput_ire.
24392 		 * Note that ip_rput_forward verifies the checksum before
24393 		 * calling this routine so in that case this is a noop.
24394 		 */
24395 		ipha->ipha_hdr_checksum = 0;
24396 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24397 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24398 		    ipst);
24399 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24400 		    "ip_wput_frag_end:(%S)",
24401 		    "don't fragment");
24402 		return;
24403 	}
24404 	if (mctl_present)
24405 		freeb(first_mp);
24406 	/*
24407 	 * Establish the starting offset.  May not be zero if we are fragging
24408 	 * a fragment that is being forwarded.
24409 	 */
24410 	offset = offset & IPH_OFFSET;
24411 
24412 	/* TODO why is this test needed? */
24413 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24414 	if (((max_frag - LENGTH) & ~7) < 8) {
24415 		/* TODO: notify ulp somehow */
24416 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24417 		freemsg(mp);
24418 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24419 		    "ip_wput_frag_end:(%S)",
24420 		    "len < 8");
24421 		return;
24422 	}
24423 
24424 	hdr_len = (V_HLEN & 0xF) << 2;
24425 
24426 	ipha->ipha_hdr_checksum = 0;
24427 
24428 	/*
24429 	 * Establish the number of bytes maximum per frag, after putting
24430 	 * in the header.
24431 	 */
24432 	len = (max_frag - hdr_len) & ~7;
24433 
24434 	/* Check if we can use MDT to send out the frags. */
24435 	ASSERT(!IRE_IS_LOCAL(ire));
24436 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24437 	    ipst->ips_ip_multidata_outbound &&
24438 	    !(ire->ire_flags & RTF_MULTIRT) &&
24439 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24440 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24441 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24442 		ASSERT(ill->ill_mdt_capab != NULL);
24443 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24444 			/*
24445 			 * If MDT has been previously turned off in the past,
24446 			 * and we currently can do MDT (due to IPQoS policy
24447 			 * removal, etc.) then enable it for this interface.
24448 			 */
24449 			ill->ill_mdt_capab->ill_mdt_on = 1;
24450 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24451 			    ill->ill_name));
24452 		}
24453 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24454 		    offset);
24455 		return;
24456 	}
24457 
24458 	/* Get a copy of the header for the trailing frags */
24459 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24460 	if (!hdr_mp) {
24461 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24462 		freemsg(mp);
24463 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24464 		    "ip_wput_frag_end:(%S)",
24465 		    "couldn't copy hdr");
24466 		return;
24467 	}
24468 	if (DB_CRED(mp) != NULL)
24469 		mblk_setcred(hdr_mp, DB_CRED(mp));
24470 
24471 	/* Store the starting offset, with the MoreFrags flag. */
24472 	i1 = offset | IPH_MF | frag_flag;
24473 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24474 
24475 	/* Establish the ending byte offset, based on the starting offset. */
24476 	offset <<= 3;
24477 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24478 
24479 	/* Store the length of the first fragment in the IP header. */
24480 	i1 = len + hdr_len;
24481 	ASSERT(i1 <= IP_MAXPACKET);
24482 	ipha->ipha_length = htons((uint16_t)i1);
24483 
24484 	/*
24485 	 * Compute the IP header checksum for the first frag.  We have to
24486 	 * watch out that we stop at the end of the header.
24487 	 */
24488 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24489 
24490 	/*
24491 	 * Now carve off the first frag.  Note that this will include the
24492 	 * original IP header.
24493 	 */
24494 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24495 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24496 		freeb(hdr_mp);
24497 		freemsg(mp_orig);
24498 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24499 		    "ip_wput_frag_end:(%S)",
24500 		    "couldn't carve first");
24501 		return;
24502 	}
24503 
24504 	/*
24505 	 * Multirouting case. Each fragment is replicated
24506 	 * via all non-condemned RTF_MULTIRT routes
24507 	 * currently resolved.
24508 	 * We ensure that first_ire is the first RTF_MULTIRT
24509 	 * ire in the bucket.
24510 	 */
24511 	if (ire->ire_flags & RTF_MULTIRT) {
24512 		irb = ire->ire_bucket;
24513 		ASSERT(irb != NULL);
24514 
24515 		multirt_send = B_TRUE;
24516 
24517 		/* Make sure we do not omit any multiroute ire. */
24518 		IRB_REFHOLD(irb);
24519 		for (first_ire = irb->irb_ire;
24520 		    first_ire != NULL;
24521 		    first_ire = first_ire->ire_next) {
24522 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24523 			    (first_ire->ire_addr == ire->ire_addr) &&
24524 			    !(first_ire->ire_marks &
24525 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24526 				break;
24527 		}
24528 
24529 		if (first_ire != NULL) {
24530 			if (first_ire != ire) {
24531 				IRE_REFHOLD(first_ire);
24532 				/*
24533 				 * Do not release the ire passed in
24534 				 * as the argument.
24535 				 */
24536 				ire = first_ire;
24537 			} else {
24538 				first_ire = NULL;
24539 			}
24540 		}
24541 		IRB_REFRELE(irb);
24542 
24543 		/*
24544 		 * Save the first ire; we will need to restore it
24545 		 * for the trailing frags.
24546 		 * We REFHOLD save_ire, as each iterated ire will be
24547 		 * REFRELEd.
24548 		 */
24549 		save_ire = ire;
24550 		IRE_REFHOLD(save_ire);
24551 	}
24552 
24553 	/*
24554 	 * First fragment emission loop.
24555 	 * In most cases, the emission loop below is entered only
24556 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24557 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24558 	 * bucket, and send the fragment through all crossed
24559 	 * RTF_MULTIRT routes.
24560 	 */
24561 	do {
24562 		if (ire->ire_flags & RTF_MULTIRT) {
24563 			/*
24564 			 * We are in a multiple send case, need to get
24565 			 * the next ire and make a copy of the packet.
24566 			 * ire1 holds here the next ire to process in the
24567 			 * bucket. If multirouting is expected,
24568 			 * any non-RTF_MULTIRT ire that has the
24569 			 * right destination address is ignored.
24570 			 *
24571 			 * We have to take into account the MTU of
24572 			 * each walked ire. max_frag is set by the
24573 			 * the caller and generally refers to
24574 			 * the primary ire entry. Here we ensure that
24575 			 * no route with a lower MTU will be used, as
24576 			 * fragments are carved once for all ires,
24577 			 * then replicated.
24578 			 */
24579 			ASSERT(irb != NULL);
24580 			IRB_REFHOLD(irb);
24581 			for (ire1 = ire->ire_next;
24582 			    ire1 != NULL;
24583 			    ire1 = ire1->ire_next) {
24584 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24585 					continue;
24586 				if (ire1->ire_addr != ire->ire_addr)
24587 					continue;
24588 				if (ire1->ire_marks &
24589 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24590 					continue;
24591 				/*
24592 				 * Ensure we do not exceed the MTU
24593 				 * of the next route.
24594 				 */
24595 				if (ire1->ire_max_frag < max_frag) {
24596 					ip_multirt_bad_mtu(ire1, max_frag);
24597 					continue;
24598 				}
24599 
24600 				/* Got one. */
24601 				IRE_REFHOLD(ire1);
24602 				break;
24603 			}
24604 			IRB_REFRELE(irb);
24605 
24606 			if (ire1 != NULL) {
24607 				next_mp = copyb(mp);
24608 				if ((next_mp == NULL) ||
24609 				    ((mp->b_cont != NULL) &&
24610 				    ((next_mp->b_cont =
24611 				    dupmsg(mp->b_cont)) == NULL))) {
24612 					freemsg(next_mp);
24613 					next_mp = NULL;
24614 					ire_refrele(ire1);
24615 					ire1 = NULL;
24616 				}
24617 			}
24618 
24619 			/* Last multiroute ire; don't loop anymore. */
24620 			if (ire1 == NULL) {
24621 				multirt_send = B_FALSE;
24622 			}
24623 		}
24624 
24625 		ll_hdr_len = 0;
24626 		LOCK_IRE_FP_MP(ire);
24627 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24628 		if (ll_hdr_mp != NULL) {
24629 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24630 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24631 		} else {
24632 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24633 		}
24634 
24635 		/* If there is a transmit header, get a copy for this frag. */
24636 		/*
24637 		 * TODO: should check db_ref before calling ip_carve_mp since
24638 		 * it might give us a dup.
24639 		 */
24640 		if (!ll_hdr_mp) {
24641 			/* No xmit header. */
24642 			xmit_mp = mp;
24643 
24644 		/* We have a link-layer header that can fit in our mblk. */
24645 		} else if (mp->b_datap->db_ref == 1 &&
24646 		    ll_hdr_len != 0 &&
24647 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24648 			/* M_DATA fastpath */
24649 			mp->b_rptr -= ll_hdr_len;
24650 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24651 			xmit_mp = mp;
24652 
24653 		/* Corner case if copyb has failed */
24654 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24655 			UNLOCK_IRE_FP_MP(ire);
24656 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24657 			freeb(hdr_mp);
24658 			freemsg(mp);
24659 			freemsg(mp_orig);
24660 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24661 			    "ip_wput_frag_end:(%S)",
24662 			    "discard");
24663 
24664 			if (multirt_send) {
24665 				ASSERT(ire1);
24666 				ASSERT(next_mp);
24667 
24668 				freemsg(next_mp);
24669 				ire_refrele(ire1);
24670 			}
24671 			if (save_ire != NULL)
24672 				IRE_REFRELE(save_ire);
24673 
24674 			if (first_ire != NULL)
24675 				ire_refrele(first_ire);
24676 			return;
24677 
24678 		/*
24679 		 * Case of res_mp OR the fastpath mp can't fit
24680 		 * in the mblk
24681 		 */
24682 		} else {
24683 			xmit_mp->b_cont = mp;
24684 			if (DB_CRED(mp) != NULL)
24685 				mblk_setcred(xmit_mp, DB_CRED(mp));
24686 			/*
24687 			 * Get priority marking, if any.
24688 			 * We propagate the CoS marking from the
24689 			 * original packet that went to QoS processing
24690 			 * in ip_wput_ire to the newly carved mp.
24691 			 */
24692 			if (DB_TYPE(xmit_mp) == M_DATA)
24693 				xmit_mp->b_band = mp->b_band;
24694 		}
24695 		UNLOCK_IRE_FP_MP(ire);
24696 
24697 		q = ire->ire_stq;
24698 		out_ill = (ill_t *)q->q_ptr;
24699 
24700 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24701 
24702 		DTRACE_PROBE4(ip4__physical__out__start,
24703 		    ill_t *, NULL, ill_t *, out_ill,
24704 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24705 
24706 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24707 		    ipst->ips_ipv4firewall_physical_out,
24708 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24709 
24710 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24711 
24712 		if (xmit_mp != NULL) {
24713 			putnext(q, xmit_mp);
24714 
24715 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24716 			UPDATE_MIB(out_ill->ill_ip_mib,
24717 			    ipIfStatsHCOutOctets, i1);
24718 
24719 			if (pkt_type != OB_PKT) {
24720 				/*
24721 				 * Update the packet count and MIB stats
24722 				 * of trailing RTF_MULTIRT ires.
24723 				 */
24724 				UPDATE_OB_PKT_COUNT(ire);
24725 				BUMP_MIB(out_ill->ill_ip_mib,
24726 				    ipIfStatsOutFragReqds);
24727 			}
24728 		}
24729 
24730 		if (multirt_send) {
24731 			/*
24732 			 * We are in a multiple send case; look for
24733 			 * the next ire and re-enter the loop.
24734 			 */
24735 			ASSERT(ire1);
24736 			ASSERT(next_mp);
24737 			/* REFRELE the current ire before looping */
24738 			ire_refrele(ire);
24739 			ire = ire1;
24740 			ire1 = NULL;
24741 			mp = next_mp;
24742 			next_mp = NULL;
24743 		}
24744 	} while (multirt_send);
24745 
24746 	ASSERT(ire1 == NULL);
24747 
24748 	/* Restore the original ire; we need it for the trailing frags */
24749 	if (save_ire != NULL) {
24750 		/* REFRELE the last iterated ire */
24751 		ire_refrele(ire);
24752 		/* save_ire has been REFHOLDed */
24753 		ire = save_ire;
24754 		save_ire = NULL;
24755 		q = ire->ire_stq;
24756 	}
24757 
24758 	if (pkt_type == OB_PKT) {
24759 		UPDATE_OB_PKT_COUNT(ire);
24760 	} else {
24761 		out_ill = (ill_t *)q->q_ptr;
24762 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24763 		UPDATE_IB_PKT_COUNT(ire);
24764 	}
24765 
24766 	/* Advance the offset to the second frag starting point. */
24767 	offset += len;
24768 	/*
24769 	 * Update hdr_len from the copied header - there might be less options
24770 	 * in the later fragments.
24771 	 */
24772 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24773 	/* Loop until done. */
24774 	for (;;) {
24775 		uint16_t	offset_and_flags;
24776 		uint16_t	ip_len;
24777 
24778 		if (ip_data_end - offset > len) {
24779 			/*
24780 			 * Carve off the appropriate amount from the original
24781 			 * datagram.
24782 			 */
24783 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24784 				mp = NULL;
24785 				break;
24786 			}
24787 			/*
24788 			 * More frags after this one.  Get another copy
24789 			 * of the header.
24790 			 */
24791 			if (carve_mp->b_datap->db_ref == 1 &&
24792 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24793 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24794 				/* Inline IP header */
24795 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24796 				    hdr_mp->b_rptr;
24797 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24798 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24799 				mp = carve_mp;
24800 			} else {
24801 				if (!(mp = copyb(hdr_mp))) {
24802 					freemsg(carve_mp);
24803 					break;
24804 				}
24805 				/* Get priority marking, if any. */
24806 				mp->b_band = carve_mp->b_band;
24807 				mp->b_cont = carve_mp;
24808 			}
24809 			ipha = (ipha_t *)mp->b_rptr;
24810 			offset_and_flags = IPH_MF;
24811 		} else {
24812 			/*
24813 			 * Last frag.  Consume the header. Set len to
24814 			 * the length of this last piece.
24815 			 */
24816 			len = ip_data_end - offset;
24817 
24818 			/*
24819 			 * Carve off the appropriate amount from the original
24820 			 * datagram.
24821 			 */
24822 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24823 				mp = NULL;
24824 				break;
24825 			}
24826 			if (carve_mp->b_datap->db_ref == 1 &&
24827 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24828 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24829 				/* Inline IP header */
24830 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24831 				    hdr_mp->b_rptr;
24832 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24833 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24834 				mp = carve_mp;
24835 				freeb(hdr_mp);
24836 				hdr_mp = mp;
24837 			} else {
24838 				mp = hdr_mp;
24839 				/* Get priority marking, if any. */
24840 				mp->b_band = carve_mp->b_band;
24841 				mp->b_cont = carve_mp;
24842 			}
24843 			ipha = (ipha_t *)mp->b_rptr;
24844 			/* A frag of a frag might have IPH_MF non-zero */
24845 			offset_and_flags =
24846 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24847 			    IPH_MF;
24848 		}
24849 		offset_and_flags |= (uint16_t)(offset >> 3);
24850 		offset_and_flags |= (uint16_t)frag_flag;
24851 		/* Store the offset and flags in the IP header. */
24852 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24853 
24854 		/* Store the length in the IP header. */
24855 		ip_len = (uint16_t)(len + hdr_len);
24856 		ipha->ipha_length = htons(ip_len);
24857 
24858 		/*
24859 		 * Set the IP header checksum.	Note that mp is just
24860 		 * the header, so this is easy to pass to ip_csum.
24861 		 */
24862 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24863 
24864 		/* Attach a transmit header, if any, and ship it. */
24865 		if (pkt_type == OB_PKT) {
24866 			UPDATE_OB_PKT_COUNT(ire);
24867 		} else {
24868 			out_ill = (ill_t *)q->q_ptr;
24869 			BUMP_MIB(out_ill->ill_ip_mib,
24870 			    ipIfStatsHCOutForwDatagrams);
24871 			UPDATE_IB_PKT_COUNT(ire);
24872 		}
24873 
24874 		if (ire->ire_flags & RTF_MULTIRT) {
24875 			irb = ire->ire_bucket;
24876 			ASSERT(irb != NULL);
24877 
24878 			multirt_send = B_TRUE;
24879 
24880 			/*
24881 			 * Save the original ire; we will need to restore it
24882 			 * for the tailing frags.
24883 			 */
24884 			save_ire = ire;
24885 			IRE_REFHOLD(save_ire);
24886 		}
24887 		/*
24888 		 * Emission loop for this fragment, similar
24889 		 * to what is done for the first fragment.
24890 		 */
24891 		do {
24892 			if (multirt_send) {
24893 				/*
24894 				 * We are in a multiple send case, need to get
24895 				 * the next ire and make a copy of the packet.
24896 				 */
24897 				ASSERT(irb != NULL);
24898 				IRB_REFHOLD(irb);
24899 				for (ire1 = ire->ire_next;
24900 				    ire1 != NULL;
24901 				    ire1 = ire1->ire_next) {
24902 					if (!(ire1->ire_flags & RTF_MULTIRT))
24903 						continue;
24904 					if (ire1->ire_addr != ire->ire_addr)
24905 						continue;
24906 					if (ire1->ire_marks &
24907 					    (IRE_MARK_CONDEMNED|
24908 						IRE_MARK_HIDDEN))
24909 						continue;
24910 					/*
24911 					 * Ensure we do not exceed the MTU
24912 					 * of the next route.
24913 					 */
24914 					if (ire1->ire_max_frag < max_frag) {
24915 						ip_multirt_bad_mtu(ire1,
24916 						    max_frag);
24917 						continue;
24918 					}
24919 
24920 					/* Got one. */
24921 					IRE_REFHOLD(ire1);
24922 					break;
24923 				}
24924 				IRB_REFRELE(irb);
24925 
24926 				if (ire1 != NULL) {
24927 					next_mp = copyb(mp);
24928 					if ((next_mp == NULL) ||
24929 					    ((mp->b_cont != NULL) &&
24930 					    ((next_mp->b_cont =
24931 					    dupmsg(mp->b_cont)) == NULL))) {
24932 						freemsg(next_mp);
24933 						next_mp = NULL;
24934 						ire_refrele(ire1);
24935 						ire1 = NULL;
24936 					}
24937 				}
24938 
24939 				/* Last multiroute ire; don't loop anymore. */
24940 				if (ire1 == NULL) {
24941 					multirt_send = B_FALSE;
24942 				}
24943 			}
24944 
24945 			/* Update transmit header */
24946 			ll_hdr_len = 0;
24947 			LOCK_IRE_FP_MP(ire);
24948 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24949 			if (ll_hdr_mp != NULL) {
24950 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24951 				ll_hdr_len = MBLKL(ll_hdr_mp);
24952 			} else {
24953 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24954 			}
24955 
24956 			if (!ll_hdr_mp) {
24957 				xmit_mp = mp;
24958 
24959 			/*
24960 			 * We have link-layer header that can fit in
24961 			 * our mblk.
24962 			 */
24963 			} else if (mp->b_datap->db_ref == 1 &&
24964 			    ll_hdr_len != 0 &&
24965 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24966 				/* M_DATA fastpath */
24967 				mp->b_rptr -= ll_hdr_len;
24968 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24969 				    ll_hdr_len);
24970 				xmit_mp = mp;
24971 
24972 			/*
24973 			 * Case of res_mp OR the fastpath mp can't fit
24974 			 * in the mblk
24975 			 */
24976 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24977 				xmit_mp->b_cont = mp;
24978 				if (DB_CRED(mp) != NULL)
24979 					mblk_setcred(xmit_mp, DB_CRED(mp));
24980 				/* Get priority marking, if any. */
24981 				if (DB_TYPE(xmit_mp) == M_DATA)
24982 					xmit_mp->b_band = mp->b_band;
24983 
24984 			/* Corner case if copyb failed */
24985 			} else {
24986 				/*
24987 				 * Exit both the replication and
24988 				 * fragmentation loops.
24989 				 */
24990 				UNLOCK_IRE_FP_MP(ire);
24991 				goto drop_pkt;
24992 			}
24993 			UNLOCK_IRE_FP_MP(ire);
24994 
24995 			mp1 = mp;
24996 			out_ill = (ill_t *)q->q_ptr;
24997 
24998 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24999 
25000 			DTRACE_PROBE4(ip4__physical__out__start,
25001 			    ill_t *, NULL, ill_t *, out_ill,
25002 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25003 
25004 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25005 			    ipst->ips_ipv4firewall_physical_out,
25006 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25007 
25008 			DTRACE_PROBE1(ip4__physical__out__end,
25009 			    mblk_t *, xmit_mp);
25010 
25011 			if (mp != mp1 && hdr_mp == mp1)
25012 				hdr_mp = mp;
25013 			if (mp != mp1 && mp_orig == mp1)
25014 				mp_orig = mp;
25015 
25016 			if (xmit_mp != NULL) {
25017 				putnext(q, xmit_mp);
25018 
25019 				BUMP_MIB(out_ill->ill_ip_mib,
25020 				    ipIfStatsHCOutTransmits);
25021 				UPDATE_MIB(out_ill->ill_ip_mib,
25022 				    ipIfStatsHCOutOctets, ip_len);
25023 
25024 				if (pkt_type != OB_PKT) {
25025 					/*
25026 					 * Update the packet count of trailing
25027 					 * RTF_MULTIRT ires.
25028 					 */
25029 					UPDATE_OB_PKT_COUNT(ire);
25030 				}
25031 			}
25032 
25033 			/* All done if we just consumed the hdr_mp. */
25034 			if (mp == hdr_mp) {
25035 				last_frag = B_TRUE;
25036 				BUMP_MIB(out_ill->ill_ip_mib,
25037 				    ipIfStatsOutFragOKs);
25038 			}
25039 
25040 			if (multirt_send) {
25041 				/*
25042 				 * We are in a multiple send case; look for
25043 				 * the next ire and re-enter the loop.
25044 				 */
25045 				ASSERT(ire1);
25046 				ASSERT(next_mp);
25047 				/* REFRELE the current ire before looping */
25048 				ire_refrele(ire);
25049 				ire = ire1;
25050 				ire1 = NULL;
25051 				q = ire->ire_stq;
25052 				mp = next_mp;
25053 				next_mp = NULL;
25054 			}
25055 		} while (multirt_send);
25056 		/*
25057 		 * Restore the original ire; we need it for the
25058 		 * trailing frags
25059 		 */
25060 		if (save_ire != NULL) {
25061 			ASSERT(ire1 == NULL);
25062 			/* REFRELE the last iterated ire */
25063 			ire_refrele(ire);
25064 			/* save_ire has been REFHOLDed */
25065 			ire = save_ire;
25066 			q = ire->ire_stq;
25067 			save_ire = NULL;
25068 		}
25069 
25070 		if (last_frag) {
25071 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25072 			    "ip_wput_frag_end:(%S)",
25073 			    "consumed hdr_mp");
25074 
25075 			if (first_ire != NULL)
25076 				ire_refrele(first_ire);
25077 			return;
25078 		}
25079 		/* Otherwise, advance and loop. */
25080 		offset += len;
25081 	}
25082 
25083 drop_pkt:
25084 	/* Clean up following allocation failure. */
25085 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25086 	freemsg(mp);
25087 	if (mp != hdr_mp)
25088 		freeb(hdr_mp);
25089 	if (mp != mp_orig)
25090 		freemsg(mp_orig);
25091 
25092 	if (save_ire != NULL)
25093 		IRE_REFRELE(save_ire);
25094 	if (first_ire != NULL)
25095 		ire_refrele(first_ire);
25096 
25097 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25098 	    "ip_wput_frag_end:(%S)",
25099 	    "end--alloc failure");
25100 }
25101 
25102 /*
25103  * Copy the header plus those options which have the copy bit set
25104  */
25105 static mblk_t *
25106 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25107 {
25108 	mblk_t	*mp;
25109 	uchar_t	*up;
25110 
25111 	/*
25112 	 * Quick check if we need to look for options without the copy bit
25113 	 * set
25114 	 */
25115 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25116 	if (!mp)
25117 		return (mp);
25118 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25119 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25120 		bcopy(rptr, mp->b_rptr, hdr_len);
25121 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25122 		return (mp);
25123 	}
25124 	up  = mp->b_rptr;
25125 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25126 	up += IP_SIMPLE_HDR_LENGTH;
25127 	rptr += IP_SIMPLE_HDR_LENGTH;
25128 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25129 	while (hdr_len > 0) {
25130 		uint32_t optval;
25131 		uint32_t optlen;
25132 
25133 		optval = *rptr;
25134 		if (optval == IPOPT_EOL)
25135 			break;
25136 		if (optval == IPOPT_NOP)
25137 			optlen = 1;
25138 		else
25139 			optlen = rptr[1];
25140 		if (optval & IPOPT_COPY) {
25141 			bcopy(rptr, up, optlen);
25142 			up += optlen;
25143 		}
25144 		rptr += optlen;
25145 		hdr_len -= optlen;
25146 	}
25147 	/*
25148 	 * Make sure that we drop an even number of words by filling
25149 	 * with EOL to the next word boundary.
25150 	 */
25151 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25152 	    hdr_len & 0x3; hdr_len++)
25153 		*up++ = IPOPT_EOL;
25154 	mp->b_wptr = up;
25155 	/* Update header length */
25156 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25157 	return (mp);
25158 }
25159 
25160 /*
25161  * Delivery to local recipients including fanout to multiple recipients.
25162  * Does not do checksumming of UDP/TCP.
25163  * Note: q should be the read side queue for either the ill or conn.
25164  * Note: rq should be the read side q for the lower (ill) stream.
25165  * We don't send packets to IPPF processing, thus the last argument
25166  * to all the fanout calls are B_FALSE.
25167  */
25168 void
25169 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25170     int fanout_flags, zoneid_t zoneid)
25171 {
25172 	uint32_t	protocol;
25173 	mblk_t		*first_mp;
25174 	boolean_t	mctl_present;
25175 	int		ire_type;
25176 #define	rptr	((uchar_t *)ipha)
25177 	ip_stack_t	*ipst = ill->ill_ipst;
25178 
25179 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25180 	    "ip_wput_local_start: q %p", q);
25181 
25182 	if (ire != NULL) {
25183 		ire_type = ire->ire_type;
25184 	} else {
25185 		/*
25186 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25187 		 * packet is not multicast, we can't tell the ire type.
25188 		 */
25189 		ASSERT(CLASSD(ipha->ipha_dst));
25190 		ire_type = IRE_BROADCAST;
25191 	}
25192 
25193 	first_mp = mp;
25194 	if (first_mp->b_datap->db_type == M_CTL) {
25195 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25196 		if (!io->ipsec_out_secure) {
25197 			/*
25198 			 * This ipsec_out_t was allocated in ip_wput
25199 			 * for multicast packets to store the ill_index.
25200 			 * As this is being delivered locally, we don't
25201 			 * need this anymore.
25202 			 */
25203 			mp = first_mp->b_cont;
25204 			freeb(first_mp);
25205 			first_mp = mp;
25206 			mctl_present = B_FALSE;
25207 		} else {
25208 			/*
25209 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25210 			 * security properties for the looped-back packet.
25211 			 */
25212 			mctl_present = B_TRUE;
25213 			mp = first_mp->b_cont;
25214 			ASSERT(mp != NULL);
25215 			ipsec_out_to_in(first_mp);
25216 		}
25217 	} else {
25218 		mctl_present = B_FALSE;
25219 	}
25220 
25221 	DTRACE_PROBE4(ip4__loopback__in__start,
25222 	    ill_t *, ill, ill_t *, NULL,
25223 	    ipha_t *, ipha, mblk_t *, first_mp);
25224 
25225 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25226 	    ipst->ips_ipv4firewall_loopback_in,
25227 	    ill, NULL, ipha, first_mp, mp, ipst);
25228 
25229 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25230 
25231 	if (first_mp == NULL)
25232 		return;
25233 
25234 	ipst->ips_loopback_packets++;
25235 
25236 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25237 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25238 	if (!IS_SIMPLE_IPH(ipha)) {
25239 		ip_wput_local_options(ipha, ipst);
25240 	}
25241 
25242 	protocol = ipha->ipha_protocol;
25243 	switch (protocol) {
25244 	case IPPROTO_ICMP: {
25245 		ire_t		*ire_zone;
25246 		ilm_t		*ilm;
25247 		mblk_t		*mp1;
25248 		zoneid_t	last_zoneid;
25249 
25250 		if (CLASSD(ipha->ipha_dst) &&
25251 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
25252 			ASSERT(ire_type == IRE_BROADCAST);
25253 			/*
25254 			 * In the multicast case, applications may have joined
25255 			 * the group from different zones, so we need to deliver
25256 			 * the packet to each of them. Loop through the
25257 			 * multicast memberships structures (ilm) on the receive
25258 			 * ill and send a copy of the packet up each matching
25259 			 * one. However, we don't do this for multicasts sent on
25260 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25261 			 * they must stay in the sender's zone.
25262 			 *
25263 			 * ilm_add_v6() ensures that ilms in the same zone are
25264 			 * contiguous in the ill_ilm list. We use this property
25265 			 * to avoid sending duplicates needed when two
25266 			 * applications in the same zone join the same group on
25267 			 * different logical interfaces: we ignore the ilm if
25268 			 * it's zoneid is the same as the last matching one.
25269 			 * In addition, the sending of the packet for
25270 			 * ire_zoneid is delayed until all of the other ilms
25271 			 * have been exhausted.
25272 			 */
25273 			last_zoneid = -1;
25274 			ILM_WALKER_HOLD(ill);
25275 			for (ilm = ill->ill_ilm; ilm != NULL;
25276 			    ilm = ilm->ilm_next) {
25277 				if ((ilm->ilm_flags & ILM_DELETED) ||
25278 				    ipha->ipha_dst != ilm->ilm_addr ||
25279 				    ilm->ilm_zoneid == last_zoneid ||
25280 				    ilm->ilm_zoneid == zoneid ||
25281 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25282 					continue;
25283 				mp1 = ip_copymsg(first_mp);
25284 				if (mp1 == NULL)
25285 					continue;
25286 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25287 				    mctl_present, B_FALSE, ill,
25288 				    ilm->ilm_zoneid);
25289 				last_zoneid = ilm->ilm_zoneid;
25290 			}
25291 			ILM_WALKER_RELE(ill);
25292 			/*
25293 			 * Loopback case: the sending endpoint has
25294 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25295 			 * dispatch the multicast packet to the sending zone.
25296 			 */
25297 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25298 				freemsg(first_mp);
25299 				return;
25300 			}
25301 		} else if (ire_type == IRE_BROADCAST) {
25302 			/*
25303 			 * In the broadcast case, there may be many zones
25304 			 * which need a copy of the packet delivered to them.
25305 			 * There is one IRE_BROADCAST per broadcast address
25306 			 * and per zone; we walk those using a helper function.
25307 			 * In addition, the sending of the packet for zoneid is
25308 			 * delayed until all of the other ires have been
25309 			 * processed.
25310 			 */
25311 			IRB_REFHOLD(ire->ire_bucket);
25312 			ire_zone = NULL;
25313 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25314 			    ire)) != NULL) {
25315 				mp1 = ip_copymsg(first_mp);
25316 				if (mp1 == NULL)
25317 					continue;
25318 
25319 				UPDATE_IB_PKT_COUNT(ire_zone);
25320 				ire_zone->ire_last_used_time = lbolt;
25321 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25322 				    mctl_present, B_FALSE, ill,
25323 				    ire_zone->ire_zoneid);
25324 			}
25325 			IRB_REFRELE(ire->ire_bucket);
25326 		}
25327 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25328 		    0, mctl_present, B_FALSE, ill, zoneid);
25329 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25330 		    "ip_wput_local_end: q %p (%S)",
25331 		    q, "icmp");
25332 		return;
25333 	}
25334 	case IPPROTO_IGMP:
25335 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25336 			/* Bad packet - discarded by igmp_input */
25337 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25338 			    "ip_wput_local_end: q %p (%S)",
25339 			    q, "igmp_input--bad packet");
25340 			if (mctl_present)
25341 				freeb(first_mp);
25342 			return;
25343 		}
25344 		/*
25345 		 * igmp_input() may have returned the pulled up message.
25346 		 * So first_mp and ipha need to be reinitialized.
25347 		 */
25348 		ipha = (ipha_t *)mp->b_rptr;
25349 		if (mctl_present)
25350 			first_mp->b_cont = mp;
25351 		else
25352 			first_mp = mp;
25353 		/* deliver to local raw users */
25354 		break;
25355 	case IPPROTO_ENCAP:
25356 		/*
25357 		 * This case is covered by either ip_fanout_proto, or by
25358 		 * the above security processing for self-tunneled packets.
25359 		 */
25360 		break;
25361 	case IPPROTO_UDP: {
25362 		uint16_t	*up;
25363 		uint32_t	ports;
25364 
25365 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25366 		    UDP_PORTS_OFFSET);
25367 		/* Force a 'valid' checksum. */
25368 		up[3] = 0;
25369 
25370 		ports = *(uint32_t *)up;
25371 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25372 		    (ire_type == IRE_BROADCAST),
25373 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25374 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25375 		    ill, zoneid);
25376 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25377 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25378 		return;
25379 	}
25380 	case IPPROTO_TCP: {
25381 
25382 		/*
25383 		 * For TCP, discard broadcast packets.
25384 		 */
25385 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25386 			freemsg(first_mp);
25387 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25388 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25389 			return;
25390 		}
25391 
25392 		if (mp->b_datap->db_type == M_DATA) {
25393 			/*
25394 			 * M_DATA mblk, so init mblk (chain) for no struio().
25395 			 */
25396 			mblk_t	*mp1 = mp;
25397 
25398 			do
25399 				mp1->b_datap->db_struioflag = 0;
25400 			while ((mp1 = mp1->b_cont) != NULL);
25401 		}
25402 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25403 		    <= mp->b_wptr);
25404 		ip_fanout_tcp(q, first_mp, ill, ipha,
25405 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25406 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25407 		    mctl_present, B_FALSE, zoneid);
25408 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25409 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25410 		return;
25411 	}
25412 	case IPPROTO_SCTP:
25413 	{
25414 		uint32_t	ports;
25415 
25416 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25417 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25418 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25419 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25420 		return;
25421 	}
25422 
25423 	default:
25424 		break;
25425 	}
25426 	/*
25427 	 * Find a client for some other protocol.  We give
25428 	 * copies to multiple clients, if more than one is
25429 	 * bound.
25430 	 */
25431 	ip_fanout_proto(q, first_mp, ill, ipha,
25432 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25433 	    mctl_present, B_FALSE, ill, zoneid);
25434 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25435 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25436 #undef	rptr
25437 }
25438 
25439 /*
25440  * Update any source route, record route, or timestamp options.
25441  * Check that we are at end of strict source route.
25442  * The options have been sanity checked by ip_wput_options().
25443  */
25444 static void
25445 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25446 {
25447 	ipoptp_t	opts;
25448 	uchar_t		*opt;
25449 	uint8_t		optval;
25450 	uint8_t		optlen;
25451 	ipaddr_t	dst;
25452 	uint32_t	ts;
25453 	ire_t		*ire;
25454 	timestruc_t	now;
25455 
25456 	ip2dbg(("ip_wput_local_options\n"));
25457 	for (optval = ipoptp_first(&opts, ipha);
25458 	    optval != IPOPT_EOL;
25459 	    optval = ipoptp_next(&opts)) {
25460 		opt = opts.ipoptp_cur;
25461 		optlen = opts.ipoptp_len;
25462 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25463 		switch (optval) {
25464 			uint32_t off;
25465 		case IPOPT_SSRR:
25466 		case IPOPT_LSRR:
25467 			off = opt[IPOPT_OFFSET];
25468 			off--;
25469 			if (optlen < IP_ADDR_LEN ||
25470 			    off > optlen - IP_ADDR_LEN) {
25471 				/* End of source route */
25472 				break;
25473 			}
25474 			/*
25475 			 * This will only happen if two consecutive entries
25476 			 * in the source route contains our address or if
25477 			 * it is a packet with a loose source route which
25478 			 * reaches us before consuming the whole source route
25479 			 */
25480 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25481 			if (optval == IPOPT_SSRR) {
25482 				return;
25483 			}
25484 			/*
25485 			 * Hack: instead of dropping the packet truncate the
25486 			 * source route to what has been used by filling the
25487 			 * rest with IPOPT_NOP.
25488 			 */
25489 			opt[IPOPT_OLEN] = (uint8_t)off;
25490 			while (off < optlen) {
25491 				opt[off++] = IPOPT_NOP;
25492 			}
25493 			break;
25494 		case IPOPT_RR:
25495 			off = opt[IPOPT_OFFSET];
25496 			off--;
25497 			if (optlen < IP_ADDR_LEN ||
25498 			    off > optlen - IP_ADDR_LEN) {
25499 				/* No more room - ignore */
25500 				ip1dbg((
25501 				    "ip_wput_forward_options: end of RR\n"));
25502 				break;
25503 			}
25504 			dst = htonl(INADDR_LOOPBACK);
25505 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25506 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25507 			break;
25508 		case IPOPT_TS:
25509 			/* Insert timestamp if there is romm */
25510 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25511 			case IPOPT_TS_TSONLY:
25512 				off = IPOPT_TS_TIMELEN;
25513 				break;
25514 			case IPOPT_TS_PRESPEC:
25515 			case IPOPT_TS_PRESPEC_RFC791:
25516 				/* Verify that the address matched */
25517 				off = opt[IPOPT_OFFSET] - 1;
25518 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25519 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25520 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25521 				    ipst);
25522 				if (ire == NULL) {
25523 					/* Not for us */
25524 					break;
25525 				}
25526 				ire_refrele(ire);
25527 				/* FALLTHRU */
25528 			case IPOPT_TS_TSANDADDR:
25529 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25530 				break;
25531 			default:
25532 				/*
25533 				 * ip_*put_options should have already
25534 				 * dropped this packet.
25535 				 */
25536 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25537 				    "unknown IT - bug in ip_wput_options?\n");
25538 				return;	/* Keep "lint" happy */
25539 			}
25540 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25541 				/* Increase overflow counter */
25542 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25543 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25544 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25545 				    (off << 4);
25546 				break;
25547 			}
25548 			off = opt[IPOPT_OFFSET] - 1;
25549 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25550 			case IPOPT_TS_PRESPEC:
25551 			case IPOPT_TS_PRESPEC_RFC791:
25552 			case IPOPT_TS_TSANDADDR:
25553 				dst = htonl(INADDR_LOOPBACK);
25554 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25555 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25556 				/* FALLTHRU */
25557 			case IPOPT_TS_TSONLY:
25558 				off = opt[IPOPT_OFFSET] - 1;
25559 				/* Compute # of milliseconds since midnight */
25560 				gethrestime(&now);
25561 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25562 				    now.tv_nsec / (NANOSEC / MILLISEC);
25563 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25564 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25565 				break;
25566 			}
25567 			break;
25568 		}
25569 	}
25570 }
25571 
25572 /*
25573  * Send out a multicast packet on interface ipif.
25574  * The sender does not have an conn.
25575  * Caller verifies that this isn't a PHYI_LOOPBACK.
25576  */
25577 void
25578 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25579 {
25580 	ipha_t	*ipha;
25581 	ire_t	*ire;
25582 	ipaddr_t	dst;
25583 	mblk_t		*first_mp;
25584 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25585 
25586 	/* igmp_sendpkt always allocates a ipsec_out_t */
25587 	ASSERT(mp->b_datap->db_type == M_CTL);
25588 	ASSERT(!ipif->ipif_isv6);
25589 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
25590 
25591 	first_mp = mp;
25592 	mp = first_mp->b_cont;
25593 	ASSERT(mp->b_datap->db_type == M_DATA);
25594 	ipha = (ipha_t *)mp->b_rptr;
25595 
25596 	/*
25597 	 * Find an IRE which matches the destination and the outgoing
25598 	 * queue (i.e. the outgoing interface.)
25599 	 */
25600 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25601 		dst = ipif->ipif_pp_dst_addr;
25602 	else
25603 		dst = ipha->ipha_dst;
25604 	/*
25605 	 * The source address has already been initialized by the
25606 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25607 	 * be sufficient rather than MATCH_IRE_IPIF.
25608 	 *
25609 	 * This function is used for sending IGMP packets. We need
25610 	 * to make sure that we send the packet out of the interface
25611 	 * (ipif->ipif_ill) where we joined the group. This is to
25612 	 * prevent from switches doing IGMP snooping to send us multicast
25613 	 * packets for a given group on the interface we have joined.
25614 	 * If we can't find an ire, igmp_sendpkt has already initialized
25615 	 * ipsec_out_attach_if so that this will not be load spread in
25616 	 * ip_newroute_ipif.
25617 	 */
25618 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25619 	    MATCH_IRE_ILL, ipst);
25620 	if (!ire) {
25621 		/*
25622 		 * Mark this packet to make it be delivered to
25623 		 * ip_wput_ire after the new ire has been
25624 		 * created.
25625 		 */
25626 		mp->b_prev = NULL;
25627 		mp->b_next = NULL;
25628 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25629 		    zoneid, &zero_info);
25630 		return;
25631 	}
25632 
25633 	/*
25634 	 * Honor the RTF_SETSRC flag; this is the only case
25635 	 * where we force this addr whatever the current src addr is,
25636 	 * because this address is set by igmp_sendpkt(), and
25637 	 * cannot be specified by any user.
25638 	 */
25639 	if (ire->ire_flags & RTF_SETSRC) {
25640 		ipha->ipha_src = ire->ire_src_addr;
25641 	}
25642 
25643 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25644 }
25645 
25646 /*
25647  * NOTE : This function does not ire_refrele the ire argument passed in.
25648  *
25649  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25650  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25651  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25652  * the ire_lock to access the nce_fp_mp in this case.
25653  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25654  * prepending a fastpath message IPQoS processing must precede it, we also set
25655  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25656  * (IPQoS might have set the b_band for CoS marking).
25657  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25658  * must follow it so that IPQoS can mark the dl_priority field for CoS
25659  * marking, if needed.
25660  */
25661 static mblk_t *
25662 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25663 {
25664 	uint_t	hlen;
25665 	ipha_t *ipha;
25666 	mblk_t *mp1;
25667 	boolean_t qos_done = B_FALSE;
25668 	uchar_t	*ll_hdr;
25669 	ip_stack_t	*ipst = ire->ire_ipst;
25670 
25671 #define	rptr	((uchar_t *)ipha)
25672 
25673 	ipha = (ipha_t *)mp->b_rptr;
25674 	hlen = 0;
25675 	LOCK_IRE_FP_MP(ire);
25676 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25677 		ASSERT(DB_TYPE(mp1) == M_DATA);
25678 		/* Initiate IPPF processing */
25679 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25680 			UNLOCK_IRE_FP_MP(ire);
25681 			ip_process(proc, &mp, ill_index);
25682 			if (mp == NULL)
25683 				return (NULL);
25684 
25685 			ipha = (ipha_t *)mp->b_rptr;
25686 			LOCK_IRE_FP_MP(ire);
25687 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25688 				qos_done = B_TRUE;
25689 				goto no_fp_mp;
25690 			}
25691 			ASSERT(DB_TYPE(mp1) == M_DATA);
25692 		}
25693 		hlen = MBLKL(mp1);
25694 		/*
25695 		 * Check if we have enough room to prepend fastpath
25696 		 * header
25697 		 */
25698 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25699 			ll_hdr = rptr - hlen;
25700 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25701 			/*
25702 			 * Set the b_rptr to the start of the link layer
25703 			 * header
25704 			 */
25705 			mp->b_rptr = ll_hdr;
25706 			mp1 = mp;
25707 		} else {
25708 			mp1 = copyb(mp1);
25709 			if (mp1 == NULL)
25710 				goto unlock_err;
25711 			mp1->b_band = mp->b_band;
25712 			mp1->b_cont = mp;
25713 			/*
25714 			 * certain system generated traffic may not
25715 			 * have cred/label in ip header block. This
25716 			 * is true even for a labeled system. But for
25717 			 * labeled traffic, inherit the label in the
25718 			 * new header.
25719 			 */
25720 			if (DB_CRED(mp) != NULL)
25721 				mblk_setcred(mp1, DB_CRED(mp));
25722 			/*
25723 			 * XXX disable ICK_VALID and compute checksum
25724 			 * here; can happen if nce_fp_mp changes and
25725 			 * it can't be copied now due to insufficient
25726 			 * space. (unlikely, fp mp can change, but it
25727 			 * does not increase in length)
25728 			 */
25729 		}
25730 		UNLOCK_IRE_FP_MP(ire);
25731 	} else {
25732 no_fp_mp:
25733 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25734 		if (mp1 == NULL) {
25735 unlock_err:
25736 			UNLOCK_IRE_FP_MP(ire);
25737 			freemsg(mp);
25738 			return (NULL);
25739 		}
25740 		UNLOCK_IRE_FP_MP(ire);
25741 		mp1->b_cont = mp;
25742 		/*
25743 		 * certain system generated traffic may not
25744 		 * have cred/label in ip header block. This
25745 		 * is true even for a labeled system. But for
25746 		 * labeled traffic, inherit the label in the
25747 		 * new header.
25748 		 */
25749 		if (DB_CRED(mp) != NULL)
25750 			mblk_setcred(mp1, DB_CRED(mp));
25751 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25752 			ip_process(proc, &mp1, ill_index);
25753 			if (mp1 == NULL)
25754 				return (NULL);
25755 		}
25756 	}
25757 	return (mp1);
25758 #undef rptr
25759 }
25760 
25761 /*
25762  * Finish the outbound IPsec processing for an IPv6 packet. This function
25763  * is called from ipsec_out_process() if the IPsec packet was processed
25764  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25765  * asynchronously.
25766  */
25767 void
25768 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25769     ire_t *ire_arg)
25770 {
25771 	in6_addr_t *v6dstp;
25772 	ire_t *ire;
25773 	mblk_t *mp;
25774 	ip6_t *ip6h1;
25775 	uint_t	ill_index;
25776 	ipsec_out_t *io;
25777 	boolean_t attach_if, hwaccel;
25778 	uint32_t flags = IP6_NO_IPPOLICY;
25779 	int match_flags;
25780 	zoneid_t zoneid;
25781 	boolean_t ill_need_rele = B_FALSE;
25782 	boolean_t ire_need_rele = B_FALSE;
25783 	ip_stack_t	*ipst;
25784 
25785 	mp = ipsec_mp->b_cont;
25786 	ip6h1 = (ip6_t *)mp->b_rptr;
25787 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25788 	ASSERT(io->ipsec_out_ns != NULL);
25789 	ipst = io->ipsec_out_ns->netstack_ip;
25790 	ill_index = io->ipsec_out_ill_index;
25791 	if (io->ipsec_out_reachable) {
25792 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25793 	}
25794 	attach_if = io->ipsec_out_attach_if;
25795 	hwaccel = io->ipsec_out_accelerated;
25796 	zoneid = io->ipsec_out_zoneid;
25797 	ASSERT(zoneid != ALL_ZONES);
25798 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25799 	/* Multicast addresses should have non-zero ill_index. */
25800 	v6dstp = &ip6h->ip6_dst;
25801 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25802 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25803 	ASSERT(!attach_if || ill_index != 0);
25804 	if (ill_index != 0) {
25805 		if (ill == NULL) {
25806 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25807 			    B_TRUE, ipst);
25808 
25809 			/* Failure case frees things for us. */
25810 			if (ill == NULL)
25811 				return;
25812 
25813 			ill_need_rele = B_TRUE;
25814 		}
25815 		/*
25816 		 * If this packet needs to go out on a particular interface
25817 		 * honor it.
25818 		 */
25819 		if (attach_if) {
25820 			match_flags = MATCH_IRE_ILL;
25821 
25822 			/*
25823 			 * Check if we need an ire that will not be
25824 			 * looked up by anybody else i.e. HIDDEN.
25825 			 */
25826 			if (ill_is_probeonly(ill)) {
25827 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25828 			}
25829 		}
25830 	}
25831 	ASSERT(mp != NULL);
25832 
25833 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25834 		boolean_t unspec_src;
25835 		ipif_t	*ipif;
25836 
25837 		/*
25838 		 * Use the ill_index to get the right ill.
25839 		 */
25840 		unspec_src = io->ipsec_out_unspec_src;
25841 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25842 		if (ipif == NULL) {
25843 			if (ill_need_rele)
25844 				ill_refrele(ill);
25845 			freemsg(ipsec_mp);
25846 			return;
25847 		}
25848 
25849 		if (ire_arg != NULL) {
25850 			ire = ire_arg;
25851 		} else {
25852 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25853 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25854 			ire_need_rele = B_TRUE;
25855 		}
25856 		if (ire != NULL) {
25857 			ipif_refrele(ipif);
25858 			/*
25859 			 * XXX Do the multicast forwarding now, as the IPSEC
25860 			 * processing has been done.
25861 			 */
25862 			goto send;
25863 		}
25864 
25865 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25866 		mp->b_prev = NULL;
25867 		mp->b_next = NULL;
25868 
25869 		/*
25870 		 * If the IPsec packet was processed asynchronously,
25871 		 * drop it now.
25872 		 */
25873 		if (q == NULL) {
25874 			if (ill_need_rele)
25875 				ill_refrele(ill);
25876 			freemsg(ipsec_mp);
25877 			return;
25878 		}
25879 
25880 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25881 		    unspec_src, zoneid);
25882 		ipif_refrele(ipif);
25883 	} else {
25884 		if (attach_if) {
25885 			ipif_t	*ipif;
25886 
25887 			ipif = ipif_get_next_ipif(NULL, ill);
25888 			if (ipif == NULL) {
25889 				if (ill_need_rele)
25890 					ill_refrele(ill);
25891 				freemsg(ipsec_mp);
25892 				return;
25893 			}
25894 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25895 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25896 			ire_need_rele = B_TRUE;
25897 			ipif_refrele(ipif);
25898 		} else {
25899 			if (ire_arg != NULL) {
25900 				ire = ire_arg;
25901 			} else {
25902 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25903 				    ipst);
25904 				ire_need_rele = B_TRUE;
25905 			}
25906 		}
25907 		if (ire != NULL)
25908 			goto send;
25909 		/*
25910 		 * ire disappeared underneath.
25911 		 *
25912 		 * What we need to do here is the ip_newroute
25913 		 * logic to get the ire without doing the IPSEC
25914 		 * processing. Follow the same old path. But this
25915 		 * time, ip_wput or ire_add_then_send will call us
25916 		 * directly as all the IPSEC operations are done.
25917 		 */
25918 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25919 		mp->b_prev = NULL;
25920 		mp->b_next = NULL;
25921 
25922 		/*
25923 		 * If the IPsec packet was processed asynchronously,
25924 		 * drop it now.
25925 		 */
25926 		if (q == NULL) {
25927 			if (ill_need_rele)
25928 				ill_refrele(ill);
25929 			freemsg(ipsec_mp);
25930 			return;
25931 		}
25932 
25933 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25934 		    zoneid, ipst);
25935 	}
25936 	if (ill != NULL && ill_need_rele)
25937 		ill_refrele(ill);
25938 	return;
25939 send:
25940 	if (ill != NULL && ill_need_rele)
25941 		ill_refrele(ill);
25942 
25943 	/* Local delivery */
25944 	if (ire->ire_stq == NULL) {
25945 		ill_t	*out_ill;
25946 		ASSERT(q != NULL);
25947 
25948 		/* PFHooks: LOOPBACK_OUT */
25949 		out_ill = ire->ire_ipif->ipif_ill;
25950 
25951 		DTRACE_PROBE4(ip6__loopback__out__start,
25952 		    ill_t *, NULL, ill_t *, out_ill,
25953 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25954 
25955 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25956 		    ipst->ips_ipv6firewall_loopback_out,
25957 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25958 
25959 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25960 
25961 		if (ipsec_mp != NULL)
25962 			ip_wput_local_v6(RD(q), out_ill,
25963 			    ip6h, ipsec_mp, ire, 0);
25964 		if (ire_need_rele)
25965 			ire_refrele(ire);
25966 		return;
25967 	}
25968 	/*
25969 	 * Everything is done. Send it out on the wire.
25970 	 * We force the insertion of a fragment header using the
25971 	 * IPH_FRAG_HDR flag in two cases:
25972 	 * - after reception of an ICMPv6 "packet too big" message
25973 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25974 	 * - for multirouted IPv6 packets, so that the receiver can
25975 	 *   discard duplicates according to their fragment identifier
25976 	 */
25977 	/* XXX fix flow control problems. */
25978 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25979 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25980 		if (hwaccel) {
25981 			/*
25982 			 * hardware acceleration does not handle these
25983 			 * "slow path" cases.
25984 			 */
25985 			/* IPsec KSTATS: should bump bean counter here. */
25986 			if (ire_need_rele)
25987 				ire_refrele(ire);
25988 			freemsg(ipsec_mp);
25989 			return;
25990 		}
25991 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25992 		    (mp->b_cont ? msgdsize(mp) :
25993 		    mp->b_wptr - (uchar_t *)ip6h)) {
25994 			/* IPsec KSTATS: should bump bean counter here. */
25995 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25996 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25997 			    msgdsize(mp)));
25998 			if (ire_need_rele)
25999 				ire_refrele(ire);
26000 			freemsg(ipsec_mp);
26001 			return;
26002 		}
26003 		ASSERT(mp->b_prev == NULL);
26004 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26005 		    ntohs(ip6h->ip6_plen) +
26006 		    IPV6_HDR_LEN, ire->ire_max_frag));
26007 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26008 		    ire->ire_max_frag);
26009 	} else {
26010 		UPDATE_OB_PKT_COUNT(ire);
26011 		ire->ire_last_used_time = lbolt;
26012 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26013 	}
26014 	if (ire_need_rele)
26015 		ire_refrele(ire);
26016 	freeb(ipsec_mp);
26017 }
26018 
26019 void
26020 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26021 {
26022 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26023 	da_ipsec_t *hada;	/* data attributes */
26024 	ill_t *ill = (ill_t *)q->q_ptr;
26025 
26026 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26027 
26028 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26029 		/* IPsec KSTATS: Bump lose counter here! */
26030 		freemsg(mp);
26031 		return;
26032 	}
26033 
26034 	/*
26035 	 * It's an IPsec packet that must be
26036 	 * accelerated by the Provider, and the
26037 	 * outbound ill is IPsec acceleration capable.
26038 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26039 	 * to the ill.
26040 	 * IPsec KSTATS: should bump packet counter here.
26041 	 */
26042 
26043 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26044 	if (hada_mp == NULL) {
26045 		/* IPsec KSTATS: should bump packet counter here. */
26046 		freemsg(mp);
26047 		return;
26048 	}
26049 
26050 	hada_mp->b_datap->db_type = M_CTL;
26051 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26052 	hada_mp->b_cont = mp;
26053 
26054 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26055 	bzero(hada, sizeof (da_ipsec_t));
26056 	hada->da_type = IPHADA_M_CTL;
26057 
26058 	putnext(q, hada_mp);
26059 }
26060 
26061 /*
26062  * Finish the outbound IPsec processing. This function is called from
26063  * ipsec_out_process() if the IPsec packet was processed
26064  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26065  * asynchronously.
26066  */
26067 void
26068 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26069     ire_t *ire_arg)
26070 {
26071 	uint32_t v_hlen_tos_len;
26072 	ipaddr_t	dst;
26073 	ipif_t	*ipif = NULL;
26074 	ire_t *ire;
26075 	ire_t *ire1 = NULL;
26076 	mblk_t *next_mp = NULL;
26077 	uint32_t max_frag;
26078 	boolean_t multirt_send = B_FALSE;
26079 	mblk_t *mp;
26080 	mblk_t *mp1;
26081 	ipha_t *ipha1;
26082 	uint_t	ill_index;
26083 	ipsec_out_t *io;
26084 	boolean_t attach_if;
26085 	int match_flags, offset;
26086 	irb_t *irb = NULL;
26087 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26088 	zoneid_t zoneid;
26089 	uint32_t cksum;
26090 	uint16_t *up;
26091 	ipxmit_state_t	pktxmit_state;
26092 	ip_stack_t	*ipst;
26093 
26094 #ifdef	_BIG_ENDIAN
26095 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26096 #else
26097 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26098 #endif
26099 
26100 	mp = ipsec_mp->b_cont;
26101 	ipha1 = (ipha_t *)mp->b_rptr;
26102 	ASSERT(mp != NULL);
26103 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26104 	dst = ipha->ipha_dst;
26105 
26106 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26107 	ill_index = io->ipsec_out_ill_index;
26108 	attach_if = io->ipsec_out_attach_if;
26109 	zoneid = io->ipsec_out_zoneid;
26110 	ASSERT(zoneid != ALL_ZONES);
26111 	ipst = io->ipsec_out_ns->netstack_ip;
26112 	ASSERT(io->ipsec_out_ns != NULL);
26113 
26114 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26115 	if (ill_index != 0) {
26116 		if (ill == NULL) {
26117 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26118 			    ill_index, B_FALSE, ipst);
26119 
26120 			/* Failure case frees things for us. */
26121 			if (ill == NULL)
26122 				return;
26123 
26124 			ill_need_rele = B_TRUE;
26125 		}
26126 		/*
26127 		 * If this packet needs to go out on a particular interface
26128 		 * honor it.
26129 		 */
26130 		if (attach_if) {
26131 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26132 
26133 			/*
26134 			 * Check if we need an ire that will not be
26135 			 * looked up by anybody else i.e. HIDDEN.
26136 			 */
26137 			if (ill_is_probeonly(ill)) {
26138 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26139 			}
26140 		}
26141 	}
26142 
26143 	if (CLASSD(dst)) {
26144 		boolean_t conn_dontroute;
26145 		/*
26146 		 * Use the ill_index to get the right ipif.
26147 		 */
26148 		conn_dontroute = io->ipsec_out_dontroute;
26149 		if (ill_index == 0)
26150 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26151 		else
26152 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26153 		if (ipif == NULL) {
26154 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26155 			    " multicast\n"));
26156 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26157 			freemsg(ipsec_mp);
26158 			goto done;
26159 		}
26160 		/*
26161 		 * ipha_src has already been intialized with the
26162 		 * value of the ipif in ip_wput. All we need now is
26163 		 * an ire to send this downstream.
26164 		 */
26165 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26166 		    MBLK_GETLABEL(mp), match_flags, ipst);
26167 		if (ire != NULL) {
26168 			ill_t *ill1;
26169 			/*
26170 			 * Do the multicast forwarding now, as the IPSEC
26171 			 * processing has been done.
26172 			 */
26173 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26174 			    (ill1 = ire_to_ill(ire))) {
26175 				if (ip_mforward(ill1, ipha, mp)) {
26176 					freemsg(ipsec_mp);
26177 					ip1dbg(("ip_wput_ipsec_out: mforward "
26178 					    "failed\n"));
26179 					ire_refrele(ire);
26180 					goto done;
26181 				}
26182 			}
26183 			goto send;
26184 		}
26185 
26186 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26187 		mp->b_prev = NULL;
26188 		mp->b_next = NULL;
26189 
26190 		/*
26191 		 * If the IPsec packet was processed asynchronously,
26192 		 * drop it now.
26193 		 */
26194 		if (q == NULL) {
26195 			freemsg(ipsec_mp);
26196 			goto done;
26197 		}
26198 
26199 		/*
26200 		 * We may be using a wrong ipif to create the ire.
26201 		 * But it is okay as the source address is assigned
26202 		 * for the packet already. Next outbound packet would
26203 		 * create the IRE with the right IPIF in ip_wput.
26204 		 *
26205 		 * Also handle RTF_MULTIRT routes.
26206 		 */
26207 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26208 		    zoneid, &zero_info);
26209 	} else {
26210 		if (attach_if) {
26211 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26212 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26213 		} else {
26214 			if (ire_arg != NULL) {
26215 				ire = ire_arg;
26216 				ire_need_rele = B_FALSE;
26217 			} else {
26218 				ire = ire_cache_lookup(dst, zoneid,
26219 				    MBLK_GETLABEL(mp), ipst);
26220 			}
26221 		}
26222 		if (ire != NULL) {
26223 			goto send;
26224 		}
26225 
26226 		/*
26227 		 * ire disappeared underneath.
26228 		 *
26229 		 * What we need to do here is the ip_newroute
26230 		 * logic to get the ire without doing the IPSEC
26231 		 * processing. Follow the same old path. But this
26232 		 * time, ip_wput or ire_add_then_put will call us
26233 		 * directly as all the IPSEC operations are done.
26234 		 */
26235 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26236 		mp->b_prev = NULL;
26237 		mp->b_next = NULL;
26238 
26239 		/*
26240 		 * If the IPsec packet was processed asynchronously,
26241 		 * drop it now.
26242 		 */
26243 		if (q == NULL) {
26244 			freemsg(ipsec_mp);
26245 			goto done;
26246 		}
26247 
26248 		/*
26249 		 * Since we're going through ip_newroute() again, we
26250 		 * need to make sure we don't:
26251 		 *
26252 		 *	1.) Trigger the ASSERT() with the ipha_ident
26253 		 *	    overloading.
26254 		 *	2.) Redo transport-layer checksumming, since we've
26255 		 *	    already done all that to get this far.
26256 		 *
26257 		 * The easiest way not do either of the above is to set
26258 		 * the ipha_ident field to IP_HDR_INCLUDED.
26259 		 */
26260 		ipha->ipha_ident = IP_HDR_INCLUDED;
26261 		ip_newroute(q, ipsec_mp, dst, NULL,
26262 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26263 	}
26264 	goto done;
26265 send:
26266 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26267 	    udp_compute_checksum(ipst->ips_netstack)) {
26268 		/*
26269 		 * ESP NAT-Traversal packet.
26270 		 *
26271 		 * Just do software checksum for now.
26272 		 */
26273 
26274 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26275 		IP_STAT(ipst, ip_out_sw_cksum);
26276 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26277 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26278 #define	iphs	((uint16_t *)ipha)
26279 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26280 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26281 		    IP_SIMPLE_HDR_LENGTH);
26282 #undef iphs
26283 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
26284 			cksum = 0xFFFF;
26285 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26286 			if (mp1->b_wptr - mp1->b_rptr >=
26287 			    offset + sizeof (uint16_t)) {
26288 				up = (uint16_t *)(mp1->b_rptr + offset);
26289 				*up = cksum;
26290 				break;	/* out of for loop */
26291 			} else {
26292 				offset -= (mp->b_wptr - mp->b_rptr);
26293 			}
26294 	} /* Otherwise, just keep the all-zero checksum. */
26295 
26296 	if (ire->ire_stq == NULL) {
26297 		ill_t	*out_ill;
26298 		/*
26299 		 * Loopbacks go through ip_wput_local except for one case.
26300 		 * We come here if we generate a icmp_frag_needed message
26301 		 * after IPSEC processing is over. When this function calls
26302 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26303 		 * icmp_frag_needed. The message generated comes back here
26304 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26305 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26306 		 * source address as it is usually set in ip_wput_ire. As
26307 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26308 		 * and we end up here. We can't enter ip_wput_ire once the
26309 		 * IPSEC processing is over and hence we need to do it here.
26310 		 */
26311 		ASSERT(q != NULL);
26312 		UPDATE_OB_PKT_COUNT(ire);
26313 		ire->ire_last_used_time = lbolt;
26314 		if (ipha->ipha_src == 0)
26315 			ipha->ipha_src = ire->ire_src_addr;
26316 
26317 		/* PFHooks: LOOPBACK_OUT */
26318 		out_ill = ire->ire_ipif->ipif_ill;
26319 
26320 		DTRACE_PROBE4(ip4__loopback__out__start,
26321 		    ill_t *, NULL, ill_t *, out_ill,
26322 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26323 
26324 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26325 		    ipst->ips_ipv4firewall_loopback_out,
26326 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26327 
26328 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26329 
26330 		if (ipsec_mp != NULL)
26331 			ip_wput_local(RD(q), out_ill,
26332 			    ipha, ipsec_mp, ire, 0, zoneid);
26333 		if (ire_need_rele)
26334 			ire_refrele(ire);
26335 		goto done;
26336 	}
26337 
26338 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26339 		/*
26340 		 * We are through with IPSEC processing.
26341 		 * Fragment this and send it on the wire.
26342 		 */
26343 		if (io->ipsec_out_accelerated) {
26344 			/*
26345 			 * The packet has been accelerated but must
26346 			 * be fragmented. This should not happen
26347 			 * since AH and ESP must not accelerate
26348 			 * packets that need fragmentation, however
26349 			 * the configuration could have changed
26350 			 * since the AH or ESP processing.
26351 			 * Drop packet.
26352 			 * IPsec KSTATS: bump bean counter here.
26353 			 */
26354 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26355 			    "fragmented accelerated packet!\n"));
26356 			freemsg(ipsec_mp);
26357 		} else {
26358 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26359 		}
26360 		if (ire_need_rele)
26361 			ire_refrele(ire);
26362 		goto done;
26363 	}
26364 
26365 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26366 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26367 	    (void *)ire->ire_ipif, (void *)ipif));
26368 
26369 	/*
26370 	 * Multiroute the secured packet, unless IPsec really
26371 	 * requires the packet to go out only through a particular
26372 	 * interface.
26373 	 */
26374 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26375 		ire_t *first_ire;
26376 		irb = ire->ire_bucket;
26377 		ASSERT(irb != NULL);
26378 		/*
26379 		 * This ire has been looked up as the one that
26380 		 * goes through the given ipif;
26381 		 * make sure we do not omit any other multiroute ire
26382 		 * that may be present in the bucket before this one.
26383 		 */
26384 		IRB_REFHOLD(irb);
26385 		for (first_ire = irb->irb_ire;
26386 		    first_ire != NULL;
26387 		    first_ire = first_ire->ire_next) {
26388 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26389 			    (first_ire->ire_addr == ire->ire_addr) &&
26390 			    !(first_ire->ire_marks &
26391 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
26392 				break;
26393 		}
26394 
26395 		if ((first_ire != NULL) && (first_ire != ire)) {
26396 			/*
26397 			 * Don't change the ire if the packet must
26398 			 * be fragmented if sent via this new one.
26399 			 */
26400 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26401 				IRE_REFHOLD(first_ire);
26402 				if (ire_need_rele)
26403 					ire_refrele(ire);
26404 				else
26405 					ire_need_rele = B_TRUE;
26406 				ire = first_ire;
26407 			}
26408 		}
26409 		IRB_REFRELE(irb);
26410 
26411 		multirt_send = B_TRUE;
26412 		max_frag = ire->ire_max_frag;
26413 	} else {
26414 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26415 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26416 			    "flag, attach_if %d\n", attach_if));
26417 		}
26418 	}
26419 
26420 	/*
26421 	 * In most cases, the emission loop below is entered only once.
26422 	 * Only in the case where the ire holds the RTF_MULTIRT
26423 	 * flag, we loop to process all RTF_MULTIRT ires in the
26424 	 * bucket, and send the packet through all crossed
26425 	 * RTF_MULTIRT routes.
26426 	 */
26427 	do {
26428 		if (multirt_send) {
26429 			/*
26430 			 * ire1 holds here the next ire to process in the
26431 			 * bucket. If multirouting is expected,
26432 			 * any non-RTF_MULTIRT ire that has the
26433 			 * right destination address is ignored.
26434 			 */
26435 			ASSERT(irb != NULL);
26436 			IRB_REFHOLD(irb);
26437 			for (ire1 = ire->ire_next;
26438 			    ire1 != NULL;
26439 			    ire1 = ire1->ire_next) {
26440 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26441 					continue;
26442 				if (ire1->ire_addr != ire->ire_addr)
26443 					continue;
26444 				if (ire1->ire_marks &
26445 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26446 					continue;
26447 				/* No loopback here */
26448 				if (ire1->ire_stq == NULL)
26449 					continue;
26450 				/*
26451 				 * Ensure we do not exceed the MTU
26452 				 * of the next route.
26453 				 */
26454 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26455 					ip_multirt_bad_mtu(ire1, max_frag);
26456 					continue;
26457 				}
26458 
26459 				IRE_REFHOLD(ire1);
26460 				break;
26461 			}
26462 			IRB_REFRELE(irb);
26463 			if (ire1 != NULL) {
26464 				/*
26465 				 * We are in a multiple send case, need to
26466 				 * make a copy of the packet.
26467 				 */
26468 				next_mp = copymsg(ipsec_mp);
26469 				if (next_mp == NULL) {
26470 					ire_refrele(ire1);
26471 					ire1 = NULL;
26472 				}
26473 			}
26474 		}
26475 		/*
26476 		 * Everything is done. Send it out on the wire
26477 		 *
26478 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26479 		 * either send it on the wire or, in the case of
26480 		 * HW acceleration, call ipsec_hw_putnext.
26481 		 */
26482 		if (ire->ire_nce &&
26483 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26484 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26485 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26486 			/*
26487 			 * If ire's link-layer is unresolved (this
26488 			 * would only happen if the incomplete ire
26489 			 * was added to cachetable via forwarding path)
26490 			 * don't bother going to ip_xmit_v4. Just drop the
26491 			 * packet.
26492 			 * There is a slight risk here, in that, if we
26493 			 * have the forwarding path create an incomplete
26494 			 * IRE, then until the IRE is completed, any
26495 			 * transmitted IPSEC packets will be dropped
26496 			 * instead of being queued waiting for resolution.
26497 			 *
26498 			 * But the likelihood of a forwarding packet and a wput
26499 			 * packet sending to the same dst at the same time
26500 			 * and there not yet be an ARP entry for it is small.
26501 			 * Furthermore, if this actually happens, it might
26502 			 * be likely that wput would generate multiple
26503 			 * packets (and forwarding would also have a train
26504 			 * of packets) for that destination. If this is
26505 			 * the case, some of them would have been dropped
26506 			 * anyway, since ARP only queues a few packets while
26507 			 * waiting for resolution
26508 			 *
26509 			 * NOTE: We should really call ip_xmit_v4,
26510 			 * and let it queue the packet and send the
26511 			 * ARP query and have ARP come back thus:
26512 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26513 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26514 			 * hw accel work. But it's too complex to get
26515 			 * the IPsec hw  acceleration approach to fit
26516 			 * well with ip_xmit_v4 doing ARP without
26517 			 * doing IPSEC simplification. For now, we just
26518 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26519 			 * that we can continue with the send on the next
26520 			 * attempt.
26521 			 *
26522 			 * XXX THis should be revisited, when
26523 			 * the IPsec/IP interaction is cleaned up
26524 			 */
26525 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26526 			    " - dropping packet\n"));
26527 			freemsg(ipsec_mp);
26528 			/*
26529 			 * Call ip_xmit_v4() to trigger ARP query
26530 			 * in case the nce_state is ND_INITIAL
26531 			 */
26532 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26533 			goto drop_pkt;
26534 		}
26535 
26536 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26537 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26538 		    mblk_t *, mp);
26539 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26540 		    ipst->ips_ipv4firewall_physical_out,
26541 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp, ipst);
26542 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
26543 		if (mp == NULL)
26544 			goto drop_pkt;
26545 
26546 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26547 		pktxmit_state = ip_xmit_v4(mp, ire,
26548 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26549 
26550 		if ((pktxmit_state ==  SEND_FAILED) ||
26551 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26552 
26553 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26554 drop_pkt:
26555 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26556 			    ipIfStatsOutDiscards);
26557 			if (ire_need_rele)
26558 				ire_refrele(ire);
26559 			if (ire1 != NULL) {
26560 				ire_refrele(ire1);
26561 				freemsg(next_mp);
26562 			}
26563 			goto done;
26564 		}
26565 
26566 		freeb(ipsec_mp);
26567 		if (ire_need_rele)
26568 			ire_refrele(ire);
26569 
26570 		if (ire1 != NULL) {
26571 			ire = ire1;
26572 			ire_need_rele = B_TRUE;
26573 			ASSERT(next_mp);
26574 			ipsec_mp = next_mp;
26575 			mp = ipsec_mp->b_cont;
26576 			ire1 = NULL;
26577 			next_mp = NULL;
26578 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26579 		} else {
26580 			multirt_send = B_FALSE;
26581 		}
26582 	} while (multirt_send);
26583 done:
26584 	if (ill != NULL && ill_need_rele)
26585 		ill_refrele(ill);
26586 	if (ipif != NULL)
26587 		ipif_refrele(ipif);
26588 }
26589 
26590 /*
26591  * Get the ill corresponding to the specified ire, and compare its
26592  * capabilities with the protocol and algorithms specified by the
26593  * the SA obtained from ipsec_out. If they match, annotate the
26594  * ipsec_out structure to indicate that the packet needs acceleration.
26595  *
26596  *
26597  * A packet is eligible for outbound hardware acceleration if the
26598  * following conditions are satisfied:
26599  *
26600  * 1. the packet will not be fragmented
26601  * 2. the provider supports the algorithm
26602  * 3. there is no pending control message being exchanged
26603  * 4. snoop is not attached
26604  * 5. the destination address is not a broadcast or multicast address.
26605  *
26606  * Rationale:
26607  *	- Hardware drivers do not support fragmentation with
26608  *	  the current interface.
26609  *	- snoop, multicast, and broadcast may result in exposure of
26610  *	  a cleartext datagram.
26611  * We check all five of these conditions here.
26612  *
26613  * XXX would like to nuke "ire_t *" parameter here; problem is that
26614  * IRE is only way to figure out if a v4 address is a broadcast and
26615  * thus ineligible for acceleration...
26616  */
26617 static void
26618 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26619 {
26620 	ipsec_out_t *io;
26621 	mblk_t *data_mp;
26622 	uint_t plen, overhead;
26623 	ip_stack_t	*ipst;
26624 
26625 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26626 		return;
26627 
26628 	if (ill == NULL)
26629 		return;
26630 	ipst = ill->ill_ipst;
26631 	/*
26632 	 * Destination address is a broadcast or multicast.  Punt.
26633 	 */
26634 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26635 	    IRE_LOCAL)))
26636 		return;
26637 
26638 	data_mp = ipsec_mp->b_cont;
26639 
26640 	if (ill->ill_isv6) {
26641 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26642 
26643 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26644 			return;
26645 
26646 		plen = ip6h->ip6_plen;
26647 	} else {
26648 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26649 
26650 		if (CLASSD(ipha->ipha_dst))
26651 			return;
26652 
26653 		plen = ipha->ipha_length;
26654 	}
26655 	/*
26656 	 * Is there a pending DLPI control message being exchanged
26657 	 * between IP/IPsec and the DLS Provider? If there is, it
26658 	 * could be a SADB update, and the state of the DLS Provider
26659 	 * SADB might not be in sync with the SADB maintained by
26660 	 * IPsec. To avoid dropping packets or using the wrong keying
26661 	 * material, we do not accelerate this packet.
26662 	 */
26663 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26664 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26665 		    "ill_dlpi_pending! don't accelerate packet\n"));
26666 		return;
26667 	}
26668 
26669 	/*
26670 	 * Is the Provider in promiscous mode? If it does, we don't
26671 	 * accelerate the packet since it will bounce back up to the
26672 	 * listeners in the clear.
26673 	 */
26674 	if (ill->ill_promisc_on_phys) {
26675 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26676 		    "ill in promiscous mode, don't accelerate packet\n"));
26677 		return;
26678 	}
26679 
26680 	/*
26681 	 * Will the packet require fragmentation?
26682 	 */
26683 
26684 	/*
26685 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26686 	 * as is used elsewhere.
26687 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26688 	 *	+ 2-byte trailer
26689 	 */
26690 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26691 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26692 
26693 	if ((plen + overhead) > ill->ill_max_mtu)
26694 		return;
26695 
26696 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26697 
26698 	/*
26699 	 * Can the ill accelerate this IPsec protocol and algorithm
26700 	 * specified by the SA?
26701 	 */
26702 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26703 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26704 		return;
26705 	}
26706 
26707 	/*
26708 	 * Tell AH or ESP that the outbound ill is capable of
26709 	 * accelerating this packet.
26710 	 */
26711 	io->ipsec_out_is_capab_ill = B_TRUE;
26712 }
26713 
26714 /*
26715  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26716  *
26717  * If this function returns B_TRUE, the requested SA's have been filled
26718  * into the ipsec_out_*_sa pointers.
26719  *
26720  * If the function returns B_FALSE, the packet has been "consumed", most
26721  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26722  *
26723  * The SA references created by the protocol-specific "select"
26724  * function will be released when the ipsec_mp is freed, thanks to the
26725  * ipsec_out_free destructor -- see spd.c.
26726  */
26727 static boolean_t
26728 ipsec_out_select_sa(mblk_t *ipsec_mp)
26729 {
26730 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26731 	ipsec_out_t *io;
26732 	ipsec_policy_t *pp;
26733 	ipsec_action_t *ap;
26734 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26735 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26736 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26737 
26738 	if (!io->ipsec_out_secure) {
26739 		/*
26740 		 * We came here by mistake.
26741 		 * Don't bother with ipsec processing
26742 		 * We should "discourage" this path in the future.
26743 		 */
26744 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26745 		return (B_FALSE);
26746 	}
26747 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26748 	ASSERT((io->ipsec_out_policy != NULL) ||
26749 	    (io->ipsec_out_act != NULL));
26750 
26751 	ASSERT(io->ipsec_out_failed == B_FALSE);
26752 
26753 	/*
26754 	 * IPSEC processing has started.
26755 	 */
26756 	io->ipsec_out_proc_begin = B_TRUE;
26757 	ap = io->ipsec_out_act;
26758 	if (ap == NULL) {
26759 		pp = io->ipsec_out_policy;
26760 		ASSERT(pp != NULL);
26761 		ap = pp->ipsp_act;
26762 		ASSERT(ap != NULL);
26763 	}
26764 
26765 	/*
26766 	 * We have an action.  now, let's select SA's.
26767 	 * (In the future, we can cache this in the conn_t..)
26768 	 */
26769 	if (ap->ipa_want_esp) {
26770 		if (io->ipsec_out_esp_sa == NULL) {
26771 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26772 			    IPPROTO_ESP);
26773 		}
26774 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26775 	}
26776 
26777 	if (ap->ipa_want_ah) {
26778 		if (io->ipsec_out_ah_sa == NULL) {
26779 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26780 			    IPPROTO_AH);
26781 		}
26782 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26783 		/*
26784 		 * The ESP and AH processing order needs to be preserved
26785 		 * when both protocols are required (ESP should be applied
26786 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26787 		 * when both ESP and AH are required, and an AH ACQUIRE
26788 		 * is needed.
26789 		 */
26790 		if (ap->ipa_want_esp && need_ah_acquire)
26791 			need_esp_acquire = B_TRUE;
26792 	}
26793 
26794 	/*
26795 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26796 	 * Release SAs that got referenced, but will not be used until we
26797 	 * acquire _all_ of the SAs we need.
26798 	 */
26799 	if (need_ah_acquire || need_esp_acquire) {
26800 		if (io->ipsec_out_ah_sa != NULL) {
26801 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26802 			io->ipsec_out_ah_sa = NULL;
26803 		}
26804 		if (io->ipsec_out_esp_sa != NULL) {
26805 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26806 			io->ipsec_out_esp_sa = NULL;
26807 		}
26808 
26809 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26810 		return (B_FALSE);
26811 	}
26812 
26813 	return (B_TRUE);
26814 }
26815 
26816 /*
26817  * Process an IPSEC_OUT message and see what you can
26818  * do with it.
26819  * IPQoS Notes:
26820  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26821  * IPSec.
26822  * XXX would like to nuke ire_t.
26823  * XXX ill_index better be "real"
26824  */
26825 void
26826 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26827 {
26828 	ipsec_out_t *io;
26829 	ipsec_policy_t *pp;
26830 	ipsec_action_t *ap;
26831 	ipha_t *ipha;
26832 	ip6_t *ip6h;
26833 	mblk_t *mp;
26834 	ill_t *ill;
26835 	zoneid_t zoneid;
26836 	ipsec_status_t ipsec_rc;
26837 	boolean_t ill_need_rele = B_FALSE;
26838 	ip_stack_t	*ipst;
26839 	ipsec_stack_t	*ipss;
26840 
26841 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26842 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26843 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26844 	ipst = io->ipsec_out_ns->netstack_ip;
26845 	mp = ipsec_mp->b_cont;
26846 
26847 	/*
26848 	 * Initiate IPPF processing. We do it here to account for packets
26849 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26850 	 * We can check for ipsec_out_proc_begin even for such packets, as
26851 	 * they will always be false (asserted below).
26852 	 */
26853 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26854 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26855 		    io->ipsec_out_ill_index : ill_index);
26856 		if (mp == NULL) {
26857 			ip2dbg(("ipsec_out_process: packet dropped "\
26858 			    "during IPPF processing\n"));
26859 			freeb(ipsec_mp);
26860 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26861 			return;
26862 		}
26863 	}
26864 
26865 	if (!io->ipsec_out_secure) {
26866 		/*
26867 		 * We came here by mistake.
26868 		 * Don't bother with ipsec processing
26869 		 * Should "discourage" this path in the future.
26870 		 */
26871 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26872 		goto done;
26873 	}
26874 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26875 	ASSERT((io->ipsec_out_policy != NULL) ||
26876 	    (io->ipsec_out_act != NULL));
26877 	ASSERT(io->ipsec_out_failed == B_FALSE);
26878 
26879 	ipss = ipst->ips_netstack->netstack_ipsec;
26880 	if (!ipsec_loaded(ipss)) {
26881 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26882 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26883 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26884 		} else {
26885 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26886 		}
26887 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26888 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26889 		    &ipss->ipsec_dropper);
26890 		return;
26891 	}
26892 
26893 	/*
26894 	 * IPSEC processing has started.
26895 	 */
26896 	io->ipsec_out_proc_begin = B_TRUE;
26897 	ap = io->ipsec_out_act;
26898 	if (ap == NULL) {
26899 		pp = io->ipsec_out_policy;
26900 		ASSERT(pp != NULL);
26901 		ap = pp->ipsp_act;
26902 		ASSERT(ap != NULL);
26903 	}
26904 
26905 	/*
26906 	 * Save the outbound ill index. When the packet comes back
26907 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26908 	 * before sending it the accelerated packet.
26909 	 */
26910 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26911 		int ifindex;
26912 		ill = ire_to_ill(ire);
26913 		ifindex = ill->ill_phyint->phyint_ifindex;
26914 		io->ipsec_out_capab_ill_index = ifindex;
26915 	}
26916 
26917 	/*
26918 	 * The order of processing is first insert a IP header if needed.
26919 	 * Then insert the ESP header and then the AH header.
26920 	 */
26921 	if ((io->ipsec_out_se_done == B_FALSE) &&
26922 	    (ap->ipa_want_se)) {
26923 		/*
26924 		 * First get the outer IP header before sending
26925 		 * it to ESP.
26926 		 */
26927 		ipha_t *oipha, *iipha;
26928 		mblk_t *outer_mp, *inner_mp;
26929 
26930 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26931 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26932 			    "ipsec_out_process: "
26933 			    "Self-Encapsulation failed: Out of memory\n");
26934 			freemsg(ipsec_mp);
26935 			if (ill != NULL) {
26936 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26937 			} else {
26938 				BUMP_MIB(&ipst->ips_ip_mib,
26939 				    ipIfStatsOutDiscards);
26940 			}
26941 			return;
26942 		}
26943 		inner_mp = ipsec_mp->b_cont;
26944 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26945 		oipha = (ipha_t *)outer_mp->b_rptr;
26946 		iipha = (ipha_t *)inner_mp->b_rptr;
26947 		*oipha = *iipha;
26948 		outer_mp->b_wptr += sizeof (ipha_t);
26949 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26950 		    sizeof (ipha_t));
26951 		oipha->ipha_protocol = IPPROTO_ENCAP;
26952 		oipha->ipha_version_and_hdr_length =
26953 		    IP_SIMPLE_HDR_VERSION;
26954 		oipha->ipha_hdr_checksum = 0;
26955 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26956 		outer_mp->b_cont = inner_mp;
26957 		ipsec_mp->b_cont = outer_mp;
26958 
26959 		io->ipsec_out_se_done = B_TRUE;
26960 		io->ipsec_out_tunnel = B_TRUE;
26961 	}
26962 
26963 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26964 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26965 	    !ipsec_out_select_sa(ipsec_mp))
26966 		return;
26967 
26968 	/*
26969 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26970 	 * to do the heavy lifting.
26971 	 */
26972 	zoneid = io->ipsec_out_zoneid;
26973 	ASSERT(zoneid != ALL_ZONES);
26974 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26975 		ASSERT(io->ipsec_out_esp_sa != NULL);
26976 		io->ipsec_out_esp_done = B_TRUE;
26977 		/*
26978 		 * Note that since hw accel can only apply one transform,
26979 		 * not two, we skip hw accel for ESP if we also have AH
26980 		 * This is an design limitation of the interface
26981 		 * which should be revisited.
26982 		 */
26983 		ASSERT(ire != NULL);
26984 		if (io->ipsec_out_ah_sa == NULL) {
26985 			ill = (ill_t *)ire->ire_stq->q_ptr;
26986 			ipsec_out_is_accelerated(ipsec_mp,
26987 			    io->ipsec_out_esp_sa, ill, ire);
26988 		}
26989 
26990 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26991 		switch (ipsec_rc) {
26992 		case IPSEC_STATUS_SUCCESS:
26993 			break;
26994 		case IPSEC_STATUS_FAILED:
26995 			if (ill != NULL) {
26996 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26997 			} else {
26998 				BUMP_MIB(&ipst->ips_ip_mib,
26999 				    ipIfStatsOutDiscards);
27000 			}
27001 			/* FALLTHRU */
27002 		case IPSEC_STATUS_PENDING:
27003 			return;
27004 		}
27005 	}
27006 
27007 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27008 		ASSERT(io->ipsec_out_ah_sa != NULL);
27009 		io->ipsec_out_ah_done = B_TRUE;
27010 		if (ire == NULL) {
27011 			int idx = io->ipsec_out_capab_ill_index;
27012 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27013 			    NULL, NULL, NULL, NULL, ipst);
27014 			ill_need_rele = B_TRUE;
27015 		} else {
27016 			ill = (ill_t *)ire->ire_stq->q_ptr;
27017 		}
27018 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27019 		    ire);
27020 
27021 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27022 		switch (ipsec_rc) {
27023 		case IPSEC_STATUS_SUCCESS:
27024 			break;
27025 		case IPSEC_STATUS_FAILED:
27026 			if (ill != NULL) {
27027 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27028 			} else {
27029 				BUMP_MIB(&ipst->ips_ip_mib,
27030 				    ipIfStatsOutDiscards);
27031 			}
27032 			/* FALLTHRU */
27033 		case IPSEC_STATUS_PENDING:
27034 			if (ill != NULL && ill_need_rele)
27035 				ill_refrele(ill);
27036 			return;
27037 		}
27038 	}
27039 	/*
27040 	 * We are done with IPSEC processing. Send it over
27041 	 * the wire.
27042 	 */
27043 done:
27044 	mp = ipsec_mp->b_cont;
27045 	ipha = (ipha_t *)mp->b_rptr;
27046 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27047 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27048 	} else {
27049 		ip6h = (ip6_t *)ipha;
27050 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27051 	}
27052 	if (ill != NULL && ill_need_rele)
27053 		ill_refrele(ill);
27054 }
27055 
27056 /* ARGSUSED */
27057 void
27058 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27059 {
27060 	opt_restart_t	*or;
27061 	int	err;
27062 	conn_t	*connp;
27063 
27064 	ASSERT(CONN_Q(q));
27065 	connp = Q_TO_CONN(q);
27066 
27067 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27068 	or = (opt_restart_t *)first_mp->b_rptr;
27069 	/*
27070 	 * We don't need to pass any credentials here since this is just
27071 	 * a restart. The credentials are passed in when svr4_optcom_req
27072 	 * is called the first time (from ip_wput_nondata).
27073 	 */
27074 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27075 		err = svr4_optcom_req(q, first_mp, NULL,
27076 		    &ip_opt_obj);
27077 	} else {
27078 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27079 		err = tpi_optcom_req(q, first_mp, NULL,
27080 		    &ip_opt_obj);
27081 	}
27082 	if (err != EINPROGRESS) {
27083 		/* operation is done */
27084 		CONN_OPER_PENDING_DONE(connp);
27085 	}
27086 }
27087 
27088 /*
27089  * ioctls that go through a down/up sequence may need to wait for the down
27090  * to complete. This involves waiting for the ire and ipif refcnts to go down
27091  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27092  */
27093 /* ARGSUSED */
27094 void
27095 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27096 {
27097 	struct iocblk *iocp;
27098 	mblk_t *mp1;
27099 	ip_ioctl_cmd_t *ipip;
27100 	int err;
27101 	sin_t	*sin;
27102 	struct lifreq *lifr;
27103 	struct ifreq *ifr;
27104 
27105 	iocp = (struct iocblk *)mp->b_rptr;
27106 	ASSERT(ipsq != NULL);
27107 	/* Existence of mp1 verified in ip_wput_nondata */
27108 	mp1 = mp->b_cont->b_cont;
27109 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27110 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27111 		/*
27112 		 * Special case where ipsq_current_ipif is not set:
27113 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27114 		 * ill could also have become part of a ipmp group in the
27115 		 * process, we are here as were not able to complete the
27116 		 * operation in ipif_set_values because we could not become
27117 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27118 		 * will not be set so we need to set it.
27119 		 */
27120 		ill_t *ill = q->q_ptr;
27121 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27122 	}
27123 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27124 
27125 	if (ipip->ipi_cmd_type == IF_CMD) {
27126 		/* This a old style SIOC[GS]IF* command */
27127 		ifr = (struct ifreq *)mp1->b_rptr;
27128 		sin = (sin_t *)&ifr->ifr_addr;
27129 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27130 		/* This a new style SIOC[GS]LIF* command */
27131 		lifr = (struct lifreq *)mp1->b_rptr;
27132 		sin = (sin_t *)&lifr->lifr_addr;
27133 	} else {
27134 		sin = NULL;
27135 	}
27136 
27137 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27138 	    ipip, mp1->b_rptr);
27139 
27140 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27141 }
27142 
27143 /*
27144  * ioctl processing
27145  *
27146  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27147  * the ioctl command in the ioctl tables and determines the copyin data size
27148  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27149  * size.
27150  *
27151  * ioctl processing then continues when the M_IOCDATA makes its way down.
27152  * Now the ioctl is looked up again in the ioctl table, and its properties are
27153  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27154  * and the general ioctl processing function ip_process_ioctl is called.
27155  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27156  * so goes thru the serialization primitive ipsq_try_enter. Then the
27157  * appropriate function to handle the ioctl is called based on the entry in
27158  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27159  * which also refreleases the 'conn' that was refheld at the start of the
27160  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27161  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27162  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27163  *
27164  * Many exclusive ioctls go thru an internal down up sequence as part of
27165  * the operation. For example an attempt to change the IP address of an
27166  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27167  * does all the cleanup such as deleting all ires that use this address.
27168  * Then we need to wait till all references to the interface go away.
27169  */
27170 void
27171 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27172 {
27173 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27174 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27175 	cmd_info_t ci;
27176 	int err;
27177 	boolean_t entered_ipsq = B_FALSE;
27178 
27179 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27180 
27181 	if (ipip == NULL)
27182 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27183 
27184 	/*
27185 	 * SIOCLIFADDIF needs to go thru a special path since the
27186 	 * ill may not exist yet. This happens in the case of lo0
27187 	 * which is created using this ioctl.
27188 	 */
27189 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27190 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27191 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27192 		return;
27193 	}
27194 
27195 	ci.ci_ipif = NULL;
27196 	switch (ipip->ipi_cmd_type) {
27197 	case IF_CMD:
27198 	case LIF_CMD:
27199 		/*
27200 		 * ioctls that pass in a [l]ifreq appear here.
27201 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27202 		 * ci.ci_ipif
27203 		 */
27204 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27205 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27206 		if (err != 0) {
27207 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27208 			return;
27209 		}
27210 		ASSERT(ci.ci_ipif != NULL);
27211 		break;
27212 
27213 	case TUN_CMD:
27214 		/*
27215 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27216 		 * a refheld ipif in ci.ci_ipif
27217 		 */
27218 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27219 		if (err != 0) {
27220 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27221 			return;
27222 		}
27223 		ASSERT(ci.ci_ipif != NULL);
27224 		break;
27225 
27226 	case MISC_CMD:
27227 		/*
27228 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27229 		 * For eg. SIOCGLIFCONF will appear here.
27230 		 */
27231 		switch (ipip->ipi_cmd) {
27232 		case IF_UNITSEL:
27233 			/* ioctl comes down the ill */
27234 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27235 			ipif_refhold(ci.ci_ipif);
27236 			break;
27237 		case SIOCGMSFILTER:
27238 		case SIOCSMSFILTER:
27239 		case SIOCGIPMSFILTER:
27240 		case SIOCSIPMSFILTER:
27241 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27242 			    ip_process_ioctl);
27243 			if (err != 0) {
27244 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27245 				    NULL);
27246 			}
27247 			break;
27248 		}
27249 		err = 0;
27250 		ci.ci_sin = NULL;
27251 		ci.ci_sin6 = NULL;
27252 		ci.ci_lifr = NULL;
27253 		break;
27254 	}
27255 
27256 	/*
27257 	 * If ipsq is non-null, we are already being called exclusively
27258 	 */
27259 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27260 	if (!(ipip->ipi_flags & IPI_WR)) {
27261 		/*
27262 		 * A return value of EINPROGRESS means the ioctl is
27263 		 * either queued and waiting for some reason or has
27264 		 * already completed.
27265 		 */
27266 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27267 		    ci.ci_lifr);
27268 		if (ci.ci_ipif != NULL)
27269 			ipif_refrele(ci.ci_ipif);
27270 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27271 		return;
27272 	}
27273 
27274 	ASSERT(ci.ci_ipif != NULL);
27275 
27276 	if (ipsq == NULL) {
27277 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27278 		    ip_process_ioctl, NEW_OP, B_TRUE);
27279 		entered_ipsq = B_TRUE;
27280 	}
27281 	/*
27282 	 * Release the ipif so that ipif_down and friends that wait for
27283 	 * references to go away are not misled about the current ipif_refcnt
27284 	 * values. We are writer so we can access the ipif even after releasing
27285 	 * the ipif.
27286 	 */
27287 	ipif_refrele(ci.ci_ipif);
27288 	if (ipsq == NULL)
27289 		return;
27290 
27291 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27292 
27293 	/*
27294 	 * For most set ioctls that come here, this serves as a single point
27295 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27296 	 * be any new references to the ipif. This helps functions that go
27297 	 * through this path and end up trying to wait for the refcnts
27298 	 * associated with the ipif to go down to zero. Some exceptions are
27299 	 * Failover, Failback, and Groupname commands that operate on more than
27300 	 * just the ci.ci_ipif. These commands internally determine the
27301 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27302 	 * flags on that set. Another exception is the Removeif command that
27303 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27304 	 * ipif to operate on.
27305 	 */
27306 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27307 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27308 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27309 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27310 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27311 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27312 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27313 
27314 	/*
27315 	 * A return value of EINPROGRESS means the ioctl is
27316 	 * either queued and waiting for some reason or has
27317 	 * already completed.
27318 	 */
27319 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27320 
27321 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27322 
27323 	if (entered_ipsq)
27324 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27325 }
27326 
27327 /*
27328  * Complete the ioctl. Typically ioctls use the mi package and need to
27329  * do mi_copyout/mi_copy_done.
27330  */
27331 void
27332 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27333 {
27334 	conn_t	*connp = NULL;
27335 
27336 	if (err == EINPROGRESS)
27337 		return;
27338 
27339 	if (CONN_Q(q)) {
27340 		connp = Q_TO_CONN(q);
27341 		ASSERT(connp->conn_ref >= 2);
27342 	}
27343 
27344 	switch (mode) {
27345 	case COPYOUT:
27346 		if (err == 0)
27347 			mi_copyout(q, mp);
27348 		else
27349 			mi_copy_done(q, mp, err);
27350 		break;
27351 
27352 	case NO_COPYOUT:
27353 		mi_copy_done(q, mp, err);
27354 		break;
27355 
27356 	default:
27357 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27358 		break;
27359 	}
27360 
27361 	/*
27362 	 * The refhold placed at the start of the ioctl is released here.
27363 	 */
27364 	if (connp != NULL)
27365 		CONN_OPER_PENDING_DONE(connp);
27366 
27367 	if (ipsq != NULL)
27368 		ipsq_current_finish(ipsq);
27369 }
27370 
27371 /*
27372  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27373  */
27374 /* ARGSUSED */
27375 void
27376 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27377 {
27378 	conn_t *connp = arg;
27379 	tcp_t	*tcp;
27380 
27381 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27382 	tcp = connp->conn_tcp;
27383 
27384 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27385 		freemsg(mp);
27386 	else
27387 		tcp_rput_other(tcp, mp);
27388 	CONN_OPER_PENDING_DONE(connp);
27389 }
27390 
27391 /* Called from ip_wput for all non data messages */
27392 /* ARGSUSED */
27393 void
27394 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27395 {
27396 	mblk_t		*mp1;
27397 	ire_t		*ire, *fake_ire;
27398 	ill_t		*ill;
27399 	struct iocblk	*iocp;
27400 	ip_ioctl_cmd_t	*ipip;
27401 	cred_t		*cr;
27402 	conn_t		*connp;
27403 	int		cmd, err;
27404 	nce_t		*nce;
27405 	ipif_t		*ipif;
27406 	ip_stack_t	*ipst;
27407 	char		*proto_str;
27408 
27409 	if (CONN_Q(q)) {
27410 		connp = Q_TO_CONN(q);
27411 		ipst = connp->conn_netstack->netstack_ip;
27412 	} else {
27413 		connp = NULL;
27414 		ipst = ILLQ_TO_IPST(q);
27415 	}
27416 
27417 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27418 
27419 	/* Check if it is a queue to /dev/sctp. */
27420 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27421 	    connp->conn_rq == NULL) {
27422 		sctp_wput(q, mp);
27423 		return;
27424 	}
27425 
27426 	switch (DB_TYPE(mp)) {
27427 	case M_IOCTL:
27428 		/*
27429 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27430 		 * will arrange to copy in associated control structures.
27431 		 */
27432 		ip_sioctl_copyin_setup(q, mp);
27433 		return;
27434 	case M_IOCDATA:
27435 		/*
27436 		 * Ensure that this is associated with one of our trans-
27437 		 * parent ioctls.  If it's not ours, discard it if we're
27438 		 * running as a driver, or pass it on if we're a module.
27439 		 */
27440 		iocp = (struct iocblk *)mp->b_rptr;
27441 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27442 		if (ipip == NULL) {
27443 			if (q->q_next == NULL) {
27444 				goto nak;
27445 			} else {
27446 				putnext(q, mp);
27447 			}
27448 			return;
27449 		} else if ((q->q_next != NULL) &&
27450 		    !(ipip->ipi_flags & IPI_MODOK)) {
27451 			/*
27452 			 * the ioctl is one we recognise, but is not
27453 			 * consumed by IP as a module, pass M_IOCDATA
27454 			 * for processing downstream, but only for
27455 			 * common Streams ioctls.
27456 			 */
27457 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27458 				putnext(q, mp);
27459 				return;
27460 			} else {
27461 				goto nak;
27462 			}
27463 		}
27464 
27465 		/* IOCTL continuation following copyin or copyout. */
27466 		if (mi_copy_state(q, mp, NULL) == -1) {
27467 			/*
27468 			 * The copy operation failed.  mi_copy_state already
27469 			 * cleaned up, so we're out of here.
27470 			 */
27471 			return;
27472 		}
27473 		/*
27474 		 * If we just completed a copy in, we become writer and
27475 		 * continue processing in ip_sioctl_copyin_done.  If it
27476 		 * was a copy out, we call mi_copyout again.  If there is
27477 		 * nothing more to copy out, it will complete the IOCTL.
27478 		 */
27479 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27480 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27481 				mi_copy_done(q, mp, EPROTO);
27482 				return;
27483 			}
27484 			/*
27485 			 * Check for cases that need more copying.  A return
27486 			 * value of 0 means a second copyin has been started,
27487 			 * so we return; a return value of 1 means no more
27488 			 * copying is needed, so we continue.
27489 			 */
27490 			cmd = iocp->ioc_cmd;
27491 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27492 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27493 			    MI_COPY_COUNT(mp) == 1) {
27494 				if (ip_copyin_msfilter(q, mp) == 0)
27495 					return;
27496 			}
27497 			/*
27498 			 * Refhold the conn, till the ioctl completes. This is
27499 			 * needed in case the ioctl ends up in the pending mp
27500 			 * list. Every mp in the ill_pending_mp list and
27501 			 * the ipsq_pending_mp must have a refhold on the conn
27502 			 * to resume processing. The refhold is released when
27503 			 * the ioctl completes. (normally or abnormally)
27504 			 * In all cases ip_ioctl_finish is called to finish
27505 			 * the ioctl.
27506 			 */
27507 			if (connp != NULL) {
27508 				/* This is not a reentry */
27509 				ASSERT(ipsq == NULL);
27510 				CONN_INC_REF(connp);
27511 			} else {
27512 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27513 					mi_copy_done(q, mp, EINVAL);
27514 					return;
27515 				}
27516 			}
27517 
27518 			ip_process_ioctl(ipsq, q, mp, ipip);
27519 
27520 		} else {
27521 			mi_copyout(q, mp);
27522 		}
27523 		return;
27524 nak:
27525 		iocp->ioc_error = EINVAL;
27526 		mp->b_datap->db_type = M_IOCNAK;
27527 		iocp->ioc_count = 0;
27528 		qreply(q, mp);
27529 		return;
27530 
27531 	case M_IOCNAK:
27532 		/*
27533 		 * The only way we could get here is if a resolver didn't like
27534 		 * an IOCTL we sent it.	 This shouldn't happen.
27535 		 */
27536 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27537 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27538 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27539 		freemsg(mp);
27540 		return;
27541 	case M_IOCACK:
27542 		/* /dev/ip shouldn't see this */
27543 		if (CONN_Q(q))
27544 			goto nak;
27545 
27546 		/* Finish socket ioctls passed through to ARP. */
27547 		ip_sioctl_iocack(q, mp);
27548 		return;
27549 	case M_FLUSH:
27550 		if (*mp->b_rptr & FLUSHW)
27551 			flushq(q, FLUSHALL);
27552 		if (q->q_next) {
27553 			/*
27554 			 * M_FLUSH is sent up to IP by some drivers during
27555 			 * unbind. ip_rput has already replied to it. We are
27556 			 * here for the M_FLUSH that we originated in IP
27557 			 * before sending the unbind request to the driver.
27558 			 * Just free it as we don't queue packets in IP
27559 			 * on the write side of the device instance.
27560 			 */
27561 			freemsg(mp);
27562 			return;
27563 		}
27564 		if (*mp->b_rptr & FLUSHR) {
27565 			*mp->b_rptr &= ~FLUSHW;
27566 			qreply(q, mp);
27567 			return;
27568 		}
27569 		freemsg(mp);
27570 		return;
27571 	case IRE_DB_REQ_TYPE:
27572 		if (connp == NULL) {
27573 			proto_str = "IRE_DB_REQ_TYPE";
27574 			goto protonak;
27575 		}
27576 		/* An Upper Level Protocol wants a copy of an IRE. */
27577 		ip_ire_req(q, mp);
27578 		return;
27579 	case M_CTL:
27580 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27581 			break;
27582 
27583 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27584 		    TUN_HELLO) {
27585 			ASSERT(connp != NULL);
27586 			connp->conn_flags |= IPCL_IPTUN;
27587 			freeb(mp);
27588 			return;
27589 		}
27590 
27591 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27592 		    IP_ULP_OUT_LABELED) {
27593 			out_labeled_t *olp;
27594 
27595 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27596 				break;
27597 			olp = (out_labeled_t *)mp->b_rptr;
27598 			connp->conn_ulp_labeled = olp->out_qnext == q;
27599 			freemsg(mp);
27600 			return;
27601 		}
27602 
27603 		/* M_CTL messages are used by ARP to tell us things. */
27604 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27605 			break;
27606 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27607 		case AR_ENTRY_SQUERY:
27608 			ip_wput_ctl(q, mp);
27609 			return;
27610 		case AR_CLIENT_NOTIFY:
27611 			ip_arp_news(q, mp);
27612 			return;
27613 		case AR_DLPIOP_DONE:
27614 			ASSERT(q->q_next != NULL);
27615 			ill = (ill_t *)q->q_ptr;
27616 			/* qwriter_ip releases the refhold */
27617 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27618 			ill_refhold(ill);
27619 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
27620 			    CUR_OP, B_FALSE);
27621 			return;
27622 		case AR_ARP_CLOSING:
27623 			/*
27624 			 * ARP (above us) is closing. If no ARP bringup is
27625 			 * currently pending, ack the message so that ARP
27626 			 * can complete its close. Also mark ill_arp_closing
27627 			 * so that new ARP bringups will fail. If any
27628 			 * ARP bringup is currently in progress, we will
27629 			 * ack this when the current ARP bringup completes.
27630 			 */
27631 			ASSERT(q->q_next != NULL);
27632 			ill = (ill_t *)q->q_ptr;
27633 			mutex_enter(&ill->ill_lock);
27634 			ill->ill_arp_closing = 1;
27635 			if (!ill->ill_arp_bringup_pending) {
27636 				mutex_exit(&ill->ill_lock);
27637 				qreply(q, mp);
27638 			} else {
27639 				mutex_exit(&ill->ill_lock);
27640 				freemsg(mp);
27641 			}
27642 			return;
27643 		case AR_ARP_EXTEND:
27644 			/*
27645 			 * The ARP module above us is capable of duplicate
27646 			 * address detection.  Old ATM drivers will not send
27647 			 * this message.
27648 			 */
27649 			ASSERT(q->q_next != NULL);
27650 			ill = (ill_t *)q->q_ptr;
27651 			ill->ill_arp_extend = B_TRUE;
27652 			freemsg(mp);
27653 			return;
27654 		default:
27655 			break;
27656 		}
27657 		break;
27658 	case M_PROTO:
27659 	case M_PCPROTO:
27660 		/*
27661 		 * The only PROTO messages we expect are ULP binds and
27662 		 * copies of option negotiation acknowledgements.
27663 		 */
27664 		switch (((union T_primitives *)mp->b_rptr)->type) {
27665 		case O_T_BIND_REQ:
27666 		case T_BIND_REQ: {
27667 			/* Request can get queued in bind */
27668 			if (connp == NULL) {
27669 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27670 				goto protonak;
27671 			}
27672 			/*
27673 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27674 			 * instead of going through this path.  We only get
27675 			 * here in the following cases:
27676 			 *
27677 			 * a. Bind retries, where ipsq is non-NULL.
27678 			 * b. T_BIND_REQ is issued from non TCP/UDP
27679 			 *    transport, e.g. icmp for raw socket,
27680 			 *    in which case ipsq will be NULL.
27681 			 */
27682 			ASSERT(ipsq != NULL ||
27683 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27684 
27685 			/* Don't increment refcnt if this is a re-entry */
27686 			if (ipsq == NULL)
27687 				CONN_INC_REF(connp);
27688 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27689 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27690 			if (mp == NULL)
27691 				return;
27692 			if (IPCL_IS_TCP(connp)) {
27693 				/*
27694 				 * In the case of TCP endpoint we
27695 				 * come here only for bind retries
27696 				 */
27697 				ASSERT(ipsq != NULL);
27698 				CONN_INC_REF(connp);
27699 				squeue_fill(connp->conn_sqp, mp,
27700 				    ip_resume_tcp_bind, connp,
27701 				    SQTAG_BIND_RETRY);
27702 				return;
27703 			} else if (IPCL_IS_UDP(connp)) {
27704 				/*
27705 				 * In the case of UDP endpoint we
27706 				 * come here only for bind retries
27707 				 */
27708 				ASSERT(ipsq != NULL);
27709 				udp_resume_bind(connp, mp);
27710 				return;
27711 			}
27712 			qreply(q, mp);
27713 			CONN_OPER_PENDING_DONE(connp);
27714 			return;
27715 		}
27716 		case T_SVR4_OPTMGMT_REQ:
27717 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27718 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27719 
27720 			if (connp == NULL) {
27721 				proto_str = "T_SVR4_OPTMGMT_REQ";
27722 				goto protonak;
27723 			}
27724 
27725 			if (!snmpcom_req(q, mp, ip_snmp_set,
27726 			    ip_snmp_get, cr)) {
27727 				/*
27728 				 * Call svr4_optcom_req so that it can
27729 				 * generate the ack. We don't come here
27730 				 * if this operation is being restarted.
27731 				 * ip_restart_optmgmt will drop the conn ref.
27732 				 * In the case of ipsec option after the ipsec
27733 				 * load is complete conn_restart_ipsec_waiter
27734 				 * drops the conn ref.
27735 				 */
27736 				ASSERT(ipsq == NULL);
27737 				CONN_INC_REF(connp);
27738 				if (ip_check_for_ipsec_opt(q, mp))
27739 					return;
27740 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27741 				if (err != EINPROGRESS) {
27742 					/* Operation is done */
27743 					CONN_OPER_PENDING_DONE(connp);
27744 				}
27745 			}
27746 			return;
27747 		case T_OPTMGMT_REQ:
27748 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27749 			/*
27750 			 * Note: No snmpcom_req support through new
27751 			 * T_OPTMGMT_REQ.
27752 			 * Call tpi_optcom_req so that it can
27753 			 * generate the ack.
27754 			 */
27755 			if (connp == NULL) {
27756 				proto_str = "T_OPTMGMT_REQ";
27757 				goto protonak;
27758 			}
27759 
27760 			ASSERT(ipsq == NULL);
27761 			/*
27762 			 * We don't come here for restart. ip_restart_optmgmt
27763 			 * will drop the conn ref. In the case of ipsec option
27764 			 * after the ipsec load is complete
27765 			 * conn_restart_ipsec_waiter drops the conn ref.
27766 			 */
27767 			CONN_INC_REF(connp);
27768 			if (ip_check_for_ipsec_opt(q, mp))
27769 				return;
27770 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27771 			if (err != EINPROGRESS) {
27772 				/* Operation is done */
27773 				CONN_OPER_PENDING_DONE(connp);
27774 			}
27775 			return;
27776 		case T_UNBIND_REQ:
27777 			if (connp == NULL) {
27778 				proto_str = "T_UNBIND_REQ";
27779 				goto protonak;
27780 			}
27781 			mp = ip_unbind(q, mp);
27782 			qreply(q, mp);
27783 			return;
27784 		default:
27785 			/*
27786 			 * Have to drop any DLPI messages coming down from
27787 			 * arp (such as an info_req which would cause ip
27788 			 * to receive an extra info_ack if it was passed
27789 			 * through.
27790 			 */
27791 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27792 			    (int)*(uint_t *)mp->b_rptr));
27793 			freemsg(mp);
27794 			return;
27795 		}
27796 		/* NOTREACHED */
27797 	case IRE_DB_TYPE: {
27798 		nce_t		*nce;
27799 		ill_t		*ill;
27800 		in6_addr_t	gw_addr_v6;
27801 
27802 
27803 		/*
27804 		 * This is a response back from a resolver.  It
27805 		 * consists of a message chain containing:
27806 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27807 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27808 		 * The LL_HDR_MBLK is the DLPI header to use to get
27809 		 * the attached packet, and subsequent ones for the
27810 		 * same destination, transmitted.
27811 		 */
27812 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27813 			break;
27814 		/*
27815 		 * First, check to make sure the resolution succeeded.
27816 		 * If it failed, the second mblk will be empty.
27817 		 * If it is, free the chain, dropping the packet.
27818 		 * (We must ire_delete the ire; that frees the ire mblk)
27819 		 * We're doing this now to support PVCs for ATM; it's
27820 		 * a partial xresolv implementation. When we fully implement
27821 		 * xresolv interfaces, instead of freeing everything here
27822 		 * we'll initiate neighbor discovery.
27823 		 *
27824 		 * For v4 (ARP and other external resolvers) the resolver
27825 		 * frees the message, so no check is needed. This check
27826 		 * is required, though, for a full xresolve implementation.
27827 		 * Including this code here now both shows how external
27828 		 * resolvers can NACK a resolution request using an
27829 		 * existing design that has no specific provisions for NACKs,
27830 		 * and also takes into account that the current non-ARP
27831 		 * external resolver has been coded to use this method of
27832 		 * NACKing for all IPv6 (xresolv) cases,
27833 		 * whether our xresolv implementation is complete or not.
27834 		 *
27835 		 */
27836 		ire = (ire_t *)mp->b_rptr;
27837 		ill = ire_to_ill(ire);
27838 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27839 		if (mp1->b_rptr == mp1->b_wptr) {
27840 			if (ire->ire_ipversion == IPV6_VERSION) {
27841 				/*
27842 				 * XRESOLV interface.
27843 				 */
27844 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27845 				mutex_enter(&ire->ire_lock);
27846 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27847 				mutex_exit(&ire->ire_lock);
27848 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27849 					nce = ndp_lookup_v6(ill,
27850 					    &ire->ire_addr_v6, B_FALSE);
27851 				} else {
27852 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27853 					    B_FALSE);
27854 				}
27855 				if (nce != NULL) {
27856 					nce_resolv_failed(nce);
27857 					ndp_delete(nce);
27858 					NCE_REFRELE(nce);
27859 				}
27860 			}
27861 			mp->b_cont = NULL;
27862 			freemsg(mp1);		/* frees the pkt as well */
27863 			ASSERT(ire->ire_nce == NULL);
27864 			ire_delete((ire_t *)mp->b_rptr);
27865 			return;
27866 		}
27867 
27868 		/*
27869 		 * Split them into IRE_MBLK and pkt and feed it into
27870 		 * ire_add_then_send. Then in ire_add_then_send
27871 		 * the IRE will be added, and then the packet will be
27872 		 * run back through ip_wput. This time it will make
27873 		 * it to the wire.
27874 		 */
27875 		mp->b_cont = NULL;
27876 		mp = mp1->b_cont;		/* now, mp points to pkt */
27877 		mp1->b_cont = NULL;
27878 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27879 		if (ire->ire_ipversion == IPV6_VERSION) {
27880 			/*
27881 			 * XRESOLV interface. Find the nce and put a copy
27882 			 * of the dl_unitdata_req in nce_res_mp
27883 			 */
27884 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27885 			mutex_enter(&ire->ire_lock);
27886 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27887 			mutex_exit(&ire->ire_lock);
27888 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27889 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27890 				    B_FALSE);
27891 			} else {
27892 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27893 			}
27894 			if (nce != NULL) {
27895 				/*
27896 				 * We have to protect nce_res_mp here
27897 				 * from being accessed by other threads
27898 				 * while we change the mblk pointer.
27899 				 * Other functions will also lock the nce when
27900 				 * accessing nce_res_mp.
27901 				 *
27902 				 * The reason we change the mblk pointer
27903 				 * here rather than copying the resolved address
27904 				 * into the template is that, unlike with
27905 				 * ethernet, we have no guarantee that the
27906 				 * resolved address length will be
27907 				 * smaller than or equal to the lla length
27908 				 * with which the template was allocated,
27909 				 * (for ethernet, they're equal)
27910 				 * so we have to use the actual resolved
27911 				 * address mblk - which holds the real
27912 				 * dl_unitdata_req with the resolved address.
27913 				 *
27914 				 * Doing this is the same behavior as was
27915 				 * previously used in the v4 ARP case.
27916 				 */
27917 				mutex_enter(&nce->nce_lock);
27918 				if (nce->nce_res_mp != NULL)
27919 					freemsg(nce->nce_res_mp);
27920 				nce->nce_res_mp = mp1;
27921 				mutex_exit(&nce->nce_lock);
27922 				/*
27923 				 * We do a fastpath probe here because
27924 				 * we have resolved the address without
27925 				 * using Neighbor Discovery.
27926 				 * In the non-XRESOLV v6 case, the fastpath
27927 				 * probe is done right after neighbor
27928 				 * discovery completes.
27929 				 */
27930 				if (nce->nce_res_mp != NULL) {
27931 					int res;
27932 					nce_fastpath_list_add(nce);
27933 					res = ill_fastpath_probe(ill,
27934 					    nce->nce_res_mp);
27935 					if (res != 0 && res != EAGAIN)
27936 						nce_fastpath_list_delete(nce);
27937 				}
27938 
27939 				ire_add_then_send(q, ire, mp);
27940 				/*
27941 				 * Now we have to clean out any packets
27942 				 * that may have been queued on the nce
27943 				 * while it was waiting for address resolution
27944 				 * to complete.
27945 				 */
27946 				mutex_enter(&nce->nce_lock);
27947 				mp1 = nce->nce_qd_mp;
27948 				nce->nce_qd_mp = NULL;
27949 				mutex_exit(&nce->nce_lock);
27950 				while (mp1 != NULL) {
27951 					mblk_t *nxt_mp;
27952 					queue_t *fwdq = NULL;
27953 					ill_t   *inbound_ill;
27954 					uint_t ifindex;
27955 
27956 					nxt_mp = mp1->b_next;
27957 					mp1->b_next = NULL;
27958 					/*
27959 					 * Retrieve ifindex stored in
27960 					 * ip_rput_data_v6()
27961 					 */
27962 					ifindex =
27963 					    (uint_t)(uintptr_t)mp1->b_prev;
27964 					inbound_ill =
27965 						ill_lookup_on_ifindex(ifindex,
27966 						    B_TRUE, NULL, NULL, NULL,
27967 						    NULL, ipst);
27968 					mp1->b_prev = NULL;
27969 					if (inbound_ill != NULL)
27970 						fwdq = inbound_ill->ill_rq;
27971 
27972 					if (fwdq != NULL) {
27973 						put(fwdq, mp1);
27974 						ill_refrele(inbound_ill);
27975 					} else
27976 						put(WR(ill->ill_rq), mp1);
27977 					mp1 = nxt_mp;
27978 				}
27979 				NCE_REFRELE(nce);
27980 			} else {	/* nce is NULL; clean up */
27981 				ire_delete(ire);
27982 				freemsg(mp);
27983 				freemsg(mp1);
27984 				return;
27985 			}
27986 		} else {
27987 			nce_t *arpce;
27988 			/*
27989 			 * Link layer resolution succeeded. Recompute the
27990 			 * ire_nce.
27991 			 */
27992 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27993 			if ((arpce = ndp_lookup_v4(ill,
27994 			    (ire->ire_gateway_addr != INADDR_ANY ?
27995 			    &ire->ire_gateway_addr : &ire->ire_addr),
27996 			    B_FALSE)) == NULL) {
27997 				freeb(ire->ire_mp);
27998 				freeb(mp1);
27999 				freemsg(mp);
28000 				return;
28001 			}
28002 			mutex_enter(&arpce->nce_lock);
28003 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
28004 			if (arpce->nce_state == ND_REACHABLE) {
28005 				/*
28006 				 * Someone resolved this before us;
28007 				 * cleanup the res_mp. Since ire has
28008 				 * not been added yet, the call to ire_add_v4
28009 				 * from ire_add_then_send (when a dup is
28010 				 * detected) will clean up the ire.
28011 				 */
28012 				freeb(mp1);
28013 			} else {
28014 				if (arpce->nce_res_mp != NULL)
28015 					freemsg(arpce->nce_res_mp);
28016 				arpce->nce_res_mp = mp1;
28017 				arpce->nce_state = ND_REACHABLE;
28018 			}
28019 			mutex_exit(&arpce->nce_lock);
28020 			if (ire->ire_marks & IRE_MARK_NOADD) {
28021 				/*
28022 				 * this ire will not be added to the ire
28023 				 * cache table, so we can set the ire_nce
28024 				 * here, as there are no atomicity constraints.
28025 				 */
28026 				ire->ire_nce = arpce;
28027 				/*
28028 				 * We are associating this nce with the ire
28029 				 * so change the nce ref taken in
28030 				 * ndp_lookup_v4() from
28031 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28032 				 */
28033 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28034 			} else {
28035 				NCE_REFRELE(arpce);
28036 			}
28037 			ire_add_then_send(q, ire, mp);
28038 		}
28039 		return;	/* All is well, the packet has been sent. */
28040 	}
28041 	case IRE_ARPRESOLVE_TYPE: {
28042 
28043 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28044 			break;
28045 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28046 		mp->b_cont = NULL;
28047 		/*
28048 		 * First, check to make sure the resolution succeeded.
28049 		 * If it failed, the second mblk will be empty.
28050 		 */
28051 		if (mp1->b_rptr == mp1->b_wptr) {
28052 			/* cleanup  the incomplete ire, free queued packets */
28053 			freemsg(mp); /* fake ire */
28054 			freeb(mp1);  /* dl_unitdata response */
28055 			return;
28056 		}
28057 
28058 		/*
28059 		 * update any incomplete nce_t found. we lookup the ctable
28060 		 * and find the nce from the ire->ire_nce because we need
28061 		 * to pass the ire to ip_xmit_v4 later, and can find both
28062 		 * ire and nce in one lookup from the ctable.
28063 		 */
28064 		fake_ire = (ire_t *)mp->b_rptr;
28065 		/*
28066 		 * By the time we come back here from ARP
28067 		 * the logical outgoing interface  of the incomplete ire
28068 		 * we added in ire_forward could have disappeared,
28069 		 * causing the incomplete ire to also have
28070 		 * dissapeared. So we need to retreive the
28071 		 * proper ipif for the ire  before looking
28072 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28073 		 */
28074 		ill = q->q_ptr;
28075 
28076 		/* Get the outgoing ipif */
28077 		mutex_enter(&ill->ill_lock);
28078 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28079 			mutex_exit(&ill->ill_lock);
28080 			freemsg(mp); /* fake ire */
28081 			freeb(mp1);  /* dl_unitdata response */
28082 			return;
28083 		}
28084 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28085 
28086 		if (ipif == NULL) {
28087 			mutex_exit(&ill->ill_lock);
28088 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28089 			freemsg(mp);
28090 			freeb(mp1);
28091 			return;
28092 		}
28093 		ipif_refhold_locked(ipif);
28094 		mutex_exit(&ill->ill_lock);
28095 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28096 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28097 		    ipif, fake_ire->ire_zoneid, NULL,
28098 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28099 		ipif_refrele(ipif);
28100 		if (ire == NULL) {
28101 			/*
28102 			 * no ire was found; check if there is an nce
28103 			 * for this lookup; if it has no ire's pointing at it
28104 			 * cleanup.
28105 			 */
28106 			if ((nce = ndp_lookup_v4(ill,
28107 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28108 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28109 			    B_FALSE)) != NULL) {
28110 				/*
28111 				 * cleanup:
28112 				 * We check for refcnt 2 (one for the nce
28113 				 * hash list + 1 for the ref taken by
28114 				 * ndp_lookup_v4) to check that there are
28115 				 * no ire's pointing at the nce.
28116 				 */
28117 				if (nce->nce_refcnt == 2)
28118 					ndp_delete(nce);
28119 				NCE_REFRELE(nce);
28120 			}
28121 			freeb(mp1);  /* dl_unitdata response */
28122 			freemsg(mp); /* fake ire */
28123 			return;
28124 		}
28125 		nce = ire->ire_nce;
28126 		DTRACE_PROBE2(ire__arpresolve__type,
28127 		    ire_t *, ire, nce_t *, nce);
28128 		ASSERT(nce->nce_state != ND_INITIAL);
28129 		mutex_enter(&nce->nce_lock);
28130 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28131 		if (nce->nce_state == ND_REACHABLE) {
28132 			/*
28133 			 * Someone resolved this before us;
28134 			 * our response is not needed any more.
28135 			 */
28136 			mutex_exit(&nce->nce_lock);
28137 			freeb(mp1);  /* dl_unitdata response */
28138 		} else {
28139 			if (nce->nce_res_mp != NULL) {
28140 				freemsg(nce->nce_res_mp);
28141 				/* existing dl_unitdata template */
28142 			}
28143 			nce->nce_res_mp = mp1;
28144 			nce->nce_state = ND_REACHABLE;
28145 			mutex_exit(&nce->nce_lock);
28146 			nce_fastpath(nce);
28147 		}
28148 		/*
28149 		 * The cached nce_t has been updated to be reachable;
28150 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
28151 		 */
28152 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28153 		freemsg(mp);
28154 		/*
28155 		 * send out queued packets.
28156 		 */
28157 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28158 
28159 		IRE_REFRELE(ire);
28160 		return;
28161 	}
28162 	default:
28163 		break;
28164 	}
28165 	if (q->q_next) {
28166 		putnext(q, mp);
28167 	} else
28168 		freemsg(mp);
28169 	return;
28170 
28171 protonak:
28172 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28173 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28174 		qreply(q, mp);
28175 }
28176 
28177 /*
28178  * Process IP options in an outbound packet.  Modify the destination if there
28179  * is a source route option.
28180  * Returns non-zero if something fails in which case an ICMP error has been
28181  * sent and mp freed.
28182  */
28183 static int
28184 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28185     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28186 {
28187 	ipoptp_t	opts;
28188 	uchar_t		*opt;
28189 	uint8_t		optval;
28190 	uint8_t		optlen;
28191 	ipaddr_t	dst;
28192 	intptr_t	code = 0;
28193 	mblk_t		*mp;
28194 	ire_t		*ire = NULL;
28195 
28196 	ip2dbg(("ip_wput_options\n"));
28197 	mp = ipsec_mp;
28198 	if (mctl_present) {
28199 		mp = ipsec_mp->b_cont;
28200 	}
28201 
28202 	dst = ipha->ipha_dst;
28203 	for (optval = ipoptp_first(&opts, ipha);
28204 	    optval != IPOPT_EOL;
28205 	    optval = ipoptp_next(&opts)) {
28206 		opt = opts.ipoptp_cur;
28207 		optlen = opts.ipoptp_len;
28208 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28209 		    optval, optlen));
28210 		switch (optval) {
28211 			uint32_t off;
28212 		case IPOPT_SSRR:
28213 		case IPOPT_LSRR:
28214 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28215 				ip1dbg((
28216 				    "ip_wput_options: bad option offset\n"));
28217 				code = (char *)&opt[IPOPT_OLEN] -
28218 				    (char *)ipha;
28219 				goto param_prob;
28220 			}
28221 			off = opt[IPOPT_OFFSET];
28222 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28223 			    ntohl(dst)));
28224 			/*
28225 			 * For strict: verify that dst is directly
28226 			 * reachable.
28227 			 */
28228 			if (optval == IPOPT_SSRR) {
28229 				ire = ire_ftable_lookup(dst, 0, 0,
28230 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28231 				    MBLK_GETLABEL(mp),
28232 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28233 				if (ire == NULL) {
28234 					ip1dbg(("ip_wput_options: SSRR not"
28235 					    " directly reachable: 0x%x\n",
28236 					    ntohl(dst)));
28237 					goto bad_src_route;
28238 				}
28239 				ire_refrele(ire);
28240 			}
28241 			break;
28242 		case IPOPT_RR:
28243 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28244 				ip1dbg((
28245 				    "ip_wput_options: bad option offset\n"));
28246 				code = (char *)&opt[IPOPT_OLEN] -
28247 				    (char *)ipha;
28248 				goto param_prob;
28249 			}
28250 			break;
28251 		case IPOPT_TS:
28252 			/*
28253 			 * Verify that length >=5 and that there is either
28254 			 * room for another timestamp or that the overflow
28255 			 * counter is not maxed out.
28256 			 */
28257 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28258 			if (optlen < IPOPT_MINLEN_IT) {
28259 				goto param_prob;
28260 			}
28261 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28262 				ip1dbg((
28263 				    "ip_wput_options: bad option offset\n"));
28264 				code = (char *)&opt[IPOPT_OFFSET] -
28265 				    (char *)ipha;
28266 				goto param_prob;
28267 			}
28268 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28269 			case IPOPT_TS_TSONLY:
28270 				off = IPOPT_TS_TIMELEN;
28271 				break;
28272 			case IPOPT_TS_TSANDADDR:
28273 			case IPOPT_TS_PRESPEC:
28274 			case IPOPT_TS_PRESPEC_RFC791:
28275 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28276 				break;
28277 			default:
28278 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28279 				    (char *)ipha;
28280 				goto param_prob;
28281 			}
28282 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28283 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28284 				/*
28285 				 * No room and the overflow counter is 15
28286 				 * already.
28287 				 */
28288 				goto param_prob;
28289 			}
28290 			break;
28291 		}
28292 	}
28293 
28294 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28295 		return (0);
28296 
28297 	ip1dbg(("ip_wput_options: error processing IP options."));
28298 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28299 
28300 param_prob:
28301 	/*
28302 	 * Since ip_wput() isn't close to finished, we fill
28303 	 * in enough of the header for credible error reporting.
28304 	 */
28305 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28306 		/* Failed */
28307 		freemsg(ipsec_mp);
28308 		return (-1);
28309 	}
28310 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28311 	return (-1);
28312 
28313 bad_src_route:
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_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28324 	return (-1);
28325 }
28326 
28327 /*
28328  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28329  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28330  * thru /etc/system.
28331  */
28332 #define	CONN_MAXDRAINCNT	64
28333 
28334 static void
28335 conn_drain_init(ip_stack_t *ipst)
28336 {
28337 	int i;
28338 
28339 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28340 
28341 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28342 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28343 		/*
28344 		 * Default value of the number of drainers is the
28345 		 * number of cpus, subject to maximum of 8 drainers.
28346 		 */
28347 		if (boot_max_ncpus != -1)
28348 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28349 		else
28350 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28351 	}
28352 
28353 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28354 	    sizeof (idl_t), KM_SLEEP);
28355 
28356 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28357 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28358 		    MUTEX_DEFAULT, NULL);
28359 	}
28360 }
28361 
28362 static void
28363 conn_drain_fini(ip_stack_t *ipst)
28364 {
28365 	int i;
28366 
28367 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28368 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28369 	kmem_free(ipst->ips_conn_drain_list,
28370 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28371 	ipst->ips_conn_drain_list = NULL;
28372 }
28373 
28374 /*
28375  * Note: For an overview of how flowcontrol is handled in IP please see the
28376  * IP Flowcontrol notes at the top of this file.
28377  *
28378  * Flow control has blocked us from proceeding. Insert the given conn in one
28379  * of the conn drain lists. These conn wq's will be qenabled later on when
28380  * STREAMS flow control does a backenable. conn_walk_drain will enable
28381  * the first conn in each of these drain lists. Each of these qenabled conns
28382  * in turn enables the next in the list, after it runs, or when it closes,
28383  * thus sustaining the drain process.
28384  *
28385  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28386  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28387  * running at any time, on a given conn, since there can be only 1 service proc
28388  * running on a queue at any time.
28389  */
28390 void
28391 conn_drain_insert(conn_t *connp)
28392 {
28393 	idl_t	*idl;
28394 	uint_t	index;
28395 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28396 
28397 	mutex_enter(&connp->conn_lock);
28398 	if (connp->conn_state_flags & CONN_CLOSING) {
28399 		/*
28400 		 * The conn is closing as a result of which CONN_CLOSING
28401 		 * is set. Return.
28402 		 */
28403 		mutex_exit(&connp->conn_lock);
28404 		return;
28405 	} else if (connp->conn_idl == NULL) {
28406 		/*
28407 		 * Assign the next drain list round robin. We dont' use
28408 		 * a lock, and thus it may not be strictly round robin.
28409 		 * Atomicity of load/stores is enough to make sure that
28410 		 * conn_drain_list_index is always within bounds.
28411 		 */
28412 		index = ipst->ips_conn_drain_list_index;
28413 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28414 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28415 		index++;
28416 		if (index == ipst->ips_conn_drain_list_cnt)
28417 			index = 0;
28418 		ipst->ips_conn_drain_list_index = index;
28419 	}
28420 	mutex_exit(&connp->conn_lock);
28421 
28422 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28423 	if ((connp->conn_drain_prev != NULL) ||
28424 	    (connp->conn_state_flags & CONN_CLOSING)) {
28425 		/*
28426 		 * The conn is already in the drain list, OR
28427 		 * the conn is closing. We need to check again for
28428 		 * the closing case again since close can happen
28429 		 * after we drop the conn_lock, and before we
28430 		 * acquire the CONN_DRAIN_LIST_LOCK.
28431 		 */
28432 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28433 		return;
28434 	} else {
28435 		idl = connp->conn_idl;
28436 	}
28437 
28438 	/*
28439 	 * The conn is not in the drain list. Insert it at the
28440 	 * tail of the drain list. The drain list is circular
28441 	 * and doubly linked. idl_conn points to the 1st element
28442 	 * in the list.
28443 	 */
28444 	if (idl->idl_conn == NULL) {
28445 		idl->idl_conn = connp;
28446 		connp->conn_drain_next = connp;
28447 		connp->conn_drain_prev = connp;
28448 	} else {
28449 		conn_t *head = idl->idl_conn;
28450 
28451 		connp->conn_drain_next = head;
28452 		connp->conn_drain_prev = head->conn_drain_prev;
28453 		head->conn_drain_prev->conn_drain_next = connp;
28454 		head->conn_drain_prev = connp;
28455 	}
28456 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28457 }
28458 
28459 /*
28460  * This conn is closing, and we are called from ip_close. OR
28461  * This conn has been serviced by ip_wsrv, and we need to do the tail
28462  * processing.
28463  * If this conn is part of the drain list, we may need to sustain the drain
28464  * process by qenabling the next conn in the drain list. We may also need to
28465  * remove this conn from the list, if it is done.
28466  */
28467 static void
28468 conn_drain_tail(conn_t *connp, boolean_t closing)
28469 {
28470 	idl_t *idl;
28471 
28472 	/*
28473 	 * connp->conn_idl is stable at this point, and no lock is needed
28474 	 * to check it. If we are called from ip_close, close has already
28475 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28476 	 * called us only because conn_idl is non-null. If we are called thru
28477 	 * service, conn_idl could be null, but it cannot change because
28478 	 * service is single-threaded per queue, and there cannot be another
28479 	 * instance of service trying to call conn_drain_insert on this conn
28480 	 * now.
28481 	 */
28482 	ASSERT(!closing || (connp->conn_idl != NULL));
28483 
28484 	/*
28485 	 * If connp->conn_idl is null, the conn has not been inserted into any
28486 	 * drain list even once since creation of the conn. Just return.
28487 	 */
28488 	if (connp->conn_idl == NULL)
28489 		return;
28490 
28491 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28492 
28493 	if (connp->conn_drain_prev == NULL) {
28494 		/* This conn is currently not in the drain list.  */
28495 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28496 		return;
28497 	}
28498 	idl = connp->conn_idl;
28499 	if (idl->idl_conn_draining == connp) {
28500 		/*
28501 		 * This conn is the current drainer. If this is the last conn
28502 		 * in the drain list, we need to do more checks, in the 'if'
28503 		 * below. Otherwwise we need to just qenable the next conn,
28504 		 * to sustain the draining, and is handled in the 'else'
28505 		 * below.
28506 		 */
28507 		if (connp->conn_drain_next == idl->idl_conn) {
28508 			/*
28509 			 * This conn is the last in this list. This round
28510 			 * of draining is complete. If idl_repeat is set,
28511 			 * it means another flow enabling has happened from
28512 			 * the driver/streams and we need to another round
28513 			 * of draining.
28514 			 * If there are more than 2 conns in the drain list,
28515 			 * do a left rotate by 1, so that all conns except the
28516 			 * conn at the head move towards the head by 1, and the
28517 			 * the conn at the head goes to the tail. This attempts
28518 			 * a more even share for all queues that are being
28519 			 * drained.
28520 			 */
28521 			if ((connp->conn_drain_next != connp) &&
28522 			    (idl->idl_conn->conn_drain_next != connp)) {
28523 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28524 			}
28525 			if (idl->idl_repeat) {
28526 				qenable(idl->idl_conn->conn_wq);
28527 				idl->idl_conn_draining = idl->idl_conn;
28528 				idl->idl_repeat = 0;
28529 			} else {
28530 				idl->idl_conn_draining = NULL;
28531 			}
28532 		} else {
28533 			/*
28534 			 * If the next queue that we are now qenable'ing,
28535 			 * is closing, it will remove itself from this list
28536 			 * and qenable the subsequent queue in ip_close().
28537 			 * Serialization is acheived thru idl_lock.
28538 			 */
28539 			qenable(connp->conn_drain_next->conn_wq);
28540 			idl->idl_conn_draining = connp->conn_drain_next;
28541 		}
28542 	}
28543 	if (!connp->conn_did_putbq || closing) {
28544 		/*
28545 		 * Remove ourself from the drain list, if we did not do
28546 		 * a putbq, or if the conn is closing.
28547 		 * Note: It is possible that q->q_first is non-null. It means
28548 		 * that these messages landed after we did a enableok() in
28549 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28550 		 * service them.
28551 		 */
28552 		if (connp->conn_drain_next == connp) {
28553 			/* Singleton in the list */
28554 			ASSERT(connp->conn_drain_prev == connp);
28555 			idl->idl_conn = NULL;
28556 			idl->idl_conn_draining = NULL;
28557 		} else {
28558 			connp->conn_drain_prev->conn_drain_next =
28559 			    connp->conn_drain_next;
28560 			connp->conn_drain_next->conn_drain_prev =
28561 			    connp->conn_drain_prev;
28562 			if (idl->idl_conn == connp)
28563 				idl->idl_conn = connp->conn_drain_next;
28564 			ASSERT(idl->idl_conn_draining != connp);
28565 
28566 		}
28567 		connp->conn_drain_next = NULL;
28568 		connp->conn_drain_prev = NULL;
28569 	}
28570 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28571 }
28572 
28573 /*
28574  * Write service routine. Shared perimeter entry point.
28575  * ip_wsrv can be called in any of the following ways.
28576  * 1. The device queue's messages has fallen below the low water mark
28577  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28578  *    the drain lists and backenable the first conn in each list.
28579  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28580  *    qenabled non-tcp upper layers. We start dequeing messages and call
28581  *    ip_wput for each message.
28582  */
28583 
28584 void
28585 ip_wsrv(queue_t *q)
28586 {
28587 	conn_t	*connp;
28588 	ill_t	*ill;
28589 	mblk_t	*mp;
28590 
28591 	if (q->q_next) {
28592 		ill = (ill_t *)q->q_ptr;
28593 		if (ill->ill_state_flags == 0) {
28594 			/*
28595 			 * The device flow control has opened up.
28596 			 * Walk through conn drain lists and qenable the
28597 			 * first conn in each list. This makes sense only
28598 			 * if the stream is fully plumbed and setup.
28599 			 * Hence the if check above.
28600 			 */
28601 			ip1dbg(("ip_wsrv: walking\n"));
28602 			conn_walk_drain(ill->ill_ipst);
28603 		}
28604 		return;
28605 	}
28606 
28607 	connp = Q_TO_CONN(q);
28608 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28609 
28610 	/*
28611 	 * 1. Set conn_draining flag to signal that service is active.
28612 	 *
28613 	 * 2. ip_output determines whether it has been called from service,
28614 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28615 	 *    has been called from service.
28616 	 *
28617 	 * 3. Message ordering is preserved by the following logic.
28618 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28619 	 *    the message at the tail, if conn_draining is set (i.e. service
28620 	 *    is running) or if q->q_first is non-null.
28621 	 *
28622 	 *    ii. If ip_output is called from service, and if ip_output cannot
28623 	 *    putnext due to flow control, it does a putbq.
28624 	 *
28625 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28626 	 *    (causing an infinite loop).
28627 	 */
28628 	ASSERT(!connp->conn_did_putbq);
28629 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28630 		connp->conn_draining = 1;
28631 		noenable(q);
28632 		while ((mp = getq(q)) != NULL) {
28633 			ASSERT(CONN_Q(q));
28634 
28635 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28636 			if (connp->conn_did_putbq) {
28637 				/* ip_wput did a putbq */
28638 				break;
28639 			}
28640 		}
28641 		/*
28642 		 * At this point, a thread coming down from top, calling
28643 		 * ip_wput, may end up queueing the message. We have not yet
28644 		 * enabled the queue, so ip_wsrv won't be called again.
28645 		 * To avoid this race, check q->q_first again (in the loop)
28646 		 * If the other thread queued the message before we call
28647 		 * enableok(), we will catch it in the q->q_first check.
28648 		 * If the other thread queues the message after we call
28649 		 * enableok(), ip_wsrv will be called again by STREAMS.
28650 		 */
28651 		connp->conn_draining = 0;
28652 		enableok(q);
28653 	}
28654 
28655 	/* Enable the next conn for draining */
28656 	conn_drain_tail(connp, B_FALSE);
28657 
28658 	connp->conn_did_putbq = 0;
28659 }
28660 
28661 /*
28662  * Walk the list of all conn's calling the function provided with the
28663  * specified argument for each.	 Note that this only walks conn's that
28664  * have been bound.
28665  * Applies to both IPv4 and IPv6.
28666  */
28667 static void
28668 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28669 {
28670 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28671 	    ipst->ips_ipcl_udp_fanout_size,
28672 	    func, arg, zoneid);
28673 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28674 	    ipst->ips_ipcl_conn_fanout_size,
28675 	    func, arg, zoneid);
28676 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28677 	    ipst->ips_ipcl_bind_fanout_size,
28678 	    func, arg, zoneid);
28679 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28680 	    IPPROTO_MAX, func, arg, zoneid);
28681 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28682 	    IPPROTO_MAX, func, arg, zoneid);
28683 }
28684 
28685 /*
28686  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28687  * of conns that need to be drained, check if drain is already in progress.
28688  * If so set the idl_repeat bit, indicating that the last conn in the list
28689  * needs to reinitiate the drain once again, for the list. If drain is not
28690  * in progress for the list, initiate the draining, by qenabling the 1st
28691  * conn in the list. The drain is self-sustaining, each qenabled conn will
28692  * in turn qenable the next conn, when it is done/blocked/closing.
28693  */
28694 static void
28695 conn_walk_drain(ip_stack_t *ipst)
28696 {
28697 	int i;
28698 	idl_t *idl;
28699 
28700 	IP_STAT(ipst, ip_conn_walk_drain);
28701 
28702 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28703 		idl = &ipst->ips_conn_drain_list[i];
28704 		mutex_enter(&idl->idl_lock);
28705 		if (idl->idl_conn == NULL) {
28706 			mutex_exit(&idl->idl_lock);
28707 			continue;
28708 		}
28709 		/*
28710 		 * If this list is not being drained currently by
28711 		 * an ip_wsrv thread, start the process.
28712 		 */
28713 		if (idl->idl_conn_draining == NULL) {
28714 			ASSERT(idl->idl_repeat == 0);
28715 			qenable(idl->idl_conn->conn_wq);
28716 			idl->idl_conn_draining = idl->idl_conn;
28717 		} else {
28718 			idl->idl_repeat = 1;
28719 		}
28720 		mutex_exit(&idl->idl_lock);
28721 	}
28722 }
28723 
28724 /*
28725  * Walk an conn hash table of `count' buckets, calling func for each entry.
28726  */
28727 static void
28728 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28729     zoneid_t zoneid)
28730 {
28731 	conn_t	*connp;
28732 
28733 	while (count-- > 0) {
28734 		mutex_enter(&connfp->connf_lock);
28735 		for (connp = connfp->connf_head; connp != NULL;
28736 		    connp = connp->conn_next) {
28737 			if (zoneid == GLOBAL_ZONEID ||
28738 			    zoneid == connp->conn_zoneid) {
28739 				CONN_INC_REF(connp);
28740 				mutex_exit(&connfp->connf_lock);
28741 				(*func)(connp, arg);
28742 				mutex_enter(&connfp->connf_lock);
28743 				CONN_DEC_REF(connp);
28744 			}
28745 		}
28746 		mutex_exit(&connfp->connf_lock);
28747 		connfp++;
28748 	}
28749 }
28750 
28751 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28752 static void
28753 conn_report1(conn_t *connp, void *mp)
28754 {
28755 	char	buf1[INET6_ADDRSTRLEN];
28756 	char	buf2[INET6_ADDRSTRLEN];
28757 	uint_t	print_len, buf_len;
28758 
28759 	ASSERT(connp != NULL);
28760 
28761 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28762 	if (buf_len <= 0)
28763 		return;
28764 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
28765 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
28766 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28767 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28768 	    "%5d %s/%05d %s/%05d\n",
28769 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28770 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28771 	    buf1, connp->conn_lport,
28772 	    buf2, connp->conn_fport);
28773 	if (print_len < buf_len) {
28774 		((mblk_t *)mp)->b_wptr += print_len;
28775 	} else {
28776 		((mblk_t *)mp)->b_wptr += buf_len;
28777 	}
28778 }
28779 
28780 /*
28781  * Named Dispatch routine to produce a formatted report on all conns
28782  * that are listed in one of the fanout tables.
28783  * This report is accessed by using the ndd utility to "get" ND variable
28784  * "ip_conn_status".
28785  */
28786 /* ARGSUSED */
28787 static int
28788 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28789 {
28790 	conn_t *connp = Q_TO_CONN(q);
28791 
28792 	(void) mi_mpprintf(mp,
28793 	    "CONN      " MI_COL_HDRPAD_STR
28794 	    "rfq      " MI_COL_HDRPAD_STR
28795 	    "stq      " MI_COL_HDRPAD_STR
28796 	    " zone local                 remote");
28797 
28798 	/*
28799 	 * Because of the ndd constraint, at most we can have 64K buffer
28800 	 * to put in all conn info.  So to be more efficient, just
28801 	 * allocate a 64K buffer here, assuming we need that large buffer.
28802 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28803 	 */
28804 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28805 		/* The following may work even if we cannot get a large buf. */
28806 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28807 		return (0);
28808 	}
28809 
28810 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28811 	    connp->conn_netstack->netstack_ip);
28812 	return (0);
28813 }
28814 
28815 /*
28816  * Determine if the ill and multicast aspects of that packets
28817  * "matches" the conn.
28818  */
28819 boolean_t
28820 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28821     zoneid_t zoneid)
28822 {
28823 	ill_t *in_ill;
28824 	boolean_t found;
28825 	ipif_t *ipif;
28826 	ire_t *ire;
28827 	ipaddr_t dst, src;
28828 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28829 
28830 	dst = ipha->ipha_dst;
28831 	src = ipha->ipha_src;
28832 
28833 	/*
28834 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28835 	 * unicast, broadcast and multicast reception to
28836 	 * conn_incoming_ill. conn_wantpacket itself is called
28837 	 * only for BROADCAST and multicast.
28838 	 *
28839 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28840 	 *    is part of a group. Hence, we should be receiving
28841 	 *    just one copy of broadcast for the whole group.
28842 	 *    Thus, if it is part of the group the packet could
28843 	 *    come on any ill of the group and hence we need a
28844 	 *    match on the group. Otherwise, match on ill should
28845 	 *    be sufficient.
28846 	 *
28847 	 * 2) ip_rput does not suppress duplicate multicast packets.
28848 	 *    If there are two interfaces in a ill group and we have
28849 	 *    2 applications (conns) joined a multicast group G on
28850 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28851 	 *    will give us two packets because we join G on both the
28852 	 *    interfaces rather than nominating just one interface
28853 	 *    for receiving multicast like broadcast above. So,
28854 	 *    we have to call ilg_lookup_ill to filter out duplicate
28855 	 *    copies, if ill is part of a group.
28856 	 */
28857 	in_ill = connp->conn_incoming_ill;
28858 	if (in_ill != NULL) {
28859 		if (in_ill->ill_group == NULL) {
28860 			if (in_ill != ill)
28861 				return (B_FALSE);
28862 		} else if (in_ill->ill_group != ill->ill_group) {
28863 			return (B_FALSE);
28864 		}
28865 	}
28866 
28867 	if (!CLASSD(dst)) {
28868 		if (IPCL_ZONE_MATCH(connp, zoneid))
28869 			return (B_TRUE);
28870 		/*
28871 		 * The conn is in a different zone; we need to check that this
28872 		 * broadcast address is configured in the application's zone and
28873 		 * on one ill in the group.
28874 		 */
28875 		ipif = ipif_get_next_ipif(NULL, ill);
28876 		if (ipif == NULL)
28877 			return (B_FALSE);
28878 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28879 		    connp->conn_zoneid, NULL,
28880 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28881 		ipif_refrele(ipif);
28882 		if (ire != NULL) {
28883 			ire_refrele(ire);
28884 			return (B_TRUE);
28885 		} else {
28886 			return (B_FALSE);
28887 		}
28888 	}
28889 
28890 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28891 	    connp->conn_zoneid == zoneid) {
28892 		/*
28893 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28894 		 * disabled, therefore we don't dispatch the multicast packet to
28895 		 * the sending zone.
28896 		 */
28897 		return (B_FALSE);
28898 	}
28899 
28900 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
28901 	    connp->conn_zoneid != zoneid) {
28902 		/*
28903 		 * Multicast packet on the loopback interface: we only match
28904 		 * conns who joined the group in the specified zone.
28905 		 */
28906 		return (B_FALSE);
28907 	}
28908 
28909 	if (connp->conn_multi_router) {
28910 		/* multicast packet and multicast router socket: send up */
28911 		return (B_TRUE);
28912 	}
28913 
28914 	mutex_enter(&connp->conn_lock);
28915 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28916 	mutex_exit(&connp->conn_lock);
28917 	return (found);
28918 }
28919 
28920 /*
28921  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28922  */
28923 /* ARGSUSED */
28924 static void
28925 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28926 {
28927 	ill_t *ill = (ill_t *)q->q_ptr;
28928 	mblk_t	*mp1, *mp2;
28929 	ipif_t  *ipif;
28930 	int err = 0;
28931 	conn_t *connp = NULL;
28932 	ipsq_t	*ipsq;
28933 	arc_t	*arc;
28934 
28935 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28936 
28937 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28938 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28939 
28940 	ASSERT(IAM_WRITER_ILL(ill));
28941 	mp2 = mp->b_cont;
28942 	mp->b_cont = NULL;
28943 
28944 	/*
28945 	 * We have now received the arp bringup completion message
28946 	 * from ARP. Mark the arp bringup as done. Also if the arp
28947 	 * stream has already started closing, send up the AR_ARP_CLOSING
28948 	 * ack now since ARP is waiting in close for this ack.
28949 	 */
28950 	mutex_enter(&ill->ill_lock);
28951 	ill->ill_arp_bringup_pending = 0;
28952 	if (ill->ill_arp_closing) {
28953 		mutex_exit(&ill->ill_lock);
28954 		/* Let's reuse the mp for sending the ack */
28955 		arc = (arc_t *)mp->b_rptr;
28956 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28957 		arc->arc_cmd = AR_ARP_CLOSING;
28958 		qreply(q, mp);
28959 	} else {
28960 		mutex_exit(&ill->ill_lock);
28961 		freeb(mp);
28962 	}
28963 
28964 	ipsq = ill->ill_phyint->phyint_ipsq;
28965 	ipif = ipsq->ipsq_pending_ipif;
28966 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28967 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28968 	if (mp1 == NULL) {
28969 		/* bringup was aborted by the user */
28970 		freemsg(mp2);
28971 		return;
28972 	}
28973 
28974 	/*
28975 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28976 	 * must have an associated conn_t.  Otherwise, we're bringing this
28977 	 * interface back up as part of handling an asynchronous event (e.g.,
28978 	 * physical address change).
28979 	 */
28980 	if (ipsq->ipsq_current_ioctl != 0) {
28981 		ASSERT(connp != NULL);
28982 		q = CONNP_TO_WQ(connp);
28983 	} else {
28984 		ASSERT(connp == NULL);
28985 		q = ill->ill_rq;
28986 	}
28987 
28988 	/*
28989 	 * If the DL_BIND_REQ fails, it is noted
28990 	 * in arc_name_offset.
28991 	 */
28992 	err = *((int *)mp2->b_rptr);
28993 	if (err == 0) {
28994 		if (ipif->ipif_isv6) {
28995 			if ((err = ipif_up_done_v6(ipif)) != 0)
28996 				ip0dbg(("ip_arp_done: init failed\n"));
28997 		} else {
28998 			if ((err = ipif_up_done(ipif)) != 0)
28999 				ip0dbg(("ip_arp_done: init failed\n"));
29000 		}
29001 	} else {
29002 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
29003 	}
29004 
29005 	freemsg(mp2);
29006 
29007 	if ((err == 0) && (ill->ill_up_ipifs)) {
29008 		err = ill_up_ipifs(ill, q, mp1);
29009 		if (err == EINPROGRESS)
29010 			return;
29011 	}
29012 
29013 	if (ill->ill_up_ipifs)
29014 		ill_group_cleanup(ill);
29015 
29016 	/*
29017 	 * The operation must complete without EINPROGRESS since
29018 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29019 	 * Otherwise, the operation will be stuck forever in the ipsq.
29020 	 */
29021 	ASSERT(err != EINPROGRESS);
29022 	if (ipsq->ipsq_current_ioctl != 0)
29023 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29024 	else
29025 		ipsq_current_finish(ipsq);
29026 }
29027 
29028 /* Allocate the private structure */
29029 static int
29030 ip_priv_alloc(void **bufp)
29031 {
29032 	void	*buf;
29033 
29034 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29035 		return (ENOMEM);
29036 
29037 	*bufp = buf;
29038 	return (0);
29039 }
29040 
29041 /* Function to delete the private structure */
29042 void
29043 ip_priv_free(void *buf)
29044 {
29045 	ASSERT(buf != NULL);
29046 	kmem_free(buf, sizeof (ip_priv_t));
29047 }
29048 
29049 /*
29050  * The entry point for IPPF processing.
29051  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29052  * routine just returns.
29053  *
29054  * When called, ip_process generates an ipp_packet_t structure
29055  * which holds the state information for this packet and invokes the
29056  * the classifier (via ipp_packet_process). The classification, depending on
29057  * configured filters, results in a list of actions for this packet. Invoking
29058  * an action may cause the packet to be dropped, in which case the resulting
29059  * mblk (*mpp) is NULL. proc indicates the callout position for
29060  * this packet and ill_index is the interface this packet on or will leave
29061  * on (inbound and outbound resp.).
29062  */
29063 void
29064 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29065 {
29066 	mblk_t		*mp;
29067 	ip_priv_t	*priv;
29068 	ipp_action_id_t	aid;
29069 	int		rc = 0;
29070 	ipp_packet_t	*pp;
29071 #define	IP_CLASS	"ip"
29072 
29073 	/* If the classifier is not loaded, return  */
29074 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29075 		return;
29076 	}
29077 
29078 	mp = *mpp;
29079 	ASSERT(mp != NULL);
29080 
29081 	/* Allocate the packet structure */
29082 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29083 	if (rc != 0) {
29084 		*mpp = NULL;
29085 		freemsg(mp);
29086 		return;
29087 	}
29088 
29089 	/* Allocate the private structure */
29090 	rc = ip_priv_alloc((void **)&priv);
29091 	if (rc != 0) {
29092 		*mpp = NULL;
29093 		freemsg(mp);
29094 		ipp_packet_free(pp);
29095 		return;
29096 	}
29097 	priv->proc = proc;
29098 	priv->ill_index = ill_index;
29099 	ipp_packet_set_private(pp, priv, ip_priv_free);
29100 	ipp_packet_set_data(pp, mp);
29101 
29102 	/* Invoke the classifier */
29103 	rc = ipp_packet_process(&pp);
29104 	if (pp != NULL) {
29105 		mp = ipp_packet_get_data(pp);
29106 		ipp_packet_free(pp);
29107 		if (rc != 0) {
29108 			freemsg(mp);
29109 			*mpp = NULL;
29110 		}
29111 	} else {
29112 		*mpp = NULL;
29113 	}
29114 #undef	IP_CLASS
29115 }
29116 
29117 /*
29118  * Propagate a multicast group membership operation (add/drop) on
29119  * all the interfaces crossed by the related multirt routes.
29120  * The call is considered successful if the operation succeeds
29121  * on at least one interface.
29122  */
29123 static int
29124 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29125     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29126     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29127     mblk_t *first_mp)
29128 {
29129 	ire_t		*ire_gw;
29130 	irb_t		*irb;
29131 	int		error = 0;
29132 	opt_restart_t	*or;
29133 	ip_stack_t	*ipst = ire->ire_ipst;
29134 
29135 	irb = ire->ire_bucket;
29136 	ASSERT(irb != NULL);
29137 
29138 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29139 
29140 	or = (opt_restart_t *)first_mp->b_rptr;
29141 	IRB_REFHOLD(irb);
29142 	for (; ire != NULL; ire = ire->ire_next) {
29143 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29144 			continue;
29145 		if (ire->ire_addr != group)
29146 			continue;
29147 
29148 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29149 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29150 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29151 		/* No resolver exists for the gateway; skip this ire. */
29152 		if (ire_gw == NULL)
29153 			continue;
29154 
29155 		/*
29156 		 * This function can return EINPROGRESS. If so the operation
29157 		 * will be restarted from ip_restart_optmgmt which will
29158 		 * call ip_opt_set and option processing will restart for
29159 		 * this option. So we may end up calling 'fn' more than once.
29160 		 * This requires that 'fn' is idempotent except for the
29161 		 * return value. The operation is considered a success if
29162 		 * it succeeds at least once on any one interface.
29163 		 */
29164 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29165 		    NULL, fmode, src, first_mp);
29166 		if (error == 0)
29167 			or->or_private = CGTP_MCAST_SUCCESS;
29168 
29169 		if (ip_debug > 0) {
29170 			ulong_t	off;
29171 			char	*ksym;
29172 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29173 			ip2dbg(("ip_multirt_apply_membership: "
29174 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29175 			    "error %d [success %u]\n",
29176 			    ksym ? ksym : "?",
29177 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29178 			    error, or->or_private));
29179 		}
29180 
29181 		ire_refrele(ire_gw);
29182 		if (error == EINPROGRESS) {
29183 			IRB_REFRELE(irb);
29184 			return (error);
29185 		}
29186 	}
29187 	IRB_REFRELE(irb);
29188 	/*
29189 	 * Consider the call as successful if we succeeded on at least
29190 	 * one interface. Otherwise, return the last encountered error.
29191 	 */
29192 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29193 }
29194 
29195 
29196 /*
29197  * Issue a warning regarding a route crossing an interface with an
29198  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29199  * amount of time is logged.
29200  */
29201 static void
29202 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29203 {
29204 	hrtime_t	current = gethrtime();
29205 	char		buf[INET_ADDRSTRLEN];
29206 	ip_stack_t	*ipst = ire->ire_ipst;
29207 
29208 	/* Convert interval in ms to hrtime in ns */
29209 	if (ipst->ips_multirt_bad_mtu_last_time +
29210 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29211 	    current) {
29212 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29213 		    "to %s, incorrect MTU %u (expected %u)\n",
29214 		    ip_dot_addr(ire->ire_addr, buf),
29215 		    ire->ire_max_frag, max_frag);
29216 
29217 		ipst->ips_multirt_bad_mtu_last_time = current;
29218 	}
29219 }
29220 
29221 
29222 /*
29223  * Get the CGTP (multirouting) filtering status.
29224  * If 0, the CGTP hooks are transparent.
29225  */
29226 /* ARGSUSED */
29227 static int
29228 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29229 {
29230 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29231 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29232 
29233 	/*
29234 	 * Only applies to the shared stack since the filter_ops
29235 	 * do not carry an ip_stack_t or zoneid.
29236 	 */
29237 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29238 		return (ENOTSUP);
29239 
29240 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29241 	return (0);
29242 }
29243 
29244 
29245 /*
29246  * Set the CGTP (multirouting) filtering status.
29247  * If the status is changed from active to transparent
29248  * or from transparent to active, forward the new status
29249  * to the filtering module (if loaded).
29250  */
29251 /* ARGSUSED */
29252 static int
29253 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29254     cred_t *ioc_cr)
29255 {
29256 	long		new_value;
29257 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29258 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29259 
29260 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
29261 		return (EPERM);
29262 
29263 	/*
29264 	 * Only applies to the shared stack since the filter_ops
29265 	 * do not carry an ip_stack_t or zoneid.
29266 	 */
29267 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29268 		return (ENOTSUP);
29269 
29270 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29271 	    new_value < 0 || new_value > 1) {
29272 		return (EINVAL);
29273 	}
29274 
29275 	/*
29276 	 * Do not enable CGTP filtering - thus preventing the hooks
29277 	 * from being invoked - if the version number of the
29278 	 * filtering module hooks does not match.
29279 	 */
29280 	if ((ip_cgtp_filter_ops != NULL) &&
29281 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29282 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29283 		    "(module hooks version %d, expecting %d)\n",
29284 		    ip_cgtp_filter_ops->cfo_filter_rev,
29285 		    CGTP_FILTER_REV);
29286 		return (ENOTSUP);
29287 	}
29288 
29289 	if ((!*ip_cgtp_filter_value) && new_value) {
29290 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29291 		    ip_cgtp_filter_ops == NULL ?
29292 		    " (module not loaded)" : "");
29293 	}
29294 	if (*ip_cgtp_filter_value && (!new_value)) {
29295 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29296 		    ip_cgtp_filter_ops == NULL ?
29297 		    " (module not loaded)" : "");
29298 	}
29299 
29300 	if (ip_cgtp_filter_ops != NULL) {
29301 		int	res;
29302 
29303 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
29304 		if (res)
29305 			return (res);
29306 	}
29307 
29308 	*ip_cgtp_filter_value = (boolean_t)new_value;
29309 
29310 	return (0);
29311 }
29312 
29313 
29314 /*
29315  * Return the expected CGTP hooks version number.
29316  */
29317 int
29318 ip_cgtp_filter_supported(void)
29319 {
29320 	ip_stack_t *ipst;
29321 	int ret;
29322 
29323 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29324 	if (ipst == NULL)
29325 		return (-1);
29326 	ret = ip_cgtp_filter_rev;
29327 	netstack_rele(ipst->ips_netstack);
29328 	return (ret);
29329 }
29330 
29331 
29332 /*
29333  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29334  * or by invoking this function. In the first case, the version number
29335  * of the registered structure is checked at hooks activation time
29336  * in ip_cgtp_filter_set().
29337  *
29338  * Only applies to the shared stack since the filter_ops
29339  * do not carry an ip_stack_t or zoneid.
29340  */
29341 int
29342 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29343 {
29344 	ip_stack_t *ipst;
29345 
29346 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29347 		return (ENOTSUP);
29348 
29349 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29350 	if (ipst == NULL)
29351 		return (EINVAL);
29352 
29353 	ip_cgtp_filter_ops = ops;
29354 	netstack_rele(ipst->ips_netstack);
29355 	return (0);
29356 }
29357 
29358 static squeue_func_t
29359 ip_squeue_switch(int val)
29360 {
29361 	squeue_func_t rval = squeue_fill;
29362 
29363 	switch (val) {
29364 	case IP_SQUEUE_ENTER_NODRAIN:
29365 		rval = squeue_enter_nodrain;
29366 		break;
29367 	case IP_SQUEUE_ENTER:
29368 		rval = squeue_enter;
29369 		break;
29370 	default:
29371 		break;
29372 	}
29373 	return (rval);
29374 }
29375 
29376 /* ARGSUSED */
29377 static int
29378 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29379     caddr_t addr, cred_t *cr)
29380 {
29381 	int *v = (int *)addr;
29382 	long new_value;
29383 
29384 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29385 		return (EPERM);
29386 
29387 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29388 		return (EINVAL);
29389 
29390 	ip_input_proc = ip_squeue_switch(new_value);
29391 	*v = new_value;
29392 	return (0);
29393 }
29394 
29395 /* ARGSUSED */
29396 static int
29397 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29398     caddr_t addr, cred_t *cr)
29399 {
29400 	int *v = (int *)addr;
29401 	long new_value;
29402 
29403 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29404 		return (EPERM);
29405 
29406 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29407 		return (EINVAL);
29408 
29409 	*v = new_value;
29410 	return (0);
29411 }
29412 
29413 /*
29414  * Handle changes to ipmp_hook_emulation ndd variable.
29415  * Need to update phyint_hook_ifindex.
29416  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29417  */
29418 static void
29419 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29420 {
29421 	phyint_t *phyi;
29422 	phyint_t *phyi_tmp;
29423 	char *groupname;
29424 	int namelen;
29425 	ill_t	*ill;
29426 	boolean_t new_group;
29427 
29428 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29429 	/*
29430 	 * Group indicies are stored in the phyint - a common structure
29431 	 * to both IPv4 and IPv6.
29432 	 */
29433 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29434 	for (; phyi != NULL;
29435 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29436 	    phyi, AVL_AFTER)) {
29437 		/* Ignore the ones that do not have a group */
29438 		if (phyi->phyint_groupname_len == 0)
29439 			continue;
29440 
29441 		/*
29442 		 * Look for other phyint in group.
29443 		 * Clear name/namelen so the lookup doesn't find ourselves.
29444 		 */
29445 		namelen = phyi->phyint_groupname_len;
29446 		groupname = phyi->phyint_groupname;
29447 		phyi->phyint_groupname_len = 0;
29448 		phyi->phyint_groupname = NULL;
29449 
29450 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29451 		/* Restore */
29452 		phyi->phyint_groupname_len = namelen;
29453 		phyi->phyint_groupname = groupname;
29454 
29455 		new_group = B_FALSE;
29456 		if (ipst->ips_ipmp_hook_emulation) {
29457 			/*
29458 			 * If the group already exists and has already
29459 			 * been assigned a group ifindex, we use the existing
29460 			 * group_ifindex, otherwise we pick a new group_ifindex
29461 			 * here.
29462 			 */
29463 			if (phyi_tmp != NULL &&
29464 			    phyi_tmp->phyint_group_ifindex != 0) {
29465 				phyi->phyint_group_ifindex =
29466 				    phyi_tmp->phyint_group_ifindex;
29467 			} else {
29468 				/* XXX We need a recovery strategy here. */
29469 				if (!ip_assign_ifindex(
29470 				    &phyi->phyint_group_ifindex, ipst))
29471 					cmn_err(CE_PANIC,
29472 					    "ip_assign_ifindex() failed");
29473 				new_group = B_TRUE;
29474 			}
29475 		} else {
29476 			phyi->phyint_group_ifindex = 0;
29477 		}
29478 		if (ipst->ips_ipmp_hook_emulation)
29479 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29480 		else
29481 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29482 
29483 		/*
29484 		 * For IP Filter to find out the relationship between
29485 		 * names and interface indicies, we need to generate
29486 		 * a NE_PLUMB event when a new group can appear.
29487 		 * We always generate events when a new interface appears
29488 		 * (even when ipmp_hook_emulation is set) so there
29489 		 * is no need to generate NE_PLUMB events when
29490 		 * ipmp_hook_emulation is turned off.
29491 		 * And since it isn't critical for IP Filter to get
29492 		 * the NE_UNPLUMB events we skip those here.
29493 		 */
29494 		if (new_group) {
29495 			/*
29496 			 * First phyint in group - generate group PLUMB event.
29497 			 * Since we are not running inside the ipsq we do
29498 			 * the dispatch immediately.
29499 			 */
29500 			if (phyi->phyint_illv4 != NULL)
29501 				ill = phyi->phyint_illv4;
29502 			else
29503 				ill = phyi->phyint_illv6;
29504 
29505 			if (ill != NULL) {
29506 				mutex_enter(&ill->ill_lock);
29507 				ill_nic_info_plumb(ill, B_TRUE);
29508 				ill_nic_info_dispatch(ill);
29509 				mutex_exit(&ill->ill_lock);
29510 			}
29511 		}
29512 	}
29513 	rw_exit(&ipst->ips_ill_g_lock);
29514 }
29515 
29516 /* ARGSUSED */
29517 static int
29518 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29519     caddr_t addr, cred_t *cr)
29520 {
29521 	int *v = (int *)addr;
29522 	long new_value;
29523 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29524 
29525 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29526 		return (EINVAL);
29527 
29528 	if (*v != new_value) {
29529 		*v = new_value;
29530 		ipmp_hook_emulation_changed(ipst);
29531 	}
29532 	return (0);
29533 }
29534 
29535 static void *
29536 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29537 {
29538 	kstat_t *ksp;
29539 
29540 	ip_stat_t template = {
29541 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29542 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29543 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29544 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29545 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29546 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29547 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29548 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29549 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29550 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29551 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29552 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29553 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29554 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29555 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29556 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29557 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29558 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29559 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29560 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29561 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29562 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29563 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29564 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29565 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29566 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29567 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29568 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29569 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29570 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29571 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29572 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29573 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29574 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29575 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29576 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29577 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29578 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29579 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29580 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29581 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29582 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29583 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29584 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29585 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29586 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29587 	};
29588 
29589 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29590 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29591 	    KSTAT_FLAG_VIRTUAL, stackid);
29592 
29593 	if (ksp == NULL)
29594 		return (NULL);
29595 
29596 	bcopy(&template, ip_statisticsp, sizeof (template));
29597 	ksp->ks_data = (void *)ip_statisticsp;
29598 	ksp->ks_private = (void *)(uintptr_t)stackid;
29599 
29600 	kstat_install(ksp);
29601 	return (ksp);
29602 }
29603 
29604 static void
29605 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29606 {
29607 	if (ksp != NULL) {
29608 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29609 		kstat_delete_netstack(ksp, stackid);
29610 	}
29611 }
29612 
29613 static void *
29614 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29615 {
29616 	kstat_t	*ksp;
29617 
29618 	ip_named_kstat_t template = {
29619 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29620 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29621 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29622 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29623 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29624 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29625 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29626 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29627 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29628 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29629 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29630 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29631 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29632 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29633 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29634 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29635 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29636 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29637 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29638 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29639 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29640 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29641 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29642 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29643 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29644 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29645 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29646 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29647 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29648 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29649 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29650 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29651 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29652 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29653 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29654 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29655 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29656 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29657 	};
29658 
29659 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29660 					NUM_OF_FIELDS(ip_named_kstat_t),
29661 					0, stackid);
29662 	if (ksp == NULL || ksp->ks_data == NULL)
29663 		return (NULL);
29664 
29665 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29666 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29667 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29668 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29669 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29670 
29671 	template.netToMediaEntrySize.value.i32 =
29672 		sizeof (mib2_ipNetToMediaEntry_t);
29673 
29674 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29675 
29676 	bcopy(&template, ksp->ks_data, sizeof (template));
29677 	ksp->ks_update = ip_kstat_update;
29678 	ksp->ks_private = (void *)(uintptr_t)stackid;
29679 
29680 	kstat_install(ksp);
29681 	return (ksp);
29682 }
29683 
29684 static void
29685 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29686 {
29687 	if (ksp != NULL) {
29688 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29689 		kstat_delete_netstack(ksp, stackid);
29690 	}
29691 }
29692 
29693 static int
29694 ip_kstat_update(kstat_t *kp, int rw)
29695 {
29696 	ip_named_kstat_t *ipkp;
29697 	mib2_ipIfStatsEntry_t ipmib;
29698 	ill_walk_context_t ctx;
29699 	ill_t *ill;
29700 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29701 	netstack_t	*ns;
29702 	ip_stack_t	*ipst;
29703 
29704 	if (kp == NULL || kp->ks_data == NULL)
29705 		return (EIO);
29706 
29707 	if (rw == KSTAT_WRITE)
29708 		return (EACCES);
29709 
29710 	ns = netstack_find_by_stackid(stackid);
29711 	if (ns == NULL)
29712 		return (-1);
29713 	ipst = ns->netstack_ip;
29714 	if (ipst == NULL) {
29715 		netstack_rele(ns);
29716 		return (-1);
29717 	}
29718 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29719 
29720 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29721 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29722 	ill = ILL_START_WALK_V4(&ctx, ipst);
29723 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29724 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29725 	rw_exit(&ipst->ips_ill_g_lock);
29726 
29727 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29728 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29729 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29730 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29731 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29732 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29733 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29734 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29735 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29736 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29737 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29738 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29739 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29740 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29741 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29742 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29743 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29744 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29745 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29746 
29747 	ipkp->routingDiscards.value.ui32 =	0;
29748 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29749 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29750 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29751 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29752 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29753 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29754 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29755 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29756 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29757 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29758 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29759 
29760 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29761 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29762 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29763 
29764 	netstack_rele(ns);
29765 
29766 	return (0);
29767 }
29768 
29769 static void *
29770 icmp_kstat_init(netstackid_t stackid)
29771 {
29772 	kstat_t	*ksp;
29773 
29774 	icmp_named_kstat_t template = {
29775 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29776 		{ "inErrors",		KSTAT_DATA_UINT32 },
29777 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29778 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29779 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29780 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29781 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29782 		{ "inEchos",		KSTAT_DATA_UINT32 },
29783 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29784 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29785 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29786 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29787 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29788 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29789 		{ "outErrors",		KSTAT_DATA_UINT32 },
29790 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29791 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29792 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29793 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29794 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29795 		{ "outEchos",		KSTAT_DATA_UINT32 },
29796 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29797 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29798 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29799 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29800 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29801 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29802 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29803 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29804 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29805 		{ "outDrops",		KSTAT_DATA_UINT32 },
29806 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29807 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29808 	};
29809 
29810 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29811 					NUM_OF_FIELDS(icmp_named_kstat_t),
29812 					0, stackid);
29813 	if (ksp == NULL || ksp->ks_data == NULL)
29814 		return (NULL);
29815 
29816 	bcopy(&template, ksp->ks_data, sizeof (template));
29817 
29818 	ksp->ks_update = icmp_kstat_update;
29819 	ksp->ks_private = (void *)(uintptr_t)stackid;
29820 
29821 	kstat_install(ksp);
29822 	return (ksp);
29823 }
29824 
29825 static void
29826 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29827 {
29828 	if (ksp != NULL) {
29829 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29830 		kstat_delete_netstack(ksp, stackid);
29831 	}
29832 }
29833 
29834 static int
29835 icmp_kstat_update(kstat_t *kp, int rw)
29836 {
29837 	icmp_named_kstat_t *icmpkp;
29838 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29839 	netstack_t	*ns;
29840 	ip_stack_t	*ipst;
29841 
29842 	if ((kp == NULL) || (kp->ks_data == NULL))
29843 		return (EIO);
29844 
29845 	if (rw == KSTAT_WRITE)
29846 		return (EACCES);
29847 
29848 	ns = netstack_find_by_stackid(stackid);
29849 	if (ns == NULL)
29850 		return (-1);
29851 	ipst = ns->netstack_ip;
29852 	if (ipst == NULL) {
29853 		netstack_rele(ns);
29854 		return (-1);
29855 	}
29856 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29857 
29858 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29859 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29860 	icmpkp->inDestUnreachs.value.ui32 =
29861 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29862 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29863 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29864 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29865 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29866 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29867 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29868 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29869 	icmpkp->inTimestampReps.value.ui32 =
29870 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29871 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29872 	icmpkp->inAddrMaskReps.value.ui32 =
29873 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29874 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29875 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29876 	icmpkp->outDestUnreachs.value.ui32 =
29877 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29878 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29879 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29880 	icmpkp->outSrcQuenchs.value.ui32 =
29881 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29882 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29883 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29884 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29885 	icmpkp->outTimestamps.value.ui32 =
29886 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29887 	icmpkp->outTimestampReps.value.ui32 =
29888 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29889 	icmpkp->outAddrMasks.value.ui32 =
29890 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29891 	icmpkp->outAddrMaskReps.value.ui32 =
29892 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29893 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29894 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29895 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29896 	icmpkp->outFragNeeded.value.ui32 =
29897 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29898 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29899 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29900 	icmpkp->inBadRedirects.value.ui32 =
29901 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29902 
29903 	netstack_rele(ns);
29904 	return (0);
29905 }
29906 
29907 /*
29908  * This is the fanout function for raw socket opened for SCTP.  Note
29909  * that it is called after SCTP checks that there is no socket which
29910  * wants a packet.  Then before SCTP handles this out of the blue packet,
29911  * this function is called to see if there is any raw socket for SCTP.
29912  * If there is and it is bound to the correct address, the packet will
29913  * be sent to that socket.  Note that only one raw socket can be bound to
29914  * a port.  This is assured in ipcl_sctp_hash_insert();
29915  */
29916 void
29917 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29918     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29919     zoneid_t zoneid)
29920 {
29921 	conn_t		*connp;
29922 	queue_t		*rq;
29923 	mblk_t		*first_mp;
29924 	boolean_t	secure;
29925 	ip6_t		*ip6h;
29926 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29927 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29928 
29929 	first_mp = mp;
29930 	if (mctl_present) {
29931 		mp = first_mp->b_cont;
29932 		secure = ipsec_in_is_secure(first_mp);
29933 		ASSERT(mp != NULL);
29934 	} else {
29935 		secure = B_FALSE;
29936 	}
29937 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29938 
29939 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29940 	if (connp == NULL) {
29941 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29942 		return;
29943 	}
29944 	rq = connp->conn_rq;
29945 	if (!canputnext(rq)) {
29946 		CONN_DEC_REF(connp);
29947 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29948 		freemsg(first_mp);
29949 		return;
29950 	}
29951 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29952 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29953 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29954 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29955 		if (first_mp == NULL) {
29956 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29957 			CONN_DEC_REF(connp);
29958 			return;
29959 		}
29960 	}
29961 	/*
29962 	 * We probably should not send M_CTL message up to
29963 	 * raw socket.
29964 	 */
29965 	if (mctl_present)
29966 		freeb(first_mp);
29967 
29968 	/* Initiate IPPF processing here if needed. */
29969 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29970 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29971 		ip_process(IPP_LOCAL_IN, &mp,
29972 		    recv_ill->ill_phyint->phyint_ifindex);
29973 		if (mp == NULL) {
29974 			CONN_DEC_REF(connp);
29975 			return;
29976 		}
29977 	}
29978 
29979 	if (connp->conn_recvif || connp->conn_recvslla ||
29980 	    ((connp->conn_ip_recvpktinfo ||
29981 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29982 	    (flags & IP_FF_IPINFO))) {
29983 		int in_flags = 0;
29984 
29985 		/*
29986 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29987 		 * IPF_RECVIF.
29988 		 */
29989 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29990 			in_flags = IPF_RECVIF;
29991 		}
29992 		if (connp->conn_recvslla) {
29993 			in_flags |= IPF_RECVSLLA;
29994 		}
29995 		if (isv4) {
29996 			mp = ip_add_info(mp, recv_ill, in_flags,
29997 			    IPCL_ZONEID(connp), ipst);
29998 		} else {
29999 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
30000 			if (mp == NULL) {
30001 				BUMP_MIB(recv_ill->ill_ip_mib,
30002 				    ipIfStatsInDiscards);
30003 				CONN_DEC_REF(connp);
30004 				return;
30005 			}
30006 		}
30007 	}
30008 
30009 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
30010 	/*
30011 	 * We are sending the IPSEC_IN message also up. Refer
30012 	 * to comments above this function.
30013 	 */
30014 	putnext(rq, mp);
30015 	CONN_DEC_REF(connp);
30016 }
30017 
30018 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30019 {									\
30020 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30021 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30022 }
30023 /*
30024  * This function should be called only if all packet processing
30025  * including fragmentation is complete. Callers of this function
30026  * must set mp->b_prev to one of these values:
30027  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30028  * prior to handing over the mp as first argument to this function.
30029  *
30030  * If the ire passed by caller is incomplete, this function
30031  * queues the packet and if necessary, sends ARP request and bails.
30032  * If the ire passed is fully resolved, we simply prepend
30033  * the link-layer header to the packet, do ipsec hw acceleration
30034  * work if necessary, and send the packet out on the wire.
30035  *
30036  * NOTE: IPSEC will only call this function with fully resolved
30037  * ires if hw acceleration is involved.
30038  * TODO list :
30039  * 	a Handle M_MULTIDATA so that
30040  *	  tcp_multisend->tcp_multisend_data can
30041  *	  call ip_xmit_v4 directly
30042  *	b Handle post-ARP work for fragments so that
30043  *	  ip_wput_frag can call this function.
30044  */
30045 ipxmit_state_t
30046 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
30047 {
30048 	nce_t		*arpce;
30049 	queue_t		*q;
30050 	int		ill_index;
30051 	mblk_t		*nxt_mp, *first_mp;
30052 	boolean_t	xmit_drop = B_FALSE;
30053 	ip_proc_t	proc;
30054 	ill_t		*out_ill;
30055 	int		pkt_len;
30056 
30057 	arpce = ire->ire_nce;
30058 	ASSERT(arpce != NULL);
30059 
30060 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30061 
30062 	mutex_enter(&arpce->nce_lock);
30063 	switch (arpce->nce_state) {
30064 	case ND_REACHABLE:
30065 		/* If there are other queued packets, queue this packet */
30066 		if (arpce->nce_qd_mp != NULL) {
30067 			if (mp != NULL)
30068 				nce_queue_mp_common(arpce, mp, B_FALSE);
30069 			mp = arpce->nce_qd_mp;
30070 		}
30071 		arpce->nce_qd_mp = NULL;
30072 		mutex_exit(&arpce->nce_lock);
30073 
30074 		/*
30075 		 * Flush the queue.  In the common case, where the
30076 		 * ARP is already resolved,  it will go through the
30077 		 * while loop only once.
30078 		 */
30079 		while (mp != NULL) {
30080 
30081 			nxt_mp = mp->b_next;
30082 			mp->b_next = NULL;
30083 			ASSERT(mp->b_datap->db_type != M_CTL);
30084 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30085 			/*
30086 			 * This info is needed for IPQOS to do COS marking
30087 			 * in ip_wput_attach_llhdr->ip_process.
30088 			 */
30089 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30090 			mp->b_prev = NULL;
30091 
30092 			/* set up ill index for outbound qos processing */
30093 			out_ill = ire->ire_ipif->ipif_ill;
30094 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30095 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30096 			    ill_index);
30097 			if (first_mp == NULL) {
30098 				xmit_drop = B_TRUE;
30099 				BUMP_MIB(out_ill->ill_ip_mib,
30100 				    ipIfStatsOutDiscards);
30101 				goto next_mp;
30102 			}
30103 			/* non-ipsec hw accel case */
30104 			if (io == NULL || !io->ipsec_out_accelerated) {
30105 				/* send it */
30106 				q = ire->ire_stq;
30107 				if (proc == IPP_FWD_OUT) {
30108 					UPDATE_IB_PKT_COUNT(ire);
30109 				} else {
30110 					UPDATE_OB_PKT_COUNT(ire);
30111 				}
30112 				ire->ire_last_used_time = lbolt;
30113 
30114 				if (flow_ctl_enabled || canputnext(q))  {
30115 					if (proc == IPP_FWD_OUT) {
30116 						BUMP_MIB(out_ill->ill_ip_mib,
30117 						ipIfStatsHCOutForwDatagrams);
30118 					}
30119 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30120 					    pkt_len);
30121 
30122 					putnext(q, first_mp);
30123 				} else {
30124 					BUMP_MIB(out_ill->ill_ip_mib,
30125 					    ipIfStatsOutDiscards);
30126 					xmit_drop = B_TRUE;
30127 					freemsg(first_mp);
30128 				}
30129 			} else {
30130 				/*
30131 				 * Safety Pup says: make sure this
30132 				 *  is going to the right interface!
30133 				 */
30134 				ill_t *ill1 =
30135 				    (ill_t *)ire->ire_stq->q_ptr;
30136 				int ifindex =
30137 				    ill1->ill_phyint->phyint_ifindex;
30138 				if (ifindex !=
30139 				    io->ipsec_out_capab_ill_index) {
30140 					xmit_drop = B_TRUE;
30141 					freemsg(mp);
30142 				} else {
30143 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30144 					    pkt_len);
30145 					ipsec_hw_putnext(ire->ire_stq, mp);
30146 				}
30147 			}
30148 next_mp:
30149 			mp = nxt_mp;
30150 		} /* while (mp != NULL) */
30151 		if (xmit_drop)
30152 			return (SEND_FAILED);
30153 		else
30154 			return (SEND_PASSED);
30155 
30156 	case ND_INITIAL:
30157 	case ND_INCOMPLETE:
30158 
30159 		/*
30160 		 * While we do send off packets to dests that
30161 		 * use fully-resolved CGTP routes, we do not
30162 		 * handle unresolved CGTP routes.
30163 		 */
30164 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30165 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30166 
30167 		if (mp != NULL) {
30168 			/* queue the packet */
30169 			nce_queue_mp_common(arpce, mp, B_FALSE);
30170 		}
30171 
30172 		if (arpce->nce_state == ND_INCOMPLETE) {
30173 			mutex_exit(&arpce->nce_lock);
30174 			DTRACE_PROBE3(ip__xmit__incomplete,
30175 			    (ire_t *), ire, (mblk_t *), mp,
30176 			    (ipsec_out_t *), io);
30177 			return (LOOKUP_IN_PROGRESS);
30178 		}
30179 
30180 		arpce->nce_state = ND_INCOMPLETE;
30181 		mutex_exit(&arpce->nce_lock);
30182 		/*
30183 		 * Note that ire_add() (called from ire_forward())
30184 		 * holds a ref on the ire until ARP is completed.
30185 		 */
30186 
30187 		ire_arpresolve(ire, ire_to_ill(ire));
30188 		return (LOOKUP_IN_PROGRESS);
30189 	default:
30190 		ASSERT(0);
30191 		mutex_exit(&arpce->nce_lock);
30192 		return (LLHDR_RESLV_FAILED);
30193 	}
30194 }
30195 
30196 #undef	UPDATE_IP_MIB_OB_COUNTERS
30197 
30198 /*
30199  * Return B_TRUE if the buffers differ in length or content.
30200  * This is used for comparing extension header buffers.
30201  * Note that an extension header would be declared different
30202  * even if all that changed was the next header value in that header i.e.
30203  * what really changed is the next extension header.
30204  */
30205 boolean_t
30206 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30207     uint_t blen)
30208 {
30209 	if (!b_valid)
30210 		blen = 0;
30211 
30212 	if (alen != blen)
30213 		return (B_TRUE);
30214 	if (alen == 0)
30215 		return (B_FALSE);	/* Both zero length */
30216 	return (bcmp(abuf, bbuf, alen));
30217 }
30218 
30219 /*
30220  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30221  * Return B_FALSE if memory allocation fails - don't change any state!
30222  */
30223 boolean_t
30224 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30225     const void *src, uint_t srclen)
30226 {
30227 	void *dst;
30228 
30229 	if (!src_valid)
30230 		srclen = 0;
30231 
30232 	ASSERT(*dstlenp == 0);
30233 	if (src != NULL && srclen != 0) {
30234 		dst = mi_alloc(srclen, BPRI_MED);
30235 		if (dst == NULL)
30236 			return (B_FALSE);
30237 	} else {
30238 		dst = NULL;
30239 	}
30240 	if (*dstp != NULL)
30241 		mi_free(*dstp);
30242 	*dstp = dst;
30243 	*dstlenp = dst == NULL ? 0 : srclen;
30244 	return (B_TRUE);
30245 }
30246 
30247 /*
30248  * Replace what is in *dst, *dstlen with the source.
30249  * Assumes ip_allocbuf has already been called.
30250  */
30251 void
30252 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30253     const void *src, uint_t srclen)
30254 {
30255 	if (!src_valid)
30256 		srclen = 0;
30257 
30258 	ASSERT(*dstlenp == srclen);
30259 	if (src != NULL && srclen != 0)
30260 		bcopy(src, *dstp, srclen);
30261 }
30262 
30263 /*
30264  * Free the storage pointed to by the members of an ip6_pkt_t.
30265  */
30266 void
30267 ip6_pkt_free(ip6_pkt_t *ipp)
30268 {
30269 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30270 
30271 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30272 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30273 		ipp->ipp_hopopts = NULL;
30274 		ipp->ipp_hopoptslen = 0;
30275 	}
30276 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30277 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30278 		ipp->ipp_rtdstopts = NULL;
30279 		ipp->ipp_rtdstoptslen = 0;
30280 	}
30281 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30282 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30283 		ipp->ipp_dstopts = NULL;
30284 		ipp->ipp_dstoptslen = 0;
30285 	}
30286 	if (ipp->ipp_fields & IPPF_RTHDR) {
30287 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30288 		ipp->ipp_rthdr = NULL;
30289 		ipp->ipp_rthdrlen = 0;
30290 	}
30291 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30292 	    IPPF_RTHDR);
30293 }
30294