xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision 4a75c0c1ad1b9f32a7a423e1f23a8d23ac800de0)
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 (broadcast || CLASSD(ipha->ipha_dst)) {
1934 		ipif_t	*ipif_chosen;
1935 		/*
1936 		 * Make it look like it was directed to us, so we don't look
1937 		 * like a fool with a broadcast or multicast source address.
1938 		 */
1939 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1940 		/*
1941 		 * Make sure that we haven't grabbed an interface that's DOWN.
1942 		 */
1943 		if (ipif != NULL) {
1944 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1945 			    ipha->ipha_src, zoneid);
1946 			if (ipif_chosen != NULL) {
1947 				ipif_refrele(ipif);
1948 				ipif = ipif_chosen;
1949 			}
1950 		}
1951 		if (ipif == NULL) {
1952 			ip0dbg(("icmp_inbound: "
1953 			    "No source for broadcast/multicast:\n"
1954 			    "\tsrc 0x%x dst 0x%x ill %p "
1955 			    "ipif_lcl_addr 0x%x\n",
1956 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1957 			    (void *)ill,
1958 			    ill->ill_ipif->ipif_lcl_addr));
1959 			freemsg(first_mp);
1960 			return;
1961 		}
1962 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1963 		ipha->ipha_dst = ipif->ipif_src_addr;
1964 		ipif_refrele(ipif);
1965 	}
1966 	/* Reset time to live. */
1967 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1968 	{
1969 		/* Swap source and destination addresses */
1970 		ipaddr_t tmp;
1971 
1972 		tmp = ipha->ipha_src;
1973 		ipha->ipha_src = ipha->ipha_dst;
1974 		ipha->ipha_dst = tmp;
1975 	}
1976 	ipha->ipha_ident = 0;
1977 	if (!IS_SIMPLE_IPH(ipha))
1978 		icmp_options_update(ipha);
1979 
1980 	/*
1981 	 * ICMP echo replies should go out on the same interface
1982 	 * the request came on as probes used by in.mpathd for detecting
1983 	 * NIC failures are ECHO packets. We turn-off load spreading
1984 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1985 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1986 	 * function. This is in turn handled by ip_wput and ip_newroute
1987 	 * to make sure that the packet goes out on the interface it came
1988 	 * in on. If we don't turnoff load spreading, the packets might get
1989 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1990 	 * to go out and in.mpathd would wrongly detect a failure or
1991 	 * mis-detect a NIC failure for link failure. As load spreading
1992 	 * can happen only if ill_group is not NULL, we do only for
1993 	 * that case and this does not affect the normal case.
1994 	 *
1995 	 * We turn off load spreading only on echo packets that came from
1996 	 * on-link hosts. If the interface route has been deleted, this will
1997 	 * not be enforced as we can't do much. For off-link hosts, as the
1998 	 * default routes in IPv4 does not typically have an ire_ipif
1999 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2000 	 * Moreover, expecting a default route through this interface may
2001 	 * not be correct. We use ipha_dst because of the swap above.
2002 	 */
2003 	onlink = B_FALSE;
2004 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2005 		/*
2006 		 * First, we need to make sure that it is not one of our
2007 		 * local addresses. If we set onlink when it is one of
2008 		 * our local addresses, we will end up creating IRE_CACHES
2009 		 * for one of our local addresses. Then, we will never
2010 		 * accept packets for them afterwards.
2011 		 */
2012 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2013 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2014 		if (src_ire == NULL) {
2015 			ipif = ipif_get_next_ipif(NULL, ill);
2016 			if (ipif == NULL) {
2017 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2018 				freemsg(mp);
2019 				return;
2020 			}
2021 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2022 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2023 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2024 			ipif_refrele(ipif);
2025 			if (src_ire != NULL) {
2026 				onlink = B_TRUE;
2027 				ire_refrele(src_ire);
2028 			}
2029 		} else {
2030 			ire_refrele(src_ire);
2031 		}
2032 	}
2033 	if (!mctl_present) {
2034 		/*
2035 		 * This packet should go out the same way as it
2036 		 * came in i.e in clear. To make sure that global
2037 		 * policy will not be applied to this in ip_wput_ire,
2038 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2039 		 */
2040 		ASSERT(first_mp == mp);
2041 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2042 		if (first_mp == NULL) {
2043 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2044 			freemsg(mp);
2045 			return;
2046 		}
2047 		ii = (ipsec_in_t *)first_mp->b_rptr;
2048 
2049 		/* This is not a secure packet */
2050 		ii->ipsec_in_secure = B_FALSE;
2051 		if (onlink) {
2052 			ii->ipsec_in_attach_if = B_TRUE;
2053 			ii->ipsec_in_ill_index =
2054 			    ill->ill_phyint->phyint_ifindex;
2055 			ii->ipsec_in_rill_index =
2056 			    recv_ill->ill_phyint->phyint_ifindex;
2057 		}
2058 		first_mp->b_cont = mp;
2059 	} else if (onlink) {
2060 		ii = (ipsec_in_t *)first_mp->b_rptr;
2061 		ii->ipsec_in_attach_if = B_TRUE;
2062 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2063 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2064 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2065 	} else {
2066 		ii = (ipsec_in_t *)first_mp->b_rptr;
2067 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2068 	}
2069 	ii->ipsec_in_zoneid = zoneid;
2070 	ASSERT(zoneid != ALL_ZONES);
2071 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2072 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2073 		return;
2074 	}
2075 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2076 	put(WR(q), first_mp);
2077 }
2078 
2079 static ipaddr_t
2080 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2081 {
2082 	conn_t *connp;
2083 	connf_t *connfp;
2084 	ipaddr_t nexthop_addr = INADDR_ANY;
2085 	int hdr_length = IPH_HDR_LENGTH(ipha);
2086 	uint16_t *up;
2087 	uint32_t ports;
2088 	ip_stack_t *ipst = ill->ill_ipst;
2089 
2090 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2091 	switch (ipha->ipha_protocol) {
2092 		case IPPROTO_TCP:
2093 		{
2094 			tcph_t *tcph;
2095 
2096 			/* do a reverse lookup */
2097 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2098 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2099 			    TCPS_LISTEN, ipst);
2100 			break;
2101 		}
2102 		case IPPROTO_UDP:
2103 		{
2104 			uint32_t dstport, srcport;
2105 
2106 			((uint16_t *)&ports)[0] = up[1];
2107 			((uint16_t *)&ports)[1] = up[0];
2108 
2109 			/* Extract ports in net byte order */
2110 			dstport = htons(ntohl(ports) & 0xFFFF);
2111 			srcport = htons(ntohl(ports) >> 16);
2112 
2113 			connfp = &ipst->ips_ipcl_udp_fanout[
2114 			    IPCL_UDP_HASH(dstport, ipst)];
2115 			mutex_enter(&connfp->connf_lock);
2116 			connp = connfp->connf_head;
2117 
2118 			/* do a reverse lookup */
2119 			while ((connp != NULL) &&
2120 			    (!IPCL_UDP_MATCH(connp, dstport,
2121 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2122 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2123 				connp = connp->conn_next;
2124 			}
2125 			if (connp != NULL)
2126 				CONN_INC_REF(connp);
2127 			mutex_exit(&connfp->connf_lock);
2128 			break;
2129 		}
2130 		case IPPROTO_SCTP:
2131 		{
2132 			in6_addr_t map_src, map_dst;
2133 
2134 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2135 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2136 			((uint16_t *)&ports)[0] = up[1];
2137 			((uint16_t *)&ports)[1] = up[0];
2138 
2139 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2140 			    zoneid, ipst->ips_netstack->netstack_sctp);
2141 			if (connp == NULL) {
2142 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2143 				    zoneid, ports, ipha, ipst);
2144 			} else {
2145 				CONN_INC_REF(connp);
2146 				SCTP_REFRELE(CONN2SCTP(connp));
2147 			}
2148 			break;
2149 		}
2150 		default:
2151 		{
2152 			ipha_t ripha;
2153 
2154 			ripha.ipha_src = ipha->ipha_dst;
2155 			ripha.ipha_dst = ipha->ipha_src;
2156 			ripha.ipha_protocol = ipha->ipha_protocol;
2157 
2158 			connfp = &ipst->ips_ipcl_proto_fanout[
2159 			    ipha->ipha_protocol];
2160 			mutex_enter(&connfp->connf_lock);
2161 			connp = connfp->connf_head;
2162 			for (connp = connfp->connf_head; connp != NULL;
2163 			    connp = connp->conn_next) {
2164 				if (IPCL_PROTO_MATCH(connp,
2165 				    ipha->ipha_protocol, &ripha, ill,
2166 				    0, zoneid)) {
2167 					CONN_INC_REF(connp);
2168 					break;
2169 				}
2170 			}
2171 			mutex_exit(&connfp->connf_lock);
2172 		}
2173 	}
2174 	if (connp != NULL) {
2175 		if (connp->conn_nexthop_set)
2176 			nexthop_addr = connp->conn_nexthop_v4;
2177 		CONN_DEC_REF(connp);
2178 	}
2179 	return (nexthop_addr);
2180 }
2181 
2182 /* Table from RFC 1191 */
2183 static int icmp_frag_size_table[] =
2184 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2185 
2186 /*
2187  * Process received ICMP Packet too big.
2188  * After updating any IRE it does the fanout to any matching transport streams.
2189  * Assumes the message has been pulled up till the IP header that caused
2190  * the error.
2191  *
2192  * Returns B_FALSE on failure and B_TRUE on success.
2193  */
2194 static boolean_t
2195 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2196     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2197     ip_stack_t *ipst)
2198 {
2199 	ire_t	*ire, *first_ire;
2200 	int	mtu;
2201 	int	hdr_length;
2202 	ipaddr_t nexthop_addr;
2203 
2204 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2205 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2206 	ASSERT(ill != NULL);
2207 
2208 	hdr_length = IPH_HDR_LENGTH(ipha);
2209 
2210 	/* Drop if the original packet contained a source route */
2211 	if (ip_source_route_included(ipha)) {
2212 		return (B_FALSE);
2213 	}
2214 	/*
2215 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2216 	 * header.
2217 	 */
2218 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2219 	    mp->b_wptr) {
2220 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2221 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2222 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2223 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2224 			return (B_FALSE);
2225 		}
2226 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2227 		ipha = (ipha_t *)&icmph[1];
2228 	}
2229 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2230 	if (nexthop_addr != INADDR_ANY) {
2231 		/* nexthop set */
2232 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2233 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2234 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2235 	} else {
2236 		/* nexthop not set */
2237 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2238 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2239 	}
2240 
2241 	if (!first_ire) {
2242 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2243 		    ntohl(ipha->ipha_dst)));
2244 		return (B_FALSE);
2245 	}
2246 	/* Check for MTU discovery advice as described in RFC 1191 */
2247 	mtu = ntohs(icmph->icmph_du_mtu);
2248 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2249 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2250 	    ire = ire->ire_next) {
2251 		/*
2252 		 * Look for the connection to which this ICMP message is
2253 		 * directed. If it has the IP_NEXTHOP option set, then the
2254 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2255 		 * option. Else the search is limited to regular IREs.
2256 		 */
2257 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2258 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2259 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2260 		    (nexthop_addr != INADDR_ANY)))
2261 			continue;
2262 
2263 		mutex_enter(&ire->ire_lock);
2264 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2265 			/* Reduce the IRE max frag value as advised. */
2266 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2267 			    mtu, ire->ire_max_frag));
2268 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2269 		} else {
2270 			uint32_t length;
2271 			int	i;
2272 
2273 			/*
2274 			 * Use the table from RFC 1191 to figure out
2275 			 * the next "plateau" based on the length in
2276 			 * the original IP packet.
2277 			 */
2278 			length = ntohs(ipha->ipha_length);
2279 			if (ire->ire_max_frag <= length &&
2280 			    ire->ire_max_frag >= length - hdr_length) {
2281 				/*
2282 				 * Handle broken BSD 4.2 systems that
2283 				 * return the wrong iph_length in ICMP
2284 				 * errors.
2285 				 */
2286 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2287 				    length, ire->ire_max_frag));
2288 				length -= hdr_length;
2289 			}
2290 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2291 				if (length > icmp_frag_size_table[i])
2292 					break;
2293 			}
2294 			if (i == A_CNT(icmp_frag_size_table)) {
2295 				/* Smaller than 68! */
2296 				ip1dbg(("Too big for packet size %d\n",
2297 				    length));
2298 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2299 				ire->ire_frag_flag = 0;
2300 			} else {
2301 				mtu = icmp_frag_size_table[i];
2302 				ip1dbg(("Calculated mtu %d, packet size %d, "
2303 				    "before %d", mtu, length,
2304 				    ire->ire_max_frag));
2305 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2306 				ip1dbg((", after %d\n", ire->ire_max_frag));
2307 			}
2308 			/* Record the new max frag size for the ULP. */
2309 			icmph->icmph_du_zero = 0;
2310 			icmph->icmph_du_mtu =
2311 			    htons((uint16_t)ire->ire_max_frag);
2312 		}
2313 		mutex_exit(&ire->ire_lock);
2314 	}
2315 	rw_exit(&first_ire->ire_bucket->irb_lock);
2316 	ire_refrele(first_ire);
2317 	return (B_TRUE);
2318 }
2319 
2320 /*
2321  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2322  * calls this function.
2323  */
2324 static mblk_t *
2325 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2326 {
2327 	ipha_t *ipha;
2328 	icmph_t *icmph;
2329 	ipha_t *in_ipha;
2330 	int length;
2331 
2332 	ASSERT(mp->b_datap->db_type == M_DATA);
2333 
2334 	/*
2335 	 * For Self-encapsulated packets, we added an extra IP header
2336 	 * without the options. Inner IP header is the one from which
2337 	 * the outer IP header was formed. Thus, we need to remove the
2338 	 * outer IP header. To do this, we pullup the whole message
2339 	 * and overlay whatever follows the outer IP header over the
2340 	 * outer IP header.
2341 	 */
2342 
2343 	if (!pullupmsg(mp, -1))
2344 		return (NULL);
2345 
2346 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2347 	ipha = (ipha_t *)&icmph[1];
2348 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2349 
2350 	/*
2351 	 * The length that we want to overlay is following the inner
2352 	 * IP header. Subtracting the IP header + icmp header + outer
2353 	 * IP header's length should give us the length that we want to
2354 	 * overlay.
2355 	 */
2356 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2357 	    hdr_length;
2358 	/*
2359 	 * Overlay whatever follows the inner header over the
2360 	 * outer header.
2361 	 */
2362 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2363 
2364 	/* Set the wptr to account for the outer header */
2365 	mp->b_wptr -= hdr_length;
2366 	return (mp);
2367 }
2368 
2369 /*
2370  * Try to pass the ICMP message upstream in case the ULP cares.
2371  *
2372  * If the packet that caused the ICMP error is secure, we send
2373  * it to AH/ESP to make sure that the attached packet has a
2374  * valid association. ipha in the code below points to the
2375  * IP header of the packet that caused the error.
2376  *
2377  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2378  * in the context of IPSEC. Normally we tell the upper layer
2379  * whenever we send the ire (including ip_bind), the IPSEC header
2380  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2381  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2382  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2383  * same thing. As TCP has the IPSEC options size that needs to be
2384  * adjusted, we just pass the MTU unchanged.
2385  *
2386  * IFN could have been generated locally or by some router.
2387  *
2388  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2389  *	    This happens because IP adjusted its value of MTU on an
2390  *	    earlier IFN message and could not tell the upper layer,
2391  *	    the new adjusted value of MTU e.g. Packet was encrypted
2392  *	    or there was not enough information to fanout to upper
2393  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2394  *	    generates the IFN, where IPSEC processing has *not* been
2395  *	    done.
2396  *
2397  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2398  *	    could have generated this. This happens because ire_max_frag
2399  *	    value in IP was set to a new value, while the IPSEC processing
2400  *	    was being done and after we made the fragmentation check in
2401  *	    ip_wput_ire. Thus on return from IPSEC processing,
2402  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2403  *	    and generates the IFN. As IPSEC processing is over, we fanout
2404  *	    to AH/ESP to remove the header.
2405  *
2406  *	    In both these cases, ipsec_in_loopback will be set indicating
2407  *	    that IFN was generated locally.
2408  *
2409  * ROUTER : IFN could be secure or non-secure.
2410  *
2411  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2412  *	      packet in error has AH/ESP headers to validate the AH/ESP
2413  *	      headers. AH/ESP will verify whether there is a valid SA or
2414  *	      not and send it back. We will fanout again if we have more
2415  *	      data in the packet.
2416  *
2417  *	      If the packet in error does not have AH/ESP, we handle it
2418  *	      like any other case.
2419  *
2420  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2421  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2422  *	      for validation. AH/ESP will verify whether there is a
2423  *	      valid SA or not and send it back. We will fanout again if
2424  *	      we have more data in the packet.
2425  *
2426  *	      If the packet in error does not have AH/ESP, we handle it
2427  *	      like any other case.
2428  */
2429 static void
2430 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2431     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2432     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2433     zoneid_t zoneid)
2434 {
2435 	uint16_t *up;	/* Pointer to ports in ULP header */
2436 	uint32_t ports;	/* reversed ports for fanout */
2437 	ipha_t ripha;	/* With reversed addresses */
2438 	mblk_t *first_mp;
2439 	ipsec_in_t *ii;
2440 	tcph_t	*tcph;
2441 	conn_t	*connp;
2442 	ip_stack_t *ipst;
2443 
2444 	ASSERT(ill != NULL);
2445 
2446 	ASSERT(recv_ill != NULL);
2447 	ipst = recv_ill->ill_ipst;
2448 
2449 	first_mp = mp;
2450 	if (mctl_present) {
2451 		mp = first_mp->b_cont;
2452 		ASSERT(mp != NULL);
2453 
2454 		ii = (ipsec_in_t *)first_mp->b_rptr;
2455 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2456 	} else {
2457 		ii = NULL;
2458 	}
2459 
2460 	switch (ipha->ipha_protocol) {
2461 	case IPPROTO_UDP:
2462 		/*
2463 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2464 		 * transport header.
2465 		 */
2466 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2467 		    mp->b_wptr) {
2468 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2469 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2470 				goto discard_pkt;
2471 			}
2472 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2473 			ipha = (ipha_t *)&icmph[1];
2474 		}
2475 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2476 
2477 		/*
2478 		 * Attempt to find a client stream based on port.
2479 		 * Note that we do a reverse lookup since the header is
2480 		 * in the form we sent it out.
2481 		 * The ripha header is only used for the IP_UDP_MATCH and we
2482 		 * only set the src and dst addresses and protocol.
2483 		 */
2484 		ripha.ipha_src = ipha->ipha_dst;
2485 		ripha.ipha_dst = ipha->ipha_src;
2486 		ripha.ipha_protocol = ipha->ipha_protocol;
2487 		((uint16_t *)&ports)[0] = up[1];
2488 		((uint16_t *)&ports)[1] = up[0];
2489 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2490 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2491 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2492 		    icmph->icmph_type, icmph->icmph_code));
2493 
2494 		/* Have to change db_type after any pullupmsg */
2495 		DB_TYPE(mp) = M_CTL;
2496 
2497 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2498 		    mctl_present, ip_policy, recv_ill, zoneid);
2499 		return;
2500 
2501 	case IPPROTO_TCP:
2502 		/*
2503 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2504 		 * transport header.
2505 		 */
2506 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2507 		    mp->b_wptr) {
2508 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2509 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2510 				goto discard_pkt;
2511 			}
2512 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2513 			ipha = (ipha_t *)&icmph[1];
2514 		}
2515 		/*
2516 		 * Find a TCP client stream for this packet.
2517 		 * Note that we do a reverse lookup since the header is
2518 		 * in the form we sent it out.
2519 		 */
2520 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2521 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2522 		    ipst);
2523 		if (connp == NULL)
2524 			goto discard_pkt;
2525 
2526 		/* Have to change db_type after any pullupmsg */
2527 		DB_TYPE(mp) = M_CTL;
2528 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2529 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2530 		return;
2531 
2532 	case IPPROTO_SCTP:
2533 		/*
2534 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2535 		 * transport header.
2536 		 */
2537 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2538 		    mp->b_wptr) {
2539 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2540 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2541 				goto discard_pkt;
2542 			}
2543 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2544 			ipha = (ipha_t *)&icmph[1];
2545 		}
2546 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2547 		/*
2548 		 * Find a SCTP client stream for this packet.
2549 		 * Note that we do a reverse lookup since the header is
2550 		 * in the form we sent it out.
2551 		 * The ripha header is only used for the matching and we
2552 		 * only set the src and dst addresses, protocol, and version.
2553 		 */
2554 		ripha.ipha_src = ipha->ipha_dst;
2555 		ripha.ipha_dst = ipha->ipha_src;
2556 		ripha.ipha_protocol = ipha->ipha_protocol;
2557 		ripha.ipha_version_and_hdr_length =
2558 		    ipha->ipha_version_and_hdr_length;
2559 		((uint16_t *)&ports)[0] = up[1];
2560 		((uint16_t *)&ports)[1] = up[0];
2561 
2562 		/* Have to change db_type after any pullupmsg */
2563 		DB_TYPE(mp) = M_CTL;
2564 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2565 		    mctl_present, ip_policy, zoneid);
2566 		return;
2567 
2568 	case IPPROTO_ESP:
2569 	case IPPROTO_AH: {
2570 		int ipsec_rc;
2571 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2572 
2573 		/*
2574 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2575 		 * We will re-use the IPSEC_IN if it is already present as
2576 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2577 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2578 		 * one and attach it in the front.
2579 		 */
2580 		if (ii != NULL) {
2581 			/*
2582 			 * ip_fanout_proto_again converts the ICMP errors
2583 			 * that come back from AH/ESP to M_DATA so that
2584 			 * if it is non-AH/ESP and we do a pullupmsg in
2585 			 * this function, it would work. Convert it back
2586 			 * to M_CTL before we send up as this is a ICMP
2587 			 * error. This could have been generated locally or
2588 			 * by some router. Validate the inner IPSEC
2589 			 * headers.
2590 			 *
2591 			 * NOTE : ill_index is used by ip_fanout_proto_again
2592 			 * to locate the ill.
2593 			 */
2594 			ASSERT(ill != NULL);
2595 			ii->ipsec_in_ill_index =
2596 			    ill->ill_phyint->phyint_ifindex;
2597 			ii->ipsec_in_rill_index =
2598 			    recv_ill->ill_phyint->phyint_ifindex;
2599 			DB_TYPE(first_mp->b_cont) = M_CTL;
2600 		} else {
2601 			/*
2602 			 * IPSEC_IN is not present. We attach a ipsec_in
2603 			 * message and send up to IPSEC for validating
2604 			 * and removing the IPSEC headers. Clear
2605 			 * ipsec_in_secure so that when we return
2606 			 * from IPSEC, we don't mistakenly think that this
2607 			 * is a secure packet came from the network.
2608 			 *
2609 			 * NOTE : ill_index is used by ip_fanout_proto_again
2610 			 * to locate the ill.
2611 			 */
2612 			ASSERT(first_mp == mp);
2613 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2614 			if (first_mp == NULL) {
2615 				freemsg(mp);
2616 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2617 				return;
2618 			}
2619 			ii = (ipsec_in_t *)first_mp->b_rptr;
2620 
2621 			/* This is not a secure packet */
2622 			ii->ipsec_in_secure = B_FALSE;
2623 			first_mp->b_cont = mp;
2624 			DB_TYPE(mp) = M_CTL;
2625 			ASSERT(ill != NULL);
2626 			ii->ipsec_in_ill_index =
2627 			    ill->ill_phyint->phyint_ifindex;
2628 			ii->ipsec_in_rill_index =
2629 			    recv_ill->ill_phyint->phyint_ifindex;
2630 		}
2631 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2632 
2633 		if (!ipsec_loaded(ipss)) {
2634 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2635 			return;
2636 		}
2637 
2638 		if (ipha->ipha_protocol == IPPROTO_ESP)
2639 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2640 		else
2641 			ipsec_rc = ipsecah_icmp_error(first_mp);
2642 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2643 			return;
2644 
2645 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2646 		return;
2647 	}
2648 	default:
2649 		/*
2650 		 * The ripha header is only used for the lookup and we
2651 		 * only set the src and dst addresses and protocol.
2652 		 */
2653 		ripha.ipha_src = ipha->ipha_dst;
2654 		ripha.ipha_dst = ipha->ipha_src;
2655 		ripha.ipha_protocol = ipha->ipha_protocol;
2656 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2657 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2658 		    ntohl(ipha->ipha_dst),
2659 		    icmph->icmph_type, icmph->icmph_code));
2660 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2661 			ipha_t *in_ipha;
2662 
2663 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2664 			    mp->b_wptr) {
2665 				if (!pullupmsg(mp, (uchar_t *)ipha +
2666 				    hdr_length + sizeof (ipha_t) -
2667 				    mp->b_rptr)) {
2668 					goto discard_pkt;
2669 				}
2670 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2671 				ipha = (ipha_t *)&icmph[1];
2672 			}
2673 			/*
2674 			 * Caller has verified that length has to be
2675 			 * at least the size of IP header.
2676 			 */
2677 			ASSERT(hdr_length >= sizeof (ipha_t));
2678 			/*
2679 			 * Check the sanity of the inner IP header like
2680 			 * we did for the outer header.
2681 			 */
2682 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2683 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2684 				goto discard_pkt;
2685 			}
2686 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2687 				goto discard_pkt;
2688 			}
2689 			/* Check for Self-encapsulated tunnels */
2690 			if (in_ipha->ipha_src == ipha->ipha_src &&
2691 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2692 
2693 				mp = icmp_inbound_self_encap_error(mp,
2694 				    iph_hdr_length, hdr_length);
2695 				if (mp == NULL)
2696 					goto discard_pkt;
2697 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2698 				ipha = (ipha_t *)&icmph[1];
2699 				hdr_length = IPH_HDR_LENGTH(ipha);
2700 				/*
2701 				 * The packet in error is self-encapsualted.
2702 				 * And we are finding it further encapsulated
2703 				 * which we could not have possibly generated.
2704 				 */
2705 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2706 					goto discard_pkt;
2707 				}
2708 				icmp_inbound_error_fanout(q, ill, first_mp,
2709 				    icmph, ipha, iph_hdr_length, hdr_length,
2710 				    mctl_present, ip_policy, recv_ill, zoneid);
2711 				return;
2712 			}
2713 		}
2714 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2715 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2716 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2717 		    ii != NULL &&
2718 		    ii->ipsec_in_loopback &&
2719 		    ii->ipsec_in_secure) {
2720 			/*
2721 			 * For IP tunnels that get a looped-back
2722 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2723 			 * reported new MTU to take into account the IPsec
2724 			 * headers protecting this configured tunnel.
2725 			 *
2726 			 * This allows the tunnel module (tun.c) to blindly
2727 			 * accept the MTU reported in an ICMP "too big"
2728 			 * message.
2729 			 *
2730 			 * Non-looped back ICMP messages will just be
2731 			 * handled by the security protocols (if needed),
2732 			 * and the first subsequent packet will hit this
2733 			 * path.
2734 			 */
2735 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2736 			    ipsec_in_extra_length(first_mp));
2737 		}
2738 		/* Have to change db_type after any pullupmsg */
2739 		DB_TYPE(mp) = M_CTL;
2740 
2741 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2742 		    ip_policy, recv_ill, zoneid);
2743 		return;
2744 	}
2745 	/* NOTREACHED */
2746 discard_pkt:
2747 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2748 drop_pkt:;
2749 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2750 	freemsg(first_mp);
2751 }
2752 
2753 /*
2754  * Common IP options parser.
2755  *
2756  * Setup routine: fill in *optp with options-parsing state, then
2757  * tail-call ipoptp_next to return the first option.
2758  */
2759 uint8_t
2760 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2761 {
2762 	uint32_t totallen; /* total length of all options */
2763 
2764 	totallen = ipha->ipha_version_and_hdr_length -
2765 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2766 	totallen <<= 2;
2767 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2768 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2769 	optp->ipoptp_flags = 0;
2770 	return (ipoptp_next(optp));
2771 }
2772 
2773 /*
2774  * Common IP options parser: extract next option.
2775  */
2776 uint8_t
2777 ipoptp_next(ipoptp_t *optp)
2778 {
2779 	uint8_t *end = optp->ipoptp_end;
2780 	uint8_t *cur = optp->ipoptp_next;
2781 	uint8_t opt, len, pointer;
2782 
2783 	/*
2784 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2785 	 * has been corrupted.
2786 	 */
2787 	ASSERT(cur <= end);
2788 
2789 	if (cur == end)
2790 		return (IPOPT_EOL);
2791 
2792 	opt = cur[IPOPT_OPTVAL];
2793 
2794 	/*
2795 	 * Skip any NOP options.
2796 	 */
2797 	while (opt == IPOPT_NOP) {
2798 		cur++;
2799 		if (cur == end)
2800 			return (IPOPT_EOL);
2801 		opt = cur[IPOPT_OPTVAL];
2802 	}
2803 
2804 	if (opt == IPOPT_EOL)
2805 		return (IPOPT_EOL);
2806 
2807 	/*
2808 	 * Option requiring a length.
2809 	 */
2810 	if ((cur + 1) >= end) {
2811 		optp->ipoptp_flags |= IPOPTP_ERROR;
2812 		return (IPOPT_EOL);
2813 	}
2814 	len = cur[IPOPT_OLEN];
2815 	if (len < 2) {
2816 		optp->ipoptp_flags |= IPOPTP_ERROR;
2817 		return (IPOPT_EOL);
2818 	}
2819 	optp->ipoptp_cur = cur;
2820 	optp->ipoptp_len = len;
2821 	optp->ipoptp_next = cur + len;
2822 	if (cur + len > end) {
2823 		optp->ipoptp_flags |= IPOPTP_ERROR;
2824 		return (IPOPT_EOL);
2825 	}
2826 
2827 	/*
2828 	 * For the options which require a pointer field, make sure
2829 	 * its there, and make sure it points to either something
2830 	 * inside this option, or the end of the option.
2831 	 */
2832 	switch (opt) {
2833 	case IPOPT_RR:
2834 	case IPOPT_TS:
2835 	case IPOPT_LSRR:
2836 	case IPOPT_SSRR:
2837 		if (len <= IPOPT_OFFSET) {
2838 			optp->ipoptp_flags |= IPOPTP_ERROR;
2839 			return (opt);
2840 		}
2841 		pointer = cur[IPOPT_OFFSET];
2842 		if (pointer - 1 > len) {
2843 			optp->ipoptp_flags |= IPOPTP_ERROR;
2844 			return (opt);
2845 		}
2846 		break;
2847 	}
2848 
2849 	/*
2850 	 * Sanity check the pointer field based on the type of the
2851 	 * option.
2852 	 */
2853 	switch (opt) {
2854 	case IPOPT_RR:
2855 	case IPOPT_SSRR:
2856 	case IPOPT_LSRR:
2857 		if (pointer < IPOPT_MINOFF_SR)
2858 			optp->ipoptp_flags |= IPOPTP_ERROR;
2859 		break;
2860 	case IPOPT_TS:
2861 		if (pointer < IPOPT_MINOFF_IT)
2862 			optp->ipoptp_flags |= IPOPTP_ERROR;
2863 		/*
2864 		 * Note that the Internet Timestamp option also
2865 		 * contains two four bit fields (the Overflow field,
2866 		 * and the Flag field), which follow the pointer
2867 		 * field.  We don't need to check that these fields
2868 		 * fall within the length of the option because this
2869 		 * was implicitely done above.  We've checked that the
2870 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2871 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2872 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2873 		 */
2874 		ASSERT(len > IPOPT_POS_OV_FLG);
2875 		break;
2876 	}
2877 
2878 	return (opt);
2879 }
2880 
2881 /*
2882  * Use the outgoing IP header to create an IP_OPTIONS option the way
2883  * it was passed down from the application.
2884  */
2885 int
2886 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2887 {
2888 	ipoptp_t	opts;
2889 	const uchar_t	*opt;
2890 	uint8_t		optval;
2891 	uint8_t		optlen;
2892 	uint32_t	len = 0;
2893 	uchar_t	*buf1 = buf;
2894 
2895 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2896 	len += IP_ADDR_LEN;
2897 	bzero(buf1, IP_ADDR_LEN);
2898 
2899 	/*
2900 	 * OK to cast away const here, as we don't store through the returned
2901 	 * opts.ipoptp_cur pointer.
2902 	 */
2903 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2904 	    optval != IPOPT_EOL;
2905 	    optval = ipoptp_next(&opts)) {
2906 		int	off;
2907 
2908 		opt = opts.ipoptp_cur;
2909 		optlen = opts.ipoptp_len;
2910 		switch (optval) {
2911 		case IPOPT_SSRR:
2912 		case IPOPT_LSRR:
2913 
2914 			/*
2915 			 * Insert ipha_dst as the first entry in the source
2916 			 * route and move down the entries on step.
2917 			 * The last entry gets placed at buf1.
2918 			 */
2919 			buf[IPOPT_OPTVAL] = optval;
2920 			buf[IPOPT_OLEN] = optlen;
2921 			buf[IPOPT_OFFSET] = optlen;
2922 
2923 			off = optlen - IP_ADDR_LEN;
2924 			if (off < 0) {
2925 				/* No entries in source route */
2926 				break;
2927 			}
2928 			/* Last entry in source route */
2929 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2930 			off -= IP_ADDR_LEN;
2931 
2932 			while (off > 0) {
2933 				bcopy(opt + off,
2934 				    buf + off + IP_ADDR_LEN,
2935 				    IP_ADDR_LEN);
2936 				off -= IP_ADDR_LEN;
2937 			}
2938 			/* ipha_dst into first slot */
2939 			bcopy(&ipha->ipha_dst,
2940 			    buf + off + IP_ADDR_LEN,
2941 			    IP_ADDR_LEN);
2942 			buf += optlen;
2943 			len += optlen;
2944 			break;
2945 
2946 		case IPOPT_COMSEC:
2947 		case IPOPT_SECURITY:
2948 			/* if passing up a label is not ok, then remove */
2949 			if (is_system_labeled())
2950 				break;
2951 			/* FALLTHROUGH */
2952 		default:
2953 			bcopy(opt, buf, optlen);
2954 			buf += optlen;
2955 			len += optlen;
2956 			break;
2957 		}
2958 	}
2959 done:
2960 	/* Pad the resulting options */
2961 	while (len & 0x3) {
2962 		*buf++ = IPOPT_EOL;
2963 		len++;
2964 	}
2965 	return (len);
2966 }
2967 
2968 /*
2969  * Update any record route or timestamp options to include this host.
2970  * Reverse any source route option.
2971  * This routine assumes that the options are well formed i.e. that they
2972  * have already been checked.
2973  */
2974 static void
2975 icmp_options_update(ipha_t *ipha)
2976 {
2977 	ipoptp_t	opts;
2978 	uchar_t		*opt;
2979 	uint8_t		optval;
2980 	ipaddr_t	src;		/* Our local address */
2981 	ipaddr_t	dst;
2982 
2983 	ip2dbg(("icmp_options_update\n"));
2984 	src = ipha->ipha_src;
2985 	dst = ipha->ipha_dst;
2986 
2987 	for (optval = ipoptp_first(&opts, ipha);
2988 	    optval != IPOPT_EOL;
2989 	    optval = ipoptp_next(&opts)) {
2990 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2991 		opt = opts.ipoptp_cur;
2992 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2993 		    optval, opts.ipoptp_len));
2994 		switch (optval) {
2995 			int off1, off2;
2996 		case IPOPT_SSRR:
2997 		case IPOPT_LSRR:
2998 			/*
2999 			 * Reverse the source route.  The first entry
3000 			 * should be the next to last one in the current
3001 			 * source route (the last entry is our address).
3002 			 * The last entry should be the final destination.
3003 			 */
3004 			off1 = IPOPT_MINOFF_SR - 1;
3005 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3006 			if (off2 < 0) {
3007 				/* No entries in source route */
3008 				ip1dbg((
3009 				    "icmp_options_update: bad src route\n"));
3010 				break;
3011 			}
3012 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3013 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3014 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3015 			off2 -= IP_ADDR_LEN;
3016 
3017 			while (off1 < off2) {
3018 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3019 				bcopy((char *)opt + off2, (char *)opt + off1,
3020 				    IP_ADDR_LEN);
3021 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3022 				off1 += IP_ADDR_LEN;
3023 				off2 -= IP_ADDR_LEN;
3024 			}
3025 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3026 			break;
3027 		}
3028 	}
3029 }
3030 
3031 /*
3032  * Process received ICMP Redirect messages.
3033  */
3034 static void
3035 icmp_redirect(ill_t *ill, mblk_t *mp)
3036 {
3037 	ipha_t	*ipha;
3038 	int	iph_hdr_length;
3039 	icmph_t	*icmph;
3040 	ipha_t	*ipha_err;
3041 	ire_t	*ire;
3042 	ire_t	*prev_ire;
3043 	ire_t	*save_ire;
3044 	ipaddr_t  src, dst, gateway;
3045 	iulp_t	ulp_info = { 0 };
3046 	int	error;
3047 	ip_stack_t *ipst;
3048 
3049 	ASSERT(ill != NULL);
3050 	ipst = ill->ill_ipst;
3051 
3052 	ipha = (ipha_t *)mp->b_rptr;
3053 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3054 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3055 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3056 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3057 		freemsg(mp);
3058 		return;
3059 	}
3060 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3061 	ipha_err = (ipha_t *)&icmph[1];
3062 	src = ipha->ipha_src;
3063 	dst = ipha_err->ipha_dst;
3064 	gateway = icmph->icmph_rd_gateway;
3065 	/* Make sure the new gateway is reachable somehow. */
3066 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3067 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3068 	/*
3069 	 * Make sure we had a route for the dest in question and that
3070 	 * that route was pointing to the old gateway (the source of the
3071 	 * redirect packet.)
3072 	 */
3073 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3074 	    NULL, MATCH_IRE_GW, ipst);
3075 	/*
3076 	 * Check that
3077 	 *	the redirect was not from ourselves
3078 	 *	the new gateway and the old gateway are directly reachable
3079 	 */
3080 	if (!prev_ire ||
3081 	    !ire ||
3082 	    ire->ire_type == IRE_LOCAL) {
3083 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3084 		freemsg(mp);
3085 		if (ire != NULL)
3086 			ire_refrele(ire);
3087 		if (prev_ire != NULL)
3088 			ire_refrele(prev_ire);
3089 		return;
3090 	}
3091 
3092 	/*
3093 	 * Should we use the old ULP info to create the new gateway?  From
3094 	 * a user's perspective, we should inherit the info so that it
3095 	 * is a "smooth" transition.  If we do not do that, then new
3096 	 * connections going thru the new gateway will have no route metrics,
3097 	 * which is counter-intuitive to user.  From a network point of
3098 	 * view, this may or may not make sense even though the new gateway
3099 	 * is still directly connected to us so the route metrics should not
3100 	 * change much.
3101 	 *
3102 	 * But if the old ire_uinfo is not initialized, we do another
3103 	 * recursive lookup on the dest using the new gateway.  There may
3104 	 * be a route to that.  If so, use it to initialize the redirect
3105 	 * route.
3106 	 */
3107 	if (prev_ire->ire_uinfo.iulp_set) {
3108 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3109 	} else {
3110 		ire_t *tmp_ire;
3111 		ire_t *sire;
3112 
3113 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3114 		    ALL_ZONES, 0, NULL,
3115 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3116 		    ipst);
3117 		if (sire != NULL) {
3118 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3119 			/*
3120 			 * If sire != NULL, ire_ftable_lookup() should not
3121 			 * return a NULL value.
3122 			 */
3123 			ASSERT(tmp_ire != NULL);
3124 			ire_refrele(tmp_ire);
3125 			ire_refrele(sire);
3126 		} else if (tmp_ire != NULL) {
3127 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3128 			    sizeof (iulp_t));
3129 			ire_refrele(tmp_ire);
3130 		}
3131 	}
3132 	if (prev_ire->ire_type == IRE_CACHE)
3133 		ire_delete(prev_ire);
3134 	ire_refrele(prev_ire);
3135 	/*
3136 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3137 	 * require TOS routing
3138 	 */
3139 	switch (icmph->icmph_code) {
3140 	case 0:
3141 	case 1:
3142 		/* TODO: TOS specificity for cases 2 and 3 */
3143 	case 2:
3144 	case 3:
3145 		break;
3146 	default:
3147 		freemsg(mp);
3148 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3149 		ire_refrele(ire);
3150 		return;
3151 	}
3152 	/*
3153 	 * Create a Route Association.  This will allow us to remember that
3154 	 * someone we believe told us to use the particular gateway.
3155 	 */
3156 	save_ire = ire;
3157 	ire = ire_create(
3158 		(uchar_t *)&dst,			/* dest addr */
3159 		(uchar_t *)&ip_g_all_ones,		/* mask */
3160 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3161 		(uchar_t *)&gateway,			/* gateway addr */
3162 		NULL,					/* no in_srcaddr */
3163 		&save_ire->ire_max_frag,		/* max frag */
3164 		NULL,					/* Fast Path header */
3165 		NULL,					/* no rfq */
3166 		NULL,					/* no stq */
3167 		IRE_HOST,
3168 		NULL,
3169 		NULL,
3170 		NULL,
3171 		0,
3172 		0,
3173 		0,
3174 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3175 		&ulp_info,
3176 		NULL,
3177 		NULL,
3178 		ipst);
3179 
3180 	if (ire == NULL) {
3181 		freemsg(mp);
3182 		ire_refrele(save_ire);
3183 		return;
3184 	}
3185 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3186 	ire_refrele(save_ire);
3187 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3188 
3189 	if (error == 0) {
3190 		ire_refrele(ire);		/* Held in ire_add_v4 */
3191 		/* tell routing sockets that we received a redirect */
3192 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3193 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3194 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3195 	}
3196 
3197 	/*
3198 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3199 	 * This together with the added IRE has the effect of
3200 	 * modifying an existing redirect.
3201 	 */
3202 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3203 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3204 	if (prev_ire != NULL) {
3205 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3206 			ire_delete(prev_ire);
3207 		ire_refrele(prev_ire);
3208 	}
3209 
3210 	freemsg(mp);
3211 }
3212 
3213 /*
3214  * Generate an ICMP parameter problem message.
3215  */
3216 static void
3217 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3218 	ip_stack_t *ipst)
3219 {
3220 	icmph_t	icmph;
3221 	boolean_t mctl_present;
3222 	mblk_t *first_mp;
3223 
3224 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3225 
3226 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3227 		if (mctl_present)
3228 			freeb(first_mp);
3229 		return;
3230 	}
3231 
3232 	bzero(&icmph, sizeof (icmph_t));
3233 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3234 	icmph.icmph_pp_ptr = ptr;
3235 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3236 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3237 	    ipst);
3238 }
3239 
3240 /*
3241  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3242  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3243  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3244  * an icmp error packet can be sent.
3245  * Assigns an appropriate source address to the packet. If ipha_dst is
3246  * one of our addresses use it for source. Otherwise pick a source based
3247  * on a route lookup back to ipha_src.
3248  * Note that ipha_src must be set here since the
3249  * packet is likely to arrive on an ill queue in ip_wput() which will
3250  * not set a source address.
3251  */
3252 static void
3253 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3254     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3255 {
3256 	ipaddr_t dst;
3257 	icmph_t	*icmph;
3258 	ipha_t	*ipha;
3259 	uint_t	len_needed;
3260 	size_t	msg_len;
3261 	mblk_t	*mp1;
3262 	ipaddr_t src;
3263 	ire_t	*ire;
3264 	mblk_t *ipsec_mp;
3265 	ipsec_out_t	*io = NULL;
3266 	boolean_t xmit_if_on = B_FALSE;
3267 
3268 	if (mctl_present) {
3269 		/*
3270 		 * If it is :
3271 		 *
3272 		 * 1) a IPSEC_OUT, then this is caused by outbound
3273 		 *    datagram originating on this host. IPSEC processing
3274 		 *    may or may not have been done. Refer to comments above
3275 		 *    icmp_inbound_error_fanout for details.
3276 		 *
3277 		 * 2) a IPSEC_IN if we are generating a icmp_message
3278 		 *    for an incoming datagram destined for us i.e called
3279 		 *    from ip_fanout_send_icmp.
3280 		 */
3281 		ipsec_info_t *in;
3282 		ipsec_mp = mp;
3283 		mp = ipsec_mp->b_cont;
3284 
3285 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3286 		ipha = (ipha_t *)mp->b_rptr;
3287 
3288 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3289 		    in->ipsec_info_type == IPSEC_IN);
3290 
3291 		if (in->ipsec_info_type == IPSEC_IN) {
3292 			/*
3293 			 * Convert the IPSEC_IN to IPSEC_OUT.
3294 			 */
3295 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3296 				BUMP_MIB(&ipst->ips_ip_mib,
3297 				    ipIfStatsOutDiscards);
3298 				return;
3299 			}
3300 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3301 		} else {
3302 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3303 			io = (ipsec_out_t *)in;
3304 			if (io->ipsec_out_xmit_if)
3305 				xmit_if_on = B_TRUE;
3306 			/*
3307 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3308 			 * ire lookup.
3309 			 */
3310 			io->ipsec_out_proc_begin = B_FALSE;
3311 		}
3312 		ASSERT(zoneid == io->ipsec_out_zoneid);
3313 		ASSERT(zoneid != ALL_ZONES);
3314 	} else {
3315 		/*
3316 		 * This is in clear. The icmp message we are building
3317 		 * here should go out in clear.
3318 		 *
3319 		 * Pardon the convolution of it all, but it's easier to
3320 		 * allocate a "use cleartext" IPSEC_IN message and convert
3321 		 * it than it is to allocate a new one.
3322 		 */
3323 		ipsec_in_t *ii;
3324 		ASSERT(DB_TYPE(mp) == M_DATA);
3325 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3326 		if (ipsec_mp == NULL) {
3327 			freemsg(mp);
3328 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3329 			return;
3330 		}
3331 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3332 
3333 		/* This is not a secure packet */
3334 		ii->ipsec_in_secure = B_FALSE;
3335 		/*
3336 		 * For trusted extensions using a shared IP address we can
3337 		 * send using any zoneid.
3338 		 */
3339 		if (zoneid == ALL_ZONES)
3340 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3341 		else
3342 			ii->ipsec_in_zoneid = zoneid;
3343 		ipsec_mp->b_cont = mp;
3344 		ipha = (ipha_t *)mp->b_rptr;
3345 		/*
3346 		 * Convert the IPSEC_IN to IPSEC_OUT.
3347 		 */
3348 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3349 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3350 			return;
3351 		}
3352 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3353 	}
3354 
3355 	/* Remember our eventual destination */
3356 	dst = ipha->ipha_src;
3357 
3358 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3359 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3360 	if (ire != NULL &&
3361 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3362 		src = ipha->ipha_dst;
3363 	} else if (!xmit_if_on) {
3364 		if (ire != NULL)
3365 			ire_refrele(ire);
3366 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3367 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3368 		    ipst);
3369 		if (ire == NULL) {
3370 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3371 			freemsg(ipsec_mp);
3372 			return;
3373 		}
3374 		src = ire->ire_src_addr;
3375 	} else {
3376 		ipif_t	*ipif = NULL;
3377 		ill_t	*ill;
3378 		/*
3379 		 * This must be an ICMP error coming from
3380 		 * ip_mrtun_forward(). The src addr should
3381 		 * be equal to the IP-addr of the outgoing
3382 		 * interface.
3383 		 */
3384 		if (io == NULL) {
3385 			/* This is not a IPSEC_OUT type control msg */
3386 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3387 			freemsg(ipsec_mp);
3388 			return;
3389 		}
3390 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3391 		    NULL, NULL, NULL, NULL, ipst);
3392 		if (ill != NULL) {
3393 			ipif = ipif_get_next_ipif(NULL, ill);
3394 			ill_refrele(ill);
3395 		}
3396 		if (ipif == NULL) {
3397 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3398 			freemsg(ipsec_mp);
3399 			return;
3400 		}
3401 		src = ipif->ipif_src_addr;
3402 		ipif_refrele(ipif);
3403 	}
3404 
3405 	if (ire != NULL)
3406 		ire_refrele(ire);
3407 
3408 	/*
3409 	 * Check if we can send back more then 8 bytes in addition
3410 	 * to the IP header. We will include as much as 64 bytes.
3411 	 */
3412 	len_needed = IPH_HDR_LENGTH(ipha);
3413 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3414 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3415 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3416 	}
3417 	len_needed += ipst->ips_ip_icmp_return;
3418 	msg_len = msgdsize(mp);
3419 	if (msg_len > len_needed) {
3420 		(void) adjmsg(mp, len_needed - msg_len);
3421 		msg_len = len_needed;
3422 	}
3423 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3424 	if (mp1 == NULL) {
3425 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3426 		freemsg(ipsec_mp);
3427 		return;
3428 	}
3429 	/*
3430 	 * On an unlabeled system, dblks don't necessarily have creds.
3431 	 */
3432 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3433 	if (DB_CRED(mp) != NULL)
3434 		mblk_setcred(mp1, DB_CRED(mp));
3435 	mp1->b_cont = mp;
3436 	mp = mp1;
3437 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3438 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3439 	    io->ipsec_out_type == IPSEC_OUT);
3440 	ipsec_mp->b_cont = mp;
3441 
3442 	/*
3443 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3444 	 * node generates be accepted in peace by all on-host destinations.
3445 	 * If we do NOT assume that all on-host destinations trust
3446 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3447 	 * (Look for ipsec_out_icmp_loopback).
3448 	 */
3449 	io->ipsec_out_icmp_loopback = B_TRUE;
3450 
3451 	ipha = (ipha_t *)mp->b_rptr;
3452 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3453 	*ipha = icmp_ipha;
3454 	ipha->ipha_src = src;
3455 	ipha->ipha_dst = dst;
3456 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3457 	msg_len += sizeof (icmp_ipha) + len;
3458 	if (msg_len > IP_MAXPACKET) {
3459 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3460 		msg_len = IP_MAXPACKET;
3461 	}
3462 	ipha->ipha_length = htons((uint16_t)msg_len);
3463 	icmph = (icmph_t *)&ipha[1];
3464 	bcopy(stuff, icmph, len);
3465 	icmph->icmph_checksum = 0;
3466 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3467 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3468 	put(q, ipsec_mp);
3469 }
3470 
3471 /*
3472  * Determine if an ICMP error packet can be sent given the rate limit.
3473  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3474  * in milliseconds) and a burst size. Burst size number of packets can
3475  * be sent arbitrarely closely spaced.
3476  * The state is tracked using two variables to implement an approximate
3477  * token bucket filter:
3478  *	icmp_pkt_err_last - lbolt value when the last burst started
3479  *	icmp_pkt_err_sent - number of packets sent in current burst
3480  */
3481 boolean_t
3482 icmp_err_rate_limit(ip_stack_t *ipst)
3483 {
3484 	clock_t now = TICK_TO_MSEC(lbolt);
3485 	uint_t refilled; /* Number of packets refilled in tbf since last */
3486 	/* Guard against changes by loading into local variable */
3487 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3488 
3489 	if (err_interval == 0)
3490 		return (B_FALSE);
3491 
3492 	if (ipst->ips_icmp_pkt_err_last > now) {
3493 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3494 		ipst->ips_icmp_pkt_err_last = 0;
3495 		ipst->ips_icmp_pkt_err_sent = 0;
3496 	}
3497 	/*
3498 	 * If we are in a burst update the token bucket filter.
3499 	 * Update the "last" time to be close to "now" but make sure
3500 	 * we don't loose precision.
3501 	 */
3502 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3503 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3504 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3505 			ipst->ips_icmp_pkt_err_sent = 0;
3506 		} else {
3507 			ipst->ips_icmp_pkt_err_sent -= refilled;
3508 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3509 		}
3510 	}
3511 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3512 		/* Start of new burst */
3513 		ipst->ips_icmp_pkt_err_last = now;
3514 	}
3515 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3516 		ipst->ips_icmp_pkt_err_sent++;
3517 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3518 			    ipst->ips_icmp_pkt_err_sent));
3519 		return (B_FALSE);
3520 	}
3521 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3522 	return (B_TRUE);
3523 }
3524 
3525 /*
3526  * Check if it is ok to send an IPv4 ICMP error packet in
3527  * response to the IPv4 packet in mp.
3528  * Free the message and return null if no
3529  * ICMP error packet should be sent.
3530  */
3531 static mblk_t *
3532 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3533 {
3534 	icmph_t	*icmph;
3535 	ipha_t	*ipha;
3536 	uint_t	len_needed;
3537 	ire_t	*src_ire;
3538 	ire_t	*dst_ire;
3539 
3540 	if (!mp)
3541 		return (NULL);
3542 	ipha = (ipha_t *)mp->b_rptr;
3543 	if (ip_csum_hdr(ipha)) {
3544 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3545 		freemsg(mp);
3546 		return (NULL);
3547 	}
3548 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3549 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3550 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3551 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3552 	if (src_ire != NULL || dst_ire != NULL ||
3553 	    CLASSD(ipha->ipha_dst) ||
3554 	    CLASSD(ipha->ipha_src) ||
3555 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3556 		/* Note: only errors to the fragment with offset 0 */
3557 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3558 		freemsg(mp);
3559 		if (src_ire != NULL)
3560 			ire_refrele(src_ire);
3561 		if (dst_ire != NULL)
3562 			ire_refrele(dst_ire);
3563 		return (NULL);
3564 	}
3565 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3566 		/*
3567 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3568 		 * errors in response to any ICMP errors.
3569 		 */
3570 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3571 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3572 			if (!pullupmsg(mp, len_needed)) {
3573 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3574 				freemsg(mp);
3575 				return (NULL);
3576 			}
3577 			ipha = (ipha_t *)mp->b_rptr;
3578 		}
3579 		icmph = (icmph_t *)
3580 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3581 		switch (icmph->icmph_type) {
3582 		case ICMP_DEST_UNREACHABLE:
3583 		case ICMP_SOURCE_QUENCH:
3584 		case ICMP_TIME_EXCEEDED:
3585 		case ICMP_PARAM_PROBLEM:
3586 		case ICMP_REDIRECT:
3587 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3588 			freemsg(mp);
3589 			return (NULL);
3590 		default:
3591 			break;
3592 		}
3593 	}
3594 	/*
3595 	 * If this is a labeled system, then check to see if we're allowed to
3596 	 * send a response to this particular sender.  If not, then just drop.
3597 	 */
3598 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3599 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3600 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3601 		freemsg(mp);
3602 		return (NULL);
3603 	}
3604 	if (icmp_err_rate_limit(ipst)) {
3605 		/*
3606 		 * Only send ICMP error packets every so often.
3607 		 * This should be done on a per port/source basis,
3608 		 * but for now this will suffice.
3609 		 */
3610 		freemsg(mp);
3611 		return (NULL);
3612 	}
3613 	return (mp);
3614 }
3615 
3616 /*
3617  * Generate an ICMP redirect message.
3618  */
3619 static void
3620 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3621 {
3622 	icmph_t	icmph;
3623 
3624 	/*
3625 	 * We are called from ip_rput where we could
3626 	 * not have attached an IPSEC_IN.
3627 	 */
3628 	ASSERT(mp->b_datap->db_type == M_DATA);
3629 
3630 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3631 		return;
3632 	}
3633 
3634 	bzero(&icmph, sizeof (icmph_t));
3635 	icmph.icmph_type = ICMP_REDIRECT;
3636 	icmph.icmph_code = 1;
3637 	icmph.icmph_rd_gateway = gateway;
3638 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3639 	/* Redirects sent by router, and router is global zone */
3640 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3641 }
3642 
3643 /*
3644  * Generate an ICMP time exceeded message.
3645  */
3646 void
3647 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3648     ip_stack_t *ipst)
3649 {
3650 	icmph_t	icmph;
3651 	boolean_t mctl_present;
3652 	mblk_t *first_mp;
3653 
3654 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3655 
3656 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3657 		if (mctl_present)
3658 			freeb(first_mp);
3659 		return;
3660 	}
3661 
3662 	bzero(&icmph, sizeof (icmph_t));
3663 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3664 	icmph.icmph_code = code;
3665 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3666 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3667 	    ipst);
3668 }
3669 
3670 /*
3671  * Generate an ICMP unreachable message.
3672  */
3673 void
3674 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3675     ip_stack_t *ipst)
3676 {
3677 	icmph_t	icmph;
3678 	mblk_t *first_mp;
3679 	boolean_t mctl_present;
3680 
3681 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3682 
3683 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3684 		if (mctl_present)
3685 			freeb(first_mp);
3686 		return;
3687 	}
3688 
3689 	bzero(&icmph, sizeof (icmph_t));
3690 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3691 	icmph.icmph_code = code;
3692 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3693 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3694 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3695 	    zoneid, ipst);
3696 }
3697 
3698 /*
3699  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3700  * duplicate.  As long as someone else holds the address, the interface will
3701  * stay down.  When that conflict goes away, the interface is brought back up.
3702  * This is done so that accidental shutdowns of addresses aren't made
3703  * permanent.  Your server will recover from a failure.
3704  *
3705  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3706  * user space process (dhcpagent).
3707  *
3708  * Recovery completes if ARP reports that the address is now ours (via
3709  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3710  *
3711  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3712  */
3713 static void
3714 ipif_dup_recovery(void *arg)
3715 {
3716 	ipif_t *ipif = arg;
3717 	ill_t *ill = ipif->ipif_ill;
3718 	mblk_t *arp_add_mp;
3719 	mblk_t *arp_del_mp;
3720 	area_t *area;
3721 	ip_stack_t *ipst = ill->ill_ipst;
3722 
3723 	ipif->ipif_recovery_id = 0;
3724 
3725 	/*
3726 	 * No lock needed for moving or condemned check, as this is just an
3727 	 * optimization.
3728 	 */
3729 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3730 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3731 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3732 		/* No reason to try to bring this address back. */
3733 		return;
3734 	}
3735 
3736 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3737 		goto alloc_fail;
3738 
3739 	if (ipif->ipif_arp_del_mp == NULL) {
3740 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3741 			goto alloc_fail;
3742 		ipif->ipif_arp_del_mp = arp_del_mp;
3743 	}
3744 
3745 	/* Setting the 'unverified' flag restarts DAD */
3746 	area = (area_t *)arp_add_mp->b_rptr;
3747 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3748 	    ACE_F_UNVERIFIED;
3749 	putnext(ill->ill_rq, arp_add_mp);
3750 	return;
3751 
3752 alloc_fail:
3753 	/*
3754 	 * On allocation failure, just restart the timer.  Note that the ipif
3755 	 * is down here, so no other thread could be trying to start a recovery
3756 	 * timer.  The ill_lock protects the condemned flag and the recovery
3757 	 * timer ID.
3758 	 */
3759 	freemsg(arp_add_mp);
3760 	mutex_enter(&ill->ill_lock);
3761 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3762 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3763 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3764 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3765 	}
3766 	mutex_exit(&ill->ill_lock);
3767 }
3768 
3769 /*
3770  * This is for exclusive changes due to ARP.  Either tear down an interface due
3771  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3772  */
3773 /* ARGSUSED */
3774 static void
3775 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3776 {
3777 	ill_t	*ill = rq->q_ptr;
3778 	arh_t *arh;
3779 	ipaddr_t src;
3780 	ipif_t	*ipif;
3781 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3782 	char hbuf[MAC_STR_LEN];
3783 	char sbuf[INET_ADDRSTRLEN];
3784 	const char *failtype;
3785 	boolean_t bring_up;
3786 	ip_stack_t *ipst = ill->ill_ipst;
3787 
3788 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3789 	case AR_CN_READY:
3790 		failtype = NULL;
3791 		bring_up = B_TRUE;
3792 		break;
3793 	case AR_CN_FAILED:
3794 		failtype = "in use";
3795 		bring_up = B_FALSE;
3796 		break;
3797 	default:
3798 		failtype = "claimed";
3799 		bring_up = B_FALSE;
3800 		break;
3801 	}
3802 
3803 	arh = (arh_t *)mp->b_cont->b_rptr;
3804 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3805 
3806 	/* Handle failures due to probes */
3807 	if (src == 0) {
3808 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3809 		    IP_ADDR_LEN);
3810 	}
3811 
3812 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3813 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3814 	    sizeof (hbuf));
3815 	(void) ip_dot_addr(src, sbuf);
3816 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3817 
3818 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3819 		    ipif->ipif_lcl_addr != src) {
3820 			continue;
3821 		}
3822 
3823 		/*
3824 		 * If we failed on a recovery probe, then restart the timer to
3825 		 * try again later.
3826 		 */
3827 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3828 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3829 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3830 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3831 		    ipst->ips_ip_dup_recovery > 0 &&
3832 		    ipif->ipif_recovery_id == 0) {
3833 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3834 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3835 			continue;
3836 		}
3837 
3838 		/*
3839 		 * If what we're trying to do has already been done, then do
3840 		 * nothing.
3841 		 */
3842 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3843 			continue;
3844 
3845 		if (ipif->ipif_id != 0) {
3846 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3847 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3848 			    ipif->ipif_id);
3849 		}
3850 		if (failtype == NULL) {
3851 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3852 			    ibuf);
3853 		} else {
3854 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3855 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3856 		}
3857 
3858 		if (bring_up) {
3859 			ASSERT(ill->ill_dl_up);
3860 			/*
3861 			 * Free up the ARP delete message so we can allocate
3862 			 * a fresh one through the normal path.
3863 			 */
3864 			freemsg(ipif->ipif_arp_del_mp);
3865 			ipif->ipif_arp_del_mp = NULL;
3866 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3867 			    EINPROGRESS) {
3868 				ipif->ipif_addr_ready = 1;
3869 				(void) ipif_up_done(ipif);
3870 			}
3871 			continue;
3872 		}
3873 
3874 		mutex_enter(&ill->ill_lock);
3875 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3876 		ipif->ipif_flags |= IPIF_DUPLICATE;
3877 		ill->ill_ipif_dup_count++;
3878 		mutex_exit(&ill->ill_lock);
3879 		/*
3880 		 * Already exclusive on the ill; no need to handle deferred
3881 		 * processing here.
3882 		 */
3883 		(void) ipif_down(ipif, NULL, NULL);
3884 		ipif_down_tail(ipif);
3885 		mutex_enter(&ill->ill_lock);
3886 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3887 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3888 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3889 		    ipst->ips_ip_dup_recovery > 0) {
3890 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3891 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3892 		}
3893 		mutex_exit(&ill->ill_lock);
3894 	}
3895 	freemsg(mp);
3896 }
3897 
3898 /* ARGSUSED */
3899 static void
3900 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3901 {
3902 	ill_t	*ill = rq->q_ptr;
3903 	arh_t *arh;
3904 	ipaddr_t src;
3905 	ipif_t	*ipif;
3906 
3907 	arh = (arh_t *)mp->b_cont->b_rptr;
3908 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3909 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3910 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3911 			(void) ipif_resolver_up(ipif, Res_act_defend);
3912 	}
3913 	freemsg(mp);
3914 }
3915 
3916 /*
3917  * News from ARP.  ARP sends notification of interesting events down
3918  * to its clients using M_CTL messages with the interesting ARP packet
3919  * attached via b_cont.
3920  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3921  * queue as opposed to ARP sending the message to all the clients, i.e. all
3922  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3923  * table if a cache IRE is found to delete all the entries for the address in
3924  * the packet.
3925  */
3926 static void
3927 ip_arp_news(queue_t *q, mblk_t *mp)
3928 {
3929 	arcn_t		*arcn;
3930 	arh_t		*arh;
3931 	ire_t		*ire = NULL;
3932 	char		hbuf[MAC_STR_LEN];
3933 	char		sbuf[INET_ADDRSTRLEN];
3934 	ipaddr_t	src;
3935 	in6_addr_t	v6src;
3936 	boolean_t	isv6 = B_FALSE;
3937 	ipif_t		*ipif;
3938 	ill_t		*ill;
3939 	ip_stack_t	*ipst;
3940 
3941 	if (CONN_Q(q)) {
3942 		conn_t *connp = Q_TO_CONN(q);
3943 
3944 		ipst = connp->conn_netstack->netstack_ip;
3945 	} else {
3946 		ill_t *ill = (ill_t *)q->q_ptr;
3947 
3948 		ipst = ill->ill_ipst;
3949 	}
3950 
3951 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3952 		if (q->q_next) {
3953 			putnext(q, mp);
3954 		} else
3955 			freemsg(mp);
3956 		return;
3957 	}
3958 	arh = (arh_t *)mp->b_cont->b_rptr;
3959 	/* Is it one we are interested in? */
3960 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3961 		isv6 = B_TRUE;
3962 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3963 		    IPV6_ADDR_LEN);
3964 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3965 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3966 		    IP_ADDR_LEN);
3967 	} else {
3968 		freemsg(mp);
3969 		return;
3970 	}
3971 
3972 	ill = q->q_ptr;
3973 
3974 	arcn = (arcn_t *)mp->b_rptr;
3975 	switch (arcn->arcn_code) {
3976 	case AR_CN_BOGON:
3977 		/*
3978 		 * Someone is sending ARP packets with a source protocol
3979 		 * address that we have published and for which we believe our
3980 		 * entry is authoritative and (when ill_arp_extend is set)
3981 		 * verified to be unique on the network.
3982 		 *
3983 		 * The ARP module internally handles the cases where the sender
3984 		 * is just probing (for DAD) and where the hardware address of
3985 		 * a non-authoritative entry has changed.  Thus, these are the
3986 		 * real conflicts, and we have to do resolution.
3987 		 *
3988 		 * We back away quickly from the address if it's from DHCP or
3989 		 * otherwise temporary and hasn't been used recently (or at
3990 		 * all).  We'd like to include "deprecated" addresses here as
3991 		 * well (as there's no real reason to defend something we're
3992 		 * discarding), but IPMP "reuses" this flag to mean something
3993 		 * other than the standard meaning.
3994 		 *
3995 		 * If the ARP module above is not extended (meaning that it
3996 		 * doesn't know how to defend the address), then we just log
3997 		 * the problem as we always did and continue on.  It's not
3998 		 * right, but there's little else we can do, and those old ATM
3999 		 * users are going away anyway.
4000 		 */
4001 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4002 		    hbuf, sizeof (hbuf));
4003 		(void) ip_dot_addr(src, sbuf);
4004 		if (isv6) {
4005 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4006 			    ipst);
4007 		} else {
4008 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4009 		}
4010 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4011 			uint32_t now;
4012 			uint32_t maxage;
4013 			clock_t lused;
4014 			uint_t maxdefense;
4015 			uint_t defs;
4016 
4017 			/*
4018 			 * First, figure out if this address hasn't been used
4019 			 * in a while.  If it hasn't, then it's a better
4020 			 * candidate for abandoning.
4021 			 */
4022 			ipif = ire->ire_ipif;
4023 			ASSERT(ipif != NULL);
4024 			now = gethrestime_sec();
4025 			maxage = now - ire->ire_create_time;
4026 			if (maxage > ipst->ips_ip_max_temp_idle)
4027 				maxage = ipst->ips_ip_max_temp_idle;
4028 			lused = drv_hztousec(ddi_get_lbolt() -
4029 			    ire->ire_last_used_time) / MICROSEC + 1;
4030 			if (lused >= maxage && (ipif->ipif_flags &
4031 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4032 				maxdefense = ipst->ips_ip_max_temp_defend;
4033 			else
4034 				maxdefense = ipst->ips_ip_max_defend;
4035 
4036 			/*
4037 			 * Now figure out how many times we've defended
4038 			 * ourselves.  Ignore defenses that happened long in
4039 			 * the past.
4040 			 */
4041 			mutex_enter(&ire->ire_lock);
4042 			if ((defs = ire->ire_defense_count) > 0 &&
4043 			    now - ire->ire_defense_time >
4044 			    ipst->ips_ip_defend_interval) {
4045 				ire->ire_defense_count = defs = 0;
4046 			}
4047 			ire->ire_defense_count++;
4048 			ire->ire_defense_time = now;
4049 			mutex_exit(&ire->ire_lock);
4050 			ill_refhold(ill);
4051 			ire_refrele(ire);
4052 
4053 			/*
4054 			 * If we've defended ourselves too many times already,
4055 			 * then give up and tear down the interface(s) using
4056 			 * this address.  Otherwise, defend by sending out a
4057 			 * gratuitous ARP.
4058 			 */
4059 			if (defs >= maxdefense && ill->ill_arp_extend) {
4060 				(void) qwriter_ip(NULL, ill, q, mp,
4061 				    ip_arp_excl, CUR_OP, B_FALSE);
4062 			} else {
4063 				cmn_err(CE_WARN,
4064 				    "node %s is using our IP address %s on %s",
4065 				    hbuf, sbuf, ill->ill_name);
4066 				/*
4067 				 * If this is an old (ATM) ARP module, then
4068 				 * don't try to defend the address.  Remain
4069 				 * compatible with the old behavior.  Defend
4070 				 * only with new ARP.
4071 				 */
4072 				if (ill->ill_arp_extend) {
4073 					(void) qwriter_ip(NULL, ill, q, mp,
4074 					    ip_arp_defend, CUR_OP, B_FALSE);
4075 				} else {
4076 					ill_refrele(ill);
4077 				}
4078 			}
4079 			return;
4080 		}
4081 		cmn_err(CE_WARN,
4082 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4083 		    hbuf, sbuf, ill->ill_name);
4084 		if (ire != NULL)
4085 			ire_refrele(ire);
4086 		break;
4087 	case AR_CN_ANNOUNCE:
4088 		if (isv6) {
4089 			/*
4090 			 * For XRESOLV interfaces.
4091 			 * Delete the IRE cache entry and NCE for this
4092 			 * v6 address
4093 			 */
4094 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4095 			/*
4096 			 * If v6src is a non-zero, it's a router address
4097 			 * as below. Do the same sort of thing to clean
4098 			 * out off-net IRE_CACHE entries that go through
4099 			 * the router.
4100 			 */
4101 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4102 				ire_walk_v6(ire_delete_cache_gw_v6,
4103 				    (char *)&v6src, ALL_ZONES, ipst);
4104 			}
4105 		} else {
4106 			nce_hw_map_t hwm;
4107 
4108 			/*
4109 			 * ARP gives us a copy of any packet where it thinks
4110 			 * the address has changed, so that we can update our
4111 			 * caches.  We're responsible for caching known answers
4112 			 * in the current design.  We check whether the
4113 			 * hardware address really has changed in all of our
4114 			 * entries that have cached this mapping, and if so, we
4115 			 * blow them away.  This way we will immediately pick
4116 			 * up the rare case of a host changing hardware
4117 			 * address.
4118 			 */
4119 			if (src == 0)
4120 				break;
4121 			hwm.hwm_addr = src;
4122 			hwm.hwm_hwlen = arh->arh_hlen;
4123 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4124 			ndp_walk_common(ipst->ips_ndp4, NULL,
4125 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4126 		}
4127 		break;
4128 	case AR_CN_READY:
4129 		/* No external v6 resolver has a contract to use this */
4130 		if (isv6)
4131 			break;
4132 		/* If the link is down, we'll retry this later */
4133 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4134 			break;
4135 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4136 		    NULL, NULL, ipst);
4137 		if (ipif != NULL) {
4138 			/*
4139 			 * If this is a duplicate recovery, then we now need to
4140 			 * go exclusive to bring this thing back up.
4141 			 */
4142 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4143 			    IPIF_DUPLICATE) {
4144 				ipif_refrele(ipif);
4145 				ill_refhold(ill);
4146 				(void) qwriter_ip(NULL, ill, q, mp,
4147 				    ip_arp_excl, CUR_OP, B_FALSE);
4148 				return;
4149 			}
4150 			/*
4151 			 * If this is the first notice that this address is
4152 			 * ready, then let the user know now.
4153 			 */
4154 			if ((ipif->ipif_flags & IPIF_UP) &&
4155 			    !ipif->ipif_addr_ready) {
4156 				ipif_mask_reply(ipif);
4157 				ip_rts_ifmsg(ipif);
4158 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4159 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4160 			}
4161 			ipif->ipif_addr_ready = 1;
4162 			ipif_refrele(ipif);
4163 		}
4164 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4165 		if (ire != NULL) {
4166 			ire->ire_defense_count = 0;
4167 			ire_refrele(ire);
4168 		}
4169 		break;
4170 	case AR_CN_FAILED:
4171 		/* No external v6 resolver has a contract to use this */
4172 		if (isv6)
4173 			break;
4174 		ill_refhold(ill);
4175 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4176 		    B_FALSE);
4177 		return;
4178 	}
4179 	freemsg(mp);
4180 }
4181 
4182 /*
4183  * Create a mblk suitable for carrying the interface index and/or source link
4184  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4185  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4186  * application.
4187  */
4188 mblk_t *
4189 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4190     ip_stack_t *ipst)
4191 {
4192 	mblk_t		*mp;
4193 	ip_pktinfo_t	*pinfo;
4194 	ipha_t *ipha;
4195 	struct ether_header *pether;
4196 
4197 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4198 	if (mp == NULL) {
4199 		ip1dbg(("ip_add_info: allocation failure.\n"));
4200 		return (data_mp);
4201 	}
4202 
4203 	ipha	= (ipha_t *)data_mp->b_rptr;
4204 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4205 	bzero(pinfo, sizeof (ip_pktinfo_t));
4206 	pinfo->ip_pkt_flags = (uchar_t)flags;
4207 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4208 
4209 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4210 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4211 	if (flags & IPF_RECVADDR) {
4212 		ipif_t	*ipif;
4213 		ire_t	*ire;
4214 
4215 		/*
4216 		 * Only valid for V4
4217 		 */
4218 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4219 		    (IPV4_VERSION << 4));
4220 
4221 		ipif = ipif_get_next_ipif(NULL, ill);
4222 		if (ipif != NULL) {
4223 			/*
4224 			 * Since a decision has already been made to deliver the
4225 			 * packet, there is no need to test for SECATTR and
4226 			 * ZONEONLY.
4227 			 */
4228 			ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0, ipif,
4229 			    zoneid, NULL, MATCH_IRE_ILL_GROUP, ipst);
4230 			if (ire == NULL) {
4231 				/*
4232 				 * packet must have come on a different
4233 				 * interface.
4234 				 * Since a decision has already been made to
4235 				 * deliver the packet, there is no need to test
4236 				 * for SECATTR and ZONEONLY.
4237 				 */
4238 				ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0,
4239 				    ipif, zoneid, NULL, NULL, ipst);
4240 			}
4241 
4242 			if (ire == NULL) {
4243 				/*
4244 				 * This is either a multicast packet or
4245 				 * the address has been removed since
4246 				 * the packet was received.
4247 				 * Return INADDR_ANY so that normal source
4248 				 * selection occurs for the response.
4249 				 */
4250 
4251 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4252 			} else {
4253 				ASSERT(ire->ire_type != IRE_CACHE);
4254 				pinfo->ip_pkt_match_addr.s_addr =
4255 				    ire->ire_src_addr;
4256 				ire_refrele(ire);
4257 			}
4258 			ipif_refrele(ipif);
4259 		} else {
4260 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4261 		}
4262 	}
4263 
4264 	pether = (struct ether_header *)((char *)ipha
4265 	    - sizeof (struct ether_header));
4266 	/*
4267 	 * Make sure the interface is an ethernet type, since this option
4268 	 * is currently supported only on this type of interface. Also make
4269 	 * sure we are pointing correctly above db_base.
4270 	 */
4271 
4272 	if ((flags & IPF_RECVSLLA) &&
4273 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4274 	    (ill->ill_type == IFT_ETHER) &&
4275 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4276 
4277 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4278 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4279 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4280 	} else {
4281 		/*
4282 		 * Clear the bit. Indicate to upper layer that IP is not
4283 		 * sending this ancillary info.
4284 		 */
4285 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4286 	}
4287 
4288 	mp->b_datap->db_type = M_CTL;
4289 	mp->b_wptr += sizeof (ip_pktinfo_t);
4290 	mp->b_cont = data_mp;
4291 
4292 	return (mp);
4293 }
4294 
4295 /*
4296  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4297  * part of the bind request.
4298  */
4299 
4300 boolean_t
4301 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4302 {
4303 	ipsec_in_t *ii;
4304 
4305 	ASSERT(policy_mp != NULL);
4306 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4307 
4308 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4309 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4310 
4311 	connp->conn_policy = ii->ipsec_in_policy;
4312 	ii->ipsec_in_policy = NULL;
4313 
4314 	if (ii->ipsec_in_action != NULL) {
4315 		if (connp->conn_latch == NULL) {
4316 			connp->conn_latch = iplatch_create();
4317 			if (connp->conn_latch == NULL)
4318 				return (B_FALSE);
4319 		}
4320 		ipsec_latch_inbound(connp->conn_latch, ii);
4321 	}
4322 	return (B_TRUE);
4323 }
4324 
4325 /*
4326  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4327  * and to arrange for power-fanout assist.  The ULP is identified by
4328  * adding a single byte at the end of the original bind message.
4329  * A ULP other than UDP or TCP that wishes to be recognized passes
4330  * down a bind with a zero length address.
4331  *
4332  * The binding works as follows:
4333  * - A zero byte address means just bind to the protocol.
4334  * - A four byte address is treated as a request to validate
4335  *   that the address is a valid local address, appropriate for
4336  *   an application to bind to. This does not affect any fanout
4337  *   information in IP.
4338  * - A sizeof sin_t byte address is used to bind to only the local address
4339  *   and port.
4340  * - A sizeof ipa_conn_t byte address contains complete fanout information
4341  *   consisting of local and remote addresses and ports.  In
4342  *   this case, the addresses are both validated as appropriate
4343  *   for this operation, and, if so, the information is retained
4344  *   for use in the inbound fanout.
4345  *
4346  * The ULP (except in the zero-length bind) can append an
4347  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4348  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4349  * a copy of the source or destination IRE (source for local bind;
4350  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4351  * policy information contained should be copied on to the conn.
4352  *
4353  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4354  */
4355 mblk_t *
4356 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4357 {
4358 	ssize_t		len;
4359 	struct T_bind_req	*tbr;
4360 	sin_t		*sin;
4361 	ipa_conn_t	*ac;
4362 	uchar_t		*ucp;
4363 	mblk_t		*mp1;
4364 	boolean_t	ire_requested;
4365 	boolean_t	ipsec_policy_set = B_FALSE;
4366 	int		error = 0;
4367 	int		protocol;
4368 	ipa_conn_x_t	*acx;
4369 
4370 	ASSERT(!connp->conn_af_isv6);
4371 	connp->conn_pkt_isv6 = B_FALSE;
4372 
4373 	len = MBLKL(mp);
4374 	if (len < (sizeof (*tbr) + 1)) {
4375 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4376 		    "ip_bind: bogus msg, len %ld", len);
4377 		/* XXX: Need to return something better */
4378 		goto bad_addr;
4379 	}
4380 	/* Back up and extract the protocol identifier. */
4381 	mp->b_wptr--;
4382 	protocol = *mp->b_wptr & 0xFF;
4383 	tbr = (struct T_bind_req *)mp->b_rptr;
4384 	/* Reset the message type in preparation for shipping it back. */
4385 	DB_TYPE(mp) = M_PCPROTO;
4386 
4387 	connp->conn_ulp = (uint8_t)protocol;
4388 
4389 	/*
4390 	 * Check for a zero length address.  This is from a protocol that
4391 	 * wants to register to receive all packets of its type.
4392 	 */
4393 	if (tbr->ADDR_length == 0) {
4394 		/*
4395 		 * These protocols are now intercepted in ip_bind_v6().
4396 		 * Reject protocol-level binds here for now.
4397 		 *
4398 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4399 		 * so that the protocol type cannot be SCTP.
4400 		 */
4401 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4402 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4403 			goto bad_addr;
4404 		}
4405 
4406 		/*
4407 		 *
4408 		 * The udp module never sends down a zero-length address,
4409 		 * and allowing this on a labeled system will break MLP
4410 		 * functionality.
4411 		 */
4412 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4413 			goto bad_addr;
4414 
4415 		if (connp->conn_mac_exempt)
4416 			goto bad_addr;
4417 
4418 		/* No hash here really.  The table is big enough. */
4419 		connp->conn_srcv6 = ipv6_all_zeros;
4420 
4421 		ipcl_proto_insert(connp, protocol);
4422 
4423 		tbr->PRIM_type = T_BIND_ACK;
4424 		return (mp);
4425 	}
4426 
4427 	/* Extract the address pointer from the message. */
4428 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4429 	    tbr->ADDR_length);
4430 	if (ucp == NULL) {
4431 		ip1dbg(("ip_bind: no address\n"));
4432 		goto bad_addr;
4433 	}
4434 	if (!OK_32PTR(ucp)) {
4435 		ip1dbg(("ip_bind: unaligned address\n"));
4436 		goto bad_addr;
4437 	}
4438 	/*
4439 	 * Check for trailing mps.
4440 	 */
4441 
4442 	mp1 = mp->b_cont;
4443 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4444 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4445 
4446 	switch (tbr->ADDR_length) {
4447 	default:
4448 		ip1dbg(("ip_bind: bad address length %d\n",
4449 		    (int)tbr->ADDR_length));
4450 		goto bad_addr;
4451 
4452 	case IP_ADDR_LEN:
4453 		/* Verification of local address only */
4454 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4455 		    ire_requested, ipsec_policy_set, B_FALSE);
4456 		break;
4457 
4458 	case sizeof (sin_t):
4459 		sin = (sin_t *)ucp;
4460 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4461 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4462 		break;
4463 
4464 	case sizeof (ipa_conn_t):
4465 		ac = (ipa_conn_t *)ucp;
4466 		/* For raw socket, the local port is not set. */
4467 		if (ac->ac_lport == 0)
4468 			ac->ac_lport = connp->conn_lport;
4469 		/* Always verify destination reachability. */
4470 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4471 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4472 		    ipsec_policy_set, B_TRUE, B_TRUE);
4473 		break;
4474 
4475 	case sizeof (ipa_conn_x_t):
4476 		acx = (ipa_conn_x_t *)ucp;
4477 		/*
4478 		 * Whether or not to verify destination reachability depends
4479 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4480 		 */
4481 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4482 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4483 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4484 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4485 		break;
4486 	}
4487 	if (error == EINPROGRESS)
4488 		return (NULL);
4489 	else if (error != 0)
4490 		goto bad_addr;
4491 	/*
4492 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4493 	 * We can't do this in ip_bind_insert_ire because the policy
4494 	 * may not have been inherited at that point in time and hence
4495 	 * conn_out_enforce_policy may not be set.
4496 	 */
4497 	mp1 = mp->b_cont;
4498 	if (ire_requested && connp->conn_out_enforce_policy &&
4499 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4500 		ire_t *ire = (ire_t *)mp1->b_rptr;
4501 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4502 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4503 	}
4504 
4505 	/* Send it home. */
4506 	mp->b_datap->db_type = M_PCPROTO;
4507 	tbr->PRIM_type = T_BIND_ACK;
4508 	return (mp);
4509 
4510 bad_addr:
4511 	/*
4512 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4513 	 * a unix errno.
4514 	 */
4515 	if (error > 0)
4516 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4517 	else
4518 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4519 	return (mp);
4520 }
4521 
4522 /*
4523  * Here address is verified to be a valid local address.
4524  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4525  * address is also considered a valid local address.
4526  * In the case of a broadcast/multicast address, however, the
4527  * upper protocol is expected to reset the src address
4528  * to 0 if it sees a IRE_BROADCAST type returned so that
4529  * no packets are emitted with broadcast/multicast address as
4530  * source address (that violates hosts requirements RFC1122)
4531  * The addresses valid for bind are:
4532  *	(1) - INADDR_ANY (0)
4533  *	(2) - IP address of an UP interface
4534  *	(3) - IP address of a DOWN interface
4535  *	(4) - valid local IP broadcast addresses. In this case
4536  *	the conn will only receive packets destined to
4537  *	the specified broadcast address.
4538  *	(5) - a multicast address. In this case
4539  *	the conn will only receive packets destined to
4540  *	the specified multicast address. Note: the
4541  *	application still has to issue an
4542  *	IP_ADD_MEMBERSHIP socket option.
4543  *
4544  * On error, return -1 for TBADADDR otherwise pass the
4545  * errno with TSYSERR reply.
4546  *
4547  * In all the above cases, the bound address must be valid in the current zone.
4548  * When the address is loopback, multicast or broadcast, there might be many
4549  * matching IREs so bind has to look up based on the zone.
4550  *
4551  * Note: lport is in network byte order.
4552  */
4553 int
4554 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4555     boolean_t ire_requested, boolean_t ipsec_policy_set,
4556     boolean_t fanout_insert)
4557 {
4558 	int		error = 0;
4559 	ire_t		*src_ire;
4560 	mblk_t		*policy_mp;
4561 	ipif_t		*ipif;
4562 	zoneid_t	zoneid;
4563 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4564 
4565 	if (ipsec_policy_set) {
4566 		policy_mp = mp->b_cont;
4567 	}
4568 
4569 	/*
4570 	 * If it was previously connected, conn_fully_bound would have
4571 	 * been set.
4572 	 */
4573 	connp->conn_fully_bound = B_FALSE;
4574 
4575 	src_ire = NULL;
4576 	ipif = NULL;
4577 
4578 	zoneid = IPCL_ZONEID(connp);
4579 
4580 	if (src_addr) {
4581 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4582 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4583 		/*
4584 		 * If an address other than 0.0.0.0 is requested,
4585 		 * we verify that it is a valid address for bind
4586 		 * Note: Following code is in if-else-if form for
4587 		 * readability compared to a condition check.
4588 		 */
4589 		/* LINTED - statement has no consequent */
4590 		if (IRE_IS_LOCAL(src_ire)) {
4591 			/*
4592 			 * (2) Bind to address of local UP interface
4593 			 */
4594 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4595 			/*
4596 			 * (4) Bind to broadcast address
4597 			 * Note: permitted only from transports that
4598 			 * request IRE
4599 			 */
4600 			if (!ire_requested)
4601 				error = EADDRNOTAVAIL;
4602 		} else {
4603 			/*
4604 			 * (3) Bind to address of local DOWN interface
4605 			 * (ipif_lookup_addr() looks up all interfaces
4606 			 * but we do not get here for UP interfaces
4607 			 * - case (2) above)
4608 			 * We put the protocol byte back into the mblk
4609 			 * since we may come back via ip_wput_nondata()
4610 			 * later with this mblk if ipif_lookup_addr chooses
4611 			 * to defer processing.
4612 			 */
4613 			*mp->b_wptr++ = (char)connp->conn_ulp;
4614 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4615 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4616 			    &error, ipst)) != NULL) {
4617 				ipif_refrele(ipif);
4618 			} else if (error == EINPROGRESS) {
4619 				if (src_ire != NULL)
4620 					ire_refrele(src_ire);
4621 				return (EINPROGRESS);
4622 			} else if (CLASSD(src_addr)) {
4623 				error = 0;
4624 				if (src_ire != NULL)
4625 					ire_refrele(src_ire);
4626 				/*
4627 				 * (5) bind to multicast address.
4628 				 * Fake out the IRE returned to upper
4629 				 * layer to be a broadcast IRE.
4630 				 */
4631 				src_ire = ire_ctable_lookup(
4632 				    INADDR_BROADCAST, INADDR_ANY,
4633 				    IRE_BROADCAST, NULL, zoneid, NULL,
4634 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4635 				    ipst);
4636 				if (src_ire == NULL || !ire_requested)
4637 					error = EADDRNOTAVAIL;
4638 			} else {
4639 				/*
4640 				 * Not a valid address for bind
4641 				 */
4642 				error = EADDRNOTAVAIL;
4643 			}
4644 			/*
4645 			 * Just to keep it consistent with the processing in
4646 			 * ip_bind_v4()
4647 			 */
4648 			mp->b_wptr--;
4649 		}
4650 		if (error) {
4651 			/* Red Alert!  Attempting to be a bogon! */
4652 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4653 			    ntohl(src_addr)));
4654 			goto bad_addr;
4655 		}
4656 	}
4657 
4658 	/*
4659 	 * Allow setting new policies. For example, disconnects come
4660 	 * down as ipa_t bind. As we would have set conn_policy_cached
4661 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4662 	 * can change after the disconnect.
4663 	 */
4664 	connp->conn_policy_cached = B_FALSE;
4665 
4666 	/*
4667 	 * If not fanout_insert this was just an address verification
4668 	 */
4669 	if (fanout_insert) {
4670 		/*
4671 		 * The addresses have been verified. Time to insert in
4672 		 * the correct fanout list.
4673 		 */
4674 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4675 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4676 		connp->conn_lport = lport;
4677 		connp->conn_fport = 0;
4678 		/*
4679 		 * Do we need to add a check to reject Multicast packets
4680 		 *
4681 		 * We need to make sure that the conn_recv is set to a non-null
4682 		 * value before we insert the conn into the classifier table.
4683 		 * This is to avoid a race with an incoming packet which does an
4684 		 * ipcl_classify().
4685 		 */
4686 		if (*mp->b_wptr == IPPROTO_TCP)
4687 			connp->conn_recv = tcp_conn_request;
4688 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4689 	}
4690 
4691 	if (error == 0) {
4692 		if (ire_requested) {
4693 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4694 				error = -1;
4695 				/* Falls through to bad_addr */
4696 			}
4697 		} else if (ipsec_policy_set) {
4698 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4699 				error = -1;
4700 				/* Falls through to bad_addr */
4701 			}
4702 		}
4703 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4704 		connp->conn_recv = tcp_input;
4705 	}
4706 bad_addr:
4707 	if (error != 0) {
4708 		if (connp->conn_anon_port) {
4709 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4710 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4711 			    B_FALSE);
4712 		}
4713 		connp->conn_mlp_type = mlptSingle;
4714 	}
4715 	if (src_ire != NULL)
4716 		IRE_REFRELE(src_ire);
4717 	if (ipsec_policy_set) {
4718 		ASSERT(policy_mp == mp->b_cont);
4719 		ASSERT(policy_mp != NULL);
4720 		freeb(policy_mp);
4721 		/*
4722 		 * As of now assume that nothing else accompanies
4723 		 * IPSEC_POLICY_SET.
4724 		 */
4725 		mp->b_cont = NULL;
4726 	}
4727 	return (error);
4728 }
4729 
4730 /*
4731  * Verify that both the source and destination addresses
4732  * are valid.  If verify_dst is false, then the destination address may be
4733  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4734  * destination reachability, while tunnels do not.
4735  * Note that we allow connect to broadcast and multicast
4736  * addresses when ire_requested is set. Thus the ULP
4737  * has to check for IRE_BROADCAST and multicast.
4738  *
4739  * Returns zero if ok.
4740  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4741  * (for use with TSYSERR reply).
4742  *
4743  * Note: lport and fport are in network byte order.
4744  */
4745 int
4746 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4747     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4748     boolean_t ire_requested, boolean_t ipsec_policy_set,
4749     boolean_t fanout_insert, boolean_t verify_dst)
4750 {
4751 	ire_t		*src_ire;
4752 	ire_t		*dst_ire;
4753 	int		error = 0;
4754 	int 		protocol;
4755 	mblk_t		*policy_mp;
4756 	ire_t		*sire = NULL;
4757 	ire_t		*md_dst_ire = NULL;
4758 	ire_t		*lso_dst_ire = NULL;
4759 	ill_t		*ill = NULL;
4760 	zoneid_t	zoneid;
4761 	ipaddr_t	src_addr = *src_addrp;
4762 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4763 
4764 	src_ire = dst_ire = NULL;
4765 	protocol = *mp->b_wptr & 0xFF;
4766 
4767 	/*
4768 	 * If we never got a disconnect before, clear it now.
4769 	 */
4770 	connp->conn_fully_bound = B_FALSE;
4771 
4772 	if (ipsec_policy_set) {
4773 		policy_mp = mp->b_cont;
4774 	}
4775 
4776 	zoneid = IPCL_ZONEID(connp);
4777 
4778 	if (CLASSD(dst_addr)) {
4779 		/* Pick up an IRE_BROADCAST */
4780 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4781 		    NULL, zoneid, MBLK_GETLABEL(mp),
4782 		    (MATCH_IRE_RECURSIVE |
4783 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4784 		    MATCH_IRE_SECATTR), ipst);
4785 	} else {
4786 		/*
4787 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4788 		 * and onlink ipif is not found set ENETUNREACH error.
4789 		 */
4790 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4791 			ipif_t *ipif;
4792 
4793 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4794 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4795 			if (ipif == NULL) {
4796 				error = ENETUNREACH;
4797 				goto bad_addr;
4798 			}
4799 			ipif_refrele(ipif);
4800 		}
4801 
4802 		if (connp->conn_nexthop_set) {
4803 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4804 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4805 			    MATCH_IRE_SECATTR, ipst);
4806 		} else {
4807 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4808 			    &sire, zoneid, MBLK_GETLABEL(mp),
4809 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4810 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4811 			    MATCH_IRE_SECATTR), ipst);
4812 		}
4813 	}
4814 	/*
4815 	 * dst_ire can't be a broadcast when not ire_requested.
4816 	 * We also prevent ire's with src address INADDR_ANY to
4817 	 * be used, which are created temporarily for
4818 	 * sending out packets from endpoints that have
4819 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4820 	 * reachable.  If verify_dst is false, the destination needn't be
4821 	 * reachable.
4822 	 *
4823 	 * If we match on a reject or black hole, then we've got a
4824 	 * local failure.  May as well fail out the connect() attempt,
4825 	 * since it's never going to succeed.
4826 	 */
4827 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4828 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4829 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4830 		/*
4831 		 * If we're verifying destination reachability, we always want
4832 		 * to complain here.
4833 		 *
4834 		 * If we're not verifying destination reachability but the
4835 		 * destination has a route, we still want to fail on the
4836 		 * temporary address and broadcast address tests.
4837 		 */
4838 		if (verify_dst || (dst_ire != NULL)) {
4839 			if (ip_debug > 2) {
4840 				pr_addr_dbg("ip_bind_connected: bad connected "
4841 				    "dst %s\n", AF_INET, &dst_addr);
4842 			}
4843 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4844 				error = ENETUNREACH;
4845 			else
4846 				error = EHOSTUNREACH;
4847 			goto bad_addr;
4848 		}
4849 	}
4850 
4851 	/*
4852 	 * We now know that routing will allow us to reach the destination.
4853 	 * Check whether Trusted Solaris policy allows communication with this
4854 	 * host, and pretend that the destination is unreachable if not.
4855 	 *
4856 	 * This is never a problem for TCP, since that transport is known to
4857 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4858 	 * handling.  If the remote is unreachable, it will be detected at that
4859 	 * point, so there's no reason to check it here.
4860 	 *
4861 	 * Note that for sendto (and other datagram-oriented friends), this
4862 	 * check is done as part of the data path label computation instead.
4863 	 * The check here is just to make non-TCP connect() report the right
4864 	 * error.
4865 	 */
4866 	if (dst_ire != NULL && is_system_labeled() &&
4867 	    !IPCL_IS_TCP(connp) &&
4868 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4869 	    connp->conn_mac_exempt, ipst) != 0) {
4870 		error = EHOSTUNREACH;
4871 		if (ip_debug > 2) {
4872 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4873 			    AF_INET, &dst_addr);
4874 		}
4875 		goto bad_addr;
4876 	}
4877 
4878 	/*
4879 	 * If the app does a connect(), it means that it will most likely
4880 	 * send more than 1 packet to the destination.  It makes sense
4881 	 * to clear the temporary flag.
4882 	 */
4883 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4884 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4885 		irb_t *irb = dst_ire->ire_bucket;
4886 
4887 		rw_enter(&irb->irb_lock, RW_WRITER);
4888 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4889 		irb->irb_tmp_ire_cnt--;
4890 		rw_exit(&irb->irb_lock);
4891 	}
4892 
4893 	/*
4894 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4895 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4896 	 * eligibility tests for passive connects are handled separately
4897 	 * through tcp_adapt_ire().  We do this before the source address
4898 	 * selection, because dst_ire may change after a call to
4899 	 * ipif_select_source().  This is a best-effort check, as the
4900 	 * packet for this connection may not actually go through
4901 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4902 	 * calling ip_newroute().  This is why we further check on the
4903 	 * IRE during LSO/Multidata packet transmission in
4904 	 * tcp_lsosend()/tcp_multisend().
4905 	 */
4906 	if (!ipsec_policy_set && dst_ire != NULL &&
4907 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4908 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4909 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4910 			lso_dst_ire = dst_ire;
4911 			IRE_REFHOLD(lso_dst_ire);
4912 		} else if (ipst->ips_ip_multidata_outbound &&
4913 		    ILL_MDT_CAPABLE(ill)) {
4914 			md_dst_ire = dst_ire;
4915 			IRE_REFHOLD(md_dst_ire);
4916 		}
4917 	}
4918 
4919 	if (dst_ire != NULL &&
4920 	    dst_ire->ire_type == IRE_LOCAL &&
4921 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4922 		/*
4923 		 * If the IRE belongs to a different zone, look for a matching
4924 		 * route in the forwarding table and use the source address from
4925 		 * that route.
4926 		 */
4927 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4928 		    zoneid, 0, NULL,
4929 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4930 		    MATCH_IRE_RJ_BHOLE, ipst);
4931 		if (src_ire == NULL) {
4932 			error = EHOSTUNREACH;
4933 			goto bad_addr;
4934 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4935 			if (!(src_ire->ire_type & IRE_HOST))
4936 				error = ENETUNREACH;
4937 			else
4938 				error = EHOSTUNREACH;
4939 			goto bad_addr;
4940 		}
4941 		if (src_addr == INADDR_ANY)
4942 			src_addr = src_ire->ire_src_addr;
4943 		ire_refrele(src_ire);
4944 		src_ire = NULL;
4945 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4946 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4947 			src_addr = sire->ire_src_addr;
4948 			ire_refrele(dst_ire);
4949 			dst_ire = sire;
4950 			sire = NULL;
4951 		} else {
4952 			/*
4953 			 * Pick a source address so that a proper inbound
4954 			 * load spreading would happen.
4955 			 */
4956 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4957 			ipif_t *src_ipif = NULL;
4958 			ire_t *ipif_ire;
4959 
4960 			/*
4961 			 * Supply a local source address such that inbound
4962 			 * load spreading happens.
4963 			 *
4964 			 * Determine the best source address on this ill for
4965 			 * the destination.
4966 			 *
4967 			 * 1) For broadcast, we should return a broadcast ire
4968 			 *    found above so that upper layers know that the
4969 			 *    destination address is a broadcast address.
4970 			 *
4971 			 * 2) If this is part of a group, select a better
4972 			 *    source address so that better inbound load
4973 			 *    balancing happens. Do the same if the ipif
4974 			 *    is DEPRECATED.
4975 			 *
4976 			 * 3) If the outgoing interface is part of a usesrc
4977 			 *    group, then try selecting a source address from
4978 			 *    the usesrc ILL.
4979 			 */
4980 			if ((dst_ire->ire_zoneid != zoneid &&
4981 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4982 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4983 			    ((dst_ill->ill_group != NULL) ||
4984 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4985 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4986 				/*
4987 				 * If the destination is reachable via a
4988 				 * given gateway, the selected source address
4989 				 * should be in the same subnet as the gateway.
4990 				 * Otherwise, the destination is not reachable.
4991 				 *
4992 				 * If there are no interfaces on the same subnet
4993 				 * as the destination, ipif_select_source gives
4994 				 * first non-deprecated interface which might be
4995 				 * on a different subnet than the gateway.
4996 				 * This is not desirable. Hence pass the dst_ire
4997 				 * source address to ipif_select_source.
4998 				 * It is sure that the destination is reachable
4999 				 * with the dst_ire source address subnet.
5000 				 * So passing dst_ire source address to
5001 				 * ipif_select_source will make sure that the
5002 				 * selected source will be on the same subnet
5003 				 * as dst_ire source address.
5004 				 */
5005 				ipaddr_t saddr =
5006 				    dst_ire->ire_ipif->ipif_src_addr;
5007 				src_ipif = ipif_select_source(dst_ill,
5008 				    saddr, zoneid);
5009 				if (src_ipif != NULL) {
5010 					if (IS_VNI(src_ipif->ipif_ill)) {
5011 						/*
5012 						 * For VNI there is no
5013 						 * interface route
5014 						 */
5015 						src_addr =
5016 						    src_ipif->ipif_src_addr;
5017 					} else {
5018 						ipif_ire =
5019 						    ipif_to_ire(src_ipif);
5020 						if (ipif_ire != NULL) {
5021 							IRE_REFRELE(dst_ire);
5022 							dst_ire = ipif_ire;
5023 						}
5024 						src_addr =
5025 						    dst_ire->ire_src_addr;
5026 					}
5027 					ipif_refrele(src_ipif);
5028 				} else {
5029 					src_addr = dst_ire->ire_src_addr;
5030 				}
5031 			} else {
5032 				src_addr = dst_ire->ire_src_addr;
5033 			}
5034 		}
5035 	}
5036 
5037 	/*
5038 	 * We do ire_route_lookup() here (and not
5039 	 * interface lookup as we assert that
5040 	 * src_addr should only come from an
5041 	 * UP interface for hard binding.
5042 	 */
5043 	ASSERT(src_ire == NULL);
5044 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5045 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5046 	/* src_ire must be a local|loopback */
5047 	if (!IRE_IS_LOCAL(src_ire)) {
5048 		if (ip_debug > 2) {
5049 			pr_addr_dbg("ip_bind_connected: bad connected "
5050 			    "src %s\n", AF_INET, &src_addr);
5051 		}
5052 		error = EADDRNOTAVAIL;
5053 		goto bad_addr;
5054 	}
5055 
5056 	/*
5057 	 * If the source address is a loopback address, the
5058 	 * destination had best be local or multicast.
5059 	 * The transports that can't handle multicast will reject
5060 	 * those addresses.
5061 	 */
5062 	if (src_ire->ire_type == IRE_LOOPBACK &&
5063 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5064 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5065 		error = -1;
5066 		goto bad_addr;
5067 	}
5068 
5069 	/*
5070 	 * Allow setting new policies. For example, disconnects come
5071 	 * down as ipa_t bind. As we would have set conn_policy_cached
5072 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5073 	 * can change after the disconnect.
5074 	 */
5075 	connp->conn_policy_cached = B_FALSE;
5076 
5077 	/*
5078 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5079 	 * can handle their passed-in conn's.
5080 	 */
5081 
5082 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5083 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5084 	connp->conn_lport = lport;
5085 	connp->conn_fport = fport;
5086 	*src_addrp = src_addr;
5087 
5088 	ASSERT(!(ipsec_policy_set && ire_requested));
5089 	if (ire_requested) {
5090 		iulp_t *ulp_info = NULL;
5091 
5092 		/*
5093 		 * Note that sire will not be NULL if this is an off-link
5094 		 * connection and there is not cache for that dest yet.
5095 		 *
5096 		 * XXX Because of an existing bug, if there are multiple
5097 		 * default routes, the IRE returned now may not be the actual
5098 		 * default route used (default routes are chosen in a
5099 		 * round robin fashion).  So if the metrics for different
5100 		 * default routes are different, we may return the wrong
5101 		 * metrics.  This will not be a problem if the existing
5102 		 * bug is fixed.
5103 		 */
5104 		if (sire != NULL) {
5105 			ulp_info = &(sire->ire_uinfo);
5106 		}
5107 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5108 			error = -1;
5109 			goto bad_addr;
5110 		}
5111 	} else if (ipsec_policy_set) {
5112 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5113 			error = -1;
5114 			goto bad_addr;
5115 		}
5116 	}
5117 
5118 	/*
5119 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5120 	 * we'll cache that.  If we don't, we'll inherit global policy.
5121 	 *
5122 	 * We can't insert until the conn reflects the policy. Note that
5123 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5124 	 * connections where we don't have a policy. This is to prevent
5125 	 * global policy lookups in the inbound path.
5126 	 *
5127 	 * If we insert before we set conn_policy_cached,
5128 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5129 	 * because global policy cound be non-empty. We normally call
5130 	 * ipsec_check_policy() for conn_policy_cached connections only if
5131 	 * ipc_in_enforce_policy is set. But in this case,
5132 	 * conn_policy_cached can get set anytime since we made the
5133 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5134 	 * called, which will make the above assumption false.  Thus, we
5135 	 * need to insert after we set conn_policy_cached.
5136 	 */
5137 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5138 		goto bad_addr;
5139 
5140 	if (fanout_insert) {
5141 		/*
5142 		 * The addresses have been verified. Time to insert in
5143 		 * the correct fanout list.
5144 		 * We need to make sure that the conn_recv is set to a non-null
5145 		 * value before we insert into the classifier table to avoid a
5146 		 * race with an incoming packet which does an ipcl_classify().
5147 		 */
5148 		if (protocol == IPPROTO_TCP)
5149 			connp->conn_recv = tcp_input;
5150 		error = ipcl_conn_insert(connp, protocol, src_addr,
5151 		    dst_addr, connp->conn_ports);
5152 	}
5153 
5154 	if (error == 0) {
5155 		connp->conn_fully_bound = B_TRUE;
5156 		/*
5157 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5158 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5159 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5160 		 * ip_xxinfo_return(), which performs further checks
5161 		 * against them and upon success, returns the LSO/MDT info
5162 		 * mblk which we will attach to the bind acknowledgment.
5163 		 */
5164 		if (lso_dst_ire != NULL) {
5165 			mblk_t *lsoinfo_mp;
5166 
5167 			ASSERT(ill->ill_lso_capab != NULL);
5168 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5169 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5170 				linkb(mp, lsoinfo_mp);
5171 		} else if (md_dst_ire != NULL) {
5172 			mblk_t *mdinfo_mp;
5173 
5174 			ASSERT(ill->ill_mdt_capab != NULL);
5175 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5176 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5177 				linkb(mp, mdinfo_mp);
5178 		}
5179 	}
5180 bad_addr:
5181 	if (ipsec_policy_set) {
5182 		ASSERT(policy_mp == mp->b_cont);
5183 		ASSERT(policy_mp != NULL);
5184 		freeb(policy_mp);
5185 		/*
5186 		 * As of now assume that nothing else accompanies
5187 		 * IPSEC_POLICY_SET.
5188 		 */
5189 		mp->b_cont = NULL;
5190 	}
5191 	if (src_ire != NULL)
5192 		IRE_REFRELE(src_ire);
5193 	if (dst_ire != NULL)
5194 		IRE_REFRELE(dst_ire);
5195 	if (sire != NULL)
5196 		IRE_REFRELE(sire);
5197 	if (md_dst_ire != NULL)
5198 		IRE_REFRELE(md_dst_ire);
5199 	if (lso_dst_ire != NULL)
5200 		IRE_REFRELE(lso_dst_ire);
5201 	return (error);
5202 }
5203 
5204 /*
5205  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5206  * Prefers dst_ire over src_ire.
5207  */
5208 static boolean_t
5209 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5210 {
5211 	mblk_t	*mp1;
5212 	ire_t *ret_ire = NULL;
5213 
5214 	mp1 = mp->b_cont;
5215 	ASSERT(mp1 != NULL);
5216 
5217 	if (ire != NULL) {
5218 		/*
5219 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5220 		 * appended mblk. Its <upper protocol>'s
5221 		 * job to make sure there is room.
5222 		 */
5223 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5224 			return (0);
5225 
5226 		mp1->b_datap->db_type = IRE_DB_TYPE;
5227 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5228 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5229 		ret_ire = (ire_t *)mp1->b_rptr;
5230 		/*
5231 		 * Pass the latest setting of the ip_path_mtu_discovery and
5232 		 * copy the ulp info if any.
5233 		 */
5234 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5235 		    IPH_DF : 0;
5236 		if (ulp_info != NULL) {
5237 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5238 			    sizeof (iulp_t));
5239 		}
5240 		ret_ire->ire_mp = mp1;
5241 	} else {
5242 		/*
5243 		 * No IRE was found. Remove IRE mblk.
5244 		 */
5245 		mp->b_cont = mp1->b_cont;
5246 		freeb(mp1);
5247 	}
5248 
5249 	return (1);
5250 }
5251 
5252 /*
5253  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5254  * the final piece where we don't.  Return a pointer to the first mblk in the
5255  * result, and update the pointer to the next mblk to chew on.  If anything
5256  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5257  * NULL pointer.
5258  */
5259 mblk_t *
5260 ip_carve_mp(mblk_t **mpp, ssize_t len)
5261 {
5262 	mblk_t	*mp0;
5263 	mblk_t	*mp1;
5264 	mblk_t	*mp2;
5265 
5266 	if (!len || !mpp || !(mp0 = *mpp))
5267 		return (NULL);
5268 	/* If we aren't going to consume the first mblk, we need a dup. */
5269 	if (mp0->b_wptr - mp0->b_rptr > len) {
5270 		mp1 = dupb(mp0);
5271 		if (mp1) {
5272 			/* Partition the data between the two mblks. */
5273 			mp1->b_wptr = mp1->b_rptr + len;
5274 			mp0->b_rptr = mp1->b_wptr;
5275 			/*
5276 			 * after adjustments if mblk not consumed is now
5277 			 * unaligned, try to align it. If this fails free
5278 			 * all messages and let upper layer recover.
5279 			 */
5280 			if (!OK_32PTR(mp0->b_rptr)) {
5281 				if (!pullupmsg(mp0, -1)) {
5282 					freemsg(mp0);
5283 					freemsg(mp1);
5284 					*mpp = NULL;
5285 					return (NULL);
5286 				}
5287 			}
5288 		}
5289 		return (mp1);
5290 	}
5291 	/* Eat through as many mblks as we need to get len bytes. */
5292 	len -= mp0->b_wptr - mp0->b_rptr;
5293 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5294 		if (mp2->b_wptr - mp2->b_rptr > len) {
5295 			/*
5296 			 * We won't consume the entire last mblk.  Like
5297 			 * above, dup and partition it.
5298 			 */
5299 			mp1->b_cont = dupb(mp2);
5300 			mp1 = mp1->b_cont;
5301 			if (!mp1) {
5302 				/*
5303 				 * Trouble.  Rather than go to a lot of
5304 				 * trouble to clean up, we free the messages.
5305 				 * This won't be any worse than losing it on
5306 				 * the wire.
5307 				 */
5308 				freemsg(mp0);
5309 				freemsg(mp2);
5310 				*mpp = NULL;
5311 				return (NULL);
5312 			}
5313 			mp1->b_wptr = mp1->b_rptr + len;
5314 			mp2->b_rptr = mp1->b_wptr;
5315 			/*
5316 			 * after adjustments if mblk not consumed is now
5317 			 * unaligned, try to align it. If this fails free
5318 			 * all messages and let upper layer recover.
5319 			 */
5320 			if (!OK_32PTR(mp2->b_rptr)) {
5321 				if (!pullupmsg(mp2, -1)) {
5322 					freemsg(mp0);
5323 					freemsg(mp2);
5324 					*mpp = NULL;
5325 					return (NULL);
5326 				}
5327 			}
5328 			*mpp = mp2;
5329 			return (mp0);
5330 		}
5331 		/* Decrement len by the amount we just got. */
5332 		len -= mp2->b_wptr - mp2->b_rptr;
5333 	}
5334 	/*
5335 	 * len should be reduced to zero now.  If not our caller has
5336 	 * screwed up.
5337 	 */
5338 	if (len) {
5339 		/* Shouldn't happen! */
5340 		freemsg(mp0);
5341 		*mpp = NULL;
5342 		return (NULL);
5343 	}
5344 	/*
5345 	 * We consumed up to exactly the end of an mblk.  Detach the part
5346 	 * we are returning from the rest of the chain.
5347 	 */
5348 	mp1->b_cont = NULL;
5349 	*mpp = mp2;
5350 	return (mp0);
5351 }
5352 
5353 /* The ill stream is being unplumbed. Called from ip_close */
5354 int
5355 ip_modclose(ill_t *ill)
5356 {
5357 
5358 	boolean_t success;
5359 	ipsq_t	*ipsq;
5360 	ipif_t	*ipif;
5361 	queue_t	*q = ill->ill_rq;
5362 	ip_stack_t	*ipst = ill->ill_ipst;
5363 	clock_t timeout;
5364 
5365 	/*
5366 	 * Wait for the ACKs of all deferred control messages to be processed.
5367 	 * In particular, we wait for a potential capability reset initiated
5368 	 * in ip_sioctl_plink() to complete before proceeding.
5369 	 *
5370 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5371 	 * in case the driver never replies.
5372 	 */
5373 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5374 	mutex_enter(&ill->ill_lock);
5375 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5376 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5377 			/* Timeout */
5378 			break;
5379 		}
5380 	}
5381 	mutex_exit(&ill->ill_lock);
5382 
5383 	/*
5384 	 * Forcibly enter the ipsq after some delay. This is to take
5385 	 * care of the case when some ioctl does not complete because
5386 	 * we sent a control message to the driver and it did not
5387 	 * send us a reply. We want to be able to at least unplumb
5388 	 * and replumb rather than force the user to reboot the system.
5389 	 */
5390 	success = ipsq_enter(ill, B_FALSE);
5391 
5392 	/*
5393 	 * Open/close/push/pop is guaranteed to be single threaded
5394 	 * per stream by STREAMS. FS guarantees that all references
5395 	 * from top are gone before close is called. So there can't
5396 	 * be another close thread that has set CONDEMNED on this ill.
5397 	 * and cause ipsq_enter to return failure.
5398 	 */
5399 	ASSERT(success);
5400 	ipsq = ill->ill_phyint->phyint_ipsq;
5401 
5402 	/*
5403 	 * Mark it condemned. No new reference will be made to this ill.
5404 	 * Lookup functions will return an error. Threads that try to
5405 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5406 	 * that the refcnt will drop down to zero.
5407 	 */
5408 	mutex_enter(&ill->ill_lock);
5409 	ill->ill_state_flags |= ILL_CONDEMNED;
5410 	for (ipif = ill->ill_ipif; ipif != NULL;
5411 	    ipif = ipif->ipif_next) {
5412 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5413 	}
5414 	/*
5415 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5416 	 * returns  error if ILL_CONDEMNED is set
5417 	 */
5418 	cv_broadcast(&ill->ill_cv);
5419 	mutex_exit(&ill->ill_lock);
5420 
5421 	/*
5422 	 * Send all the deferred control messages downstream which came in
5423 	 * during the small window right before ipsq_enter(). We do this
5424 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5425 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5426 	 */
5427 	ill_send_all_deferred_mp(ill);
5428 
5429 	/*
5430 	 * Shut down fragmentation reassembly.
5431 	 * ill_frag_timer won't start a timer again.
5432 	 * Now cancel any existing timer
5433 	 */
5434 	(void) untimeout(ill->ill_frag_timer_id);
5435 	(void) ill_frag_timeout(ill, 0);
5436 
5437 	/*
5438 	 * If MOVE was in progress, clear the
5439 	 * move_in_progress fields also.
5440 	 */
5441 	if (ill->ill_move_in_progress) {
5442 		ILL_CLEAR_MOVE(ill);
5443 	}
5444 
5445 	/*
5446 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5447 	 * this ill. Then wait for the refcnts to drop to zero.
5448 	 * ill_is_quiescent checks whether the ill is really quiescent.
5449 	 * Then make sure that threads that are waiting to enter the
5450 	 * ipsq have seen the error returned by ipsq_enter and have
5451 	 * gone away. Then we call ill_delete_tail which does the
5452 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5453 	 */
5454 	ill_delete(ill);
5455 	mutex_enter(&ill->ill_lock);
5456 	while (!ill_is_quiescent(ill))
5457 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5458 	while (ill->ill_waiters)
5459 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5460 
5461 	mutex_exit(&ill->ill_lock);
5462 
5463 	/*
5464 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5465 	 * it held until the end of the function since the cleanup
5466 	 * below needs to be able to use the ip_stack_t.
5467 	 */
5468 	netstack_hold(ipst->ips_netstack);
5469 
5470 	/* qprocsoff is called in ill_delete_tail */
5471 	ill_delete_tail(ill);
5472 	ASSERT(ill->ill_ipst == NULL);
5473 
5474 	/*
5475 	 * Walk through all upper (conn) streams and qenable
5476 	 * those that have queued data.
5477 	 * close synchronization needs this to
5478 	 * be done to ensure that all upper layers blocked
5479 	 * due to flow control to the closing device
5480 	 * get unblocked.
5481 	 */
5482 	ip1dbg(("ip_wsrv: walking\n"));
5483 	conn_walk_drain(ipst);
5484 
5485 	mutex_enter(&ipst->ips_ip_mi_lock);
5486 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5487 	mutex_exit(&ipst->ips_ip_mi_lock);
5488 
5489 	/*
5490 	 * credp could be null if the open didn't succeed and ip_modopen
5491 	 * itself calls ip_close.
5492 	 */
5493 	if (ill->ill_credp != NULL)
5494 		crfree(ill->ill_credp);
5495 
5496 	mutex_enter(&ill->ill_lock);
5497 	ill_nic_info_dispatch(ill);
5498 	mutex_exit(&ill->ill_lock);
5499 
5500 	/*
5501 	 * Now we are done with the module close pieces that
5502 	 * need the netstack_t.
5503 	 */
5504 	netstack_rele(ipst->ips_netstack);
5505 
5506 	mi_close_free((IDP)ill);
5507 	q->q_ptr = WR(q)->q_ptr = NULL;
5508 
5509 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5510 
5511 	return (0);
5512 }
5513 
5514 /*
5515  * This is called as part of close() for both IP and UDP
5516  * in order to quiesce the conn.
5517  */
5518 void
5519 ip_quiesce_conn(conn_t *connp)
5520 {
5521 	boolean_t	drain_cleanup_reqd = B_FALSE;
5522 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5523 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5524 	ip_stack_t	*ipst;
5525 
5526 	ASSERT(!IPCL_IS_TCP(connp));
5527 	ipst = connp->conn_netstack->netstack_ip;
5528 
5529 	/*
5530 	 * Mark the conn as closing, and this conn must not be
5531 	 * inserted in future into any list. Eg. conn_drain_insert(),
5532 	 * won't insert this conn into the conn_drain_list.
5533 	 * Similarly ill_pending_mp_add() will not add any mp to
5534 	 * the pending mp list, after this conn has started closing.
5535 	 *
5536 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5537 	 * cannot get set henceforth.
5538 	 */
5539 	mutex_enter(&connp->conn_lock);
5540 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5541 	connp->conn_state_flags |= CONN_CLOSING;
5542 	if (connp->conn_idl != NULL)
5543 		drain_cleanup_reqd = B_TRUE;
5544 	if (connp->conn_oper_pending_ill != NULL)
5545 		conn_ioctl_cleanup_reqd = B_TRUE;
5546 	if (connp->conn_ilg_inuse != 0)
5547 		ilg_cleanup_reqd = B_TRUE;
5548 	mutex_exit(&connp->conn_lock);
5549 
5550 	if (IPCL_IS_UDP(connp))
5551 		udp_quiesce_conn(connp);
5552 
5553 	if (conn_ioctl_cleanup_reqd)
5554 		conn_ioctl_cleanup(connp);
5555 
5556 	if (is_system_labeled() && connp->conn_anon_port) {
5557 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5558 		    connp->conn_mlp_type, connp->conn_ulp,
5559 		    ntohs(connp->conn_lport), B_FALSE);
5560 		connp->conn_anon_port = 0;
5561 	}
5562 	connp->conn_mlp_type = mlptSingle;
5563 
5564 	/*
5565 	 * Remove this conn from any fanout list it is on.
5566 	 * and then wait for any threads currently operating
5567 	 * on this endpoint to finish
5568 	 */
5569 	ipcl_hash_remove(connp);
5570 
5571 	/*
5572 	 * Remove this conn from the drain list, and do
5573 	 * any other cleanup that may be required.
5574 	 * (Only non-tcp streams may have a non-null conn_idl.
5575 	 * TCP streams are never flow controlled, and
5576 	 * conn_idl will be null)
5577 	 */
5578 	if (drain_cleanup_reqd)
5579 		conn_drain_tail(connp, B_TRUE);
5580 
5581 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5582 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5583 		(void) ip_mrouter_done(NULL, ipst);
5584 
5585 	if (ilg_cleanup_reqd)
5586 		ilg_delete_all(connp);
5587 
5588 	conn_delete_ire(connp, NULL);
5589 
5590 	/*
5591 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5592 	 * callers from write side can't be there now because close
5593 	 * is in progress. The only other caller is ipcl_walk
5594 	 * which checks for the condemned flag.
5595 	 */
5596 	mutex_enter(&connp->conn_lock);
5597 	connp->conn_state_flags |= CONN_CONDEMNED;
5598 	while (connp->conn_ref != 1)
5599 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5600 	connp->conn_state_flags |= CONN_QUIESCED;
5601 	mutex_exit(&connp->conn_lock);
5602 }
5603 
5604 /* ARGSUSED */
5605 int
5606 ip_close(queue_t *q, int flags)
5607 {
5608 	conn_t		*connp;
5609 
5610 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5611 
5612 	/*
5613 	 * Call the appropriate delete routine depending on whether this is
5614 	 * a module or device.
5615 	 */
5616 	if (WR(q)->q_next != NULL) {
5617 		/* This is a module close */
5618 		return (ip_modclose((ill_t *)q->q_ptr));
5619 	}
5620 
5621 	connp = q->q_ptr;
5622 	ip_quiesce_conn(connp);
5623 
5624 	qprocsoff(q);
5625 
5626 	/*
5627 	 * Now we are truly single threaded on this stream, and can
5628 	 * delete the things hanging off the connp, and finally the connp.
5629 	 * We removed this connp from the fanout list, it cannot be
5630 	 * accessed thru the fanouts, and we already waited for the
5631 	 * conn_ref to drop to 0. We are already in close, so
5632 	 * there cannot be any other thread from the top. qprocsoff
5633 	 * has completed, and service has completed or won't run in
5634 	 * future.
5635 	 */
5636 	ASSERT(connp->conn_ref == 1);
5637 
5638 	/*
5639 	 * A conn which was previously marked as IPCL_UDP cannot
5640 	 * retain the flag because it would have been cleared by
5641 	 * udp_close().
5642 	 */
5643 	ASSERT(!IPCL_IS_UDP(connp));
5644 
5645 	if (connp->conn_latch != NULL) {
5646 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5647 		connp->conn_latch = NULL;
5648 	}
5649 	if (connp->conn_policy != NULL) {
5650 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5651 		connp->conn_policy = NULL;
5652 	}
5653 	if (connp->conn_ipsec_opt_mp != NULL) {
5654 		freemsg(connp->conn_ipsec_opt_mp);
5655 		connp->conn_ipsec_opt_mp = NULL;
5656 	}
5657 
5658 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5659 
5660 	connp->conn_ref--;
5661 	ipcl_conn_destroy(connp);
5662 
5663 	q->q_ptr = WR(q)->q_ptr = NULL;
5664 	return (0);
5665 }
5666 
5667 int
5668 ip_snmpmod_close(queue_t *q)
5669 {
5670 	conn_t *connp = Q_TO_CONN(q);
5671 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5672 
5673 	qprocsoff(q);
5674 
5675 	if (connp->conn_flags & IPCL_UDPMOD)
5676 		udp_close_free(connp);
5677 
5678 	if (connp->conn_cred != NULL) {
5679 		crfree(connp->conn_cred);
5680 		connp->conn_cred = NULL;
5681 	}
5682 	CONN_DEC_REF(connp);
5683 	q->q_ptr = WR(q)->q_ptr = NULL;
5684 	return (0);
5685 }
5686 
5687 /*
5688  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5689  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5690  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5691  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5692  * queues as we never enqueue messages there and we don't handle any ioctls.
5693  * Everything else is freed.
5694  */
5695 void
5696 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5697 {
5698 	conn_t	*connp = q->q_ptr;
5699 	pfi_t	setfn;
5700 	pfi_t	getfn;
5701 
5702 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5703 
5704 	switch (DB_TYPE(mp)) {
5705 	case M_PROTO:
5706 	case M_PCPROTO:
5707 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5708 		    ((((union T_primitives *)mp->b_rptr)->type ==
5709 			T_SVR4_OPTMGMT_REQ) ||
5710 		    (((union T_primitives *)mp->b_rptr)->type ==
5711 			T_OPTMGMT_REQ))) {
5712 			/*
5713 			 * This is the only TPI primitive supported. Its
5714 			 * handling does not require tcp_t, but it does require
5715 			 * conn_t to check permissions.
5716 			 */
5717 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5718 
5719 			if (connp->conn_flags & IPCL_TCPMOD) {
5720 				setfn = tcp_snmp_set;
5721 				getfn = tcp_snmp_get;
5722 			} else {
5723 				setfn = udp_snmp_set;
5724 				getfn = udp_snmp_get;
5725 			}
5726 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5727 				freemsg(mp);
5728 				return;
5729 			}
5730 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5731 		    != NULL)
5732 			qreply(q, mp);
5733 		break;
5734 	case M_FLUSH:
5735 	case M_IOCTL:
5736 		putnext(q, mp);
5737 		break;
5738 	default:
5739 		freemsg(mp);
5740 		break;
5741 	}
5742 }
5743 
5744 /* Return the IP checksum for the IP header at "iph". */
5745 uint16_t
5746 ip_csum_hdr(ipha_t *ipha)
5747 {
5748 	uint16_t	*uph;
5749 	uint32_t	sum;
5750 	int		opt_len;
5751 
5752 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5753 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5754 	uph = (uint16_t *)ipha;
5755 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5756 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5757 	if (opt_len > 0) {
5758 		do {
5759 			sum += uph[10];
5760 			sum += uph[11];
5761 			uph += 2;
5762 		} while (--opt_len);
5763 	}
5764 	sum = (sum & 0xFFFF) + (sum >> 16);
5765 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5766 	if (sum == 0xffff)
5767 		sum = 0;
5768 	return ((uint16_t)sum);
5769 }
5770 
5771 /*
5772  * Called when the module is about to be unloaded
5773  */
5774 void
5775 ip_ddi_destroy(void)
5776 {
5777 	tnet_fini();
5778 
5779 	sctp_ddi_g_destroy();
5780 	tcp_ddi_g_destroy();
5781 	ipsec_policy_g_destroy();
5782 	ipcl_g_destroy();
5783 	ip_net_g_destroy();
5784 	ip_ire_g_fini();
5785 	inet_minor_destroy(ip_minor_arena);
5786 
5787 	netstack_unregister(NS_IP);
5788 }
5789 
5790 /*
5791  * First step in cleanup.
5792  */
5793 /* ARGSUSED */
5794 static void
5795 ip_stack_shutdown(netstackid_t stackid, void *arg)
5796 {
5797 	ip_stack_t *ipst = (ip_stack_t *)arg;
5798 
5799 #ifdef NS_DEBUG
5800 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5801 #endif
5802 
5803 	/* Get rid of loopback interfaces and their IREs */
5804 	ip_loopback_cleanup(ipst);
5805 }
5806 
5807 /*
5808  * Free the IP stack instance.
5809  */
5810 static void
5811 ip_stack_fini(netstackid_t stackid, void *arg)
5812 {
5813 	ip_stack_t *ipst = (ip_stack_t *)arg;
5814 	int ret;
5815 
5816 #ifdef NS_DEBUG
5817 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5818 #endif
5819 	ipv4_hook_destroy(ipst);
5820 	ipv6_hook_destroy(ipst);
5821 	ip_net_destroy(ipst);
5822 
5823 	rw_destroy(&ipst->ips_srcid_lock);
5824 
5825 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5826 	ipst->ips_ip_mibkp = NULL;
5827 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5828 	ipst->ips_icmp_mibkp = NULL;
5829 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5830 	ipst->ips_ip_kstat = NULL;
5831 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5832 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5833 	ipst->ips_ip6_kstat = NULL;
5834 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5835 
5836 	nd_free(&ipst->ips_ip_g_nd);
5837 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5838 	ipst->ips_param_arr = NULL;
5839 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5840 	ipst->ips_ndp_arr = NULL;
5841 
5842 	ip_mrouter_stack_destroy(ipst);
5843 
5844 	mutex_destroy(&ipst->ips_ip_mi_lock);
5845 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5846 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5847 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5848 
5849 	ret = untimeout(ipst->ips_igmp_timeout_id);
5850 	if (ret == -1) {
5851 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5852 	} else {
5853 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5854 		ipst->ips_igmp_timeout_id = 0;
5855 	}
5856 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5857 	if (ret == -1) {
5858 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5859 	} else {
5860 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5861 		ipst->ips_igmp_slowtimeout_id = 0;
5862 	}
5863 	ret = untimeout(ipst->ips_mld_timeout_id);
5864 	if (ret == -1) {
5865 		ASSERT(ipst->ips_mld_timeout_id == 0);
5866 	} else {
5867 		ASSERT(ipst->ips_mld_timeout_id != 0);
5868 		ipst->ips_mld_timeout_id = 0;
5869 	}
5870 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5871 	if (ret == -1) {
5872 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5873 	} else {
5874 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5875 		ipst->ips_mld_slowtimeout_id = 0;
5876 	}
5877 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5878 	if (ret == -1) {
5879 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5880 	} else {
5881 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5882 		ipst->ips_ip_ire_expire_id = 0;
5883 	}
5884 
5885 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5886 	mutex_destroy(&ipst->ips_mld_timer_lock);
5887 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5888 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5889 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5890 	rw_destroy(&ipst->ips_ill_g_lock);
5891 
5892 	ip_ire_fini(ipst);
5893 	ip6_asp_free(ipst);
5894 	conn_drain_fini(ipst);
5895 	ipcl_destroy(ipst);
5896 
5897 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5898 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5899 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5900 	ipst->ips_ndp4 = NULL;
5901 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5902 	ipst->ips_ndp6 = NULL;
5903 
5904 	if (ipst->ips_loopback_ksp != NULL) {
5905 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5906 		ipst->ips_loopback_ksp = NULL;
5907 	}
5908 
5909 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5910 	ipst->ips_phyint_g_list = NULL;
5911 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5912 	ipst->ips_ill_g_heads = NULL;
5913 
5914 	kmem_free(ipst, sizeof (*ipst));
5915 }
5916 
5917 /*
5918  * Called when the IP kernel module is loaded into the kernel
5919  */
5920 void
5921 ip_ddi_init(void)
5922 {
5923 	TCP6_MAJ = ddi_name_to_major(TCP6);
5924 	TCP_MAJ	= ddi_name_to_major(TCP);
5925 	SCTP_MAJ = ddi_name_to_major(SCTP);
5926 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5927 
5928 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5929 
5930 	/*
5931 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5932 	 * initial devices: ip, ip6, tcp, tcp6.
5933 	 */
5934 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5935 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5936 		cmn_err(CE_PANIC,
5937 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5938 	}
5939 
5940 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5941 
5942 	ipcl_g_init();
5943 	ip_ire_g_init();
5944 	ip_net_g_init();
5945 
5946 	/*
5947 	 * We want to be informed each time a stack is created or
5948 	 * destroyed in the kernel, so we can maintain the
5949 	 * set of udp_stack_t's.
5950 	 */
5951 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5952 	    ip_stack_fini);
5953 
5954 	ipsec_policy_g_init();
5955 	tcp_ddi_g_init();
5956 	sctp_ddi_g_init();
5957 
5958 	tnet_init();
5959 }
5960 
5961 /*
5962  * Initialize the IP stack instance.
5963  */
5964 static void *
5965 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5966 {
5967 	ip_stack_t	*ipst;
5968 	ipparam_t	*pa;
5969 	ipndp_t		*na;
5970 
5971 #ifdef NS_DEBUG
5972 	printf("ip_stack_init(stack %d)\n", stackid);
5973 #endif
5974 
5975 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5976 	ipst->ips_netstack = ns;
5977 
5978 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5979 	    KM_SLEEP);
5980 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5981 	    KM_SLEEP);
5982 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5983 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5984 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5985 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5986 
5987 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5988 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5989 	ipst->ips_igmp_deferred_next = INFINITY;
5990 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5991 	ipst->ips_mld_deferred_next = INFINITY;
5992 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5993 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5994 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5995 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5996 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5997 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5998 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5999 
6000 	ipcl_init(ipst);
6001 	ip_ire_init(ipst);
6002 	ip6_asp_init(ipst);
6003 	ipif_init(ipst);
6004 	conn_drain_init(ipst);
6005 	ip_mrouter_stack_init(ipst);
6006 
6007 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6008 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6009 
6010 	ipst->ips_ip_multirt_log_interval = 1000;
6011 
6012 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6013 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6014 	ipst->ips_ill_index = 1;
6015 
6016 	ipst->ips_saved_ip_g_forward = -1;
6017 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6018 
6019 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6020 	ipst->ips_param_arr = pa;
6021 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6022 
6023 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6024 	ipst->ips_ndp_arr = na;
6025 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6026 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6027 	    (caddr_t)&ipst->ips_ip_g_forward;
6028 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6029 	    (caddr_t)&ipst->ips_ipv6_forward;
6030 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6031 		"ip_cgtp_filter") == 0);
6032 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6033 	    (caddr_t)&ip_cgtp_filter;
6034 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6035 		"ipmp_hook_emulation") == 0);
6036 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6037 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6038 
6039 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6040 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6041 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6042 
6043 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6044 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6045 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6046 	ipst->ips_ip6_kstat =
6047 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6048 
6049 	ipst->ips_ipmp_enable_failback = B_TRUE;
6050 
6051 	ipst->ips_ip_src_id = 1;
6052 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6053 
6054 	ip_net_init(ipst, ns);
6055 	ipv4_hook_init(ipst);
6056 	ipv6_hook_init(ipst);
6057 
6058 	return (ipst);
6059 }
6060 
6061 /*
6062  * Allocate and initialize a DLPI template of the specified length.  (May be
6063  * called as writer.)
6064  */
6065 mblk_t *
6066 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6067 {
6068 	mblk_t	*mp;
6069 
6070 	mp = allocb(len, BPRI_MED);
6071 	if (!mp)
6072 		return (NULL);
6073 
6074 	/*
6075 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6076 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6077 	 * that other DLPI are M_PROTO.
6078 	 */
6079 	if (prim == DL_INFO_REQ) {
6080 		mp->b_datap->db_type = M_PCPROTO;
6081 	} else {
6082 		mp->b_datap->db_type = M_PROTO;
6083 	}
6084 
6085 	mp->b_wptr = mp->b_rptr + len;
6086 	bzero(mp->b_rptr, len);
6087 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6088 	return (mp);
6089 }
6090 
6091 const char *
6092 dlpi_prim_str(int prim)
6093 {
6094 	switch (prim) {
6095 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6096 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6097 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6098 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6099 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6100 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6101 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6102 	case DL_OK_ACK:		return ("DL_OK_ACK");
6103 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6104 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6105 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6106 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6107 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6108 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6109 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6110 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6111 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6112 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6113 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6114 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6115 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6116 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6117 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6118 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6119 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6120 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6121 	default:		return ("<unknown primitive>");
6122 	}
6123 }
6124 
6125 const char *
6126 dlpi_err_str(int err)
6127 {
6128 	switch (err) {
6129 	case DL_ACCESS:		return ("DL_ACCESS");
6130 	case DL_BADADDR:	return ("DL_BADADDR");
6131 	case DL_BADCORR:	return ("DL_BADCORR");
6132 	case DL_BADDATA:	return ("DL_BADDATA");
6133 	case DL_BADPPA:		return ("DL_BADPPA");
6134 	case DL_BADPRIM:	return ("DL_BADPRIM");
6135 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6136 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6137 	case DL_BADSAP:		return ("DL_BADSAP");
6138 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6139 	case DL_BOUND:		return ("DL_BOUND");
6140 	case DL_INITFAILED:	return ("DL_INITFAILED");
6141 	case DL_NOADDR:		return ("DL_NOADDR");
6142 	case DL_NOTINIT:	return ("DL_NOTINIT");
6143 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6144 	case DL_SYSERR:		return ("DL_SYSERR");
6145 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6146 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6147 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6148 	case DL_TOOMANY:	return ("DL_TOOMANY");
6149 	case DL_NOTENAB:	return ("DL_NOTENAB");
6150 	case DL_BUSY:		return ("DL_BUSY");
6151 	case DL_NOAUTO:		return ("DL_NOAUTO");
6152 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6153 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6154 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6155 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6156 	case DL_PENDING:	return ("DL_PENDING");
6157 	default:		return ("<unknown error>");
6158 	}
6159 }
6160 
6161 /*
6162  * Debug formatting routine.  Returns a character string representation of the
6163  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6164  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6165  *
6166  * Once the ndd table-printing interfaces are removed, this can be changed to
6167  * standard dotted-decimal form.
6168  */
6169 char *
6170 ip_dot_addr(ipaddr_t addr, char *buf)
6171 {
6172 	uint8_t *ap = (uint8_t *)&addr;
6173 
6174 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6175 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6176 	return (buf);
6177 }
6178 
6179 /*
6180  * Write the given MAC address as a printable string in the usual colon-
6181  * separated format.
6182  */
6183 const char *
6184 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6185 {
6186 	char *bp;
6187 
6188 	if (alen == 0 || buflen < 4)
6189 		return ("?");
6190 	bp = buf;
6191 	for (;;) {
6192 		/*
6193 		 * If there are more MAC address bytes available, but we won't
6194 		 * have any room to print them, then add "..." to the string
6195 		 * instead.  See below for the 'magic number' explanation.
6196 		 */
6197 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6198 			(void) strcpy(bp, "...");
6199 			break;
6200 		}
6201 		(void) sprintf(bp, "%02x", *addr++);
6202 		bp += 2;
6203 		if (--alen == 0)
6204 			break;
6205 		*bp++ = ':';
6206 		buflen -= 3;
6207 		/*
6208 		 * At this point, based on the first 'if' statement above,
6209 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6210 		 * buflen >= 4.  The first case leaves room for the final "xx"
6211 		 * number and trailing NUL byte.  The second leaves room for at
6212 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6213 		 * that statement.
6214 		 */
6215 	}
6216 	return (buf);
6217 }
6218 
6219 /*
6220  * Send an ICMP error after patching up the packet appropriately.  Returns
6221  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6222  */
6223 static boolean_t
6224 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6225     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6226     zoneid_t zoneid, ip_stack_t *ipst)
6227 {
6228 	ipha_t *ipha;
6229 	mblk_t *first_mp;
6230 	boolean_t secure;
6231 	unsigned char db_type;
6232 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6233 
6234 	first_mp = mp;
6235 	if (mctl_present) {
6236 		mp = mp->b_cont;
6237 		secure = ipsec_in_is_secure(first_mp);
6238 		ASSERT(mp != NULL);
6239 	} else {
6240 		/*
6241 		 * If this is an ICMP error being reported - which goes
6242 		 * up as M_CTLs, we need to convert them to M_DATA till
6243 		 * we finish checking with global policy because
6244 		 * ipsec_check_global_policy() assumes M_DATA as clear
6245 		 * and M_CTL as secure.
6246 		 */
6247 		db_type = DB_TYPE(mp);
6248 		DB_TYPE(mp) = M_DATA;
6249 		secure = B_FALSE;
6250 	}
6251 	/*
6252 	 * We are generating an icmp error for some inbound packet.
6253 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6254 	 * Before we generate an error, check with global policy
6255 	 * to see whether this is allowed to enter the system. As
6256 	 * there is no "conn", we are checking with global policy.
6257 	 */
6258 	ipha = (ipha_t *)mp->b_rptr;
6259 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6260 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6261 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6262 		if (first_mp == NULL)
6263 			return (B_FALSE);
6264 	}
6265 
6266 	if (!mctl_present)
6267 		DB_TYPE(mp) = db_type;
6268 
6269 	if (flags & IP_FF_SEND_ICMP) {
6270 		if (flags & IP_FF_HDR_COMPLETE) {
6271 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6272 				freemsg(first_mp);
6273 				return (B_TRUE);
6274 			}
6275 		}
6276 		if (flags & IP_FF_CKSUM) {
6277 			/*
6278 			 * Have to correct checksum since
6279 			 * the packet might have been
6280 			 * fragmented and the reassembly code in ip_rput
6281 			 * does not restore the IP checksum.
6282 			 */
6283 			ipha->ipha_hdr_checksum = 0;
6284 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6285 		}
6286 		switch (icmp_type) {
6287 		case ICMP_DEST_UNREACHABLE:
6288 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6289 			    ipst);
6290 			break;
6291 		default:
6292 			freemsg(first_mp);
6293 			break;
6294 		}
6295 	} else {
6296 		freemsg(first_mp);
6297 		return (B_FALSE);
6298 	}
6299 
6300 	return (B_TRUE);
6301 }
6302 
6303 /*
6304  * Used to send an ICMP error message when a packet is received for
6305  * a protocol that is not supported. The mblk passed as argument
6306  * is consumed by this function.
6307  */
6308 void
6309 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6310     ip_stack_t *ipst)
6311 {
6312 	mblk_t *mp;
6313 	ipha_t *ipha;
6314 	ill_t *ill;
6315 	ipsec_in_t *ii;
6316 
6317 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6318 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6319 
6320 	mp = ipsec_mp->b_cont;
6321 	ipsec_mp->b_cont = NULL;
6322 	ipha = (ipha_t *)mp->b_rptr;
6323 	/* Get ill from index in ipsec_in_t. */
6324 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6325 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6326 	    ipst);
6327 	if (ill != NULL) {
6328 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6329 			if (ip_fanout_send_icmp(q, mp, flags,
6330 			    ICMP_DEST_UNREACHABLE,
6331 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6332 				BUMP_MIB(ill->ill_ip_mib,
6333 				    ipIfStatsInUnknownProtos);
6334 			}
6335 		} else {
6336 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6337 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6338 			    0, B_FALSE, zoneid, ipst)) {
6339 				BUMP_MIB(ill->ill_ip_mib,
6340 				    ipIfStatsInUnknownProtos);
6341 			}
6342 		}
6343 		ill_refrele(ill);
6344 	} else { /* re-link for the freemsg() below. */
6345 		ipsec_mp->b_cont = mp;
6346 	}
6347 
6348 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6349 	freemsg(ipsec_mp);
6350 }
6351 
6352 /*
6353  * See if the inbound datagram has had IPsec processing applied to it.
6354  */
6355 boolean_t
6356 ipsec_in_is_secure(mblk_t *ipsec_mp)
6357 {
6358 	ipsec_in_t *ii;
6359 
6360 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6361 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6362 
6363 	if (ii->ipsec_in_loopback) {
6364 		return (ii->ipsec_in_secure);
6365 	} else {
6366 		return (ii->ipsec_in_ah_sa != NULL ||
6367 		    ii->ipsec_in_esp_sa != NULL ||
6368 		    ii->ipsec_in_decaps);
6369 	}
6370 }
6371 
6372 /*
6373  * Handle protocols with which IP is less intimate.  There
6374  * can be more than one stream bound to a particular
6375  * protocol.  When this is the case, normally each one gets a copy
6376  * of any incoming packets.
6377  *
6378  * IPSEC NOTE :
6379  *
6380  * Don't allow a secure packet going up a non-secure connection.
6381  * We don't allow this because
6382  *
6383  * 1) Reply might go out in clear which will be dropped at
6384  *    the sending side.
6385  * 2) If the reply goes out in clear it will give the
6386  *    adversary enough information for getting the key in
6387  *    most of the cases.
6388  *
6389  * Moreover getting a secure packet when we expect clear
6390  * implies that SA's were added without checking for
6391  * policy on both ends. This should not happen once ISAKMP
6392  * is used to negotiate SAs as SAs will be added only after
6393  * verifying the policy.
6394  *
6395  * NOTE : If the packet was tunneled and not multicast we only send
6396  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6397  * back to delivering packets to AF_INET6 raw sockets.
6398  *
6399  * IPQoS Notes:
6400  * Once we have determined the client, invoke IPPF processing.
6401  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6402  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6403  * ip_policy will be false.
6404  *
6405  * Zones notes:
6406  * Currently only applications in the global zone can create raw sockets for
6407  * protocols other than ICMP. So unlike the broadcast / multicast case of
6408  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6409  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6410  */
6411 static void
6412 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6413     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6414     zoneid_t zoneid)
6415 {
6416 	queue_t	*rq;
6417 	mblk_t	*mp1, *first_mp1;
6418 	uint_t	protocol = ipha->ipha_protocol;
6419 	ipaddr_t dst;
6420 	boolean_t one_only;
6421 	mblk_t *first_mp = mp;
6422 	boolean_t secure;
6423 	uint32_t ill_index;
6424 	conn_t	*connp, *first_connp, *next_connp;
6425 	connf_t	*connfp;
6426 	boolean_t shared_addr;
6427 	mib2_ipIfStatsEntry_t *mibptr;
6428 	ip_stack_t *ipst = recv_ill->ill_ipst;
6429 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6430 
6431 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6432 	if (mctl_present) {
6433 		mp = first_mp->b_cont;
6434 		secure = ipsec_in_is_secure(first_mp);
6435 		ASSERT(mp != NULL);
6436 	} else {
6437 		secure = B_FALSE;
6438 	}
6439 	dst = ipha->ipha_dst;
6440 	/*
6441 	 * If the packet was tunneled and not multicast we only send to it
6442 	 * the first match.
6443 	 */
6444 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6445 	    !CLASSD(dst));
6446 
6447 	shared_addr = (zoneid == ALL_ZONES);
6448 	if (shared_addr) {
6449 		/*
6450 		 * We don't allow multilevel ports for raw IP, so no need to
6451 		 * check for that here.
6452 		 */
6453 		zoneid = tsol_packet_to_zoneid(mp);
6454 	}
6455 
6456 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6457 	mutex_enter(&connfp->connf_lock);
6458 	connp = connfp->connf_head;
6459 	for (connp = connfp->connf_head; connp != NULL;
6460 		connp = connp->conn_next) {
6461 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6462 		    zoneid) &&
6463 		    (!is_system_labeled() ||
6464 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6465 		    connp)))
6466 			break;
6467 	}
6468 
6469 	if (connp == NULL || connp->conn_upq == NULL) {
6470 		/*
6471 		 * No one bound to these addresses.  Is
6472 		 * there a client that wants all
6473 		 * unclaimed datagrams?
6474 		 */
6475 		mutex_exit(&connfp->connf_lock);
6476 		/*
6477 		 * Check for IPPROTO_ENCAP...
6478 		 */
6479 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6480 			/*
6481 			 * If an IPsec mblk is here on a multicast
6482 			 * tunnel (using ip_mroute stuff), check policy here,
6483 			 * THEN ship off to ip_mroute_decap().
6484 			 *
6485 			 * BTW,  If I match a configured IP-in-IP
6486 			 * tunnel, this path will not be reached, and
6487 			 * ip_mroute_decap will never be called.
6488 			 */
6489 			first_mp = ipsec_check_global_policy(first_mp, connp,
6490 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6491 			if (first_mp != NULL) {
6492 				if (mctl_present)
6493 					freeb(first_mp);
6494 				ip_mroute_decap(q, mp, ill);
6495 			} /* Else we already freed everything! */
6496 		} else {
6497 			/*
6498 			 * Otherwise send an ICMP protocol unreachable.
6499 			 */
6500 			if (ip_fanout_send_icmp(q, first_mp, flags,
6501 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6502 			    mctl_present, zoneid, ipst)) {
6503 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6504 			}
6505 		}
6506 		return;
6507 	}
6508 	CONN_INC_REF(connp);
6509 	first_connp = connp;
6510 
6511 	/*
6512 	 * Only send message to one tunnel driver by immediately
6513 	 * terminating the loop.
6514 	 */
6515 	connp = one_only ? NULL : connp->conn_next;
6516 
6517 	for (;;) {
6518 		while (connp != NULL) {
6519 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6520 			    flags, zoneid) &&
6521 			    (!is_system_labeled() ||
6522 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6523 			    shared_addr, connp)))
6524 				break;
6525 			connp = connp->conn_next;
6526 		}
6527 
6528 		/*
6529 		 * Copy the packet.
6530 		 */
6531 		if (connp == NULL || connp->conn_upq == NULL ||
6532 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6533 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6534 			/*
6535 			 * No more interested clients or memory
6536 			 * allocation failed
6537 			 */
6538 			connp = first_connp;
6539 			break;
6540 		}
6541 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6542 		CONN_INC_REF(connp);
6543 		mutex_exit(&connfp->connf_lock);
6544 		rq = connp->conn_rq;
6545 		if (!canputnext(rq)) {
6546 			if (flags & IP_FF_RAWIP) {
6547 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6548 			} else {
6549 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6550 			}
6551 
6552 			freemsg(first_mp1);
6553 		} else {
6554 			/*
6555 			 * Don't enforce here if we're an actual tunnel -
6556 			 * let "tun" do it instead.
6557 			 */
6558 			if (!IPCL_IS_IPTUN(connp) &&
6559 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6560 			    secure)) {
6561 				first_mp1 = ipsec_check_inbound_policy
6562 				    (first_mp1, connp, ipha, NULL,
6563 				    mctl_present);
6564 			}
6565 			if (first_mp1 != NULL) {
6566 				int in_flags = 0;
6567 				/*
6568 				 * ip_fanout_proto also gets called from
6569 				 * icmp_inbound_error_fanout, in which case
6570 				 * the msg type is M_CTL.  Don't add info
6571 				 * in this case for the time being. In future
6572 				 * when there is a need for knowing the
6573 				 * inbound iface index for ICMP error msgs,
6574 				 * then this can be changed.
6575 				 */
6576 				if (connp->conn_recvif)
6577 					in_flags = IPF_RECVIF;
6578 				/*
6579 				 * The ULP may support IP_RECVPKTINFO for both
6580 				 * IP v4 and v6 so pass the appropriate argument
6581 				 * based on conn IP version.
6582 				 */
6583 				if (connp->conn_ip_recvpktinfo) {
6584 					if (connp->conn_af_isv6) {
6585 						/*
6586 						 * V6 only needs index
6587 						 */
6588 						in_flags |= IPF_RECVIF;
6589 					} else {
6590 						/*
6591 						 * V4 needs index +
6592 						 * matching address.
6593 						 */
6594 						in_flags |= IPF_RECVADDR;
6595 					}
6596 				}
6597 				if ((in_flags != 0) &&
6598 				    (mp->b_datap->db_type != M_CTL)) {
6599 					/*
6600 					 * the actual data will be
6601 					 * contained in b_cont upon
6602 					 * successful return of the
6603 					 * following call else
6604 					 * original mblk is returned
6605 					 */
6606 					ASSERT(recv_ill != NULL);
6607 					mp1 = ip_add_info(mp1, recv_ill,
6608 					    in_flags, IPCL_ZONEID(connp), ipst);
6609 				}
6610 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6611 				if (mctl_present)
6612 					freeb(first_mp1);
6613 				putnext(rq, mp1);
6614 			}
6615 		}
6616 		mutex_enter(&connfp->connf_lock);
6617 		/* Follow the next pointer before releasing the conn. */
6618 		next_connp = connp->conn_next;
6619 		CONN_DEC_REF(connp);
6620 		connp = next_connp;
6621 	}
6622 
6623 	/* Last one.  Send it upstream. */
6624 	mutex_exit(&connfp->connf_lock);
6625 
6626 	/*
6627 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6628 	 * will be set to false.
6629 	 */
6630 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6631 		ill_index = ill->ill_phyint->phyint_ifindex;
6632 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6633 		if (mp == NULL) {
6634 			CONN_DEC_REF(connp);
6635 			if (mctl_present) {
6636 				freeb(first_mp);
6637 			}
6638 			return;
6639 		}
6640 	}
6641 
6642 	rq = connp->conn_rq;
6643 	if (!canputnext(rq)) {
6644 		if (flags & IP_FF_RAWIP) {
6645 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6646 		} else {
6647 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6648 		}
6649 
6650 		freemsg(first_mp);
6651 	} else {
6652 		if (IPCL_IS_IPTUN(connp)) {
6653 			/*
6654 			 * Tunneled packet.  We enforce policy in the tunnel
6655 			 * module itself.
6656 			 *
6657 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6658 			 * a policy check.
6659 			 */
6660 			putnext(rq, first_mp);
6661 			CONN_DEC_REF(connp);
6662 			return;
6663 		}
6664 
6665 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6666 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6667 			    ipha, NULL, mctl_present);
6668 		}
6669 
6670 		if (first_mp != NULL) {
6671 			int in_flags = 0;
6672 
6673 			/*
6674 			 * ip_fanout_proto also gets called
6675 			 * from icmp_inbound_error_fanout, in
6676 			 * which case the msg type is M_CTL.
6677 			 * Don't add info in this case for time
6678 			 * being. In future when there is a
6679 			 * need for knowing the inbound iface
6680 			 * index for ICMP error msgs, then this
6681 			 * can be changed
6682 			 */
6683 			if (connp->conn_recvif)
6684 				in_flags = IPF_RECVIF;
6685 			if (connp->conn_ip_recvpktinfo) {
6686 				if (connp->conn_af_isv6) {
6687 					/*
6688 					 * V6 only needs index
6689 					 */
6690 					in_flags |= IPF_RECVIF;
6691 				} else {
6692 					/*
6693 					 * V4 needs index +
6694 					 * matching address.
6695 					 */
6696 					in_flags |= IPF_RECVADDR;
6697 				}
6698 			}
6699 			if ((in_flags != 0) &&
6700 			    (mp->b_datap->db_type != M_CTL)) {
6701 
6702 				/*
6703 				 * the actual data will be contained in
6704 				 * b_cont upon successful return
6705 				 * of the following call else original
6706 				 * mblk is returned
6707 				 */
6708 				ASSERT(recv_ill != NULL);
6709 				mp = ip_add_info(mp, recv_ill,
6710 				    in_flags, IPCL_ZONEID(connp), ipst);
6711 			}
6712 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6713 			putnext(rq, mp);
6714 			if (mctl_present)
6715 				freeb(first_mp);
6716 		}
6717 	}
6718 	CONN_DEC_REF(connp);
6719 }
6720 
6721 /*
6722  * Fanout for TCP packets
6723  * The caller puts <fport, lport> in the ports parameter.
6724  *
6725  * IPQoS Notes
6726  * Before sending it to the client, invoke IPPF processing.
6727  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6728  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6729  * ip_policy is false.
6730  */
6731 static void
6732 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6733     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6734 {
6735 	mblk_t  *first_mp;
6736 	boolean_t secure;
6737 	uint32_t ill_index;
6738 	int	ip_hdr_len;
6739 	tcph_t	*tcph;
6740 	boolean_t syn_present = B_FALSE;
6741 	conn_t	*connp;
6742 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6743 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6744 
6745 	ASSERT(recv_ill != NULL);
6746 
6747 	first_mp = mp;
6748 	if (mctl_present) {
6749 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6750 		mp = first_mp->b_cont;
6751 		secure = ipsec_in_is_secure(first_mp);
6752 		ASSERT(mp != NULL);
6753 	} else {
6754 		secure = B_FALSE;
6755 	}
6756 
6757 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6758 
6759 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6760 		    zoneid, ipst)) == NULL) {
6761 		/*
6762 		 * No connected connection or listener. Send a
6763 		 * TH_RST via tcp_xmit_listeners_reset.
6764 		 */
6765 
6766 		/* Initiate IPPf processing, if needed. */
6767 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6768 			uint32_t ill_index;
6769 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6770 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6771 			if (first_mp == NULL)
6772 				return;
6773 		}
6774 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6775 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6776 		    zoneid));
6777 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6778 		    ipst->ips_netstack->netstack_tcp);
6779 		return;
6780 	}
6781 
6782 	/*
6783 	 * Allocate the SYN for the TCP connection here itself
6784 	 */
6785 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6786 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6787 		if (IPCL_IS_TCP(connp)) {
6788 			squeue_t *sqp;
6789 
6790 			/*
6791 			 * For fused tcp loopback, assign the eager's
6792 			 * squeue to be that of the active connect's.
6793 			 * Note that we don't check for IP_FF_LOOPBACK
6794 			 * here since this routine gets called only
6795 			 * for loopback (unlike the IPv6 counterpart).
6796 			 */
6797 			ASSERT(Q_TO_CONN(q) != NULL);
6798 			if (do_tcp_fusion &&
6799 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6800 			    !secure &&
6801 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6802 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6803 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6804 				sqp = Q_TO_CONN(q)->conn_sqp;
6805 			} else {
6806 				sqp = IP_SQUEUE_GET(lbolt);
6807 			}
6808 
6809 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6810 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6811 			syn_present = B_TRUE;
6812 		}
6813 	}
6814 
6815 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6816 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6817 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6818 		if ((flags & TH_RST) || (flags & TH_URG)) {
6819 			CONN_DEC_REF(connp);
6820 			freemsg(first_mp);
6821 			return;
6822 		}
6823 		if (flags & TH_ACK) {
6824 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6825 			    ipst->ips_netstack->netstack_tcp);
6826 			CONN_DEC_REF(connp);
6827 			return;
6828 		}
6829 
6830 		CONN_DEC_REF(connp);
6831 		freemsg(first_mp);
6832 		return;
6833 	}
6834 
6835 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6836 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6837 		    NULL, mctl_present);
6838 		if (first_mp == NULL) {
6839 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6840 			CONN_DEC_REF(connp);
6841 			return;
6842 		}
6843 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6844 			ASSERT(syn_present);
6845 			if (mctl_present) {
6846 				ASSERT(first_mp != mp);
6847 				first_mp->b_datap->db_struioflag |=
6848 				    STRUIO_POLICY;
6849 			} else {
6850 				ASSERT(first_mp == mp);
6851 				mp->b_datap->db_struioflag &=
6852 				    ~STRUIO_EAGER;
6853 				mp->b_datap->db_struioflag |=
6854 				    STRUIO_POLICY;
6855 			}
6856 		} else {
6857 			/*
6858 			 * Discard first_mp early since we're dealing with a
6859 			 * fully-connected conn_t and tcp doesn't do policy in
6860 			 * this case.
6861 			 */
6862 			if (mctl_present) {
6863 				freeb(first_mp);
6864 				mctl_present = B_FALSE;
6865 			}
6866 			first_mp = mp;
6867 		}
6868 	}
6869 
6870 	/*
6871 	 * Initiate policy processing here if needed. If we get here from
6872 	 * icmp_inbound_error_fanout, ip_policy is false.
6873 	 */
6874 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6875 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6876 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6877 		if (mp == NULL) {
6878 			CONN_DEC_REF(connp);
6879 			if (mctl_present)
6880 				freeb(first_mp);
6881 			return;
6882 		} else if (mctl_present) {
6883 			ASSERT(first_mp != mp);
6884 			first_mp->b_cont = mp;
6885 		} else {
6886 			first_mp = mp;
6887 		}
6888 	}
6889 
6890 
6891 
6892 	/* Handle socket options. */
6893 	if (!syn_present &&
6894 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6895 		/* Add header */
6896 		ASSERT(recv_ill != NULL);
6897 		/*
6898 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6899 		 * IPF_RECVIF.
6900 		 */
6901 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6902 		    ipst);
6903 		if (mp == NULL) {
6904 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6905 			CONN_DEC_REF(connp);
6906 			if (mctl_present)
6907 				freeb(first_mp);
6908 			return;
6909 		} else if (mctl_present) {
6910 			/*
6911 			 * ip_add_info might return a new mp.
6912 			 */
6913 			ASSERT(first_mp != mp);
6914 			first_mp->b_cont = mp;
6915 		} else {
6916 			first_mp = mp;
6917 		}
6918 	}
6919 
6920 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6921 	if (IPCL_IS_TCP(connp)) {
6922 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6923 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6924 	} else {
6925 		putnext(connp->conn_rq, first_mp);
6926 		CONN_DEC_REF(connp);
6927 	}
6928 }
6929 
6930 /*
6931  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6932  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6933  * Caller is responsible for dropping references to the conn, and freeing
6934  * first_mp.
6935  *
6936  * IPQoS Notes
6937  * Before sending it to the client, invoke IPPF processing. Policy processing
6938  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6939  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6940  * ip_wput_local, ip_policy is false.
6941  */
6942 static void
6943 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6944     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6945     boolean_t ip_policy)
6946 {
6947 	boolean_t	mctl_present = (first_mp != NULL);
6948 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6949 	uint32_t	ill_index;
6950 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6951 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6952 
6953 	ASSERT(ill != NULL);
6954 
6955 	if (mctl_present)
6956 		first_mp->b_cont = mp;
6957 	else
6958 		first_mp = mp;
6959 
6960 	if (CONN_UDP_FLOWCTLD(connp)) {
6961 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6962 		freemsg(first_mp);
6963 		return;
6964 	}
6965 
6966 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6967 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6968 		    NULL, mctl_present);
6969 		if (first_mp == NULL) {
6970 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6971 			return;	/* Freed by ipsec_check_inbound_policy(). */
6972 		}
6973 	}
6974 	if (mctl_present)
6975 		freeb(first_mp);
6976 
6977 	/* Handle options. */
6978 	if (connp->conn_recvif)
6979 		in_flags = IPF_RECVIF;
6980 	/*
6981 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6982 	 * passed to ip_add_info is based on IP version of connp.
6983 	 */
6984 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6985 		if (connp->conn_af_isv6) {
6986 			/*
6987 			 * V6 only needs index
6988 			 */
6989 			in_flags |= IPF_RECVIF;
6990 		} else {
6991 			/*
6992 			 * V4 needs index + matching address.
6993 			 */
6994 			in_flags |= IPF_RECVADDR;
6995 		}
6996 	}
6997 
6998 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6999 		in_flags |= IPF_RECVSLLA;
7000 
7001 	/*
7002 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7003 	 * freed if the packet is dropped. The caller will do so.
7004 	 */
7005 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7006 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7007 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7008 		if (mp == NULL) {
7009 			return;
7010 		}
7011 	}
7012 	if ((in_flags != 0) &&
7013 	    (mp->b_datap->db_type != M_CTL)) {
7014 		/*
7015 		 * The actual data will be contained in b_cont
7016 		 * upon successful return of the following call
7017 		 * else original mblk is returned
7018 		 */
7019 		ASSERT(recv_ill != NULL);
7020 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7021 		    ipst);
7022 	}
7023 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7024 	/* Send it upstream */
7025 	CONN_UDP_RECV(connp, mp);
7026 }
7027 
7028 /*
7029  * Fanout for UDP packets.
7030  * The caller puts <fport, lport> in the ports parameter.
7031  *
7032  * If SO_REUSEADDR is set all multicast and broadcast packets
7033  * will be delivered to all streams bound to the same port.
7034  *
7035  * Zones notes:
7036  * Multicast and broadcast packets will be distributed to streams in all zones.
7037  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7038  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7039  * packets. To maintain this behavior with multiple zones, the conns are grouped
7040  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7041  * each zone. If unset, all the following conns in the same zone are skipped.
7042  */
7043 static void
7044 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7045     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7046     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7047 {
7048 	uint32_t	dstport, srcport;
7049 	ipaddr_t	dst;
7050 	mblk_t		*first_mp;
7051 	boolean_t	secure;
7052 	in6_addr_t	v6src;
7053 	conn_t		*connp;
7054 	connf_t		*connfp;
7055 	conn_t		*first_connp;
7056 	conn_t		*next_connp;
7057 	mblk_t		*mp1, *first_mp1;
7058 	ipaddr_t	src;
7059 	zoneid_t	last_zoneid;
7060 	boolean_t	reuseaddr;
7061 	boolean_t	shared_addr;
7062 	ip_stack_t	*ipst;
7063 
7064 	ASSERT(recv_ill != NULL);
7065 	ipst = recv_ill->ill_ipst;
7066 
7067 	first_mp = mp;
7068 	if (mctl_present) {
7069 		mp = first_mp->b_cont;
7070 		first_mp->b_cont = NULL;
7071 		secure = ipsec_in_is_secure(first_mp);
7072 		ASSERT(mp != NULL);
7073 	} else {
7074 		first_mp = NULL;
7075 		secure = B_FALSE;
7076 	}
7077 
7078 	/* Extract ports in net byte order */
7079 	dstport = htons(ntohl(ports) & 0xFFFF);
7080 	srcport = htons(ntohl(ports) >> 16);
7081 	dst = ipha->ipha_dst;
7082 	src = ipha->ipha_src;
7083 
7084 	shared_addr = (zoneid == ALL_ZONES);
7085 	if (shared_addr) {
7086 		/*
7087 		 * No need to handle exclusive-stack zones since ALL_ZONES
7088 		 * only applies to the shared stack.
7089 		 */
7090 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7091 		if (zoneid == ALL_ZONES)
7092 			zoneid = tsol_packet_to_zoneid(mp);
7093 	}
7094 
7095 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7096 	mutex_enter(&connfp->connf_lock);
7097 	connp = connfp->connf_head;
7098 	if (!broadcast && !CLASSD(dst)) {
7099 		/*
7100 		 * Not broadcast or multicast. Send to the one (first)
7101 		 * client we find. No need to check conn_wantpacket()
7102 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7103 		 * IPv4 unicast packets.
7104 		 */
7105 		while ((connp != NULL) &&
7106 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7107 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7108 			connp = connp->conn_next;
7109 		}
7110 
7111 		if (connp == NULL || connp->conn_upq == NULL)
7112 			goto notfound;
7113 
7114 		if (is_system_labeled() &&
7115 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7116 		    connp))
7117 			goto notfound;
7118 
7119 		CONN_INC_REF(connp);
7120 		mutex_exit(&connfp->connf_lock);
7121 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7122 		    flags, recv_ill, ip_policy);
7123 		IP_STAT(ipst, ip_udp_fannorm);
7124 		CONN_DEC_REF(connp);
7125 		return;
7126 	}
7127 
7128 	/*
7129 	 * Broadcast and multicast case
7130 	 *
7131 	 * Need to check conn_wantpacket().
7132 	 * If SO_REUSEADDR has been set on the first we send the
7133 	 * packet to all clients that have joined the group and
7134 	 * match the port.
7135 	 */
7136 
7137 	while (connp != NULL) {
7138 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7139 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7140 		    (!is_system_labeled() ||
7141 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7142 		    connp)))
7143 			break;
7144 		connp = connp->conn_next;
7145 	}
7146 
7147 	if (connp == NULL || connp->conn_upq == NULL)
7148 		goto notfound;
7149 
7150 	first_connp = connp;
7151 	/*
7152 	 * When SO_REUSEADDR is not set, send the packet only to the first
7153 	 * matching connection in its zone by keeping track of the zoneid.
7154 	 */
7155 	reuseaddr = first_connp->conn_reuseaddr;
7156 	last_zoneid = first_connp->conn_zoneid;
7157 
7158 	CONN_INC_REF(connp);
7159 	connp = connp->conn_next;
7160 	for (;;) {
7161 		while (connp != NULL) {
7162 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7163 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7164 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7165 			    (!is_system_labeled() ||
7166 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7167 			    shared_addr, connp)))
7168 				break;
7169 			connp = connp->conn_next;
7170 		}
7171 		/*
7172 		 * Just copy the data part alone. The mctl part is
7173 		 * needed just for verifying policy and it is never
7174 		 * sent up.
7175 		 */
7176 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7177 		    ((mp1 = copymsg(mp)) == NULL))) {
7178 			/*
7179 			 * No more interested clients or memory
7180 			 * allocation failed
7181 			 */
7182 			connp = first_connp;
7183 			break;
7184 		}
7185 		if (connp->conn_zoneid != last_zoneid) {
7186 			/*
7187 			 * Update the zoneid so that the packet isn't sent to
7188 			 * any more conns in the same zone unless SO_REUSEADDR
7189 			 * is set.
7190 			 */
7191 			reuseaddr = connp->conn_reuseaddr;
7192 			last_zoneid = connp->conn_zoneid;
7193 		}
7194 		if (first_mp != NULL) {
7195 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7196 			    ipsec_info_type == IPSEC_IN);
7197 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7198 			    ipst->ips_netstack);
7199 			if (first_mp1 == NULL) {
7200 				freemsg(mp1);
7201 				connp = first_connp;
7202 				break;
7203 			}
7204 		} else {
7205 			first_mp1 = NULL;
7206 		}
7207 		CONN_INC_REF(connp);
7208 		mutex_exit(&connfp->connf_lock);
7209 		/*
7210 		 * IPQoS notes: We don't send the packet for policy
7211 		 * processing here, will do it for the last one (below).
7212 		 * i.e. we do it per-packet now, but if we do policy
7213 		 * processing per-conn, then we would need to do it
7214 		 * here too.
7215 		 */
7216 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7217 		    ipha, flags, recv_ill, B_FALSE);
7218 		mutex_enter(&connfp->connf_lock);
7219 		/* Follow the next pointer before releasing the conn. */
7220 		next_connp = connp->conn_next;
7221 		IP_STAT(ipst, ip_udp_fanmb);
7222 		CONN_DEC_REF(connp);
7223 		connp = next_connp;
7224 	}
7225 
7226 	/* Last one.  Send it upstream. */
7227 	mutex_exit(&connfp->connf_lock);
7228 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7229 	    recv_ill, ip_policy);
7230 	IP_STAT(ipst, ip_udp_fanmb);
7231 	CONN_DEC_REF(connp);
7232 	return;
7233 
7234 notfound:
7235 
7236 	mutex_exit(&connfp->connf_lock);
7237 	IP_STAT(ipst, ip_udp_fanothers);
7238 	/*
7239 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7240 	 * have already been matched above, since they live in the IPv4
7241 	 * fanout tables. This implies we only need to
7242 	 * check for IPv6 in6addr_any endpoints here.
7243 	 * Thus we compare using ipv6_all_zeros instead of the destination
7244 	 * address, except for the multicast group membership lookup which
7245 	 * uses the IPv4 destination.
7246 	 */
7247 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7248 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7249 	mutex_enter(&connfp->connf_lock);
7250 	connp = connfp->connf_head;
7251 	if (!broadcast && !CLASSD(dst)) {
7252 		while (connp != NULL) {
7253 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7254 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7255 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7256 			    !connp->conn_ipv6_v6only)
7257 				break;
7258 			connp = connp->conn_next;
7259 		}
7260 
7261 		if (connp != NULL && is_system_labeled() &&
7262 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7263 		    connp))
7264 			connp = NULL;
7265 
7266 		if (connp == NULL || connp->conn_upq == NULL) {
7267 			/*
7268 			 * No one bound to this port.  Is
7269 			 * there a client that wants all
7270 			 * unclaimed datagrams?
7271 			 */
7272 			mutex_exit(&connfp->connf_lock);
7273 
7274 			if (mctl_present)
7275 				first_mp->b_cont = mp;
7276 			else
7277 				first_mp = mp;
7278 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7279 			    connf_head != NULL) {
7280 				ip_fanout_proto(q, first_mp, ill, ipha,
7281 				    flags | IP_FF_RAWIP, mctl_present,
7282 				    ip_policy, recv_ill, zoneid);
7283 			} else {
7284 				if (ip_fanout_send_icmp(q, first_mp, flags,
7285 				    ICMP_DEST_UNREACHABLE,
7286 				    ICMP_PORT_UNREACHABLE,
7287 				    mctl_present, zoneid, ipst)) {
7288 					BUMP_MIB(ill->ill_ip_mib,
7289 					    udpIfStatsNoPorts);
7290 				}
7291 			}
7292 			return;
7293 		}
7294 
7295 		CONN_INC_REF(connp);
7296 		mutex_exit(&connfp->connf_lock);
7297 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7298 		    flags, recv_ill, ip_policy);
7299 		CONN_DEC_REF(connp);
7300 		return;
7301 	}
7302 	/*
7303 	 * IPv4 multicast packet being delivered to an AF_INET6
7304 	 * in6addr_any endpoint.
7305 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7306 	 * and not conn_wantpacket_v6() since any multicast membership is
7307 	 * for an IPv4-mapped multicast address.
7308 	 * The packet is sent to all clients in all zones that have joined the
7309 	 * group and match the port.
7310 	 */
7311 	while (connp != NULL) {
7312 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7313 		    srcport, v6src) &&
7314 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7315 		    (!is_system_labeled() ||
7316 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7317 		    connp)))
7318 			break;
7319 		connp = connp->conn_next;
7320 	}
7321 
7322 	if (connp == NULL || connp->conn_upq == NULL) {
7323 		/*
7324 		 * No one bound to this port.  Is
7325 		 * there a client that wants all
7326 		 * unclaimed datagrams?
7327 		 */
7328 		mutex_exit(&connfp->connf_lock);
7329 
7330 		if (mctl_present)
7331 			first_mp->b_cont = mp;
7332 		else
7333 			first_mp = mp;
7334 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7335 		    NULL) {
7336 			ip_fanout_proto(q, first_mp, ill, ipha,
7337 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7338 			    recv_ill, zoneid);
7339 		} else {
7340 			/*
7341 			 * We used to attempt to send an icmp error here, but
7342 			 * since this is known to be a multicast packet
7343 			 * and we don't send icmp errors in response to
7344 			 * multicast, just drop the packet and give up sooner.
7345 			 */
7346 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7347 			freemsg(first_mp);
7348 		}
7349 		return;
7350 	}
7351 
7352 	first_connp = connp;
7353 
7354 	CONN_INC_REF(connp);
7355 	connp = connp->conn_next;
7356 	for (;;) {
7357 		while (connp != NULL) {
7358 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7359 			    ipv6_all_zeros, srcport, v6src) &&
7360 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7361 			    (!is_system_labeled() ||
7362 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7363 			    shared_addr, connp)))
7364 				break;
7365 			connp = connp->conn_next;
7366 		}
7367 		/*
7368 		 * Just copy the data part alone. The mctl part is
7369 		 * needed just for verifying policy and it is never
7370 		 * sent up.
7371 		 */
7372 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7373 		    ((mp1 = copymsg(mp)) == NULL))) {
7374 			/*
7375 			 * No more intested clients or memory
7376 			 * allocation failed
7377 			 */
7378 			connp = first_connp;
7379 			break;
7380 		}
7381 		if (first_mp != NULL) {
7382 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7383 			    ipsec_info_type == IPSEC_IN);
7384 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7385 			    ipst->ips_netstack);
7386 			if (first_mp1 == NULL) {
7387 				freemsg(mp1);
7388 				connp = first_connp;
7389 				break;
7390 			}
7391 		} else {
7392 			first_mp1 = NULL;
7393 		}
7394 		CONN_INC_REF(connp);
7395 		mutex_exit(&connfp->connf_lock);
7396 		/*
7397 		 * IPQoS notes: We don't send the packet for policy
7398 		 * processing here, will do it for the last one (below).
7399 		 * i.e. we do it per-packet now, but if we do policy
7400 		 * processing per-conn, then we would need to do it
7401 		 * here too.
7402 		 */
7403 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7404 		    ipha, flags, recv_ill, B_FALSE);
7405 		mutex_enter(&connfp->connf_lock);
7406 		/* Follow the next pointer before releasing the conn. */
7407 		next_connp = connp->conn_next;
7408 		CONN_DEC_REF(connp);
7409 		connp = next_connp;
7410 	}
7411 
7412 	/* Last one.  Send it upstream. */
7413 	mutex_exit(&connfp->connf_lock);
7414 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7415 	    recv_ill, ip_policy);
7416 	CONN_DEC_REF(connp);
7417 }
7418 
7419 /*
7420  * Complete the ip_wput header so that it
7421  * is possible to generate ICMP
7422  * errors.
7423  */
7424 int
7425 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7426 {
7427 	ire_t *ire;
7428 
7429 	if (ipha->ipha_src == INADDR_ANY) {
7430 		ire = ire_lookup_local(zoneid, ipst);
7431 		if (ire == NULL) {
7432 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7433 			return (1);
7434 		}
7435 		ipha->ipha_src = ire->ire_addr;
7436 		ire_refrele(ire);
7437 	}
7438 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7439 	ipha->ipha_hdr_checksum = 0;
7440 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7441 	return (0);
7442 }
7443 
7444 /*
7445  * Nobody should be sending
7446  * packets up this stream
7447  */
7448 static void
7449 ip_lrput(queue_t *q, mblk_t *mp)
7450 {
7451 	mblk_t *mp1;
7452 
7453 	switch (mp->b_datap->db_type) {
7454 	case M_FLUSH:
7455 		/* Turn around */
7456 		if (*mp->b_rptr & FLUSHW) {
7457 			*mp->b_rptr &= ~FLUSHR;
7458 			qreply(q, mp);
7459 			return;
7460 		}
7461 		break;
7462 	}
7463 	/* Could receive messages that passed through ar_rput */
7464 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7465 		mp1->b_prev = mp1->b_next = NULL;
7466 	freemsg(mp);
7467 }
7468 
7469 /* Nobody should be sending packets down this stream */
7470 /* ARGSUSED */
7471 void
7472 ip_lwput(queue_t *q, mblk_t *mp)
7473 {
7474 	freemsg(mp);
7475 }
7476 
7477 /*
7478  * Move the first hop in any source route to ipha_dst and remove that part of
7479  * the source route.  Called by other protocols.  Errors in option formatting
7480  * are ignored - will be handled by ip_wput_options Return the final
7481  * destination (either ipha_dst or the last entry in a source route.)
7482  */
7483 ipaddr_t
7484 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7485 {
7486 	ipoptp_t	opts;
7487 	uchar_t		*opt;
7488 	uint8_t		optval;
7489 	uint8_t		optlen;
7490 	ipaddr_t	dst;
7491 	int		i;
7492 	ire_t		*ire;
7493 	ip_stack_t	*ipst = ns->netstack_ip;
7494 
7495 	ip2dbg(("ip_massage_options\n"));
7496 	dst = ipha->ipha_dst;
7497 	for (optval = ipoptp_first(&opts, ipha);
7498 	    optval != IPOPT_EOL;
7499 	    optval = ipoptp_next(&opts)) {
7500 		opt = opts.ipoptp_cur;
7501 		switch (optval) {
7502 			uint8_t off;
7503 		case IPOPT_SSRR:
7504 		case IPOPT_LSRR:
7505 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7506 				ip1dbg(("ip_massage_options: bad src route\n"));
7507 				break;
7508 			}
7509 			optlen = opts.ipoptp_len;
7510 			off = opt[IPOPT_OFFSET];
7511 			off--;
7512 		redo_srr:
7513 			if (optlen < IP_ADDR_LEN ||
7514 			    off > optlen - IP_ADDR_LEN) {
7515 				/* End of source route */
7516 				ip1dbg(("ip_massage_options: end of SR\n"));
7517 				break;
7518 			}
7519 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7520 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7521 			    ntohl(dst)));
7522 			/*
7523 			 * Check if our address is present more than
7524 			 * once as consecutive hops in source route.
7525 			 * XXX verify per-interface ip_forwarding
7526 			 * for source route?
7527 			 */
7528 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7529 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7530 			if (ire != NULL) {
7531 				ire_refrele(ire);
7532 				off += IP_ADDR_LEN;
7533 				goto redo_srr;
7534 			}
7535 			if (dst == htonl(INADDR_LOOPBACK)) {
7536 				ip1dbg(("ip_massage_options: loopback addr in "
7537 				    "source route!\n"));
7538 				break;
7539 			}
7540 			/*
7541 			 * Update ipha_dst to be the first hop and remove the
7542 			 * first hop from the source route (by overwriting
7543 			 * part of the option with NOP options).
7544 			 */
7545 			ipha->ipha_dst = dst;
7546 			/* Put the last entry in dst */
7547 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7548 			    3;
7549 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7550 
7551 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7552 			    ntohl(dst)));
7553 			/* Move down and overwrite */
7554 			opt[IP_ADDR_LEN] = opt[0];
7555 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7556 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7557 			for (i = 0; i < IP_ADDR_LEN; i++)
7558 				opt[i] = IPOPT_NOP;
7559 			break;
7560 		}
7561 	}
7562 	return (dst);
7563 }
7564 
7565 /*
7566  * This function's job is to forward data to the reverse tunnel (FA->HA)
7567  * after doing a few checks. It is assumed that the incoming interface
7568  * of the packet is always different than the outgoing interface and the
7569  * ire_type of the found ire has to be a non-resolver type.
7570  *
7571  * IPQoS notes
7572  * IP policy is invoked twice for a forwarded packet, once on the read side
7573  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7574  * enabled.
7575  */
7576 static void
7577 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7578 {
7579 	ipha_t		*ipha;
7580 	queue_t		*q;
7581 	uint32_t 	pkt_len;
7582 #define	rptr    ((uchar_t *)ipha)
7583 	uint32_t 	sum;
7584 	uint32_t 	max_frag;
7585 	mblk_t		*first_mp;
7586 	uint32_t	ill_index;
7587 	ipxmit_state_t	pktxmit_state;
7588 	ill_t		*out_ill;
7589 	ip_stack_t	*ipst = in_ill->ill_ipst;
7590 
7591 	ASSERT(ire != NULL);
7592 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7593 	ASSERT(ire->ire_stq != NULL);
7594 
7595 	/* Initiate read side IPPF processing */
7596 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
7597 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7598 		ip_process(IPP_FWD_IN, &mp, ill_index);
7599 		if (mp == NULL) {
7600 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7601 			    "dropped during IPPF processing\n"));
7602 			return;
7603 		}
7604 	}
7605 
7606 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7607 		ILLF_ROUTER) == 0) ||
7608 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7609 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7610 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7611 		    "forwarding is not turned on\n"));
7612 		goto drop_pkt;
7613 	}
7614 
7615 	/*
7616 	 * Don't forward if the interface is down
7617 	 */
7618 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7619 		goto discard_pkt;
7620 	}
7621 
7622 	ipha = (ipha_t *)mp->b_rptr;
7623 	pkt_len = ntohs(ipha->ipha_length);
7624 	/* Adjust the checksum to reflect the ttl decrement. */
7625 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7626 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7627 	if (ipha->ipha_ttl-- <= 1) {
7628 		if (ip_csum_hdr(ipha)) {
7629 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7630 			goto drop_pkt;
7631 		}
7632 		q = ire->ire_stq;
7633 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7634 		    BPRI_HI)) == NULL) {
7635 			goto discard_pkt;
7636 		}
7637 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7638 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7639 		/* Sent by forwarding path, and router is global zone */
7640 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7641 		    GLOBAL_ZONEID, ipst);
7642 		return;
7643 	}
7644 
7645 	/* Get the ill_index of the ILL */
7646 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7647 
7648 	/*
7649 	 * This location is chosen for the placement of the forwarding hook
7650 	 * because at this point we know that we have a path out for the
7651 	 * packet but haven't yet applied any logic (such as fragmenting)
7652 	 * that happen as part of transmitting the packet out.
7653 	 */
7654 	out_ill = ire->ire_ipif->ipif_ill;
7655 
7656 	DTRACE_PROBE4(ip4__forwarding__start,
7657 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7658 
7659 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
7660 	    ipst->ips_ipv4firewall_forwarding,
7661 	    in_ill, out_ill, ipha, mp, mp, ipst);
7662 
7663 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7664 
7665 	if (mp == NULL)
7666 		return;
7667 	pkt_len = ntohs(ipha->ipha_length);
7668 
7669 	/*
7670 	 * ip_mrtun_forward is only used by foreign agent to reverse
7671 	 * tunnel the incoming packet. So it does not do any option
7672 	 * processing for source routing.
7673 	 */
7674 	max_frag = ire->ire_max_frag;
7675 	if (pkt_len > max_frag) {
7676 		/*
7677 		 * It needs fragging on its way out.  We haven't
7678 		 * verified the header checksum yet.  Since we
7679 		 * are going to put a surely good checksum in the
7680 		 * outgoing header, we have to make sure that it
7681 		 * was good coming in.
7682 		 */
7683 		if (ip_csum_hdr(ipha)) {
7684 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7685 			goto drop_pkt;
7686 		}
7687 
7688 		/* Initiate write side IPPF processing */
7689 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
7690 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7691 			if (mp == NULL) {
7692 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7693 				    "dropped/deferred during ip policy "\
7694 				    "processing\n"));
7695 				return;
7696 			}
7697 		}
7698 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7699 		    BPRI_HI)) == NULL) {
7700 			goto discard_pkt;
7701 		}
7702 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7703 		mp = first_mp;
7704 
7705 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
7706 		return;
7707 	}
7708 
7709 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7710 
7711 	ASSERT(ire->ire_ipif != NULL);
7712 
7713 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7714 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7715 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
7716 	    ipst->ips_ipv4firewall_physical_out,
7717 	    NULL, out_ill, ipha, mp, mp, ipst);
7718 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7719 	if (mp == NULL)
7720 		return;
7721 
7722 	/* Now send the packet to the tunnel interface */
7723 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7724 	q = ire->ire_stq;
7725 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7726 	if ((pktxmit_state == SEND_FAILED) ||
7727 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7728 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7729 		    q->q_ptr));
7730 	}
7731 
7732 	return;
7733 discard_pkt:
7734 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7735 drop_pkt:;
7736 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7737 	freemsg(mp);
7738 #undef	rptr
7739 }
7740 
7741 /*
7742  * Fills the ipsec_out_t data structure with appropriate fields and
7743  * prepends it to mp which contains the IP hdr + data that was meant
7744  * to be forwarded. Please note that ipsec_out_info data structure
7745  * is used here to communicate the outgoing ill path at ip_wput()
7746  * for the ICMP error packet. This has nothing to do with ipsec IP
7747  * security. ipsec_out_t is really used to pass the info to the module
7748  * IP where this information cannot be extracted from conn.
7749  * This functions is called by ip_mrtun_forward().
7750  */
7751 void
7752 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7753 {
7754 	ipsec_out_t	*io;
7755 
7756 	ASSERT(xmit_ill != NULL);
7757 	first_mp->b_datap->db_type = M_CTL;
7758 	first_mp->b_wptr += sizeof (ipsec_info_t);
7759 	/*
7760 	 * This is to pass info to ip_wput in absence of conn.
7761 	 * ipsec_out_secure will be B_FALSE because of this.
7762 	 * Thus ipsec_out_secure being B_FALSE indicates that
7763 	 * this is not IPSEC security related information.
7764 	 */
7765 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7766 	io = (ipsec_out_t *)first_mp->b_rptr;
7767 	io->ipsec_out_type = IPSEC_OUT;
7768 	io->ipsec_out_len = sizeof (ipsec_out_t);
7769 	first_mp->b_cont = mp;
7770 	io->ipsec_out_ill_index =
7771 	    xmit_ill->ill_phyint->phyint_ifindex;
7772 	io->ipsec_out_xmit_if = B_TRUE;
7773 	io->ipsec_out_ns = xmit_ill->ill_ipst->ips_netstack;
7774 }
7775 
7776 /*
7777  * Return the network mask
7778  * associated with the specified address.
7779  */
7780 ipaddr_t
7781 ip_net_mask(ipaddr_t addr)
7782 {
7783 	uchar_t	*up = (uchar_t *)&addr;
7784 	ipaddr_t mask = 0;
7785 	uchar_t	*maskp = (uchar_t *)&mask;
7786 
7787 #if defined(__i386) || defined(__amd64)
7788 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7789 #endif
7790 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7791 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7792 #endif
7793 	if (CLASSD(addr)) {
7794 		maskp[0] = 0xF0;
7795 		return (mask);
7796 	}
7797 	if (addr == 0)
7798 		return (0);
7799 	maskp[0] = 0xFF;
7800 	if ((up[0] & 0x80) == 0)
7801 		return (mask);
7802 
7803 	maskp[1] = 0xFF;
7804 	if ((up[0] & 0xC0) == 0x80)
7805 		return (mask);
7806 
7807 	maskp[2] = 0xFF;
7808 	if ((up[0] & 0xE0) == 0xC0)
7809 		return (mask);
7810 
7811 	/* Must be experimental or multicast, indicate as much */
7812 	return ((ipaddr_t)0);
7813 }
7814 
7815 /*
7816  * Select an ill for the packet by considering load spreading across
7817  * a different ill in the group if dst_ill is part of some group.
7818  */
7819 ill_t *
7820 ip_newroute_get_dst_ill(ill_t *dst_ill)
7821 {
7822 	ill_t *ill;
7823 
7824 	/*
7825 	 * We schedule irrespective of whether the source address is
7826 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7827 	 */
7828 	ill = illgrp_scheduler(dst_ill);
7829 	if (ill == NULL)
7830 		return (NULL);
7831 
7832 	/*
7833 	 * For groups with names ip_sioctl_groupname ensures that all
7834 	 * ills are of same type. For groups without names, ifgrp_insert
7835 	 * ensures this.
7836 	 */
7837 	ASSERT(dst_ill->ill_type == ill->ill_type);
7838 
7839 	return (ill);
7840 }
7841 
7842 /*
7843  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7844  */
7845 ill_t *
7846 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7847     ip_stack_t *ipst)
7848 {
7849 	ill_t *ret_ill;
7850 
7851 	ASSERT(ifindex != 0);
7852 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7853 	    ipst);
7854 	if (ret_ill == NULL ||
7855 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7856 		if (isv6) {
7857 			if (ill != NULL) {
7858 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7859 			} else {
7860 				BUMP_MIB(&ipst->ips_ip6_mib,
7861 				    ipIfStatsOutDiscards);
7862 			}
7863 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7864 			    "bad ifindex %d.\n", ifindex));
7865 		} else {
7866 			if (ill != NULL) {
7867 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7868 			} else {
7869 				BUMP_MIB(&ipst->ips_ip_mib,
7870 				    ipIfStatsOutDiscards);
7871 			}
7872 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7873 			    "bad ifindex %d.\n", ifindex));
7874 		}
7875 		if (ret_ill != NULL)
7876 			ill_refrele(ret_ill);
7877 		freemsg(first_mp);
7878 		return (NULL);
7879 	}
7880 
7881 	return (ret_ill);
7882 }
7883 
7884 /*
7885  * IPv4 -
7886  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7887  * out a packet to a destination address for which we do not have specific
7888  * (or sufficient) routing information.
7889  *
7890  * NOTE : These are the scopes of some of the variables that point at IRE,
7891  *	  which needs to be followed while making any future modifications
7892  *	  to avoid memory leaks.
7893  *
7894  *	- ire and sire are the entries looked up initially by
7895  *	  ire_ftable_lookup.
7896  *	- ipif_ire is used to hold the interface ire associated with
7897  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7898  *	  it before branching out to error paths.
7899  *	- save_ire is initialized before ire_create, so that ire returned
7900  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7901  *	  before breaking out of the switch.
7902  *
7903  *	Thus on failures, we have to REFRELE only ire and sire, if they
7904  *	are not NULL.
7905  */
7906 void
7907 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7908     zoneid_t zoneid, ip_stack_t *ipst)
7909 {
7910 	areq_t	*areq;
7911 	ipaddr_t gw = 0;
7912 	ire_t	*ire = NULL;
7913 	mblk_t	*res_mp;
7914 	ipaddr_t *addrp;
7915 	ipaddr_t nexthop_addr;
7916 	ipif_t  *src_ipif = NULL;
7917 	ill_t	*dst_ill = NULL;
7918 	ipha_t  *ipha;
7919 	ire_t	*sire = NULL;
7920 	mblk_t	*first_mp;
7921 	ire_t	*save_ire;
7922 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7923 	ushort_t ire_marks = 0;
7924 	boolean_t mctl_present;
7925 	ipsec_out_t *io;
7926 	mblk_t	*saved_mp;
7927 	ire_t	*first_sire = NULL;
7928 	mblk_t	*copy_mp = NULL;
7929 	mblk_t	*xmit_mp = NULL;
7930 	ipaddr_t save_dst;
7931 	uint32_t multirt_flags =
7932 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7933 	boolean_t multirt_is_resolvable;
7934 	boolean_t multirt_resolve_next;
7935 	boolean_t do_attach_ill = B_FALSE;
7936 	boolean_t ip_nexthop = B_FALSE;
7937 	tsol_ire_gw_secattr_t *attrp = NULL;
7938 	tsol_gcgrp_t *gcgrp = NULL;
7939 	tsol_gcgrp_addr_t ga;
7940 
7941 	if (ip_debug > 2) {
7942 		/* ip1dbg */
7943 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7944 	}
7945 
7946 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7947 	if (mctl_present) {
7948 		io = (ipsec_out_t *)first_mp->b_rptr;
7949 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7950 		ASSERT(zoneid == io->ipsec_out_zoneid);
7951 		ASSERT(zoneid != ALL_ZONES);
7952 	}
7953 
7954 	ipha = (ipha_t *)mp->b_rptr;
7955 
7956 	/* All multicast lookups come through ip_newroute_ipif() */
7957 	if (CLASSD(dst)) {
7958 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7959 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7960 		freemsg(first_mp);
7961 		return;
7962 	}
7963 
7964 	if (mctl_present && io->ipsec_out_attach_if) {
7965 		/* ip_grab_attach_ill returns a held ill */
7966 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7967 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7968 
7969 		/* Failure case frees things for us. */
7970 		if (attach_ill == NULL)
7971 			return;
7972 
7973 		/*
7974 		 * Check if we need an ire that will not be
7975 		 * looked up by anybody else i.e. HIDDEN.
7976 		 */
7977 		if (ill_is_probeonly(attach_ill))
7978 			ire_marks = IRE_MARK_HIDDEN;
7979 	}
7980 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7981 		ip_nexthop = B_TRUE;
7982 		nexthop_addr = io->ipsec_out_nexthop_addr;
7983 	}
7984 	/*
7985 	 * If this IRE is created for forwarding or it is not for
7986 	 * traffic for congestion controlled protocols, mark it as temporary.
7987 	 */
7988 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7989 		ire_marks |= IRE_MARK_TEMPORARY;
7990 
7991 	/*
7992 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7993 	 * chain until it gets the most specific information available.
7994 	 * For example, we know that there is no IRE_CACHE for this dest,
7995 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7996 	 * ire_ftable_lookup will look up the gateway, etc.
7997 	 * Check if in_ill != NULL. If it is true, the packet must be
7998 	 * from an incoming interface where RTA_SRCIFP is set.
7999 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
8000 	 * to the destination, of equal netmask length in the forward table,
8001 	 * will be recursively explored. If no information is available
8002 	 * for the final gateway of that route, we force the returned ire
8003 	 * to be equal to sire using MATCH_IRE_PARENT.
8004 	 * At least, in this case we have a starting point (in the buckets)
8005 	 * to look for other routes to the destination in the forward table.
8006 	 * This is actually used only for multirouting, where a list
8007 	 * of routes has to be processed in sequence.
8008 	 *
8009 	 * In the process of coming up with the most specific information,
8010 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8011 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8012 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8013 	 * Two caveats when handling incomplete ire's in ip_newroute:
8014 	 * - we should be careful when accessing its ire_nce (specifically
8015 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8016 	 * - not all legacy code path callers are prepared to handle
8017 	 *   incomplete ire's, so we should not create/add incomplete
8018 	 *   ire_cache entries here. (See discussion about temporary solution
8019 	 *   further below).
8020 	 *
8021 	 * In order to minimize packet dropping, and to preserve existing
8022 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8023 	 * gateway, and instead use the IF_RESOLVER ire to send out
8024 	 * another request to ARP (this is achieved by passing the
8025 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8026 	 * arp response comes back in ip_wput_nondata, we will create
8027 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8028 	 *
8029 	 * Note that this is a temporary solution; the correct solution is
8030 	 * to create an incomplete  per-dst ire_cache entry, and send the
8031 	 * packet out when the gw's nce is resolved. In order to achieve this,
8032 	 * all packet processing must have been completed prior to calling
8033 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8034 	 * to be modified to accomodate this solution.
8035 	 */
8036 	if (in_ill != NULL) {
8037 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
8038 		    in_ill, MATCH_IRE_TYPE);
8039 	} else if (ip_nexthop) {
8040 		/*
8041 		 * The first time we come here, we look for an IRE_INTERFACE
8042 		 * entry for the specified nexthop, set the dst to be the
8043 		 * nexthop address and create an IRE_CACHE entry for the
8044 		 * nexthop. The next time around, we are able to find an
8045 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8046 		 * nexthop address and create an IRE_CACHE entry for the
8047 		 * destination address via the specified nexthop.
8048 		 */
8049 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8050 		    MBLK_GETLABEL(mp), ipst);
8051 		if (ire != NULL) {
8052 			gw = nexthop_addr;
8053 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8054 		} else {
8055 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8056 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8057 			    MBLK_GETLABEL(mp),
8058 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8059 			    ipst);
8060 			if (ire != NULL) {
8061 				dst = nexthop_addr;
8062 			}
8063 		}
8064 	} else if (attach_ill == NULL) {
8065 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8066 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8067 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8068 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8069 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8070 		    ipst);
8071 	} else {
8072 		/*
8073 		 * attach_ill is set only for communicating with
8074 		 * on-link hosts. So, don't look for DEFAULT.
8075 		 */
8076 		ipif_t	*attach_ipif;
8077 
8078 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8079 		if (attach_ipif == NULL) {
8080 			ill_refrele(attach_ill);
8081 			goto icmp_err_ret;
8082 		}
8083 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8084 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8085 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8086 		    MATCH_IRE_SECATTR, ipst);
8087 		ipif_refrele(attach_ipif);
8088 	}
8089 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8090 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8091 
8092 	/*
8093 	 * This loop is run only once in most cases.
8094 	 * We loop to resolve further routes only when the destination
8095 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8096 	 */
8097 	do {
8098 		/* Clear the previous iteration's values */
8099 		if (src_ipif != NULL) {
8100 			ipif_refrele(src_ipif);
8101 			src_ipif = NULL;
8102 		}
8103 		if (dst_ill != NULL) {
8104 			ill_refrele(dst_ill);
8105 			dst_ill = NULL;
8106 		}
8107 
8108 		multirt_resolve_next = B_FALSE;
8109 		/*
8110 		 * We check if packets have to be multirouted.
8111 		 * In this case, given the current <ire, sire> couple,
8112 		 * we look for the next suitable <ire, sire>.
8113 		 * This check is done in ire_multirt_lookup(),
8114 		 * which applies various criteria to find the next route
8115 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8116 		 * unchanged if it detects it has not been tried yet.
8117 		 */
8118 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8119 			ip3dbg(("ip_newroute: starting next_resolution "
8120 			    "with first_mp %p, tag %d\n",
8121 			    (void *)first_mp,
8122 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8123 
8124 			ASSERT(sire != NULL);
8125 			multirt_is_resolvable =
8126 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8127 				MBLK_GETLABEL(mp), ipst);
8128 
8129 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8130 			    "ire %p, sire %p\n",
8131 			    multirt_is_resolvable,
8132 			    (void *)ire, (void *)sire));
8133 
8134 			if (!multirt_is_resolvable) {
8135 				/*
8136 				 * No more multirt route to resolve; give up
8137 				 * (all routes resolved or no more
8138 				 * resolvable routes).
8139 				 */
8140 				if (ire != NULL) {
8141 					ire_refrele(ire);
8142 					ire = NULL;
8143 				}
8144 			} else {
8145 				ASSERT(sire != NULL);
8146 				ASSERT(ire != NULL);
8147 				/*
8148 				 * We simply use first_sire as a flag that
8149 				 * indicates if a resolvable multirt route
8150 				 * has already been found.
8151 				 * If it is not the case, we may have to send
8152 				 * an ICMP error to report that the
8153 				 * destination is unreachable.
8154 				 * We do not IRE_REFHOLD first_sire.
8155 				 */
8156 				if (first_sire == NULL) {
8157 					first_sire = sire;
8158 				}
8159 			}
8160 		}
8161 		if (ire == NULL) {
8162 			if (ip_debug > 3) {
8163 				/* ip2dbg */
8164 				pr_addr_dbg("ip_newroute: "
8165 				    "can't resolve %s\n", AF_INET, &dst);
8166 			}
8167 			ip3dbg(("ip_newroute: "
8168 			    "ire %p, sire %p, first_sire %p\n",
8169 			    (void *)ire, (void *)sire, (void *)first_sire));
8170 
8171 			if (sire != NULL) {
8172 				ire_refrele(sire);
8173 				sire = NULL;
8174 			}
8175 
8176 			if (first_sire != NULL) {
8177 				/*
8178 				 * At least one multirt route has been found
8179 				 * in the same call to ip_newroute();
8180 				 * there is no need to report an ICMP error.
8181 				 * first_sire was not IRE_REFHOLDed.
8182 				 */
8183 				MULTIRT_DEBUG_UNTAG(first_mp);
8184 				freemsg(first_mp);
8185 				return;
8186 			}
8187 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8188 			    RTA_DST, ipst);
8189 			if (attach_ill != NULL)
8190 				ill_refrele(attach_ill);
8191 			goto icmp_err_ret;
8192 		}
8193 
8194 		/*
8195 		 * When RTA_SRCIFP is used to add a route, then an interface
8196 		 * route is added in the source interface's routing table.
8197 		 * If the outgoing interface of this route is of type
8198 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8199 		 * ire_nce->nce_res_mp is set to NULL.
8200 		 * Later, when this route is first used for forwarding
8201 		 * a packet, ip_newroute() is called
8202 		 * to resolve the hardware address of the outgoing ipif.
8203 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8204 		 * source interface based table. We only come here if the
8205 		 * outgoing interface is a resolver interface and we don't
8206 		 * have the ire_nce->nce_res_mp information yet.
8207 		 * If in_ill is not null that means it is called from
8208 		 * ip_rput.
8209 		 */
8210 
8211 		ASSERT(ire->ire_in_ill == NULL ||
8212 		    (ire->ire_type == IRE_IF_RESOLVER &&
8213 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8214 
8215 		/*
8216 		 * Verify that the returned IRE does not have either
8217 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8218 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8219 		 */
8220 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8221 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8222 			if (attach_ill != NULL)
8223 				ill_refrele(attach_ill);
8224 			goto icmp_err_ret;
8225 		}
8226 		/*
8227 		 * Increment the ire_ob_pkt_count field for ire if it is an
8228 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8229 		 * increment the same for the parent IRE, sire, if it is some
8230 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
8231 		 * and HOST_REDIRECT).
8232 		 */
8233 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8234 			UPDATE_OB_PKT_COUNT(ire);
8235 			ire->ire_last_used_time = lbolt;
8236 		}
8237 
8238 		if (sire != NULL) {
8239 			gw = sire->ire_gateway_addr;
8240 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8241 			    IRE_INTERFACE)) == 0);
8242 			UPDATE_OB_PKT_COUNT(sire);
8243 			sire->ire_last_used_time = lbolt;
8244 		}
8245 		/*
8246 		 * We have a route to reach the destination.
8247 		 *
8248 		 * 1) If the interface is part of ill group, try to get a new
8249 		 *    ill taking load spreading into account.
8250 		 *
8251 		 * 2) After selecting the ill, get a source address that
8252 		 *    might create good inbound load spreading.
8253 		 *    ipif_select_source does this for us.
8254 		 *
8255 		 * If the application specified the ill (ifindex), we still
8256 		 * load spread. Only if the packets needs to go out
8257 		 * specifically on a given ill e.g. binding to
8258 		 * IPIF_NOFAILOVER address, then we don't try to use a
8259 		 * different ill for load spreading.
8260 		 */
8261 		if (attach_ill == NULL) {
8262 			/*
8263 			 * Don't perform outbound load spreading in the
8264 			 * case of an RTF_MULTIRT route, as we actually
8265 			 * typically want to replicate outgoing packets
8266 			 * through particular interfaces.
8267 			 */
8268 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8269 				dst_ill = ire->ire_ipif->ipif_ill;
8270 				/* for uniformity */
8271 				ill_refhold(dst_ill);
8272 			} else {
8273 				/*
8274 				 * If we are here trying to create an IRE_CACHE
8275 				 * for an offlink destination and have the
8276 				 * IRE_CACHE for the next hop and the latter is
8277 				 * using virtual IP source address selection i.e
8278 				 * it's ire->ire_ipif is pointing to a virtual
8279 				 * network interface (vni) then
8280 				 * ip_newroute_get_dst_ll() will return the vni
8281 				 * interface as the dst_ill. Since the vni is
8282 				 * virtual i.e not associated with any physical
8283 				 * interface, it cannot be the dst_ill, hence
8284 				 * in such a case call ip_newroute_get_dst_ll()
8285 				 * with the stq_ill instead of the ire_ipif ILL.
8286 				 * The function returns a refheld ill.
8287 				 */
8288 				if ((ire->ire_type == IRE_CACHE) &&
8289 				    IS_VNI(ire->ire_ipif->ipif_ill))
8290 					dst_ill = ip_newroute_get_dst_ill(
8291 						ire->ire_stq->q_ptr);
8292 				else
8293 					dst_ill = ip_newroute_get_dst_ill(
8294 						ire->ire_ipif->ipif_ill);
8295 			}
8296 			if (dst_ill == NULL) {
8297 				if (ip_debug > 2) {
8298 					pr_addr_dbg("ip_newroute: "
8299 					    "no dst ill for dst"
8300 					    " %s\n", AF_INET, &dst);
8301 				}
8302 				goto icmp_err_ret;
8303 			}
8304 		} else {
8305 			dst_ill = ire->ire_ipif->ipif_ill;
8306 			/* for uniformity */
8307 			ill_refhold(dst_ill);
8308 			/*
8309 			 * We should have found a route matching ill as we
8310 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8311 			 * Rather than asserting, when there is a mismatch,
8312 			 * we just drop the packet.
8313 			 */
8314 			if (dst_ill != attach_ill) {
8315 				ip0dbg(("ip_newroute: Packet dropped as "
8316 				    "IPIF_NOFAILOVER ill is %s, "
8317 				    "ire->ire_ipif->ipif_ill is %s\n",
8318 				    attach_ill->ill_name,
8319 				    dst_ill->ill_name));
8320 				ill_refrele(attach_ill);
8321 				goto icmp_err_ret;
8322 			}
8323 		}
8324 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8325 		if (attach_ill != NULL) {
8326 			ill_refrele(attach_ill);
8327 			attach_ill = NULL;
8328 			do_attach_ill = B_TRUE;
8329 		}
8330 		ASSERT(dst_ill != NULL);
8331 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8332 
8333 		/*
8334 		 * Pick the best source address from dst_ill.
8335 		 *
8336 		 * 1) If it is part of a multipathing group, we would
8337 		 *    like to spread the inbound packets across different
8338 		 *    interfaces. ipif_select_source picks a random source
8339 		 *    across the different ills in the group.
8340 		 *
8341 		 * 2) If it is not part of a multipathing group, we try
8342 		 *    to pick the source address from the destination
8343 		 *    route. Clustering assumes that when we have multiple
8344 		 *    prefixes hosted on an interface, the prefix of the
8345 		 *    source address matches the prefix of the destination
8346 		 *    route. We do this only if the address is not
8347 		 *    DEPRECATED.
8348 		 *
8349 		 * 3) If the conn is in a different zone than the ire, we
8350 		 *    need to pick a source address from the right zone.
8351 		 *
8352 		 * NOTE : If we hit case (1) above, the prefix of the source
8353 		 *	  address picked may not match the prefix of the
8354 		 *	  destination routes prefix as ipif_select_source
8355 		 *	  does not look at "dst" while picking a source
8356 		 *	  address.
8357 		 *	  If we want the same behavior as (2), we will need
8358 		 *	  to change the behavior of ipif_select_source.
8359 		 */
8360 		ASSERT(src_ipif == NULL);
8361 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8362 			/*
8363 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8364 			 * Check that the ipif matching the requested source
8365 			 * address still exists.
8366 			 */
8367 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8368 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8369 		}
8370 		if (src_ipif == NULL) {
8371 			ire_marks |= IRE_MARK_USESRC_CHECK;
8372 			if ((dst_ill->ill_group != NULL) ||
8373 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8374 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8375 			    ire->ire_zoneid != ALL_ZONES) ||
8376 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8377 				/*
8378 				 * If the destination is reachable via a
8379 				 * given gateway, the selected source address
8380 				 * should be in the same subnet as the gateway.
8381 				 * Otherwise, the destination is not reachable.
8382 				 *
8383 				 * If there are no interfaces on the same subnet
8384 				 * as the destination, ipif_select_source gives
8385 				 * first non-deprecated interface which might be
8386 				 * on a different subnet than the gateway.
8387 				 * This is not desirable. Hence pass the dst_ire
8388 				 * source address to ipif_select_source.
8389 				 * It is sure that the destination is reachable
8390 				 * with the dst_ire source address subnet.
8391 				 * So passing dst_ire source address to
8392 				 * ipif_select_source will make sure that the
8393 				 * selected source will be on the same subnet
8394 				 * as dst_ire source address.
8395 				 */
8396 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8397 				src_ipif = ipif_select_source(dst_ill, saddr,
8398 				    zoneid);
8399 				if (src_ipif == NULL) {
8400 					if (ip_debug > 2) {
8401 						pr_addr_dbg("ip_newroute: "
8402 						    "no src for dst %s ",
8403 						    AF_INET, &dst);
8404 						printf("through interface %s\n",
8405 						    dst_ill->ill_name);
8406 					}
8407 					goto icmp_err_ret;
8408 				}
8409 			} else {
8410 				src_ipif = ire->ire_ipif;
8411 				ASSERT(src_ipif != NULL);
8412 				/* hold src_ipif for uniformity */
8413 				ipif_refhold(src_ipif);
8414 			}
8415 		}
8416 
8417 		/*
8418 		 * Assign a source address while we have the conn.
8419 		 * We can't have ip_wput_ire pick a source address when the
8420 		 * packet returns from arp since we need to look at
8421 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8422 		 * going through arp.
8423 		 *
8424 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8425 		 *	  it uses ip6i to store this information.
8426 		 */
8427 		if (ipha->ipha_src == INADDR_ANY &&
8428 		    (connp == NULL || !connp->conn_unspec_src)) {
8429 			ipha->ipha_src = src_ipif->ipif_src_addr;
8430 		}
8431 		if (ip_debug > 3) {
8432 			/* ip2dbg */
8433 			pr_addr_dbg("ip_newroute: first hop %s\n",
8434 			    AF_INET, &gw);
8435 		}
8436 		ip2dbg(("\tire type %s (%d)\n",
8437 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8438 
8439 		/*
8440 		 * The TTL of multirouted packets is bounded by the
8441 		 * ip_multirt_ttl ndd variable.
8442 		 */
8443 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8444 			/* Force TTL of multirouted packets */
8445 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8446 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8447 				ip2dbg(("ip_newroute: forcing multirt TTL "
8448 				    "to %d (was %d), dst 0x%08x\n",
8449 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8450 				    ntohl(sire->ire_addr)));
8451 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8452 			}
8453 		}
8454 		/*
8455 		 * At this point in ip_newroute(), ire is either the
8456 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8457 		 * destination or an IRE_INTERFACE type that should be used
8458 		 * to resolve an on-subnet destination or an on-subnet
8459 		 * next-hop gateway.
8460 		 *
8461 		 * In the IRE_CACHE case, we have the following :
8462 		 *
8463 		 * 1) src_ipif - used for getting a source address.
8464 		 *
8465 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8466 		 *    means packets using this IRE_CACHE will go out on
8467 		 *    dst_ill.
8468 		 *
8469 		 * 3) The IRE sire will point to the prefix that is the
8470 		 *    longest  matching route for the destination. These
8471 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8472 		 *
8473 		 *    The newly created IRE_CACHE entry for the off-subnet
8474 		 *    destination is tied to both the prefix route and the
8475 		 *    interface route used to resolve the next-hop gateway
8476 		 *    via the ire_phandle and ire_ihandle fields,
8477 		 *    respectively.
8478 		 *
8479 		 * In the IRE_INTERFACE case, we have the following :
8480 		 *
8481 		 * 1) src_ipif - used for getting a source address.
8482 		 *
8483 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8484 		 *    means packets using the IRE_CACHE that we will build
8485 		 *    here will go out on dst_ill.
8486 		 *
8487 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8488 		 *    to be created will only be tied to the IRE_INTERFACE
8489 		 *    that was derived from the ire_ihandle field.
8490 		 *
8491 		 *    If sire is non-NULL, it means the destination is
8492 		 *    off-link and we will first create the IRE_CACHE for the
8493 		 *    gateway. Next time through ip_newroute, we will create
8494 		 *    the IRE_CACHE for the final destination as described
8495 		 *    above.
8496 		 *
8497 		 * In both cases, after the current resolution has been
8498 		 * completed (or possibly initialised, in the IRE_INTERFACE
8499 		 * case), the loop may be re-entered to attempt the resolution
8500 		 * of another RTF_MULTIRT route.
8501 		 *
8502 		 * When an IRE_CACHE entry for the off-subnet destination is
8503 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8504 		 * for further processing in emission loops.
8505 		 */
8506 		save_ire = ire;
8507 		switch (ire->ire_type) {
8508 		case IRE_CACHE: {
8509 			ire_t	*ipif_ire;
8510 			mblk_t	*ire_fp_mp;
8511 
8512 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8513 			if (gw == 0)
8514 				gw = ire->ire_gateway_addr;
8515 			/*
8516 			 * We need 3 ire's to create a new cache ire for an
8517 			 * off-link destination from the cache ire of the
8518 			 * gateway.
8519 			 *
8520 			 *	1. The prefix ire 'sire' (Note that this does
8521 			 *	   not apply to the conn_nexthop_set case)
8522 			 *	2. The cache ire of the gateway 'ire'
8523 			 *	3. The interface ire 'ipif_ire'
8524 			 *
8525 			 * We have (1) and (2). We lookup (3) below.
8526 			 *
8527 			 * If there is no interface route to the gateway,
8528 			 * it is a race condition, where we found the cache
8529 			 * but the interface route has been deleted.
8530 			 */
8531 			if (ip_nexthop) {
8532 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8533 			} else {
8534 				ipif_ire =
8535 				    ire_ihandle_lookup_offlink(ire, sire);
8536 			}
8537 			if (ipif_ire == NULL) {
8538 				ip1dbg(("ip_newroute: "
8539 				    "ire_ihandle_lookup_offlink failed\n"));
8540 				goto icmp_err_ret;
8541 			}
8542 			/*
8543 			 * XXX We are using the same res_mp
8544 			 * (DL_UNITDATA_REQ) though the save_ire is not
8545 			 * pointing at the same ill.
8546 			 * This is incorrect. We need to send it up to the
8547 			 * resolver to get the right res_mp. For ethernets
8548 			 * this may be okay (ill_type == DL_ETHER).
8549 			 */
8550 			res_mp = save_ire->ire_nce->nce_res_mp;
8551 			ire_fp_mp = NULL;
8552 
8553 			/*
8554 			 * Check cached gateway IRE for any security
8555 			 * attributes; if found, associate the gateway
8556 			 * credentials group to the destination IRE.
8557 			 */
8558 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8559 				mutex_enter(&attrp->igsa_lock);
8560 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8561 					GCGRP_REFHOLD(gcgrp);
8562 				mutex_exit(&attrp->igsa_lock);
8563 			}
8564 
8565 			ire = ire_create(
8566 			    (uchar_t *)&dst,		/* dest address */
8567 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8568 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8569 			    (uchar_t *)&gw,		/* gateway address */
8570 			    NULL,
8571 			    &save_ire->ire_max_frag,
8572 			    ire_fp_mp,			/* Fast Path header */
8573 			    dst_ill->ill_rq,		/* recv-from queue */
8574 			    dst_ill->ill_wq,		/* send-to queue */
8575 			    IRE_CACHE,			/* IRE type */
8576 			    res_mp,
8577 			    src_ipif,
8578 			    in_ill,			/* incoming ill */
8579 			    (sire != NULL) ?
8580 				sire->ire_mask : 0, 	/* Parent mask */
8581 			    (sire != NULL) ?
8582 				sire->ire_phandle : 0,  /* Parent handle */
8583 			    ipif_ire->ire_ihandle,	/* Interface handle */
8584 			    (sire != NULL) ? (sire->ire_flags &
8585 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8586 			    (sire != NULL) ?
8587 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8588 			    NULL,
8589 			    gcgrp,
8590 			    ipst);
8591 
8592 			if (ire == NULL) {
8593 				if (gcgrp != NULL) {
8594 					GCGRP_REFRELE(gcgrp);
8595 					gcgrp = NULL;
8596 				}
8597 				ire_refrele(ipif_ire);
8598 				ire_refrele(save_ire);
8599 				break;
8600 			}
8601 
8602 			/* reference now held by IRE */
8603 			gcgrp = NULL;
8604 
8605 			ire->ire_marks |= ire_marks;
8606 
8607 			/*
8608 			 * Prevent sire and ipif_ire from getting deleted.
8609 			 * The newly created ire is tied to both of them via
8610 			 * the phandle and ihandle respectively.
8611 			 */
8612 			if (sire != NULL) {
8613 				IRB_REFHOLD(sire->ire_bucket);
8614 				/* Has it been removed already ? */
8615 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8616 					IRB_REFRELE(sire->ire_bucket);
8617 					ire_refrele(ipif_ire);
8618 					ire_refrele(save_ire);
8619 					break;
8620 				}
8621 			}
8622 
8623 			IRB_REFHOLD(ipif_ire->ire_bucket);
8624 			/* Has it been removed already ? */
8625 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8626 				IRB_REFRELE(ipif_ire->ire_bucket);
8627 				if (sire != NULL)
8628 					IRB_REFRELE(sire->ire_bucket);
8629 				ire_refrele(ipif_ire);
8630 				ire_refrele(save_ire);
8631 				break;
8632 			}
8633 
8634 			xmit_mp = first_mp;
8635 			/*
8636 			 * In the case of multirouting, a copy
8637 			 * of the packet is done before its sending.
8638 			 * The copy is used to attempt another
8639 			 * route resolution, in a next loop.
8640 			 */
8641 			if (ire->ire_flags & RTF_MULTIRT) {
8642 				copy_mp = copymsg(first_mp);
8643 				if (copy_mp != NULL) {
8644 					xmit_mp = copy_mp;
8645 					MULTIRT_DEBUG_TAG(first_mp);
8646 				}
8647 			}
8648 			ire_add_then_send(q, ire, xmit_mp);
8649 			ire_refrele(save_ire);
8650 
8651 			/* Assert that sire is not deleted yet. */
8652 			if (sire != NULL) {
8653 				ASSERT(sire->ire_ptpn != NULL);
8654 				IRB_REFRELE(sire->ire_bucket);
8655 			}
8656 
8657 			/* Assert that ipif_ire is not deleted yet. */
8658 			ASSERT(ipif_ire->ire_ptpn != NULL);
8659 			IRB_REFRELE(ipif_ire->ire_bucket);
8660 			ire_refrele(ipif_ire);
8661 
8662 			/*
8663 			 * If copy_mp is not NULL, multirouting was
8664 			 * requested. We loop to initiate a next
8665 			 * route resolution attempt, starting from sire.
8666 			 */
8667 			if (copy_mp != NULL) {
8668 				/*
8669 				 * Search for the next unresolved
8670 				 * multirt route.
8671 				 */
8672 				copy_mp = NULL;
8673 				ipif_ire = NULL;
8674 				ire = NULL;
8675 				multirt_resolve_next = B_TRUE;
8676 				continue;
8677 			}
8678 			if (sire != NULL)
8679 				ire_refrele(sire);
8680 			ipif_refrele(src_ipif);
8681 			ill_refrele(dst_ill);
8682 			return;
8683 		}
8684 		case IRE_IF_NORESOLVER: {
8685 			/*
8686 			 * We have what we need to build an IRE_CACHE.
8687 			 *
8688 			 * Create a new res_mp with the IP gateway address
8689 			 * in destination address in the DLPI hdr if the
8690 			 * physical length is exactly 4 bytes.
8691 			 */
8692 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8693 				uchar_t *addr;
8694 
8695 				if (gw)
8696 					addr = (uchar_t *)&gw;
8697 				else
8698 					addr = (uchar_t *)&dst;
8699 
8700 				res_mp = ill_dlur_gen(addr,
8701 				    dst_ill->ill_phys_addr_length,
8702 				    dst_ill->ill_sap,
8703 				    dst_ill->ill_sap_length);
8704 
8705 				if (res_mp == NULL) {
8706 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8707 					break;
8708 				}
8709 			} else if (dst_ill->ill_resolver_mp == NULL) {
8710 				ip1dbg(("ip_newroute: dst_ill %p "
8711 				    "for IF_NORESOLV ire %p has "
8712 				    "no ill_resolver_mp\n",
8713 				    (void *)dst_ill, (void *)ire));
8714 				break;
8715 			} else {
8716 				res_mp = NULL;
8717 			}
8718 
8719 			/*
8720 			 * TSol note: We are creating the ire cache for the
8721 			 * destination 'dst'. If 'dst' is offlink, going
8722 			 * through the first hop 'gw', the security attributes
8723 			 * of 'dst' must be set to point to the gateway
8724 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8725 			 * is possible that 'dst' is a potential gateway that is
8726 			 * referenced by some route that has some security
8727 			 * attributes. Thus in the former case, we need to do a
8728 			 * gcgrp_lookup of 'gw' while in the latter case we
8729 			 * need to do gcgrp_lookup of 'dst' itself.
8730 			 */
8731 			ga.ga_af = AF_INET;
8732 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8733 			    &ga.ga_addr);
8734 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8735 
8736 			ire = ire_create(
8737 			    (uchar_t *)&dst,		/* dest address */
8738 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8739 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8740 			    (uchar_t *)&gw,		/* gateway address */
8741 			    NULL,
8742 			    &save_ire->ire_max_frag,
8743 			    NULL,			/* Fast Path header */
8744 			    dst_ill->ill_rq,		/* recv-from queue */
8745 			    dst_ill->ill_wq,		/* send-to queue */
8746 			    IRE_CACHE,
8747 			    res_mp,
8748 			    src_ipif,
8749 			    in_ill,			/* Incoming ill */
8750 			    save_ire->ire_mask,		/* Parent mask */
8751 			    (sire != NULL) ?		/* Parent handle */
8752 				sire->ire_phandle : 0,
8753 			    save_ire->ire_ihandle,	/* Interface handle */
8754 			    (sire != NULL) ? sire->ire_flags &
8755 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8756 			    &(save_ire->ire_uinfo),
8757 			    NULL,
8758 			    gcgrp,
8759 			    ipst);
8760 
8761 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8762 				freeb(res_mp);
8763 
8764 			if (ire == NULL) {
8765 				if (gcgrp != NULL) {
8766 					GCGRP_REFRELE(gcgrp);
8767 					gcgrp = NULL;
8768 				}
8769 				ire_refrele(save_ire);
8770 				break;
8771 			}
8772 
8773 			/* reference now held by IRE */
8774 			gcgrp = NULL;
8775 
8776 			ire->ire_marks |= ire_marks;
8777 
8778 			/* Prevent save_ire from getting deleted */
8779 			IRB_REFHOLD(save_ire->ire_bucket);
8780 			/* Has it been removed already ? */
8781 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8782 				IRB_REFRELE(save_ire->ire_bucket);
8783 				ire_refrele(save_ire);
8784 				break;
8785 			}
8786 
8787 			/*
8788 			 * In the case of multirouting, a copy
8789 			 * of the packet is made before it is sent.
8790 			 * The copy is used in the next
8791 			 * loop to attempt another resolution.
8792 			 */
8793 			xmit_mp = first_mp;
8794 			if ((sire != NULL) &&
8795 			    (sire->ire_flags & RTF_MULTIRT)) {
8796 				copy_mp = copymsg(first_mp);
8797 				if (copy_mp != NULL) {
8798 					xmit_mp = copy_mp;
8799 					MULTIRT_DEBUG_TAG(first_mp);
8800 				}
8801 			}
8802 			ire_add_then_send(q, ire, xmit_mp);
8803 
8804 			/* Assert that it is not deleted yet. */
8805 			ASSERT(save_ire->ire_ptpn != NULL);
8806 			IRB_REFRELE(save_ire->ire_bucket);
8807 			ire_refrele(save_ire);
8808 
8809 			if (copy_mp != NULL) {
8810 				/*
8811 				 * If we found a (no)resolver, we ignore any
8812 				 * trailing top priority IRE_CACHE in further
8813 				 * loops. This ensures that we do not omit any
8814 				 * (no)resolver.
8815 				 * This IRE_CACHE, if any, will be processed
8816 				 * by another thread entering ip_newroute().
8817 				 * IRE_CACHE entries, if any, will be processed
8818 				 * by another thread entering ip_newroute(),
8819 				 * (upon resolver response, for instance).
8820 				 * This aims to force parallel multirt
8821 				 * resolutions as soon as a packet must be sent.
8822 				 * In the best case, after the tx of only one
8823 				 * packet, all reachable routes are resolved.
8824 				 * Otherwise, the resolution of all RTF_MULTIRT
8825 				 * routes would require several emissions.
8826 				 */
8827 				multirt_flags &= ~MULTIRT_CACHEGW;
8828 
8829 				/*
8830 				 * Search for the next unresolved multirt
8831 				 * route.
8832 				 */
8833 				copy_mp = NULL;
8834 				save_ire = NULL;
8835 				ire = NULL;
8836 				multirt_resolve_next = B_TRUE;
8837 				continue;
8838 			}
8839 
8840 			/*
8841 			 * Don't need sire anymore
8842 			 */
8843 			if (sire != NULL)
8844 				ire_refrele(sire);
8845 
8846 			ipif_refrele(src_ipif);
8847 			ill_refrele(dst_ill);
8848 			return;
8849 		}
8850 		case IRE_IF_RESOLVER:
8851 			/*
8852 			 * We can't build an IRE_CACHE yet, but at least we
8853 			 * found a resolver that can help.
8854 			 */
8855 			res_mp = dst_ill->ill_resolver_mp;
8856 			if (!OK_RESOLVER_MP(res_mp))
8857 				break;
8858 
8859 			/*
8860 			 * To be at this point in the code with a non-zero gw
8861 			 * means that dst is reachable through a gateway that
8862 			 * we have never resolved.  By changing dst to the gw
8863 			 * addr we resolve the gateway first.
8864 			 * When ire_add_then_send() tries to put the IP dg
8865 			 * to dst, it will reenter ip_newroute() at which
8866 			 * time we will find the IRE_CACHE for the gw and
8867 			 * create another IRE_CACHE in case IRE_CACHE above.
8868 			 */
8869 			if (gw != INADDR_ANY) {
8870 				/*
8871 				 * The source ipif that was determined above was
8872 				 * relative to the destination address, not the
8873 				 * gateway's. If src_ipif was not taken out of
8874 				 * the IRE_IF_RESOLVER entry, we'll need to call
8875 				 * ipif_select_source() again.
8876 				 */
8877 				if (src_ipif != ire->ire_ipif) {
8878 					ipif_refrele(src_ipif);
8879 					src_ipif = ipif_select_source(dst_ill,
8880 					    gw, zoneid);
8881 					if (src_ipif == NULL) {
8882 						if (ip_debug > 2) {
8883 							pr_addr_dbg(
8884 							    "ip_newroute: no "
8885 							    "src for gw %s ",
8886 							    AF_INET, &gw);
8887 							printf("through "
8888 							    "interface %s\n",
8889 							    dst_ill->ill_name);
8890 						}
8891 						goto icmp_err_ret;
8892 					}
8893 				}
8894 				save_dst = dst;
8895 				dst = gw;
8896 				gw = INADDR_ANY;
8897 			}
8898 
8899 			/*
8900 			 * We obtain a partial IRE_CACHE which we will pass
8901 			 * along with the resolver query.  When the response
8902 			 * comes back it will be there ready for us to add.
8903 			 * The ire_max_frag is atomically set under the
8904 			 * irebucket lock in ire_add_v[46].
8905 			 */
8906 
8907 			ire = ire_create_mp(
8908 			    (uchar_t *)&dst,		/* dest address */
8909 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8910 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8911 			    (uchar_t *)&gw,		/* gateway address */
8912 			    NULL,			/* no in_src_addr */
8913 			    NULL,			/* ire_max_frag */
8914 			    NULL,			/* Fast Path header */
8915 			    dst_ill->ill_rq,		/* recv-from queue */
8916 			    dst_ill->ill_wq,		/* send-to queue */
8917 			    IRE_CACHE,
8918 			    NULL,
8919 			    src_ipif,			/* Interface ipif */
8920 			    in_ill,			/* Incoming ILL */
8921 			    save_ire->ire_mask,		/* Parent mask */
8922 			    0,
8923 			    save_ire->ire_ihandle,	/* Interface handle */
8924 			    0,				/* flags if any */
8925 			    &(save_ire->ire_uinfo),
8926 			    NULL,
8927 			    NULL,
8928 			    ipst);
8929 
8930 			if (ire == NULL) {
8931 				ire_refrele(save_ire);
8932 				break;
8933 			}
8934 
8935 			if ((sire != NULL) &&
8936 			    (sire->ire_flags & RTF_MULTIRT)) {
8937 				copy_mp = copymsg(first_mp);
8938 				if (copy_mp != NULL)
8939 					MULTIRT_DEBUG_TAG(copy_mp);
8940 			}
8941 
8942 			ire->ire_marks |= ire_marks;
8943 
8944 			/*
8945 			 * Construct message chain for the resolver
8946 			 * of the form:
8947 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8948 			 * Packet could contain a IPSEC_OUT mp.
8949 			 *
8950 			 * NOTE : ire will be added later when the response
8951 			 * comes back from ARP. If the response does not
8952 			 * come back, ARP frees the packet. For this reason,
8953 			 * we can't REFHOLD the bucket of save_ire to prevent
8954 			 * deletions. We may not be able to REFRELE the bucket
8955 			 * if the response never comes back. Thus, before
8956 			 * adding the ire, ire_add_v4 will make sure that the
8957 			 * interface route does not get deleted. This is the
8958 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8959 			 * where we can always prevent deletions because of
8960 			 * the synchronous nature of adding IRES i.e
8961 			 * ire_add_then_send is called after creating the IRE.
8962 			 */
8963 			ASSERT(ire->ire_mp != NULL);
8964 			ire->ire_mp->b_cont = first_mp;
8965 			/* Have saved_mp handy, for cleanup if canput fails */
8966 			saved_mp = mp;
8967 			mp = copyb(res_mp);
8968 			if (mp == NULL) {
8969 				/* Prepare for cleanup */
8970 				mp = saved_mp; /* pkt */
8971 				ire_delete(ire); /* ire_mp */
8972 				ire = NULL;
8973 				ire_refrele(save_ire);
8974 				if (copy_mp != NULL) {
8975 					MULTIRT_DEBUG_UNTAG(copy_mp);
8976 					freemsg(copy_mp);
8977 					copy_mp = NULL;
8978 				}
8979 				break;
8980 			}
8981 			linkb(mp, ire->ire_mp);
8982 
8983 			/*
8984 			 * Fill in the source and dest addrs for the resolver.
8985 			 * NOTE: this depends on memory layouts imposed by
8986 			 * ill_init().
8987 			 */
8988 			areq = (areq_t *)mp->b_rptr;
8989 			addrp = (ipaddr_t *)((char *)areq +
8990 			    areq->areq_sender_addr_offset);
8991 			if (do_attach_ill) {
8992 				/*
8993 				 * This is bind to no failover case.
8994 				 * arp packet also must go out on attach_ill.
8995 				 */
8996 				ASSERT(ipha->ipha_src != NULL);
8997 				*addrp = ipha->ipha_src;
8998 			} else {
8999 				*addrp = save_ire->ire_src_addr;
9000 			}
9001 
9002 			ire_refrele(save_ire);
9003 			addrp = (ipaddr_t *)((char *)areq +
9004 			    areq->areq_target_addr_offset);
9005 			*addrp = dst;
9006 			/* Up to the resolver. */
9007 			if (canputnext(dst_ill->ill_rq) &&
9008 			    !(dst_ill->ill_arp_closing)) {
9009 				putnext(dst_ill->ill_rq, mp);
9010 				ire = NULL;
9011 				if (copy_mp != NULL) {
9012 					/*
9013 					 * If we found a resolver, we ignore
9014 					 * any trailing top priority IRE_CACHE
9015 					 * in the further loops. This ensures
9016 					 * that we do not omit any resolver.
9017 					 * IRE_CACHE entries, if any, will be
9018 					 * processed next time we enter
9019 					 * ip_newroute().
9020 					 */
9021 					multirt_flags &= ~MULTIRT_CACHEGW;
9022 					/*
9023 					 * Search for the next unresolved
9024 					 * multirt route.
9025 					 */
9026 					first_mp = copy_mp;
9027 					copy_mp = NULL;
9028 					/* Prepare the next resolution loop. */
9029 					mp = first_mp;
9030 					EXTRACT_PKT_MP(mp, first_mp,
9031 					    mctl_present);
9032 					if (mctl_present)
9033 						io = (ipsec_out_t *)
9034 						    first_mp->b_rptr;
9035 					ipha = (ipha_t *)mp->b_rptr;
9036 
9037 					ASSERT(sire != NULL);
9038 
9039 					dst = save_dst;
9040 					multirt_resolve_next = B_TRUE;
9041 					continue;
9042 				}
9043 
9044 				if (sire != NULL)
9045 					ire_refrele(sire);
9046 
9047 				/*
9048 				 * The response will come back in ip_wput
9049 				 * with db_type IRE_DB_TYPE.
9050 				 */
9051 				ipif_refrele(src_ipif);
9052 				ill_refrele(dst_ill);
9053 				return;
9054 			} else {
9055 				/* Prepare for cleanup */
9056 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
9057 				    mp);
9058 				mp->b_cont = NULL;
9059 				freeb(mp); /* areq */
9060 				/*
9061 				 * this is an ire that is not added to the
9062 				 * cache. ire_freemblk will handle the release
9063 				 * of any resources associated with the ire.
9064 				 */
9065 				ire_delete(ire); /* ire_mp */
9066 				mp = saved_mp; /* pkt */
9067 				ire = NULL;
9068 				if (copy_mp != NULL) {
9069 					MULTIRT_DEBUG_UNTAG(copy_mp);
9070 					freemsg(copy_mp);
9071 					copy_mp = NULL;
9072 				}
9073 				break;
9074 			}
9075 		default:
9076 			break;
9077 		}
9078 	} while (multirt_resolve_next);
9079 
9080 	ip1dbg(("ip_newroute: dropped\n"));
9081 	/* Did this packet originate externally? */
9082 	if (mp->b_prev) {
9083 		mp->b_next = NULL;
9084 		mp->b_prev = NULL;
9085 		if (in_ill != NULL) {
9086 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
9087 		} else {
9088 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9089 		}
9090 	} else {
9091 		if (dst_ill != NULL) {
9092 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
9093 		} else {
9094 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
9095 		}
9096 	}
9097 	ASSERT(copy_mp == NULL);
9098 	MULTIRT_DEBUG_UNTAG(first_mp);
9099 	freemsg(first_mp);
9100 	if (ire != NULL)
9101 		ire_refrele(ire);
9102 	if (sire != NULL)
9103 		ire_refrele(sire);
9104 	if (src_ipif != NULL)
9105 		ipif_refrele(src_ipif);
9106 	if (dst_ill != NULL)
9107 		ill_refrele(dst_ill);
9108 	return;
9109 
9110 icmp_err_ret:
9111 	ip1dbg(("ip_newroute: no route\n"));
9112 	if (src_ipif != NULL)
9113 		ipif_refrele(src_ipif);
9114 	if (dst_ill != NULL)
9115 		ill_refrele(dst_ill);
9116 	if (sire != NULL)
9117 		ire_refrele(sire);
9118 	/* Did this packet originate externally? */
9119 	if (mp->b_prev) {
9120 		mp->b_next = NULL;
9121 		mp->b_prev = NULL;
9122 		if (in_ill != NULL) {
9123 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
9124 		} else {
9125 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9126 		}
9127 		q = WR(q);
9128 	} else {
9129 		/*
9130 		 * There is no outgoing ill, so just increment the
9131 		 * system MIB.
9132 		 */
9133 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9134 		/*
9135 		 * Since ip_wput() isn't close to finished, we fill
9136 		 * in enough of the header for credible error reporting.
9137 		 */
9138 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9139 			/* Failed */
9140 			MULTIRT_DEBUG_UNTAG(first_mp);
9141 			freemsg(first_mp);
9142 			if (ire != NULL)
9143 				ire_refrele(ire);
9144 			return;
9145 		}
9146 	}
9147 
9148 	/*
9149 	 * At this point we will have ire only if RTF_BLACKHOLE
9150 	 * or RTF_REJECT flags are set on the IRE. It will not
9151 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9152 	 */
9153 	if (ire != NULL) {
9154 		if (ire->ire_flags & RTF_BLACKHOLE) {
9155 			ire_refrele(ire);
9156 			MULTIRT_DEBUG_UNTAG(first_mp);
9157 			freemsg(first_mp);
9158 			return;
9159 		}
9160 		ire_refrele(ire);
9161 	}
9162 	if (ip_source_routed(ipha, ipst)) {
9163 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9164 		    zoneid, ipst);
9165 		return;
9166 	}
9167 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9168 }
9169 
9170 ip_opt_info_t zero_info;
9171 
9172 /*
9173  * IPv4 -
9174  * ip_newroute_ipif is called by ip_wput_multicast and
9175  * ip_rput_forward_multicast whenever we need to send
9176  * out a packet to a destination address for which we do not have specific
9177  * routing information. It is used when the packet will be sent out
9178  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9179  * socket option is set or icmp error message wants to go out on a particular
9180  * interface for a unicast packet.
9181  *
9182  * In most cases, the destination address is resolved thanks to the ipif
9183  * intrinsic resolver. However, there are some cases where the call to
9184  * ip_newroute_ipif must take into account the potential presence of
9185  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9186  * that uses the interface. This is specified through flags,
9187  * which can be a combination of:
9188  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9189  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9190  *   and flags. Additionally, the packet source address has to be set to
9191  *   the specified address. The caller is thus expected to set this flag
9192  *   if the packet has no specific source address yet.
9193  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9194  *   flag, the resulting ire will inherit the flag. All unresolved routes
9195  *   to the destination must be explored in the same call to
9196  *   ip_newroute_ipif().
9197  */
9198 static void
9199 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9200     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9201 {
9202 	areq_t	*areq;
9203 	ire_t	*ire = NULL;
9204 	mblk_t	*res_mp;
9205 	ipaddr_t *addrp;
9206 	mblk_t *first_mp;
9207 	ire_t	*save_ire = NULL;
9208 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9209 	ipif_t	*src_ipif = NULL;
9210 	ushort_t ire_marks = 0;
9211 	ill_t	*dst_ill = NULL;
9212 	boolean_t mctl_present;
9213 	ipsec_out_t *io;
9214 	ipha_t *ipha;
9215 	int	ihandle = 0;
9216 	mblk_t	*saved_mp;
9217 	ire_t   *fire = NULL;
9218 	mblk_t  *copy_mp = NULL;
9219 	boolean_t multirt_resolve_next;
9220 	ipaddr_t ipha_dst;
9221 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9222 
9223 	/*
9224 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9225 	 * here for uniformity
9226 	 */
9227 	ipif_refhold(ipif);
9228 
9229 	/*
9230 	 * This loop is run only once in most cases.
9231 	 * We loop to resolve further routes only when the destination
9232 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9233 	 */
9234 	do {
9235 		if (dst_ill != NULL) {
9236 			ill_refrele(dst_ill);
9237 			dst_ill = NULL;
9238 		}
9239 		if (src_ipif != NULL) {
9240 			ipif_refrele(src_ipif);
9241 			src_ipif = NULL;
9242 		}
9243 		multirt_resolve_next = B_FALSE;
9244 
9245 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9246 		    ipif->ipif_ill->ill_name));
9247 
9248 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9249 		if (mctl_present)
9250 			io = (ipsec_out_t *)first_mp->b_rptr;
9251 
9252 		ipha = (ipha_t *)mp->b_rptr;
9253 
9254 		/*
9255 		 * Save the packet destination address, we may need it after
9256 		 * the packet has been consumed.
9257 		 */
9258 		ipha_dst = ipha->ipha_dst;
9259 
9260 		/*
9261 		 * If the interface is a pt-pt interface we look for an
9262 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9263 		 * local_address and the pt-pt destination address. Otherwise
9264 		 * we just match the local address.
9265 		 * NOTE: dst could be different than ipha->ipha_dst in case
9266 		 * of sending igmp multicast packets over a point-to-point
9267 		 * connection.
9268 		 * Thus we must be careful enough to check ipha_dst to be a
9269 		 * multicast address, otherwise it will take xmit_if path for
9270 		 * multicast packets resulting into kernel stack overflow by
9271 		 * repeated calls to ip_newroute_ipif from ire_send().
9272 		 */
9273 		if (CLASSD(ipha_dst) &&
9274 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9275 			goto err_ret;
9276 		}
9277 
9278 		/*
9279 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9280 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9281 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9282 		 * propagate its flags to the new ire.
9283 		 */
9284 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9285 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9286 			ip2dbg(("ip_newroute_ipif: "
9287 			    "ipif_lookup_multi_ire("
9288 			    "ipif %p, dst %08x) = fire %p\n",
9289 			    (void *)ipif, ntohl(dst), (void *)fire));
9290 		}
9291 
9292 		if (mctl_present && io->ipsec_out_attach_if) {
9293 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9294 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9295 
9296 			/* Failure case frees things for us. */
9297 			if (attach_ill == NULL) {
9298 				ipif_refrele(ipif);
9299 				if (fire != NULL)
9300 					ire_refrele(fire);
9301 				return;
9302 			}
9303 
9304 			/*
9305 			 * Check if we need an ire that will not be
9306 			 * looked up by anybody else i.e. HIDDEN.
9307 			 */
9308 			if (ill_is_probeonly(attach_ill)) {
9309 				ire_marks = IRE_MARK_HIDDEN;
9310 			}
9311 			/*
9312 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9313 			 * case.
9314 			 */
9315 			dst_ill = ipif->ipif_ill;
9316 			/* attach_ill has been refheld by ip_grab_attach_ill */
9317 			ASSERT(dst_ill == attach_ill);
9318 		} else {
9319 			/*
9320 			 * If this is set by IP_XMIT_IF, then make sure that
9321 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9322 			 * specified ill.
9323 			 */
9324 			ASSERT((connp == NULL) ||
9325 			    (connp->conn_xmit_if_ill == NULL) ||
9326 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9327 			/*
9328 			 * If the interface belongs to an interface group,
9329 			 * make sure the next possible interface in the group
9330 			 * is used.  This encourages load spreading among
9331 			 * peers in an interface group.
9332 			 * Note: load spreading is disabled for RTF_MULTIRT
9333 			 * routes.
9334 			 */
9335 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9336 			    (fire->ire_flags & RTF_MULTIRT)) {
9337 				/*
9338 				 * Don't perform outbound load spreading
9339 				 * in the case of an RTF_MULTIRT issued route,
9340 				 * we actually typically want to replicate
9341 				 * outgoing packets through particular
9342 				 * interfaces.
9343 				 */
9344 				dst_ill = ipif->ipif_ill;
9345 				ill_refhold(dst_ill);
9346 			} else {
9347 				dst_ill = ip_newroute_get_dst_ill(
9348 				    ipif->ipif_ill);
9349 			}
9350 			if (dst_ill == NULL) {
9351 				if (ip_debug > 2) {
9352 					pr_addr_dbg("ip_newroute_ipif: "
9353 					    "no dst ill for dst %s\n",
9354 					    AF_INET, &dst);
9355 				}
9356 				goto err_ret;
9357 			}
9358 		}
9359 
9360 		/*
9361 		 * Pick a source address preferring non-deprecated ones.
9362 		 * Unlike ip_newroute, we don't do any source address
9363 		 * selection here since for multicast it really does not help
9364 		 * in inbound load spreading as in the unicast case.
9365 		 */
9366 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9367 		    (fire->ire_flags & RTF_SETSRC)) {
9368 			/*
9369 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9370 			 * on that interface. This ire has RTF_SETSRC flag, so
9371 			 * the source address of the packet must be changed.
9372 			 * Check that the ipif matching the requested source
9373 			 * address still exists.
9374 			 */
9375 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9376 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9377 		}
9378 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9379 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9380 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9381 		    (src_ipif == NULL)) {
9382 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9383 			if (src_ipif == NULL) {
9384 				if (ip_debug > 2) {
9385 					/* ip1dbg */
9386 					pr_addr_dbg("ip_newroute_ipif: "
9387 					    "no src for dst %s",
9388 					    AF_INET, &dst);
9389 				}
9390 				ip1dbg((" through interface %s\n",
9391 				    dst_ill->ill_name));
9392 				goto err_ret;
9393 			}
9394 			ipif_refrele(ipif);
9395 			ipif = src_ipif;
9396 			ipif_refhold(ipif);
9397 		}
9398 		if (src_ipif == NULL) {
9399 			src_ipif = ipif;
9400 			ipif_refhold(src_ipif);
9401 		}
9402 
9403 		/*
9404 		 * Assign a source address while we have the conn.
9405 		 * We can't have ip_wput_ire pick a source address when the
9406 		 * packet returns from arp since conn_unspec_src might be set
9407 		 * and we loose the conn when going through arp.
9408 		 */
9409 		if (ipha->ipha_src == INADDR_ANY &&
9410 		    (connp == NULL || !connp->conn_unspec_src)) {
9411 			ipha->ipha_src = src_ipif->ipif_src_addr;
9412 		}
9413 
9414 		/*
9415 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9416 		 * interface does not have an interface ire.
9417 		 * Example: Thousands of mobileip PPP interfaces to mobile
9418 		 * nodes. We don't want to create interface ires because
9419 		 * packets from other mobile nodes must not take the route
9420 		 * via interface ires to the visiting mobile node without
9421 		 * going through the home agent, in absence of mobileip
9422 		 * route optimization.
9423 		 */
9424 		if (CLASSD(ipha_dst) && (connp == NULL ||
9425 		    connp->conn_xmit_if_ill == NULL) &&
9426 		    infop->ip_opt_ill_index == 0) {
9427 			/* ipif_to_ire returns an held ire */
9428 			ire = ipif_to_ire(ipif);
9429 			if (ire == NULL)
9430 				goto err_ret;
9431 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9432 				goto err_ret;
9433 			/*
9434 			 * ihandle is needed when the ire is added to
9435 			 * cache table.
9436 			 */
9437 			save_ire = ire;
9438 			ihandle = save_ire->ire_ihandle;
9439 
9440 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9441 			    "flags %04x\n",
9442 			    (void *)ire, (void *)ipif, flags));
9443 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9444 			    (fire->ire_flags & RTF_MULTIRT)) {
9445 				/*
9446 				 * As requested by flags, an IRE_OFFSUBNET was
9447 				 * looked up on that interface. This ire has
9448 				 * RTF_MULTIRT flag, so the resolution loop will
9449 				 * be re-entered to resolve additional routes on
9450 				 * other interfaces. For that purpose, a copy of
9451 				 * the packet is performed at this point.
9452 				 */
9453 				fire->ire_last_used_time = lbolt;
9454 				copy_mp = copymsg(first_mp);
9455 				if (copy_mp) {
9456 					MULTIRT_DEBUG_TAG(copy_mp);
9457 				}
9458 			}
9459 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9460 			    (fire->ire_flags & RTF_SETSRC)) {
9461 				/*
9462 				 * As requested by flags, an IRE_OFFSUBET was
9463 				 * looked up on that interface. This ire has
9464 				 * RTF_SETSRC flag, so the source address of the
9465 				 * packet must be changed.
9466 				 */
9467 				ipha->ipha_src = fire->ire_src_addr;
9468 			}
9469 		} else {
9470 			ASSERT((connp == NULL) ||
9471 			    (connp->conn_xmit_if_ill != NULL) ||
9472 			    (connp->conn_dontroute) ||
9473 			    infop->ip_opt_ill_index != 0);
9474 			/*
9475 			 * The only ways we can come here are:
9476 			 * 1) IP_XMIT_IF socket option is set
9477 			 * 2) ICMP error message generated from
9478 			 *    ip_mrtun_forward() routine and it needs
9479 			 *    to go through the specified ill.
9480 			 * 3) SO_DONTROUTE socket option is set
9481 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9482 			 * In all cases, the new ire will not be added
9483 			 * into cache table.
9484 			 */
9485 			ire_marks |= IRE_MARK_NOADD;
9486 		}
9487 
9488 		switch (ipif->ipif_net_type) {
9489 		case IRE_IF_NORESOLVER: {
9490 			/* We have what we need to build an IRE_CACHE. */
9491 			mblk_t	*res_mp;
9492 
9493 			/*
9494 			 * Create a new res_mp with the
9495 			 * IP gateway address as destination address in the
9496 			 * DLPI hdr if the physical length is exactly 4 bytes.
9497 			 */
9498 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9499 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9500 				    dst_ill->ill_phys_addr_length,
9501 				    dst_ill->ill_sap,
9502 				    dst_ill->ill_sap_length);
9503 			} else if (dst_ill->ill_resolver_mp == NULL) {
9504 				ip1dbg(("ip_newroute: dst_ill %p "
9505 				    "for IF_NORESOLV ire %p has "
9506 				    "no ill_resolver_mp\n",
9507 				    (void *)dst_ill, (void *)ire));
9508 				break;
9509 			} else {
9510 				/* use the value set in ip_ll_subnet_defaults */
9511 				res_mp = ill_dlur_gen(NULL,
9512 				    dst_ill->ill_phys_addr_length,
9513 				    dst_ill->ill_sap,
9514 				    dst_ill->ill_sap_length);
9515 			}
9516 
9517 			if (res_mp == NULL)
9518 				break;
9519 			/*
9520 			 * The new ire inherits the IRE_OFFSUBNET flags
9521 			 * and source address, if this was requested.
9522 			 */
9523 			ire = ire_create(
9524 			    (uchar_t *)&dst,		/* dest address */
9525 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9526 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9527 			    NULL,			/* gateway address */
9528 			    NULL,
9529 			    &ipif->ipif_mtu,
9530 			    NULL,			/* Fast Path header */
9531 			    dst_ill->ill_rq,		/* recv-from queue */
9532 			    dst_ill->ill_wq,		/* send-to queue */
9533 			    IRE_CACHE,
9534 			    res_mp,
9535 			    src_ipif,
9536 			    NULL,
9537 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9538 			    (fire != NULL) ?		/* Parent handle */
9539 				fire->ire_phandle : 0,
9540 			    ihandle,			/* Interface handle */
9541 			    (fire != NULL) ?
9542 				(fire->ire_flags &
9543 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9544 			    (save_ire == NULL ? &ire_uinfo_null :
9545 				&save_ire->ire_uinfo),
9546 			    NULL,
9547 			    NULL,
9548 			    ipst);
9549 
9550 			freeb(res_mp);
9551 
9552 			if (ire == NULL) {
9553 				if (save_ire != NULL)
9554 					ire_refrele(save_ire);
9555 				break;
9556 			}
9557 
9558 			ire->ire_marks |= ire_marks;
9559 
9560 			/*
9561 			 * If IRE_MARK_NOADD is set then we need to convert
9562 			 * the max_fragp to a useable value now. This is
9563 			 * normally done in ire_add_v[46]. We also need to
9564 			 * associate the ire with an nce (normally would be
9565 			 * done in ip_wput_nondata()).
9566 			 *
9567 			 * Note that IRE_MARK_NOADD packets created here
9568 			 * do not have a non-null ire_mp pointer. The null
9569 			 * value of ire_bucket indicates that they were
9570 			 * never added.
9571 			 */
9572 			if (ire->ire_marks & IRE_MARK_NOADD) {
9573 				uint_t  max_frag;
9574 
9575 				max_frag = *ire->ire_max_fragp;
9576 				ire->ire_max_fragp = NULL;
9577 				ire->ire_max_frag = max_frag;
9578 
9579 				if ((ire->ire_nce = ndp_lookup_v4(
9580 				    ire_to_ill(ire),
9581 				    (ire->ire_gateway_addr != INADDR_ANY ?
9582 				    &ire->ire_gateway_addr : &ire->ire_addr),
9583 				    B_FALSE)) == NULL) {
9584 					if (save_ire != NULL)
9585 						ire_refrele(save_ire);
9586 					break;
9587 				}
9588 				ASSERT(ire->ire_nce->nce_state ==
9589 				    ND_REACHABLE);
9590 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9591 			}
9592 
9593 			/* Prevent save_ire from getting deleted */
9594 			if (save_ire != NULL) {
9595 				IRB_REFHOLD(save_ire->ire_bucket);
9596 				/* Has it been removed already ? */
9597 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9598 					IRB_REFRELE(save_ire->ire_bucket);
9599 					ire_refrele(save_ire);
9600 					break;
9601 				}
9602 			}
9603 
9604 			ire_add_then_send(q, ire, first_mp);
9605 
9606 			/* Assert that save_ire is not deleted yet. */
9607 			if (save_ire != NULL) {
9608 				ASSERT(save_ire->ire_ptpn != NULL);
9609 				IRB_REFRELE(save_ire->ire_bucket);
9610 				ire_refrele(save_ire);
9611 				save_ire = NULL;
9612 			}
9613 			if (fire != NULL) {
9614 				ire_refrele(fire);
9615 				fire = NULL;
9616 			}
9617 
9618 			/*
9619 			 * the resolution loop is re-entered if this
9620 			 * was requested through flags and if we
9621 			 * actually are in a multirouting case.
9622 			 */
9623 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9624 				boolean_t need_resolve =
9625 				    ire_multirt_need_resolve(ipha_dst,
9626 					MBLK_GETLABEL(copy_mp), ipst);
9627 				if (!need_resolve) {
9628 					MULTIRT_DEBUG_UNTAG(copy_mp);
9629 					freemsg(copy_mp);
9630 					copy_mp = NULL;
9631 				} else {
9632 					/*
9633 					 * ipif_lookup_group() calls
9634 					 * ire_lookup_multi() that uses
9635 					 * ire_ftable_lookup() to find
9636 					 * an IRE_INTERFACE for the group.
9637 					 * In the multirt case,
9638 					 * ire_lookup_multi() then invokes
9639 					 * ire_multirt_lookup() to find
9640 					 * the next resolvable ire.
9641 					 * As a result, we obtain an new
9642 					 * interface, derived from the
9643 					 * next ire.
9644 					 */
9645 					ipif_refrele(ipif);
9646 					ipif = ipif_lookup_group(ipha_dst,
9647 					    zoneid, ipst);
9648 					ip2dbg(("ip_newroute_ipif: "
9649 					    "multirt dst %08x, ipif %p\n",
9650 					    htonl(dst), (void *)ipif));
9651 					if (ipif != NULL) {
9652 						mp = copy_mp;
9653 						copy_mp = NULL;
9654 						multirt_resolve_next = B_TRUE;
9655 						continue;
9656 					} else {
9657 						freemsg(copy_mp);
9658 					}
9659 				}
9660 			}
9661 			if (ipif != NULL)
9662 				ipif_refrele(ipif);
9663 			ill_refrele(dst_ill);
9664 			ipif_refrele(src_ipif);
9665 			return;
9666 		}
9667 		case IRE_IF_RESOLVER:
9668 			/*
9669 			 * We can't build an IRE_CACHE yet, but at least
9670 			 * we found a resolver that can help.
9671 			 */
9672 			res_mp = dst_ill->ill_resolver_mp;
9673 			if (!OK_RESOLVER_MP(res_mp))
9674 				break;
9675 
9676 			/*
9677 			 * We obtain a partial IRE_CACHE which we will pass
9678 			 * along with the resolver query.  When the response
9679 			 * comes back it will be there ready for us to add.
9680 			 * The new ire inherits the IRE_OFFSUBNET flags
9681 			 * and source address, if this was requested.
9682 			 * The ire_max_frag is atomically set under the
9683 			 * irebucket lock in ire_add_v[46]. Only in the
9684 			 * case of IRE_MARK_NOADD, we set it here itself.
9685 			 */
9686 			ire = ire_create_mp(
9687 			    (uchar_t *)&dst,		/* dest address */
9688 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9689 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9690 			    NULL,			/* gateway address */
9691 			    NULL,			/* no in_src_addr */
9692 			    (ire_marks & IRE_MARK_NOADD) ?
9693 				ipif->ipif_mtu : 0,	/* max_frag */
9694 			    NULL,			/* Fast path header */
9695 			    dst_ill->ill_rq,		/* recv-from queue */
9696 			    dst_ill->ill_wq,		/* send-to queue */
9697 			    IRE_CACHE,
9698 			    NULL,	/* let ire_nce_init figure res_mp out */
9699 			    src_ipif,
9700 			    NULL,
9701 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9702 			    (fire != NULL) ?		/* Parent handle */
9703 				fire->ire_phandle : 0,
9704 			    ihandle,			/* Interface handle */
9705 			    (fire != NULL) ?		/* flags if any */
9706 				(fire->ire_flags &
9707 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9708 			    (save_ire == NULL ? &ire_uinfo_null :
9709 				&save_ire->ire_uinfo),
9710 			    NULL,
9711 			    NULL,
9712 			    ipst);
9713 
9714 			if (save_ire != NULL) {
9715 				ire_refrele(save_ire);
9716 				save_ire = NULL;
9717 			}
9718 			if (ire == NULL)
9719 				break;
9720 
9721 			ire->ire_marks |= ire_marks;
9722 			/*
9723 			 * Construct message chain for the resolver of the
9724 			 * form:
9725 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9726 			 *
9727 			 * NOTE : ire will be added later when the response
9728 			 * comes back from ARP. If the response does not
9729 			 * come back, ARP frees the packet. For this reason,
9730 			 * we can't REFHOLD the bucket of save_ire to prevent
9731 			 * deletions. We may not be able to REFRELE the
9732 			 * bucket if the response never comes back.
9733 			 * Thus, before adding the ire, ire_add_v4 will make
9734 			 * sure that the interface route does not get deleted.
9735 			 * This is the only case unlike ip_newroute_v6,
9736 			 * ip_newroute_ipif_v6 where we can always prevent
9737 			 * deletions because ire_add_then_send is called after
9738 			 * creating the IRE.
9739 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9740 			 * does not add this IRE into the IRE CACHE.
9741 			 */
9742 			ASSERT(ire->ire_mp != NULL);
9743 			ire->ire_mp->b_cont = first_mp;
9744 			/* Have saved_mp handy, for cleanup if canput fails */
9745 			saved_mp = mp;
9746 			mp = copyb(res_mp);
9747 			if (mp == NULL) {
9748 				/* Prepare for cleanup */
9749 				mp = saved_mp; /* pkt */
9750 				ire_delete(ire); /* ire_mp */
9751 				ire = NULL;
9752 				if (copy_mp != NULL) {
9753 					MULTIRT_DEBUG_UNTAG(copy_mp);
9754 					freemsg(copy_mp);
9755 					copy_mp = NULL;
9756 				}
9757 				break;
9758 			}
9759 			linkb(mp, ire->ire_mp);
9760 
9761 			/*
9762 			 * Fill in the source and dest addrs for the resolver.
9763 			 * NOTE: this depends on memory layouts imposed by
9764 			 * ill_init().
9765 			 */
9766 			areq = (areq_t *)mp->b_rptr;
9767 			addrp = (ipaddr_t *)((char *)areq +
9768 			    areq->areq_sender_addr_offset);
9769 			*addrp = ire->ire_src_addr;
9770 			addrp = (ipaddr_t *)((char *)areq +
9771 			    areq->areq_target_addr_offset);
9772 			*addrp = dst;
9773 			/* Up to the resolver. */
9774 			if (canputnext(dst_ill->ill_rq) &&
9775 			    !(dst_ill->ill_arp_closing)) {
9776 				putnext(dst_ill->ill_rq, mp);
9777 				/*
9778 				 * The response will come back in ip_wput
9779 				 * with db_type IRE_DB_TYPE.
9780 				 */
9781 			} else {
9782 				mp->b_cont = NULL;
9783 				freeb(mp); /* areq */
9784 				ire_delete(ire); /* ire_mp */
9785 				saved_mp->b_next = NULL;
9786 				saved_mp->b_prev = NULL;
9787 				freemsg(first_mp); /* pkt */
9788 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9789 			}
9790 
9791 			if (fire != NULL) {
9792 				ire_refrele(fire);
9793 				fire = NULL;
9794 			}
9795 
9796 
9797 			/*
9798 			 * The resolution loop is re-entered if this was
9799 			 * requested through flags and we actually are
9800 			 * in a multirouting case.
9801 			 */
9802 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9803 				boolean_t need_resolve =
9804 				    ire_multirt_need_resolve(ipha_dst,
9805 					MBLK_GETLABEL(copy_mp), ipst);
9806 				if (!need_resolve) {
9807 					MULTIRT_DEBUG_UNTAG(copy_mp);
9808 					freemsg(copy_mp);
9809 					copy_mp = NULL;
9810 				} else {
9811 					/*
9812 					 * ipif_lookup_group() calls
9813 					 * ire_lookup_multi() that uses
9814 					 * ire_ftable_lookup() to find
9815 					 * an IRE_INTERFACE for the group.
9816 					 * In the multirt case,
9817 					 * ire_lookup_multi() then invokes
9818 					 * ire_multirt_lookup() to find
9819 					 * the next resolvable ire.
9820 					 * As a result, we obtain an new
9821 					 * interface, derived from the
9822 					 * next ire.
9823 					 */
9824 					ipif_refrele(ipif);
9825 					ipif = ipif_lookup_group(ipha_dst,
9826 					    zoneid, ipst);
9827 					if (ipif != NULL) {
9828 						mp = copy_mp;
9829 						copy_mp = NULL;
9830 						multirt_resolve_next = B_TRUE;
9831 						continue;
9832 					} else {
9833 						freemsg(copy_mp);
9834 					}
9835 				}
9836 			}
9837 			if (ipif != NULL)
9838 				ipif_refrele(ipif);
9839 			ill_refrele(dst_ill);
9840 			ipif_refrele(src_ipif);
9841 			return;
9842 		default:
9843 			break;
9844 		}
9845 	} while (multirt_resolve_next);
9846 
9847 err_ret:
9848 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9849 	if (fire != NULL)
9850 		ire_refrele(fire);
9851 	ipif_refrele(ipif);
9852 	/* Did this packet originate externally? */
9853 	if (dst_ill != NULL)
9854 		ill_refrele(dst_ill);
9855 	if (src_ipif != NULL)
9856 		ipif_refrele(src_ipif);
9857 	if (mp->b_prev || mp->b_next) {
9858 		mp->b_next = NULL;
9859 		mp->b_prev = NULL;
9860 	} else {
9861 		/*
9862 		 * Since ip_wput() isn't close to finished, we fill
9863 		 * in enough of the header for credible error reporting.
9864 		 */
9865 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9866 			/* Failed */
9867 			freemsg(first_mp);
9868 			if (ire != NULL)
9869 				ire_refrele(ire);
9870 			return;
9871 		}
9872 	}
9873 	/*
9874 	 * At this point we will have ire only if RTF_BLACKHOLE
9875 	 * or RTF_REJECT flags are set on the IRE. It will not
9876 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9877 	 */
9878 	if (ire != NULL) {
9879 		if (ire->ire_flags & RTF_BLACKHOLE) {
9880 			ire_refrele(ire);
9881 			freemsg(first_mp);
9882 			return;
9883 		}
9884 		ire_refrele(ire);
9885 	}
9886 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9887 }
9888 
9889 /* Name/Value Table Lookup Routine */
9890 char *
9891 ip_nv_lookup(nv_t *nv, int value)
9892 {
9893 	if (!nv)
9894 		return (NULL);
9895 	for (; nv->nv_name; nv++) {
9896 		if (nv->nv_value == value)
9897 			return (nv->nv_name);
9898 	}
9899 	return ("unknown");
9900 }
9901 
9902 /*
9903  * This is a module open, i.e. this is a control stream for access
9904  * to a DLPI device.  We allocate an ill_t as the instance data in
9905  * this case.
9906  */
9907 int
9908 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9909 {
9910 	ill_t	*ill;
9911 	int	err;
9912 	zoneid_t zoneid;
9913 	netstack_t *ns;
9914 	ip_stack_t *ipst;
9915 
9916 	/*
9917 	 * Prevent unprivileged processes from pushing IP so that
9918 	 * they can't send raw IP.
9919 	 */
9920 	if (secpolicy_net_rawaccess(credp) != 0)
9921 		return (EPERM);
9922 
9923 	ns = netstack_find_by_cred(credp);
9924 	ASSERT(ns != NULL);
9925 	ipst = ns->netstack_ip;
9926 	ASSERT(ipst != NULL);
9927 
9928 	/*
9929 	 * For exclusive stacks we set the zoneid to zero
9930 	 * to make IP operate as if in the global zone.
9931 	 */
9932 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9933 		zoneid = GLOBAL_ZONEID;
9934 	else
9935 		zoneid = crgetzoneid(credp);
9936 
9937 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9938 	q->q_ptr = WR(q)->q_ptr = ill;
9939 	ill->ill_ipst = ipst;
9940 	ill->ill_zoneid = zoneid;
9941 
9942 	/*
9943 	 * ill_init initializes the ill fields and then sends down
9944 	 * down a DL_INFO_REQ after calling qprocson.
9945 	 */
9946 	err = ill_init(q, ill);
9947 	if (err != 0) {
9948 		mi_free(ill);
9949 		netstack_rele(ipst->ips_netstack);
9950 		q->q_ptr = NULL;
9951 		WR(q)->q_ptr = NULL;
9952 		return (err);
9953 	}
9954 
9955 	/* ill_init initializes the ipsq marking this thread as writer */
9956 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9957 	/* Wait for the DL_INFO_ACK */
9958 	mutex_enter(&ill->ill_lock);
9959 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9960 		/*
9961 		 * Return value of 0 indicates a pending signal.
9962 		 */
9963 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9964 		if (err == 0) {
9965 			mutex_exit(&ill->ill_lock);
9966 			(void) ip_close(q, 0);
9967 			return (EINTR);
9968 		}
9969 	}
9970 	mutex_exit(&ill->ill_lock);
9971 
9972 	/*
9973 	 * ip_rput_other could have set an error  in ill_error on
9974 	 * receipt of M_ERROR.
9975 	 */
9976 
9977 	err = ill->ill_error;
9978 	if (err != 0) {
9979 		(void) ip_close(q, 0);
9980 		return (err);
9981 	}
9982 
9983 	ill->ill_credp = credp;
9984 	crhold(credp);
9985 
9986 	mutex_enter(&ipst->ips_ip_mi_lock);
9987 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9988 	    credp);
9989 	mutex_exit(&ipst->ips_ip_mi_lock);
9990 	if (err) {
9991 		(void) ip_close(q, 0);
9992 		return (err);
9993 	}
9994 	return (0);
9995 }
9996 
9997 /* IP open routine. */
9998 int
9999 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
10000 {
10001 	conn_t 		*connp;
10002 	major_t		maj;
10003 	zoneid_t	zoneid;
10004 	netstack_t	*ns;
10005 	ip_stack_t	*ipst;
10006 
10007 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
10008 
10009 	/* Allow reopen. */
10010 	if (q->q_ptr != NULL)
10011 		return (0);
10012 
10013 	if (sflag & MODOPEN) {
10014 		/* This is a module open */
10015 		return (ip_modopen(q, devp, flag, sflag, credp));
10016 	}
10017 
10018 	ns = netstack_find_by_cred(credp);
10019 	ASSERT(ns != NULL);
10020 	ipst = ns->netstack_ip;
10021 	ASSERT(ipst != NULL);
10022 
10023 	/*
10024 	 * For exclusive stacks we set the zoneid to zero
10025 	 * to make IP operate as if in the global zone.
10026 	 */
10027 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
10028 		zoneid = GLOBAL_ZONEID;
10029 	else
10030 		zoneid = crgetzoneid(credp);
10031 
10032 	/*
10033 	 * We are opening as a device. This is an IP client stream, and we
10034 	 * allocate an conn_t as the instance data.
10035 	 */
10036 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
10037 
10038 	/*
10039 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
10040 	 * done by netstack_find_by_cred()
10041 	 */
10042 	netstack_rele(ipst->ips_netstack);
10043 
10044 	connp->conn_zoneid = zoneid;
10045 
10046 	connp->conn_upq = q;
10047 	q->q_ptr = WR(q)->q_ptr = connp;
10048 
10049 	if (flag & SO_SOCKSTR)
10050 		connp->conn_flags |= IPCL_SOCKET;
10051 
10052 	/* Minor tells us which /dev entry was opened */
10053 	if (geteminor(*devp) == IPV6_MINOR) {
10054 		connp->conn_flags |= IPCL_ISV6;
10055 		connp->conn_af_isv6 = B_TRUE;
10056 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
10057 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
10058 	} else {
10059 		connp->conn_af_isv6 = B_FALSE;
10060 		connp->conn_pkt_isv6 = B_FALSE;
10061 	}
10062 
10063 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
10064 		/* CONN_DEC_REF takes care of netstack_rele() */
10065 		q->q_ptr = WR(q)->q_ptr = NULL;
10066 		CONN_DEC_REF(connp);
10067 		return (EBUSY);
10068 	}
10069 
10070 	maj = getemajor(*devp);
10071 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
10072 
10073 	/*
10074 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
10075 	 */
10076 	connp->conn_cred = credp;
10077 	crhold(connp->conn_cred);
10078 
10079 	/*
10080 	 * If the caller has the process-wide flag set, then default to MAC
10081 	 * exempt mode.  This allows read-down to unlabeled hosts.
10082 	 */
10083 	if (getpflags(NET_MAC_AWARE, credp) != 0)
10084 		connp->conn_mac_exempt = B_TRUE;
10085 
10086 	/*
10087 	 * This should only happen for ndd, netstat, raw socket or other SCTP
10088 	 * administrative ops.  In these cases, we just need a normal conn_t
10089 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
10090 	 * an error will be returned.
10091 	 */
10092 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
10093 		connp->conn_rq = q;
10094 		connp->conn_wq = WR(q);
10095 	} else {
10096 		connp->conn_ulp = IPPROTO_SCTP;
10097 		connp->conn_rq = connp->conn_wq = NULL;
10098 	}
10099 	/* Non-zero default values */
10100 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
10101 
10102 	/*
10103 	 * Make the conn globally visible to walkers
10104 	 */
10105 	mutex_enter(&connp->conn_lock);
10106 	connp->conn_state_flags &= ~CONN_INCIPIENT;
10107 	mutex_exit(&connp->conn_lock);
10108 	ASSERT(connp->conn_ref == 1);
10109 
10110 	qprocson(q);
10111 
10112 	return (0);
10113 }
10114 
10115 /*
10116  * Change q_qinfo based on the value of isv6.
10117  * This can not called on an ill queue.
10118  * Note that there is no race since either q_qinfo works for conn queues - it
10119  * is just an optimization to enter the best wput routine directly.
10120  */
10121 void
10122 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
10123 {
10124 	ASSERT(q->q_flag & QREADR);
10125 	ASSERT(WR(q)->q_next == NULL);
10126 	ASSERT(q->q_ptr != NULL);
10127 
10128 	if (minor == IPV6_MINOR)  {
10129 		if (bump_mib) {
10130 			BUMP_MIB(&ipst->ips_ip6_mib,
10131 			    ipIfStatsOutSwitchIPVersion);
10132 		}
10133 		q->q_qinfo = &rinit_ipv6;
10134 		WR(q)->q_qinfo = &winit_ipv6;
10135 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
10136 	} else {
10137 		if (bump_mib) {
10138 			BUMP_MIB(&ipst->ips_ip_mib,
10139 			    ipIfStatsOutSwitchIPVersion);
10140 		}
10141 		q->q_qinfo = &iprinit;
10142 		WR(q)->q_qinfo = &ipwinit;
10143 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
10144 	}
10145 
10146 }
10147 
10148 /*
10149  * See if IPsec needs loading because of the options in mp.
10150  */
10151 static boolean_t
10152 ipsec_opt_present(mblk_t *mp)
10153 {
10154 	uint8_t *optcp, *next_optcp, *opt_endcp;
10155 	struct opthdr *opt;
10156 	struct T_opthdr *topt;
10157 	int opthdr_len;
10158 	t_uscalar_t optname, optlevel;
10159 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10160 	ipsec_req_t *ipsr;
10161 
10162 	/*
10163 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10164 	 * return TRUE.
10165 	 */
10166 
10167 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10168 	opt_endcp = optcp + tor->OPT_length;
10169 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10170 		opthdr_len = sizeof (struct T_opthdr);
10171 	} else {		/* O_OPTMGMT_REQ */
10172 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10173 		opthdr_len = sizeof (struct opthdr);
10174 	}
10175 	for (; optcp < opt_endcp; optcp = next_optcp) {
10176 		if (optcp + opthdr_len > opt_endcp)
10177 			return (B_FALSE);	/* Not enough option header. */
10178 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10179 			topt = (struct T_opthdr *)optcp;
10180 			optlevel = topt->level;
10181 			optname = topt->name;
10182 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10183 		} else {
10184 			opt = (struct opthdr *)optcp;
10185 			optlevel = opt->level;
10186 			optname = opt->name;
10187 			next_optcp = optcp + opthdr_len +
10188 			    _TPI_ALIGN_OPT(opt->len);
10189 		}
10190 		if ((next_optcp < optcp) || /* wraparound pointer space */
10191 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10192 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10193 			return (B_FALSE); /* bad option buffer */
10194 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10195 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10196 			/*
10197 			 * Check to see if it's an all-bypass or all-zeroes
10198 			 * IPsec request.  Don't bother loading IPsec if
10199 			 * the socket doesn't want to use it.  (A good example
10200 			 * is a bypass request.)
10201 			 *
10202 			 * Basically, if any of the non-NEVER bits are set,
10203 			 * load IPsec.
10204 			 */
10205 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10206 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10207 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10208 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10209 			    != 0)
10210 				return (B_TRUE);
10211 		}
10212 	}
10213 	return (B_FALSE);
10214 }
10215 
10216 /*
10217  * If conn is is waiting for ipsec to finish loading, kick it.
10218  */
10219 /* ARGSUSED */
10220 static void
10221 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10222 {
10223 	t_scalar_t	optreq_prim;
10224 	mblk_t		*mp;
10225 	cred_t		*cr;
10226 	int		err = 0;
10227 
10228 	/*
10229 	 * This function is called, after ipsec loading is complete.
10230 	 * Since IP checks exclusively and atomically (i.e it prevents
10231 	 * ipsec load from completing until ip_optcom_req completes)
10232 	 * whether ipsec load is complete, there cannot be a race with IP
10233 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10234 	 */
10235 	mutex_enter(&connp->conn_lock);
10236 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10237 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10238 		mp = connp->conn_ipsec_opt_mp;
10239 		connp->conn_ipsec_opt_mp = NULL;
10240 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10241 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10242 		mutex_exit(&connp->conn_lock);
10243 
10244 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10245 
10246 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10247 		if (optreq_prim == T_OPTMGMT_REQ) {
10248 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10249 			    &ip_opt_obj);
10250 		} else {
10251 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10252 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10253 			    &ip_opt_obj);
10254 		}
10255 		if (err != EINPROGRESS)
10256 			CONN_OPER_PENDING_DONE(connp);
10257 		return;
10258 	}
10259 	mutex_exit(&connp->conn_lock);
10260 }
10261 
10262 /*
10263  * Called from the ipsec_loader thread, outside any perimeter, to tell
10264  * ip qenable any of the queues waiting for the ipsec loader to
10265  * complete.
10266  */
10267 void
10268 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10269 {
10270 	netstack_t *ns = ipss->ipsec_netstack;
10271 
10272 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10273 }
10274 
10275 /*
10276  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10277  * determines the grp on which it has to become exclusive, queues the mp
10278  * and sq draining restarts the optmgmt
10279  */
10280 static boolean_t
10281 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10282 {
10283 	conn_t *connp = Q_TO_CONN(q);
10284 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10285 
10286 	/*
10287 	 * Take IPsec requests and treat them special.
10288 	 */
10289 	if (ipsec_opt_present(mp)) {
10290 		/* First check if IPsec is loaded. */
10291 		mutex_enter(&ipss->ipsec_loader_lock);
10292 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10293 			mutex_exit(&ipss->ipsec_loader_lock);
10294 			return (B_FALSE);
10295 		}
10296 		mutex_enter(&connp->conn_lock);
10297 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10298 
10299 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10300 		connp->conn_ipsec_opt_mp = mp;
10301 		mutex_exit(&connp->conn_lock);
10302 		mutex_exit(&ipss->ipsec_loader_lock);
10303 
10304 		ipsec_loader_loadnow(ipss);
10305 		return (B_TRUE);
10306 	}
10307 	return (B_FALSE);
10308 }
10309 
10310 /*
10311  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10312  * all of them are copied to the conn_t. If the req is "zero", the policy is
10313  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10314  * fields.
10315  * We keep only the latest setting of the policy and thus policy setting
10316  * is not incremental/cumulative.
10317  *
10318  * Requests to set policies with multiple alternative actions will
10319  * go through a different API.
10320  */
10321 int
10322 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10323 {
10324 	uint_t ah_req = 0;
10325 	uint_t esp_req = 0;
10326 	uint_t se_req = 0;
10327 	ipsec_selkey_t sel;
10328 	ipsec_act_t *actp = NULL;
10329 	uint_t nact;
10330 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10331 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10332 	ipsec_policy_root_t *pr;
10333 	ipsec_policy_head_t *ph;
10334 	int fam;
10335 	boolean_t is_pol_reset;
10336 	int error = 0;
10337 	netstack_t	*ns = connp->conn_netstack;
10338 	ip_stack_t	*ipst = ns->netstack_ip;
10339 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10340 
10341 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10342 
10343 	/*
10344 	 * The IP_SEC_OPT option does not allow variable length parameters,
10345 	 * hence a request cannot be NULL.
10346 	 */
10347 	if (req == NULL)
10348 		return (EINVAL);
10349 
10350 	ah_req = req->ipsr_ah_req;
10351 	esp_req = req->ipsr_esp_req;
10352 	se_req = req->ipsr_self_encap_req;
10353 
10354 	/*
10355 	 * Are we dealing with a request to reset the policy (i.e.
10356 	 * zero requests).
10357 	 */
10358 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10359 	    (esp_req & REQ_MASK) == 0 &&
10360 	    (se_req & REQ_MASK) == 0);
10361 
10362 	if (!is_pol_reset) {
10363 		/*
10364 		 * If we couldn't load IPsec, fail with "protocol
10365 		 * not supported".
10366 		 * IPsec may not have been loaded for a request with zero
10367 		 * policies, so we don't fail in this case.
10368 		 */
10369 		mutex_enter(&ipss->ipsec_loader_lock);
10370 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10371 			mutex_exit(&ipss->ipsec_loader_lock);
10372 			return (EPROTONOSUPPORT);
10373 		}
10374 		mutex_exit(&ipss->ipsec_loader_lock);
10375 
10376 		/*
10377 		 * Test for valid requests. Invalid algorithms
10378 		 * need to be tested by IPSEC code because new
10379 		 * algorithms can be added dynamically.
10380 		 */
10381 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10382 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10383 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10384 			return (EINVAL);
10385 		}
10386 
10387 		/*
10388 		 * Only privileged users can issue these
10389 		 * requests.
10390 		 */
10391 		if (((ah_req & IPSEC_PREF_NEVER) ||
10392 		    (esp_req & IPSEC_PREF_NEVER) ||
10393 		    (se_req & IPSEC_PREF_NEVER)) &&
10394 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10395 			return (EPERM);
10396 		}
10397 
10398 		/*
10399 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10400 		 * are mutually exclusive.
10401 		 */
10402 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10403 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10404 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10405 			/* Both of them are set */
10406 			return (EINVAL);
10407 		}
10408 	}
10409 
10410 	mutex_enter(&connp->conn_lock);
10411 
10412 	/*
10413 	 * If we have already cached policies in ip_bind_connected*(), don't
10414 	 * let them change now. We cache policies for connections
10415 	 * whose src,dst [addr, port] is known.
10416 	 */
10417 	if (connp->conn_policy_cached) {
10418 		mutex_exit(&connp->conn_lock);
10419 		return (EINVAL);
10420 	}
10421 
10422 	/*
10423 	 * We have a zero policies, reset the connection policy if already
10424 	 * set. This will cause the connection to inherit the
10425 	 * global policy, if any.
10426 	 */
10427 	if (is_pol_reset) {
10428 		if (connp->conn_policy != NULL) {
10429 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10430 			connp->conn_policy = NULL;
10431 		}
10432 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10433 		connp->conn_in_enforce_policy = B_FALSE;
10434 		connp->conn_out_enforce_policy = B_FALSE;
10435 		mutex_exit(&connp->conn_lock);
10436 		return (0);
10437 	}
10438 
10439 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10440 	    ipst->ips_netstack);
10441 	if (ph == NULL)
10442 		goto enomem;
10443 
10444 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10445 	if (actp == NULL)
10446 		goto enomem;
10447 
10448 	/*
10449 	 * Always allocate IPv4 policy entries, since they can also
10450 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10451 	 */
10452 	bzero(&sel, sizeof (sel));
10453 	sel.ipsl_valid = IPSL_IPV4;
10454 
10455 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10456 	    ipst->ips_netstack);
10457 	if (pin4 == NULL)
10458 		goto enomem;
10459 
10460 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10461 	    ipst->ips_netstack);
10462 	if (pout4 == NULL)
10463 		goto enomem;
10464 
10465 	if (connp->conn_pkt_isv6) {
10466 		/*
10467 		 * We're looking at a v6 socket, also allocate the
10468 		 * v6-specific entries...
10469 		 */
10470 		sel.ipsl_valid = IPSL_IPV6;
10471 		pin6 = ipsec_policy_create(&sel, actp, nact,
10472 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10473 		if (pin6 == NULL)
10474 			goto enomem;
10475 
10476 		pout6 = ipsec_policy_create(&sel, actp, nact,
10477 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10478 		if (pout6 == NULL)
10479 			goto enomem;
10480 
10481 		/*
10482 		 * .. and file them away in the right place.
10483 		 */
10484 		fam = IPSEC_AF_V6;
10485 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10486 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10487 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10488 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10489 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10490 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10491 	}
10492 
10493 	ipsec_actvec_free(actp, nact);
10494 
10495 	/*
10496 	 * File the v4 policies.
10497 	 */
10498 	fam = IPSEC_AF_V4;
10499 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10500 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10501 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10502 
10503 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10504 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10505 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10506 
10507 	/*
10508 	 * If the requests need security, set enforce_policy.
10509 	 * If the requests are IPSEC_PREF_NEVER, one should
10510 	 * still set conn_out_enforce_policy so that an ipsec_out
10511 	 * gets attached in ip_wput. This is needed so that
10512 	 * for connections that we don't cache policy in ip_bind,
10513 	 * if global policy matches in ip_wput_attach_policy, we
10514 	 * don't wrongly inherit global policy. Similarly, we need
10515 	 * to set conn_in_enforce_policy also so that we don't verify
10516 	 * policy wrongly.
10517 	 */
10518 	if ((ah_req & REQ_MASK) != 0 ||
10519 	    (esp_req & REQ_MASK) != 0 ||
10520 	    (se_req & REQ_MASK) != 0) {
10521 		connp->conn_in_enforce_policy = B_TRUE;
10522 		connp->conn_out_enforce_policy = B_TRUE;
10523 		connp->conn_flags |= IPCL_CHECK_POLICY;
10524 	}
10525 
10526 	mutex_exit(&connp->conn_lock);
10527 	return (error);
10528 #undef REQ_MASK
10529 
10530 	/*
10531 	 * Common memory-allocation-failure exit path.
10532 	 */
10533 enomem:
10534 	mutex_exit(&connp->conn_lock);
10535 	if (actp != NULL)
10536 		ipsec_actvec_free(actp, nact);
10537 	if (pin4 != NULL)
10538 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10539 	if (pout4 != NULL)
10540 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10541 	if (pin6 != NULL)
10542 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10543 	if (pout6 != NULL)
10544 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10545 	return (ENOMEM);
10546 }
10547 
10548 /*
10549  * Only for options that pass in an IP addr. Currently only V4 options
10550  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10551  * So this function assumes level is IPPROTO_IP
10552  */
10553 int
10554 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10555     mblk_t *first_mp)
10556 {
10557 	ipif_t *ipif = NULL;
10558 	int error;
10559 	ill_t *ill;
10560 	int zoneid;
10561 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10562 
10563 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10564 
10565 	if (addr != INADDR_ANY || checkonly) {
10566 		ASSERT(connp != NULL);
10567 		zoneid = IPCL_ZONEID(connp);
10568 		if (option == IP_NEXTHOP) {
10569 			ipif = ipif_lookup_onlink_addr(addr,
10570 			    connp->conn_zoneid, ipst);
10571 		} else {
10572 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10573 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10574 			    &error, ipst);
10575 		}
10576 		if (ipif == NULL) {
10577 			if (error == EINPROGRESS)
10578 				return (error);
10579 			else if ((option == IP_MULTICAST_IF) ||
10580 			    (option == IP_NEXTHOP))
10581 				return (EHOSTUNREACH);
10582 			else
10583 				return (EINVAL);
10584 		} else if (checkonly) {
10585 			if (option == IP_MULTICAST_IF) {
10586 				ill = ipif->ipif_ill;
10587 				/* not supported by the virtual network iface */
10588 				if (IS_VNI(ill)) {
10589 					ipif_refrele(ipif);
10590 					return (EINVAL);
10591 				}
10592 			}
10593 			ipif_refrele(ipif);
10594 			return (0);
10595 		}
10596 		ill = ipif->ipif_ill;
10597 		mutex_enter(&connp->conn_lock);
10598 		mutex_enter(&ill->ill_lock);
10599 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10600 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10601 			mutex_exit(&ill->ill_lock);
10602 			mutex_exit(&connp->conn_lock);
10603 			ipif_refrele(ipif);
10604 			return (option == IP_MULTICAST_IF ?
10605 			    EHOSTUNREACH : EINVAL);
10606 		}
10607 	} else {
10608 		mutex_enter(&connp->conn_lock);
10609 	}
10610 
10611 	/* None of the options below are supported on the VNI */
10612 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10613 		mutex_exit(&ill->ill_lock);
10614 		mutex_exit(&connp->conn_lock);
10615 		ipif_refrele(ipif);
10616 		return (EINVAL);
10617 	}
10618 
10619 	switch (option) {
10620 	case IP_DONTFAILOVER_IF:
10621 		/*
10622 		 * This option is used by in.mpathd to ensure
10623 		 * that IPMP probe packets only go out on the
10624 		 * test interfaces. in.mpathd sets this option
10625 		 * on the non-failover interfaces.
10626 		 * For backward compatibility, this option
10627 		 * implicitly sets IP_MULTICAST_IF, as used
10628 		 * be done in bind(), so that ip_wput gets
10629 		 * this ipif to send mcast packets.
10630 		 */
10631 		if (ipif != NULL) {
10632 			ASSERT(addr != INADDR_ANY);
10633 			connp->conn_nofailover_ill = ipif->ipif_ill;
10634 			connp->conn_multicast_ipif = ipif;
10635 		} else {
10636 			ASSERT(addr == INADDR_ANY);
10637 			connp->conn_nofailover_ill = NULL;
10638 			connp->conn_multicast_ipif = NULL;
10639 		}
10640 		break;
10641 
10642 	case IP_MULTICAST_IF:
10643 		connp->conn_multicast_ipif = ipif;
10644 		break;
10645 	case IP_NEXTHOP:
10646 		connp->conn_nexthop_v4 = addr;
10647 		connp->conn_nexthop_set = B_TRUE;
10648 		break;
10649 	}
10650 
10651 	if (ipif != NULL) {
10652 		mutex_exit(&ill->ill_lock);
10653 		mutex_exit(&connp->conn_lock);
10654 		ipif_refrele(ipif);
10655 		return (0);
10656 	}
10657 	mutex_exit(&connp->conn_lock);
10658 	/* We succeded in cleared the option */
10659 	return (0);
10660 }
10661 
10662 /*
10663  * For options that pass in an ifindex specifying the ill. V6 options always
10664  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10665  */
10666 int
10667 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10668     int level, int option, mblk_t *first_mp)
10669 {
10670 	ill_t *ill = NULL;
10671 	int error = 0;
10672 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10673 
10674 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10675 	if (ifindex != 0) {
10676 		ASSERT(connp != NULL);
10677 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10678 		    first_mp, ip_restart_optmgmt, &error, ipst);
10679 		if (ill != NULL) {
10680 			if (checkonly) {
10681 				/* not supported by the virtual network iface */
10682 				if (IS_VNI(ill)) {
10683 					ill_refrele(ill);
10684 					return (EINVAL);
10685 				}
10686 				ill_refrele(ill);
10687 				return (0);
10688 			}
10689 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10690 			    0, NULL)) {
10691 				ill_refrele(ill);
10692 				ill = NULL;
10693 				mutex_enter(&connp->conn_lock);
10694 				goto setit;
10695 			}
10696 			mutex_enter(&connp->conn_lock);
10697 			mutex_enter(&ill->ill_lock);
10698 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10699 				mutex_exit(&ill->ill_lock);
10700 				mutex_exit(&connp->conn_lock);
10701 				ill_refrele(ill);
10702 				ill = NULL;
10703 				mutex_enter(&connp->conn_lock);
10704 			}
10705 			goto setit;
10706 		} else if (error == EINPROGRESS) {
10707 			return (error);
10708 		} else {
10709 			error = 0;
10710 		}
10711 	}
10712 	mutex_enter(&connp->conn_lock);
10713 setit:
10714 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10715 
10716 	/*
10717 	 * The options below assume that the ILL (if any) transmits and/or
10718 	 * receives traffic. Neither of which is true for the virtual network
10719 	 * interface, so fail setting these on a VNI.
10720 	 */
10721 	if (IS_VNI(ill)) {
10722 		ASSERT(ill != NULL);
10723 		mutex_exit(&ill->ill_lock);
10724 		mutex_exit(&connp->conn_lock);
10725 		ill_refrele(ill);
10726 		return (EINVAL);
10727 	}
10728 
10729 	if (level == IPPROTO_IP) {
10730 		switch (option) {
10731 		case IP_BOUND_IF:
10732 			connp->conn_incoming_ill = ill;
10733 			connp->conn_outgoing_ill = ill;
10734 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10735 			    0 : ifindex;
10736 			break;
10737 
10738 		case IP_XMIT_IF:
10739 			/*
10740 			 * Similar to IP_BOUND_IF, but this only
10741 			 * determines the outgoing interface for
10742 			 * unicast packets. Also no IRE_CACHE entry
10743 			 * is added for the destination of the
10744 			 * outgoing packets. This feature is needed
10745 			 * for mobile IP.
10746 			 */
10747 			connp->conn_xmit_if_ill = ill;
10748 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10749 			    0 : ifindex;
10750 			break;
10751 
10752 		case IP_MULTICAST_IF:
10753 			/*
10754 			 * This option is an internal special. The socket
10755 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10756 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10757 			 * specifies an ifindex and we try first on V6 ill's.
10758 			 * If we don't find one, we they try using on v4 ill's
10759 			 * intenally and we come here.
10760 			 */
10761 			if (!checkonly && ill != NULL) {
10762 				ipif_t	*ipif;
10763 				ipif = ill->ill_ipif;
10764 
10765 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10766 					mutex_exit(&ill->ill_lock);
10767 					mutex_exit(&connp->conn_lock);
10768 					ill_refrele(ill);
10769 					ill = NULL;
10770 					mutex_enter(&connp->conn_lock);
10771 				} else {
10772 					connp->conn_multicast_ipif = ipif;
10773 				}
10774 			}
10775 			break;
10776 		}
10777 	} else {
10778 		switch (option) {
10779 		case IPV6_BOUND_IF:
10780 			connp->conn_incoming_ill = ill;
10781 			connp->conn_outgoing_ill = ill;
10782 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10783 			    0 : ifindex;
10784 			break;
10785 
10786 		case IPV6_BOUND_PIF:
10787 			/*
10788 			 * Limit all transmit to this ill.
10789 			 * Unlike IPV6_BOUND_IF, using this option
10790 			 * prevents load spreading and failover from
10791 			 * happening when the interface is part of the
10792 			 * group. That's why we don't need to remember
10793 			 * the ifindex in orig_bound_ifindex as in
10794 			 * IPV6_BOUND_IF.
10795 			 */
10796 			connp->conn_outgoing_pill = ill;
10797 			break;
10798 
10799 		case IPV6_DONTFAILOVER_IF:
10800 			/*
10801 			 * This option is used by in.mpathd to ensure
10802 			 * that IPMP probe packets only go out on the
10803 			 * test interfaces. in.mpathd sets this option
10804 			 * on the non-failover interfaces.
10805 			 */
10806 			connp->conn_nofailover_ill = ill;
10807 			/*
10808 			 * For backward compatibility, this option
10809 			 * implicitly sets ip_multicast_ill as used in
10810 			 * IP_MULTICAST_IF so that ip_wput gets
10811 			 * this ipif to send mcast packets.
10812 			 */
10813 			connp->conn_multicast_ill = ill;
10814 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10815 			    0 : ifindex;
10816 			break;
10817 
10818 		case IPV6_MULTICAST_IF:
10819 			/*
10820 			 * Set conn_multicast_ill to be the IPv6 ill.
10821 			 * Set conn_multicast_ipif to be an IPv4 ipif
10822 			 * for ifindex to make IPv4 mapped addresses
10823 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10824 			 * Even if no IPv6 ill exists for the ifindex
10825 			 * we need to check for an IPv4 ifindex in order
10826 			 * for this to work with mapped addresses. In that
10827 			 * case only set conn_multicast_ipif.
10828 			 */
10829 			if (!checkonly) {
10830 				if (ifindex == 0) {
10831 					connp->conn_multicast_ill = NULL;
10832 					connp->conn_orig_multicast_ifindex = 0;
10833 					connp->conn_multicast_ipif = NULL;
10834 				} else if (ill != NULL) {
10835 					connp->conn_multicast_ill = ill;
10836 					connp->conn_orig_multicast_ifindex =
10837 					    ifindex;
10838 				}
10839 			}
10840 			break;
10841 		}
10842 	}
10843 
10844 	if (ill != NULL) {
10845 		mutex_exit(&ill->ill_lock);
10846 		mutex_exit(&connp->conn_lock);
10847 		ill_refrele(ill);
10848 		return (0);
10849 	}
10850 	mutex_exit(&connp->conn_lock);
10851 	/*
10852 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10853 	 * locate the ill and could not set the option (ifindex != 0)
10854 	 */
10855 	return (ifindex == 0 ? 0 : EINVAL);
10856 }
10857 
10858 /* This routine sets socket options. */
10859 /* ARGSUSED */
10860 int
10861 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10862     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10863     void *dummy, cred_t *cr, mblk_t *first_mp)
10864 {
10865 	int		*i1 = (int *)invalp;
10866 	conn_t		*connp = Q_TO_CONN(q);
10867 	int		error = 0;
10868 	boolean_t	checkonly;
10869 	ire_t		*ire;
10870 	boolean_t	found;
10871 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10872 
10873 	switch (optset_context) {
10874 
10875 	case SETFN_OPTCOM_CHECKONLY:
10876 		checkonly = B_TRUE;
10877 		/*
10878 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10879 		 * inlen != 0 implies value supplied and
10880 		 * 	we have to "pretend" to set it.
10881 		 * inlen == 0 implies that there is no
10882 		 * 	value part in T_CHECK request and just validation
10883 		 * done elsewhere should be enough, we just return here.
10884 		 */
10885 		if (inlen == 0) {
10886 			*outlenp = 0;
10887 			return (0);
10888 		}
10889 		break;
10890 	case SETFN_OPTCOM_NEGOTIATE:
10891 	case SETFN_UD_NEGOTIATE:
10892 	case SETFN_CONN_NEGOTIATE:
10893 		checkonly = B_FALSE;
10894 		break;
10895 	default:
10896 		/*
10897 		 * We should never get here
10898 		 */
10899 		*outlenp = 0;
10900 		return (EINVAL);
10901 	}
10902 
10903 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10904 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10905 
10906 	/*
10907 	 * For fixed length options, no sanity check
10908 	 * of passed in length is done. It is assumed *_optcom_req()
10909 	 * routines do the right thing.
10910 	 */
10911 
10912 	switch (level) {
10913 	case SOL_SOCKET:
10914 		/*
10915 		 * conn_lock protects the bitfields, and is used to
10916 		 * set the fields atomically.
10917 		 */
10918 		switch (name) {
10919 		case SO_BROADCAST:
10920 			if (!checkonly) {
10921 				/* TODO: use value someplace? */
10922 				mutex_enter(&connp->conn_lock);
10923 				connp->conn_broadcast = *i1 ? 1 : 0;
10924 				mutex_exit(&connp->conn_lock);
10925 			}
10926 			break;	/* goto sizeof (int) option return */
10927 		case SO_USELOOPBACK:
10928 			if (!checkonly) {
10929 				/* TODO: use value someplace? */
10930 				mutex_enter(&connp->conn_lock);
10931 				connp->conn_loopback = *i1 ? 1 : 0;
10932 				mutex_exit(&connp->conn_lock);
10933 			}
10934 			break;	/* goto sizeof (int) option return */
10935 		case SO_DONTROUTE:
10936 			if (!checkonly) {
10937 				mutex_enter(&connp->conn_lock);
10938 				connp->conn_dontroute = *i1 ? 1 : 0;
10939 				mutex_exit(&connp->conn_lock);
10940 			}
10941 			break;	/* goto sizeof (int) option return */
10942 		case SO_REUSEADDR:
10943 			if (!checkonly) {
10944 				mutex_enter(&connp->conn_lock);
10945 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10946 				mutex_exit(&connp->conn_lock);
10947 			}
10948 			break;	/* goto sizeof (int) option return */
10949 		case SO_PROTOTYPE:
10950 			if (!checkonly) {
10951 				mutex_enter(&connp->conn_lock);
10952 				connp->conn_proto = *i1;
10953 				mutex_exit(&connp->conn_lock);
10954 			}
10955 			break;	/* goto sizeof (int) option return */
10956 		case SO_ALLZONES:
10957 			if (!checkonly) {
10958 				mutex_enter(&connp->conn_lock);
10959 				if (IPCL_IS_BOUND(connp)) {
10960 					mutex_exit(&connp->conn_lock);
10961 					return (EINVAL);
10962 				}
10963 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10964 				mutex_exit(&connp->conn_lock);
10965 			}
10966 			break;	/* goto sizeof (int) option return */
10967 		case SO_ANON_MLP:
10968 			if (!checkonly) {
10969 				mutex_enter(&connp->conn_lock);
10970 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10971 				mutex_exit(&connp->conn_lock);
10972 			}
10973 			break;	/* goto sizeof (int) option return */
10974 		case SO_MAC_EXEMPT:
10975 			if (secpolicy_net_mac_aware(cr) != 0 ||
10976 			    IPCL_IS_BOUND(connp))
10977 				return (EACCES);
10978 			if (!checkonly) {
10979 				mutex_enter(&connp->conn_lock);
10980 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10981 				mutex_exit(&connp->conn_lock);
10982 			}
10983 			break;	/* goto sizeof (int) option return */
10984 		default:
10985 			/*
10986 			 * "soft" error (negative)
10987 			 * option not handled at this level
10988 			 * Note: Do not modify *outlenp
10989 			 */
10990 			return (-EINVAL);
10991 		}
10992 		break;
10993 	case IPPROTO_IP:
10994 		switch (name) {
10995 		case IP_NEXTHOP:
10996 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10997 				return (EPERM);
10998 			/* FALLTHRU */
10999 		case IP_MULTICAST_IF:
11000 		case IP_DONTFAILOVER_IF: {
11001 			ipaddr_t addr = *i1;
11002 
11003 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
11004 			    first_mp);
11005 			if (error != 0)
11006 				return (error);
11007 			break;	/* goto sizeof (int) option return */
11008 		}
11009 
11010 		case IP_MULTICAST_TTL:
11011 			/* Recorded in transport above IP */
11012 			*outvalp = *invalp;
11013 			*outlenp = sizeof (uchar_t);
11014 			return (0);
11015 		case IP_MULTICAST_LOOP:
11016 			if (!checkonly) {
11017 				mutex_enter(&connp->conn_lock);
11018 				connp->conn_multicast_loop = *invalp ? 1 : 0;
11019 				mutex_exit(&connp->conn_lock);
11020 			}
11021 			*outvalp = *invalp;
11022 			*outlenp = sizeof (uchar_t);
11023 			return (0);
11024 		case IP_ADD_MEMBERSHIP:
11025 		case MCAST_JOIN_GROUP:
11026 		case IP_DROP_MEMBERSHIP:
11027 		case MCAST_LEAVE_GROUP: {
11028 			struct ip_mreq *mreqp;
11029 			struct group_req *greqp;
11030 			ire_t *ire;
11031 			boolean_t done = B_FALSE;
11032 			ipaddr_t group, ifaddr;
11033 			struct sockaddr_in *sin;
11034 			uint32_t *ifindexp;
11035 			boolean_t mcast_opt = B_TRUE;
11036 			mcast_record_t fmode;
11037 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11038 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11039 
11040 			switch (name) {
11041 			case IP_ADD_MEMBERSHIP:
11042 				mcast_opt = B_FALSE;
11043 				/* FALLTHRU */
11044 			case MCAST_JOIN_GROUP:
11045 				fmode = MODE_IS_EXCLUDE;
11046 				optfn = ip_opt_add_group;
11047 				break;
11048 
11049 			case IP_DROP_MEMBERSHIP:
11050 				mcast_opt = B_FALSE;
11051 				/* FALLTHRU */
11052 			case MCAST_LEAVE_GROUP:
11053 				fmode = MODE_IS_INCLUDE;
11054 				optfn = ip_opt_delete_group;
11055 				break;
11056 			}
11057 
11058 			if (mcast_opt) {
11059 				greqp = (struct group_req *)i1;
11060 				sin = (struct sockaddr_in *)&greqp->gr_group;
11061 				if (sin->sin_family != AF_INET) {
11062 					*outlenp = 0;
11063 					return (ENOPROTOOPT);
11064 				}
11065 				group = (ipaddr_t)sin->sin_addr.s_addr;
11066 				ifaddr = INADDR_ANY;
11067 				ifindexp = &greqp->gr_interface;
11068 			} else {
11069 				mreqp = (struct ip_mreq *)i1;
11070 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
11071 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
11072 				ifindexp = NULL;
11073 			}
11074 
11075 			/*
11076 			 * In the multirouting case, we need to replicate
11077 			 * the request on all interfaces that will take part
11078 			 * in replication.  We do so because multirouting is
11079 			 * reflective, thus we will probably receive multi-
11080 			 * casts on those interfaces.
11081 			 * The ip_multirt_apply_membership() succeeds if the
11082 			 * operation succeeds on at least one interface.
11083 			 */
11084 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
11085 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11086 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11087 			if (ire != NULL) {
11088 				if (ire->ire_flags & RTF_MULTIRT) {
11089 					error = ip_multirt_apply_membership(
11090 					    optfn, ire, connp, checkonly, group,
11091 					    fmode, INADDR_ANY, first_mp);
11092 					done = B_TRUE;
11093 				}
11094 				ire_refrele(ire);
11095 			}
11096 			if (!done) {
11097 				error = optfn(connp, checkonly, group, ifaddr,
11098 				    ifindexp, fmode, INADDR_ANY, first_mp);
11099 			}
11100 			if (error) {
11101 				/*
11102 				 * EINPROGRESS is a soft error, needs retry
11103 				 * so don't make *outlenp zero.
11104 				 */
11105 				if (error != EINPROGRESS)
11106 					*outlenp = 0;
11107 				return (error);
11108 			}
11109 			/* OK return - copy input buffer into output buffer */
11110 			if (invalp != outvalp) {
11111 				/* don't trust bcopy for identical src/dst */
11112 				bcopy(invalp, outvalp, inlen);
11113 			}
11114 			*outlenp = inlen;
11115 			return (0);
11116 		}
11117 		case IP_BLOCK_SOURCE:
11118 		case IP_UNBLOCK_SOURCE:
11119 		case IP_ADD_SOURCE_MEMBERSHIP:
11120 		case IP_DROP_SOURCE_MEMBERSHIP:
11121 		case MCAST_BLOCK_SOURCE:
11122 		case MCAST_UNBLOCK_SOURCE:
11123 		case MCAST_JOIN_SOURCE_GROUP:
11124 		case MCAST_LEAVE_SOURCE_GROUP: {
11125 			struct ip_mreq_source *imreqp;
11126 			struct group_source_req *gsreqp;
11127 			in_addr_t grp, src, ifaddr = INADDR_ANY;
11128 			uint32_t ifindex = 0;
11129 			mcast_record_t fmode;
11130 			struct sockaddr_in *sin;
11131 			ire_t *ire;
11132 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11133 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11134 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11135 
11136 			switch (name) {
11137 			case IP_BLOCK_SOURCE:
11138 				mcast_opt = B_FALSE;
11139 				/* FALLTHRU */
11140 			case MCAST_BLOCK_SOURCE:
11141 				fmode = MODE_IS_EXCLUDE;
11142 				optfn = ip_opt_add_group;
11143 				break;
11144 
11145 			case IP_UNBLOCK_SOURCE:
11146 				mcast_opt = B_FALSE;
11147 				/* FALLTHRU */
11148 			case MCAST_UNBLOCK_SOURCE:
11149 				fmode = MODE_IS_EXCLUDE;
11150 				optfn = ip_opt_delete_group;
11151 				break;
11152 
11153 			case IP_ADD_SOURCE_MEMBERSHIP:
11154 				mcast_opt = B_FALSE;
11155 				/* FALLTHRU */
11156 			case MCAST_JOIN_SOURCE_GROUP:
11157 				fmode = MODE_IS_INCLUDE;
11158 				optfn = ip_opt_add_group;
11159 				break;
11160 
11161 			case IP_DROP_SOURCE_MEMBERSHIP:
11162 				mcast_opt = B_FALSE;
11163 				/* FALLTHRU */
11164 			case MCAST_LEAVE_SOURCE_GROUP:
11165 				fmode = MODE_IS_INCLUDE;
11166 				optfn = ip_opt_delete_group;
11167 				break;
11168 			}
11169 
11170 			if (mcast_opt) {
11171 				gsreqp = (struct group_source_req *)i1;
11172 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11173 					*outlenp = 0;
11174 					return (ENOPROTOOPT);
11175 				}
11176 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11177 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11178 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11179 				src = (ipaddr_t)sin->sin_addr.s_addr;
11180 				ifindex = gsreqp->gsr_interface;
11181 			} else {
11182 				imreqp = (struct ip_mreq_source *)i1;
11183 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11184 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11185 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11186 			}
11187 
11188 			/*
11189 			 * In the multirouting case, we need to replicate
11190 			 * the request as noted in the mcast cases above.
11191 			 */
11192 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11193 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11194 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11195 			if (ire != NULL) {
11196 				if (ire->ire_flags & RTF_MULTIRT) {
11197 					error = ip_multirt_apply_membership(
11198 					    optfn, ire, connp, checkonly, grp,
11199 					    fmode, src, first_mp);
11200 					done = B_TRUE;
11201 				}
11202 				ire_refrele(ire);
11203 			}
11204 			if (!done) {
11205 				error = optfn(connp, checkonly, grp, ifaddr,
11206 				    &ifindex, fmode, src, first_mp);
11207 			}
11208 			if (error != 0) {
11209 				/*
11210 				 * EINPROGRESS is a soft error, needs retry
11211 				 * so don't make *outlenp zero.
11212 				 */
11213 				if (error != EINPROGRESS)
11214 					*outlenp = 0;
11215 				return (error);
11216 			}
11217 			/* OK return - copy input buffer into output buffer */
11218 			if (invalp != outvalp) {
11219 				bcopy(invalp, outvalp, inlen);
11220 			}
11221 			*outlenp = inlen;
11222 			return (0);
11223 		}
11224 		case IP_SEC_OPT:
11225 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11226 			if (error != 0) {
11227 				*outlenp = 0;
11228 				return (error);
11229 			}
11230 			break;
11231 		case IP_HDRINCL:
11232 		case IP_OPTIONS:
11233 		case T_IP_OPTIONS:
11234 		case IP_TOS:
11235 		case T_IP_TOS:
11236 		case IP_TTL:
11237 		case IP_RECVDSTADDR:
11238 		case IP_RECVOPTS:
11239 			/* OK return - copy input buffer into output buffer */
11240 			if (invalp != outvalp) {
11241 				/* don't trust bcopy for identical src/dst */
11242 				bcopy(invalp, outvalp, inlen);
11243 			}
11244 			*outlenp = inlen;
11245 			return (0);
11246 		case IP_RECVIF:
11247 			/* Retrieve the inbound interface index */
11248 			if (!checkonly) {
11249 				mutex_enter(&connp->conn_lock);
11250 				connp->conn_recvif = *i1 ? 1 : 0;
11251 				mutex_exit(&connp->conn_lock);
11252 			}
11253 			break;	/* goto sizeof (int) option return */
11254 		case IP_RECVPKTINFO:
11255 			if (!checkonly) {
11256 				mutex_enter(&connp->conn_lock);
11257 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11258 				mutex_exit(&connp->conn_lock);
11259 			}
11260 			break;	/* goto sizeof (int) option return */
11261 		case IP_RECVSLLA:
11262 			/* Retrieve the source link layer address */
11263 			if (!checkonly) {
11264 				mutex_enter(&connp->conn_lock);
11265 				connp->conn_recvslla = *i1 ? 1 : 0;
11266 				mutex_exit(&connp->conn_lock);
11267 			}
11268 			break;	/* goto sizeof (int) option return */
11269 		case MRT_INIT:
11270 		case MRT_DONE:
11271 		case MRT_ADD_VIF:
11272 		case MRT_DEL_VIF:
11273 		case MRT_ADD_MFC:
11274 		case MRT_DEL_MFC:
11275 		case MRT_ASSERT:
11276 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11277 				*outlenp = 0;
11278 				return (error);
11279 			}
11280 			error = ip_mrouter_set((int)name, q, checkonly,
11281 			    (uchar_t *)invalp, inlen, first_mp);
11282 			if (error) {
11283 				*outlenp = 0;
11284 				return (error);
11285 			}
11286 			/* OK return - copy input buffer into output buffer */
11287 			if (invalp != outvalp) {
11288 				/* don't trust bcopy for identical src/dst */
11289 				bcopy(invalp, outvalp, inlen);
11290 			}
11291 			*outlenp = inlen;
11292 			return (0);
11293 		case IP_BOUND_IF:
11294 		case IP_XMIT_IF:
11295 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11296 			    level, name, first_mp);
11297 			if (error != 0)
11298 				return (error);
11299 			break; 		/* goto sizeof (int) option return */
11300 
11301 		case IP_UNSPEC_SRC:
11302 			/* Allow sending with a zero source address */
11303 			if (!checkonly) {
11304 				mutex_enter(&connp->conn_lock);
11305 				connp->conn_unspec_src = *i1 ? 1 : 0;
11306 				mutex_exit(&connp->conn_lock);
11307 			}
11308 			break;	/* goto sizeof (int) option return */
11309 		default:
11310 			/*
11311 			 * "soft" error (negative)
11312 			 * option not handled at this level
11313 			 * Note: Do not modify *outlenp
11314 			 */
11315 			return (-EINVAL);
11316 		}
11317 		break;
11318 	case IPPROTO_IPV6:
11319 		switch (name) {
11320 		case IPV6_BOUND_IF:
11321 		case IPV6_BOUND_PIF:
11322 		case IPV6_DONTFAILOVER_IF:
11323 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11324 			    level, name, first_mp);
11325 			if (error != 0)
11326 				return (error);
11327 			break; 		/* goto sizeof (int) option return */
11328 
11329 		case IPV6_MULTICAST_IF:
11330 			/*
11331 			 * The only possible errors are EINPROGRESS and
11332 			 * EINVAL. EINPROGRESS will be restarted and is not
11333 			 * a hard error. We call this option on both V4 and V6
11334 			 * If both return EINVAL, then this call returns
11335 			 * EINVAL. If at least one of them succeeds we
11336 			 * return success.
11337 			 */
11338 			found = B_FALSE;
11339 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11340 			    level, name, first_mp);
11341 			if (error == EINPROGRESS)
11342 				return (error);
11343 			if (error == 0)
11344 				found = B_TRUE;
11345 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11346 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11347 			if (error == 0)
11348 				found = B_TRUE;
11349 			if (!found)
11350 				return (error);
11351 			break; 		/* goto sizeof (int) option return */
11352 
11353 		case IPV6_MULTICAST_HOPS:
11354 			/* Recorded in transport above IP */
11355 			break;	/* goto sizeof (int) option return */
11356 		case IPV6_MULTICAST_LOOP:
11357 			if (!checkonly) {
11358 				mutex_enter(&connp->conn_lock);
11359 				connp->conn_multicast_loop = *i1;
11360 				mutex_exit(&connp->conn_lock);
11361 			}
11362 			break;	/* goto sizeof (int) option return */
11363 		case IPV6_JOIN_GROUP:
11364 		case MCAST_JOIN_GROUP:
11365 		case IPV6_LEAVE_GROUP:
11366 		case MCAST_LEAVE_GROUP: {
11367 			struct ipv6_mreq *ip_mreqp;
11368 			struct group_req *greqp;
11369 			ire_t *ire;
11370 			boolean_t done = B_FALSE;
11371 			in6_addr_t groupv6;
11372 			uint32_t ifindex;
11373 			boolean_t mcast_opt = B_TRUE;
11374 			mcast_record_t fmode;
11375 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11376 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11377 
11378 			switch (name) {
11379 			case IPV6_JOIN_GROUP:
11380 				mcast_opt = B_FALSE;
11381 				/* FALLTHRU */
11382 			case MCAST_JOIN_GROUP:
11383 				fmode = MODE_IS_EXCLUDE;
11384 				optfn = ip_opt_add_group_v6;
11385 				break;
11386 
11387 			case IPV6_LEAVE_GROUP:
11388 				mcast_opt = B_FALSE;
11389 				/* FALLTHRU */
11390 			case MCAST_LEAVE_GROUP:
11391 				fmode = MODE_IS_INCLUDE;
11392 				optfn = ip_opt_delete_group_v6;
11393 				break;
11394 			}
11395 
11396 			if (mcast_opt) {
11397 				struct sockaddr_in *sin;
11398 				struct sockaddr_in6 *sin6;
11399 				greqp = (struct group_req *)i1;
11400 				if (greqp->gr_group.ss_family == AF_INET) {
11401 					sin = (struct sockaddr_in *)
11402 					    &(greqp->gr_group);
11403 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11404 					    &groupv6);
11405 				} else {
11406 					sin6 = (struct sockaddr_in6 *)
11407 					    &(greqp->gr_group);
11408 					groupv6 = sin6->sin6_addr;
11409 				}
11410 				ifindex = greqp->gr_interface;
11411 			} else {
11412 				ip_mreqp = (struct ipv6_mreq *)i1;
11413 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11414 				ifindex = ip_mreqp->ipv6mr_interface;
11415 			}
11416 			/*
11417 			 * In the multirouting case, we need to replicate
11418 			 * the request on all interfaces that will take part
11419 			 * in replication.  We do so because multirouting is
11420 			 * reflective, thus we will probably receive multi-
11421 			 * casts on those interfaces.
11422 			 * The ip_multirt_apply_membership_v6() succeeds if
11423 			 * the operation succeeds on at least one interface.
11424 			 */
11425 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11426 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11427 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11428 			if (ire != NULL) {
11429 				if (ire->ire_flags & RTF_MULTIRT) {
11430 					error = ip_multirt_apply_membership_v6(
11431 					    optfn, ire, connp, checkonly,
11432 					    &groupv6, fmode, &ipv6_all_zeros,
11433 					    first_mp);
11434 					done = B_TRUE;
11435 				}
11436 				ire_refrele(ire);
11437 			}
11438 			if (!done) {
11439 				error = optfn(connp, checkonly, &groupv6,
11440 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11441 			}
11442 			if (error) {
11443 				/*
11444 				 * EINPROGRESS is a soft error, needs retry
11445 				 * so don't make *outlenp zero.
11446 				 */
11447 				if (error != EINPROGRESS)
11448 					*outlenp = 0;
11449 				return (error);
11450 			}
11451 			/* OK return - copy input buffer into output buffer */
11452 			if (invalp != outvalp) {
11453 				/* don't trust bcopy for identical src/dst */
11454 				bcopy(invalp, outvalp, inlen);
11455 			}
11456 			*outlenp = inlen;
11457 			return (0);
11458 		}
11459 		case MCAST_BLOCK_SOURCE:
11460 		case MCAST_UNBLOCK_SOURCE:
11461 		case MCAST_JOIN_SOURCE_GROUP:
11462 		case MCAST_LEAVE_SOURCE_GROUP: {
11463 			struct group_source_req *gsreqp;
11464 			in6_addr_t v6grp, v6src;
11465 			uint32_t ifindex;
11466 			mcast_record_t fmode;
11467 			ire_t *ire;
11468 			boolean_t done = B_FALSE;
11469 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11470 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11471 
11472 			switch (name) {
11473 			case MCAST_BLOCK_SOURCE:
11474 				fmode = MODE_IS_EXCLUDE;
11475 				optfn = ip_opt_add_group_v6;
11476 				break;
11477 			case MCAST_UNBLOCK_SOURCE:
11478 				fmode = MODE_IS_EXCLUDE;
11479 				optfn = ip_opt_delete_group_v6;
11480 				break;
11481 			case MCAST_JOIN_SOURCE_GROUP:
11482 				fmode = MODE_IS_INCLUDE;
11483 				optfn = ip_opt_add_group_v6;
11484 				break;
11485 			case MCAST_LEAVE_SOURCE_GROUP:
11486 				fmode = MODE_IS_INCLUDE;
11487 				optfn = ip_opt_delete_group_v6;
11488 				break;
11489 			}
11490 
11491 			gsreqp = (struct group_source_req *)i1;
11492 			ifindex = gsreqp->gsr_interface;
11493 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11494 				struct sockaddr_in *s;
11495 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11496 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11497 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11498 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11499 			} else {
11500 				struct sockaddr_in6 *s6;
11501 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11502 				v6grp = s6->sin6_addr;
11503 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11504 				v6src = s6->sin6_addr;
11505 			}
11506 
11507 			/*
11508 			 * In the multirouting case, we need to replicate
11509 			 * the request as noted in the mcast cases above.
11510 			 */
11511 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11512 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11513 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11514 			if (ire != NULL) {
11515 				if (ire->ire_flags & RTF_MULTIRT) {
11516 					error = ip_multirt_apply_membership_v6(
11517 					    optfn, ire, connp, checkonly,
11518 					    &v6grp, fmode, &v6src, first_mp);
11519 					done = B_TRUE;
11520 				}
11521 				ire_refrele(ire);
11522 			}
11523 			if (!done) {
11524 				error = optfn(connp, checkonly, &v6grp,
11525 				    ifindex, fmode, &v6src, first_mp);
11526 			}
11527 			if (error != 0) {
11528 				/*
11529 				 * EINPROGRESS is a soft error, needs retry
11530 				 * so don't make *outlenp zero.
11531 				 */
11532 				if (error != EINPROGRESS)
11533 					*outlenp = 0;
11534 				return (error);
11535 			}
11536 			/* OK return - copy input buffer into output buffer */
11537 			if (invalp != outvalp) {
11538 				bcopy(invalp, outvalp, inlen);
11539 			}
11540 			*outlenp = inlen;
11541 			return (0);
11542 		}
11543 		case IPV6_UNICAST_HOPS:
11544 			/* Recorded in transport above IP */
11545 			break;	/* goto sizeof (int) option return */
11546 		case IPV6_UNSPEC_SRC:
11547 			/* Allow sending with a zero source address */
11548 			if (!checkonly) {
11549 				mutex_enter(&connp->conn_lock);
11550 				connp->conn_unspec_src = *i1 ? 1 : 0;
11551 				mutex_exit(&connp->conn_lock);
11552 			}
11553 			break;	/* goto sizeof (int) option return */
11554 		case IPV6_RECVPKTINFO:
11555 			if (!checkonly) {
11556 				mutex_enter(&connp->conn_lock);
11557 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11558 				mutex_exit(&connp->conn_lock);
11559 			}
11560 			break;	/* goto sizeof (int) option return */
11561 		case IPV6_RECVTCLASS:
11562 			if (!checkonly) {
11563 				if (*i1 < 0 || *i1 > 1) {
11564 					return (EINVAL);
11565 				}
11566 				mutex_enter(&connp->conn_lock);
11567 				connp->conn_ipv6_recvtclass = *i1;
11568 				mutex_exit(&connp->conn_lock);
11569 			}
11570 			break;
11571 		case IPV6_RECVPATHMTU:
11572 			if (!checkonly) {
11573 				if (*i1 < 0 || *i1 > 1) {
11574 					return (EINVAL);
11575 				}
11576 				mutex_enter(&connp->conn_lock);
11577 				connp->conn_ipv6_recvpathmtu = *i1;
11578 				mutex_exit(&connp->conn_lock);
11579 			}
11580 			break;
11581 		case IPV6_RECVHOPLIMIT:
11582 			if (!checkonly) {
11583 				mutex_enter(&connp->conn_lock);
11584 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11585 				mutex_exit(&connp->conn_lock);
11586 			}
11587 			break;	/* goto sizeof (int) option return */
11588 		case IPV6_RECVHOPOPTS:
11589 			if (!checkonly) {
11590 				mutex_enter(&connp->conn_lock);
11591 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11592 				mutex_exit(&connp->conn_lock);
11593 			}
11594 			break;	/* goto sizeof (int) option return */
11595 		case IPV6_RECVDSTOPTS:
11596 			if (!checkonly) {
11597 				mutex_enter(&connp->conn_lock);
11598 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11599 				mutex_exit(&connp->conn_lock);
11600 			}
11601 			break;	/* goto sizeof (int) option return */
11602 		case IPV6_RECVRTHDR:
11603 			if (!checkonly) {
11604 				mutex_enter(&connp->conn_lock);
11605 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11606 				mutex_exit(&connp->conn_lock);
11607 			}
11608 			break;	/* goto sizeof (int) option return */
11609 		case IPV6_RECVRTHDRDSTOPTS:
11610 			if (!checkonly) {
11611 				mutex_enter(&connp->conn_lock);
11612 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11613 				mutex_exit(&connp->conn_lock);
11614 			}
11615 			break;	/* goto sizeof (int) option return */
11616 		case IPV6_PKTINFO:
11617 			if (inlen == 0)
11618 				return (-EINVAL);	/* clearing option */
11619 			error = ip6_set_pktinfo(cr, connp,
11620 			    (struct in6_pktinfo *)invalp, first_mp);
11621 			if (error != 0)
11622 				*outlenp = 0;
11623 			else
11624 				*outlenp = inlen;
11625 			return (error);
11626 		case IPV6_NEXTHOP: {
11627 			struct sockaddr_in6 *sin6;
11628 
11629 			/* Verify that the nexthop is reachable */
11630 			if (inlen == 0)
11631 				return (-EINVAL);	/* clearing option */
11632 
11633 			sin6 = (struct sockaddr_in6 *)invalp;
11634 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11635 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11636 			    NULL, MATCH_IRE_DEFAULT, ipst);
11637 
11638 			if (ire == NULL) {
11639 				*outlenp = 0;
11640 				return (EHOSTUNREACH);
11641 			}
11642 			ire_refrele(ire);
11643 			return (-EINVAL);
11644 		}
11645 		case IPV6_SEC_OPT:
11646 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11647 			if (error != 0) {
11648 				*outlenp = 0;
11649 				return (error);
11650 			}
11651 			break;
11652 		case IPV6_SRC_PREFERENCES: {
11653 			/*
11654 			 * This is implemented strictly in the ip module
11655 			 * (here and in tcp_opt_*() to accomodate tcp
11656 			 * sockets).  Modules above ip pass this option
11657 			 * down here since ip is the only one that needs to
11658 			 * be aware of source address preferences.
11659 			 *
11660 			 * This socket option only affects connected
11661 			 * sockets that haven't already bound to a specific
11662 			 * IPv6 address.  In other words, sockets that
11663 			 * don't call bind() with an address other than the
11664 			 * unspecified address and that call connect().
11665 			 * ip_bind_connected_v6() passes these preferences
11666 			 * to the ipif_select_source_v6() function.
11667 			 */
11668 			if (inlen != sizeof (uint32_t))
11669 				return (EINVAL);
11670 			error = ip6_set_src_preferences(connp,
11671 			    *(uint32_t *)invalp);
11672 			if (error != 0) {
11673 				*outlenp = 0;
11674 				return (error);
11675 			} else {
11676 				*outlenp = sizeof (uint32_t);
11677 			}
11678 			break;
11679 		}
11680 		case IPV6_V6ONLY:
11681 			if (*i1 < 0 || *i1 > 1) {
11682 				return (EINVAL);
11683 			}
11684 			mutex_enter(&connp->conn_lock);
11685 			connp->conn_ipv6_v6only = *i1;
11686 			mutex_exit(&connp->conn_lock);
11687 			break;
11688 		default:
11689 			return (-EINVAL);
11690 		}
11691 		break;
11692 	default:
11693 		/*
11694 		 * "soft" error (negative)
11695 		 * option not handled at this level
11696 		 * Note: Do not modify *outlenp
11697 		 */
11698 		return (-EINVAL);
11699 	}
11700 	/*
11701 	 * Common case of return from an option that is sizeof (int)
11702 	 */
11703 	*(int *)outvalp = *i1;
11704 	*outlenp = sizeof (int);
11705 	return (0);
11706 }
11707 
11708 /*
11709  * This routine gets default values of certain options whose default
11710  * values are maintained by protocol specific code
11711  */
11712 /* ARGSUSED */
11713 int
11714 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11715 {
11716 	int *i1 = (int *)ptr;
11717 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11718 
11719 	switch (level) {
11720 	case IPPROTO_IP:
11721 		switch (name) {
11722 		case IP_MULTICAST_TTL:
11723 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11724 			return (sizeof (uchar_t));
11725 		case IP_MULTICAST_LOOP:
11726 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11727 			return (sizeof (uchar_t));
11728 		default:
11729 			return (-1);
11730 		}
11731 	case IPPROTO_IPV6:
11732 		switch (name) {
11733 		case IPV6_UNICAST_HOPS:
11734 			*i1 = ipst->ips_ipv6_def_hops;
11735 			return (sizeof (int));
11736 		case IPV6_MULTICAST_HOPS:
11737 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11738 			return (sizeof (int));
11739 		case IPV6_MULTICAST_LOOP:
11740 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11741 			return (sizeof (int));
11742 		case IPV6_V6ONLY:
11743 			*i1 = 1;
11744 			return (sizeof (int));
11745 		default:
11746 			return (-1);
11747 		}
11748 	default:
11749 		return (-1);
11750 	}
11751 	/* NOTREACHED */
11752 }
11753 
11754 /*
11755  * Given a destination address and a pointer to where to put the information
11756  * this routine fills in the mtuinfo.
11757  */
11758 int
11759 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11760     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11761 {
11762 	ire_t *ire;
11763 	ip_stack_t	*ipst = ns->netstack_ip;
11764 
11765 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11766 		return (-1);
11767 
11768 	bzero(mtuinfo, sizeof (*mtuinfo));
11769 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11770 	mtuinfo->ip6m_addr.sin6_port = port;
11771 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11772 
11773 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11774 	if (ire != NULL) {
11775 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11776 		ire_refrele(ire);
11777 	} else {
11778 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11779 	}
11780 	return (sizeof (struct ip6_mtuinfo));
11781 }
11782 
11783 /*
11784  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11785  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11786  * isn't.  This doesn't matter as the error checking is done properly for the
11787  * other MRT options coming in through ip_opt_set.
11788  */
11789 int
11790 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11791 {
11792 	conn_t		*connp = Q_TO_CONN(q);
11793 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11794 
11795 	switch (level) {
11796 	case IPPROTO_IP:
11797 		switch (name) {
11798 		case MRT_VERSION:
11799 		case MRT_ASSERT:
11800 			(void) ip_mrouter_get(name, q, ptr);
11801 			return (sizeof (int));
11802 		case IP_SEC_OPT:
11803 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11804 		case IP_NEXTHOP:
11805 			if (connp->conn_nexthop_set) {
11806 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11807 				return (sizeof (ipaddr_t));
11808 			} else
11809 				return (0);
11810 		case IP_RECVPKTINFO:
11811 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11812 			return (sizeof (int));
11813 		default:
11814 			break;
11815 		}
11816 		break;
11817 	case IPPROTO_IPV6:
11818 		switch (name) {
11819 		case IPV6_SEC_OPT:
11820 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11821 		case IPV6_SRC_PREFERENCES: {
11822 			return (ip6_get_src_preferences(connp,
11823 			    (uint32_t *)ptr));
11824 		}
11825 		case IPV6_V6ONLY:
11826 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11827 			return (sizeof (int));
11828 		case IPV6_PATHMTU:
11829 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11830 				(struct ip6_mtuinfo *)ptr,
11831 				connp->conn_netstack));
11832 		default:
11833 			break;
11834 		}
11835 		break;
11836 	default:
11837 		break;
11838 	}
11839 	return (-1);
11840 }
11841 
11842 /* Named Dispatch routine to get a current value out of our parameter table. */
11843 /* ARGSUSED */
11844 static int
11845 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11846 {
11847 	ipparam_t *ippa = (ipparam_t *)cp;
11848 
11849 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11850 	return (0);
11851 }
11852 
11853 /* ARGSUSED */
11854 static int
11855 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11856 {
11857 
11858 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11859 	return (0);
11860 }
11861 
11862 /*
11863  * Set ip{,6}_forwarding values.  This means walking through all of the
11864  * ill's and toggling their forwarding values.
11865  */
11866 /* ARGSUSED */
11867 static int
11868 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11869 {
11870 	long new_value;
11871 	int *forwarding_value = (int *)cp;
11872 	ill_t *walker;
11873 	boolean_t isv6;
11874 	ill_walk_context_t ctx;
11875 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11876 
11877 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11878 
11879 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11880 	    new_value < 0 || new_value > 1) {
11881 		return (EINVAL);
11882 	}
11883 
11884 	*forwarding_value = new_value;
11885 
11886 	/*
11887 	 * Regardless of the current value of ip_forwarding, set all per-ill
11888 	 * values of ip_forwarding to the value being set.
11889 	 *
11890 	 * Bring all the ill's up to date with the new global value.
11891 	 */
11892 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11893 
11894 	if (isv6)
11895 		walker = ILL_START_WALK_V6(&ctx, ipst);
11896 	else
11897 		walker = ILL_START_WALK_V4(&ctx, ipst);
11898 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11899 		(void) ill_forward_set(q, mp, (new_value != 0),
11900 		    (caddr_t)walker);
11901 	}
11902 	rw_exit(&ipst->ips_ill_g_lock);
11903 
11904 	return (0);
11905 }
11906 
11907 /*
11908  * Walk through the param array specified registering each element with the
11909  * Named Dispatch handler. This is called only during init. So it is ok
11910  * not to acquire any locks
11911  */
11912 static boolean_t
11913 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11914     ipndp_t *ipnd, size_t ipnd_cnt)
11915 {
11916 	for (; ippa_cnt-- > 0; ippa++) {
11917 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11918 			if (!nd_load(ndp, ippa->ip_param_name,
11919 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11920 				nd_free(ndp);
11921 				return (B_FALSE);
11922 			}
11923 		}
11924 	}
11925 
11926 	for (; ipnd_cnt-- > 0; ipnd++) {
11927 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11928 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11929 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11930 			    ipnd->ip_ndp_data)) {
11931 				nd_free(ndp);
11932 				return (B_FALSE);
11933 			}
11934 		}
11935 	}
11936 
11937 	return (B_TRUE);
11938 }
11939 
11940 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11941 /* ARGSUSED */
11942 static int
11943 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11944 {
11945 	long		new_value;
11946 	ipparam_t	*ippa = (ipparam_t *)cp;
11947 
11948 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11949 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11950 		return (EINVAL);
11951 	}
11952 	ippa->ip_param_value = new_value;
11953 	return (0);
11954 }
11955 
11956 /*
11957  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11958  * When an ipf is passed here for the first time, if
11959  * we already have in-order fragments on the queue, we convert from the fast-
11960  * path reassembly scheme to the hard-case scheme.  From then on, additional
11961  * fragments are reassembled here.  We keep track of the start and end offsets
11962  * of each piece, and the number of holes in the chain.  When the hole count
11963  * goes to zero, we are done!
11964  *
11965  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11966  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11967  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11968  * after the call to ip_reassemble().
11969  */
11970 int
11971 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11972     size_t msg_len)
11973 {
11974 	uint_t	end;
11975 	mblk_t	*next_mp;
11976 	mblk_t	*mp1;
11977 	uint_t	offset;
11978 	boolean_t incr_dups = B_TRUE;
11979 	boolean_t offset_zero_seen = B_FALSE;
11980 	boolean_t pkt_boundary_checked = B_FALSE;
11981 
11982 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11983 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11984 
11985 	/* Add in byte count */
11986 	ipf->ipf_count += msg_len;
11987 	if (ipf->ipf_end) {
11988 		/*
11989 		 * We were part way through in-order reassembly, but now there
11990 		 * is a hole.  We walk through messages already queued, and
11991 		 * mark them for hard case reassembly.  We know that up till
11992 		 * now they were in order starting from offset zero.
11993 		 */
11994 		offset = 0;
11995 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11996 			IP_REASS_SET_START(mp1, offset);
11997 			if (offset == 0) {
11998 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11999 				offset = -ipf->ipf_nf_hdr_len;
12000 			}
12001 			offset += mp1->b_wptr - mp1->b_rptr;
12002 			IP_REASS_SET_END(mp1, offset);
12003 		}
12004 		/* One hole at the end. */
12005 		ipf->ipf_hole_cnt = 1;
12006 		/* Brand it as a hard case, forever. */
12007 		ipf->ipf_end = 0;
12008 	}
12009 	/* Walk through all the new pieces. */
12010 	do {
12011 		end = start + (mp->b_wptr - mp->b_rptr);
12012 		/*
12013 		 * If start is 0, decrease 'end' only for the first mblk of
12014 		 * the fragment. Otherwise 'end' can get wrong value in the
12015 		 * second pass of the loop if first mblk is exactly the
12016 		 * size of ipf_nf_hdr_len.
12017 		 */
12018 		if (start == 0 && !offset_zero_seen) {
12019 			/* First segment */
12020 			ASSERT(ipf->ipf_nf_hdr_len != 0);
12021 			end -= ipf->ipf_nf_hdr_len;
12022 			offset_zero_seen = B_TRUE;
12023 		}
12024 		next_mp = mp->b_cont;
12025 		/*
12026 		 * We are checking to see if there is any interesing data
12027 		 * to process.  If there isn't and the mblk isn't the
12028 		 * one which carries the unfragmentable header then we
12029 		 * drop it.  It's possible to have just the unfragmentable
12030 		 * header come through without any data.  That needs to be
12031 		 * saved.
12032 		 *
12033 		 * If the assert at the top of this function holds then the
12034 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
12035 		 * is infrequently traveled enough that the test is left in
12036 		 * to protect against future code changes which break that
12037 		 * invariant.
12038 		 */
12039 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
12040 			/* Empty.  Blast it. */
12041 			IP_REASS_SET_START(mp, 0);
12042 			IP_REASS_SET_END(mp, 0);
12043 			/*
12044 			 * If the ipf points to the mblk we are about to free,
12045 			 * update ipf to point to the next mblk (or NULL
12046 			 * if none).
12047 			 */
12048 			if (ipf->ipf_mp->b_cont == mp)
12049 				ipf->ipf_mp->b_cont = next_mp;
12050 			freeb(mp);
12051 			continue;
12052 		}
12053 		mp->b_cont = NULL;
12054 		IP_REASS_SET_START(mp, start);
12055 		IP_REASS_SET_END(mp, end);
12056 		if (!ipf->ipf_tail_mp) {
12057 			ipf->ipf_tail_mp = mp;
12058 			ipf->ipf_mp->b_cont = mp;
12059 			if (start == 0 || !more) {
12060 				ipf->ipf_hole_cnt = 1;
12061 				/*
12062 				 * if the first fragment comes in more than one
12063 				 * mblk, this loop will be executed for each
12064 				 * mblk. Need to adjust hole count so exiting
12065 				 * this routine will leave hole count at 1.
12066 				 */
12067 				if (next_mp)
12068 					ipf->ipf_hole_cnt++;
12069 			} else
12070 				ipf->ipf_hole_cnt = 2;
12071 			continue;
12072 		} else if (ipf->ipf_last_frag_seen && !more &&
12073 			    !pkt_boundary_checked) {
12074 			/*
12075 			 * We check datagram boundary only if this fragment
12076 			 * claims to be the last fragment and we have seen a
12077 			 * last fragment in the past too. We do this only
12078 			 * once for a given fragment.
12079 			 *
12080 			 * start cannot be 0 here as fragments with start=0
12081 			 * and MF=0 gets handled as a complete packet. These
12082 			 * fragments should not reach here.
12083 			 */
12084 
12085 			if (start + msgdsize(mp) !=
12086 			    IP_REASS_END(ipf->ipf_tail_mp)) {
12087 				/*
12088 				 * We have two fragments both of which claim
12089 				 * to be the last fragment but gives conflicting
12090 				 * information about the whole datagram size.
12091 				 * Something fishy is going on. Drop the
12092 				 * fragment and free up the reassembly list.
12093 				 */
12094 				return (IP_REASS_FAILED);
12095 			}
12096 
12097 			/*
12098 			 * We shouldn't come to this code block again for this
12099 			 * particular fragment.
12100 			 */
12101 			pkt_boundary_checked = B_TRUE;
12102 		}
12103 
12104 		/* New stuff at or beyond tail? */
12105 		offset = IP_REASS_END(ipf->ipf_tail_mp);
12106 		if (start >= offset) {
12107 			if (ipf->ipf_last_frag_seen) {
12108 				/* current fragment is beyond last fragment */
12109 				return (IP_REASS_FAILED);
12110 			}
12111 			/* Link it on end. */
12112 			ipf->ipf_tail_mp->b_cont = mp;
12113 			ipf->ipf_tail_mp = mp;
12114 			if (more) {
12115 				if (start != offset)
12116 					ipf->ipf_hole_cnt++;
12117 			} else if (start == offset && next_mp == NULL)
12118 					ipf->ipf_hole_cnt--;
12119 			continue;
12120 		}
12121 		mp1 = ipf->ipf_mp->b_cont;
12122 		offset = IP_REASS_START(mp1);
12123 		/* New stuff at the front? */
12124 		if (start < offset) {
12125 			if (start == 0) {
12126 				if (end >= offset) {
12127 					/* Nailed the hole at the begining. */
12128 					ipf->ipf_hole_cnt--;
12129 				}
12130 			} else if (end < offset) {
12131 				/*
12132 				 * A hole, stuff, and a hole where there used
12133 				 * to be just a hole.
12134 				 */
12135 				ipf->ipf_hole_cnt++;
12136 			}
12137 			mp->b_cont = mp1;
12138 			/* Check for overlap. */
12139 			while (end > offset) {
12140 				if (end < IP_REASS_END(mp1)) {
12141 					mp->b_wptr -= end - offset;
12142 					IP_REASS_SET_END(mp, offset);
12143 					BUMP_MIB(ill->ill_ip_mib,
12144 					    ipIfStatsReasmPartDups);
12145 					break;
12146 				}
12147 				/* Did we cover another hole? */
12148 				if ((mp1->b_cont &&
12149 				    IP_REASS_END(mp1) !=
12150 				    IP_REASS_START(mp1->b_cont) &&
12151 				    end >= IP_REASS_START(mp1->b_cont)) ||
12152 				    (!ipf->ipf_last_frag_seen && !more)) {
12153 					ipf->ipf_hole_cnt--;
12154 				}
12155 				/* Clip out mp1. */
12156 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12157 					/*
12158 					 * After clipping out mp1, this guy
12159 					 * is now hanging off the end.
12160 					 */
12161 					ipf->ipf_tail_mp = mp;
12162 				}
12163 				IP_REASS_SET_START(mp1, 0);
12164 				IP_REASS_SET_END(mp1, 0);
12165 				/* Subtract byte count */
12166 				ipf->ipf_count -= mp1->b_datap->db_lim -
12167 				    mp1->b_datap->db_base;
12168 				freeb(mp1);
12169 				BUMP_MIB(ill->ill_ip_mib,
12170 				    ipIfStatsReasmPartDups);
12171 				mp1 = mp->b_cont;
12172 				if (!mp1)
12173 					break;
12174 				offset = IP_REASS_START(mp1);
12175 			}
12176 			ipf->ipf_mp->b_cont = mp;
12177 			continue;
12178 		}
12179 		/*
12180 		 * The new piece starts somewhere between the start of the head
12181 		 * and before the end of the tail.
12182 		 */
12183 		for (; mp1; mp1 = mp1->b_cont) {
12184 			offset = IP_REASS_END(mp1);
12185 			if (start < offset) {
12186 				if (end <= offset) {
12187 					/* Nothing new. */
12188 					IP_REASS_SET_START(mp, 0);
12189 					IP_REASS_SET_END(mp, 0);
12190 					/* Subtract byte count */
12191 					ipf->ipf_count -= mp->b_datap->db_lim -
12192 					    mp->b_datap->db_base;
12193 					if (incr_dups) {
12194 						ipf->ipf_num_dups++;
12195 						incr_dups = B_FALSE;
12196 					}
12197 					freeb(mp);
12198 					BUMP_MIB(ill->ill_ip_mib,
12199 					    ipIfStatsReasmDuplicates);
12200 					break;
12201 				}
12202 				/*
12203 				 * Trim redundant stuff off beginning of new
12204 				 * piece.
12205 				 */
12206 				IP_REASS_SET_START(mp, offset);
12207 				mp->b_rptr += offset - start;
12208 				BUMP_MIB(ill->ill_ip_mib,
12209 				    ipIfStatsReasmPartDups);
12210 				start = offset;
12211 				if (!mp1->b_cont) {
12212 					/*
12213 					 * After trimming, this guy is now
12214 					 * hanging off the end.
12215 					 */
12216 					mp1->b_cont = mp;
12217 					ipf->ipf_tail_mp = mp;
12218 					if (!more) {
12219 						ipf->ipf_hole_cnt--;
12220 					}
12221 					break;
12222 				}
12223 			}
12224 			if (start >= IP_REASS_START(mp1->b_cont))
12225 				continue;
12226 			/* Fill a hole */
12227 			if (start > offset)
12228 				ipf->ipf_hole_cnt++;
12229 			mp->b_cont = mp1->b_cont;
12230 			mp1->b_cont = mp;
12231 			mp1 = mp->b_cont;
12232 			offset = IP_REASS_START(mp1);
12233 			if (end >= offset) {
12234 				ipf->ipf_hole_cnt--;
12235 				/* Check for overlap. */
12236 				while (end > offset) {
12237 					if (end < IP_REASS_END(mp1)) {
12238 						mp->b_wptr -= end - offset;
12239 						IP_REASS_SET_END(mp, offset);
12240 						/*
12241 						 * TODO we might bump
12242 						 * this up twice if there is
12243 						 * overlap at both ends.
12244 						 */
12245 						BUMP_MIB(ill->ill_ip_mib,
12246 						    ipIfStatsReasmPartDups);
12247 						break;
12248 					}
12249 					/* Did we cover another hole? */
12250 					if ((mp1->b_cont &&
12251 					    IP_REASS_END(mp1)
12252 					    != IP_REASS_START(mp1->b_cont) &&
12253 					    end >=
12254 					    IP_REASS_START(mp1->b_cont)) ||
12255 					    (!ipf->ipf_last_frag_seen &&
12256 					    !more)) {
12257 						ipf->ipf_hole_cnt--;
12258 					}
12259 					/* Clip out mp1. */
12260 					if ((mp->b_cont = mp1->b_cont) ==
12261 					    NULL) {
12262 						/*
12263 						 * After clipping out mp1,
12264 						 * this guy is now hanging
12265 						 * off the end.
12266 						 */
12267 						ipf->ipf_tail_mp = mp;
12268 					}
12269 					IP_REASS_SET_START(mp1, 0);
12270 					IP_REASS_SET_END(mp1, 0);
12271 					/* Subtract byte count */
12272 					ipf->ipf_count -=
12273 					    mp1->b_datap->db_lim -
12274 					    mp1->b_datap->db_base;
12275 					freeb(mp1);
12276 					BUMP_MIB(ill->ill_ip_mib,
12277 					    ipIfStatsReasmPartDups);
12278 					mp1 = mp->b_cont;
12279 					if (!mp1)
12280 						break;
12281 					offset = IP_REASS_START(mp1);
12282 				}
12283 			}
12284 			break;
12285 		}
12286 	} while (start = end, mp = next_mp);
12287 
12288 	/* Fragment just processed could be the last one. Remember this fact */
12289 	if (!more)
12290 		ipf->ipf_last_frag_seen = B_TRUE;
12291 
12292 	/* Still got holes? */
12293 	if (ipf->ipf_hole_cnt)
12294 		return (IP_REASS_PARTIAL);
12295 	/* Clean up overloaded fields to avoid upstream disasters. */
12296 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12297 		IP_REASS_SET_START(mp1, 0);
12298 		IP_REASS_SET_END(mp1, 0);
12299 	}
12300 	return (IP_REASS_COMPLETE);
12301 }
12302 
12303 /*
12304  * ipsec processing for the fast path, used for input UDP Packets
12305  */
12306 static boolean_t
12307 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12308     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12309 {
12310 	uint32_t	ill_index;
12311 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12312 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12313 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12314 
12315 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12316 	/* The ill_index of the incoming ILL */
12317 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12318 
12319 	/* pass packet up to the transport */
12320 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12321 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12322 		    NULL, mctl_present);
12323 		if (*first_mpp == NULL) {
12324 			return (B_FALSE);
12325 		}
12326 	}
12327 
12328 	/* Initiate IPPF processing for fastpath UDP */
12329 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12330 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12331 		if (*mpp == NULL) {
12332 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12333 			    "deferred/dropped during IPPF processing\n"));
12334 			return (B_FALSE);
12335 		}
12336 	}
12337 	/*
12338 	 * We make the checks as below since we are in the fast path
12339 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12340 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12341 	 */
12342 	if (connp->conn_recvif || connp->conn_recvslla ||
12343 	    connp->conn_ip_recvpktinfo) {
12344 		if (connp->conn_recvif) {
12345 			in_flags = IPF_RECVIF;
12346 		}
12347 		/*
12348 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12349 		 * so the flag passed to ip_add_info is based on IP version
12350 		 * of connp.
12351 		 */
12352 		if (connp->conn_ip_recvpktinfo) {
12353 			if (connp->conn_af_isv6) {
12354 				/*
12355 				 * V6 only needs index
12356 				 */
12357 				in_flags |= IPF_RECVIF;
12358 			} else {
12359 				/*
12360 				 * V4 needs index + matching address.
12361 				 */
12362 				in_flags |= IPF_RECVADDR;
12363 			}
12364 		}
12365 		if (connp->conn_recvslla) {
12366 			in_flags |= IPF_RECVSLLA;
12367 		}
12368 		/*
12369 		 * since in_flags are being set ill will be
12370 		 * referenced in ip_add_info, so it better not
12371 		 * be NULL.
12372 		 */
12373 		/*
12374 		 * the actual data will be contained in b_cont
12375 		 * upon successful return of the following call.
12376 		 * If the call fails then the original mblk is
12377 		 * returned.
12378 		 */
12379 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12380 		    ipst);
12381 	}
12382 
12383 	return (B_TRUE);
12384 }
12385 
12386 /*
12387  * Fragmentation reassembly.  Each ILL has a hash table for
12388  * queuing packets undergoing reassembly for all IPIFs
12389  * associated with the ILL.  The hash is based on the packet
12390  * IP ident field.  The ILL frag hash table was allocated
12391  * as a timer block at the time the ILL was created.  Whenever
12392  * there is anything on the reassembly queue, the timer will
12393  * be running.  Returns B_TRUE if successful else B_FALSE;
12394  * frees mp on failure.
12395  */
12396 static boolean_t
12397 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12398     uint32_t *cksum_val, uint16_t *cksum_flags)
12399 {
12400 	uint32_t	frag_offset_flags;
12401 	ill_t		*ill = (ill_t *)q->q_ptr;
12402 	mblk_t		*mp = *mpp;
12403 	mblk_t		*t_mp;
12404 	ipaddr_t	dst;
12405 	uint8_t		proto = ipha->ipha_protocol;
12406 	uint32_t	sum_val;
12407 	uint16_t	sum_flags;
12408 	ipf_t		*ipf;
12409 	ipf_t		**ipfp;
12410 	ipfb_t		*ipfb;
12411 	uint16_t	ident;
12412 	uint32_t	offset;
12413 	ipaddr_t	src;
12414 	uint_t		hdr_length;
12415 	uint32_t	end;
12416 	mblk_t		*mp1;
12417 	mblk_t		*tail_mp;
12418 	size_t		count;
12419 	size_t		msg_len;
12420 	uint8_t		ecn_info = 0;
12421 	uint32_t	packet_size;
12422 	boolean_t	pruned = B_FALSE;
12423 	ip_stack_t *ipst = ill->ill_ipst;
12424 
12425 	if (cksum_val != NULL)
12426 		*cksum_val = 0;
12427 	if (cksum_flags != NULL)
12428 		*cksum_flags = 0;
12429 
12430 	/*
12431 	 * Drop the fragmented as early as possible, if
12432 	 * we don't have resource(s) to re-assemble.
12433 	 */
12434 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12435 		freemsg(mp);
12436 		return (B_FALSE);
12437 	}
12438 
12439 	/* Check for fragmentation offset; return if there's none */
12440 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12441 	    (IPH_MF | IPH_OFFSET)) == 0)
12442 		return (B_TRUE);
12443 
12444 	/*
12445 	 * We utilize hardware computed checksum info only for UDP since
12446 	 * IP fragmentation is a normal occurence for the protocol.  In
12447 	 * addition, checksum offload support for IP fragments carrying
12448 	 * UDP payload is commonly implemented across network adapters.
12449 	 */
12450 	ASSERT(ill != NULL);
12451 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12452 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12453 		mblk_t *mp1 = mp->b_cont;
12454 		int32_t len;
12455 
12456 		/* Record checksum information from the packet */
12457 		sum_val = (uint32_t)DB_CKSUM16(mp);
12458 		sum_flags = DB_CKSUMFLAGS(mp);
12459 
12460 		/* IP payload offset from beginning of mblk */
12461 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12462 
12463 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12464 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12465 		    offset >= DB_CKSUMSTART(mp) &&
12466 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12467 			uint32_t adj;
12468 			/*
12469 			 * Partial checksum has been calculated by hardware
12470 			 * and attached to the packet; in addition, any
12471 			 * prepended extraneous data is even byte aligned.
12472 			 * If any such data exists, we adjust the checksum;
12473 			 * this would also handle any postpended data.
12474 			 */
12475 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12476 			    mp, mp1, len, adj);
12477 
12478 			/* One's complement subtract extraneous checksum */
12479 			if (adj >= sum_val)
12480 				sum_val = ~(adj - sum_val) & 0xFFFF;
12481 			else
12482 				sum_val -= adj;
12483 		}
12484 	} else {
12485 		sum_val = 0;
12486 		sum_flags = 0;
12487 	}
12488 
12489 	/* Clear hardware checksumming flag */
12490 	DB_CKSUMFLAGS(mp) = 0;
12491 
12492 	ident = ipha->ipha_ident;
12493 	offset = (frag_offset_flags << 3) & 0xFFFF;
12494 	src = ipha->ipha_src;
12495 	dst = ipha->ipha_dst;
12496 	hdr_length = IPH_HDR_LENGTH(ipha);
12497 	end = ntohs(ipha->ipha_length) - hdr_length;
12498 
12499 	/* If end == 0 then we have a packet with no data, so just free it */
12500 	if (end == 0) {
12501 		freemsg(mp);
12502 		return (B_FALSE);
12503 	}
12504 
12505 	/* Record the ECN field info. */
12506 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12507 	if (offset != 0) {
12508 		/*
12509 		 * If this isn't the first piece, strip the header, and
12510 		 * add the offset to the end value.
12511 		 */
12512 		mp->b_rptr += hdr_length;
12513 		end += offset;
12514 	}
12515 
12516 	msg_len = MBLKSIZE(mp);
12517 	tail_mp = mp;
12518 	while (tail_mp->b_cont != NULL) {
12519 		tail_mp = tail_mp->b_cont;
12520 		msg_len += MBLKSIZE(tail_mp);
12521 	}
12522 
12523 	/* If the reassembly list for this ILL will get too big, prune it */
12524 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12525 	    ipst->ips_ip_reass_queue_bytes) {
12526 		ill_frag_prune(ill,
12527 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12528 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12529 		pruned = B_TRUE;
12530 	}
12531 
12532 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12533 	mutex_enter(&ipfb->ipfb_lock);
12534 
12535 	ipfp = &ipfb->ipfb_ipf;
12536 	/* Try to find an existing fragment queue for this packet. */
12537 	for (;;) {
12538 		ipf = ipfp[0];
12539 		if (ipf != NULL) {
12540 			/*
12541 			 * It has to match on ident and src/dst address.
12542 			 */
12543 			if (ipf->ipf_ident == ident &&
12544 			    ipf->ipf_src == src &&
12545 			    ipf->ipf_dst == dst &&
12546 			    ipf->ipf_protocol == proto) {
12547 				/*
12548 				 * If we have received too many
12549 				 * duplicate fragments for this packet
12550 				 * free it.
12551 				 */
12552 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12553 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12554 					freemsg(mp);
12555 					mutex_exit(&ipfb->ipfb_lock);
12556 					return (B_FALSE);
12557 				}
12558 				/* Found it. */
12559 				break;
12560 			}
12561 			ipfp = &ipf->ipf_hash_next;
12562 			continue;
12563 		}
12564 
12565 		/*
12566 		 * If we pruned the list, do we want to store this new
12567 		 * fragment?. We apply an optimization here based on the
12568 		 * fact that most fragments will be received in order.
12569 		 * So if the offset of this incoming fragment is zero,
12570 		 * it is the first fragment of a new packet. We will
12571 		 * keep it.  Otherwise drop the fragment, as we have
12572 		 * probably pruned the packet already (since the
12573 		 * packet cannot be found).
12574 		 */
12575 		if (pruned && offset != 0) {
12576 			mutex_exit(&ipfb->ipfb_lock);
12577 			freemsg(mp);
12578 			return (B_FALSE);
12579 		}
12580 
12581 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12582 			/*
12583 			 * Too many fragmented packets in this hash
12584 			 * bucket. Free the oldest.
12585 			 */
12586 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12587 		}
12588 
12589 		/* New guy.  Allocate a frag message. */
12590 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12591 		if (mp1 == NULL) {
12592 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12593 			freemsg(mp);
12594 reass_done:
12595 			mutex_exit(&ipfb->ipfb_lock);
12596 			return (B_FALSE);
12597 		}
12598 
12599 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12600 		mp1->b_cont = mp;
12601 
12602 		/* Initialize the fragment header. */
12603 		ipf = (ipf_t *)mp1->b_rptr;
12604 		ipf->ipf_mp = mp1;
12605 		ipf->ipf_ptphn = ipfp;
12606 		ipfp[0] = ipf;
12607 		ipf->ipf_hash_next = NULL;
12608 		ipf->ipf_ident = ident;
12609 		ipf->ipf_protocol = proto;
12610 		ipf->ipf_src = src;
12611 		ipf->ipf_dst = dst;
12612 		ipf->ipf_nf_hdr_len = 0;
12613 		/* Record reassembly start time. */
12614 		ipf->ipf_timestamp = gethrestime_sec();
12615 		/* Record ipf generation and account for frag header */
12616 		ipf->ipf_gen = ill->ill_ipf_gen++;
12617 		ipf->ipf_count = MBLKSIZE(mp1);
12618 		ipf->ipf_last_frag_seen = B_FALSE;
12619 		ipf->ipf_ecn = ecn_info;
12620 		ipf->ipf_num_dups = 0;
12621 		ipfb->ipfb_frag_pkts++;
12622 		ipf->ipf_checksum = 0;
12623 		ipf->ipf_checksum_flags = 0;
12624 
12625 		/* Store checksum value in fragment header */
12626 		if (sum_flags != 0) {
12627 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12628 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12629 			ipf->ipf_checksum = sum_val;
12630 			ipf->ipf_checksum_flags = sum_flags;
12631 		}
12632 
12633 		/*
12634 		 * We handle reassembly two ways.  In the easy case,
12635 		 * where all the fragments show up in order, we do
12636 		 * minimal bookkeeping, and just clip new pieces on
12637 		 * the end.  If we ever see a hole, then we go off
12638 		 * to ip_reassemble which has to mark the pieces and
12639 		 * keep track of the number of holes, etc.  Obviously,
12640 		 * the point of having both mechanisms is so we can
12641 		 * handle the easy case as efficiently as possible.
12642 		 */
12643 		if (offset == 0) {
12644 			/* Easy case, in-order reassembly so far. */
12645 			ipf->ipf_count += msg_len;
12646 			ipf->ipf_tail_mp = tail_mp;
12647 			/*
12648 			 * Keep track of next expected offset in
12649 			 * ipf_end.
12650 			 */
12651 			ipf->ipf_end = end;
12652 			ipf->ipf_nf_hdr_len = hdr_length;
12653 		} else {
12654 			/* Hard case, hole at the beginning. */
12655 			ipf->ipf_tail_mp = NULL;
12656 			/*
12657 			 * ipf_end == 0 means that we have given up
12658 			 * on easy reassembly.
12659 			 */
12660 			ipf->ipf_end = 0;
12661 
12662 			/* Forget checksum offload from now on */
12663 			ipf->ipf_checksum_flags = 0;
12664 
12665 			/*
12666 			 * ipf_hole_cnt is set by ip_reassemble.
12667 			 * ipf_count is updated by ip_reassemble.
12668 			 * No need to check for return value here
12669 			 * as we don't expect reassembly to complete
12670 			 * or fail for the first fragment itself.
12671 			 */
12672 			(void) ip_reassemble(mp, ipf,
12673 			    (frag_offset_flags & IPH_OFFSET) << 3,
12674 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12675 		}
12676 		/* Update per ipfb and ill byte counts */
12677 		ipfb->ipfb_count += ipf->ipf_count;
12678 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12679 		ill->ill_frag_count += ipf->ipf_count;
12680 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12681 		/* If the frag timer wasn't already going, start it. */
12682 		mutex_enter(&ill->ill_lock);
12683 		ill_frag_timer_start(ill);
12684 		mutex_exit(&ill->ill_lock);
12685 		goto reass_done;
12686 	}
12687 
12688 	/*
12689 	 * If the packet's flag has changed (it could be coming up
12690 	 * from an interface different than the previous, therefore
12691 	 * possibly different checksum capability), then forget about
12692 	 * any stored checksum states.  Otherwise add the value to
12693 	 * the existing one stored in the fragment header.
12694 	 */
12695 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12696 		sum_val += ipf->ipf_checksum;
12697 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12698 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12699 		ipf->ipf_checksum = sum_val;
12700 	} else if (ipf->ipf_checksum_flags != 0) {
12701 		/* Forget checksum offload from now on */
12702 		ipf->ipf_checksum_flags = 0;
12703 	}
12704 
12705 	/*
12706 	 * We have a new piece of a datagram which is already being
12707 	 * reassembled.  Update the ECN info if all IP fragments
12708 	 * are ECN capable.  If there is one which is not, clear
12709 	 * all the info.  If there is at least one which has CE
12710 	 * code point, IP needs to report that up to transport.
12711 	 */
12712 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12713 		if (ecn_info == IPH_ECN_CE)
12714 			ipf->ipf_ecn = IPH_ECN_CE;
12715 	} else {
12716 		ipf->ipf_ecn = IPH_ECN_NECT;
12717 	}
12718 	if (offset && ipf->ipf_end == offset) {
12719 		/* The new fragment fits at the end */
12720 		ipf->ipf_tail_mp->b_cont = mp;
12721 		/* Update the byte count */
12722 		ipf->ipf_count += msg_len;
12723 		/* Update per ipfb and ill byte counts */
12724 		ipfb->ipfb_count += msg_len;
12725 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12726 		ill->ill_frag_count += msg_len;
12727 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12728 		if (frag_offset_flags & IPH_MF) {
12729 			/* More to come. */
12730 			ipf->ipf_end = end;
12731 			ipf->ipf_tail_mp = tail_mp;
12732 			goto reass_done;
12733 		}
12734 	} else {
12735 		/* Go do the hard cases. */
12736 		int ret;
12737 
12738 		if (offset == 0)
12739 			ipf->ipf_nf_hdr_len = hdr_length;
12740 
12741 		/* Save current byte count */
12742 		count = ipf->ipf_count;
12743 		ret = ip_reassemble(mp, ipf,
12744 		    (frag_offset_flags & IPH_OFFSET) << 3,
12745 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12746 		/* Count of bytes added and subtracted (freeb()ed) */
12747 		count = ipf->ipf_count - count;
12748 		if (count) {
12749 			/* Update per ipfb and ill byte counts */
12750 			ipfb->ipfb_count += count;
12751 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12752 			ill->ill_frag_count += count;
12753 			ASSERT(ill->ill_frag_count > 0);
12754 		}
12755 		if (ret == IP_REASS_PARTIAL) {
12756 			goto reass_done;
12757 		} else if (ret == IP_REASS_FAILED) {
12758 			/* Reassembly failed. Free up all resources */
12759 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12760 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12761 				IP_REASS_SET_START(t_mp, 0);
12762 				IP_REASS_SET_END(t_mp, 0);
12763 			}
12764 			freemsg(mp);
12765 			goto reass_done;
12766 		}
12767 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12768 	}
12769 	/*
12770 	 * We have completed reassembly.  Unhook the frag header from
12771 	 * the reassembly list.
12772 	 *
12773 	 * Before we free the frag header, record the ECN info
12774 	 * to report back to the transport.
12775 	 */
12776 	ecn_info = ipf->ipf_ecn;
12777 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12778 	ipfp = ipf->ipf_ptphn;
12779 
12780 	/* We need to supply these to caller */
12781 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12782 		sum_val = ipf->ipf_checksum;
12783 	else
12784 		sum_val = 0;
12785 
12786 	mp1 = ipf->ipf_mp;
12787 	count = ipf->ipf_count;
12788 	ipf = ipf->ipf_hash_next;
12789 	if (ipf != NULL)
12790 		ipf->ipf_ptphn = ipfp;
12791 	ipfp[0] = ipf;
12792 	ill->ill_frag_count -= count;
12793 	ASSERT(ipfb->ipfb_count >= count);
12794 	ipfb->ipfb_count -= count;
12795 	ipfb->ipfb_frag_pkts--;
12796 	mutex_exit(&ipfb->ipfb_lock);
12797 	/* Ditch the frag header. */
12798 	mp = mp1->b_cont;
12799 
12800 	freeb(mp1);
12801 
12802 	/* Restore original IP length in header. */
12803 	packet_size = (uint32_t)msgdsize(mp);
12804 	if (packet_size > IP_MAXPACKET) {
12805 		freemsg(mp);
12806 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12807 		return (B_FALSE);
12808 	}
12809 
12810 	if (DB_REF(mp) > 1) {
12811 		mblk_t *mp2 = copymsg(mp);
12812 
12813 		freemsg(mp);
12814 		if (mp2 == NULL) {
12815 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12816 			return (B_FALSE);
12817 		}
12818 		mp = mp2;
12819 	}
12820 	ipha = (ipha_t *)mp->b_rptr;
12821 
12822 	ipha->ipha_length = htons((uint16_t)packet_size);
12823 	/* We're now complete, zip the frag state */
12824 	ipha->ipha_fragment_offset_and_flags = 0;
12825 	/* Record the ECN info. */
12826 	ipha->ipha_type_of_service &= 0xFC;
12827 	ipha->ipha_type_of_service |= ecn_info;
12828 	*mpp = mp;
12829 
12830 	/* Reassembly is successful; return checksum information if needed */
12831 	if (cksum_val != NULL)
12832 		*cksum_val = sum_val;
12833 	if (cksum_flags != NULL)
12834 		*cksum_flags = sum_flags;
12835 
12836 	return (B_TRUE);
12837 }
12838 
12839 /*
12840  * Perform ip header check sum update local options.
12841  * return B_TRUE if all is well, else return B_FALSE and release
12842  * the mp. caller is responsible for decrementing ire ref cnt.
12843  */
12844 static boolean_t
12845 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12846     ip_stack_t *ipst)
12847 {
12848 	mblk_t		*first_mp;
12849 	boolean_t	mctl_present;
12850 	uint16_t	sum;
12851 
12852 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12853 	/*
12854 	 * Don't do the checksum if it has gone through AH/ESP
12855 	 * processing.
12856 	 */
12857 	if (!mctl_present) {
12858 		sum = ip_csum_hdr(ipha);
12859 		if (sum != 0) {
12860 			if (ill != NULL) {
12861 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12862 			} else {
12863 				BUMP_MIB(&ipst->ips_ip_mib,
12864 				    ipIfStatsInCksumErrs);
12865 			}
12866 			freemsg(first_mp);
12867 			return (B_FALSE);
12868 		}
12869 	}
12870 
12871 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12872 		if (mctl_present)
12873 			freeb(first_mp);
12874 		return (B_FALSE);
12875 	}
12876 
12877 	return (B_TRUE);
12878 }
12879 
12880 /*
12881  * All udp packet are delivered to the local host via this routine.
12882  */
12883 void
12884 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12885     ill_t *recv_ill)
12886 {
12887 	uint32_t	sum;
12888 	uint32_t	u1;
12889 	boolean_t	mctl_present;
12890 	conn_t		*connp;
12891 	mblk_t		*first_mp;
12892 	uint16_t	*up;
12893 	ill_t		*ill = (ill_t *)q->q_ptr;
12894 	uint16_t	reass_hck_flags = 0;
12895 	ip_stack_t	*ipst;
12896 
12897 	ASSERT(recv_ill != NULL);
12898 	ipst = recv_ill->ill_ipst;
12899 
12900 #define	rptr    ((uchar_t *)ipha)
12901 
12902 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12903 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12904 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12905 	ASSERT(ill != NULL);
12906 
12907 	/*
12908 	 * FAST PATH for udp packets
12909 	 */
12910 
12911 	/* u1 is # words of IP options */
12912 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12913 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12914 
12915 	/* IP options present */
12916 	if (u1 != 0)
12917 		goto ipoptions;
12918 
12919 	/* Check the IP header checksum.  */
12920 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12921 		/* Clear the IP header h/w cksum flag */
12922 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12923 	} else {
12924 #define	uph	((uint16_t *)ipha)
12925 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12926 		    uph[6] + uph[7] + uph[8] + uph[9];
12927 #undef	uph
12928 		/* finish doing IP checksum */
12929 		sum = (sum & 0xFFFF) + (sum >> 16);
12930 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12931 		/*
12932 		 * Don't verify header checksum if this packet is coming
12933 		 * back from AH/ESP as we already did it.
12934 		 */
12935 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12936 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12937 			freemsg(first_mp);
12938 			return;
12939 		}
12940 	}
12941 
12942 	/*
12943 	 * Count for SNMP of inbound packets for ire.
12944 	 * if mctl is present this might be a secure packet and
12945 	 * has already been counted for in ip_proto_input().
12946 	 */
12947 	if (!mctl_present) {
12948 		UPDATE_IB_PKT_COUNT(ire);
12949 		ire->ire_last_used_time = lbolt;
12950 	}
12951 
12952 	/* packet part of fragmented IP packet? */
12953 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12954 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12955 		goto fragmented;
12956 	}
12957 
12958 	/* u1 = IP header length (20 bytes) */
12959 	u1 = IP_SIMPLE_HDR_LENGTH;
12960 
12961 	/* packet does not contain complete IP & UDP headers */
12962 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12963 		goto udppullup;
12964 
12965 	/* up points to UDP header */
12966 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12967 #define	iphs    ((uint16_t *)ipha)
12968 
12969 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12970 	if (up[3] != 0) {
12971 		mblk_t *mp1 = mp->b_cont;
12972 		boolean_t cksum_err;
12973 		uint16_t hck_flags = 0;
12974 
12975 		/* Pseudo-header checksum */
12976 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12977 		    iphs[9] + up[2];
12978 
12979 		/*
12980 		 * Revert to software checksum calculation if the interface
12981 		 * isn't capable of checksum offload or if IPsec is present.
12982 		 */
12983 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12984 			hck_flags = DB_CKSUMFLAGS(mp);
12985 
12986 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12987 			IP_STAT(ipst, ip_in_sw_cksum);
12988 
12989 		IP_CKSUM_RECV(hck_flags, u1,
12990 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12991 		    (int32_t)((uchar_t *)up - rptr),
12992 		    mp, mp1, cksum_err);
12993 
12994 		if (cksum_err) {
12995 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12996 			if (hck_flags & HCK_FULLCKSUM)
12997 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12998 			else if (hck_flags & HCK_PARTIALCKSUM)
12999 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13000 			else
13001 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13002 
13003 			freemsg(first_mp);
13004 			return;
13005 		}
13006 	}
13007 
13008 	/* Non-fragmented broadcast or multicast packet? */
13009 	if (ire->ire_type == IRE_BROADCAST)
13010 		goto udpslowpath;
13011 
13012 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
13013 	    ire->ire_zoneid, ipst)) != NULL) {
13014 		ASSERT(connp->conn_upq != NULL);
13015 		IP_STAT(ipst, ip_udp_fast_path);
13016 
13017 		if (CONN_UDP_FLOWCTLD(connp)) {
13018 			freemsg(mp);
13019 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
13020 		} else {
13021 			if (!mctl_present) {
13022 				BUMP_MIB(ill->ill_ip_mib,
13023 				    ipIfStatsHCInDelivers);
13024 			}
13025 			/*
13026 			 * mp and first_mp can change.
13027 			 */
13028 			if (ip_udp_check(q, connp, recv_ill,
13029 			    ipha, &mp, &first_mp, mctl_present)) {
13030 				/* Send it upstream */
13031 				CONN_UDP_RECV(connp, mp);
13032 			}
13033 		}
13034 		/*
13035 		 * freeb() cannot deal with null mblk being passed
13036 		 * in and first_mp can be set to null in the call
13037 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
13038 		 */
13039 		if (mctl_present && first_mp != NULL) {
13040 			freeb(first_mp);
13041 		}
13042 		CONN_DEC_REF(connp);
13043 		return;
13044 	}
13045 
13046 	/*
13047 	 * if we got here we know the packet is not fragmented and
13048 	 * has no options. The classifier could not find a conn_t and
13049 	 * most likely its an icmp packet so send it through slow path.
13050 	 */
13051 
13052 	goto udpslowpath;
13053 
13054 ipoptions:
13055 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
13056 		goto slow_done;
13057 	}
13058 
13059 	UPDATE_IB_PKT_COUNT(ire);
13060 	ire->ire_last_used_time = lbolt;
13061 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13062 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13063 fragmented:
13064 		/*
13065 		 * "sum" and "reass_hck_flags" are non-zero if the
13066 		 * reassembled packet has a valid hardware computed
13067 		 * checksum information associated with it.
13068 		 */
13069 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
13070 			goto slow_done;
13071 		/*
13072 		 * Make sure that first_mp points back to mp as
13073 		 * the mp we came in with could have changed in
13074 		 * ip_rput_fragment().
13075 		 */
13076 		ASSERT(!mctl_present);
13077 		ipha = (ipha_t *)mp->b_rptr;
13078 		first_mp = mp;
13079 	}
13080 
13081 	/* Now we have a complete datagram, destined for this machine. */
13082 	u1 = IPH_HDR_LENGTH(ipha);
13083 	/* Pull up the UDP header, if necessary. */
13084 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
13085 udppullup:
13086 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
13087 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13088 			freemsg(first_mp);
13089 			goto slow_done;
13090 		}
13091 		ipha = (ipha_t *)mp->b_rptr;
13092 	}
13093 
13094 	/*
13095 	 * Validate the checksum for the reassembled packet; for the
13096 	 * pullup case we calculate the payload checksum in software.
13097 	 */
13098 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
13099 	if (up[3] != 0) {
13100 		boolean_t cksum_err;
13101 
13102 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13103 			IP_STAT(ipst, ip_in_sw_cksum);
13104 
13105 		IP_CKSUM_RECV_REASS(reass_hck_flags,
13106 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
13107 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13108 		    iphs[9] + up[2], sum, cksum_err);
13109 
13110 		if (cksum_err) {
13111 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13112 
13113 			if (reass_hck_flags & HCK_FULLCKSUM)
13114 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13115 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13116 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13117 			else
13118 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13119 
13120 			freemsg(first_mp);
13121 			goto slow_done;
13122 		}
13123 	}
13124 udpslowpath:
13125 
13126 	/* Clear hardware checksum flag to be safe */
13127 	DB_CKSUMFLAGS(mp) = 0;
13128 
13129 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13130 	    (ire->ire_type == IRE_BROADCAST),
13131 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13132 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13133 
13134 slow_done:
13135 	IP_STAT(ipst, ip_udp_slow_path);
13136 	return;
13137 
13138 #undef  iphs
13139 #undef  rptr
13140 }
13141 
13142 /* ARGSUSED */
13143 static mblk_t *
13144 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13145     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13146     ill_rx_ring_t *ill_ring)
13147 {
13148 	conn_t		*connp;
13149 	uint32_t	sum;
13150 	uint32_t	u1;
13151 	uint16_t	*up;
13152 	int		offset;
13153 	ssize_t		len;
13154 	mblk_t		*mp1;
13155 	boolean_t	syn_present = B_FALSE;
13156 	tcph_t		*tcph;
13157 	uint_t		ip_hdr_len;
13158 	ill_t		*ill = (ill_t *)q->q_ptr;
13159 	zoneid_t	zoneid = ire->ire_zoneid;
13160 	boolean_t	cksum_err;
13161 	uint16_t	hck_flags = 0;
13162 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13163 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13164 
13165 #define	rptr	((uchar_t *)ipha)
13166 
13167 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13168 	ASSERT(ill != NULL);
13169 
13170 	/*
13171 	 * FAST PATH for tcp packets
13172 	 */
13173 
13174 	/* u1 is # words of IP options */
13175 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13176 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13177 
13178 	/* IP options present */
13179 	if (u1) {
13180 		goto ipoptions;
13181 	} else {
13182 		/* Check the IP header checksum.  */
13183 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13184 			/* Clear the IP header h/w cksum flag */
13185 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13186 		} else {
13187 #define	uph	((uint16_t *)ipha)
13188 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13189 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13190 #undef	uph
13191 			/* finish doing IP checksum */
13192 			sum = (sum & 0xFFFF) + (sum >> 16);
13193 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13194 			/*
13195 			 * Don't verify header checksum if this packet
13196 			 * is coming back from AH/ESP as we already did it.
13197 			 */
13198 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13199 				BUMP_MIB(ill->ill_ip_mib,
13200 				    ipIfStatsInCksumErrs);
13201 				goto error;
13202 			}
13203 		}
13204 	}
13205 
13206 	if (!mctl_present) {
13207 		UPDATE_IB_PKT_COUNT(ire);
13208 		ire->ire_last_used_time = lbolt;
13209 	}
13210 
13211 	/* packet part of fragmented IP packet? */
13212 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13213 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13214 		goto fragmented;
13215 	}
13216 
13217 	/* u1 = IP header length (20 bytes) */
13218 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13219 
13220 	/* does packet contain IP+TCP headers? */
13221 	len = mp->b_wptr - rptr;
13222 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13223 		IP_STAT(ipst, ip_tcppullup);
13224 		goto tcppullup;
13225 	}
13226 
13227 	/* TCP options present? */
13228 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13229 
13230 	/*
13231 	 * If options need to be pulled up, then goto tcpoptions.
13232 	 * otherwise we are still in the fast path
13233 	 */
13234 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13235 		IP_STAT(ipst, ip_tcpoptions);
13236 		goto tcpoptions;
13237 	}
13238 
13239 	/* multiple mblks of tcp data? */
13240 	if ((mp1 = mp->b_cont) != NULL) {
13241 		/* more then two? */
13242 		if (mp1->b_cont != NULL) {
13243 			IP_STAT(ipst, ip_multipkttcp);
13244 			goto multipkttcp;
13245 		}
13246 		len += mp1->b_wptr - mp1->b_rptr;
13247 	}
13248 
13249 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13250 
13251 	/* part of pseudo checksum */
13252 
13253 	/* TCP datagram length */
13254 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13255 
13256 #define	iphs    ((uint16_t *)ipha)
13257 
13258 #ifdef	_BIG_ENDIAN
13259 	u1 += IPPROTO_TCP;
13260 #else
13261 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13262 #endif
13263 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13264 
13265 	/*
13266 	 * Revert to software checksum calculation if the interface
13267 	 * isn't capable of checksum offload or if IPsec is present.
13268 	 */
13269 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13270 		hck_flags = DB_CKSUMFLAGS(mp);
13271 
13272 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13273 		IP_STAT(ipst, ip_in_sw_cksum);
13274 
13275 	IP_CKSUM_RECV(hck_flags, u1,
13276 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13277 	    (int32_t)((uchar_t *)up - rptr),
13278 	    mp, mp1, cksum_err);
13279 
13280 	if (cksum_err) {
13281 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13282 
13283 		if (hck_flags & HCK_FULLCKSUM)
13284 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13285 		else if (hck_flags & HCK_PARTIALCKSUM)
13286 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13287 		else
13288 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13289 
13290 		goto error;
13291 	}
13292 
13293 try_again:
13294 
13295 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13296 		    zoneid, ipst)) == NULL) {
13297 		/* Send the TH_RST */
13298 		goto no_conn;
13299 	}
13300 
13301 	/*
13302 	 * TCP FAST PATH for AF_INET socket.
13303 	 *
13304 	 * TCP fast path to avoid extra work. An AF_INET socket type
13305 	 * does not have facility to receive extra information via
13306 	 * ip_process or ip_add_info. Also, when the connection was
13307 	 * established, we made a check if this connection is impacted
13308 	 * by any global IPSec policy or per connection policy (a
13309 	 * policy that comes in effect later will not apply to this
13310 	 * connection). Since all this can be determined at the
13311 	 * connection establishment time, a quick check of flags
13312 	 * can avoid extra work.
13313 	 */
13314 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13315 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13316 		ASSERT(first_mp == mp);
13317 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13318 		SET_SQUEUE(mp, tcp_rput_data, connp);
13319 		return (mp);
13320 	}
13321 
13322 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13323 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13324 		if (IPCL_IS_TCP(connp)) {
13325 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13326 			DB_CKSUMSTART(mp) =
13327 			    (intptr_t)ip_squeue_get(ill_ring);
13328 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13329 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13330 				BUMP_MIB(ill->ill_ip_mib,
13331 				    ipIfStatsHCInDelivers);
13332 				SET_SQUEUE(mp, connp->conn_recv, connp);
13333 				return (mp);
13334 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13335 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13336 				BUMP_MIB(ill->ill_ip_mib,
13337 				    ipIfStatsHCInDelivers);
13338 				ip_squeue_enter_unbound++;
13339 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13340 				    connp);
13341 				return (mp);
13342 			}
13343 			syn_present = B_TRUE;
13344 		}
13345 
13346 	}
13347 
13348 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13349 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13350 
13351 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13352 		/* No need to send this packet to TCP */
13353 		if ((flags & TH_RST) || (flags & TH_URG)) {
13354 			CONN_DEC_REF(connp);
13355 			freemsg(first_mp);
13356 			return (NULL);
13357 		}
13358 		if (flags & TH_ACK) {
13359 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13360 			    ipst->ips_netstack->netstack_tcp);
13361 			CONN_DEC_REF(connp);
13362 			return (NULL);
13363 		}
13364 
13365 		CONN_DEC_REF(connp);
13366 		freemsg(first_mp);
13367 		return (NULL);
13368 	}
13369 
13370 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13371 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13372 		    ipha, NULL, mctl_present);
13373 		if (first_mp == NULL) {
13374 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13375 			CONN_DEC_REF(connp);
13376 			return (NULL);
13377 		}
13378 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13379 			ASSERT(syn_present);
13380 			if (mctl_present) {
13381 				ASSERT(first_mp != mp);
13382 				first_mp->b_datap->db_struioflag |=
13383 				    STRUIO_POLICY;
13384 			} else {
13385 				ASSERT(first_mp == mp);
13386 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13387 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13388 			}
13389 		} else {
13390 			/*
13391 			 * Discard first_mp early since we're dealing with a
13392 			 * fully-connected conn_t and tcp doesn't do policy in
13393 			 * this case.
13394 			 */
13395 			if (mctl_present) {
13396 				freeb(first_mp);
13397 				mctl_present = B_FALSE;
13398 			}
13399 			first_mp = mp;
13400 		}
13401 	}
13402 
13403 	/* Initiate IPPF processing for fastpath */
13404 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13405 		uint32_t	ill_index;
13406 
13407 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13408 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13409 		if (mp == NULL) {
13410 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13411 			    "deferred/dropped during IPPF processing\n"));
13412 			CONN_DEC_REF(connp);
13413 			if (mctl_present)
13414 				freeb(first_mp);
13415 			return (NULL);
13416 		} else if (mctl_present) {
13417 			/*
13418 			 * ip_process might return a new mp.
13419 			 */
13420 			ASSERT(first_mp != mp);
13421 			first_mp->b_cont = mp;
13422 		} else {
13423 			first_mp = mp;
13424 		}
13425 
13426 	}
13427 
13428 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13429 		/*
13430 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13431 		 * make sure IPF_RECVIF is passed to ip_add_info.
13432 		 */
13433 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13434 		    IPCL_ZONEID(connp), ipst);
13435 		if (mp == NULL) {
13436 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13437 			CONN_DEC_REF(connp);
13438 			if (mctl_present)
13439 				freeb(first_mp);
13440 			return (NULL);
13441 		} else if (mctl_present) {
13442 			/*
13443 			 * ip_add_info might return a new mp.
13444 			 */
13445 			ASSERT(first_mp != mp);
13446 			first_mp->b_cont = mp;
13447 		} else {
13448 			first_mp = mp;
13449 		}
13450 	}
13451 
13452 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13453 	if (IPCL_IS_TCP(connp)) {
13454 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13455 		return (first_mp);
13456 	} else {
13457 		putnext(connp->conn_rq, first_mp);
13458 		CONN_DEC_REF(connp);
13459 		return (NULL);
13460 	}
13461 
13462 no_conn:
13463 	/* Initiate IPPf processing, if needed. */
13464 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13465 		uint32_t ill_index;
13466 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13467 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13468 		if (first_mp == NULL) {
13469 			return (NULL);
13470 		}
13471 	}
13472 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13473 
13474 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13475 	    ipst->ips_netstack->netstack_tcp);
13476 	return (NULL);
13477 ipoptions:
13478 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13479 		goto slow_done;
13480 	}
13481 
13482 	UPDATE_IB_PKT_COUNT(ire);
13483 	ire->ire_last_used_time = lbolt;
13484 
13485 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13486 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13487 fragmented:
13488 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13489 			if (mctl_present)
13490 				freeb(first_mp);
13491 			goto slow_done;
13492 		}
13493 		/*
13494 		 * Make sure that first_mp points back to mp as
13495 		 * the mp we came in with could have changed in
13496 		 * ip_rput_fragment().
13497 		 */
13498 		ASSERT(!mctl_present);
13499 		ipha = (ipha_t *)mp->b_rptr;
13500 		first_mp = mp;
13501 	}
13502 
13503 	/* Now we have a complete datagram, destined for this machine. */
13504 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13505 
13506 	len = mp->b_wptr - mp->b_rptr;
13507 	/* Pull up a minimal TCP header, if necessary. */
13508 	if (len < (u1 + 20)) {
13509 tcppullup:
13510 		if (!pullupmsg(mp, u1 + 20)) {
13511 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13512 			goto error;
13513 		}
13514 		ipha = (ipha_t *)mp->b_rptr;
13515 		len = mp->b_wptr - mp->b_rptr;
13516 	}
13517 
13518 	/*
13519 	 * Extract the offset field from the TCP header.  As usual, we
13520 	 * try to help the compiler more than the reader.
13521 	 */
13522 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13523 	if (offset != 5) {
13524 tcpoptions:
13525 		if (offset < 5) {
13526 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13527 			goto error;
13528 		}
13529 		/*
13530 		 * There must be TCP options.
13531 		 * Make sure we can grab them.
13532 		 */
13533 		offset <<= 2;
13534 		offset += u1;
13535 		if (len < offset) {
13536 			if (!pullupmsg(mp, offset)) {
13537 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13538 				goto error;
13539 			}
13540 			ipha = (ipha_t *)mp->b_rptr;
13541 			len = mp->b_wptr - rptr;
13542 		}
13543 	}
13544 
13545 	/* Get the total packet length in len, including headers. */
13546 	if (mp->b_cont) {
13547 multipkttcp:
13548 		len = msgdsize(mp);
13549 	}
13550 
13551 	/*
13552 	 * Check the TCP checksum by pulling together the pseudo-
13553 	 * header checksum, and passing it to ip_csum to be added in
13554 	 * with the TCP datagram.
13555 	 *
13556 	 * Since we are not using the hwcksum if available we must
13557 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13558 	 * If either of these fails along the way the mblk is freed.
13559 	 * If this logic ever changes and mblk is reused to say send
13560 	 * ICMP's back, then this flag may need to be cleared in
13561 	 * other places as well.
13562 	 */
13563 	DB_CKSUMFLAGS(mp) = 0;
13564 
13565 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13566 
13567 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13568 #ifdef	_BIG_ENDIAN
13569 	u1 += IPPROTO_TCP;
13570 #else
13571 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13572 #endif
13573 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13574 	/*
13575 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13576 	 */
13577 	IP_STAT(ipst, ip_in_sw_cksum);
13578 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13579 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13580 		goto error;
13581 	}
13582 
13583 	IP_STAT(ipst, ip_tcp_slow_path);
13584 	goto try_again;
13585 #undef  iphs
13586 #undef  rptr
13587 
13588 error:
13589 	freemsg(first_mp);
13590 slow_done:
13591 	return (NULL);
13592 }
13593 
13594 /* ARGSUSED */
13595 static void
13596 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13597     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13598 {
13599 	conn_t		*connp;
13600 	uint32_t	sum;
13601 	uint32_t	u1;
13602 	ssize_t		len;
13603 	sctp_hdr_t	*sctph;
13604 	zoneid_t	zoneid = ire->ire_zoneid;
13605 	uint32_t	pktsum;
13606 	uint32_t	calcsum;
13607 	uint32_t	ports;
13608 	in6_addr_t	map_src, map_dst;
13609 	ill_t		*ill = (ill_t *)q->q_ptr;
13610 	ip_stack_t	*ipst;
13611 	sctp_stack_t	*sctps;
13612 
13613 	ASSERT(recv_ill != NULL);
13614 	ipst = recv_ill->ill_ipst;
13615 	sctps = ipst->ips_netstack->netstack_sctp;
13616 
13617 #define	rptr	((uchar_t *)ipha)
13618 
13619 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13620 	ASSERT(ill != NULL);
13621 
13622 	/* u1 is # words of IP options */
13623 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13624 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13625 
13626 	/* IP options present */
13627 	if (u1 > 0) {
13628 		goto ipoptions;
13629 	} else {
13630 		/* Check the IP header checksum.  */
13631 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13632 #define	uph	((uint16_t *)ipha)
13633 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13634 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13635 #undef	uph
13636 			/* finish doing IP checksum */
13637 			sum = (sum & 0xFFFF) + (sum >> 16);
13638 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13639 			/*
13640 			 * Don't verify header checksum if this packet
13641 			 * is coming back from AH/ESP as we already did it.
13642 			 */
13643 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13644 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13645 				goto error;
13646 			}
13647 		}
13648 		/*
13649 		 * Since there is no SCTP h/w cksum support yet, just
13650 		 * clear the flag.
13651 		 */
13652 		DB_CKSUMFLAGS(mp) = 0;
13653 	}
13654 
13655 	/*
13656 	 * Don't verify header checksum if this packet is coming
13657 	 * back from AH/ESP as we already did it.
13658 	 */
13659 	if (!mctl_present) {
13660 		UPDATE_IB_PKT_COUNT(ire);
13661 		ire->ire_last_used_time = lbolt;
13662 	}
13663 
13664 	/* packet part of fragmented IP packet? */
13665 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13666 	if (u1 & (IPH_MF | IPH_OFFSET))
13667 		goto fragmented;
13668 
13669 	/* u1 = IP header length (20 bytes) */
13670 	u1 = IP_SIMPLE_HDR_LENGTH;
13671 
13672 find_sctp_client:
13673 	/* Pullup if we don't have the sctp common header. */
13674 	len = MBLKL(mp);
13675 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13676 		if (mp->b_cont == NULL ||
13677 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13678 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13679 			goto error;
13680 		}
13681 		ipha = (ipha_t *)mp->b_rptr;
13682 		len = MBLKL(mp);
13683 	}
13684 
13685 	sctph = (sctp_hdr_t *)(rptr + u1);
13686 #ifdef	DEBUG
13687 	if (!skip_sctp_cksum) {
13688 #endif
13689 		pktsum = sctph->sh_chksum;
13690 		sctph->sh_chksum = 0;
13691 		calcsum = sctp_cksum(mp, u1);
13692 		if (calcsum != pktsum) {
13693 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13694 			goto error;
13695 		}
13696 		sctph->sh_chksum = pktsum;
13697 #ifdef	DEBUG	/* skip_sctp_cksum */
13698 	}
13699 #endif
13700 	/* get the ports */
13701 	ports = *(uint32_t *)&sctph->sh_sport;
13702 
13703 	IRE_REFRELE(ire);
13704 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13705 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13706 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13707 	    sctps)) == NULL) {
13708 		/* Check for raw socket or OOTB handling */
13709 		goto no_conn;
13710 	}
13711 
13712 	/* Found a client; up it goes */
13713 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13714 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13715 	return;
13716 
13717 no_conn:
13718 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13719 	    ports, mctl_present, flags, B_TRUE, zoneid);
13720 	return;
13721 
13722 ipoptions:
13723 	DB_CKSUMFLAGS(mp) = 0;
13724 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13725 		goto slow_done;
13726 
13727 	UPDATE_IB_PKT_COUNT(ire);
13728 	ire->ire_last_used_time = lbolt;
13729 
13730 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13731 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13732 fragmented:
13733 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13734 			goto slow_done;
13735 		/*
13736 		 * Make sure that first_mp points back to mp as
13737 		 * the mp we came in with could have changed in
13738 		 * ip_rput_fragment().
13739 		 */
13740 		ASSERT(!mctl_present);
13741 		ipha = (ipha_t *)mp->b_rptr;
13742 		first_mp = mp;
13743 	}
13744 
13745 	/* Now we have a complete datagram, destined for this machine. */
13746 	u1 = IPH_HDR_LENGTH(ipha);
13747 	goto find_sctp_client;
13748 #undef  iphs
13749 #undef  rptr
13750 
13751 error:
13752 	freemsg(first_mp);
13753 slow_done:
13754 	IRE_REFRELE(ire);
13755 }
13756 
13757 #define	VER_BITS	0xF0
13758 #define	VERSION_6	0x60
13759 
13760 static boolean_t
13761 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13762     ipaddr_t *dstp, ip_stack_t *ipst)
13763 {
13764 	uint_t	opt_len;
13765 	ipha_t *ipha;
13766 	ssize_t len;
13767 	uint_t	pkt_len;
13768 
13769 	ASSERT(ill != NULL);
13770 	IP_STAT(ipst, ip_ipoptions);
13771 	ipha = *iphapp;
13772 
13773 #define	rptr    ((uchar_t *)ipha)
13774 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13775 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13776 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13777 		freemsg(mp);
13778 		return (B_FALSE);
13779 	}
13780 
13781 	/* multiple mblk or too short */
13782 	pkt_len = ntohs(ipha->ipha_length);
13783 
13784 	/* Get the number of words of IP options in the IP header. */
13785 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13786 	if (opt_len) {
13787 		/* IP Options present!  Validate and process. */
13788 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13789 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13790 			goto done;
13791 		}
13792 		/*
13793 		 * Recompute complete header length and make sure we
13794 		 * have access to all of it.
13795 		 */
13796 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13797 		if (len > (mp->b_wptr - rptr)) {
13798 			if (len > pkt_len) {
13799 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13800 				goto done;
13801 			}
13802 			if (!pullupmsg(mp, len)) {
13803 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13804 				goto done;
13805 			}
13806 			ipha = (ipha_t *)mp->b_rptr;
13807 		}
13808 		/*
13809 		 * Go off to ip_rput_options which returns the next hop
13810 		 * destination address, which may have been affected
13811 		 * by source routing.
13812 		 */
13813 		IP_STAT(ipst, ip_opt);
13814 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13815 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13816 			return (B_FALSE);
13817 		}
13818 	}
13819 	*iphapp = ipha;
13820 	return (B_TRUE);
13821 done:
13822 	/* clear b_prev - used by ip_mroute_decap */
13823 	mp->b_prev = NULL;
13824 	freemsg(mp);
13825 	return (B_FALSE);
13826 #undef  rptr
13827 }
13828 
13829 /*
13830  * Deal with the fact that there is no ire for the destination.
13831  * The incoming ill (in_ill) is passed in to ip_newroute only
13832  * in the case of packets coming from mobile ip forward tunnel.
13833  * It must be null otherwise.
13834  */
13835 static ire_t *
13836 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13837     ipaddr_t dst)
13838 {
13839 	ipha_t	*ipha;
13840 	ill_t	*ill;
13841 	ire_t	*ire;
13842 	boolean_t	check_multirt = B_FALSE;
13843 	ip_stack_t *ipst;
13844 
13845 	ipha = (ipha_t *)mp->b_rptr;
13846 	ill = (ill_t *)q->q_ptr;
13847 
13848 	ASSERT(ill != NULL);
13849 	ipst = ill->ill_ipst;
13850 
13851 	/*
13852 	 * No IRE for this destination, so it can't be for us.
13853 	 * Unless we are forwarding, drop the packet.
13854 	 * We have to let source routed packets through
13855 	 * since we don't yet know if they are 'ping -l'
13856 	 * packets i.e. if they will go out over the
13857 	 * same interface as they came in on.
13858 	 */
13859 	if (ll_multicast) {
13860 		freemsg(mp);
13861 		return (NULL);
13862 	}
13863 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13864 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13865 		freemsg(mp);
13866 		return (NULL);
13867 	}
13868 
13869 	/*
13870 	 * Mark this packet as having originated externally.
13871 	 *
13872 	 * For non-forwarding code path, ire_send later double
13873 	 * checks this interface to see if it is still exists
13874 	 * post-ARP resolution.
13875 	 *
13876 	 * Also, IPQOS uses this to differentiate between
13877 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13878 	 * QOS packet processing in ip_wput_attach_llhdr().
13879 	 * The QoS module can mark the b_band for a fastpath message
13880 	 * or the dl_priority field in a unitdata_req header for
13881 	 * CoS marking. This info can only be found in
13882 	 * ip_wput_attach_llhdr().
13883 	 */
13884 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13885 	/*
13886 	 * Clear the indication that this may have a hardware checksum
13887 	 * as we are not using it
13888 	 */
13889 	DB_CKSUMFLAGS(mp) = 0;
13890 
13891 	if (in_ill != NULL) {
13892 		/*
13893 		 * Now hand the packet to ip_newroute.
13894 		 */
13895 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13896 		return (NULL);
13897 	}
13898 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13899 	    MBLK_GETLABEL(mp), ipst);
13900 
13901 	if (ire == NULL && check_multirt) {
13902 		/* Let ip_newroute handle CGTP  */
13903 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13904 		return (NULL);
13905 	}
13906 
13907 	if (ire != NULL)
13908 		return (ire);
13909 
13910 	mp->b_prev = mp->b_next = 0;
13911 	/* send icmp unreachable */
13912 	q = WR(q);
13913 	/* Sent by forwarding path, and router is global zone */
13914 	if (ip_source_routed(ipha, ipst)) {
13915 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13916 		    GLOBAL_ZONEID, ipst);
13917 	} else {
13918 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13919 		    ipst);
13920 	}
13921 
13922 	return (NULL);
13923 
13924 }
13925 
13926 /*
13927  * check ip header length and align it.
13928  */
13929 static boolean_t
13930 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13931 {
13932 	ssize_t len;
13933 	ill_t *ill;
13934 	ipha_t	*ipha;
13935 
13936 	len = MBLKL(mp);
13937 
13938 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13939 		ill = (ill_t *)q->q_ptr;
13940 
13941 		if (!OK_32PTR(mp->b_rptr))
13942 			IP_STAT(ipst, ip_notaligned1);
13943 		else
13944 			IP_STAT(ipst, ip_notaligned2);
13945 		/* Guard against bogus device drivers */
13946 		if (len < 0) {
13947 			/* clear b_prev - used by ip_mroute_decap */
13948 			mp->b_prev = NULL;
13949 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13950 			freemsg(mp);
13951 			return (B_FALSE);
13952 		}
13953 
13954 		if (ip_rput_pullups++ == 0) {
13955 			ipha = (ipha_t *)mp->b_rptr;
13956 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13957 			    "ip_check_and_align_header: %s forced us to "
13958 			    " pullup pkt, hdr len %ld, hdr addr %p",
13959 			    ill->ill_name, len, ipha);
13960 		}
13961 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13962 			/* clear b_prev - used by ip_mroute_decap */
13963 			mp->b_prev = NULL;
13964 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13965 			freemsg(mp);
13966 			return (B_FALSE);
13967 		}
13968 	}
13969 	return (B_TRUE);
13970 }
13971 
13972 ire_t *
13973 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13974 {
13975 	ire_t		*new_ire;
13976 	ill_t		*ire_ill;
13977 	uint_t		ifindex;
13978 	ip_stack_t	*ipst = ill->ill_ipst;
13979 	boolean_t	strict_check = B_FALSE;
13980 
13981 	/*
13982 	 * This packet came in on an interface other than the one associated
13983 	 * with the first ire we found for the destination address. We do
13984 	 * another ire lookup here, using the ingress ill, to see if the
13985 	 * interface is in an interface group.
13986 	 * As long as the ills belong to the same group, we don't consider
13987 	 * them to be arriving on the wrong interface. Thus, if the switch
13988 	 * is doing inbound load spreading, we won't drop packets when the
13989 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13990 	 * for 'usesrc groups' where the destination address may belong to
13991 	 * another interface to allow multipathing to happen.
13992 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13993 	 * where the local address may not be unique. In this case we were
13994 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13995 	 * actually returned. The new lookup, which is more specific, should
13996 	 * only find the IRE_LOCAL associated with the ingress ill if one
13997 	 * exists.
13998 	 */
13999 
14000 	if (ire->ire_ipversion == IPV4_VERSION) {
14001 		if (ipst->ips_ip_strict_dst_multihoming)
14002 			strict_check = B_TRUE;
14003 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
14004 		    ill->ill_ipif, ALL_ZONES, NULL,
14005 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14006 	} else {
14007 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
14008 		if (ipst->ips_ipv6_strict_dst_multihoming)
14009 			strict_check = B_TRUE;
14010 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
14011 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
14012 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14013 	}
14014 	/*
14015 	 * If the same ire that was returned in ip_input() is found then this
14016 	 * is an indication that interface groups are in use. The packet
14017 	 * arrived on a different ill in the group than the one associated with
14018 	 * the destination address.  If a different ire was found then the same
14019 	 * IP address must be hosted on multiple ills. This is possible with
14020 	 * unnumbered point2point interfaces. We switch to use this new ire in
14021 	 * order to have accurate interface statistics.
14022 	 */
14023 	if (new_ire != NULL) {
14024 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
14025 			ire_refrele(ire);
14026 			ire = new_ire;
14027 		} else {
14028 			ire_refrele(new_ire);
14029 		}
14030 		return (ire);
14031 	} else if ((ire->ire_rfq == NULL) &&
14032 		    (ire->ire_ipversion == IPV4_VERSION)) {
14033 		/*
14034 		 * The best match could have been the original ire which
14035 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
14036 		 * the strict multihoming checks are irrelevant as we consider
14037 		 * local addresses hosted on lo0 to be interface agnostic. We
14038 		 * only expect a null ire_rfq on IREs which are associated with
14039 		 * lo0 hence we can return now.
14040 		 */
14041 		return (ire);
14042 	}
14043 
14044 	/*
14045 	 * Chase pointers once and store locally.
14046 	 */
14047 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
14048 	    (ill_t *)(ire->ire_rfq->q_ptr);
14049 	ifindex = ill->ill_usesrc_ifindex;
14050 
14051 	/*
14052 	 * Check if it's a legal address on the 'usesrc' interface.
14053 	 */
14054 	if ((ifindex != 0) && (ire_ill != NULL) &&
14055 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
14056 		return (ire);
14057 	}
14058 
14059 	/*
14060 	 * If the ip*_strict_dst_multihoming switch is on then we can
14061 	 * only accept this packet if the interface is marked as routing.
14062 	 */
14063 	if (!(strict_check))
14064 		return (ire);
14065 
14066 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
14067 	    ILLF_ROUTER) != 0) {
14068 		return (ire);
14069 	}
14070 
14071 	ire_refrele(ire);
14072 	return (NULL);
14073 }
14074 
14075 ire_t *
14076 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
14077 {
14078 	ipha_t	*ipha;
14079 	ipaddr_t ip_dst, ip_src;
14080 	ire_t	*src_ire = NULL;
14081 	ill_t	*stq_ill;
14082 	uint_t	hlen;
14083 	uint_t	pkt_len;
14084 	uint32_t sum;
14085 	queue_t	*dev_q;
14086 	boolean_t check_multirt = B_FALSE;
14087 	ip_stack_t *ipst = ill->ill_ipst;
14088 
14089 	ipha = (ipha_t *)mp->b_rptr;
14090 
14091 	/*
14092 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14093 	 * The loopback address check for both src and dst has already
14094 	 * been checked in ip_input
14095 	 */
14096 	ip_dst = ntohl(dst);
14097 	ip_src = ntohl(ipha->ipha_src);
14098 
14099 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
14100 	    IN_CLASSD(ip_src)) {
14101 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14102 		goto drop;
14103 	}
14104 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14105 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14106 
14107 	if (src_ire != NULL) {
14108 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14109 		goto drop;
14110 	}
14111 
14112 
14113 	/* No ire cache of nexthop. So first create one  */
14114 	if (ire == NULL) {
14115 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
14116 		/*
14117 		 * We only come to ip_fast_forward if ip_cgtp_filter is
14118 		 * is not set. So upon return from ire_forward
14119 		 * check_multirt should remain as false.
14120 		 */
14121 		ASSERT(!check_multirt);
14122 		if (ire == NULL) {
14123 			/* An attempt was made to forward the packet */
14124 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14125 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14126 			mp->b_prev = mp->b_next = 0;
14127 			/* send icmp unreachable */
14128 			/* Sent by forwarding path, and router is global zone */
14129 			if (ip_source_routed(ipha, ipst)) {
14130 				icmp_unreachable(ill->ill_wq, mp,
14131 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
14132 				    ipst);
14133 			} else {
14134 				icmp_unreachable(ill->ill_wq, mp,
14135 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
14136 				    ipst);
14137 			}
14138 			return (ire);
14139 		}
14140 	}
14141 
14142 	/*
14143 	 * Forwarding fastpath exception case:
14144 	 * If either of the follwoing case is true, we take
14145 	 * the slowpath
14146 	 *	o forwarding is not enabled
14147 	 *	o incoming and outgoing interface are the same, or the same
14148 	 *	  IPMP group
14149 	 *	o corresponding ire is in incomplete state
14150 	 *	o packet needs fragmentation
14151 	 *
14152 	 * The codeflow from here on is thus:
14153 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14154 	 */
14155 	pkt_len = ntohs(ipha->ipha_length);
14156 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14157 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14158 	    !(ill->ill_flags & ILLF_ROUTER) ||
14159 	    (ill == stq_ill) ||
14160 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14161 	    (ire->ire_nce == NULL) ||
14162 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14163 	    (pkt_len > ire->ire_max_frag) ||
14164 	    ipha->ipha_ttl <= 1) {
14165 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14166 		    ipha, ill, B_FALSE);
14167 		return (ire);
14168 	}
14169 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14170 
14171 	DTRACE_PROBE4(ip4__forwarding__start,
14172 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14173 
14174 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14175 	    ipst->ips_ipv4firewall_forwarding,
14176 	    ill, stq_ill, ipha, mp, mp, ipst);
14177 
14178 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14179 
14180 	if (mp == NULL)
14181 		goto drop;
14182 
14183 	mp->b_datap->db_struioun.cksum.flags = 0;
14184 	/* Adjust the checksum to reflect the ttl decrement. */
14185 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14186 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14187 	ipha->ipha_ttl--;
14188 
14189 	dev_q = ire->ire_stq->q_next;
14190 	if ((dev_q->q_next != NULL ||
14191 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14192 		goto indiscard;
14193 	}
14194 
14195 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14196 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14197 
14198 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14199 		mblk_t *mpip = mp;
14200 
14201 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14202 		if (mp != NULL) {
14203 			DTRACE_PROBE4(ip4__physical__out__start,
14204 			    ill_t *, NULL, ill_t *, stq_ill,
14205 			    ipha_t *, ipha, mblk_t *, mp);
14206 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14207 			    ipst->ips_ipv4firewall_physical_out,
14208 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14209 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14210 			    mp);
14211 			if (mp == NULL)
14212 				goto drop;
14213 
14214 			UPDATE_IB_PKT_COUNT(ire);
14215 			ire->ire_last_used_time = lbolt;
14216 			BUMP_MIB(stq_ill->ill_ip_mib,
14217 			    ipIfStatsHCOutForwDatagrams);
14218 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14219 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14220 			    pkt_len);
14221 			putnext(ire->ire_stq, mp);
14222 			return (ire);
14223 		}
14224 	}
14225 
14226 indiscard:
14227 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14228 drop:
14229 	if (mp != NULL)
14230 		freemsg(mp);
14231 	if (src_ire != NULL)
14232 		ire_refrele(src_ire);
14233 	return (ire);
14234 
14235 }
14236 
14237 /*
14238  * This function is called in the forwarding slowpath, when
14239  * either the ire lacks the link-layer address, or the packet needs
14240  * further processing(eg. fragmentation), before transmission.
14241  */
14242 
14243 static void
14244 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14245     ill_t *ill, boolean_t ll_multicast)
14246 {
14247 	ill_group_t	*ill_group;
14248 	ill_group_t	*ire_group;
14249 	queue_t		*dev_q;
14250 	ire_t		*src_ire;
14251 	ip_stack_t	*ipst = ill->ill_ipst;
14252 
14253 	ASSERT(ire->ire_stq != NULL);
14254 
14255 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14256 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14257 
14258 	if (ll_multicast != 0) {
14259 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14260 		goto drop_pkt;
14261 	}
14262 
14263 	/*
14264 	 * check if ipha_src is a broadcast address. Note that this
14265 	 * check is redundant when we get here from ip_fast_forward()
14266 	 * which has already done this check. However, since we can
14267 	 * also get here from ip_rput_process_broadcast() or, for
14268 	 * for the slow path through ip_fast_forward(), we perform
14269 	 * the check again for code-reusability
14270 	 */
14271 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14272 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14273 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14274 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14275 		if (src_ire != NULL)
14276 			ire_refrele(src_ire);
14277 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14278 		ip2dbg(("ip_rput_process_forward: Received packet with"
14279 		    " bad src/dst address on %s\n", ill->ill_name));
14280 		goto drop_pkt;
14281 	}
14282 
14283 	ill_group = ill->ill_group;
14284 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14285 	/*
14286 	 * Check if we want to forward this one at this time.
14287 	 * We allow source routed packets on a host provided that
14288 	 * they go out the same interface or same interface group
14289 	 * as they came in on.
14290 	 *
14291 	 * XXX To be quicker, we may wish to not chase pointers to
14292 	 * get the ILLF_ROUTER flag and instead store the
14293 	 * forwarding policy in the ire.  An unfortunate
14294 	 * side-effect of that would be requiring an ire flush
14295 	 * whenever the ILLF_ROUTER flag changes.
14296 	 */
14297 	if (((ill->ill_flags &
14298 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14299 	    ILLF_ROUTER) == 0) &&
14300 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14301 	    (ill_group != NULL && ill_group == ire_group)))) {
14302 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14303 		if (ip_source_routed(ipha, ipst)) {
14304 			q = WR(q);
14305 			/*
14306 			 * Clear the indication that this may have
14307 			 * hardware checksum as we are not using it.
14308 			 */
14309 			DB_CKSUMFLAGS(mp) = 0;
14310 			/* Sent by forwarding path, and router is global zone */
14311 			icmp_unreachable(q, mp,
14312 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14313 			return;
14314 		}
14315 		goto drop_pkt;
14316 	}
14317 
14318 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14319 
14320 	/* Packet is being forwarded. Turning off hwcksum flag. */
14321 	DB_CKSUMFLAGS(mp) = 0;
14322 	if (ipst->ips_ip_g_send_redirects) {
14323 		/*
14324 		 * Check whether the incoming interface and outgoing
14325 		 * interface is part of the same group. If so,
14326 		 * send redirects.
14327 		 *
14328 		 * Check the source address to see if it originated
14329 		 * on the same logical subnet it is going back out on.
14330 		 * If so, we should be able to send it a redirect.
14331 		 * Avoid sending a redirect if the destination
14332 		 * is directly connected (i.e., ipha_dst is the same
14333 		 * as ire_gateway_addr or the ire_addr of the
14334 		 * nexthop IRE_CACHE ), or if the packet was source
14335 		 * routed out this interface.
14336 		 */
14337 		ipaddr_t src, nhop;
14338 		mblk_t	*mp1;
14339 		ire_t	*nhop_ire = NULL;
14340 
14341 		/*
14342 		 * Check whether ire_rfq and q are from the same ill
14343 		 * or if they are not same, they at least belong
14344 		 * to the same group. If so, send redirects.
14345 		 */
14346 		if ((ire->ire_rfq == q ||
14347 		    (ill_group != NULL && ill_group == ire_group)) &&
14348 		    !ip_source_routed(ipha, ipst)) {
14349 
14350 			nhop = (ire->ire_gateway_addr != 0 ?
14351 			    ire->ire_gateway_addr : ire->ire_addr);
14352 
14353 			if (ipha->ipha_dst == nhop) {
14354 				/*
14355 				 * We avoid sending a redirect if the
14356 				 * destination is directly connected
14357 				 * because it is possible that multiple
14358 				 * IP subnets may have been configured on
14359 				 * the link, and the source may not
14360 				 * be on the same subnet as ip destination,
14361 				 * even though they are on the same
14362 				 * physical link.
14363 				 */
14364 				goto sendit;
14365 			}
14366 
14367 			src = ipha->ipha_src;
14368 
14369 			/*
14370 			 * We look up the interface ire for the nexthop,
14371 			 * to see if ipha_src is in the same subnet
14372 			 * as the nexthop.
14373 			 *
14374 			 * Note that, if, in the future, IRE_CACHE entries
14375 			 * are obsoleted,  this lookup will not be needed,
14376 			 * as the ire passed to this function will be the
14377 			 * same as the nhop_ire computed below.
14378 			 */
14379 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14380 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14381 			    0, NULL, MATCH_IRE_TYPE, ipst);
14382 
14383 			if (nhop_ire != NULL) {
14384 				if ((src & nhop_ire->ire_mask) ==
14385 				    (nhop & nhop_ire->ire_mask)) {
14386 					/*
14387 					 * The source is directly connected.
14388 					 * Just copy the ip header (which is
14389 					 * in the first mblk)
14390 					 */
14391 					mp1 = copyb(mp);
14392 					if (mp1 != NULL) {
14393 						icmp_send_redirect(WR(q), mp1,
14394 						    nhop, ipst);
14395 					}
14396 				}
14397 				ire_refrele(nhop_ire);
14398 			}
14399 		}
14400 	}
14401 sendit:
14402 	dev_q = ire->ire_stq->q_next;
14403 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14404 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14405 		freemsg(mp);
14406 		return;
14407 	}
14408 
14409 	ip_rput_forward(ire, ipha, mp, ill);
14410 	return;
14411 
14412 drop_pkt:
14413 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14414 	freemsg(mp);
14415 }
14416 
14417 ire_t *
14418 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14419     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14420 {
14421 	queue_t		*q;
14422 	uint16_t	hcksumflags;
14423 	ip_stack_t	*ipst = ill->ill_ipst;
14424 
14425 	q = *qp;
14426 
14427 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14428 
14429 	/*
14430 	 * Clear the indication that this may have hardware
14431 	 * checksum as we are not using it for forwarding.
14432 	 */
14433 	hcksumflags = DB_CKSUMFLAGS(mp);
14434 	DB_CKSUMFLAGS(mp) = 0;
14435 
14436 	/*
14437 	 * Directed broadcast forwarding: if the packet came in over a
14438 	 * different interface then it is routed out over we can forward it.
14439 	 */
14440 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14441 		ire_refrele(ire);
14442 		freemsg(mp);
14443 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14444 		return (NULL);
14445 	}
14446 	/*
14447 	 * For multicast we have set dst to be INADDR_BROADCAST
14448 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14449 	 * only for broadcast packets.
14450 	 */
14451 	if (!CLASSD(ipha->ipha_dst)) {
14452 		ire_t *new_ire;
14453 		ipif_t *ipif;
14454 		/*
14455 		 * For ill groups, as the switch duplicates broadcasts
14456 		 * across all the ports, we need to filter out and
14457 		 * send up only one copy. There is one copy for every
14458 		 * broadcast address on each ill. Thus, we look for a
14459 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14460 		 * later to see whether this ill is eligible to receive
14461 		 * them or not. ill_nominate_bcast_rcv() nominates only
14462 		 * one set of IREs for receiving.
14463 		 */
14464 
14465 		ipif = ipif_get_next_ipif(NULL, ill);
14466 		if (ipif == NULL) {
14467 			ire_refrele(ire);
14468 			freemsg(mp);
14469 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14470 			return (NULL);
14471 		}
14472 		new_ire = ire_ctable_lookup(dst, 0, 0,
14473 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14474 		ipif_refrele(ipif);
14475 
14476 		if (new_ire != NULL) {
14477 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14478 				ire_refrele(ire);
14479 				ire_refrele(new_ire);
14480 				freemsg(mp);
14481 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14482 				return (NULL);
14483 			}
14484 			/*
14485 			 * In the special case of multirouted broadcast
14486 			 * packets, we unconditionally need to "gateway"
14487 			 * them to the appropriate interface here.
14488 			 * In the normal case, this cannot happen, because
14489 			 * there is no broadcast IRE tagged with the
14490 			 * RTF_MULTIRT flag.
14491 			 */
14492 			if (new_ire->ire_flags & RTF_MULTIRT) {
14493 				ire_refrele(new_ire);
14494 				if (ire->ire_rfq != NULL) {
14495 					q = ire->ire_rfq;
14496 					*qp = q;
14497 				}
14498 			} else {
14499 				ire_refrele(ire);
14500 				ire = new_ire;
14501 			}
14502 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14503 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14504 				/*
14505 				 * Free the message if
14506 				 * ip_g_forward_directed_bcast is turned
14507 				 * off for non-local broadcast.
14508 				 */
14509 				ire_refrele(ire);
14510 				freemsg(mp);
14511 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14512 				return (NULL);
14513 			}
14514 		} else {
14515 			/*
14516 			 * This CGTP packet successfully passed the
14517 			 * CGTP filter, but the related CGTP
14518 			 * broadcast IRE has not been found,
14519 			 * meaning that the redundant ipif is
14520 			 * probably down. However, if we discarded
14521 			 * this packet, its duplicate would be
14522 			 * filtered out by the CGTP filter so none
14523 			 * of them would get through. So we keep
14524 			 * going with this one.
14525 			 */
14526 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14527 			if (ire->ire_rfq != NULL) {
14528 				q = ire->ire_rfq;
14529 				*qp = q;
14530 			}
14531 		}
14532 	}
14533 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14534 		/*
14535 		 * Verify that there are not more then one
14536 		 * IRE_BROADCAST with this broadcast address which
14537 		 * has ire_stq set.
14538 		 * TODO: simplify, loop over all IRE's
14539 		 */
14540 		ire_t	*ire1;
14541 		int	num_stq = 0;
14542 		mblk_t	*mp1;
14543 
14544 		/* Find the first one with ire_stq set */
14545 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14546 		for (ire1 = ire; ire1 &&
14547 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14548 		    ire1 = ire1->ire_next)
14549 			;
14550 		if (ire1) {
14551 			ire_refrele(ire);
14552 			ire = ire1;
14553 			IRE_REFHOLD(ire);
14554 		}
14555 
14556 		/* Check if there are additional ones with stq set */
14557 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14558 			if (ire->ire_addr != ire1->ire_addr)
14559 				break;
14560 			if (ire1->ire_stq) {
14561 				num_stq++;
14562 				break;
14563 			}
14564 		}
14565 		rw_exit(&ire->ire_bucket->irb_lock);
14566 		if (num_stq == 1 && ire->ire_stq != NULL) {
14567 			ip1dbg(("ip_rput_process_broadcast: directed "
14568 			    "broadcast to 0x%x\n",
14569 			    ntohl(ire->ire_addr)));
14570 			mp1 = copymsg(mp);
14571 			if (mp1) {
14572 				switch (ipha->ipha_protocol) {
14573 				case IPPROTO_UDP:
14574 					ip_udp_input(q, mp1, ipha, ire, ill);
14575 					break;
14576 				default:
14577 					ip_proto_input(q, mp1, ipha, ire, ill);
14578 					break;
14579 				}
14580 			}
14581 			/*
14582 			 * Adjust ttl to 2 (1+1 - the forward engine
14583 			 * will decrement it by one.
14584 			 */
14585 			if (ip_csum_hdr(ipha)) {
14586 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14587 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14588 				freemsg(mp);
14589 				ire_refrele(ire);
14590 				return (NULL);
14591 			}
14592 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14593 			ipha->ipha_hdr_checksum = 0;
14594 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14595 			ip_rput_process_forward(q, mp, ire, ipha,
14596 			    ill, ll_multicast);
14597 			ire_refrele(ire);
14598 			return (NULL);
14599 		}
14600 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14601 		    ntohl(ire->ire_addr)));
14602 	}
14603 
14604 
14605 	/* Restore any hardware checksum flags */
14606 	DB_CKSUMFLAGS(mp) = hcksumflags;
14607 	return (ire);
14608 }
14609 
14610 /* ARGSUSED */
14611 static boolean_t
14612 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14613     int *ll_multicast, ipaddr_t *dstp)
14614 {
14615 	ip_stack_t	*ipst = ill->ill_ipst;
14616 
14617 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14618 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14619 	    ntohs(ipha->ipha_length));
14620 
14621 	/*
14622 	 * Forward packets only if we have joined the allmulti
14623 	 * group on this interface.
14624 	 */
14625 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14626 		int retval;
14627 
14628 		/*
14629 		 * Clear the indication that this may have hardware
14630 		 * checksum as we are not using it.
14631 		 */
14632 		DB_CKSUMFLAGS(mp) = 0;
14633 		retval = ip_mforward(ill, ipha, mp);
14634 		/* ip_mforward updates mib variables if needed */
14635 		/* clear b_prev - used by ip_mroute_decap */
14636 		mp->b_prev = NULL;
14637 
14638 		switch (retval) {
14639 		case 0:
14640 			/*
14641 			 * pkt is okay and arrived on phyint.
14642 			 *
14643 			 * If we are running as a multicast router
14644 			 * we need to see all IGMP and/or PIM packets.
14645 			 */
14646 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14647 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14648 				goto done;
14649 			}
14650 			break;
14651 		case -1:
14652 			/* pkt is mal-formed, toss it */
14653 			goto drop_pkt;
14654 		case 1:
14655 			/* pkt is okay and arrived on a tunnel */
14656 			/*
14657 			 * If we are running a multicast router
14658 			 *  we need to see all igmp packets.
14659 			 */
14660 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14661 				*dstp = INADDR_BROADCAST;
14662 				*ll_multicast = 1;
14663 				return (B_FALSE);
14664 			}
14665 
14666 			goto drop_pkt;
14667 		}
14668 	}
14669 
14670 	ILM_WALKER_HOLD(ill);
14671 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14672 		/*
14673 		 * This might just be caused by the fact that
14674 		 * multiple IP Multicast addresses map to the same
14675 		 * link layer multicast - no need to increment counter!
14676 		 */
14677 		ILM_WALKER_RELE(ill);
14678 		freemsg(mp);
14679 		return (B_TRUE);
14680 	}
14681 	ILM_WALKER_RELE(ill);
14682 done:
14683 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14684 	/*
14685 	 * This assumes the we deliver to all streams for multicast
14686 	 * and broadcast packets.
14687 	 */
14688 	*dstp = INADDR_BROADCAST;
14689 	*ll_multicast = 1;
14690 	return (B_FALSE);
14691 drop_pkt:
14692 	ip2dbg(("ip_rput: drop pkt\n"));
14693 	freemsg(mp);
14694 	return (B_TRUE);
14695 }
14696 
14697 static boolean_t
14698 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14699     int *ll_multicast, mblk_t **mpp)
14700 {
14701 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14702 	boolean_t must_copy = B_FALSE;
14703 	struct iocblk   *iocp;
14704 	ipha_t		*ipha;
14705 	ip_stack_t	*ipst = ill->ill_ipst;
14706 
14707 #define	rptr    ((uchar_t *)ipha)
14708 
14709 	first_mp = *first_mpp;
14710 	mp = *mpp;
14711 
14712 	ASSERT(first_mp == mp);
14713 
14714 	/*
14715 	 * if db_ref > 1 then copymsg and free original. Packet may be
14716 	 * changed and do not want other entity who has a reference to this
14717 	 * message to trip over the changes. This is a blind change because
14718 	 * trying to catch all places that might change packet is too
14719 	 * difficult (since it may be a module above this one)
14720 	 *
14721 	 * This corresponds to the non-fast path case. We walk down the full
14722 	 * chain in this case, and check the db_ref count of all the dblks,
14723 	 * and do a copymsg if required. It is possible that the db_ref counts
14724 	 * of the data blocks in the mblk chain can be different.
14725 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14726 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14727 	 * 'snoop' is running.
14728 	 */
14729 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14730 		if (mp1->b_datap->db_ref > 1) {
14731 			must_copy = B_TRUE;
14732 			break;
14733 		}
14734 	}
14735 
14736 	if (must_copy) {
14737 		mp1 = copymsg(mp);
14738 		if (mp1 == NULL) {
14739 			for (mp1 = mp; mp1 != NULL;
14740 			    mp1 = mp1->b_cont) {
14741 				mp1->b_next = NULL;
14742 				mp1->b_prev = NULL;
14743 			}
14744 			freemsg(mp);
14745 			if (ill != NULL) {
14746 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14747 			} else {
14748 				BUMP_MIB(&ipst->ips_ip_mib,
14749 				    ipIfStatsInDiscards);
14750 			}
14751 			return (B_TRUE);
14752 		}
14753 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14754 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14755 			/* Copy b_prev - used by ip_mroute_decap */
14756 			to_mp->b_prev = from_mp->b_prev;
14757 			from_mp->b_prev = NULL;
14758 		}
14759 		*first_mpp = first_mp = mp1;
14760 		freemsg(mp);
14761 		mp = mp1;
14762 		*mpp = mp1;
14763 	}
14764 
14765 	ipha = (ipha_t *)mp->b_rptr;
14766 
14767 	/*
14768 	 * previous code has a case for M_DATA.
14769 	 * We want to check how that happens.
14770 	 */
14771 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14772 	switch (first_mp->b_datap->db_type) {
14773 	case M_PROTO:
14774 	case M_PCPROTO:
14775 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14776 		    DL_UNITDATA_IND) {
14777 			/* Go handle anything other than data elsewhere. */
14778 			ip_rput_dlpi(q, mp);
14779 			return (B_TRUE);
14780 		}
14781 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14782 		/* Ditch the DLPI header. */
14783 		mp1 = mp->b_cont;
14784 		ASSERT(first_mp == mp);
14785 		*first_mpp = mp1;
14786 		freeb(mp);
14787 		*mpp = mp1;
14788 		return (B_FALSE);
14789 	case M_IOCACK:
14790 		ip1dbg(("got iocack "));
14791 		iocp = (struct iocblk *)mp->b_rptr;
14792 		switch (iocp->ioc_cmd) {
14793 		case DL_IOC_HDR_INFO:
14794 			ill = (ill_t *)q->q_ptr;
14795 			ill_fastpath_ack(ill, mp);
14796 			return (B_TRUE);
14797 		case SIOCSTUNPARAM:
14798 		case OSIOCSTUNPARAM:
14799 			/* Go through qwriter_ip */
14800 			break;
14801 		case SIOCGTUNPARAM:
14802 		case OSIOCGTUNPARAM:
14803 			ip_rput_other(NULL, q, mp, NULL);
14804 			return (B_TRUE);
14805 		default:
14806 			putnext(q, mp);
14807 			return (B_TRUE);
14808 		}
14809 		/* FALLTHRU */
14810 	case M_ERROR:
14811 	case M_HANGUP:
14812 		/*
14813 		 * Since this is on the ill stream we unconditionally
14814 		 * bump up the refcount
14815 		 */
14816 		ill_refhold(ill);
14817 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14818 		    B_FALSE);
14819 		return (B_TRUE);
14820 	case M_CTL:
14821 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14822 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14823 			IPHADA_M_CTL)) {
14824 			/*
14825 			 * It's an IPsec accelerated packet.
14826 			 * Make sure that the ill from which we received the
14827 			 * packet has enabled IPsec hardware acceleration.
14828 			 */
14829 			if (!(ill->ill_capabilities &
14830 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14831 				/* IPsec kstats: bean counter */
14832 				freemsg(mp);
14833 				return (B_TRUE);
14834 			}
14835 
14836 			/*
14837 			 * Make mp point to the mblk following the M_CTL,
14838 			 * then process according to type of mp.
14839 			 * After this processing, first_mp will point to
14840 			 * the data-attributes and mp to the pkt following
14841 			 * the M_CTL.
14842 			 */
14843 			mp = first_mp->b_cont;
14844 			if (mp == NULL) {
14845 				freemsg(first_mp);
14846 				return (B_TRUE);
14847 			}
14848 			/*
14849 			 * A Hardware Accelerated packet can only be M_DATA
14850 			 * ESP or AH packet.
14851 			 */
14852 			if (mp->b_datap->db_type != M_DATA) {
14853 				/* non-M_DATA IPsec accelerated packet */
14854 				IPSECHW_DEBUG(IPSECHW_PKT,
14855 				    ("non-M_DATA IPsec accelerated pkt\n"));
14856 				freemsg(first_mp);
14857 				return (B_TRUE);
14858 			}
14859 			ipha = (ipha_t *)mp->b_rptr;
14860 			if (ipha->ipha_protocol != IPPROTO_AH &&
14861 			    ipha->ipha_protocol != IPPROTO_ESP) {
14862 				IPSECHW_DEBUG(IPSECHW_PKT,
14863 				    ("non-M_DATA IPsec accelerated pkt\n"));
14864 				freemsg(first_mp);
14865 				return (B_TRUE);
14866 			}
14867 			*mpp = mp;
14868 			return (B_FALSE);
14869 		}
14870 		putnext(q, mp);
14871 		return (B_TRUE);
14872 	case M_FLUSH:
14873 		if (*mp->b_rptr & FLUSHW) {
14874 			*mp->b_rptr &= ~FLUSHR;
14875 			qreply(q, mp);
14876 			return (B_TRUE);
14877 		}
14878 		freemsg(mp);
14879 		return (B_TRUE);
14880 	case M_IOCNAK:
14881 		ip1dbg(("got iocnak "));
14882 		iocp = (struct iocblk *)mp->b_rptr;
14883 		switch (iocp->ioc_cmd) {
14884 		case DL_IOC_HDR_INFO:
14885 		case SIOCSTUNPARAM:
14886 		case OSIOCSTUNPARAM:
14887 			/*
14888 			 * Since this is on the ill stream we unconditionally
14889 			 * bump up the refcount
14890 			 */
14891 			ill_refhold(ill);
14892 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14893 			    CUR_OP, B_FALSE);
14894 			return (B_TRUE);
14895 		case SIOCGTUNPARAM:
14896 		case OSIOCGTUNPARAM:
14897 			ip_rput_other(NULL, q, mp, NULL);
14898 			return (B_TRUE);
14899 		default:
14900 			break;
14901 		}
14902 		/* FALLTHRU */
14903 	default:
14904 		putnext(q, mp);
14905 		return (B_TRUE);
14906 	}
14907 }
14908 
14909 /* Read side put procedure.  Packets coming from the wire arrive here. */
14910 void
14911 ip_rput(queue_t *q, mblk_t *mp)
14912 {
14913 	ill_t	*ill;
14914 	ip_stack_t	*ipst;
14915 
14916 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14917 
14918 	ill = (ill_t *)q->q_ptr;
14919 	ipst = ill->ill_ipst;
14920 
14921 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14922 		union DL_primitives *dl;
14923 
14924 		/*
14925 		 * Things are opening or closing. Only accept DLPI control
14926 		 * messages. In the open case, the ill->ill_ipif has not yet
14927 		 * been created. In the close case, things hanging off the
14928 		 * ill could have been freed already. In either case it
14929 		 * may not be safe to proceed further.
14930 		 */
14931 
14932 		dl = (union DL_primitives *)mp->b_rptr;
14933 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14934 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14935 			/*
14936 			 * Also SIOC[GS]TUN* ioctls can come here.
14937 			 */
14938 			inet_freemsg(mp);
14939 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14940 			    "ip_input_end: q %p (%S)", q, "uninit");
14941 			return;
14942 		}
14943 	}
14944 
14945 	/*
14946 	 * if db_ref > 1 then copymsg and free original. Packet may be
14947 	 * changed and we do not want the other entity who has a reference to
14948 	 * this message to trip over the changes. This is a blind change because
14949 	 * trying to catch all places that might change the packet is too
14950 	 * difficult.
14951 	 *
14952 	 * This corresponds to the fast path case, where we have a chain of
14953 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14954 	 * in the mblk chain. There doesn't seem to be a reason why a device
14955 	 * driver would send up data with varying db_ref counts in the mblk
14956 	 * chain. In any case the Fast path is a private interface, and our
14957 	 * drivers don't do such a thing. Given the above assumption, there is
14958 	 * no need to walk down the entire mblk chain (which could have a
14959 	 * potential performance problem)
14960 	 */
14961 	if (mp->b_datap->db_ref > 1) {
14962 		mblk_t  *mp1;
14963 		boolean_t adjusted = B_FALSE;
14964 		IP_STAT(ipst, ip_db_ref);
14965 
14966 		/*
14967 		 * The IP_RECVSLLA option depends on having the link layer
14968 		 * header. First check that:
14969 		 * a> the underlying device is of type ether, since this
14970 		 * option is currently supported only over ethernet.
14971 		 * b> there is enough room to copy over the link layer header.
14972 		 *
14973 		 * Once the checks are done, adjust rptr so that the link layer
14974 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14975 		 * be returned by some non-ethernet drivers but in this case the
14976 		 * second check will fail.
14977 		 */
14978 		if (ill->ill_type == IFT_ETHER &&
14979 		    (mp->b_rptr - mp->b_datap->db_base) >=
14980 		    sizeof (struct ether_header)) {
14981 			mp->b_rptr -= sizeof (struct ether_header);
14982 			adjusted = B_TRUE;
14983 		}
14984 		mp1 = copymsg(mp);
14985 		if (mp1 == NULL) {
14986 			mp->b_next = NULL;
14987 			/* clear b_prev - used by ip_mroute_decap */
14988 			mp->b_prev = NULL;
14989 			freemsg(mp);
14990 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14991 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14992 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14993 			return;
14994 		}
14995 		if (adjusted) {
14996 			/*
14997 			 * Copy is done. Restore the pointer in the _new_ mblk
14998 			 */
14999 			mp1->b_rptr += sizeof (struct ether_header);
15000 		}
15001 		/* Copy b_prev - used by ip_mroute_decap */
15002 		mp1->b_prev = mp->b_prev;
15003 		mp->b_prev = NULL;
15004 		freemsg(mp);
15005 		mp = mp1;
15006 	}
15007 
15008 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15009 	    "ip_rput_end: q %p (%S)", q, "end");
15010 
15011 	ip_input(ill, NULL, mp, NULL);
15012 }
15013 
15014 /*
15015  * Direct read side procedure capable of dealing with chains. GLDv3 based
15016  * drivers call this function directly with mblk chains while STREAMS
15017  * read side procedure ip_rput() calls this for single packet with ip_ring
15018  * set to NULL to process one packet at a time.
15019  *
15020  * The ill will always be valid if this function is called directly from
15021  * the driver.
15022  *
15023  * If ip_input() is called from GLDv3:
15024  *
15025  *   - This must be a non-VLAN IP stream.
15026  *   - 'mp' is either an untagged or a special priority-tagged packet.
15027  *   - Any VLAN tag that was in the MAC header has been stripped.
15028  *
15029  * If the IP header in packet is not 32-bit aligned, every message in the
15030  * chain will be aligned before further operations. This is required on SPARC
15031  * platform.
15032  */
15033 /* ARGSUSED */
15034 void
15035 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
15036     struct mac_header_info_s *mhip)
15037 {
15038 	ipaddr_t		dst = NULL;
15039 	ipaddr_t		prev_dst;
15040 	ire_t			*ire = NULL;
15041 	ipha_t			*ipha;
15042 	uint_t			pkt_len;
15043 	ssize_t			len;
15044 	uint_t			opt_len;
15045 	int			ll_multicast;
15046 	int			cgtp_flt_pkt;
15047 	queue_t			*q = ill->ill_rq;
15048 	squeue_t		*curr_sqp = NULL;
15049 	mblk_t 			*head = NULL;
15050 	mblk_t			*tail = NULL;
15051 	mblk_t			*first_mp;
15052 	mblk_t 			*mp;
15053 	mblk_t			*dmp;
15054 	int			cnt = 0;
15055 	ip_stack_t		*ipst = ill->ill_ipst;
15056 
15057 	ASSERT(mp_chain != NULL);
15058 	ASSERT(ill != NULL);
15059 
15060 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15061 
15062 #define	rptr	((uchar_t *)ipha)
15063 
15064 	while (mp_chain != NULL) {
15065 		first_mp = mp = mp_chain;
15066 		mp_chain = mp_chain->b_next;
15067 		mp->b_next = NULL;
15068 		ll_multicast = 0;
15069 
15070 		/*
15071 		 * We do ire caching from one iteration to
15072 		 * another. In the event the packet chain contains
15073 		 * all packets from the same dst, this caching saves
15074 		 * an ire_cache_lookup for each of the succeeding
15075 		 * packets in a packet chain.
15076 		 */
15077 		prev_dst = dst;
15078 
15079 		/*
15080 		 * Check and align the IP header.
15081 		 */
15082 		if (DB_TYPE(mp) == M_DATA) {
15083 			dmp = mp;
15084 		} else if (DB_TYPE(mp) == M_PROTO &&
15085 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15086 			dmp = mp->b_cont;
15087 		} else {
15088 			dmp = NULL;
15089 		}
15090 		if (dmp != NULL) {
15091 			/*
15092 			 * IP header ptr not aligned?
15093 			 * OR IP header not complete in first mblk
15094 			 */
15095 			if (!OK_32PTR(dmp->b_rptr) ||
15096 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15097 				if (!ip_check_and_align_header(q, dmp, ipst))
15098 					continue;
15099 			}
15100 		}
15101 
15102 		/*
15103 		 * ip_input fast path
15104 		 */
15105 
15106 		/* mblk type is not M_DATA */
15107 		if (DB_TYPE(mp) != M_DATA) {
15108 			if (ip_rput_process_notdata(q, &first_mp, ill,
15109 			    &ll_multicast, &mp))
15110 				continue;
15111 		}
15112 
15113 		/* Make sure its an M_DATA and that its aligned */
15114 		ASSERT(DB_TYPE(mp) == M_DATA);
15115 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15116 
15117 		ipha = (ipha_t *)mp->b_rptr;
15118 		len = mp->b_wptr - rptr;
15119 		pkt_len = ntohs(ipha->ipha_length);
15120 
15121 		/*
15122 		 * We must count all incoming packets, even if they end
15123 		 * up being dropped later on.
15124 		 */
15125 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15126 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15127 
15128 		/* multiple mblk or too short */
15129 		len -= pkt_len;
15130 		if (len != 0) {
15131 			/*
15132 			 * Make sure we have data length consistent
15133 			 * with the IP header.
15134 			 */
15135 			if (mp->b_cont == NULL) {
15136 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15137 					BUMP_MIB(ill->ill_ip_mib,
15138 					    ipIfStatsInHdrErrors);
15139 					ip2dbg(("ip_input: drop pkt\n"));
15140 					freemsg(mp);
15141 					continue;
15142 				}
15143 				mp->b_wptr = rptr + pkt_len;
15144 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15145 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15146 					BUMP_MIB(ill->ill_ip_mib,
15147 					    ipIfStatsInHdrErrors);
15148 					ip2dbg(("ip_input: drop pkt\n"));
15149 					freemsg(mp);
15150 					continue;
15151 				}
15152 				(void) adjmsg(mp, -len);
15153 				IP_STAT(ipst, ip_multimblk3);
15154 			}
15155 		}
15156 
15157 		/* Obtain the dst of the current packet */
15158 		dst = ipha->ipha_dst;
15159 
15160 		if (IP_LOOPBACK_ADDR(dst) ||
15161 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15162 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15163 			cmn_err(CE_CONT, "dst %X src %X\n",
15164 			    dst, ipha->ipha_src);
15165 			freemsg(mp);
15166 			continue;
15167 		}
15168 
15169 		/*
15170 		 * The event for packets being received from a 'physical'
15171 		 * interface is placed after validation of the source and/or
15172 		 * destination address as being local so that packets can be
15173 		 * redirected to loopback addresses using ipnat.
15174 		 */
15175 		DTRACE_PROBE4(ip4__physical__in__start,
15176 		    ill_t *, ill, ill_t *, NULL,
15177 		    ipha_t *, ipha, mblk_t *, first_mp);
15178 
15179 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15180 		    ipst->ips_ipv4firewall_physical_in,
15181 		    ill, NULL, ipha, first_mp, mp, ipst);
15182 
15183 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15184 
15185 		if (first_mp == NULL) {
15186 			continue;
15187 		}
15188 		dst = ipha->ipha_dst;
15189 
15190 		/*
15191 		 * Attach any necessary label information to
15192 		 * this packet
15193 		 */
15194 		if (is_system_labeled() &&
15195 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15196 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15197 			freemsg(mp);
15198 			continue;
15199 		}
15200 
15201 		/*
15202 		 * Reuse the cached ire only if the ipha_dst of the previous
15203 		 * packet is the same as the current packet AND it is not
15204 		 * INADDR_ANY.
15205 		 */
15206 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15207 		    (ire != NULL)) {
15208 			ire_refrele(ire);
15209 			ire = NULL;
15210 		}
15211 		opt_len = ipha->ipha_version_and_hdr_length -
15212 		    IP_SIMPLE_HDR_VERSION;
15213 
15214 		/*
15215 		 * Check to see if we can take the fastpath.
15216 		 * That is possible if the following conditions are met
15217 		 *	o Tsol disabled
15218 		 *	o CGTP disabled
15219 		 *	o ipp_action_count is 0
15220 		 *	o Mobile IP not running
15221 		 *	o no options in the packet
15222 		 *	o not a RSVP packet
15223 		 * 	o not a multicast packet
15224 		 */
15225 		if (!is_system_labeled() &&
15226 		    !ip_cgtp_filter && ipp_action_count == 0 &&
15227 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
15228 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15229 		    !ll_multicast && !CLASSD(dst)) {
15230 			if (ire == NULL)
15231 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15232 				    ipst);
15233 
15234 			/* incoming packet is for forwarding */
15235 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15236 				ire = ip_fast_forward(ire, dst, ill, mp);
15237 				continue;
15238 			}
15239 			/* incoming packet is for local consumption */
15240 			if (ire->ire_type & IRE_LOCAL)
15241 				goto local;
15242 		}
15243 
15244 		/*
15245 		 * Disable ire caching for anything more complex
15246 		 * than the simple fast path case we checked for above.
15247 		 */
15248 		if (ire != NULL) {
15249 			ire_refrele(ire);
15250 			ire = NULL;
15251 		}
15252 
15253 		/* Full-blown slow path */
15254 		if (opt_len != 0) {
15255 			if (len != 0)
15256 				IP_STAT(ipst, ip_multimblk4);
15257 			else
15258 				IP_STAT(ipst, ip_ipoptions);
15259 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15260 			    &dst, ipst))
15261 				continue;
15262 		}
15263 
15264 		/*
15265 		 * Invoke the CGTP (multirouting) filtering module to process
15266 		 * the incoming packet. Packets identified as duplicates
15267 		 * must be discarded. Filtering is active only if the
15268 		 * the ip_cgtp_filter ndd variable is non-zero.
15269 		 *
15270 		 * Only applies to the shared stack since the filter_ops
15271 		 * do not carry an ip_stack_t or zoneid.
15272 		 */
15273 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15274 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
15275 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
15276 			cgtp_flt_pkt =
15277 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15278 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15279 				freemsg(first_mp);
15280 				continue;
15281 			}
15282 		}
15283 
15284 		/*
15285 		 * If rsvpd is running, let RSVP daemon handle its processing
15286 		 * and forwarding of RSVP multicast/unicast packets.
15287 		 * If rsvpd is not running but mrouted is running, RSVP
15288 		 * multicast packets are forwarded as multicast traffic
15289 		 * and RSVP unicast packets are forwarded by unicast router.
15290 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15291 		 * packets are not forwarded, but the unicast packets are
15292 		 * forwarded like unicast traffic.
15293 		 */
15294 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15295 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15296 		    NULL) {
15297 			/* RSVP packet and rsvpd running. Treat as ours */
15298 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15299 			/*
15300 			 * This assumes that we deliver to all streams for
15301 			 * multicast and broadcast packets.
15302 			 * We have to force ll_multicast to 1 to handle the
15303 			 * M_DATA messages passed in from ip_mroute_decap.
15304 			 */
15305 			dst = INADDR_BROADCAST;
15306 			ll_multicast = 1;
15307 		} else if (CLASSD(dst)) {
15308 			/* packet is multicast */
15309 			mp->b_next = NULL;
15310 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15311 			    &ll_multicast, &dst))
15312 				continue;
15313 		}
15314 
15315 
15316 		/*
15317 		 * Check if the packet is coming from the Mobile IP
15318 		 * forward tunnel interface
15319 		 */
15320 		if (ill->ill_srcif_refcnt > 0) {
15321 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15322 			    NULL, ill, MATCH_IRE_TYPE);
15323 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15324 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15325 
15326 				/* We need to resolve the link layer info */
15327 				ire_refrele(ire);
15328 				ire = NULL;
15329 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15330 				    ll_multicast, dst);
15331 				continue;
15332 			}
15333 		}
15334 
15335 		if (ire == NULL) {
15336 			ire = ire_cache_lookup(dst, ALL_ZONES,
15337 			    MBLK_GETLABEL(mp), ipst);
15338 		}
15339 
15340 		/*
15341 		 * If mipagent is running and reverse tunnel is created as per
15342 		 * mobile node request, then any packet coming through the
15343 		 * incoming interface from the mobile-node, should be reverse
15344 		 * tunneled to it's home agent except those that are destined
15345 		 * to foreign agent only.
15346 		 * This needs source address based ire lookup. The routing
15347 		 * entries for source address based lookup are only created by
15348 		 * mipagent program only when a reverse tunnel is created.
15349 		 * Reference : RFC2002, RFC2344
15350 		 */
15351 		if (ill->ill_mrtun_refcnt > 0) {
15352 			ipaddr_t	srcaddr;
15353 			ire_t		*tmp_ire;
15354 
15355 			tmp_ire = ire;	/* Save, we might need it later */
15356 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15357 			    ire->ire_type != IRE_BROADCAST)) {
15358 				srcaddr = ipha->ipha_src;
15359 				ire = ire_mrtun_lookup(srcaddr, ill);
15360 				if (ire != NULL) {
15361 					/*
15362 					 * Should not be getting iphada packet
15363 					 * here. we should only get those for
15364 					 * IRE_LOCAL traffic, excluded above.
15365 					 * Fail-safe (drop packet) in the event
15366 					 * hardware is misbehaving.
15367 					 */
15368 					if (first_mp != mp) {
15369 						/* IPsec KSTATS: beancount me */
15370 						freemsg(first_mp);
15371 					} else {
15372 						/*
15373 						 * This packet must be forwarded
15374 						 * to Reverse Tunnel
15375 						 */
15376 						ip_mrtun_forward(ire, ill, mp);
15377 					}
15378 					ire_refrele(ire);
15379 					ire = NULL;
15380 					if (tmp_ire != NULL) {
15381 						ire_refrele(tmp_ire);
15382 						tmp_ire = NULL;
15383 					}
15384 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15385 					    "ip_input_end: q %p (%S)",
15386 					    q, "uninit");
15387 					continue;
15388 				}
15389 			}
15390 			/*
15391 			 * If this packet is from a non-mobilenode  or a
15392 			 * mobile-node which does not request reverse
15393 			 * tunnel service
15394 			 */
15395 			ire = tmp_ire;
15396 		}
15397 
15398 
15399 		/*
15400 		 * If we reach here that means the incoming packet satisfies
15401 		 * one of the following conditions:
15402 		 *   - packet is from a mobile node which does not request
15403 		 *	reverse tunnel
15404 		 *   - packet is from a non-mobile node, which is the most
15405 		 *	common case
15406 		 *   - packet is from a reverse tunnel enabled mobile node
15407 		 *	and destined to foreign agent only
15408 		 */
15409 
15410 		if (ire == NULL) {
15411 			/*
15412 			 * No IRE for this destination, so it can't be for us.
15413 			 * Unless we are forwarding, drop the packet.
15414 			 * We have to let source routed packets through
15415 			 * since we don't yet know if they are 'ping -l'
15416 			 * packets i.e. if they will go out over the
15417 			 * same interface as they came in on.
15418 			 */
15419 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15420 			if (ire == NULL)
15421 				continue;
15422 		}
15423 
15424 		/*
15425 		 * Broadcast IRE may indicate either broadcast or
15426 		 * multicast packet
15427 		 */
15428 		if (ire->ire_type == IRE_BROADCAST) {
15429 			/*
15430 			 * Skip broadcast checks if packet is UDP multicast;
15431 			 * we'd rather not enter ip_rput_process_broadcast()
15432 			 * unless the packet is broadcast for real, since
15433 			 * that routine is a no-op for multicast.
15434 			 */
15435 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15436 			    !CLASSD(ipha->ipha_dst)) {
15437 				ire = ip_rput_process_broadcast(&q, mp,
15438 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15439 				    ll_multicast);
15440 				if (ire == NULL)
15441 					continue;
15442 			}
15443 		} else if (ire->ire_stq != NULL) {
15444 			/* fowarding? */
15445 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15446 			    ll_multicast);
15447 			/* ip_rput_process_forward consumed the packet */
15448 			continue;
15449 		}
15450 
15451 local:
15452 		/*
15453 		 * If the queue in the ire is different to the ingress queue
15454 		 * then we need to check to see if we can accept the packet.
15455 		 * Note that for multicast packets and broadcast packets sent
15456 		 * to a broadcast address which is shared between multiple
15457 		 * interfaces we should not do this since we just got a random
15458 		 * broadcast ire.
15459 		 */
15460 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15461 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15462 			    ill)) == NULL) {
15463 				/* Drop packet */
15464 				BUMP_MIB(ill->ill_ip_mib,
15465 				    ipIfStatsForwProhibits);
15466 				freemsg(mp);
15467 				continue;
15468 			}
15469 			if (ire->ire_rfq != NULL)
15470 				q = ire->ire_rfq;
15471 		}
15472 
15473 		switch (ipha->ipha_protocol) {
15474 		case IPPROTO_TCP:
15475 			ASSERT(first_mp == mp);
15476 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15477 				mp, 0, q, ip_ring)) != NULL) {
15478 				if (curr_sqp == NULL) {
15479 					curr_sqp = GET_SQUEUE(mp);
15480 					ASSERT(cnt == 0);
15481 					cnt++;
15482 					head = tail = mp;
15483 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15484 					ASSERT(tail != NULL);
15485 					cnt++;
15486 					tail->b_next = mp;
15487 					tail = mp;
15488 				} else {
15489 					/*
15490 					 * A different squeue. Send the
15491 					 * chain for the previous squeue on
15492 					 * its way. This shouldn't happen
15493 					 * often unless interrupt binding
15494 					 * changes.
15495 					 */
15496 					IP_STAT(ipst, ip_input_multi_squeue);
15497 					squeue_enter_chain(curr_sqp, head,
15498 					    tail, cnt, SQTAG_IP_INPUT);
15499 					curr_sqp = GET_SQUEUE(mp);
15500 					head = mp;
15501 					tail = mp;
15502 					cnt = 1;
15503 				}
15504 			}
15505 			continue;
15506 		case IPPROTO_UDP:
15507 			ASSERT(first_mp == mp);
15508 			ip_udp_input(q, mp, ipha, ire, ill);
15509 			continue;
15510 		case IPPROTO_SCTP:
15511 			ASSERT(first_mp == mp);
15512 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15513 			    q, dst);
15514 			/* ire has been released by ip_sctp_input */
15515 			ire = NULL;
15516 			continue;
15517 		default:
15518 			ip_proto_input(q, first_mp, ipha, ire, ill);
15519 			continue;
15520 		}
15521 	}
15522 
15523 	if (ire != NULL)
15524 		ire_refrele(ire);
15525 
15526 	if (head != NULL)
15527 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15528 
15529 	/*
15530 	 * This code is there just to make netperf/ttcp look good.
15531 	 *
15532 	 * Its possible that after being in polling mode (and having cleared
15533 	 * the backlog), squeues have turned the interrupt frequency higher
15534 	 * to improve latency at the expense of more CPU utilization (less
15535 	 * packets per interrupts or more number of interrupts). Workloads
15536 	 * like ttcp/netperf do manage to tickle polling once in a while
15537 	 * but for the remaining time, stay in higher interrupt mode since
15538 	 * their packet arrival rate is pretty uniform and this shows up
15539 	 * as higher CPU utilization. Since people care about CPU utilization
15540 	 * while running netperf/ttcp, turn the interrupt frequency back to
15541 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15542 	 */
15543 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15544 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15545 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15546 			ip_ring->rr_blank(ip_ring->rr_handle,
15547 			    ip_ring->rr_normal_blank_time,
15548 			    ip_ring->rr_normal_pkt_cnt);
15549 		}
15550 		}
15551 
15552 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15553 	    "ip_input_end: q %p (%S)", q, "end");
15554 #undef  rptr
15555 }
15556 
15557 static void
15558 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15559     t_uscalar_t err)
15560 {
15561 	if (dl_err == DL_SYSERR) {
15562 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15563 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15564 		    ill->ill_name, dlpi_prim_str(prim), err);
15565 		return;
15566 	}
15567 
15568 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15569 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15570 	    dlpi_err_str(dl_err));
15571 }
15572 
15573 /*
15574  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15575  * than DL_UNITDATA_IND messages. If we need to process this message
15576  * exclusively, we call qwriter_ip, in which case we also need to call
15577  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15578  */
15579 void
15580 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15581 {
15582 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15583 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15584 	ill_t		*ill;
15585 
15586 	ip1dbg(("ip_rput_dlpi"));
15587 	ill = (ill_t *)q->q_ptr;
15588 	switch (dloa->dl_primitive) {
15589 	case DL_ERROR_ACK:
15590 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15591 		    "%s (0x%x), unix %u\n", ill->ill_name,
15592 		    dlpi_prim_str(dlea->dl_error_primitive),
15593 		    dlea->dl_error_primitive,
15594 		    dlpi_err_str(dlea->dl_errno),
15595 		    dlea->dl_errno,
15596 		    dlea->dl_unix_errno));
15597 		switch (dlea->dl_error_primitive) {
15598 		case DL_UNBIND_REQ:
15599 			mutex_enter(&ill->ill_lock);
15600 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15601 			cv_signal(&ill->ill_cv);
15602 			mutex_exit(&ill->ill_lock);
15603 			/* FALLTHRU */
15604 		case DL_NOTIFY_REQ:
15605 		case DL_ATTACH_REQ:
15606 		case DL_DETACH_REQ:
15607 		case DL_INFO_REQ:
15608 		case DL_BIND_REQ:
15609 		case DL_ENABMULTI_REQ:
15610 		case DL_PHYS_ADDR_REQ:
15611 		case DL_CAPABILITY_REQ:
15612 		case DL_CONTROL_REQ:
15613 			/*
15614 			 * Refhold the ill to match qwriter_ip which does a
15615 			 * refrele. Since this is on the ill stream we
15616 			 * unconditionally bump up the refcount without
15617 			 * checking for ILL_CAN_LOOKUP
15618 			 */
15619 			ill_refhold(ill);
15620 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15621 			    CUR_OP, B_FALSE);
15622 			return;
15623 		case DL_DISABMULTI_REQ:
15624 			freemsg(mp);	/* Don't want to pass this up */
15625 			return;
15626 		default:
15627 			break;
15628 		}
15629 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15630 		    dlea->dl_errno, dlea->dl_unix_errno);
15631 		freemsg(mp);
15632 		return;
15633 	case DL_INFO_ACK:
15634 	case DL_BIND_ACK:
15635 	case DL_PHYS_ADDR_ACK:
15636 	case DL_NOTIFY_ACK:
15637 	case DL_CAPABILITY_ACK:
15638 	case DL_CONTROL_ACK:
15639 		/*
15640 		 * Refhold the ill to match qwriter_ip which does a refrele
15641 		 * Since this is on the ill stream we unconditionally
15642 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15643 		 */
15644 		ill_refhold(ill);
15645 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15646 		    CUR_OP, B_FALSE);
15647 		return;
15648 	case DL_NOTIFY_IND:
15649 		ill_refhold(ill);
15650 		/*
15651 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15652 		 * relation to the current ioctl in progress (if any). Hence we
15653 		 * pass in NEW_OP in this case.
15654 		 */
15655 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15656 		    NEW_OP, B_FALSE);
15657 		return;
15658 	case DL_OK_ACK:
15659 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15660 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15661 		switch (dloa->dl_correct_primitive) {
15662 		case DL_UNBIND_REQ:
15663 			mutex_enter(&ill->ill_lock);
15664 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15665 			cv_signal(&ill->ill_cv);
15666 			mutex_exit(&ill->ill_lock);
15667 			/* FALLTHRU */
15668 		case DL_ATTACH_REQ:
15669 		case DL_DETACH_REQ:
15670 			/*
15671 			 * Refhold the ill to match qwriter_ip which does a
15672 			 * refrele. Since this is on the ill stream we
15673 			 * unconditionally bump up the refcount
15674 			 */
15675 			ill_refhold(ill);
15676 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15677 			    CUR_OP, B_FALSE);
15678 			return;
15679 		case DL_ENABMULTI_REQ:
15680 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15681 				ill->ill_dlpi_multicast_state = IDS_OK;
15682 			break;
15683 
15684 		}
15685 		break;
15686 	default:
15687 		break;
15688 	}
15689 	freemsg(mp);
15690 }
15691 
15692 /*
15693  * Handling of DLPI messages that require exclusive access to the ipsq.
15694  *
15695  * Need to do ill_pending_mp_release on ioctl completion, which could
15696  * happen here. (along with mi_copy_done)
15697  */
15698 /* ARGSUSED */
15699 static void
15700 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15701 {
15702 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15703 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15704 	int		err = 0;
15705 	ill_t		*ill;
15706 	ipif_t		*ipif = NULL;
15707 	mblk_t		*mp1 = NULL;
15708 	conn_t		*connp = NULL;
15709 	t_uscalar_t	paddrreq;
15710 	mblk_t		*mp_hw;
15711 	boolean_t	success;
15712 	boolean_t	ioctl_aborted = B_FALSE;
15713 	boolean_t	log = B_TRUE;
15714 	hook_nic_event_t	*info;
15715 	ip_stack_t		*ipst;
15716 
15717 	ip1dbg(("ip_rput_dlpi_writer .."));
15718 	ill = (ill_t *)q->q_ptr;
15719 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15720 
15721 	ASSERT(IAM_WRITER_ILL(ill));
15722 
15723 	ipst = ill->ill_ipst;
15724 
15725 	/*
15726 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15727 	 * both are null or non-null. However we can assert that only
15728 	 * after grabbing the ipsq_lock. So we don't make any assertion
15729 	 * here and in other places in the code.
15730 	 */
15731 	ipif = ipsq->ipsq_pending_ipif;
15732 	/*
15733 	 * The current ioctl could have been aborted by the user and a new
15734 	 * ioctl to bring up another ill could have started. We could still
15735 	 * get a response from the driver later.
15736 	 */
15737 	if (ipif != NULL && ipif->ipif_ill != ill)
15738 		ioctl_aborted = B_TRUE;
15739 
15740 	switch (dloa->dl_primitive) {
15741 	case DL_ERROR_ACK:
15742 		switch (dlea->dl_error_primitive) {
15743 		case DL_UNBIND_REQ:
15744 		case DL_ATTACH_REQ:
15745 		case DL_DETACH_REQ:
15746 		case DL_INFO_REQ:
15747 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15748 			break;
15749 		case DL_NOTIFY_REQ:
15750 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15751 			log = B_FALSE;
15752 			break;
15753 		case DL_PHYS_ADDR_REQ:
15754 			/*
15755 			 * For IPv6 only, there are two additional
15756 			 * phys_addr_req's sent to the driver to get the
15757 			 * IPv6 token and lla. This allows IP to acquire
15758 			 * the hardware address format for a given interface
15759 			 * without having built in knowledge of the hardware
15760 			 * address. ill_phys_addr_pend keeps track of the last
15761 			 * DL_PAR sent so we know which response we are
15762 			 * dealing with. ill_dlpi_done will update
15763 			 * ill_phys_addr_pend when it sends the next req.
15764 			 * We don't complete the IOCTL until all three DL_PARs
15765 			 * have been attempted, so set *_len to 0 and break.
15766 			 */
15767 			paddrreq = ill->ill_phys_addr_pend;
15768 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15769 			if (paddrreq == DL_IPV6_TOKEN) {
15770 				ill->ill_token_length = 0;
15771 				log = B_FALSE;
15772 				break;
15773 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15774 				ill->ill_nd_lla_len = 0;
15775 				log = B_FALSE;
15776 				break;
15777 			}
15778 			/*
15779 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15780 			 * We presumably have an IOCTL hanging out waiting
15781 			 * for completion. Find it and complete the IOCTL
15782 			 * with the error noted.
15783 			 * However, ill_dl_phys was called on an ill queue
15784 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15785 			 * set. But the ioctl is known to be pending on ill_wq.
15786 			 */
15787 			if (!ill->ill_ifname_pending)
15788 				break;
15789 			ill->ill_ifname_pending = 0;
15790 			if (!ioctl_aborted)
15791 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15792 			if (mp1 != NULL) {
15793 				/*
15794 				 * This operation (SIOCSLIFNAME) must have
15795 				 * happened on the ill. Assert there is no conn
15796 				 */
15797 				ASSERT(connp == NULL);
15798 				q = ill->ill_wq;
15799 			}
15800 			break;
15801 		case DL_BIND_REQ:
15802 			ill_dlpi_done(ill, DL_BIND_REQ);
15803 			if (ill->ill_ifname_pending)
15804 				break;
15805 			/*
15806 			 * Something went wrong with the bind.  We presumably
15807 			 * have an IOCTL hanging out waiting for completion.
15808 			 * Find it, take down the interface that was coming
15809 			 * up, and complete the IOCTL with the error noted.
15810 			 */
15811 			if (!ioctl_aborted)
15812 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15813 			if (mp1 != NULL) {
15814 				/*
15815 				 * This operation (SIOCSLIFFLAGS) must have
15816 				 * happened from a conn.
15817 				 */
15818 				ASSERT(connp != NULL);
15819 				q = CONNP_TO_WQ(connp);
15820 				if (ill->ill_move_in_progress) {
15821 					ILL_CLEAR_MOVE(ill);
15822 				}
15823 				(void) ipif_down(ipif, NULL, NULL);
15824 				/* error is set below the switch */
15825 			}
15826 			break;
15827 		case DL_ENABMULTI_REQ:
15828 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15829 
15830 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15831 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15832 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15833 				ipif_t *ipif;
15834 
15835 				log = B_FALSE;
15836 				printf("ip: joining multicasts failed (%d)"
15837 				    " on %s - will use link layer "
15838 				    "broadcasts for multicast\n",
15839 				    dlea->dl_errno, ill->ill_name);
15840 
15841 				/*
15842 				 * Set up the multicast mapping alone.
15843 				 * writer, so ok to access ill->ill_ipif
15844 				 * without any lock.
15845 				 */
15846 				ipif = ill->ill_ipif;
15847 				mutex_enter(&ill->ill_phyint->phyint_lock);
15848 				ill->ill_phyint->phyint_flags |=
15849 				    PHYI_MULTI_BCAST;
15850 				mutex_exit(&ill->ill_phyint->phyint_lock);
15851 
15852 				if (!ill->ill_isv6) {
15853 					(void) ipif_arp_setup_multicast(ipif,
15854 					    NULL);
15855 				} else {
15856 					(void) ipif_ndp_setup_multicast(ipif,
15857 					    NULL);
15858 				}
15859 			}
15860 			freemsg(mp);	/* Don't want to pass this up */
15861 			return;
15862 		case DL_CAPABILITY_REQ:
15863 		case DL_CONTROL_REQ:
15864 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15865 			    "DL_CAPABILITY/CONTROL REQ\n"));
15866 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15867 			ill->ill_dlpi_capab_state = IDS_FAILED;
15868 			freemsg(mp);
15869 			return;
15870 		}
15871 		/*
15872 		 * Note the error for IOCTL completion (mp1 is set when
15873 		 * ready to complete ioctl). If ill_ifname_pending_err is
15874 		 * set, an error occured during plumbing (ill_ifname_pending),
15875 		 * so we want to report that error.
15876 		 *
15877 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15878 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15879 		 * expected to get errack'd if the driver doesn't support
15880 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15881 		 * if these error conditions are encountered.
15882 		 */
15883 		if (mp1 != NULL) {
15884 			if (ill->ill_ifname_pending_err != 0)  {
15885 				err = ill->ill_ifname_pending_err;
15886 				ill->ill_ifname_pending_err = 0;
15887 			} else {
15888 				err = dlea->dl_unix_errno ?
15889 				    dlea->dl_unix_errno : ENXIO;
15890 			}
15891 		/*
15892 		 * If we're plumbing an interface and an error hasn't already
15893 		 * been saved, set ill_ifname_pending_err to the error passed
15894 		 * up. Ignore the error if log is B_FALSE (see comment above).
15895 		 */
15896 		} else if (log && ill->ill_ifname_pending &&
15897 		    ill->ill_ifname_pending_err == 0) {
15898 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15899 			dlea->dl_unix_errno : ENXIO;
15900 		}
15901 
15902 		if (log)
15903 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15904 			    dlea->dl_errno, dlea->dl_unix_errno);
15905 		break;
15906 	case DL_CAPABILITY_ACK: {
15907 		boolean_t reneg_flag = B_FALSE;
15908 		/* Call a routine to handle this one. */
15909 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15910 		/*
15911 		 * Check if the ACK is due to renegotiation case since we
15912 		 * will need to send a new CAPABILITY_REQ later.
15913 		 */
15914 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15915 			/* This is the ack for a renogiation case */
15916 			reneg_flag = B_TRUE;
15917 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15918 		}
15919 		ill_capability_ack(ill, mp);
15920 		if (reneg_flag)
15921 			ill_capability_probe(ill);
15922 		break;
15923 	}
15924 	case DL_CONTROL_ACK:
15925 		/* We treat all of these as "fire and forget" */
15926 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15927 		break;
15928 	case DL_INFO_ACK:
15929 		/* Call a routine to handle this one. */
15930 		ill_dlpi_done(ill, DL_INFO_REQ);
15931 		ip_ll_subnet_defaults(ill, mp);
15932 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15933 		return;
15934 	case DL_BIND_ACK:
15935 		/*
15936 		 * We should have an IOCTL waiting on this unless
15937 		 * sent by ill_dl_phys, in which case just return
15938 		 */
15939 		ill_dlpi_done(ill, DL_BIND_REQ);
15940 		if (ill->ill_ifname_pending)
15941 			break;
15942 
15943 		if (!ioctl_aborted)
15944 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15945 		if (mp1 == NULL)
15946 			break;
15947 		/*
15948 		 * Because mp1 was added by ill_dl_up(), and it always
15949 		 * passes a valid connp, connp must be valid here.
15950 		 */
15951 		ASSERT(connp != NULL);
15952 		q = CONNP_TO_WQ(connp);
15953 
15954 		/*
15955 		 * We are exclusive. So nothing can change even after
15956 		 * we get the pending mp. If need be we can put it back
15957 		 * and restart, as in calling ipif_arp_up()  below.
15958 		 */
15959 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15960 
15961 		mutex_enter(&ill->ill_lock);
15962 
15963 		ill->ill_dl_up = 1;
15964 
15965 		if ((info = ill->ill_nic_event_info) != NULL) {
15966 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15967 			    "attached for %s\n", info->hne_event,
15968 			    ill->ill_name));
15969 			if (info->hne_data != NULL)
15970 				kmem_free(info->hne_data, info->hne_datalen);
15971 			kmem_free(info, sizeof (hook_nic_event_t));
15972 		}
15973 
15974 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15975 		if (info != NULL) {
15976 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15977 			info->hne_lif = 0;
15978 			info->hne_event = NE_UP;
15979 			info->hne_data = NULL;
15980 			info->hne_datalen = 0;
15981 			info->hne_family = ill->ill_isv6 ?
15982 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15983 		} else
15984 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15985 			    "event information for %s (ENOMEM)\n",
15986 			    ill->ill_name));
15987 
15988 		ill->ill_nic_event_info = info;
15989 
15990 		mutex_exit(&ill->ill_lock);
15991 
15992 		/*
15993 		 * Now bring up the resolver; when that is complete, we'll
15994 		 * create IREs.  Note that we intentionally mirror what
15995 		 * ipif_up() would have done, because we got here by way of
15996 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15997 		 */
15998 		if (ill->ill_isv6) {
15999 			/*
16000 			 * v6 interfaces.
16001 			 * Unlike ARP which has to do another bind
16002 			 * and attach, once we get here we are
16003 			 * done with NDP. Except in the case of
16004 			 * ILLF_XRESOLV, in which case we send an
16005 			 * AR_INTERFACE_UP to the external resolver.
16006 			 * If all goes well, the ioctl will complete
16007 			 * in ip_rput(). If there's an error, we
16008 			 * complete it here.
16009 			 */
16010 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
16011 			if (err == 0) {
16012 				if (ill->ill_flags & ILLF_XRESOLV) {
16013 					mutex_enter(&connp->conn_lock);
16014 					mutex_enter(&ill->ill_lock);
16015 					success = ipsq_pending_mp_add(
16016 					    connp, ipif, q, mp1, 0);
16017 					mutex_exit(&ill->ill_lock);
16018 					mutex_exit(&connp->conn_lock);
16019 					if (success) {
16020 						err = ipif_resolver_up(ipif,
16021 						    Res_act_initial);
16022 						if (err == EINPROGRESS) {
16023 							freemsg(mp);
16024 							return;
16025 						}
16026 						ASSERT(err != 0);
16027 						mp1 = ipsq_pending_mp_get(ipsq,
16028 						    &connp);
16029 						ASSERT(mp1 != NULL);
16030 					} else {
16031 						/* conn has started closing */
16032 						err = EINTR;
16033 					}
16034 				} else { /* Non XRESOLV interface */
16035 					(void) ipif_resolver_up(ipif,
16036 					    Res_act_initial);
16037 					err = ipif_up_done_v6(ipif);
16038 				}
16039 			}
16040 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16041 			/*
16042 			 * ARP and other v4 external resolvers.
16043 			 * Leave the pending mblk intact so that
16044 			 * the ioctl completes in ip_rput().
16045 			 */
16046 			mutex_enter(&connp->conn_lock);
16047 			mutex_enter(&ill->ill_lock);
16048 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16049 			mutex_exit(&ill->ill_lock);
16050 			mutex_exit(&connp->conn_lock);
16051 			if (success) {
16052 				err = ipif_resolver_up(ipif, Res_act_initial);
16053 				if (err == EINPROGRESS) {
16054 					freemsg(mp);
16055 					return;
16056 				}
16057 				ASSERT(err != 0);
16058 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16059 			} else {
16060 				/* The conn has started closing */
16061 				err = EINTR;
16062 			}
16063 		} else {
16064 			/*
16065 			 * This one is complete. Reply to pending ioctl.
16066 			 */
16067 			(void) ipif_resolver_up(ipif, Res_act_initial);
16068 			err = ipif_up_done(ipif);
16069 		}
16070 
16071 		if ((err == 0) && (ill->ill_up_ipifs)) {
16072 			err = ill_up_ipifs(ill, q, mp1);
16073 			if (err == EINPROGRESS) {
16074 				freemsg(mp);
16075 				return;
16076 			}
16077 		}
16078 
16079 		if (ill->ill_up_ipifs) {
16080 			ill_group_cleanup(ill);
16081 		}
16082 
16083 		break;
16084 	case DL_NOTIFY_IND: {
16085 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16086 		ire_t *ire;
16087 		boolean_t need_ire_walk_v4 = B_FALSE;
16088 		boolean_t need_ire_walk_v6 = B_FALSE;
16089 
16090 		switch (notify->dl_notification) {
16091 		case DL_NOTE_PHYS_ADDR:
16092 			err = ill_set_phys_addr(ill, mp);
16093 			break;
16094 
16095 		case DL_NOTE_FASTPATH_FLUSH:
16096 			ill_fastpath_flush(ill);
16097 			break;
16098 
16099 		case DL_NOTE_SDU_SIZE:
16100 			/*
16101 			 * Change the MTU size of the interface, of all
16102 			 * attached ipif's, and of all relevant ire's.  The
16103 			 * new value's a uint32_t at notify->dl_data.
16104 			 * Mtu change Vs. new ire creation - protocol below.
16105 			 *
16106 			 * a Mark the ipif as IPIF_CHANGING.
16107 			 * b Set the new mtu in the ipif.
16108 			 * c Change the ire_max_frag on all affected ires
16109 			 * d Unmark the IPIF_CHANGING
16110 			 *
16111 			 * To see how the protocol works, assume an interface
16112 			 * route is also being added simultaneously by
16113 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16114 			 * the ire. If the ire is created before step a,
16115 			 * it will be cleaned up by step c. If the ire is
16116 			 * created after step d, it will see the new value of
16117 			 * ipif_mtu. Any attempt to create the ire between
16118 			 * steps a to d will fail because of the IPIF_CHANGING
16119 			 * flag. Note that ire_create() is passed a pointer to
16120 			 * the ipif_mtu, and not the value. During ire_add
16121 			 * under the bucket lock, the ire_max_frag of the
16122 			 * new ire being created is set from the ipif/ire from
16123 			 * which it is being derived.
16124 			 */
16125 			mutex_enter(&ill->ill_lock);
16126 			ill->ill_max_frag = (uint_t)notify->dl_data;
16127 
16128 			/*
16129 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16130 			 * leave it alone
16131 			 */
16132 			if (ill->ill_mtu_userspecified) {
16133 				mutex_exit(&ill->ill_lock);
16134 				break;
16135 			}
16136 			ill->ill_max_mtu = ill->ill_max_frag;
16137 			if (ill->ill_isv6) {
16138 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16139 					ill->ill_max_mtu = IPV6_MIN_MTU;
16140 			} else {
16141 				if (ill->ill_max_mtu < IP_MIN_MTU)
16142 					ill->ill_max_mtu = IP_MIN_MTU;
16143 			}
16144 			for (ipif = ill->ill_ipif; ipif != NULL;
16145 			    ipif = ipif->ipif_next) {
16146 				/*
16147 				 * Don't override the mtu if the user
16148 				 * has explicitly set it.
16149 				 */
16150 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16151 					continue;
16152 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16153 				if (ipif->ipif_isv6)
16154 					ire = ipif_to_ire_v6(ipif);
16155 				else
16156 					ire = ipif_to_ire(ipif);
16157 				if (ire != NULL) {
16158 					ire->ire_max_frag = ipif->ipif_mtu;
16159 					ire_refrele(ire);
16160 				}
16161 				if (ipif->ipif_flags & IPIF_UP) {
16162 					if (ill->ill_isv6)
16163 						need_ire_walk_v6 = B_TRUE;
16164 					else
16165 						need_ire_walk_v4 = B_TRUE;
16166 				}
16167 			}
16168 			mutex_exit(&ill->ill_lock);
16169 			if (need_ire_walk_v4)
16170 				ire_walk_v4(ill_mtu_change, (char *)ill,
16171 				    ALL_ZONES, ipst);
16172 			if (need_ire_walk_v6)
16173 				ire_walk_v6(ill_mtu_change, (char *)ill,
16174 				    ALL_ZONES, ipst);
16175 			break;
16176 		case DL_NOTE_LINK_UP:
16177 		case DL_NOTE_LINK_DOWN: {
16178 			/*
16179 			 * We are writer. ill / phyint / ipsq assocs stable.
16180 			 * The RUNNING flag reflects the state of the link.
16181 			 */
16182 			phyint_t *phyint = ill->ill_phyint;
16183 			uint64_t new_phyint_flags;
16184 			boolean_t changed = B_FALSE;
16185 			boolean_t went_up;
16186 
16187 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16188 			mutex_enter(&phyint->phyint_lock);
16189 			new_phyint_flags = went_up ?
16190 			    phyint->phyint_flags | PHYI_RUNNING :
16191 			    phyint->phyint_flags & ~PHYI_RUNNING;
16192 			if (new_phyint_flags != phyint->phyint_flags) {
16193 				phyint->phyint_flags = new_phyint_flags;
16194 				changed = B_TRUE;
16195 			}
16196 			mutex_exit(&phyint->phyint_lock);
16197 			/*
16198 			 * ill_restart_dad handles the DAD restart and routing
16199 			 * socket notification logic.
16200 			 */
16201 			if (changed) {
16202 				ill_restart_dad(phyint->phyint_illv4, went_up);
16203 				ill_restart_dad(phyint->phyint_illv6, went_up);
16204 			}
16205 			break;
16206 		}
16207 		case DL_NOTE_PROMISC_ON_PHYS:
16208 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16209 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16210 			mutex_enter(&ill->ill_lock);
16211 			ill->ill_promisc_on_phys = B_TRUE;
16212 			mutex_exit(&ill->ill_lock);
16213 			break;
16214 		case DL_NOTE_PROMISC_OFF_PHYS:
16215 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16216 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16217 			mutex_enter(&ill->ill_lock);
16218 			ill->ill_promisc_on_phys = B_FALSE;
16219 			mutex_exit(&ill->ill_lock);
16220 			break;
16221 		case DL_NOTE_CAPAB_RENEG:
16222 			/*
16223 			 * Something changed on the driver side.
16224 			 * It wants us to renegotiate the capabilities
16225 			 * on this ill. The most likely cause is the
16226 			 * aggregation interface under us where a
16227 			 * port got added or went away.
16228 			 *
16229 			 * We reset the capabilities and set the
16230 			 * state to IDS_RENG so that when the ack
16231 			 * comes back, we can start the
16232 			 * renegotiation process.
16233 			 */
16234 			ill_capability_reset(ill);
16235 			ill->ill_dlpi_capab_state = IDS_RENEG;
16236 			break;
16237 		default:
16238 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16239 			    "type 0x%x for DL_NOTIFY_IND\n",
16240 			    notify->dl_notification));
16241 			break;
16242 		}
16243 
16244 		/*
16245 		 * As this is an asynchronous operation, we
16246 		 * should not call ill_dlpi_done
16247 		 */
16248 		break;
16249 	}
16250 	case DL_NOTIFY_ACK: {
16251 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16252 
16253 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16254 			ill->ill_note_link = 1;
16255 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16256 		break;
16257 	}
16258 	case DL_PHYS_ADDR_ACK: {
16259 		/*
16260 		 * As part of plumbing the interface via SIOCSLIFNAME,
16261 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16262 		 * whose answers we receive here.  As each answer is received,
16263 		 * we call ill_dlpi_done() to dispatch the next request as
16264 		 * we're processing the current one.  Once all answers have
16265 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16266 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16267 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16268 		 * available, but we know the ioctl is pending on ill_wq.)
16269 		 */
16270 		uint_t paddrlen, paddroff;
16271 
16272 		paddrreq = ill->ill_phys_addr_pend;
16273 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16274 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16275 
16276 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16277 		if (paddrreq == DL_IPV6_TOKEN) {
16278 			/*
16279 			 * bcopy to low-order bits of ill_token
16280 			 *
16281 			 * XXX Temporary hack - currently, all known tokens
16282 			 * are 64 bits, so I'll cheat for the moment.
16283 			 */
16284 			bcopy(mp->b_rptr + paddroff,
16285 			    &ill->ill_token.s6_addr32[2], paddrlen);
16286 			ill->ill_token_length = paddrlen;
16287 			break;
16288 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16289 			ASSERT(ill->ill_nd_lla_mp == NULL);
16290 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16291 			mp = NULL;
16292 			break;
16293 		}
16294 
16295 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16296 		ASSERT(ill->ill_phys_addr_mp == NULL);
16297 		if (!ill->ill_ifname_pending)
16298 			break;
16299 		ill->ill_ifname_pending = 0;
16300 		if (!ioctl_aborted)
16301 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16302 		if (mp1 != NULL) {
16303 			ASSERT(connp == NULL);
16304 			q = ill->ill_wq;
16305 		}
16306 		/*
16307 		 * If any error acks received during the plumbing sequence,
16308 		 * ill_ifname_pending_err will be set. Break out and send up
16309 		 * the error to the pending ioctl.
16310 		 */
16311 		if (ill->ill_ifname_pending_err != 0) {
16312 			err = ill->ill_ifname_pending_err;
16313 			ill->ill_ifname_pending_err = 0;
16314 			break;
16315 		}
16316 
16317 		ill->ill_phys_addr_mp = mp;
16318 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16319 		mp = NULL;
16320 
16321 		/*
16322 		 * If paddrlen is zero, the DLPI provider doesn't support
16323 		 * physical addresses.  The other two tests were historical
16324 		 * workarounds for bugs in our former PPP implementation, but
16325 		 * now other things have grown dependencies on them -- e.g.,
16326 		 * the tun module specifies a dl_addr_length of zero in its
16327 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16328 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16329 		 * but only after careful testing ensures that all dependent
16330 		 * broken DLPI providers have been fixed.
16331 		 */
16332 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16333 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16334 			ill->ill_phys_addr = NULL;
16335 		} else if (paddrlen != ill->ill_phys_addr_length) {
16336 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16337 			    paddrlen, ill->ill_phys_addr_length));
16338 			err = EINVAL;
16339 			break;
16340 		}
16341 
16342 		if (ill->ill_nd_lla_mp == NULL) {
16343 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16344 				err = ENOMEM;
16345 				break;
16346 			}
16347 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16348 		}
16349 
16350 		/*
16351 		 * Set the interface token.  If the zeroth interface address
16352 		 * is unspecified, then set it to the link local address.
16353 		 */
16354 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16355 			(void) ill_setdefaulttoken(ill);
16356 
16357 		ASSERT(ill->ill_ipif->ipif_id == 0);
16358 		if (ipif != NULL &&
16359 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16360 			(void) ipif_setlinklocal(ipif);
16361 		}
16362 		break;
16363 	}
16364 	case DL_OK_ACK:
16365 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16366 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16367 		    dloa->dl_correct_primitive));
16368 		switch (dloa->dl_correct_primitive) {
16369 		case DL_UNBIND_REQ:
16370 		case DL_ATTACH_REQ:
16371 		case DL_DETACH_REQ:
16372 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16373 			break;
16374 		}
16375 		break;
16376 	default:
16377 		break;
16378 	}
16379 
16380 	freemsg(mp);
16381 	if (mp1 != NULL) {
16382 		/*
16383 		 * The operation must complete without EINPROGRESS
16384 		 * since ipsq_pending_mp_get() has removed the mblk
16385 		 * from ipsq_pending_mp.  Otherwise, the operation
16386 		 * will be stuck forever in the ipsq.
16387 		 */
16388 		ASSERT(err != EINPROGRESS);
16389 
16390 		switch (ipsq->ipsq_current_ioctl) {
16391 		case 0:
16392 			ipsq_current_finish(ipsq);
16393 			break;
16394 
16395 		case SIOCLIFADDIF:
16396 		case SIOCSLIFNAME:
16397 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16398 			break;
16399 
16400 		default:
16401 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16402 			break;
16403 		}
16404 	}
16405 }
16406 
16407 /*
16408  * ip_rput_other is called by ip_rput to handle messages modifying the global
16409  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16410  */
16411 /* ARGSUSED */
16412 void
16413 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16414 {
16415 	ill_t		*ill;
16416 	struct iocblk	*iocp;
16417 	mblk_t		*mp1;
16418 	conn_t		*connp = NULL;
16419 
16420 	ip1dbg(("ip_rput_other "));
16421 	ill = (ill_t *)q->q_ptr;
16422 	/*
16423 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16424 	 * in which case ipsq is NULL.
16425 	 */
16426 	if (ipsq != NULL) {
16427 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16428 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16429 	}
16430 
16431 	switch (mp->b_datap->db_type) {
16432 	case M_ERROR:
16433 	case M_HANGUP:
16434 		/*
16435 		 * The device has a problem.  We force the ILL down.  It can
16436 		 * be brought up again manually using SIOCSIFFLAGS (via
16437 		 * ifconfig or equivalent).
16438 		 */
16439 		ASSERT(ipsq != NULL);
16440 		if (mp->b_rptr < mp->b_wptr)
16441 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16442 		if (ill->ill_error == 0)
16443 			ill->ill_error = ENXIO;
16444 		if (!ill_down_start(q, mp))
16445 			return;
16446 		ipif_all_down_tail(ipsq, q, mp, NULL);
16447 		break;
16448 	case M_IOCACK:
16449 		iocp = (struct iocblk *)mp->b_rptr;
16450 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16451 		switch (iocp->ioc_cmd) {
16452 		case SIOCSTUNPARAM:
16453 		case OSIOCSTUNPARAM:
16454 			ASSERT(ipsq != NULL);
16455 			/*
16456 			 * Finish socket ioctl passed through to tun.
16457 			 * We should have an IOCTL waiting on this.
16458 			 */
16459 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16460 			if (ill->ill_isv6) {
16461 				struct iftun_req *ta;
16462 
16463 				/*
16464 				 * if a source or destination is
16465 				 * being set, try and set the link
16466 				 * local address for the tunnel
16467 				 */
16468 				ta = (struct iftun_req *)mp->b_cont->
16469 				    b_cont->b_rptr;
16470 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16471 					ipif_set_tun_llink(ill, ta);
16472 				}
16473 
16474 			}
16475 			if (mp1 != NULL) {
16476 				/*
16477 				 * Now copy back the b_next/b_prev used by
16478 				 * mi code for the mi_copy* functions.
16479 				 * See ip_sioctl_tunparam() for the reason.
16480 				 * Also protect against missing b_cont.
16481 				 */
16482 				if (mp->b_cont != NULL) {
16483 					mp->b_cont->b_next =
16484 					    mp1->b_cont->b_next;
16485 					mp->b_cont->b_prev =
16486 					    mp1->b_cont->b_prev;
16487 				}
16488 				inet_freemsg(mp1);
16489 				ASSERT(connp != NULL);
16490 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16491 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16492 			} else {
16493 				ASSERT(connp == NULL);
16494 				putnext(q, mp);
16495 			}
16496 			break;
16497 		case SIOCGTUNPARAM:
16498 		case OSIOCGTUNPARAM:
16499 			/*
16500 			 * This is really M_IOCDATA from the tunnel driver.
16501 			 * convert back and complete the ioctl.
16502 			 * We should have an IOCTL waiting on this.
16503 			 */
16504 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16505 			if (mp1) {
16506 				/*
16507 				 * Now copy back the b_next/b_prev used by
16508 				 * mi code for the mi_copy* functions.
16509 				 * See ip_sioctl_tunparam() for the reason.
16510 				 * Also protect against missing b_cont.
16511 				 */
16512 				if (mp->b_cont != NULL) {
16513 					mp->b_cont->b_next =
16514 					    mp1->b_cont->b_next;
16515 					mp->b_cont->b_prev =
16516 					    mp1->b_cont->b_prev;
16517 				}
16518 				inet_freemsg(mp1);
16519 				if (iocp->ioc_error == 0)
16520 					mp->b_datap->db_type = M_IOCDATA;
16521 				ASSERT(connp != NULL);
16522 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16523 				    iocp->ioc_error, COPYOUT, NULL);
16524 			} else {
16525 				ASSERT(connp == NULL);
16526 				putnext(q, mp);
16527 			}
16528 			break;
16529 		default:
16530 			break;
16531 		}
16532 		break;
16533 	case M_IOCNAK:
16534 		iocp = (struct iocblk *)mp->b_rptr;
16535 
16536 		switch (iocp->ioc_cmd) {
16537 		int mode;
16538 
16539 		case DL_IOC_HDR_INFO:
16540 			/*
16541 			 * If this was the first attempt turn of the
16542 			 * fastpath probing.
16543 			 */
16544 			mutex_enter(&ill->ill_lock);
16545 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16546 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16547 				mutex_exit(&ill->ill_lock);
16548 				ill_fastpath_nack(ill);
16549 				ip1dbg(("ip_rput: DLPI fastpath off on "
16550 				    "interface %s\n",
16551 				    ill->ill_name));
16552 			} else {
16553 				mutex_exit(&ill->ill_lock);
16554 			}
16555 			freemsg(mp);
16556 			break;
16557 		case SIOCSTUNPARAM:
16558 		case OSIOCSTUNPARAM:
16559 			ASSERT(ipsq != NULL);
16560 			/*
16561 			 * Finish socket ioctl passed through to tun
16562 			 * We should have an IOCTL waiting on this.
16563 			 */
16564 			/* FALLTHRU */
16565 		case SIOCGTUNPARAM:
16566 		case OSIOCGTUNPARAM:
16567 			/*
16568 			 * This is really M_IOCDATA from the tunnel driver.
16569 			 * convert back and complete the ioctl.
16570 			 * We should have an IOCTL waiting on this.
16571 			 */
16572 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16573 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16574 				mp1 = ill_pending_mp_get(ill, &connp,
16575 				    iocp->ioc_id);
16576 				mode = COPYOUT;
16577 				ipsq = NULL;
16578 			} else {
16579 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16580 				mode = NO_COPYOUT;
16581 			}
16582 			if (mp1 != NULL) {
16583 				/*
16584 				 * Now copy back the b_next/b_prev used by
16585 				 * mi code for the mi_copy* functions.
16586 				 * See ip_sioctl_tunparam() for the reason.
16587 				 * Also protect against missing b_cont.
16588 				 */
16589 				if (mp->b_cont != NULL) {
16590 					mp->b_cont->b_next =
16591 					    mp1->b_cont->b_next;
16592 					mp->b_cont->b_prev =
16593 					    mp1->b_cont->b_prev;
16594 				}
16595 				inet_freemsg(mp1);
16596 				if (iocp->ioc_error == 0)
16597 					iocp->ioc_error = EINVAL;
16598 				ASSERT(connp != NULL);
16599 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16600 				    iocp->ioc_error, mode, ipsq);
16601 			} else {
16602 				ASSERT(connp == NULL);
16603 				putnext(q, mp);
16604 			}
16605 			break;
16606 		default:
16607 			break;
16608 		}
16609 	default:
16610 		break;
16611 	}
16612 }
16613 
16614 /*
16615  * NOTE : This function does not ire_refrele the ire argument passed in.
16616  *
16617  * IPQoS notes
16618  * IP policy is invoked twice for a forwarded packet, once on the read side
16619  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16620  * enabled. An additional parameter, in_ill, has been added for this purpose.
16621  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16622  * because ip_mroute drops this information.
16623  *
16624  */
16625 void
16626 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16627 {
16628 	uint32_t	pkt_len;
16629 	queue_t	*q;
16630 	uint32_t	sum;
16631 #define	rptr	((uchar_t *)ipha)
16632 	uint32_t	max_frag;
16633 	uint32_t	ill_index;
16634 	ill_t		*out_ill;
16635 	mib2_ipIfStatsEntry_t *mibptr;
16636 	ip_stack_t	*ipst = in_ill->ill_ipst;
16637 
16638 	/* Get the ill_index of the incoming ILL */
16639 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16640 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16641 
16642 	/* Initiate Read side IPPF processing */
16643 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16644 		ip_process(IPP_FWD_IN, &mp, ill_index);
16645 		if (mp == NULL) {
16646 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16647 			    "during IPPF processing\n"));
16648 			return;
16649 		}
16650 	}
16651 
16652 	pkt_len = ntohs(ipha->ipha_length);
16653 
16654 	/* Adjust the checksum to reflect the ttl decrement. */
16655 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16656 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16657 
16658 	if (ipha->ipha_ttl-- <= 1) {
16659 		if (ip_csum_hdr(ipha)) {
16660 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16661 			goto drop_pkt;
16662 		}
16663 		/*
16664 		 * Note: ire_stq this will be NULL for multicast
16665 		 * datagrams using the long path through arp (the IRE
16666 		 * is not an IRE_CACHE). This should not cause
16667 		 * problems since we don't generate ICMP errors for
16668 		 * multicast packets.
16669 		 */
16670 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16671 		q = ire->ire_stq;
16672 		if (q != NULL) {
16673 			/* Sent by forwarding path, and router is global zone */
16674 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16675 			    GLOBAL_ZONEID, ipst);
16676 		} else
16677 			freemsg(mp);
16678 		return;
16679 	}
16680 
16681 	/*
16682 	 * Don't forward if the interface is down
16683 	 */
16684 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16685 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16686 		ip2dbg(("ip_rput_forward:interface is down\n"));
16687 		goto drop_pkt;
16688 	}
16689 
16690 	/* Get the ill_index of the outgoing ILL */
16691 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16692 
16693 	out_ill = ire->ire_ipif->ipif_ill;
16694 
16695 	DTRACE_PROBE4(ip4__forwarding__start,
16696 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16697 
16698 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16699 	    ipst->ips_ipv4firewall_forwarding,
16700 	    in_ill, out_ill, ipha, mp, mp, ipst);
16701 
16702 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16703 
16704 	if (mp == NULL)
16705 		return;
16706 	pkt_len = ntohs(ipha->ipha_length);
16707 
16708 	if (is_system_labeled()) {
16709 		mblk_t *mp1;
16710 
16711 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16712 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16713 			goto drop_pkt;
16714 		}
16715 		/* Size may have changed */
16716 		mp = mp1;
16717 		ipha = (ipha_t *)mp->b_rptr;
16718 		pkt_len = ntohs(ipha->ipha_length);
16719 	}
16720 
16721 	/* Check if there are options to update */
16722 	if (!IS_SIMPLE_IPH(ipha)) {
16723 		if (ip_csum_hdr(ipha)) {
16724 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16725 			goto drop_pkt;
16726 		}
16727 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16728 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16729 			return;
16730 		}
16731 
16732 		ipha->ipha_hdr_checksum = 0;
16733 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16734 	}
16735 	max_frag = ire->ire_max_frag;
16736 	if (pkt_len > max_frag) {
16737 		/*
16738 		 * It needs fragging on its way out.  We haven't
16739 		 * verified the header checksum yet.  Since we
16740 		 * are going to put a surely good checksum in the
16741 		 * outgoing header, we have to make sure that it
16742 		 * was good coming in.
16743 		 */
16744 		if (ip_csum_hdr(ipha)) {
16745 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16746 			goto drop_pkt;
16747 		}
16748 		/* Initiate Write side IPPF processing */
16749 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16750 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16751 			if (mp == NULL) {
16752 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16753 				    " during IPPF processing\n"));
16754 				return;
16755 			}
16756 		}
16757 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16758 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16759 		return;
16760 	}
16761 
16762 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16763 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16764 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16765 	    ipst->ips_ipv4firewall_physical_out,
16766 	    NULL, out_ill, ipha, mp, mp, ipst);
16767 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16768 	if (mp == NULL)
16769 		return;
16770 
16771 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16772 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16773 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16774 	/* ip_xmit_v4 always consumes the packet */
16775 	return;
16776 
16777 drop_pkt:;
16778 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16779 	freemsg(mp);
16780 #undef	rptr
16781 }
16782 
16783 void
16784 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16785 {
16786 	ire_t	*ire;
16787 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16788 
16789 	ASSERT(!ipif->ipif_isv6);
16790 	/*
16791 	 * Find an IRE which matches the destination and the outgoing
16792 	 * queue in the cache table. All we need is an IRE_CACHE which
16793 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16794 	 * then it is enough to have some IRE_CACHE in the group.
16795 	 */
16796 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16797 		dst = ipif->ipif_pp_dst_addr;
16798 
16799 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16800 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16801 	if (ire == NULL) {
16802 		/*
16803 		 * Mark this packet to make it be delivered to
16804 		 * ip_rput_forward after the new ire has been
16805 		 * created.
16806 		 */
16807 		mp->b_prev = NULL;
16808 		mp->b_next = mp;
16809 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16810 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16811 	} else {
16812 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16813 		IRE_REFRELE(ire);
16814 	}
16815 }
16816 
16817 /* Update any source route, record route or timestamp options */
16818 static int
16819 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16820 {
16821 	ipoptp_t	opts;
16822 	uchar_t		*opt;
16823 	uint8_t		optval;
16824 	uint8_t		optlen;
16825 	ipaddr_t	dst;
16826 	uint32_t	ts;
16827 	ire_t		*dst_ire = NULL;
16828 	ire_t		*tmp_ire = NULL;
16829 	timestruc_t	now;
16830 
16831 	ip2dbg(("ip_rput_forward_options\n"));
16832 	dst = ipha->ipha_dst;
16833 	for (optval = ipoptp_first(&opts, ipha);
16834 	    optval != IPOPT_EOL;
16835 	    optval = ipoptp_next(&opts)) {
16836 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16837 		opt = opts.ipoptp_cur;
16838 		optlen = opts.ipoptp_len;
16839 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16840 		    optval, opts.ipoptp_len));
16841 		switch (optval) {
16842 			uint32_t off;
16843 		case IPOPT_SSRR:
16844 		case IPOPT_LSRR:
16845 			/* Check if adminstratively disabled */
16846 			if (!ipst->ips_ip_forward_src_routed) {
16847 				if (ire->ire_stq != NULL) {
16848 					/*
16849 					 * Sent by forwarding path, and router
16850 					 * is global zone
16851 					 */
16852 					icmp_unreachable(ire->ire_stq, mp,
16853 					    ICMP_SOURCE_ROUTE_FAILED,
16854 					    GLOBAL_ZONEID, ipst);
16855 				} else {
16856 					ip0dbg(("ip_rput_forward_options: "
16857 					    "unable to send unreach\n"));
16858 					freemsg(mp);
16859 				}
16860 				return (-1);
16861 			}
16862 
16863 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16864 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16865 			if (dst_ire == NULL) {
16866 				/*
16867 				 * Must be partial since ip_rput_options
16868 				 * checked for strict.
16869 				 */
16870 				break;
16871 			}
16872 			off = opt[IPOPT_OFFSET];
16873 			off--;
16874 		redo_srr:
16875 			if (optlen < IP_ADDR_LEN ||
16876 			    off > optlen - IP_ADDR_LEN) {
16877 				/* End of source route */
16878 				ip1dbg((
16879 				    "ip_rput_forward_options: end of SR\n"));
16880 				ire_refrele(dst_ire);
16881 				break;
16882 			}
16883 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16884 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16885 			    IP_ADDR_LEN);
16886 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16887 			    ntohl(dst)));
16888 
16889 			/*
16890 			 * Check if our address is present more than
16891 			 * once as consecutive hops in source route.
16892 			 */
16893 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16894 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16895 			if (tmp_ire != NULL) {
16896 				ire_refrele(tmp_ire);
16897 				off += IP_ADDR_LEN;
16898 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16899 				goto redo_srr;
16900 			}
16901 			ipha->ipha_dst = dst;
16902 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16903 			ire_refrele(dst_ire);
16904 			break;
16905 		case IPOPT_RR:
16906 			off = opt[IPOPT_OFFSET];
16907 			off--;
16908 			if (optlen < IP_ADDR_LEN ||
16909 			    off > optlen - IP_ADDR_LEN) {
16910 				/* No more room - ignore */
16911 				ip1dbg((
16912 				    "ip_rput_forward_options: end of RR\n"));
16913 				break;
16914 			}
16915 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16916 			    IP_ADDR_LEN);
16917 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16918 			break;
16919 		case IPOPT_TS:
16920 			/* Insert timestamp if there is room */
16921 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16922 			case IPOPT_TS_TSONLY:
16923 				off = IPOPT_TS_TIMELEN;
16924 				break;
16925 			case IPOPT_TS_PRESPEC:
16926 			case IPOPT_TS_PRESPEC_RFC791:
16927 				/* Verify that the address matched */
16928 				off = opt[IPOPT_OFFSET] - 1;
16929 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16930 				dst_ire = ire_ctable_lookup(dst, 0,
16931 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16932 				    MATCH_IRE_TYPE, ipst);
16933 				if (dst_ire == NULL) {
16934 					/* Not for us */
16935 					break;
16936 				}
16937 				ire_refrele(dst_ire);
16938 				/* FALLTHRU */
16939 			case IPOPT_TS_TSANDADDR:
16940 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16941 				break;
16942 			default:
16943 				/*
16944 				 * ip_*put_options should have already
16945 				 * dropped this packet.
16946 				 */
16947 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16948 				    "unknown IT - bug in ip_rput_options?\n");
16949 				return (0);	/* Keep "lint" happy */
16950 			}
16951 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16952 				/* Increase overflow counter */
16953 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16954 				opt[IPOPT_POS_OV_FLG] =
16955 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16956 				    (off << 4));
16957 				break;
16958 			}
16959 			off = opt[IPOPT_OFFSET] - 1;
16960 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16961 			case IPOPT_TS_PRESPEC:
16962 			case IPOPT_TS_PRESPEC_RFC791:
16963 			case IPOPT_TS_TSANDADDR:
16964 				bcopy(&ire->ire_src_addr,
16965 				    (char *)opt + off, IP_ADDR_LEN);
16966 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16967 				/* FALLTHRU */
16968 			case IPOPT_TS_TSONLY:
16969 				off = opt[IPOPT_OFFSET] - 1;
16970 				/* Compute # of milliseconds since midnight */
16971 				gethrestime(&now);
16972 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16973 				    now.tv_nsec / (NANOSEC / MILLISEC);
16974 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16975 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16976 				break;
16977 			}
16978 			break;
16979 		}
16980 	}
16981 	return (0);
16982 }
16983 
16984 /*
16985  * This is called after processing at least one of AH/ESP headers.
16986  *
16987  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16988  * the actual, physical interface on which the packet was received,
16989  * but, when ip_strict_dst_multihoming is set to 1, could be the
16990  * interface which had the ipha_dst configured when the packet went
16991  * through ip_rput. The ill_index corresponding to the recv_ill
16992  * is saved in ipsec_in_rill_index
16993  */
16994 void
16995 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16996 {
16997 	mblk_t *mp;
16998 	ipaddr_t dst;
16999 	in6_addr_t *v6dstp;
17000 	ipha_t *ipha;
17001 	ip6_t *ip6h;
17002 	ipsec_in_t *ii;
17003 	boolean_t ill_need_rele = B_FALSE;
17004 	boolean_t rill_need_rele = B_FALSE;
17005 	boolean_t ire_need_rele = B_FALSE;
17006 	netstack_t	*ns;
17007 	ip_stack_t	*ipst;
17008 
17009 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17010 	ASSERT(ii->ipsec_in_ill_index != 0);
17011 	ns = ii->ipsec_in_ns;
17012 	ASSERT(ii->ipsec_in_ns != NULL);
17013 	ipst = ns->netstack_ip;
17014 
17015 	mp = ipsec_mp->b_cont;
17016 	ASSERT(mp != NULL);
17017 
17018 
17019 	if (ill == NULL) {
17020 		ASSERT(recv_ill == NULL);
17021 		/*
17022 		 * We need to get the original queue on which ip_rput_local
17023 		 * or ip_rput_data_v6 was called.
17024 		 */
17025 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17026 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17027 		ill_need_rele = B_TRUE;
17028 
17029 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17030 			recv_ill = ill_lookup_on_ifindex(
17031 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17032 			    NULL, NULL, NULL, NULL, ipst);
17033 			rill_need_rele = B_TRUE;
17034 		} else {
17035 			recv_ill = ill;
17036 		}
17037 
17038 		if ((ill == NULL) || (recv_ill == NULL)) {
17039 			ip0dbg(("ip_fanout_proto_again: interface "
17040 			    "disappeared\n"));
17041 			if (ill != NULL)
17042 				ill_refrele(ill);
17043 			if (recv_ill != NULL)
17044 				ill_refrele(recv_ill);
17045 			freemsg(ipsec_mp);
17046 			return;
17047 		}
17048 	}
17049 
17050 	ASSERT(ill != NULL && recv_ill != NULL);
17051 
17052 	if (mp->b_datap->db_type == M_CTL) {
17053 		/*
17054 		 * AH/ESP is returning the ICMP message after
17055 		 * removing their headers. Fanout again till
17056 		 * it gets to the right protocol.
17057 		 */
17058 		if (ii->ipsec_in_v4) {
17059 			icmph_t *icmph;
17060 			int iph_hdr_length;
17061 			int hdr_length;
17062 
17063 			ipha = (ipha_t *)mp->b_rptr;
17064 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17065 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17066 			ipha = (ipha_t *)&icmph[1];
17067 			hdr_length = IPH_HDR_LENGTH(ipha);
17068 			/*
17069 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17070 			 * Reset the type to M_DATA.
17071 			 */
17072 			mp->b_datap->db_type = M_DATA;
17073 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17074 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17075 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17076 		} else {
17077 			icmp6_t *icmp6;
17078 			int hdr_length;
17079 
17080 			ip6h = (ip6_t *)mp->b_rptr;
17081 			/* Don't call hdr_length_v6() unless you have to. */
17082 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17083 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17084 			else
17085 				hdr_length = IPV6_HDR_LEN;
17086 
17087 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17088 			/*
17089 			 * icmp_inbound_error_fanout_v6 may need to do
17090 			 * pullupmsg.  Reset the type to M_DATA.
17091 			 */
17092 			mp->b_datap->db_type = M_DATA;
17093 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17094 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17095 		}
17096 		if (ill_need_rele)
17097 			ill_refrele(ill);
17098 		if (rill_need_rele)
17099 			ill_refrele(recv_ill);
17100 		return;
17101 	}
17102 
17103 	if (ii->ipsec_in_v4) {
17104 		ipha = (ipha_t *)mp->b_rptr;
17105 		dst = ipha->ipha_dst;
17106 		if (CLASSD(dst)) {
17107 			/*
17108 			 * Multicast has to be delivered to all streams.
17109 			 */
17110 			dst = INADDR_BROADCAST;
17111 		}
17112 
17113 		if (ire == NULL) {
17114 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17115 			    MBLK_GETLABEL(mp), ipst);
17116 			if (ire == NULL) {
17117 				if (ill_need_rele)
17118 					ill_refrele(ill);
17119 				if (rill_need_rele)
17120 					ill_refrele(recv_ill);
17121 				ip1dbg(("ip_fanout_proto_again: "
17122 				    "IRE not found"));
17123 				freemsg(ipsec_mp);
17124 				return;
17125 			}
17126 			ire_need_rele = B_TRUE;
17127 		}
17128 
17129 		switch (ipha->ipha_protocol) {
17130 			case IPPROTO_UDP:
17131 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17132 				    recv_ill);
17133 				if (ire_need_rele)
17134 					ire_refrele(ire);
17135 				break;
17136 			case IPPROTO_TCP:
17137 				if (!ire_need_rele)
17138 					IRE_REFHOLD(ire);
17139 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17140 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17141 				IRE_REFRELE(ire);
17142 				if (mp != NULL)
17143 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17144 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17145 				break;
17146 			case IPPROTO_SCTP:
17147 				if (!ire_need_rele)
17148 					IRE_REFHOLD(ire);
17149 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17150 				    ipsec_mp, 0, ill->ill_rq, dst);
17151 				break;
17152 			default:
17153 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17154 				    recv_ill);
17155 				if (ire_need_rele)
17156 					ire_refrele(ire);
17157 				break;
17158 		}
17159 	} else {
17160 		uint32_t rput_flags = 0;
17161 
17162 		ip6h = (ip6_t *)mp->b_rptr;
17163 		v6dstp = &ip6h->ip6_dst;
17164 		/*
17165 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17166 		 * address.
17167 		 *
17168 		 * Currently, we don't store that state in the IPSEC_IN
17169 		 * message, and we may need to.
17170 		 */
17171 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17172 		    IP6_IN_LLMCAST : 0);
17173 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17174 		    NULL, NULL);
17175 	}
17176 	if (ill_need_rele)
17177 		ill_refrele(ill);
17178 	if (rill_need_rele)
17179 		ill_refrele(recv_ill);
17180 }
17181 
17182 /*
17183  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17184  * returns 'true' if there are still fragments left on the queue, in
17185  * which case we restart the timer.
17186  */
17187 void
17188 ill_frag_timer(void *arg)
17189 {
17190 	ill_t	*ill = (ill_t *)arg;
17191 	boolean_t frag_pending;
17192 	ip_stack_t	*ipst = ill->ill_ipst;
17193 
17194 	mutex_enter(&ill->ill_lock);
17195 	ASSERT(!ill->ill_fragtimer_executing);
17196 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17197 		ill->ill_frag_timer_id = 0;
17198 		mutex_exit(&ill->ill_lock);
17199 		return;
17200 	}
17201 	ill->ill_fragtimer_executing = 1;
17202 	mutex_exit(&ill->ill_lock);
17203 
17204 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17205 
17206 	/*
17207 	 * Restart the timer, if we have fragments pending or if someone
17208 	 * wanted us to be scheduled again.
17209 	 */
17210 	mutex_enter(&ill->ill_lock);
17211 	ill->ill_fragtimer_executing = 0;
17212 	ill->ill_frag_timer_id = 0;
17213 	if (frag_pending || ill->ill_fragtimer_needrestart)
17214 		ill_frag_timer_start(ill);
17215 	mutex_exit(&ill->ill_lock);
17216 }
17217 
17218 void
17219 ill_frag_timer_start(ill_t *ill)
17220 {
17221 	ip_stack_t	*ipst = ill->ill_ipst;
17222 
17223 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17224 
17225 	/* If the ill is closing or opening don't proceed */
17226 	if (ill->ill_state_flags & ILL_CONDEMNED)
17227 		return;
17228 
17229 	if (ill->ill_fragtimer_executing) {
17230 		/*
17231 		 * ill_frag_timer is currently executing. Just record the
17232 		 * the fact that we want the timer to be restarted.
17233 		 * ill_frag_timer will post a timeout before it returns,
17234 		 * ensuring it will be called again.
17235 		 */
17236 		ill->ill_fragtimer_needrestart = 1;
17237 		return;
17238 	}
17239 
17240 	if (ill->ill_frag_timer_id == 0) {
17241 		/*
17242 		 * The timer is neither running nor is the timeout handler
17243 		 * executing. Post a timeout so that ill_frag_timer will be
17244 		 * called
17245 		 */
17246 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17247 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17248 		ill->ill_fragtimer_needrestart = 0;
17249 	}
17250 }
17251 
17252 /*
17253  * This routine is needed for loopback when forwarding multicasts.
17254  *
17255  * IPQoS Notes:
17256  * IPPF processing is done in fanout routines.
17257  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17258  * processing for IPSec packets is done when it comes back in clear.
17259  * NOTE : The callers of this function need to do the ire_refrele for the
17260  *	  ire that is being passed in.
17261  */
17262 void
17263 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17264     ill_t *recv_ill)
17265 {
17266 	ill_t	*ill = (ill_t *)q->q_ptr;
17267 	uint32_t	sum;
17268 	uint32_t	u1;
17269 	uint32_t	u2;
17270 	int		hdr_length;
17271 	boolean_t	mctl_present;
17272 	mblk_t		*first_mp = mp;
17273 	mblk_t		*hada_mp = NULL;
17274 	ipha_t		*inner_ipha;
17275 	ip_stack_t	*ipst;
17276 
17277 	ASSERT(recv_ill != NULL);
17278 	ipst = recv_ill->ill_ipst;
17279 
17280 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17281 	    "ip_rput_locl_start: q %p", q);
17282 
17283 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17284 	ASSERT(ill != NULL);
17285 
17286 
17287 #define	rptr	((uchar_t *)ipha)
17288 #define	iphs	((uint16_t *)ipha)
17289 
17290 	/*
17291 	 * no UDP or TCP packet should come here anymore.
17292 	 */
17293 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17294 	    (ipha->ipha_protocol != IPPROTO_UDP));
17295 
17296 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17297 	if (mctl_present &&
17298 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17299 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17300 
17301 		/*
17302 		 * It's an IPsec accelerated packet.
17303 		 * Keep a pointer to the data attributes around until
17304 		 * we allocate the ipsec_info_t.
17305 		 */
17306 		IPSECHW_DEBUG(IPSECHW_PKT,
17307 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17308 		hada_mp = first_mp;
17309 		hada_mp->b_cont = NULL;
17310 		/*
17311 		 * Since it is accelerated, it comes directly from
17312 		 * the ill and the data attributes is followed by
17313 		 * the packet data.
17314 		 */
17315 		ASSERT(mp->b_datap->db_type != M_CTL);
17316 		first_mp = mp;
17317 		mctl_present = B_FALSE;
17318 	}
17319 
17320 	/*
17321 	 * IF M_CTL is not present, then ipsec_in_is_secure
17322 	 * should return B_TRUE. There is a case where loopback
17323 	 * packets has an M_CTL in the front with all the
17324 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17325 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17326 	 * packets never comes here, it is safe to ASSERT the
17327 	 * following.
17328 	 */
17329 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17330 
17331 
17332 	/* u1 is # words of IP options */
17333 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17334 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17335 
17336 	if (u1) {
17337 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17338 			if (hada_mp != NULL)
17339 				freemsg(hada_mp);
17340 			return;
17341 		}
17342 	} else {
17343 		/* Check the IP header checksum.  */
17344 #define	uph	((uint16_t *)ipha)
17345 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17346 		    uph[6] + uph[7] + uph[8] + uph[9];
17347 #undef  uph
17348 		/* finish doing IP checksum */
17349 		sum = (sum & 0xFFFF) + (sum >> 16);
17350 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17351 		/*
17352 		 * Don't verify header checksum if this packet is coming
17353 		 * back from AH/ESP as we already did it.
17354 		 */
17355 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17356 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17357 			goto drop_pkt;
17358 		}
17359 	}
17360 
17361 	/*
17362 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17363 	 * might be called more than once for secure packets, count only
17364 	 * the first time.
17365 	 */
17366 	if (!mctl_present) {
17367 		UPDATE_IB_PKT_COUNT(ire);
17368 		ire->ire_last_used_time = lbolt;
17369 	}
17370 
17371 	/* Check for fragmentation offset. */
17372 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17373 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17374 	if (u1) {
17375 		/*
17376 		 * We re-assemble fragments before we do the AH/ESP
17377 		 * processing. Thus, M_CTL should not be present
17378 		 * while we are re-assembling.
17379 		 */
17380 		ASSERT(!mctl_present);
17381 		ASSERT(first_mp == mp);
17382 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17383 			return;
17384 		}
17385 		/*
17386 		 * Make sure that first_mp points back to mp as
17387 		 * the mp we came in with could have changed in
17388 		 * ip_rput_fragment().
17389 		 */
17390 		ipha = (ipha_t *)mp->b_rptr;
17391 		first_mp = mp;
17392 	}
17393 
17394 	/*
17395 	 * Clear hardware checksumming flag as it is currently only
17396 	 * used by TCP and UDP.
17397 	 */
17398 	DB_CKSUMFLAGS(mp) = 0;
17399 
17400 	/* Now we have a complete datagram, destined for this machine. */
17401 	u1 = IPH_HDR_LENGTH(ipha);
17402 	switch (ipha->ipha_protocol) {
17403 	case IPPROTO_ICMP: {
17404 		ire_t		*ire_zone;
17405 		ilm_t		*ilm;
17406 		mblk_t		*mp1;
17407 		zoneid_t	last_zoneid;
17408 
17409 		if (CLASSD(ipha->ipha_dst) &&
17410 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17411 			ASSERT(ire->ire_type == IRE_BROADCAST);
17412 			/*
17413 			 * In the multicast case, applications may have joined
17414 			 * the group from different zones, so we need to deliver
17415 			 * the packet to each of them. Loop through the
17416 			 * multicast memberships structures (ilm) on the receive
17417 			 * ill and send a copy of the packet up each matching
17418 			 * one. However, we don't do this for multicasts sent on
17419 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17420 			 * they must stay in the sender's zone.
17421 			 *
17422 			 * ilm_add_v6() ensures that ilms in the same zone are
17423 			 * contiguous in the ill_ilm list. We use this property
17424 			 * to avoid sending duplicates needed when two
17425 			 * applications in the same zone join the same group on
17426 			 * different logical interfaces: we ignore the ilm if
17427 			 * its zoneid is the same as the last matching one.
17428 			 * In addition, the sending of the packet for
17429 			 * ire_zoneid is delayed until all of the other ilms
17430 			 * have been exhausted.
17431 			 */
17432 			last_zoneid = -1;
17433 			ILM_WALKER_HOLD(recv_ill);
17434 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17435 			    ilm = ilm->ilm_next) {
17436 				if ((ilm->ilm_flags & ILM_DELETED) ||
17437 				    ipha->ipha_dst != ilm->ilm_addr ||
17438 				    ilm->ilm_zoneid == last_zoneid ||
17439 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17440 				    ilm->ilm_zoneid == ALL_ZONES ||
17441 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17442 					continue;
17443 				mp1 = ip_copymsg(first_mp);
17444 				if (mp1 == NULL)
17445 					continue;
17446 				icmp_inbound(q, mp1, B_TRUE, ill,
17447 				    0, sum, mctl_present, B_TRUE,
17448 				    recv_ill, ilm->ilm_zoneid);
17449 				last_zoneid = ilm->ilm_zoneid;
17450 			}
17451 			ILM_WALKER_RELE(recv_ill);
17452 		} else if (ire->ire_type == IRE_BROADCAST) {
17453 			/*
17454 			 * In the broadcast case, there may be many zones
17455 			 * which need a copy of the packet delivered to them.
17456 			 * There is one IRE_BROADCAST per broadcast address
17457 			 * and per zone; we walk those using a helper function.
17458 			 * In addition, the sending of the packet for ire is
17459 			 * delayed until all of the other ires have been
17460 			 * processed.
17461 			 */
17462 			IRB_REFHOLD(ire->ire_bucket);
17463 			ire_zone = NULL;
17464 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17465 			    ire)) != NULL) {
17466 				mp1 = ip_copymsg(first_mp);
17467 				if (mp1 == NULL)
17468 					continue;
17469 
17470 				UPDATE_IB_PKT_COUNT(ire_zone);
17471 				ire_zone->ire_last_used_time = lbolt;
17472 				icmp_inbound(q, mp1, B_TRUE, ill,
17473 				    0, sum, mctl_present, B_TRUE,
17474 				    recv_ill, ire_zone->ire_zoneid);
17475 			}
17476 			IRB_REFRELE(ire->ire_bucket);
17477 		}
17478 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17479 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17480 		    ire->ire_zoneid);
17481 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17482 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17483 		return;
17484 	}
17485 	case IPPROTO_IGMP:
17486 		/*
17487 		 * If we are not willing to accept IGMP packets in clear,
17488 		 * then check with global policy.
17489 		 */
17490 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17491 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17492 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17493 			if (first_mp == NULL)
17494 				return;
17495 		}
17496 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17497 			freemsg(first_mp);
17498 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17499 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17500 			return;
17501 		}
17502 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17503 			/* Bad packet - discarded by igmp_input */
17504 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17505 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17506 			if (mctl_present)
17507 				freeb(first_mp);
17508 			return;
17509 		}
17510 		/*
17511 		 * igmp_input() may have returned the pulled up message.
17512 		 * So first_mp and ipha need to be reinitialized.
17513 		 */
17514 		ipha = (ipha_t *)mp->b_rptr;
17515 		if (mctl_present)
17516 			first_mp->b_cont = mp;
17517 		else
17518 			first_mp = mp;
17519 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17520 		    connf_head != NULL) {
17521 			/* No user-level listener for IGMP packets */
17522 			goto drop_pkt;
17523 		}
17524 		/* deliver to local raw users */
17525 		break;
17526 	case IPPROTO_PIM:
17527 		/*
17528 		 * If we are not willing to accept PIM packets in clear,
17529 		 * then check with global policy.
17530 		 */
17531 		if (ipst->ips_pim_accept_clear_messages == 0) {
17532 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17533 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17534 			if (first_mp == NULL)
17535 				return;
17536 		}
17537 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17538 			freemsg(first_mp);
17539 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17540 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17541 			return;
17542 		}
17543 		if (pim_input(q, mp, ill) != 0) {
17544 			/* Bad packet - discarded by pim_input */
17545 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17546 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17547 			if (mctl_present)
17548 				freeb(first_mp);
17549 			return;
17550 		}
17551 
17552 		/*
17553 		 * pim_input() may have pulled up the message so ipha needs to
17554 		 * be reinitialized.
17555 		 */
17556 		ipha = (ipha_t *)mp->b_rptr;
17557 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17558 		    connf_head != NULL) {
17559 			/* No user-level listener for PIM packets */
17560 			goto drop_pkt;
17561 		}
17562 		/* deliver to local raw users */
17563 		break;
17564 	case IPPROTO_ENCAP:
17565 		/*
17566 		 * Handle self-encapsulated packets (IP-in-IP where
17567 		 * the inner addresses == the outer addresses).
17568 		 */
17569 		hdr_length = IPH_HDR_LENGTH(ipha);
17570 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17571 		    mp->b_wptr) {
17572 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17573 			    sizeof (ipha_t) - mp->b_rptr)) {
17574 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17575 				freemsg(first_mp);
17576 				return;
17577 			}
17578 			ipha = (ipha_t *)mp->b_rptr;
17579 		}
17580 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17581 		/*
17582 		 * Check the sanity of the inner IP header.
17583 		 */
17584 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17585 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17586 			freemsg(first_mp);
17587 			return;
17588 		}
17589 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17590 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17591 			freemsg(first_mp);
17592 			return;
17593 		}
17594 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17595 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17596 			ipsec_in_t *ii;
17597 
17598 			/*
17599 			 * Self-encapsulated tunnel packet. Remove
17600 			 * the outer IP header and fanout again.
17601 			 * We also need to make sure that the inner
17602 			 * header is pulled up until options.
17603 			 */
17604 			mp->b_rptr = (uchar_t *)inner_ipha;
17605 			ipha = inner_ipha;
17606 			hdr_length = IPH_HDR_LENGTH(ipha);
17607 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17608 				if (!pullupmsg(mp, (uchar_t *)ipha +
17609 				    + hdr_length - mp->b_rptr)) {
17610 					freemsg(first_mp);
17611 					return;
17612 				}
17613 				ipha = (ipha_t *)mp->b_rptr;
17614 			}
17615 			if (!mctl_present) {
17616 				ASSERT(first_mp == mp);
17617 				/*
17618 				 * This means that somebody is sending
17619 				 * Self-encapsualted packets without AH/ESP.
17620 				 * If AH/ESP was present, we would have already
17621 				 * allocated the first_mp.
17622 				 */
17623 				first_mp = ipsec_in_alloc(B_TRUE,
17624 				    ipst->ips_netstack);
17625 				if (first_mp == NULL) {
17626 					ip1dbg(("ip_proto_input: IPSEC_IN "
17627 					    "allocation failure.\n"));
17628 					BUMP_MIB(ill->ill_ip_mib,
17629 					    ipIfStatsInDiscards);
17630 					freemsg(mp);
17631 					return;
17632 				}
17633 				first_mp->b_cont = mp;
17634 			}
17635 			/*
17636 			 * We generally store the ill_index if we need to
17637 			 * do IPSEC processing as we lose the ill queue when
17638 			 * we come back. But in this case, we never should
17639 			 * have to store the ill_index here as it should have
17640 			 * been stored previously when we processed the
17641 			 * AH/ESP header in this routine or for non-ipsec
17642 			 * cases, we still have the queue. But for some bad
17643 			 * packets from the wire, we can get to IPSEC after
17644 			 * this and we better store the index for that case.
17645 			 */
17646 			ill = (ill_t *)q->q_ptr;
17647 			ii = (ipsec_in_t *)first_mp->b_rptr;
17648 			ii->ipsec_in_ill_index =
17649 			    ill->ill_phyint->phyint_ifindex;
17650 			ii->ipsec_in_rill_index =
17651 			    recv_ill->ill_phyint->phyint_ifindex;
17652 			if (ii->ipsec_in_decaps) {
17653 				/*
17654 				 * This packet is self-encapsulated multiple
17655 				 * times. We don't want to recurse infinitely.
17656 				 * To keep it simple, drop the packet.
17657 				 */
17658 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17659 				freemsg(first_mp);
17660 				return;
17661 			}
17662 			ii->ipsec_in_decaps = B_TRUE;
17663 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17664 			    ire);
17665 			return;
17666 		}
17667 		break;
17668 	case IPPROTO_AH:
17669 	case IPPROTO_ESP: {
17670 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17671 
17672 		/*
17673 		 * Fast path for AH/ESP. If this is the first time
17674 		 * we are sending a datagram to AH/ESP, allocate
17675 		 * a IPSEC_IN message and prepend it. Otherwise,
17676 		 * just fanout.
17677 		 */
17678 
17679 		int ipsec_rc;
17680 		ipsec_in_t *ii;
17681 		netstack_t *ns = ipst->ips_netstack;
17682 
17683 		IP_STAT(ipst, ipsec_proto_ahesp);
17684 		if (!mctl_present) {
17685 			ASSERT(first_mp == mp);
17686 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17687 			if (first_mp == NULL) {
17688 				ip1dbg(("ip_proto_input: IPSEC_IN "
17689 				    "allocation failure.\n"));
17690 				freemsg(hada_mp); /* okay ifnull */
17691 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17692 				freemsg(mp);
17693 				return;
17694 			}
17695 			/*
17696 			 * Store the ill_index so that when we come back
17697 			 * from IPSEC we ride on the same queue.
17698 			 */
17699 			ill = (ill_t *)q->q_ptr;
17700 			ii = (ipsec_in_t *)first_mp->b_rptr;
17701 			ii->ipsec_in_ill_index =
17702 			    ill->ill_phyint->phyint_ifindex;
17703 			ii->ipsec_in_rill_index =
17704 			    recv_ill->ill_phyint->phyint_ifindex;
17705 			first_mp->b_cont = mp;
17706 			/*
17707 			 * Cache hardware acceleration info.
17708 			 */
17709 			if (hada_mp != NULL) {
17710 				IPSECHW_DEBUG(IPSECHW_PKT,
17711 				    ("ip_rput_local: caching data attr.\n"));
17712 				ii->ipsec_in_accelerated = B_TRUE;
17713 				ii->ipsec_in_da = hada_mp;
17714 				hada_mp = NULL;
17715 			}
17716 		} else {
17717 			ii = (ipsec_in_t *)first_mp->b_rptr;
17718 		}
17719 
17720 		if (!ipsec_loaded(ipss)) {
17721 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17722 			    ire->ire_zoneid, ipst);
17723 			return;
17724 		}
17725 
17726 		ns = ipst->ips_netstack;
17727 		/* select inbound SA and have IPsec process the pkt */
17728 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17729 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17730 			if (esph == NULL)
17731 				return;
17732 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17733 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17734 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17735 			    first_mp, esph);
17736 		} else {
17737 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17738 			if (ah == NULL)
17739 				return;
17740 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17741 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17742 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17743 			    first_mp, ah);
17744 		}
17745 
17746 		switch (ipsec_rc) {
17747 		case IPSEC_STATUS_SUCCESS:
17748 			break;
17749 		case IPSEC_STATUS_FAILED:
17750 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17751 			/* FALLTHRU */
17752 		case IPSEC_STATUS_PENDING:
17753 			return;
17754 		}
17755 		/* we're done with IPsec processing, send it up */
17756 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17757 		return;
17758 	}
17759 	default:
17760 		break;
17761 	}
17762 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17763 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17764 		    ire->ire_zoneid));
17765 		goto drop_pkt;
17766 	}
17767 	/*
17768 	 * Handle protocols with which IP is less intimate.  There
17769 	 * can be more than one stream bound to a particular
17770 	 * protocol.  When this is the case, each one gets a copy
17771 	 * of any incoming packets.
17772 	 */
17773 	ip_fanout_proto(q, first_mp, ill, ipha,
17774 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17775 	    B_TRUE, recv_ill, ire->ire_zoneid);
17776 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17777 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17778 	return;
17779 
17780 drop_pkt:
17781 	freemsg(first_mp);
17782 	if (hada_mp != NULL)
17783 		freeb(hada_mp);
17784 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17785 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17786 #undef	rptr
17787 #undef  iphs
17788 
17789 }
17790 
17791 /*
17792  * Update any source route, record route or timestamp options.
17793  * Check that we are at end of strict source route.
17794  * The options have already been checked for sanity in ip_rput_options().
17795  */
17796 static boolean_t
17797 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17798     ip_stack_t *ipst)
17799 {
17800 	ipoptp_t	opts;
17801 	uchar_t		*opt;
17802 	uint8_t		optval;
17803 	uint8_t		optlen;
17804 	ipaddr_t	dst;
17805 	uint32_t	ts;
17806 	ire_t		*dst_ire;
17807 	timestruc_t	now;
17808 	zoneid_t	zoneid;
17809 	ill_t		*ill;
17810 
17811 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17812 
17813 	ip2dbg(("ip_rput_local_options\n"));
17814 
17815 	for (optval = ipoptp_first(&opts, ipha);
17816 	    optval != IPOPT_EOL;
17817 	    optval = ipoptp_next(&opts)) {
17818 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17819 		opt = opts.ipoptp_cur;
17820 		optlen = opts.ipoptp_len;
17821 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17822 		    optval, optlen));
17823 		switch (optval) {
17824 			uint32_t off;
17825 		case IPOPT_SSRR:
17826 		case IPOPT_LSRR:
17827 			off = opt[IPOPT_OFFSET];
17828 			off--;
17829 			if (optlen < IP_ADDR_LEN ||
17830 			    off > optlen - IP_ADDR_LEN) {
17831 				/* End of source route */
17832 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17833 				break;
17834 			}
17835 			/*
17836 			 * This will only happen if two consecutive entries
17837 			 * in the source route contains our address or if
17838 			 * it is a packet with a loose source route which
17839 			 * reaches us before consuming the whole source route
17840 			 */
17841 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17842 			if (optval == IPOPT_SSRR) {
17843 				goto bad_src_route;
17844 			}
17845 			/*
17846 			 * Hack: instead of dropping the packet truncate the
17847 			 * source route to what has been used by filling the
17848 			 * rest with IPOPT_NOP.
17849 			 */
17850 			opt[IPOPT_OLEN] = (uint8_t)off;
17851 			while (off < optlen) {
17852 				opt[off++] = IPOPT_NOP;
17853 			}
17854 			break;
17855 		case IPOPT_RR:
17856 			off = opt[IPOPT_OFFSET];
17857 			off--;
17858 			if (optlen < IP_ADDR_LEN ||
17859 			    off > optlen - IP_ADDR_LEN) {
17860 				/* No more room - ignore */
17861 				ip1dbg((
17862 				    "ip_rput_local_options: end of RR\n"));
17863 				break;
17864 			}
17865 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17866 			    IP_ADDR_LEN);
17867 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17868 			break;
17869 		case IPOPT_TS:
17870 			/* Insert timestamp if there is romm */
17871 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17872 			case IPOPT_TS_TSONLY:
17873 				off = IPOPT_TS_TIMELEN;
17874 				break;
17875 			case IPOPT_TS_PRESPEC:
17876 			case IPOPT_TS_PRESPEC_RFC791:
17877 				/* Verify that the address matched */
17878 				off = opt[IPOPT_OFFSET] - 1;
17879 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17880 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17881 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17882 				    ipst);
17883 				if (dst_ire == NULL) {
17884 					/* Not for us */
17885 					break;
17886 				}
17887 				ire_refrele(dst_ire);
17888 				/* FALLTHRU */
17889 			case IPOPT_TS_TSANDADDR:
17890 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17891 				break;
17892 			default:
17893 				/*
17894 				 * ip_*put_options should have already
17895 				 * dropped this packet.
17896 				 */
17897 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17898 				    "unknown IT - bug in ip_rput_options?\n");
17899 				return (B_TRUE);	/* Keep "lint" happy */
17900 			}
17901 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17902 				/* Increase overflow counter */
17903 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17904 				opt[IPOPT_POS_OV_FLG] =
17905 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17906 				    (off << 4));
17907 				break;
17908 			}
17909 			off = opt[IPOPT_OFFSET] - 1;
17910 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17911 			case IPOPT_TS_PRESPEC:
17912 			case IPOPT_TS_PRESPEC_RFC791:
17913 			case IPOPT_TS_TSANDADDR:
17914 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17915 				    IP_ADDR_LEN);
17916 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17917 				/* FALLTHRU */
17918 			case IPOPT_TS_TSONLY:
17919 				off = opt[IPOPT_OFFSET] - 1;
17920 				/* Compute # of milliseconds since midnight */
17921 				gethrestime(&now);
17922 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17923 				    now.tv_nsec / (NANOSEC / MILLISEC);
17924 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17925 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17926 				break;
17927 			}
17928 			break;
17929 		}
17930 	}
17931 	return (B_TRUE);
17932 
17933 bad_src_route:
17934 	q = WR(q);
17935 	if (q->q_next != NULL)
17936 		ill = q->q_ptr;
17937 	else
17938 		ill = NULL;
17939 
17940 	/* make sure we clear any indication of a hardware checksum */
17941 	DB_CKSUMFLAGS(mp) = 0;
17942 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17943 	if (zoneid == ALL_ZONES)
17944 		freemsg(mp);
17945 	else
17946 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17947 	return (B_FALSE);
17948 
17949 }
17950 
17951 /*
17952  * Process IP options in an inbound packet.  If an option affects the
17953  * effective destination address, return the next hop address via dstp.
17954  * Returns -1 if something fails in which case an ICMP error has been sent
17955  * and mp freed.
17956  */
17957 static int
17958 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17959     ip_stack_t *ipst)
17960 {
17961 	ipoptp_t	opts;
17962 	uchar_t		*opt;
17963 	uint8_t		optval;
17964 	uint8_t		optlen;
17965 	ipaddr_t	dst;
17966 	intptr_t	code = 0;
17967 	ire_t		*ire = NULL;
17968 	zoneid_t	zoneid;
17969 	ill_t		*ill;
17970 
17971 	ip2dbg(("ip_rput_options\n"));
17972 	dst = ipha->ipha_dst;
17973 	for (optval = ipoptp_first(&opts, ipha);
17974 	    optval != IPOPT_EOL;
17975 	    optval = ipoptp_next(&opts)) {
17976 		opt = opts.ipoptp_cur;
17977 		optlen = opts.ipoptp_len;
17978 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17979 		    optval, optlen));
17980 		/*
17981 		 * Note: we need to verify the checksum before we
17982 		 * modify anything thus this routine only extracts the next
17983 		 * hop dst from any source route.
17984 		 */
17985 		switch (optval) {
17986 			uint32_t off;
17987 		case IPOPT_SSRR:
17988 		case IPOPT_LSRR:
17989 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17990 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17991 			if (ire == NULL) {
17992 				if (optval == IPOPT_SSRR) {
17993 					ip1dbg(("ip_rput_options: not next"
17994 					    " strict source route 0x%x\n",
17995 					    ntohl(dst)));
17996 					code = (char *)&ipha->ipha_dst -
17997 					    (char *)ipha;
17998 					goto param_prob; /* RouterReq's */
17999 				}
18000 				ip2dbg(("ip_rput_options: "
18001 				    "not next source route 0x%x\n",
18002 				    ntohl(dst)));
18003 				break;
18004 			}
18005 			ire_refrele(ire);
18006 
18007 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18008 				ip1dbg((
18009 				    "ip_rput_options: bad option offset\n"));
18010 				code = (char *)&opt[IPOPT_OLEN] -
18011 				    (char *)ipha;
18012 				goto param_prob;
18013 			}
18014 			off = opt[IPOPT_OFFSET];
18015 			off--;
18016 		redo_srr:
18017 			if (optlen < IP_ADDR_LEN ||
18018 			    off > optlen - IP_ADDR_LEN) {
18019 				/* End of source route */
18020 				ip1dbg(("ip_rput_options: end of SR\n"));
18021 				break;
18022 			}
18023 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18024 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18025 			    ntohl(dst)));
18026 
18027 			/*
18028 			 * Check if our address is present more than
18029 			 * once as consecutive hops in source route.
18030 			 * XXX verify per-interface ip_forwarding
18031 			 * for source route?
18032 			 */
18033 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18034 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18035 
18036 			if (ire != NULL) {
18037 				ire_refrele(ire);
18038 				off += IP_ADDR_LEN;
18039 				goto redo_srr;
18040 			}
18041 
18042 			if (dst == htonl(INADDR_LOOPBACK)) {
18043 				ip1dbg(("ip_rput_options: loopback addr in "
18044 				    "source route!\n"));
18045 				goto bad_src_route;
18046 			}
18047 			/*
18048 			 * For strict: verify that dst is directly
18049 			 * reachable.
18050 			 */
18051 			if (optval == IPOPT_SSRR) {
18052 				ire = ire_ftable_lookup(dst, 0, 0,
18053 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18054 				    MBLK_GETLABEL(mp),
18055 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18056 				if (ire == NULL) {
18057 					ip1dbg(("ip_rput_options: SSRR not "
18058 					    "directly reachable: 0x%x\n",
18059 					    ntohl(dst)));
18060 					goto bad_src_route;
18061 				}
18062 				ire_refrele(ire);
18063 			}
18064 			/*
18065 			 * Defer update of the offset and the record route
18066 			 * until the packet is forwarded.
18067 			 */
18068 			break;
18069 		case IPOPT_RR:
18070 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18071 				ip1dbg((
18072 				    "ip_rput_options: bad option offset\n"));
18073 				code = (char *)&opt[IPOPT_OLEN] -
18074 				    (char *)ipha;
18075 				goto param_prob;
18076 			}
18077 			break;
18078 		case IPOPT_TS:
18079 			/*
18080 			 * Verify that length >= 5 and that there is either
18081 			 * room for another timestamp or that the overflow
18082 			 * counter is not maxed out.
18083 			 */
18084 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18085 			if (optlen < IPOPT_MINLEN_IT) {
18086 				goto param_prob;
18087 			}
18088 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18089 				ip1dbg((
18090 				    "ip_rput_options: bad option offset\n"));
18091 				code = (char *)&opt[IPOPT_OFFSET] -
18092 				    (char *)ipha;
18093 				goto param_prob;
18094 			}
18095 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18096 			case IPOPT_TS_TSONLY:
18097 				off = IPOPT_TS_TIMELEN;
18098 				break;
18099 			case IPOPT_TS_TSANDADDR:
18100 			case IPOPT_TS_PRESPEC:
18101 			case IPOPT_TS_PRESPEC_RFC791:
18102 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18103 				break;
18104 			default:
18105 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18106 				    (char *)ipha;
18107 				goto param_prob;
18108 			}
18109 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18110 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18111 				/*
18112 				 * No room and the overflow counter is 15
18113 				 * already.
18114 				 */
18115 				goto param_prob;
18116 			}
18117 			break;
18118 		}
18119 	}
18120 
18121 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18122 		*dstp = dst;
18123 		return (0);
18124 	}
18125 
18126 	ip1dbg(("ip_rput_options: error processing IP options."));
18127 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18128 
18129 param_prob:
18130 	q = WR(q);
18131 	if (q->q_next != NULL)
18132 		ill = q->q_ptr;
18133 	else
18134 		ill = NULL;
18135 
18136 	/* make sure we clear any indication of a hardware checksum */
18137 	DB_CKSUMFLAGS(mp) = 0;
18138 	/* Don't know whether this is for non-global or global/forwarding */
18139 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18140 	if (zoneid == ALL_ZONES)
18141 		freemsg(mp);
18142 	else
18143 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18144 	return (-1);
18145 
18146 bad_src_route:
18147 	q = WR(q);
18148 	if (q->q_next != NULL)
18149 		ill = q->q_ptr;
18150 	else
18151 		ill = NULL;
18152 
18153 	/* make sure we clear any indication of a hardware checksum */
18154 	DB_CKSUMFLAGS(mp) = 0;
18155 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18156 	if (zoneid == ALL_ZONES)
18157 		freemsg(mp);
18158 	else
18159 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18160 	return (-1);
18161 }
18162 
18163 /*
18164  * IP & ICMP info in >=14 msg's ...
18165  *  - ip fixed part (mib2_ip_t)
18166  *  - icmp fixed part (mib2_icmp_t)
18167  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18168  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18169  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18170  *  - ipRouteAttributeTable (ip 102)	labeled routes
18171  *  - ip multicast membership (ip_member_t)
18172  *  - ip multicast source filtering (ip_grpsrc_t)
18173  *  - igmp fixed part (struct igmpstat)
18174  *  - multicast routing stats (struct mrtstat)
18175  *  - multicast routing vifs (array of struct vifctl)
18176  *  - multicast routing routes (array of struct mfcctl)
18177  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18178  *					One per ill plus one generic
18179  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18180  *					One per ill plus one generic
18181  *  - ipv6RouteEntry			all IPv6 IREs
18182  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18183  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18184  *  - ipv6AddrEntry			all IPv6 ipifs
18185  *  - ipv6 multicast membership (ipv6_member_t)
18186  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18187  *
18188  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18189  *
18190  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18191  * already filled in by the caller.
18192  * Return value of 0 indicates that no messages were sent and caller
18193  * should free mpctl.
18194  */
18195 int
18196 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18197 {
18198 	ip_stack_t *ipst;
18199 	sctp_stack_t *sctps;
18200 
18201 
18202 	if (q->q_next != NULL) {
18203 		ipst = ILLQ_TO_IPST(q);
18204 	} else {
18205 		ipst = CONNQ_TO_IPST(q);
18206 	}
18207 	ASSERT(ipst != NULL);
18208 	sctps = ipst->ips_netstack->netstack_sctp;
18209 
18210 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18211 		return (0);
18212 	}
18213 
18214 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18215 	    ipst)) == NULL) {
18216 		return (1);
18217 	}
18218 
18219 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18220 		return (1);
18221 	}
18222 
18223 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18224 		return (1);
18225 	}
18226 
18227 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18228 		return (1);
18229 	}
18230 
18231 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18232 		return (1);
18233 	}
18234 
18235 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18236 		return (1);
18237 	}
18238 
18239 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18240 		return (1);
18241 	}
18242 
18243 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18244 		return (1);
18245 	}
18246 
18247 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18248 		return (1);
18249 	}
18250 
18251 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18252 		return (1);
18253 	}
18254 
18255 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18256 		return (1);
18257 	}
18258 
18259 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18260 		return (1);
18261 	}
18262 
18263 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18264 		return (1);
18265 	}
18266 
18267 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18268 		return (1);
18269 	}
18270 
18271 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18272 		return (1);
18273 	}
18274 
18275 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18276 	if (mpctl == NULL) {
18277 		return (1);
18278 	}
18279 
18280 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18281 		return (1);
18282 	}
18283 	freemsg(mpctl);
18284 	return (1);
18285 }
18286 
18287 
18288 /* Get global (legacy) IPv4 statistics */
18289 static mblk_t *
18290 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18291     ip_stack_t *ipst)
18292 {
18293 	mib2_ip_t		old_ip_mib;
18294 	struct opthdr		*optp;
18295 	mblk_t			*mp2ctl;
18296 
18297 	/*
18298 	 * make a copy of the original message
18299 	 */
18300 	mp2ctl = copymsg(mpctl);
18301 
18302 	/* fixed length IP structure... */
18303 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18304 	optp->level = MIB2_IP;
18305 	optp->name = 0;
18306 	SET_MIB(old_ip_mib.ipForwarding,
18307 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18308 	SET_MIB(old_ip_mib.ipDefaultTTL,
18309 	    (uint32_t)ipst->ips_ip_def_ttl);
18310 	SET_MIB(old_ip_mib.ipReasmTimeout,
18311 	    ipst->ips_ip_g_frag_timeout);
18312 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18313 	    sizeof (mib2_ipAddrEntry_t));
18314 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18315 	    sizeof (mib2_ipRouteEntry_t));
18316 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18317 	    sizeof (mib2_ipNetToMediaEntry_t));
18318 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18319 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18320 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18321 	    sizeof (mib2_ipAttributeEntry_t));
18322 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18323 
18324 	/*
18325 	 * Grab the statistics from the new IP MIB
18326 	 */
18327 	SET_MIB(old_ip_mib.ipInReceives,
18328 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18329 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18330 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18331 	SET_MIB(old_ip_mib.ipForwDatagrams,
18332 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18333 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18334 	    ipmib->ipIfStatsInUnknownProtos);
18335 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18336 	SET_MIB(old_ip_mib.ipInDelivers,
18337 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18338 	SET_MIB(old_ip_mib.ipOutRequests,
18339 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18340 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18341 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18342 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18343 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18344 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18345 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18346 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18347 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18348 
18349 	/* ipRoutingDiscards is not being used */
18350 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18351 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18352 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18353 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18354 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18355 	    ipmib->ipIfStatsReasmDuplicates);
18356 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18357 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18358 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18359 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18360 	SET_MIB(old_ip_mib.rawipInOverflows,
18361 	    ipmib->rawipIfStatsInOverflows);
18362 
18363 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18364 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18365 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18366 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18367 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18368 	    ipmib->ipIfStatsOutSwitchIPVersion);
18369 
18370 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18371 	    (int)sizeof (old_ip_mib))) {
18372 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18373 		    (uint_t)sizeof (old_ip_mib)));
18374 	}
18375 
18376 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18377 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18378 	    (int)optp->level, (int)optp->name, (int)optp->len));
18379 	qreply(q, mpctl);
18380 	return (mp2ctl);
18381 }
18382 
18383 /* Per interface IPv4 statistics */
18384 static mblk_t *
18385 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18386 {
18387 	struct opthdr		*optp;
18388 	mblk_t			*mp2ctl;
18389 	ill_t			*ill;
18390 	ill_walk_context_t	ctx;
18391 	mblk_t			*mp_tail = NULL;
18392 	mib2_ipIfStatsEntry_t	global_ip_mib;
18393 
18394 	/*
18395 	 * Make a copy of the original message
18396 	 */
18397 	mp2ctl = copymsg(mpctl);
18398 
18399 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18400 	optp->level = MIB2_IP;
18401 	optp->name = MIB2_IP_TRAFFIC_STATS;
18402 	/* Include "unknown interface" ip_mib */
18403 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18404 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18405 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18406 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18407 	    (ipst->ips_ip_g_forward ? 1 : 2));
18408 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18409 	    (uint32_t)ipst->ips_ip_def_ttl);
18410 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18411 	    sizeof (mib2_ipIfStatsEntry_t));
18412 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18413 	    sizeof (mib2_ipAddrEntry_t));
18414 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18415 	    sizeof (mib2_ipRouteEntry_t));
18416 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18417 	    sizeof (mib2_ipNetToMediaEntry_t));
18418 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18419 	    sizeof (ip_member_t));
18420 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18421 	    sizeof (ip_grpsrc_t));
18422 
18423 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18424 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18425 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18426 		    "failed to allocate %u bytes\n",
18427 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18428 	}
18429 
18430 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18431 
18432 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18433 	ill = ILL_START_WALK_V4(&ctx, ipst);
18434 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18435 		ill->ill_ip_mib->ipIfStatsIfIndex =
18436 		    ill->ill_phyint->phyint_ifindex;
18437 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18438 		    (ipst->ips_ip_g_forward ? 1 : 2));
18439 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18440 		    (uint32_t)ipst->ips_ip_def_ttl);
18441 
18442 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18443 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18444 		    (char *)ill->ill_ip_mib,
18445 		    (int)sizeof (*ill->ill_ip_mib))) {
18446 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18447 			    "failed to allocate %u bytes\n",
18448 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18449 		}
18450 	}
18451 	rw_exit(&ipst->ips_ill_g_lock);
18452 
18453 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18454 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18455 	    "level %d, name %d, len %d\n",
18456 	    (int)optp->level, (int)optp->name, (int)optp->len));
18457 	qreply(q, mpctl);
18458 
18459 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18460 }
18461 
18462 /* Global IPv4 ICMP statistics */
18463 static mblk_t *
18464 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18465 {
18466 	struct opthdr		*optp;
18467 	mblk_t			*mp2ctl;
18468 
18469 	/*
18470 	 * Make a copy of the original message
18471 	 */
18472 	mp2ctl = copymsg(mpctl);
18473 
18474 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18475 	optp->level = MIB2_ICMP;
18476 	optp->name = 0;
18477 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18478 	    (int)sizeof (ipst->ips_icmp_mib))) {
18479 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18480 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18481 	}
18482 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18483 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18484 	    (int)optp->level, (int)optp->name, (int)optp->len));
18485 	qreply(q, mpctl);
18486 	return (mp2ctl);
18487 }
18488 
18489 /* Global IPv4 IGMP statistics */
18490 static mblk_t *
18491 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18492 {
18493 	struct opthdr		*optp;
18494 	mblk_t			*mp2ctl;
18495 
18496 	/*
18497 	 * make a copy of the original message
18498 	 */
18499 	mp2ctl = copymsg(mpctl);
18500 
18501 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18502 	optp->level = EXPER_IGMP;
18503 	optp->name = 0;
18504 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18505 	    (int)sizeof (ipst->ips_igmpstat))) {
18506 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18507 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18508 	}
18509 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18510 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18511 	    (int)optp->level, (int)optp->name, (int)optp->len));
18512 	qreply(q, mpctl);
18513 	return (mp2ctl);
18514 }
18515 
18516 /* Global IPv4 Multicast Routing statistics */
18517 static mblk_t *
18518 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18519 {
18520 	struct opthdr		*optp;
18521 	mblk_t			*mp2ctl;
18522 
18523 	/*
18524 	 * make a copy of the original message
18525 	 */
18526 	mp2ctl = copymsg(mpctl);
18527 
18528 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18529 	optp->level = EXPER_DVMRP;
18530 	optp->name = 0;
18531 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18532 		ip0dbg(("ip_mroute_stats: failed\n"));
18533 	}
18534 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18535 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18536 	    (int)optp->level, (int)optp->name, (int)optp->len));
18537 	qreply(q, mpctl);
18538 	return (mp2ctl);
18539 }
18540 
18541 /* IPv4 address information */
18542 static mblk_t *
18543 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18544 {
18545 	struct opthdr		*optp;
18546 	mblk_t			*mp2ctl;
18547 	mblk_t			*mp_tail = NULL;
18548 	ill_t			*ill;
18549 	ipif_t			*ipif;
18550 	uint_t			bitval;
18551 	mib2_ipAddrEntry_t	mae;
18552 	zoneid_t		zoneid;
18553 	ill_walk_context_t ctx;
18554 
18555 	/*
18556 	 * make a copy of the original message
18557 	 */
18558 	mp2ctl = copymsg(mpctl);
18559 
18560 	/* ipAddrEntryTable */
18561 
18562 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18563 	optp->level = MIB2_IP;
18564 	optp->name = MIB2_IP_ADDR;
18565 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18566 
18567 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18568 	ill = ILL_START_WALK_V4(&ctx, ipst);
18569 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18570 		for (ipif = ill->ill_ipif; ipif != NULL;
18571 		    ipif = ipif->ipif_next) {
18572 			if (ipif->ipif_zoneid != zoneid &&
18573 			    ipif->ipif_zoneid != ALL_ZONES)
18574 				continue;
18575 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18576 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18577 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18578 
18579 			(void) ipif_get_name(ipif,
18580 			    mae.ipAdEntIfIndex.o_bytes,
18581 			    OCTET_LENGTH);
18582 			mae.ipAdEntIfIndex.o_length =
18583 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18584 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18585 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18586 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18587 			mae.ipAdEntInfo.ae_subnet_len =
18588 			    ip_mask_to_plen(ipif->ipif_net_mask);
18589 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18590 			for (bitval = 1;
18591 			    bitval &&
18592 			    !(bitval & ipif->ipif_brd_addr);
18593 			    bitval <<= 1)
18594 				noop;
18595 			mae.ipAdEntBcastAddr = bitval;
18596 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18597 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18598 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18599 			mae.ipAdEntInfo.ae_broadcast_addr =
18600 			    ipif->ipif_brd_addr;
18601 			mae.ipAdEntInfo.ae_pp_dst_addr =
18602 			    ipif->ipif_pp_dst_addr;
18603 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18604 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18605 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18606 
18607 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18608 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18609 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18610 				    "allocate %u bytes\n",
18611 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18612 			}
18613 		}
18614 	}
18615 	rw_exit(&ipst->ips_ill_g_lock);
18616 
18617 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18618 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18619 	    (int)optp->level, (int)optp->name, (int)optp->len));
18620 	qreply(q, mpctl);
18621 	return (mp2ctl);
18622 }
18623 
18624 /* IPv6 address information */
18625 static mblk_t *
18626 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18627 {
18628 	struct opthdr		*optp;
18629 	mblk_t			*mp2ctl;
18630 	mblk_t			*mp_tail = NULL;
18631 	ill_t			*ill;
18632 	ipif_t			*ipif;
18633 	mib2_ipv6AddrEntry_t	mae6;
18634 	zoneid_t		zoneid;
18635 	ill_walk_context_t	ctx;
18636 
18637 	/*
18638 	 * make a copy of the original message
18639 	 */
18640 	mp2ctl = copymsg(mpctl);
18641 
18642 	/* ipv6AddrEntryTable */
18643 
18644 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18645 	optp->level = MIB2_IP6;
18646 	optp->name = MIB2_IP6_ADDR;
18647 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18648 
18649 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18650 	ill = ILL_START_WALK_V6(&ctx, ipst);
18651 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18652 		for (ipif = ill->ill_ipif; ipif != NULL;
18653 		    ipif = ipif->ipif_next) {
18654 			if (ipif->ipif_zoneid != zoneid &&
18655 			    ipif->ipif_zoneid != ALL_ZONES)
18656 				continue;
18657 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18658 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18659 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18660 
18661 			(void) ipif_get_name(ipif,
18662 			    mae6.ipv6AddrIfIndex.o_bytes,
18663 			    OCTET_LENGTH);
18664 			mae6.ipv6AddrIfIndex.o_length =
18665 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18666 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18667 			mae6.ipv6AddrPfxLength =
18668 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18669 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18670 			mae6.ipv6AddrInfo.ae_subnet_len =
18671 			    mae6.ipv6AddrPfxLength;
18672 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18673 
18674 			/* Type: stateless(1), stateful(2), unknown(3) */
18675 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18676 				mae6.ipv6AddrType = 1;
18677 			else
18678 				mae6.ipv6AddrType = 2;
18679 			/* Anycast: true(1), false(2) */
18680 			if (ipif->ipif_flags & IPIF_ANYCAST)
18681 				mae6.ipv6AddrAnycastFlag = 1;
18682 			else
18683 				mae6.ipv6AddrAnycastFlag = 2;
18684 
18685 			/*
18686 			 * Address status: preferred(1), deprecated(2),
18687 			 * invalid(3), inaccessible(4), unknown(5)
18688 			 */
18689 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18690 				mae6.ipv6AddrStatus = 3;
18691 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18692 				mae6.ipv6AddrStatus = 2;
18693 			else
18694 				mae6.ipv6AddrStatus = 1;
18695 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18696 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18697 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18698 						ipif->ipif_v6pp_dst_addr;
18699 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18700 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18701 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18702 			mae6.ipv6AddrIdentifier = ill->ill_token;
18703 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18704 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18705 			mae6.ipv6AddrRetransmitTime =
18706 			    ill->ill_reachable_retrans_time;
18707 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18708 				(char *)&mae6,
18709 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18710 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18711 				    "allocate %u bytes\n",
18712 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18713 			}
18714 		}
18715 	}
18716 	rw_exit(&ipst->ips_ill_g_lock);
18717 
18718 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18719 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18720 	    (int)optp->level, (int)optp->name, (int)optp->len));
18721 	qreply(q, mpctl);
18722 	return (mp2ctl);
18723 }
18724 
18725 /* IPv4 multicast group membership. */
18726 static mblk_t *
18727 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18728 {
18729 	struct opthdr		*optp;
18730 	mblk_t			*mp2ctl;
18731 	ill_t			*ill;
18732 	ipif_t			*ipif;
18733 	ilm_t			*ilm;
18734 	ip_member_t		ipm;
18735 	mblk_t			*mp_tail = NULL;
18736 	ill_walk_context_t	ctx;
18737 	zoneid_t		zoneid;
18738 
18739 	/*
18740 	 * make a copy of the original message
18741 	 */
18742 	mp2ctl = copymsg(mpctl);
18743 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18744 
18745 	/* ipGroupMember table */
18746 	optp = (struct opthdr *)&mpctl->b_rptr[
18747 	    sizeof (struct T_optmgmt_ack)];
18748 	optp->level = MIB2_IP;
18749 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18750 
18751 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18752 	ill = ILL_START_WALK_V4(&ctx, ipst);
18753 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18754 		ILM_WALKER_HOLD(ill);
18755 		for (ipif = ill->ill_ipif; ipif != NULL;
18756 		    ipif = ipif->ipif_next) {
18757 			if (ipif->ipif_zoneid != zoneid &&
18758 			    ipif->ipif_zoneid != ALL_ZONES)
18759 				continue;	/* not this zone */
18760 			(void) ipif_get_name(ipif,
18761 			    ipm.ipGroupMemberIfIndex.o_bytes,
18762 			    OCTET_LENGTH);
18763 			ipm.ipGroupMemberIfIndex.o_length =
18764 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18765 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18766 				ASSERT(ilm->ilm_ipif != NULL);
18767 				ASSERT(ilm->ilm_ill == NULL);
18768 				if (ilm->ilm_ipif != ipif)
18769 					continue;
18770 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18771 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18772 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18773 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18774 				    (char *)&ipm, (int)sizeof (ipm))) {
18775 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18776 					    "failed to allocate %u bytes\n",
18777 						(uint_t)sizeof (ipm)));
18778 				}
18779 			}
18780 		}
18781 		ILM_WALKER_RELE(ill);
18782 	}
18783 	rw_exit(&ipst->ips_ill_g_lock);
18784 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18785 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18786 	    (int)optp->level, (int)optp->name, (int)optp->len));
18787 	qreply(q, mpctl);
18788 	return (mp2ctl);
18789 }
18790 
18791 /* IPv6 multicast group membership. */
18792 static mblk_t *
18793 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18794 {
18795 	struct opthdr		*optp;
18796 	mblk_t			*mp2ctl;
18797 	ill_t			*ill;
18798 	ilm_t			*ilm;
18799 	ipv6_member_t		ipm6;
18800 	mblk_t			*mp_tail = NULL;
18801 	ill_walk_context_t	ctx;
18802 	zoneid_t		zoneid;
18803 
18804 	/*
18805 	 * make a copy of the original message
18806 	 */
18807 	mp2ctl = copymsg(mpctl);
18808 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18809 
18810 	/* ip6GroupMember table */
18811 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18812 	optp->level = MIB2_IP6;
18813 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18814 
18815 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18816 	ill = ILL_START_WALK_V6(&ctx, ipst);
18817 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18818 		ILM_WALKER_HOLD(ill);
18819 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18820 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18821 			ASSERT(ilm->ilm_ipif == NULL);
18822 			ASSERT(ilm->ilm_ill != NULL);
18823 			if (ilm->ilm_zoneid != zoneid)
18824 				continue;	/* not this zone */
18825 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18826 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18827 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18828 			if (!snmp_append_data2(mpctl->b_cont,
18829 			    &mp_tail,
18830 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18831 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18832 				    "failed to allocate %u bytes\n",
18833 				    (uint_t)sizeof (ipm6)));
18834 			}
18835 		}
18836 		ILM_WALKER_RELE(ill);
18837 	}
18838 	rw_exit(&ipst->ips_ill_g_lock);
18839 
18840 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18841 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18842 	    (int)optp->level, (int)optp->name, (int)optp->len));
18843 	qreply(q, mpctl);
18844 	return (mp2ctl);
18845 }
18846 
18847 /* IP multicast filtered sources */
18848 static mblk_t *
18849 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18850 {
18851 	struct opthdr		*optp;
18852 	mblk_t			*mp2ctl;
18853 	ill_t			*ill;
18854 	ipif_t			*ipif;
18855 	ilm_t			*ilm;
18856 	ip_grpsrc_t		ips;
18857 	mblk_t			*mp_tail = NULL;
18858 	ill_walk_context_t	ctx;
18859 	zoneid_t		zoneid;
18860 	int			i;
18861 	slist_t			*sl;
18862 
18863 	/*
18864 	 * make a copy of the original message
18865 	 */
18866 	mp2ctl = copymsg(mpctl);
18867 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18868 
18869 	/* ipGroupSource table */
18870 	optp = (struct opthdr *)&mpctl->b_rptr[
18871 	    sizeof (struct T_optmgmt_ack)];
18872 	optp->level = MIB2_IP;
18873 	optp->name = EXPER_IP_GROUP_SOURCES;
18874 
18875 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18876 	ill = ILL_START_WALK_V4(&ctx, ipst);
18877 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18878 		ILM_WALKER_HOLD(ill);
18879 		for (ipif = ill->ill_ipif; ipif != NULL;
18880 		    ipif = ipif->ipif_next) {
18881 			if (ipif->ipif_zoneid != zoneid)
18882 				continue;	/* not this zone */
18883 			(void) ipif_get_name(ipif,
18884 			    ips.ipGroupSourceIfIndex.o_bytes,
18885 			    OCTET_LENGTH);
18886 			ips.ipGroupSourceIfIndex.o_length =
18887 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18888 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18889 				ASSERT(ilm->ilm_ipif != NULL);
18890 				ASSERT(ilm->ilm_ill == NULL);
18891 				sl = ilm->ilm_filter;
18892 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18893 					continue;
18894 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18895 				for (i = 0; i < sl->sl_numsrc; i++) {
18896 					if (!IN6_IS_ADDR_V4MAPPED(
18897 					    &sl->sl_addr[i]))
18898 						continue;
18899 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18900 					    ips.ipGroupSourceAddress);
18901 					if (snmp_append_data2(mpctl->b_cont,
18902 					    &mp_tail, (char *)&ips,
18903 					    (int)sizeof (ips)) == 0) {
18904 						ip1dbg(("ip_snmp_get_mib2_"
18905 						    "ip_group_src: failed to "
18906 						    "allocate %u bytes\n",
18907 						    (uint_t)sizeof (ips)));
18908 					}
18909 				}
18910 			}
18911 		}
18912 		ILM_WALKER_RELE(ill);
18913 	}
18914 	rw_exit(&ipst->ips_ill_g_lock);
18915 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18916 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18917 	    (int)optp->level, (int)optp->name, (int)optp->len));
18918 	qreply(q, mpctl);
18919 	return (mp2ctl);
18920 }
18921 
18922 /* IPv6 multicast filtered sources. */
18923 static mblk_t *
18924 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18925 {
18926 	struct opthdr		*optp;
18927 	mblk_t			*mp2ctl;
18928 	ill_t			*ill;
18929 	ilm_t			*ilm;
18930 	ipv6_grpsrc_t		ips6;
18931 	mblk_t			*mp_tail = NULL;
18932 	ill_walk_context_t	ctx;
18933 	zoneid_t		zoneid;
18934 	int			i;
18935 	slist_t			*sl;
18936 
18937 	/*
18938 	 * make a copy of the original message
18939 	 */
18940 	mp2ctl = copymsg(mpctl);
18941 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18942 
18943 	/* ip6GroupMember table */
18944 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18945 	optp->level = MIB2_IP6;
18946 	optp->name = EXPER_IP6_GROUP_SOURCES;
18947 
18948 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18949 	ill = ILL_START_WALK_V6(&ctx, ipst);
18950 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18951 		ILM_WALKER_HOLD(ill);
18952 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18953 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18954 			ASSERT(ilm->ilm_ipif == NULL);
18955 			ASSERT(ilm->ilm_ill != NULL);
18956 			sl = ilm->ilm_filter;
18957 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18958 				continue;
18959 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18960 			for (i = 0; i < sl->sl_numsrc; i++) {
18961 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18962 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18963 				    (char *)&ips6, (int)sizeof (ips6))) {
18964 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18965 					    "group_src: failed to allocate "
18966 					    "%u bytes\n",
18967 					    (uint_t)sizeof (ips6)));
18968 				}
18969 			}
18970 		}
18971 		ILM_WALKER_RELE(ill);
18972 	}
18973 	rw_exit(&ipst->ips_ill_g_lock);
18974 
18975 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18976 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18977 	    (int)optp->level, (int)optp->name, (int)optp->len));
18978 	qreply(q, mpctl);
18979 	return (mp2ctl);
18980 }
18981 
18982 /* Multicast routing virtual interface table. */
18983 static mblk_t *
18984 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18985 {
18986 	struct opthdr		*optp;
18987 	mblk_t			*mp2ctl;
18988 
18989 	/*
18990 	 * make a copy of the original message
18991 	 */
18992 	mp2ctl = copymsg(mpctl);
18993 
18994 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18995 	optp->level = EXPER_DVMRP;
18996 	optp->name = EXPER_DVMRP_VIF;
18997 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18998 		ip0dbg(("ip_mroute_vif: failed\n"));
18999 	}
19000 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19001 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19002 	    (int)optp->level, (int)optp->name, (int)optp->len));
19003 	qreply(q, mpctl);
19004 	return (mp2ctl);
19005 }
19006 
19007 /* Multicast routing table. */
19008 static mblk_t *
19009 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19010 {
19011 	struct opthdr		*optp;
19012 	mblk_t			*mp2ctl;
19013 
19014 	/*
19015 	 * make a copy of the original message
19016 	 */
19017 	mp2ctl = copymsg(mpctl);
19018 
19019 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19020 	optp->level = EXPER_DVMRP;
19021 	optp->name = EXPER_DVMRP_MRT;
19022 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19023 		ip0dbg(("ip_mroute_mrt: failed\n"));
19024 	}
19025 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19026 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19027 	    (int)optp->level, (int)optp->name, (int)optp->len));
19028 	qreply(q, mpctl);
19029 	return (mp2ctl);
19030 }
19031 
19032 /*
19033  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19034  * in one IRE walk.
19035  */
19036 static mblk_t *
19037 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19038 {
19039 	struct opthdr	*optp;
19040 	mblk_t		*mp2ctl;	/* Returned */
19041 	mblk_t		*mp3ctl;	/* nettomedia */
19042 	mblk_t		*mp4ctl;	/* routeattrs */
19043 	iproutedata_t	ird;
19044 	zoneid_t	zoneid;
19045 
19046 	/*
19047 	 * make copies of the original message
19048 	 *	- mp2ctl is returned unchanged to the caller for his use
19049 	 *	- mpctl is sent upstream as ipRouteEntryTable
19050 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19051 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19052 	 */
19053 	mp2ctl = copymsg(mpctl);
19054 	mp3ctl = copymsg(mpctl);
19055 	mp4ctl = copymsg(mpctl);
19056 	if (mp3ctl == NULL || mp4ctl == NULL) {
19057 		freemsg(mp4ctl);
19058 		freemsg(mp3ctl);
19059 		freemsg(mp2ctl);
19060 		freemsg(mpctl);
19061 		return (NULL);
19062 	}
19063 
19064 	bzero(&ird, sizeof (ird));
19065 
19066 	ird.ird_route.lp_head = mpctl->b_cont;
19067 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19068 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19069 
19070 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19071 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19072 	if (zoneid == GLOBAL_ZONEID) {
19073 		/*
19074 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19075 		 * requires the sys_net_config or sys_ip_config privilege,
19076 		 * it can only run in the global zone or an exclusive-IP zone,
19077 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19078 		 */
19079 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19080 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19081 	}
19082 
19083 	/* ipRouteEntryTable in mpctl */
19084 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19085 	optp->level = MIB2_IP;
19086 	optp->name = MIB2_IP_ROUTE;
19087 	optp->len = msgdsize(ird.ird_route.lp_head);
19088 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19089 	    (int)optp->level, (int)optp->name, (int)optp->len));
19090 	qreply(q, mpctl);
19091 
19092 	/* ipNetToMediaEntryTable in mp3ctl */
19093 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19094 	optp->level = MIB2_IP;
19095 	optp->name = MIB2_IP_MEDIA;
19096 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19097 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19098 	    (int)optp->level, (int)optp->name, (int)optp->len));
19099 	qreply(q, mp3ctl);
19100 
19101 	/* ipRouteAttributeTable in mp4ctl */
19102 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19103 	optp->level = MIB2_IP;
19104 	optp->name = EXPER_IP_RTATTR;
19105 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19106 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19107 	    (int)optp->level, (int)optp->name, (int)optp->len));
19108 	if (optp->len == 0)
19109 		freemsg(mp4ctl);
19110 	else
19111 		qreply(q, mp4ctl);
19112 
19113 	return (mp2ctl);
19114 }
19115 
19116 /*
19117  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19118  * ipv6NetToMediaEntryTable in an NDP walk.
19119  */
19120 static mblk_t *
19121 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19122 {
19123 	struct opthdr	*optp;
19124 	mblk_t		*mp2ctl;	/* Returned */
19125 	mblk_t		*mp3ctl;	/* nettomedia */
19126 	mblk_t		*mp4ctl;	/* routeattrs */
19127 	iproutedata_t	ird;
19128 	zoneid_t	zoneid;
19129 
19130 	/*
19131 	 * make copies of the original message
19132 	 *	- mp2ctl is returned unchanged to the caller for his use
19133 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19134 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19135 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19136 	 */
19137 	mp2ctl = copymsg(mpctl);
19138 	mp3ctl = copymsg(mpctl);
19139 	mp4ctl = copymsg(mpctl);
19140 	if (mp3ctl == NULL || mp4ctl == NULL) {
19141 		freemsg(mp4ctl);
19142 		freemsg(mp3ctl);
19143 		freemsg(mp2ctl);
19144 		freemsg(mpctl);
19145 		return (NULL);
19146 	}
19147 
19148 	bzero(&ird, sizeof (ird));
19149 
19150 	ird.ird_route.lp_head = mpctl->b_cont;
19151 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19152 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19153 
19154 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19155 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19156 
19157 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19158 	optp->level = MIB2_IP6;
19159 	optp->name = MIB2_IP6_ROUTE;
19160 	optp->len = msgdsize(ird.ird_route.lp_head);
19161 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19162 	    (int)optp->level, (int)optp->name, (int)optp->len));
19163 	qreply(q, mpctl);
19164 
19165 	/* ipv6NetToMediaEntryTable in mp3ctl */
19166 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19167 
19168 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19169 	optp->level = MIB2_IP6;
19170 	optp->name = MIB2_IP6_MEDIA;
19171 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19172 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19173 	    (int)optp->level, (int)optp->name, (int)optp->len));
19174 	qreply(q, mp3ctl);
19175 
19176 	/* ipv6RouteAttributeTable in mp4ctl */
19177 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19178 	optp->level = MIB2_IP6;
19179 	optp->name = EXPER_IP_RTATTR;
19180 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19181 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19182 	    (int)optp->level, (int)optp->name, (int)optp->len));
19183 	if (optp->len == 0)
19184 		freemsg(mp4ctl);
19185 	else
19186 		qreply(q, mp4ctl);
19187 
19188 	return (mp2ctl);
19189 }
19190 
19191 /*
19192  * IPv6 mib: One per ill
19193  */
19194 static mblk_t *
19195 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19196 {
19197 	struct opthdr		*optp;
19198 	mblk_t			*mp2ctl;
19199 	ill_t			*ill;
19200 	ill_walk_context_t	ctx;
19201 	mblk_t			*mp_tail = NULL;
19202 
19203 	/*
19204 	 * Make a copy of the original message
19205 	 */
19206 	mp2ctl = copymsg(mpctl);
19207 
19208 	/* fixed length IPv6 structure ... */
19209 
19210 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19211 	optp->level = MIB2_IP6;
19212 	optp->name = 0;
19213 	/* Include "unknown interface" ip6_mib */
19214 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19215 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19216 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19217 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19218 	    ipst->ips_ipv6_forward ? 1 : 2);
19219 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19220 	    ipst->ips_ipv6_def_hops);
19221 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19222 	    sizeof (mib2_ipIfStatsEntry_t));
19223 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19224 	    sizeof (mib2_ipv6AddrEntry_t));
19225 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19226 	    sizeof (mib2_ipv6RouteEntry_t));
19227 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19228 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19229 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19230 	    sizeof (ipv6_member_t));
19231 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19232 	    sizeof (ipv6_grpsrc_t));
19233 
19234 	/*
19235 	 * Synchronize 64- and 32-bit counters
19236 	 */
19237 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19238 	    ipIfStatsHCInReceives);
19239 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19240 	    ipIfStatsHCInDelivers);
19241 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19242 	    ipIfStatsHCOutRequests);
19243 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19244 	    ipIfStatsHCOutForwDatagrams);
19245 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19246 	    ipIfStatsHCOutMcastPkts);
19247 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19248 	    ipIfStatsHCInMcastPkts);
19249 
19250 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19251 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19252 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19253 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19254 	}
19255 
19256 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19257 	ill = ILL_START_WALK_V6(&ctx, ipst);
19258 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19259 		ill->ill_ip_mib->ipIfStatsIfIndex =
19260 		    ill->ill_phyint->phyint_ifindex;
19261 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19262 		    ipst->ips_ipv6_forward ? 1 : 2);
19263 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19264 		    ill->ill_max_hops);
19265 
19266 		/*
19267 		 * Synchronize 64- and 32-bit counters
19268 		 */
19269 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19270 		    ipIfStatsHCInReceives);
19271 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19272 		    ipIfStatsHCInDelivers);
19273 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19274 		    ipIfStatsHCOutRequests);
19275 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19276 		    ipIfStatsHCOutForwDatagrams);
19277 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19278 		    ipIfStatsHCOutMcastPkts);
19279 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19280 		    ipIfStatsHCInMcastPkts);
19281 
19282 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19283 		    (char *)ill->ill_ip_mib,
19284 		    (int)sizeof (*ill->ill_ip_mib))) {
19285 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19286 				"%u bytes\n",
19287 				(uint_t)sizeof (*ill->ill_ip_mib)));
19288 		}
19289 	}
19290 	rw_exit(&ipst->ips_ill_g_lock);
19291 
19292 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19293 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19294 	    (int)optp->level, (int)optp->name, (int)optp->len));
19295 	qreply(q, mpctl);
19296 	return (mp2ctl);
19297 }
19298 
19299 /*
19300  * ICMPv6 mib: One per ill
19301  */
19302 static mblk_t *
19303 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19304 {
19305 	struct opthdr		*optp;
19306 	mblk_t			*mp2ctl;
19307 	ill_t			*ill;
19308 	ill_walk_context_t	ctx;
19309 	mblk_t			*mp_tail = NULL;
19310 	/*
19311 	 * Make a copy of the original message
19312 	 */
19313 	mp2ctl = copymsg(mpctl);
19314 
19315 	/* fixed length ICMPv6 structure ... */
19316 
19317 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19318 	optp->level = MIB2_ICMP6;
19319 	optp->name = 0;
19320 	/* Include "unknown interface" icmp6_mib */
19321 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19322 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19323 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19324 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19325 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19326 	    (char *)&ipst->ips_icmp6_mib,
19327 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19328 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19329 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19330 	}
19331 
19332 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19333 	ill = ILL_START_WALK_V6(&ctx, ipst);
19334 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19335 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19336 		    ill->ill_phyint->phyint_ifindex;
19337 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19338 		    (char *)ill->ill_icmp6_mib,
19339 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19340 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19341 			    "%u bytes\n",
19342 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19343 		}
19344 	}
19345 	rw_exit(&ipst->ips_ill_g_lock);
19346 
19347 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19348 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19349 	    (int)optp->level, (int)optp->name, (int)optp->len));
19350 	qreply(q, mpctl);
19351 	return (mp2ctl);
19352 }
19353 
19354 /*
19355  * ire_walk routine to create both ipRouteEntryTable and
19356  * ipRouteAttributeTable in one IRE walk
19357  */
19358 static void
19359 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19360 {
19361 	ill_t				*ill;
19362 	ipif_t				*ipif;
19363 	mib2_ipRouteEntry_t		*re;
19364 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19365 	ipaddr_t			gw_addr;
19366 	tsol_ire_gw_secattr_t		*attrp;
19367 	tsol_gc_t			*gc = NULL;
19368 	tsol_gcgrp_t			*gcgrp = NULL;
19369 	uint_t				sacnt = 0;
19370 	int				i;
19371 
19372 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19373 
19374 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19375 		return;
19376 
19377 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19378 		mutex_enter(&attrp->igsa_lock);
19379 		if ((gc = attrp->igsa_gc) != NULL) {
19380 			gcgrp = gc->gc_grp;
19381 			ASSERT(gcgrp != NULL);
19382 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19383 			sacnt = 1;
19384 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19385 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19386 			gc = gcgrp->gcgrp_head;
19387 			sacnt = gcgrp->gcgrp_count;
19388 		}
19389 		mutex_exit(&attrp->igsa_lock);
19390 
19391 		/* do nothing if there's no gc to report */
19392 		if (gc == NULL) {
19393 			ASSERT(sacnt == 0);
19394 			if (gcgrp != NULL) {
19395 				/* we might as well drop the lock now */
19396 				rw_exit(&gcgrp->gcgrp_rwlock);
19397 				gcgrp = NULL;
19398 			}
19399 			attrp = NULL;
19400 		}
19401 
19402 		ASSERT(gc == NULL || (gcgrp != NULL &&
19403 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19404 	}
19405 	ASSERT(sacnt == 0 || gc != NULL);
19406 
19407 	if (sacnt != 0 &&
19408 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19409 		kmem_free(re, sizeof (*re));
19410 		rw_exit(&gcgrp->gcgrp_rwlock);
19411 		return;
19412 	}
19413 
19414 	/*
19415 	 * Return all IRE types for route table... let caller pick and choose
19416 	 */
19417 	re->ipRouteDest = ire->ire_addr;
19418 	ipif = ire->ire_ipif;
19419 	re->ipRouteIfIndex.o_length = 0;
19420 	if (ire->ire_type == IRE_CACHE) {
19421 		ill = (ill_t *)ire->ire_stq->q_ptr;
19422 		re->ipRouteIfIndex.o_length =
19423 		    ill->ill_name_length == 0 ? 0 :
19424 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19425 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19426 		    re->ipRouteIfIndex.o_length);
19427 	} else if (ipif != NULL) {
19428 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19429 		    OCTET_LENGTH);
19430 		re->ipRouteIfIndex.o_length =
19431 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19432 	}
19433 	re->ipRouteMetric1 = -1;
19434 	re->ipRouteMetric2 = -1;
19435 	re->ipRouteMetric3 = -1;
19436 	re->ipRouteMetric4 = -1;
19437 
19438 	gw_addr = ire->ire_gateway_addr;
19439 
19440 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19441 		re->ipRouteNextHop = ire->ire_src_addr;
19442 	else
19443 		re->ipRouteNextHop = gw_addr;
19444 	/* indirect(4), direct(3), or invalid(2) */
19445 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19446 		re->ipRouteType = 2;
19447 	else
19448 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19449 	re->ipRouteProto = -1;
19450 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19451 	re->ipRouteMask = ire->ire_mask;
19452 	re->ipRouteMetric5 = -1;
19453 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19454 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19455 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19456 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19457 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19458 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19459 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19460 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19461 	re->ipRouteInfo.re_in_ill.o_length = 0;
19462 
19463 	if (ire->ire_flags & RTF_DYNAMIC) {
19464 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19465 	} else {
19466 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19467 	}
19468 
19469 	if (ire->ire_in_ill != NULL) {
19470 		re->ipRouteInfo.re_in_ill.o_length =
19471 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19472 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19473 		bcopy(ire->ire_in_ill->ill_name,
19474 		    re->ipRouteInfo.re_in_ill.o_bytes,
19475 		    re->ipRouteInfo.re_in_ill.o_length);
19476 	}
19477 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19478 
19479 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19480 	    (char *)re, (int)sizeof (*re))) {
19481 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19482 		    (uint_t)sizeof (*re)));
19483 	}
19484 
19485 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19486 		iaeptr->iae_routeidx = ird->ird_idx;
19487 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19488 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19489 	}
19490 
19491 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19492 	    (char *)iae, sacnt * sizeof (*iae))) {
19493 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19494 		    (unsigned)(sacnt * sizeof (*iae))));
19495 	}
19496 
19497 	/* bump route index for next pass */
19498 	ird->ird_idx++;
19499 
19500 	kmem_free(re, sizeof (*re));
19501 	if (sacnt != 0)
19502 		kmem_free(iae, sacnt * sizeof (*iae));
19503 
19504 	if (gcgrp != NULL)
19505 		rw_exit(&gcgrp->gcgrp_rwlock);
19506 }
19507 
19508 /*
19509  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19510  */
19511 static void
19512 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19513 {
19514 	ill_t				*ill;
19515 	ipif_t				*ipif;
19516 	mib2_ipv6RouteEntry_t		*re;
19517 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19518 	in6_addr_t			gw_addr_v6;
19519 	tsol_ire_gw_secattr_t		*attrp;
19520 	tsol_gc_t			*gc = NULL;
19521 	tsol_gcgrp_t			*gcgrp = NULL;
19522 	uint_t				sacnt = 0;
19523 	int				i;
19524 
19525 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19526 
19527 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19528 		return;
19529 
19530 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19531 		mutex_enter(&attrp->igsa_lock);
19532 		if ((gc = attrp->igsa_gc) != NULL) {
19533 			gcgrp = gc->gc_grp;
19534 			ASSERT(gcgrp != NULL);
19535 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19536 			sacnt = 1;
19537 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19538 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19539 			gc = gcgrp->gcgrp_head;
19540 			sacnt = gcgrp->gcgrp_count;
19541 		}
19542 		mutex_exit(&attrp->igsa_lock);
19543 
19544 		/* do nothing if there's no gc to report */
19545 		if (gc == NULL) {
19546 			ASSERT(sacnt == 0);
19547 			if (gcgrp != NULL) {
19548 				/* we might as well drop the lock now */
19549 				rw_exit(&gcgrp->gcgrp_rwlock);
19550 				gcgrp = NULL;
19551 			}
19552 			attrp = NULL;
19553 		}
19554 
19555 		ASSERT(gc == NULL || (gcgrp != NULL &&
19556 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19557 	}
19558 	ASSERT(sacnt == 0 || gc != NULL);
19559 
19560 	if (sacnt != 0 &&
19561 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19562 		kmem_free(re, sizeof (*re));
19563 		rw_exit(&gcgrp->gcgrp_rwlock);
19564 		return;
19565 	}
19566 
19567 	/*
19568 	 * Return all IRE types for route table... let caller pick and choose
19569 	 */
19570 	re->ipv6RouteDest = ire->ire_addr_v6;
19571 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19572 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19573 	re->ipv6RouteIfIndex.o_length = 0;
19574 	ipif = ire->ire_ipif;
19575 	if (ire->ire_type == IRE_CACHE) {
19576 		ill = (ill_t *)ire->ire_stq->q_ptr;
19577 		re->ipv6RouteIfIndex.o_length =
19578 		    ill->ill_name_length == 0 ? 0 :
19579 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19580 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19581 		    re->ipv6RouteIfIndex.o_length);
19582 	} else if (ipif != NULL) {
19583 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19584 		    OCTET_LENGTH);
19585 		re->ipv6RouteIfIndex.o_length =
19586 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19587 	}
19588 
19589 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19590 
19591 	mutex_enter(&ire->ire_lock);
19592 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19593 	mutex_exit(&ire->ire_lock);
19594 
19595 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19596 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19597 	else
19598 		re->ipv6RouteNextHop = gw_addr_v6;
19599 
19600 	/* remote(4), local(3), or discard(2) */
19601 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19602 		re->ipv6RouteType = 2;
19603 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19604 		re->ipv6RouteType = 3;
19605 	else
19606 		re->ipv6RouteType = 4;
19607 
19608 	re->ipv6RouteProtocol	= -1;
19609 	re->ipv6RoutePolicy	= 0;
19610 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19611 	re->ipv6RouteNextHopRDI	= 0;
19612 	re->ipv6RouteWeight	= 0;
19613 	re->ipv6RouteMetric	= 0;
19614 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19615 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19616 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19617 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19618 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19619 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19620 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19621 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19622 
19623 	if (ire->ire_flags & RTF_DYNAMIC) {
19624 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19625 	} else {
19626 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19627 	}
19628 
19629 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19630 	    (char *)re, (int)sizeof (*re))) {
19631 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19632 		    (uint_t)sizeof (*re)));
19633 	}
19634 
19635 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19636 		iaeptr->iae_routeidx = ird->ird_idx;
19637 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19638 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19639 	}
19640 
19641 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19642 	    (char *)iae, sacnt * sizeof (*iae))) {
19643 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19644 		    (unsigned)(sacnt * sizeof (*iae))));
19645 	}
19646 
19647 	/* bump route index for next pass */
19648 	ird->ird_idx++;
19649 
19650 	kmem_free(re, sizeof (*re));
19651 	if (sacnt != 0)
19652 		kmem_free(iae, sacnt * sizeof (*iae));
19653 
19654 	if (gcgrp != NULL)
19655 		rw_exit(&gcgrp->gcgrp_rwlock);
19656 }
19657 
19658 /*
19659  * ndp_walk routine to create ipv6NetToMediaEntryTable
19660  */
19661 static int
19662 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19663 {
19664 	ill_t				*ill;
19665 	mib2_ipv6NetToMediaEntry_t	ntme;
19666 	dl_unitdata_req_t		*dl;
19667 
19668 	ill = nce->nce_ill;
19669 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19670 		return (0);
19671 
19672 	/*
19673 	 * Neighbor cache entry attached to IRE with on-link
19674 	 * destination.
19675 	 */
19676 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19677 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19678 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19679 	    (nce->nce_res_mp != NULL)) {
19680 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19681 		ntme.ipv6NetToMediaPhysAddress.o_length =
19682 		    dl->dl_dest_addr_length;
19683 	} else {
19684 		ntme.ipv6NetToMediaPhysAddress.o_length =
19685 		    ill->ill_phys_addr_length;
19686 	}
19687 	if (nce->nce_res_mp != NULL) {
19688 		bcopy((char *)nce->nce_res_mp->b_rptr +
19689 		    NCE_LL_ADDR_OFFSET(ill),
19690 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19691 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19692 	} else {
19693 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19694 		    ill->ill_phys_addr_length);
19695 	}
19696 	/*
19697 	 * Note: Returns ND_* states. Should be:
19698 	 * reachable(1), stale(2), delay(3), probe(4),
19699 	 * invalid(5), unknown(6)
19700 	 */
19701 	ntme.ipv6NetToMediaState = nce->nce_state;
19702 	ntme.ipv6NetToMediaLastUpdated = 0;
19703 
19704 	/* other(1), dynamic(2), static(3), local(4) */
19705 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19706 		ntme.ipv6NetToMediaType = 4;
19707 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19708 		ntme.ipv6NetToMediaType = 1;
19709 	} else {
19710 		ntme.ipv6NetToMediaType = 2;
19711 	}
19712 
19713 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19714 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19715 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19716 		    (uint_t)sizeof (ntme)));
19717 	}
19718 	return (0);
19719 }
19720 
19721 /*
19722  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19723  */
19724 /* ARGSUSED */
19725 int
19726 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19727 {
19728 	switch (level) {
19729 	case MIB2_IP:
19730 	case MIB2_ICMP:
19731 		switch (name) {
19732 		default:
19733 			break;
19734 		}
19735 		return (1);
19736 	default:
19737 		return (1);
19738 	}
19739 }
19740 
19741 /*
19742  * When there exists both a 64- and 32-bit counter of a particular type
19743  * (i.e., InReceives), only the 64-bit counters are added.
19744  */
19745 void
19746 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19747 {
19748 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19749 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19750 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19751 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19752 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19753 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19754 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19755 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19756 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19757 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19758 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19759 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19760 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19761 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19762 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19763 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19764 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19765 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19766 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19767 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19768 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19769 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19770 	    o2->ipIfStatsInWrongIPVersion);
19771 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19772 	    o2->ipIfStatsInWrongIPVersion);
19773 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19774 	    o2->ipIfStatsOutSwitchIPVersion);
19775 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19776 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19777 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19778 	    o2->ipIfStatsHCInForwDatagrams);
19779 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19780 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19781 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19782 	    o2->ipIfStatsHCOutForwDatagrams);
19783 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19784 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19785 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19786 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19787 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19788 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19789 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19790 	    o2->ipIfStatsHCOutMcastOctets);
19791 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19792 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19793 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19794 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19795 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19796 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19797 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19798 }
19799 
19800 void
19801 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19802 {
19803 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19804 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19805 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19806 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19807 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19808 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19809 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19810 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19811 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19812 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19813 	    o2->ipv6IfIcmpInRouterSolicits);
19814 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19815 	    o2->ipv6IfIcmpInRouterAdvertisements);
19816 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19817 	    o2->ipv6IfIcmpInNeighborSolicits);
19818 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19819 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19820 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19821 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19822 	    o2->ipv6IfIcmpInGroupMembQueries);
19823 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19824 	    o2->ipv6IfIcmpInGroupMembResponses);
19825 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19826 	    o2->ipv6IfIcmpInGroupMembReductions);
19827 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19828 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19829 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19830 	    o2->ipv6IfIcmpOutDestUnreachs);
19831 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19832 	    o2->ipv6IfIcmpOutAdminProhibs);
19833 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19834 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19835 	    o2->ipv6IfIcmpOutParmProblems);
19836 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19837 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19838 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19839 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19840 	    o2->ipv6IfIcmpOutRouterSolicits);
19841 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19842 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19843 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19844 	    o2->ipv6IfIcmpOutNeighborSolicits);
19845 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19846 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19847 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19848 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19849 	    o2->ipv6IfIcmpOutGroupMembQueries);
19850 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19851 	    o2->ipv6IfIcmpOutGroupMembResponses);
19852 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19853 	    o2->ipv6IfIcmpOutGroupMembReductions);
19854 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19855 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19856 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19857 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19858 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19859 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19860 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19861 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19862 	    o2->ipv6IfIcmpInGroupMembTotal);
19863 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19864 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19865 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19866 	    o2->ipv6IfIcmpInGroupMembBadReports);
19867 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19868 	    o2->ipv6IfIcmpInGroupMembOurReports);
19869 }
19870 
19871 /*
19872  * Called before the options are updated to check if this packet will
19873  * be source routed from here.
19874  * This routine assumes that the options are well formed i.e. that they
19875  * have already been checked.
19876  */
19877 static boolean_t
19878 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19879 {
19880 	ipoptp_t	opts;
19881 	uchar_t		*opt;
19882 	uint8_t		optval;
19883 	uint8_t		optlen;
19884 	ipaddr_t	dst;
19885 	ire_t		*ire;
19886 
19887 	if (IS_SIMPLE_IPH(ipha)) {
19888 		ip2dbg(("not source routed\n"));
19889 		return (B_FALSE);
19890 	}
19891 	dst = ipha->ipha_dst;
19892 	for (optval = ipoptp_first(&opts, ipha);
19893 	    optval != IPOPT_EOL;
19894 	    optval = ipoptp_next(&opts)) {
19895 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19896 		opt = opts.ipoptp_cur;
19897 		optlen = opts.ipoptp_len;
19898 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19899 		    optval, optlen));
19900 		switch (optval) {
19901 			uint32_t off;
19902 		case IPOPT_SSRR:
19903 		case IPOPT_LSRR:
19904 			/*
19905 			 * If dst is one of our addresses and there are some
19906 			 * entries left in the source route return (true).
19907 			 */
19908 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19909 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19910 			if (ire == NULL) {
19911 				ip2dbg(("ip_source_routed: not next"
19912 				    " source route 0x%x\n",
19913 				    ntohl(dst)));
19914 				return (B_FALSE);
19915 			}
19916 			ire_refrele(ire);
19917 			off = opt[IPOPT_OFFSET];
19918 			off--;
19919 			if (optlen < IP_ADDR_LEN ||
19920 			    off > optlen - IP_ADDR_LEN) {
19921 				/* End of source route */
19922 				ip1dbg(("ip_source_routed: end of SR\n"));
19923 				return (B_FALSE);
19924 			}
19925 			return (B_TRUE);
19926 		}
19927 	}
19928 	ip2dbg(("not source routed\n"));
19929 	return (B_FALSE);
19930 }
19931 
19932 /*
19933  * Check if the packet contains any source route.
19934  */
19935 static boolean_t
19936 ip_source_route_included(ipha_t *ipha)
19937 {
19938 	ipoptp_t	opts;
19939 	uint8_t		optval;
19940 
19941 	if (IS_SIMPLE_IPH(ipha))
19942 		return (B_FALSE);
19943 	for (optval = ipoptp_first(&opts, ipha);
19944 	    optval != IPOPT_EOL;
19945 	    optval = ipoptp_next(&opts)) {
19946 		switch (optval) {
19947 		case IPOPT_SSRR:
19948 		case IPOPT_LSRR:
19949 			return (B_TRUE);
19950 		}
19951 	}
19952 	return (B_FALSE);
19953 }
19954 
19955 /*
19956  * Called when the IRE expiration timer fires.
19957  */
19958 void
19959 ip_trash_timer_expire(void *args)
19960 {
19961 	int			flush_flag = 0;
19962 	ire_expire_arg_t	iea;
19963 	ip_stack_t		*ipst = (ip_stack_t *)args;
19964 
19965 	iea.iea_ipst = ipst;	/* No netstack_hold */
19966 
19967 	/*
19968 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19969 	 * This lock makes sure that a new invocation of this function
19970 	 * that occurs due to an almost immediate timer firing will not
19971 	 * progress beyond this point until the current invocation is done
19972 	 */
19973 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19974 	ipst->ips_ip_ire_expire_id = 0;
19975 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19976 
19977 	/* Periodic timer */
19978 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19979 	    ipst->ips_ip_ire_arp_interval) {
19980 		/*
19981 		 * Remove all IRE_CACHE entries since they might
19982 		 * contain arp information.
19983 		 */
19984 		flush_flag |= FLUSH_ARP_TIME;
19985 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19986 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19987 	}
19988 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19989 	    ipst->ips_ip_ire_redir_interval) {
19990 		/* Remove all redirects */
19991 		flush_flag |= FLUSH_REDIRECT_TIME;
19992 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19993 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19994 	}
19995 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19996 	    ipst->ips_ip_ire_pathmtu_interval) {
19997 		/* Increase path mtu */
19998 		flush_flag |= FLUSH_MTU_TIME;
19999 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20000 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20001 	}
20002 
20003 	/*
20004 	 * Optimize for the case when there are no redirects in the
20005 	 * ftable, that is, no need to walk the ftable in that case.
20006 	 */
20007 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20008 		iea.iea_flush_flag = flush_flag;
20009 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20010 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20011 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20012 		    NULL, ALL_ZONES, ipst);
20013 	}
20014 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20015 	    ipst->ips_ip_redirect_cnt > 0) {
20016 		iea.iea_flush_flag = flush_flag;
20017 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20018 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20019 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20020 	}
20021 	if (flush_flag & FLUSH_MTU_TIME) {
20022 		/*
20023 		 * Walk all IPv6 IRE's and update them
20024 		 * Note that ARP and redirect timers are not
20025 		 * needed since NUD handles stale entries.
20026 		 */
20027 		flush_flag = FLUSH_MTU_TIME;
20028 		iea.iea_flush_flag = flush_flag;
20029 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20030 		    ALL_ZONES, ipst);
20031 	}
20032 
20033 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20034 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20035 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20036 
20037 	/*
20038 	 * Hold the lock to serialize timeout calls and prevent
20039 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20040 	 * for the timer to fire and a new invocation of this function
20041 	 * to start before the return value of timeout has been stored
20042 	 * in ip_ire_expire_id by the current invocation.
20043 	 */
20044 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20045 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20046 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20047 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20048 }
20049 
20050 /*
20051  * Called by the memory allocator subsystem directly, when the system
20052  * is running low on memory.
20053  */
20054 /* ARGSUSED */
20055 void
20056 ip_trash_ire_reclaim(void *args)
20057 {
20058 	netstack_handle_t nh;
20059 	netstack_t *ns;
20060 
20061 	netstack_next_init(&nh);
20062 	while ((ns = netstack_next(&nh)) != NULL) {
20063 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20064 		netstack_rele(ns);
20065 	}
20066 	netstack_next_fini(&nh);
20067 }
20068 
20069 static void
20070 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20071 {
20072 	ire_cache_count_t icc;
20073 	ire_cache_reclaim_t icr;
20074 	ncc_cache_count_t ncc;
20075 	nce_cache_reclaim_t ncr;
20076 	uint_t delete_cnt;
20077 	/*
20078 	 * Memory reclaim call back.
20079 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20080 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20081 	 * entries, determine what fraction to free for
20082 	 * each category of IRE_CACHE entries giving absolute priority
20083 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20084 	 * entry will be freed unless all offlink entries are freed).
20085 	 */
20086 	icc.icc_total = 0;
20087 	icc.icc_unused = 0;
20088 	icc.icc_offlink = 0;
20089 	icc.icc_pmtu = 0;
20090 	icc.icc_onlink = 0;
20091 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20092 
20093 	/*
20094 	 * Free NCEs for IPv6 like the onlink ires.
20095 	 */
20096 	ncc.ncc_total = 0;
20097 	ncc.ncc_host = 0;
20098 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20099 
20100 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20101 	    icc.icc_pmtu + icc.icc_onlink);
20102 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20103 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20104 	if (delete_cnt == 0)
20105 		return;
20106 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20107 	/* Always delete all unused offlink entries */
20108 	icr.icr_ipst = ipst;
20109 	icr.icr_unused = 1;
20110 	if (delete_cnt <= icc.icc_unused) {
20111 		/*
20112 		 * Only need to free unused entries.  In other words,
20113 		 * there are enough unused entries to free to meet our
20114 		 * target number of freed ire cache entries.
20115 		 */
20116 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20117 		ncr.ncr_host = 0;
20118 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20119 		/*
20120 		 * Only need to free unused entries, plus a fraction of offlink
20121 		 * entries.  It follows from the first if statement that
20122 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20123 		 */
20124 		delete_cnt -= icc.icc_unused;
20125 		/* Round up # deleted by truncating fraction */
20126 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20127 		icr.icr_pmtu = icr.icr_onlink = 0;
20128 		ncr.ncr_host = 0;
20129 	} else if (delete_cnt <=
20130 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20131 		/*
20132 		 * Free all unused and offlink entries, plus a fraction of
20133 		 * pmtu entries.  It follows from the previous if statement
20134 		 * that icc_pmtu is non-zero, and that
20135 		 * delete_cnt != icc_unused + icc_offlink.
20136 		 */
20137 		icr.icr_offlink = 1;
20138 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20139 		/* Round up # deleted by truncating fraction */
20140 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20141 		icr.icr_onlink = 0;
20142 		ncr.ncr_host = 0;
20143 	} else {
20144 		/*
20145 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20146 		 * of onlink entries.  If we're here, then we know that
20147 		 * icc_onlink is non-zero, and that
20148 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20149 		 */
20150 		icr.icr_offlink = icr.icr_pmtu = 1;
20151 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20152 		    icc.icc_pmtu;
20153 		/* Round up # deleted by truncating fraction */
20154 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20155 		/* Using the same delete fraction as for onlink IREs */
20156 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20157 	}
20158 #ifdef DEBUG
20159 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20160 	    "fractions %d/%d/%d/%d\n",
20161 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20162 	    icc.icc_unused, icc.icc_offlink,
20163 	    icc.icc_pmtu, icc.icc_onlink,
20164 	    icr.icr_unused, icr.icr_offlink,
20165 	    icr.icr_pmtu, icr.icr_onlink));
20166 #endif
20167 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20168 	if (ncr.ncr_host != 0)
20169 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20170 		    (uchar_t *)&ncr, ipst);
20171 #ifdef DEBUG
20172 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20173 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20174 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20175 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20176 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20177 	    icc.icc_pmtu, icc.icc_onlink));
20178 #endif
20179 }
20180 
20181 /*
20182  * ip_unbind is called when a copy of an unbind request is received from the
20183  * upper level protocol.  We remove this conn from any fanout hash list it is
20184  * on, and zero out the bind information.  No reply is expected up above.
20185  */
20186 mblk_t *
20187 ip_unbind(queue_t *q, mblk_t *mp)
20188 {
20189 	conn_t	*connp = Q_TO_CONN(q);
20190 
20191 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20192 
20193 	if (is_system_labeled() && connp->conn_anon_port) {
20194 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20195 		    connp->conn_mlp_type, connp->conn_ulp,
20196 		    ntohs(connp->conn_lport), B_FALSE);
20197 		connp->conn_anon_port = 0;
20198 	}
20199 	connp->conn_mlp_type = mlptSingle;
20200 
20201 	ipcl_hash_remove(connp);
20202 
20203 	ASSERT(mp->b_cont == NULL);
20204 	/*
20205 	 * Convert mp into a T_OK_ACK
20206 	 */
20207 	mp = mi_tpi_ok_ack_alloc(mp);
20208 
20209 	/*
20210 	 * should not happen in practice... T_OK_ACK is smaller than the
20211 	 * original message.
20212 	 */
20213 	if (mp == NULL)
20214 		return (NULL);
20215 
20216 	/*
20217 	 * Don't bzero the ports if its TCP since TCP still needs the
20218 	 * lport to remove it from its own bind hash. TCP will do the
20219 	 * cleanup.
20220 	 */
20221 	if (!IPCL_IS_TCP(connp))
20222 		bzero(&connp->u_port, sizeof (connp->u_port));
20223 
20224 	return (mp);
20225 }
20226 
20227 /*
20228  * Write side put procedure.  Outbound data, IOCTLs, responses from
20229  * resolvers, etc, come down through here.
20230  *
20231  * arg2 is always a queue_t *.
20232  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20233  * the zoneid.
20234  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20235  */
20236 void
20237 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20238 {
20239 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20240 }
20241 
20242 void
20243 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20244     ip_opt_info_t *infop)
20245 {
20246 	conn_t		*connp = NULL;
20247 	queue_t		*q = (queue_t *)arg2;
20248 	ipha_t		*ipha;
20249 #define	rptr	((uchar_t *)ipha)
20250 	ire_t		*ire = NULL;
20251 	ire_t		*sctp_ire = NULL;
20252 	uint32_t	v_hlen_tos_len;
20253 	ipaddr_t	dst;
20254 	mblk_t		*first_mp = NULL;
20255 	boolean_t	mctl_present;
20256 	ipsec_out_t	*io;
20257 	int		match_flags;
20258 	ill_t		*attach_ill = NULL;
20259 					/* Bind to IPIF_NOFAILOVER ill etc. */
20260 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20261 	ipif_t		*dst_ipif;
20262 	boolean_t	multirt_need_resolve = B_FALSE;
20263 	mblk_t		*copy_mp = NULL;
20264 	int		err;
20265 	zoneid_t	zoneid;
20266 	int	adjust;
20267 	uint16_t iplen;
20268 	boolean_t	need_decref = B_FALSE;
20269 	boolean_t	ignore_dontroute = B_FALSE;
20270 	boolean_t	ignore_nexthop = B_FALSE;
20271 	boolean_t	ip_nexthop = B_FALSE;
20272 	ipaddr_t	nexthop_addr;
20273 	ip_stack_t	*ipst;
20274 
20275 #ifdef	_BIG_ENDIAN
20276 #define	V_HLEN	(v_hlen_tos_len >> 24)
20277 #else
20278 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20279 #endif
20280 
20281 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20282 	    "ip_wput_start: q %p", q);
20283 
20284 	/*
20285 	 * ip_wput fast path
20286 	 */
20287 
20288 	/* is packet from ARP ? */
20289 	if (q->q_next != NULL) {
20290 		zoneid = (zoneid_t)(uintptr_t)arg;
20291 		goto qnext;
20292 	}
20293 
20294 	connp = (conn_t *)arg;
20295 	ASSERT(connp != NULL);
20296 	zoneid = connp->conn_zoneid;
20297 	ipst = connp->conn_netstack->netstack_ip;
20298 
20299 	/* is queue flow controlled? */
20300 	if ((q->q_first != NULL || connp->conn_draining) &&
20301 	    (caller == IP_WPUT)) {
20302 		ASSERT(!need_decref);
20303 		(void) putq(q, mp);
20304 		return;
20305 	}
20306 
20307 	/* Multidata transmit? */
20308 	if (DB_TYPE(mp) == M_MULTIDATA) {
20309 		/*
20310 		 * We should never get here, since all Multidata messages
20311 		 * originating from tcp should have been directed over to
20312 		 * tcp_multisend() in the first place.
20313 		 */
20314 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20315 		freemsg(mp);
20316 		return;
20317 	} else if (DB_TYPE(mp) != M_DATA)
20318 		goto notdata;
20319 
20320 	if (mp->b_flag & MSGHASREF) {
20321 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20322 		mp->b_flag &= ~MSGHASREF;
20323 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20324 		need_decref = B_TRUE;
20325 	}
20326 	ipha = (ipha_t *)mp->b_rptr;
20327 
20328 	/* is IP header non-aligned or mblk smaller than basic IP header */
20329 #ifndef SAFETY_BEFORE_SPEED
20330 	if (!OK_32PTR(rptr) ||
20331 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20332 		goto hdrtoosmall;
20333 #endif
20334 
20335 	ASSERT(OK_32PTR(ipha));
20336 
20337 	/*
20338 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20339 	 * wrong version, we'll catch it again in ip_output_v6.
20340 	 *
20341 	 * Note that this is *only* locally-generated output here, and never
20342 	 * forwarded data, and that we need to deal only with transports that
20343 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20344 	 * label.)
20345 	 */
20346 	if (is_system_labeled() &&
20347 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20348 	    !connp->conn_ulp_labeled) {
20349 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20350 		    connp->conn_mac_exempt, ipst);
20351 		ipha = (ipha_t *)mp->b_rptr;
20352 		if (err != 0) {
20353 			first_mp = mp;
20354 			if (err == EINVAL)
20355 				goto icmp_parameter_problem;
20356 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20357 			goto discard_pkt;
20358 		}
20359 		iplen = ntohs(ipha->ipha_length) + adjust;
20360 		ipha->ipha_length = htons(iplen);
20361 	}
20362 
20363 	ASSERT(infop != NULL);
20364 
20365 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20366 		/*
20367 		 * IP_PKTINFO ancillary option is present.
20368 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20369 		 * allows using address of any zone as the source address.
20370 		 */
20371 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20372 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20373 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20374 		if (ire == NULL)
20375 			goto drop_pkt;
20376 		ire_refrele(ire);
20377 		ire = NULL;
20378 	}
20379 
20380 	/*
20381 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20382 	 * ill index passed in IP_PKTINFO.
20383 	 */
20384 	if (infop->ip_opt_ill_index != 0 &&
20385 	    connp->conn_xmit_if_ill == NULL &&
20386 	    connp->conn_nofailover_ill == NULL) {
20387 
20388 		xmit_ill = ill_lookup_on_ifindex(
20389 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20390 		    ipst);
20391 
20392 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20393 			goto drop_pkt;
20394 		/*
20395 		 * check that there is an ipif belonging
20396 		 * to our zone. IPCL_ZONEID is not used because
20397 		 * IP_ALLZONES option is valid only when the ill is
20398 		 * accessible from all zones i.e has a valid ipif in
20399 		 * all zones.
20400 		 */
20401 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20402 			goto drop_pkt;
20403 		}
20404 	}
20405 
20406 	/*
20407 	 * If there is a policy, try to attach an ipsec_out in
20408 	 * the front. At the end, first_mp either points to a
20409 	 * M_DATA message or IPSEC_OUT message linked to a
20410 	 * M_DATA message. We have to do it now as we might
20411 	 * lose the "conn" if we go through ip_newroute.
20412 	 */
20413 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20414 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
20415 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20416 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20417 			if (need_decref)
20418 				CONN_DEC_REF(connp);
20419 			return;
20420 		} else {
20421 			ASSERT(mp->b_datap->db_type == M_CTL);
20422 			first_mp = mp;
20423 			mp = mp->b_cont;
20424 			mctl_present = B_TRUE;
20425 		}
20426 	} else {
20427 		first_mp = mp;
20428 		mctl_present = B_FALSE;
20429 	}
20430 
20431 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20432 
20433 	/* is wrong version or IP options present */
20434 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20435 		goto version_hdrlen_check;
20436 	dst = ipha->ipha_dst;
20437 
20438 	if (connp->conn_nofailover_ill != NULL) {
20439 		attach_ill = conn_get_held_ill(connp,
20440 		    &connp->conn_nofailover_ill, &err);
20441 		if (err == ILL_LOOKUP_FAILED) {
20442 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20443 			if (need_decref)
20444 				CONN_DEC_REF(connp);
20445 			freemsg(first_mp);
20446 			return;
20447 		}
20448 	}
20449 
20450 
20451 	/* is packet multicast? */
20452 	if (CLASSD(dst))
20453 		goto multicast;
20454 
20455 	/*
20456 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20457 	 * takes precedence over conn_dontroute and conn_nexthop_set
20458 	 */
20459 	if (xmit_ill != NULL) {
20460 		goto send_from_ill;
20461 	}
20462 
20463 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20464 	    (connp->conn_nexthop_set)) {
20465 		/*
20466 		 * If the destination is a broadcast or a loopback
20467 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20468 		 * through the standard path. But in the case of local
20469 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20470 		 * the standard path not IP_XMIT_IF.
20471 		 */
20472 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20473 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20474 		    (ire->ire_type != IRE_LOOPBACK))) {
20475 			if ((connp->conn_dontroute ||
20476 			    connp->conn_nexthop_set) && (ire != NULL) &&
20477 			    (ire->ire_type == IRE_LOCAL))
20478 				goto standard_path;
20479 
20480 			if (ire != NULL) {
20481 				ire_refrele(ire);
20482 				/* No more access to ire */
20483 				ire = NULL;
20484 			}
20485 			/*
20486 			 * bypass routing checks and go directly to
20487 			 * interface.
20488 			 */
20489 			if (connp->conn_dontroute) {
20490 				goto dontroute;
20491 			} else if (connp->conn_nexthop_set) {
20492 				ip_nexthop = B_TRUE;
20493 				nexthop_addr = connp->conn_nexthop_v4;
20494 				goto send_from_ill;
20495 			}
20496 
20497 			/*
20498 			 * If IP_XMIT_IF socket option is set,
20499 			 * then we allow unicast and multicast
20500 			 * packets to go through the ill. It is
20501 			 * quite possible that the destination
20502 			 * is not in the ire cache table and we
20503 			 * do not want to go to ip_newroute()
20504 			 * instead we call ip_newroute_ipif.
20505 			 */
20506 			xmit_ill = conn_get_held_ill(connp,
20507 			    &connp->conn_xmit_if_ill, &err);
20508 			if (err == ILL_LOOKUP_FAILED) {
20509 				BUMP_MIB(&ipst->ips_ip_mib,
20510 				    ipIfStatsOutDiscards);
20511 				if (attach_ill != NULL)
20512 					ill_refrele(attach_ill);
20513 				if (need_decref)
20514 					CONN_DEC_REF(connp);
20515 				freemsg(first_mp);
20516 				return;
20517 			}
20518 			goto send_from_ill;
20519 		}
20520 standard_path:
20521 		/* Must be a broadcast, a loopback or a local ire */
20522 		if (ire != NULL) {
20523 			ire_refrele(ire);
20524 			/* No more access to ire */
20525 			ire = NULL;
20526 		}
20527 	}
20528 
20529 	if (attach_ill != NULL)
20530 		goto send_from_ill;
20531 
20532 	/*
20533 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20534 	 * this for the tcp global queue and listen end point
20535 	 * as it does not really have a real destination to
20536 	 * talk to.  This is also true for SCTP.
20537 	 */
20538 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20539 	    !connp->conn_fully_bound) {
20540 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20541 		if (ire == NULL)
20542 			goto noirefound;
20543 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20544 		    "ip_wput_end: q %p (%S)", q, "end");
20545 
20546 		/*
20547 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20548 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20549 		 */
20550 		if (ire->ire_flags & RTF_MULTIRT) {
20551 
20552 			/*
20553 			 * Force the TTL of multirouted packets if required.
20554 			 * The TTL of such packets is bounded by the
20555 			 * ip_multirt_ttl ndd variable.
20556 			 */
20557 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20558 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20559 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20560 				    "(was %d), dst 0x%08x\n",
20561 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20562 				    ntohl(ire->ire_addr)));
20563 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20564 			}
20565 			/*
20566 			 * We look at this point if there are pending
20567 			 * unresolved routes. ire_multirt_resolvable()
20568 			 * checks in O(n) that all IRE_OFFSUBNET ire
20569 			 * entries for the packet's destination and
20570 			 * flagged RTF_MULTIRT are currently resolved.
20571 			 * If some remain unresolved, we make a copy
20572 			 * of the current message. It will be used
20573 			 * to initiate additional route resolutions.
20574 			 */
20575 			multirt_need_resolve =
20576 			    ire_multirt_need_resolve(ire->ire_addr,
20577 			    MBLK_GETLABEL(first_mp), ipst);
20578 			ip2dbg(("ip_wput[TCP]: ire %p, "
20579 			    "multirt_need_resolve %d, first_mp %p\n",
20580 			    (void *)ire, multirt_need_resolve,
20581 			    (void *)first_mp));
20582 			if (multirt_need_resolve) {
20583 				copy_mp = copymsg(first_mp);
20584 				if (copy_mp != NULL) {
20585 					MULTIRT_DEBUG_TAG(copy_mp);
20586 				}
20587 			}
20588 		}
20589 
20590 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20591 
20592 		/*
20593 		 * Try to resolve another multiroute if
20594 		 * ire_multirt_need_resolve() deemed it necessary.
20595 		 */
20596 		if (copy_mp != NULL) {
20597 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20598 		}
20599 		if (need_decref)
20600 			CONN_DEC_REF(connp);
20601 		return;
20602 	}
20603 
20604 	/*
20605 	 * Access to conn_ire_cache. (protected by conn_lock)
20606 	 *
20607 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20608 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20609 	 * send a packet or two with the IRE_CACHE that is going away.
20610 	 * Access to the ire requires an ire refhold on the ire prior to
20611 	 * its use since an interface unplumb thread may delete the cached
20612 	 * ire and release the refhold at any time.
20613 	 *
20614 	 * Caching an ire in the conn_ire_cache
20615 	 *
20616 	 * o Caching an ire pointer in the conn requires a strict check for
20617 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20618 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20619 	 * in the conn is done after making sure under the bucket lock that the
20620 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20621 	 * caching an ire after the unplumb thread has cleaned up the conn.
20622 	 * If the conn does not send a packet subsequently the unplumb thread
20623 	 * will be hanging waiting for the ire count to drop to zero.
20624 	 *
20625 	 * o We also need to atomically test for a null conn_ire_cache and
20626 	 * set the conn_ire_cache under the the protection of the conn_lock
20627 	 * to avoid races among concurrent threads trying to simultaneously
20628 	 * cache an ire in the conn_ire_cache.
20629 	 */
20630 	mutex_enter(&connp->conn_lock);
20631 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20632 
20633 	if (ire != NULL && ire->ire_addr == dst &&
20634 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20635 
20636 		IRE_REFHOLD(ire);
20637 		mutex_exit(&connp->conn_lock);
20638 
20639 	} else {
20640 		boolean_t cached = B_FALSE;
20641 		connp->conn_ire_cache = NULL;
20642 		mutex_exit(&connp->conn_lock);
20643 		/* Release the old ire */
20644 		if (ire != NULL && sctp_ire == NULL)
20645 			IRE_REFRELE_NOTR(ire);
20646 
20647 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20648 		if (ire == NULL)
20649 			goto noirefound;
20650 		IRE_REFHOLD_NOTR(ire);
20651 
20652 		mutex_enter(&connp->conn_lock);
20653 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20654 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20655 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20656 				connp->conn_ire_cache = ire;
20657 				cached = B_TRUE;
20658 			}
20659 			rw_exit(&ire->ire_bucket->irb_lock);
20660 		}
20661 		mutex_exit(&connp->conn_lock);
20662 
20663 		/*
20664 		 * We can continue to use the ire but since it was
20665 		 * not cached, we should drop the extra reference.
20666 		 */
20667 		if (!cached)
20668 			IRE_REFRELE_NOTR(ire);
20669 	}
20670 
20671 
20672 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20673 	    "ip_wput_end: q %p (%S)", q, "end");
20674 
20675 	/*
20676 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20677 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20678 	 */
20679 	if (ire->ire_flags & RTF_MULTIRT) {
20680 
20681 		/*
20682 		 * Force the TTL of multirouted packets if required.
20683 		 * The TTL of such packets is bounded by the
20684 		 * ip_multirt_ttl ndd variable.
20685 		 */
20686 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20687 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20688 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20689 			    "(was %d), dst 0x%08x\n",
20690 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20691 			    ntohl(ire->ire_addr)));
20692 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20693 		}
20694 
20695 		/*
20696 		 * At this point, we check to see if there are any pending
20697 		 * unresolved routes. ire_multirt_resolvable()
20698 		 * checks in O(n) that all IRE_OFFSUBNET ire
20699 		 * entries for the packet's destination and
20700 		 * flagged RTF_MULTIRT are currently resolved.
20701 		 * If some remain unresolved, we make a copy
20702 		 * of the current message. It will be used
20703 		 * to initiate additional route resolutions.
20704 		 */
20705 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20706 		    MBLK_GETLABEL(first_mp), ipst);
20707 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20708 		    "multirt_need_resolve %d, first_mp %p\n",
20709 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20710 		if (multirt_need_resolve) {
20711 			copy_mp = copymsg(first_mp);
20712 			if (copy_mp != NULL) {
20713 				MULTIRT_DEBUG_TAG(copy_mp);
20714 			}
20715 		}
20716 	}
20717 
20718 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20719 
20720 	/*
20721 	 * Try to resolve another multiroute if
20722 	 * ire_multirt_resolvable() deemed it necessary
20723 	 */
20724 	if (copy_mp != NULL) {
20725 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20726 	}
20727 	if (need_decref)
20728 		CONN_DEC_REF(connp);
20729 	return;
20730 
20731 qnext:
20732 	/*
20733 	 * Upper Level Protocols pass down complete IP datagrams
20734 	 * as M_DATA messages.	Everything else is a sideshow.
20735 	 *
20736 	 * 1) We could be re-entering ip_wput because of ip_neworute
20737 	 *    in which case we could have a IPSEC_OUT message. We
20738 	 *    need to pass through ip_wput like other datagrams and
20739 	 *    hence cannot branch to ip_wput_nondata.
20740 	 *
20741 	 * 2) ARP, AH, ESP, and other clients who are on the module
20742 	 *    instance of IP stream, give us something to deal with.
20743 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20744 	 *
20745 	 * 3) ICMP replies also could come here.
20746 	 */
20747 	ipst = ILLQ_TO_IPST(q);
20748 
20749 	if (DB_TYPE(mp) != M_DATA) {
20750 	    notdata:
20751 		if (DB_TYPE(mp) == M_CTL) {
20752 			/*
20753 			 * M_CTL messages are used by ARP, AH and ESP to
20754 			 * communicate with IP. We deal with IPSEC_IN and
20755 			 * IPSEC_OUT here. ip_wput_nondata handles other
20756 			 * cases.
20757 			 */
20758 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20759 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20760 				first_mp = mp->b_cont;
20761 				first_mp->b_flag &= ~MSGHASREF;
20762 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20763 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20764 				CONN_DEC_REF(connp);
20765 				connp = NULL;
20766 			}
20767 			if (ii->ipsec_info_type == IPSEC_IN) {
20768 				/*
20769 				 * Either this message goes back to
20770 				 * IPSEC for further processing or to
20771 				 * ULP after policy checks.
20772 				 */
20773 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20774 				return;
20775 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20776 				io = (ipsec_out_t *)ii;
20777 				if (io->ipsec_out_proc_begin) {
20778 					/*
20779 					 * IPSEC processing has already started.
20780 					 * Complete it.
20781 					 * IPQoS notes: We don't care what is
20782 					 * in ipsec_out_ill_index since this
20783 					 * won't be processed for IPQoS policies
20784 					 * in ipsec_out_process.
20785 					 */
20786 					ipsec_out_process(q, mp, NULL,
20787 					    io->ipsec_out_ill_index);
20788 					return;
20789 				} else {
20790 					connp = (q->q_next != NULL) ?
20791 					    NULL : Q_TO_CONN(q);
20792 					first_mp = mp;
20793 					mp = mp->b_cont;
20794 					mctl_present = B_TRUE;
20795 				}
20796 				zoneid = io->ipsec_out_zoneid;
20797 				ASSERT(zoneid != ALL_ZONES);
20798 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20799 				/*
20800 				 * It's an IPsec control message requesting
20801 				 * an SADB update to be sent to the IPsec
20802 				 * hardware acceleration capable ills.
20803 				 */
20804 				ipsec_ctl_t *ipsec_ctl =
20805 				    (ipsec_ctl_t *)mp->b_rptr;
20806 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20807 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20808 				mblk_t *cmp = mp->b_cont;
20809 
20810 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20811 				ASSERT(cmp != NULL);
20812 
20813 				freeb(mp);
20814 				ill_ipsec_capab_send_all(satype, cmp, sa,
20815 				    ipst->ips_netstack);
20816 				return;
20817 			} else {
20818 				/*
20819 				 * This must be ARP or special TSOL signaling.
20820 				 */
20821 				ip_wput_nondata(NULL, q, mp, NULL);
20822 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20823 				    "ip_wput_end: q %p (%S)", q, "nondata");
20824 				return;
20825 			}
20826 		} else {
20827 			/*
20828 			 * This must be non-(ARP/AH/ESP) messages.
20829 			 */
20830 			ASSERT(!need_decref);
20831 			ip_wput_nondata(NULL, q, mp, NULL);
20832 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20833 			    "ip_wput_end: q %p (%S)", q, "nondata");
20834 			return;
20835 		}
20836 	} else {
20837 		first_mp = mp;
20838 		mctl_present = B_FALSE;
20839 	}
20840 
20841 	ASSERT(first_mp != NULL);
20842 	/*
20843 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20844 	 * to make sure that this packet goes out on the same interface it
20845 	 * came in. We handle that here.
20846 	 */
20847 	if (mctl_present) {
20848 		uint_t ifindex;
20849 
20850 		io = (ipsec_out_t *)first_mp->b_rptr;
20851 		if (io->ipsec_out_attach_if ||
20852 		    io->ipsec_out_xmit_if ||
20853 		    io->ipsec_out_ip_nexthop) {
20854 			ill_t	*ill;
20855 
20856 			/*
20857 			 * We may have lost the conn context if we are
20858 			 * coming here from ip_newroute(). Copy the
20859 			 * nexthop information.
20860 			 */
20861 			if (io->ipsec_out_ip_nexthop) {
20862 				ip_nexthop = B_TRUE;
20863 				nexthop_addr = io->ipsec_out_nexthop_addr;
20864 
20865 				ipha = (ipha_t *)mp->b_rptr;
20866 				dst = ipha->ipha_dst;
20867 				goto send_from_ill;
20868 			} else {
20869 				ASSERT(io->ipsec_out_ill_index != 0);
20870 				ifindex = io->ipsec_out_ill_index;
20871 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20872 				    NULL, NULL, NULL, NULL, ipst);
20873 				/*
20874 				 * ipsec_out_xmit_if bit is used to tell
20875 				 * ip_wput to use the ill to send outgoing data
20876 				 * as we have no conn when data comes from ICMP
20877 				 * error msg routines. Currently this feature is
20878 				 * only used by ip_mrtun_forward routine.
20879 				 */
20880 				if (io->ipsec_out_xmit_if) {
20881 					xmit_ill = ill;
20882 					if (xmit_ill == NULL) {
20883 						ip1dbg(("ip_output:bad ifindex "
20884 						    "for xmit_ill %d\n",
20885 						    ifindex));
20886 						freemsg(first_mp);
20887 						BUMP_MIB(&ipst->ips_ip_mib,
20888 						    ipIfStatsOutDiscards);
20889 						ASSERT(!need_decref);
20890 						return;
20891 					}
20892 					/* Free up the ipsec_out_t mblk */
20893 					ASSERT(first_mp->b_cont == mp);
20894 					first_mp->b_cont = NULL;
20895 					freeb(first_mp);
20896 					/* Just send the IP header+ICMP+data */
20897 					first_mp = mp;
20898 					ipha = (ipha_t *)mp->b_rptr;
20899 					dst = ipha->ipha_dst;
20900 					goto send_from_ill;
20901 				} else {
20902 					attach_ill = ill;
20903 				}
20904 
20905 				if (attach_ill == NULL) {
20906 					ASSERT(xmit_ill == NULL);
20907 					ip1dbg(("ip_output: bad ifindex for "
20908 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20909 					    ifindex));
20910 					freemsg(first_mp);
20911 					BUMP_MIB(&ipst->ips_ip_mib,
20912 					    ipIfStatsOutDiscards);
20913 					ASSERT(!need_decref);
20914 					return;
20915 				}
20916 			}
20917 		}
20918 	}
20919 
20920 	ASSERT(xmit_ill == NULL);
20921 
20922 	/* We have a complete IP datagram heading outbound. */
20923 	ipha = (ipha_t *)mp->b_rptr;
20924 
20925 #ifndef SPEED_BEFORE_SAFETY
20926 	/*
20927 	 * Make sure we have a full-word aligned message and that at least
20928 	 * a simple IP header is accessible in the first message.  If not,
20929 	 * try a pullup.
20930 	 */
20931 	if (!OK_32PTR(rptr) ||
20932 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20933 	    hdrtoosmall:
20934 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20935 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20936 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20937 			if (first_mp == NULL)
20938 				first_mp = mp;
20939 			goto discard_pkt;
20940 		}
20941 
20942 		/* This function assumes that mp points to an IPv4 packet. */
20943 		if (is_system_labeled() && q->q_next == NULL &&
20944 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20945 		    !connp->conn_ulp_labeled) {
20946 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20947 			    &adjust, connp->conn_mac_exempt, ipst);
20948 			ipha = (ipha_t *)mp->b_rptr;
20949 			if (first_mp != NULL)
20950 				first_mp->b_cont = mp;
20951 			if (err != 0) {
20952 				if (first_mp == NULL)
20953 					first_mp = mp;
20954 				if (err == EINVAL)
20955 					goto icmp_parameter_problem;
20956 				ip2dbg(("ip_wput: label check failed (%d)\n",
20957 				    err));
20958 				goto discard_pkt;
20959 			}
20960 			iplen = ntohs(ipha->ipha_length) + adjust;
20961 			ipha->ipha_length = htons(iplen);
20962 		}
20963 
20964 		ipha = (ipha_t *)mp->b_rptr;
20965 		if (first_mp == NULL) {
20966 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20967 			/*
20968 			 * If we got here because of "goto hdrtoosmall"
20969 			 * We need to attach a IPSEC_OUT.
20970 			 */
20971 			if (connp->conn_out_enforce_policy) {
20972 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20973 				    NULL, ipha->ipha_protocol,
20974 				    ipst->ips_netstack)) == NULL)) {
20975 					BUMP_MIB(&ipst->ips_ip_mib,
20976 					    ipIfStatsOutDiscards);
20977 					if (need_decref)
20978 						CONN_DEC_REF(connp);
20979 					return;
20980 				} else {
20981 					ASSERT(mp->b_datap->db_type == M_CTL);
20982 					first_mp = mp;
20983 					mp = mp->b_cont;
20984 					mctl_present = B_TRUE;
20985 				}
20986 			} else {
20987 				first_mp = mp;
20988 				mctl_present = B_FALSE;
20989 			}
20990 		}
20991 	}
20992 #endif
20993 
20994 	/* Most of the code below is written for speed, not readability */
20995 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20996 
20997 	/*
20998 	 * If ip_newroute() fails, we're going to need a full
20999 	 * header for the icmp wraparound.
21000 	 */
21001 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21002 		uint_t	v_hlen;
21003 	    version_hdrlen_check:
21004 		ASSERT(first_mp != NULL);
21005 		v_hlen = V_HLEN;
21006 		/*
21007 		 * siphon off IPv6 packets coming down from transport
21008 		 * layer modules here.
21009 		 * Note: high-order bit carries NUD reachability confirmation
21010 		 */
21011 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21012 			/*
21013 			 * XXX implement a IPv4 and IPv6 packet counter per
21014 			 * conn and switch when ratio exceeds e.g. 10:1
21015 			 */
21016 #ifdef notyet
21017 			if (q->q_next == NULL) /* Avoid ill queue */
21018 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
21019 #endif
21020 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21021 			ASSERT(xmit_ill == NULL);
21022 			if (attach_ill != NULL)
21023 				ill_refrele(attach_ill);
21024 			if (need_decref)
21025 				mp->b_flag |= MSGHASREF;
21026 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21027 			return;
21028 		}
21029 
21030 		if ((v_hlen >> 4) != IP_VERSION) {
21031 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21032 			    "ip_wput_end: q %p (%S)", q, "badvers");
21033 			goto discard_pkt;
21034 		}
21035 		/*
21036 		 * Is the header length at least 20 bytes?
21037 		 *
21038 		 * Are there enough bytes accessible in the header?  If
21039 		 * not, try a pullup.
21040 		 */
21041 		v_hlen &= 0xF;
21042 		v_hlen <<= 2;
21043 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21044 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21045 			    "ip_wput_end: q %p (%S)", q, "badlen");
21046 			goto discard_pkt;
21047 		}
21048 		if (v_hlen > (mp->b_wptr - rptr)) {
21049 			if (!pullupmsg(mp, v_hlen)) {
21050 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21051 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21052 				goto discard_pkt;
21053 			}
21054 			ipha = (ipha_t *)mp->b_rptr;
21055 		}
21056 		/*
21057 		 * Move first entry from any source route into ipha_dst and
21058 		 * verify the options
21059 		 */
21060 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21061 			zoneid, ipst)) {
21062 			ASSERT(xmit_ill == NULL);
21063 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21064 			if (attach_ill != NULL)
21065 				ill_refrele(attach_ill);
21066 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21067 			    "ip_wput_end: q %p (%S)", q, "badopts");
21068 			if (need_decref)
21069 				CONN_DEC_REF(connp);
21070 			return;
21071 		}
21072 	}
21073 	dst = ipha->ipha_dst;
21074 
21075 	/*
21076 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21077 	 * we have to run the packet through ip_newroute which will take
21078 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21079 	 * a resolver, or assigning a default gateway, etc.
21080 	 */
21081 	if (CLASSD(dst)) {
21082 		ipif_t	*ipif;
21083 		uint32_t setsrc = 0;
21084 
21085 	    multicast:
21086 		ASSERT(first_mp != NULL);
21087 		ip2dbg(("ip_wput: CLASSD\n"));
21088 		if (connp == NULL) {
21089 			/*
21090 			 * Use the first good ipif on the ill.
21091 			 * XXX Should this ever happen? (Appears
21092 			 * to show up with just ppp and no ethernet due
21093 			 * to in.rdisc.)
21094 			 * However, ire_send should be able to
21095 			 * call ip_wput_ire directly.
21096 			 *
21097 			 * XXX Also, this can happen for ICMP and other packets
21098 			 * with multicast source addresses.  Perhaps we should
21099 			 * fix things so that we drop the packet in question,
21100 			 * but for now, just run with it.
21101 			 */
21102 			ill_t *ill = (ill_t *)q->q_ptr;
21103 
21104 			/*
21105 			 * Don't honor attach_if for this case. If ill
21106 			 * is part of the group, ipif could belong to
21107 			 * any ill and we cannot maintain attach_ill
21108 			 * and ipif_ill same anymore and the assert
21109 			 * below would fail.
21110 			 */
21111 			if (mctl_present && io->ipsec_out_attach_if) {
21112 				io->ipsec_out_ill_index = 0;
21113 				io->ipsec_out_attach_if = B_FALSE;
21114 				ASSERT(attach_ill != NULL);
21115 				ill_refrele(attach_ill);
21116 				attach_ill = NULL;
21117 			}
21118 
21119 			ASSERT(attach_ill == NULL);
21120 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21121 			if (ipif == NULL) {
21122 				if (need_decref)
21123 					CONN_DEC_REF(connp);
21124 				freemsg(first_mp);
21125 				return;
21126 			}
21127 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21128 			    ntohl(dst), ill->ill_name));
21129 		} else {
21130 			/*
21131 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21132 			 * and IP_MULTICAST_IF.
21133 			 * Block comment above this function explains the
21134 			 * locking mechanism used here
21135 			 */
21136 			if (xmit_ill == NULL) {
21137 				xmit_ill = conn_get_held_ill(connp,
21138 				    &connp->conn_xmit_if_ill, &err);
21139 				if (err == ILL_LOOKUP_FAILED) {
21140 					ip1dbg(("ip_wput: No ill for "
21141 					    "IP_XMIT_IF\n"));
21142 					BUMP_MIB(&ipst->ips_ip_mib,
21143 					    ipIfStatsOutNoRoutes);
21144 					goto drop_pkt;
21145 				}
21146 			}
21147 
21148 			if (xmit_ill == NULL) {
21149 				ipif = conn_get_held_ipif(connp,
21150 				    &connp->conn_multicast_ipif, &err);
21151 				if (err == IPIF_LOOKUP_FAILED) {
21152 					ip1dbg(("ip_wput: No ipif for "
21153 					    "multicast\n"));
21154 					BUMP_MIB(&ipst->ips_ip_mib,
21155 					    ipIfStatsOutNoRoutes);
21156 					goto drop_pkt;
21157 				}
21158 			}
21159 			if (xmit_ill != NULL) {
21160 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21161 				if (ipif == NULL) {
21162 					ip1dbg(("ip_wput: No ipif for "
21163 					    "IP_XMIT_IF\n"));
21164 					BUMP_MIB(&ipst->ips_ip_mib,
21165 					    ipIfStatsOutNoRoutes);
21166 					goto drop_pkt;
21167 				}
21168 			} else if (ipif == NULL || ipif->ipif_isv6) {
21169 				/*
21170 				 * We must do this ipif determination here
21171 				 * else we could pass through ip_newroute
21172 				 * and come back here without the conn context.
21173 				 *
21174 				 * Note: we do late binding i.e. we bind to
21175 				 * the interface when the first packet is sent.
21176 				 * For performance reasons we do not rebind on
21177 				 * each packet but keep the binding until the
21178 				 * next IP_MULTICAST_IF option.
21179 				 *
21180 				 * conn_multicast_{ipif,ill} are shared between
21181 				 * IPv4 and IPv6 and AF_INET6 sockets can
21182 				 * send both IPv4 and IPv6 packets. Hence
21183 				 * we have to check that "isv6" matches above.
21184 				 */
21185 				if (ipif != NULL)
21186 					ipif_refrele(ipif);
21187 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21188 				if (ipif == NULL) {
21189 					ip1dbg(("ip_wput: No ipif for "
21190 					    "multicast\n"));
21191 					BUMP_MIB(&ipst->ips_ip_mib,
21192 					    ipIfStatsOutNoRoutes);
21193 					goto drop_pkt;
21194 				}
21195 				err = conn_set_held_ipif(connp,
21196 				    &connp->conn_multicast_ipif, ipif);
21197 				if (err == IPIF_LOOKUP_FAILED) {
21198 					ipif_refrele(ipif);
21199 					ip1dbg(("ip_wput: No ipif for "
21200 					    "multicast\n"));
21201 					BUMP_MIB(&ipst->ips_ip_mib,
21202 					    ipIfStatsOutNoRoutes);
21203 					goto drop_pkt;
21204 				}
21205 			}
21206 		}
21207 		ASSERT(!ipif->ipif_isv6);
21208 		/*
21209 		 * As we may lose the conn by the time we reach ip_wput_ire,
21210 		 * we copy conn_multicast_loop and conn_dontroute on to an
21211 		 * ipsec_out. In case if this datagram goes out secure,
21212 		 * we need the ill_index also. Copy that also into the
21213 		 * ipsec_out.
21214 		 */
21215 		if (mctl_present) {
21216 			io = (ipsec_out_t *)first_mp->b_rptr;
21217 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21218 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21219 		} else {
21220 			ASSERT(mp == first_mp);
21221 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21222 			    BPRI_HI)) == NULL) {
21223 				ipif_refrele(ipif);
21224 				first_mp = mp;
21225 				goto discard_pkt;
21226 			}
21227 			first_mp->b_datap->db_type = M_CTL;
21228 			first_mp->b_wptr += sizeof (ipsec_info_t);
21229 			/* ipsec_out_secure is B_FALSE now */
21230 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21231 			io = (ipsec_out_t *)first_mp->b_rptr;
21232 			io->ipsec_out_type = IPSEC_OUT;
21233 			io->ipsec_out_len = sizeof (ipsec_out_t);
21234 			io->ipsec_out_use_global_policy = B_TRUE;
21235 			io->ipsec_out_ns = ipst->ips_netstack;
21236 			first_mp->b_cont = mp;
21237 			mctl_present = B_TRUE;
21238 		}
21239 		if (attach_ill != NULL) {
21240 			ASSERT(attach_ill == ipif->ipif_ill);
21241 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21242 
21243 			/*
21244 			 * Check if we need an ire that will not be
21245 			 * looked up by anybody else i.e. HIDDEN.
21246 			 */
21247 			if (ill_is_probeonly(attach_ill)) {
21248 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21249 			}
21250 			io->ipsec_out_ill_index =
21251 			    attach_ill->ill_phyint->phyint_ifindex;
21252 			io->ipsec_out_attach_if = B_TRUE;
21253 		} else {
21254 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21255 			io->ipsec_out_ill_index =
21256 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21257 		}
21258 		if (connp != NULL) {
21259 			io->ipsec_out_multicast_loop =
21260 			    connp->conn_multicast_loop;
21261 			io->ipsec_out_dontroute = connp->conn_dontroute;
21262 			io->ipsec_out_zoneid = connp->conn_zoneid;
21263 		}
21264 		/*
21265 		 * If the application uses IP_MULTICAST_IF with
21266 		 * different logical addresses of the same ILL, we
21267 		 * need to make sure that the soruce address of
21268 		 * the packet matches the logical IP address used
21269 		 * in the option. We do it by initializing ipha_src
21270 		 * here. This should keep IPSEC also happy as
21271 		 * when we return from IPSEC processing, we don't
21272 		 * have to worry about getting the right address on
21273 		 * the packet. Thus it is sufficient to look for
21274 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21275 		 * MATCH_IRE_IPIF.
21276 		 *
21277 		 * NOTE : We need to do it for non-secure case also as
21278 		 * this might go out secure if there is a global policy
21279 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21280 		 * address, the source should be initialized already and
21281 		 * hence we won't be initializing here.
21282 		 *
21283 		 * As we do not have the ire yet, it is possible that
21284 		 * we set the source address here and then later discover
21285 		 * that the ire implies the source address to be assigned
21286 		 * through the RTF_SETSRC flag.
21287 		 * In that case, the setsrc variable will remind us
21288 		 * that overwritting the source address by the one
21289 		 * of the RTF_SETSRC-flagged ire is allowed.
21290 		 */
21291 		if (ipha->ipha_src == INADDR_ANY &&
21292 		    (connp == NULL || !connp->conn_unspec_src)) {
21293 			ipha->ipha_src = ipif->ipif_src_addr;
21294 			setsrc = RTF_SETSRC;
21295 		}
21296 		/*
21297 		 * Find an IRE which matches the destination and the outgoing
21298 		 * queue (i.e. the outgoing interface.)
21299 		 * For loopback use a unicast IP address for
21300 		 * the ire lookup.
21301 		 */
21302 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
21303 		    PHYI_LOOPBACK) {
21304 			dst = ipif->ipif_lcl_addr;
21305 		}
21306 		/*
21307 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21308 		 * We don't need to lookup ire in ctable as the packet
21309 		 * needs to be sent to the destination through the specified
21310 		 * ill irrespective of ires in the cache table.
21311 		 */
21312 		ire = NULL;
21313 		if (xmit_ill == NULL) {
21314 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21315 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21316 		}
21317 
21318 		/*
21319 		 * refrele attach_ill as its not needed anymore.
21320 		 */
21321 		if (attach_ill != NULL) {
21322 			ill_refrele(attach_ill);
21323 			attach_ill = NULL;
21324 		}
21325 
21326 		if (ire == NULL) {
21327 			/*
21328 			 * Multicast loopback and multicast forwarding is
21329 			 * done in ip_wput_ire.
21330 			 *
21331 			 * Mark this packet to make it be delivered to
21332 			 * ip_wput_ire after the new ire has been
21333 			 * created.
21334 			 *
21335 			 * The call to ip_newroute_ipif takes into account
21336 			 * the setsrc reminder. In any case, we take care
21337 			 * of the RTF_MULTIRT flag.
21338 			 */
21339 			mp->b_prev = mp->b_next = NULL;
21340 			if (xmit_ill == NULL ||
21341 			    xmit_ill->ill_ipif_up_count > 0) {
21342 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21343 				    setsrc | RTF_MULTIRT, zoneid, infop);
21344 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21345 				    "ip_wput_end: q %p (%S)", q, "noire");
21346 			} else {
21347 				freemsg(first_mp);
21348 			}
21349 			ipif_refrele(ipif);
21350 			if (xmit_ill != NULL)
21351 				ill_refrele(xmit_ill);
21352 			if (need_decref)
21353 				CONN_DEC_REF(connp);
21354 			return;
21355 		}
21356 
21357 		ipif_refrele(ipif);
21358 		ipif = NULL;
21359 		ASSERT(xmit_ill == NULL);
21360 
21361 		/*
21362 		 * Honor the RTF_SETSRC flag for multicast packets,
21363 		 * if allowed by the setsrc reminder.
21364 		 */
21365 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21366 			ipha->ipha_src = ire->ire_src_addr;
21367 		}
21368 
21369 		/*
21370 		 * Unconditionally force the TTL to 1 for
21371 		 * multirouted multicast packets:
21372 		 * multirouted multicast should not cross
21373 		 * multicast routers.
21374 		 */
21375 		if (ire->ire_flags & RTF_MULTIRT) {
21376 			if (ipha->ipha_ttl > 1) {
21377 				ip2dbg(("ip_wput: forcing multicast "
21378 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21379 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21380 				ipha->ipha_ttl = 1;
21381 			}
21382 		}
21383 	} else {
21384 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21385 		if ((ire != NULL) && (ire->ire_type &
21386 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21387 			ignore_dontroute = B_TRUE;
21388 			ignore_nexthop = B_TRUE;
21389 		}
21390 		if (ire != NULL) {
21391 			ire_refrele(ire);
21392 			ire = NULL;
21393 		}
21394 		/*
21395 		 * Guard against coming in from arp in which case conn is NULL.
21396 		 * Also guard against non M_DATA with dontroute set but
21397 		 * destined to local, loopback or broadcast addresses.
21398 		 */
21399 		if (connp != NULL && connp->conn_dontroute &&
21400 		    !ignore_dontroute) {
21401 dontroute:
21402 			/*
21403 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21404 			 * routing protocols from seeing false direct
21405 			 * connectivity.
21406 			 */
21407 			ipha->ipha_ttl = 1;
21408 			/*
21409 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21410 			 * along with SO_DONTROUTE, higher precedence is
21411 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21412 			 */
21413 			if (connp->conn_xmit_if_ill == NULL) {
21414 				/* If suitable ipif not found, drop packet */
21415 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21416 				    ipst);
21417 				if (dst_ipif == NULL) {
21418 					ip1dbg(("ip_wput: no route for "
21419 					    "dst using SO_DONTROUTE\n"));
21420 					BUMP_MIB(&ipst->ips_ip_mib,
21421 					    ipIfStatsOutNoRoutes);
21422 					mp->b_prev = mp->b_next = NULL;
21423 					if (first_mp == NULL)
21424 						first_mp = mp;
21425 					goto drop_pkt;
21426 				} else {
21427 					/*
21428 					 * If suitable ipif has been found, set
21429 					 * xmit_ill to the corresponding
21430 					 * ipif_ill because we'll be following
21431 					 * the IP_XMIT_IF logic.
21432 					 */
21433 					ASSERT(xmit_ill == NULL);
21434 					xmit_ill = dst_ipif->ipif_ill;
21435 					mutex_enter(&xmit_ill->ill_lock);
21436 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21437 						mutex_exit(&xmit_ill->ill_lock);
21438 						xmit_ill = NULL;
21439 						ipif_refrele(dst_ipif);
21440 						ip1dbg(("ip_wput: no route for"
21441 						    " dst using"
21442 						    " SO_DONTROUTE\n"));
21443 						BUMP_MIB(&ipst->ips_ip_mib,
21444 						    ipIfStatsOutNoRoutes);
21445 						mp->b_prev = mp->b_next = NULL;
21446 						if (first_mp == NULL)
21447 							first_mp = mp;
21448 						goto drop_pkt;
21449 					}
21450 					ill_refhold_locked(xmit_ill);
21451 					mutex_exit(&xmit_ill->ill_lock);
21452 					ipif_refrele(dst_ipif);
21453 				}
21454 			}
21455 
21456 		}
21457 		/*
21458 		 * If we are bound to IPIF_NOFAILOVER address, look for
21459 		 * an IRE_CACHE matching the ill.
21460 		 */
21461 send_from_ill:
21462 		if (attach_ill != NULL) {
21463 			ipif_t	*attach_ipif;
21464 
21465 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21466 
21467 			/*
21468 			 * Check if we need an ire that will not be
21469 			 * looked up by anybody else i.e. HIDDEN.
21470 			 */
21471 			if (ill_is_probeonly(attach_ill)) {
21472 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21473 			}
21474 
21475 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21476 			if (attach_ipif == NULL) {
21477 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21478 				goto discard_pkt;
21479 			}
21480 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21481 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21482 			ipif_refrele(attach_ipif);
21483 		} else if (xmit_ill != NULL || (connp != NULL &&
21484 			    connp->conn_xmit_if_ill != NULL)) {
21485 			/*
21486 			 * Mark this packet as originated locally
21487 			 */
21488 			mp->b_prev = mp->b_next = NULL;
21489 			/*
21490 			 * xmit_ill could be NULL if SO_DONTROUTE
21491 			 * is also set.
21492 			 */
21493 			if (xmit_ill == NULL) {
21494 				xmit_ill = conn_get_held_ill(connp,
21495 				    &connp->conn_xmit_if_ill, &err);
21496 				if (err == ILL_LOOKUP_FAILED) {
21497 					BUMP_MIB(&ipst->ips_ip_mib,
21498 					    ipIfStatsOutDiscards);
21499 					if (need_decref)
21500 						CONN_DEC_REF(connp);
21501 					freemsg(first_mp);
21502 					return;
21503 				}
21504 				if (xmit_ill == NULL) {
21505 					if (connp->conn_dontroute)
21506 						goto dontroute;
21507 					goto send_from_ill;
21508 				}
21509 			}
21510 			/*
21511 			 * Could be SO_DONTROUTE case also.
21512 			 * check at least one interface is UP as
21513 			 * specified by this ILL
21514 			 */
21515 			if (xmit_ill->ill_ipif_up_count > 0) {
21516 				ipif_t *ipif;
21517 
21518 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21519 				if (ipif == NULL) {
21520 					ip1dbg(("ip_output: "
21521 					    "xmit_ill NULL ipif\n"));
21522 					goto drop_pkt;
21523 				}
21524 				/*
21525 				 * Look for a ire that is part of the group,
21526 				 * if found use it else call ip_newroute_ipif.
21527 				 * IPCL_ZONEID is not used for matching because
21528 				 * IP_ALLZONES option is valid only when the
21529 				 * ill is accessible from all zones i.e has a
21530 				 * valid ipif in all zones.
21531 				 */
21532 				match_flags = MATCH_IRE_ILL_GROUP |
21533 				    MATCH_IRE_SECATTR;
21534 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21535 				    MBLK_GETLABEL(mp), match_flags, ipst);
21536 				/*
21537 				 * If an ire exists use it or else create
21538 				 * an ire but don't add it to the cache.
21539 				 * Adding an ire may cause issues with
21540 				 * asymmetric routing.
21541 				 * In case of multiroute always act as if
21542 				 * ire does not exist.
21543 				 */
21544 				if (ire == NULL ||
21545 				    ire->ire_flags & RTF_MULTIRT) {
21546 					if (ire != NULL)
21547 						ire_refrele(ire);
21548 					ip_newroute_ipif(q, first_mp, ipif,
21549 					    dst, connp, 0, zoneid, infop);
21550 					ipif_refrele(ipif);
21551 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21552 					ill_refrele(xmit_ill);
21553 					if (need_decref)
21554 						CONN_DEC_REF(connp);
21555 					return;
21556 				}
21557 				ipif_refrele(ipif);
21558 			} else {
21559 				goto drop_pkt;
21560 			}
21561 		} else if (ip_nexthop || (connp != NULL &&
21562 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21563 			if (!ip_nexthop) {
21564 				ip_nexthop = B_TRUE;
21565 				nexthop_addr = connp->conn_nexthop_v4;
21566 			}
21567 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21568 			    MATCH_IRE_GW;
21569 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21570 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21571 		} else {
21572 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21573 			    ipst);
21574 		}
21575 		if (!ire) {
21576 			/*
21577 			 * Make sure we don't load spread if this
21578 			 * is IPIF_NOFAILOVER case.
21579 			 */
21580 			if ((attach_ill != NULL) ||
21581 			    (ip_nexthop && !ignore_nexthop)) {
21582 				if (mctl_present) {
21583 					io = (ipsec_out_t *)first_mp->b_rptr;
21584 					ASSERT(first_mp->b_datap->db_type ==
21585 					    M_CTL);
21586 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21587 				} else {
21588 					ASSERT(mp == first_mp);
21589 					first_mp = allocb(
21590 					    sizeof (ipsec_info_t), BPRI_HI);
21591 					if (first_mp == NULL) {
21592 						first_mp = mp;
21593 						goto discard_pkt;
21594 					}
21595 					first_mp->b_datap->db_type = M_CTL;
21596 					first_mp->b_wptr +=
21597 					    sizeof (ipsec_info_t);
21598 					/* ipsec_out_secure is B_FALSE now */
21599 					bzero(first_mp->b_rptr,
21600 					    sizeof (ipsec_info_t));
21601 					io = (ipsec_out_t *)first_mp->b_rptr;
21602 					io->ipsec_out_type = IPSEC_OUT;
21603 					io->ipsec_out_len =
21604 					    sizeof (ipsec_out_t);
21605 					io->ipsec_out_use_global_policy =
21606 					    B_TRUE;
21607 					io->ipsec_out_ns = ipst->ips_netstack;
21608 					first_mp->b_cont = mp;
21609 					mctl_present = B_TRUE;
21610 				}
21611 				if (attach_ill != NULL) {
21612 					io->ipsec_out_ill_index = attach_ill->
21613 					    ill_phyint->phyint_ifindex;
21614 					io->ipsec_out_attach_if = B_TRUE;
21615 				} else {
21616 					io->ipsec_out_ip_nexthop = ip_nexthop;
21617 					io->ipsec_out_nexthop_addr =
21618 					    nexthop_addr;
21619 				}
21620 			}
21621 noirefound:
21622 			/*
21623 			 * Mark this packet as having originated on
21624 			 * this machine.  This will be noted in
21625 			 * ire_add_then_send, which needs to know
21626 			 * whether to run it back through ip_wput or
21627 			 * ip_rput following successful resolution.
21628 			 */
21629 			mp->b_prev = NULL;
21630 			mp->b_next = NULL;
21631 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21632 			    ipst);
21633 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21634 			    "ip_wput_end: q %p (%S)", q, "newroute");
21635 			if (attach_ill != NULL)
21636 				ill_refrele(attach_ill);
21637 			if (xmit_ill != NULL)
21638 				ill_refrele(xmit_ill);
21639 			if (need_decref)
21640 				CONN_DEC_REF(connp);
21641 			return;
21642 		}
21643 	}
21644 
21645 	/* We now know where we are going with it. */
21646 
21647 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21648 	    "ip_wput_end: q %p (%S)", q, "end");
21649 
21650 	/*
21651 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21652 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21653 	 */
21654 	if (ire->ire_flags & RTF_MULTIRT) {
21655 		/*
21656 		 * Force the TTL of multirouted packets if required.
21657 		 * The TTL of such packets is bounded by the
21658 		 * ip_multirt_ttl ndd variable.
21659 		 */
21660 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21661 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21662 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21663 			    "(was %d), dst 0x%08x\n",
21664 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21665 			    ntohl(ire->ire_addr)));
21666 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21667 		}
21668 		/*
21669 		 * At this point, we check to see if there are any pending
21670 		 * unresolved routes. ire_multirt_resolvable()
21671 		 * checks in O(n) that all IRE_OFFSUBNET ire
21672 		 * entries for the packet's destination and
21673 		 * flagged RTF_MULTIRT are currently resolved.
21674 		 * If some remain unresolved, we make a copy
21675 		 * of the current message. It will be used
21676 		 * to initiate additional route resolutions.
21677 		 */
21678 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21679 		    MBLK_GETLABEL(first_mp), ipst);
21680 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21681 		    "multirt_need_resolve %d, first_mp %p\n",
21682 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21683 		if (multirt_need_resolve) {
21684 			copy_mp = copymsg(first_mp);
21685 			if (copy_mp != NULL) {
21686 				MULTIRT_DEBUG_TAG(copy_mp);
21687 			}
21688 		}
21689 	}
21690 
21691 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21692 	/*
21693 	 * Try to resolve another multiroute if
21694 	 * ire_multirt_resolvable() deemed it necessary.
21695 	 * At this point, we need to distinguish
21696 	 * multicasts from other packets. For multicasts,
21697 	 * we call ip_newroute_ipif() and request that both
21698 	 * multirouting and setsrc flags are checked.
21699 	 */
21700 	if (copy_mp != NULL) {
21701 		if (CLASSD(dst)) {
21702 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21703 			if (ipif) {
21704 				ASSERT(infop->ip_opt_ill_index == 0);
21705 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21706 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21707 				ipif_refrele(ipif);
21708 			} else {
21709 				MULTIRT_DEBUG_UNTAG(copy_mp);
21710 				freemsg(copy_mp);
21711 				copy_mp = NULL;
21712 			}
21713 		} else {
21714 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21715 		}
21716 	}
21717 	if (attach_ill != NULL)
21718 		ill_refrele(attach_ill);
21719 	if (xmit_ill != NULL)
21720 		ill_refrele(xmit_ill);
21721 	if (need_decref)
21722 		CONN_DEC_REF(connp);
21723 	return;
21724 
21725 icmp_parameter_problem:
21726 	/* could not have originated externally */
21727 	ASSERT(mp->b_prev == NULL);
21728 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21729 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21730 		/* it's the IP header length that's in trouble */
21731 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21732 		first_mp = NULL;
21733 	}
21734 
21735 discard_pkt:
21736 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21737 drop_pkt:
21738 	ip1dbg(("ip_wput: dropped packet\n"));
21739 	if (ire != NULL)
21740 		ire_refrele(ire);
21741 	if (need_decref)
21742 		CONN_DEC_REF(connp);
21743 	freemsg(first_mp);
21744 	if (attach_ill != NULL)
21745 		ill_refrele(attach_ill);
21746 	if (xmit_ill != NULL)
21747 		ill_refrele(xmit_ill);
21748 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21749 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21750 }
21751 
21752 /*
21753  * If this is a conn_t queue, then we pass in the conn. This includes the
21754  * zoneid.
21755  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21756  * in which case we use the global zoneid since those are all part of
21757  * the global zone.
21758  */
21759 void
21760 ip_wput(queue_t *q, mblk_t *mp)
21761 {
21762 	if (CONN_Q(q))
21763 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21764 	else
21765 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21766 }
21767 
21768 /*
21769  *
21770  * The following rules must be observed when accessing any ipif or ill
21771  * that has been cached in the conn. Typically conn_nofailover_ill,
21772  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21773  *
21774  * Access: The ipif or ill pointed to from the conn can be accessed under
21775  * the protection of the conn_lock or after it has been refheld under the
21776  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21777  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21778  * The reason for this is that a concurrent unplumb could actually be
21779  * cleaning up these cached pointers by walking the conns and might have
21780  * finished cleaning up the conn in question. The macros check that an
21781  * unplumb has not yet started on the ipif or ill.
21782  *
21783  * Caching: An ipif or ill pointer may be cached in the conn only after
21784  * making sure that an unplumb has not started. So the caching is done
21785  * while holding both the conn_lock and the ill_lock and after using the
21786  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21787  * flag before starting the cleanup of conns.
21788  *
21789  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21790  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21791  * or a reference to the ipif or a reference to an ire that references the
21792  * ipif. An ipif does not change its ill except for failover/failback. Since
21793  * failover/failback happens only after bringing down the ipif and making sure
21794  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21795  * the above holds.
21796  */
21797 ipif_t *
21798 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21799 {
21800 	ipif_t	*ipif;
21801 	ill_t	*ill;
21802 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21803 
21804 	*err = 0;
21805 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21806 	mutex_enter(&connp->conn_lock);
21807 	ipif = *ipifp;
21808 	if (ipif != NULL) {
21809 		ill = ipif->ipif_ill;
21810 		mutex_enter(&ill->ill_lock);
21811 		if (IPIF_CAN_LOOKUP(ipif)) {
21812 			ipif_refhold_locked(ipif);
21813 			mutex_exit(&ill->ill_lock);
21814 			mutex_exit(&connp->conn_lock);
21815 			rw_exit(&ipst->ips_ill_g_lock);
21816 			return (ipif);
21817 		} else {
21818 			*err = IPIF_LOOKUP_FAILED;
21819 		}
21820 		mutex_exit(&ill->ill_lock);
21821 	}
21822 	mutex_exit(&connp->conn_lock);
21823 	rw_exit(&ipst->ips_ill_g_lock);
21824 	return (NULL);
21825 }
21826 
21827 ill_t *
21828 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21829 {
21830 	ill_t	*ill;
21831 
21832 	*err = 0;
21833 	mutex_enter(&connp->conn_lock);
21834 	ill = *illp;
21835 	if (ill != NULL) {
21836 		mutex_enter(&ill->ill_lock);
21837 		if (ILL_CAN_LOOKUP(ill)) {
21838 			ill_refhold_locked(ill);
21839 			mutex_exit(&ill->ill_lock);
21840 			mutex_exit(&connp->conn_lock);
21841 			return (ill);
21842 		} else {
21843 			*err = ILL_LOOKUP_FAILED;
21844 		}
21845 		mutex_exit(&ill->ill_lock);
21846 	}
21847 	mutex_exit(&connp->conn_lock);
21848 	return (NULL);
21849 }
21850 
21851 static int
21852 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21853 {
21854 	ill_t	*ill;
21855 
21856 	ill = ipif->ipif_ill;
21857 	mutex_enter(&connp->conn_lock);
21858 	mutex_enter(&ill->ill_lock);
21859 	if (IPIF_CAN_LOOKUP(ipif)) {
21860 		*ipifp = ipif;
21861 		mutex_exit(&ill->ill_lock);
21862 		mutex_exit(&connp->conn_lock);
21863 		return (0);
21864 	}
21865 	mutex_exit(&ill->ill_lock);
21866 	mutex_exit(&connp->conn_lock);
21867 	return (IPIF_LOOKUP_FAILED);
21868 }
21869 
21870 /*
21871  * This is called if the outbound datagram needs fragmentation.
21872  *
21873  * NOTE : This function does not ire_refrele the ire argument passed in.
21874  */
21875 static void
21876 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21877     ip_stack_t *ipst)
21878 {
21879 	ipha_t		*ipha;
21880 	mblk_t		*mp;
21881 	uint32_t	v_hlen_tos_len;
21882 	uint32_t	max_frag;
21883 	uint32_t	frag_flag;
21884 	boolean_t	dont_use;
21885 
21886 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21887 		mp = ipsec_mp->b_cont;
21888 	} else {
21889 		mp = ipsec_mp;
21890 	}
21891 
21892 	ipha = (ipha_t *)mp->b_rptr;
21893 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21894 
21895 #ifdef	_BIG_ENDIAN
21896 #define	V_HLEN	(v_hlen_tos_len >> 24)
21897 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21898 #else
21899 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21900 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21901 #endif
21902 
21903 #ifndef SPEED_BEFORE_SAFETY
21904 	/*
21905 	 * Check that ipha_length is consistent with
21906 	 * the mblk length
21907 	 */
21908 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21909 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21910 		    LENGTH, msgdsize(mp)));
21911 		freemsg(ipsec_mp);
21912 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21913 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21914 		    "packet length mismatch");
21915 		return;
21916 	}
21917 #endif
21918 	/*
21919 	 * Don't use frag_flag if pre-built packet or source
21920 	 * routed or if multicast (since multicast packets do not solicit
21921 	 * ICMP "packet too big" messages). Get the values of
21922 	 * max_frag and frag_flag atomically by acquiring the
21923 	 * ire_lock.
21924 	 */
21925 	mutex_enter(&ire->ire_lock);
21926 	max_frag = ire->ire_max_frag;
21927 	frag_flag = ire->ire_frag_flag;
21928 	mutex_exit(&ire->ire_lock);
21929 
21930 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21931 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21932 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21933 
21934 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21935 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21936 }
21937 
21938 /*
21939  * Used for deciding the MSS size for the upper layer. Thus
21940  * we need to check the outbound policy values in the conn.
21941  */
21942 int
21943 conn_ipsec_length(conn_t *connp)
21944 {
21945 	ipsec_latch_t *ipl;
21946 
21947 	ipl = connp->conn_latch;
21948 	if (ipl == NULL)
21949 		return (0);
21950 
21951 	if (ipl->ipl_out_policy == NULL)
21952 		return (0);
21953 
21954 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21955 }
21956 
21957 /*
21958  * Returns an estimate of the IPSEC headers size. This is used if
21959  * we don't want to call into IPSEC to get the exact size.
21960  */
21961 int
21962 ipsec_out_extra_length(mblk_t *ipsec_mp)
21963 {
21964 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21965 	ipsec_action_t *a;
21966 
21967 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21968 	if (!io->ipsec_out_secure)
21969 		return (0);
21970 
21971 	a = io->ipsec_out_act;
21972 
21973 	if (a == NULL) {
21974 		ASSERT(io->ipsec_out_policy != NULL);
21975 		a = io->ipsec_out_policy->ipsp_act;
21976 	}
21977 	ASSERT(a != NULL);
21978 
21979 	return (a->ipa_ovhd);
21980 }
21981 
21982 /*
21983  * Returns an estimate of the IPSEC headers size. This is used if
21984  * we don't want to call into IPSEC to get the exact size.
21985  */
21986 int
21987 ipsec_in_extra_length(mblk_t *ipsec_mp)
21988 {
21989 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21990 	ipsec_action_t *a;
21991 
21992 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21993 
21994 	a = ii->ipsec_in_action;
21995 	return (a == NULL ? 0 : a->ipa_ovhd);
21996 }
21997 
21998 /*
21999  * If there are any source route options, return the true final
22000  * destination. Otherwise, return the destination.
22001  */
22002 ipaddr_t
22003 ip_get_dst(ipha_t *ipha)
22004 {
22005 	ipoptp_t	opts;
22006 	uchar_t		*opt;
22007 	uint8_t		optval;
22008 	uint8_t		optlen;
22009 	ipaddr_t	dst;
22010 	uint32_t off;
22011 
22012 	dst = ipha->ipha_dst;
22013 
22014 	if (IS_SIMPLE_IPH(ipha))
22015 		return (dst);
22016 
22017 	for (optval = ipoptp_first(&opts, ipha);
22018 	    optval != IPOPT_EOL;
22019 	    optval = ipoptp_next(&opts)) {
22020 		opt = opts.ipoptp_cur;
22021 		optlen = opts.ipoptp_len;
22022 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22023 		switch (optval) {
22024 		case IPOPT_SSRR:
22025 		case IPOPT_LSRR:
22026 			off = opt[IPOPT_OFFSET];
22027 			/*
22028 			 * If one of the conditions is true, it means
22029 			 * end of options and dst already has the right
22030 			 * value.
22031 			 */
22032 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22033 				off = optlen - IP_ADDR_LEN;
22034 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22035 			}
22036 			return (dst);
22037 		default:
22038 			break;
22039 		}
22040 	}
22041 
22042 	return (dst);
22043 }
22044 
22045 mblk_t *
22046 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22047     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22048 {
22049 	ipsec_out_t	*io;
22050 	mblk_t		*first_mp;
22051 	boolean_t policy_present;
22052 	ip_stack_t	*ipst;
22053 	ipsec_stack_t	*ipss;
22054 
22055 	ASSERT(ire != NULL);
22056 	ipst = ire->ire_ipst;
22057 	ipss = ipst->ips_netstack->netstack_ipsec;
22058 
22059 	first_mp = mp;
22060 	if (mp->b_datap->db_type == M_CTL) {
22061 		io = (ipsec_out_t *)first_mp->b_rptr;
22062 		/*
22063 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22064 		 *
22065 		 * 1) There is per-socket policy (including cached global
22066 		 *    policy) or a policy on the IP-in-IP tunnel.
22067 		 * 2) There is no per-socket policy, but it is
22068 		 *    a multicast packet that needs to go out
22069 		 *    on a specific interface. This is the case
22070 		 *    where (ip_wput and ip_wput_multicast) attaches
22071 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22072 		 *
22073 		 * In case (2) we check with global policy to
22074 		 * see if there is a match and set the ill_index
22075 		 * appropriately so that we can lookup the ire
22076 		 * properly in ip_wput_ipsec_out.
22077 		 */
22078 
22079 		/*
22080 		 * ipsec_out_use_global_policy is set to B_FALSE
22081 		 * in ipsec_in_to_out(). Refer to that function for
22082 		 * details.
22083 		 */
22084 		if ((io->ipsec_out_latch == NULL) &&
22085 		    (io->ipsec_out_use_global_policy)) {
22086 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22087 				    ire, connp, unspec_src, zoneid));
22088 		}
22089 		if (!io->ipsec_out_secure) {
22090 			/*
22091 			 * If this is not a secure packet, drop
22092 			 * the IPSEC_OUT mp and treat it as a clear
22093 			 * packet. This happens when we are sending
22094 			 * a ICMP reply back to a clear packet. See
22095 			 * ipsec_in_to_out() for details.
22096 			 */
22097 			mp = first_mp->b_cont;
22098 			freeb(first_mp);
22099 		}
22100 		return (mp);
22101 	}
22102 	/*
22103 	 * See whether we need to attach a global policy here. We
22104 	 * don't depend on the conn (as it could be null) for deciding
22105 	 * what policy this datagram should go through because it
22106 	 * should have happened in ip_wput if there was some
22107 	 * policy. This normally happens for connections which are not
22108 	 * fully bound preventing us from caching policies in
22109 	 * ip_bind. Packets coming from the TCP listener/global queue
22110 	 * - which are non-hard_bound - could also be affected by
22111 	 * applying policy here.
22112 	 *
22113 	 * If this packet is coming from tcp global queue or listener,
22114 	 * we will be applying policy here.  This may not be *right*
22115 	 * if these packets are coming from the detached connection as
22116 	 * it could have gone in clear before. This happens only if a
22117 	 * TCP connection started when there is no policy and somebody
22118 	 * added policy before it became detached. Thus packets of the
22119 	 * detached connection could go out secure and the other end
22120 	 * would drop it because it will be expecting in clear. The
22121 	 * converse is not true i.e if somebody starts a TCP
22122 	 * connection and deletes the policy, all the packets will
22123 	 * still go out with the policy that existed before deleting
22124 	 * because ip_unbind sends up policy information which is used
22125 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22126 	 * TCP to attach a dummy IPSEC_OUT and set
22127 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22128 	 * affect performance for normal cases, we are not doing it.
22129 	 * Thus, set policy before starting any TCP connections.
22130 	 *
22131 	 * NOTE - We might apply policy even for a hard bound connection
22132 	 * - for which we cached policy in ip_bind - if somebody added
22133 	 * global policy after we inherited the policy in ip_bind.
22134 	 * This means that the packets that were going out in clear
22135 	 * previously would start going secure and hence get dropped
22136 	 * on the other side. To fix this, TCP attaches a dummy
22137 	 * ipsec_out and make sure that we don't apply global policy.
22138 	 */
22139 	if (ipha != NULL)
22140 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22141 	else
22142 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22143 	if (!policy_present)
22144 		return (mp);
22145 
22146 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22147 		    zoneid));
22148 }
22149 
22150 ire_t *
22151 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22152 {
22153 	ipaddr_t addr;
22154 	ire_t *save_ire;
22155 	irb_t *irb;
22156 	ill_group_t *illgrp;
22157 	int	err;
22158 
22159 	save_ire = ire;
22160 	addr = ire->ire_addr;
22161 
22162 	ASSERT(ire->ire_type == IRE_BROADCAST);
22163 
22164 	illgrp = connp->conn_outgoing_ill->ill_group;
22165 	if (illgrp == NULL) {
22166 		*conn_outgoing_ill = conn_get_held_ill(connp,
22167 		    &connp->conn_outgoing_ill, &err);
22168 		if (err == ILL_LOOKUP_FAILED) {
22169 			ire_refrele(save_ire);
22170 			return (NULL);
22171 		}
22172 		return (save_ire);
22173 	}
22174 	/*
22175 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22176 	 * If it is part of the group, we need to send on the ire
22177 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22178 	 * to this group. This is okay as IP_BOUND_IF really means
22179 	 * any ill in the group. We depend on the fact that the
22180 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22181 	 * if such an ire exists. This is possible only if you have
22182 	 * at least one ill in the group that has not failed.
22183 	 *
22184 	 * First get to the ire that matches the address and group.
22185 	 *
22186 	 * We don't look for an ire with a matching zoneid because a given zone
22187 	 * won't always have broadcast ires on all ills in the group.
22188 	 */
22189 	irb = ire->ire_bucket;
22190 	rw_enter(&irb->irb_lock, RW_READER);
22191 	if (ire->ire_marks & IRE_MARK_NORECV) {
22192 		/*
22193 		 * If the current zone only has an ire broadcast for this
22194 		 * address marked NORECV, the ire we want is ahead in the
22195 		 * bucket, so we look it up deliberately ignoring the zoneid.
22196 		 */
22197 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22198 			if (ire->ire_addr != addr)
22199 				continue;
22200 			/* skip over deleted ires */
22201 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22202 				continue;
22203 		}
22204 	}
22205 	while (ire != NULL) {
22206 		/*
22207 		 * If a new interface is coming up, we could end up
22208 		 * seeing the loopback ire and the non-loopback ire
22209 		 * may not have been added yet. So check for ire_stq
22210 		 */
22211 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22212 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22213 			break;
22214 		}
22215 		ire = ire->ire_next;
22216 	}
22217 	if (ire != NULL && ire->ire_addr == addr &&
22218 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22219 		IRE_REFHOLD(ire);
22220 		rw_exit(&irb->irb_lock);
22221 		ire_refrele(save_ire);
22222 		*conn_outgoing_ill = ire_to_ill(ire);
22223 		/*
22224 		 * Refhold the ill to make the conn_outgoing_ill
22225 		 * independent of the ire. ip_wput_ire goes in a loop
22226 		 * and may refrele the ire. Since we have an ire at this
22227 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22228 		 */
22229 		ill_refhold(*conn_outgoing_ill);
22230 		return (ire);
22231 	}
22232 	rw_exit(&irb->irb_lock);
22233 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22234 	/*
22235 	 * If we can't find a suitable ire, return the original ire.
22236 	 */
22237 	return (save_ire);
22238 }
22239 
22240 /*
22241  * This function does the ire_refrele of the ire passed in as the
22242  * argument. As this function looks up more ires i.e broadcast ires,
22243  * it needs to REFRELE them. Currently, for simplicity we don't
22244  * differentiate the one passed in and looked up here. We always
22245  * REFRELE.
22246  * IPQoS Notes:
22247  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22248  * IPSec packets are done in ipsec_out_process.
22249  *
22250  */
22251 void
22252 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22253     zoneid_t zoneid)
22254 {
22255 	ipha_t		*ipha;
22256 #define	rptr	((uchar_t *)ipha)
22257 	queue_t		*stq;
22258 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22259 	uint32_t	v_hlen_tos_len;
22260 	uint32_t	ttl_protocol;
22261 	ipaddr_t	src;
22262 	ipaddr_t	dst;
22263 	uint32_t	cksum;
22264 	ipaddr_t	orig_src;
22265 	ire_t		*ire1;
22266 	mblk_t		*next_mp;
22267 	uint_t		hlen;
22268 	uint16_t	*up;
22269 	uint32_t	max_frag = ire->ire_max_frag;
22270 	ill_t		*ill = ire_to_ill(ire);
22271 	int		clusterwide;
22272 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22273 	int		ipsec_len;
22274 	mblk_t		*first_mp;
22275 	ipsec_out_t	*io;
22276 	boolean_t	conn_dontroute;		/* conn value for multicast */
22277 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22278 	boolean_t	multicast_forward;	/* Should we forward ? */
22279 	boolean_t	unspec_src;
22280 	ill_t		*conn_outgoing_ill = NULL;
22281 	ill_t		*ire_ill;
22282 	ill_t		*ire1_ill;
22283 	ill_t		*out_ill;
22284 	uint32_t 	ill_index = 0;
22285 	boolean_t	multirt_send = B_FALSE;
22286 	int		err;
22287 	ipxmit_state_t	pktxmit_state;
22288 	ip_stack_t	*ipst = ire->ire_ipst;
22289 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22290 
22291 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22292 	    "ip_wput_ire_start: q %p", q);
22293 
22294 	multicast_forward = B_FALSE;
22295 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22296 
22297 	if (ire->ire_flags & RTF_MULTIRT) {
22298 		/*
22299 		 * Multirouting case. The bucket where ire is stored
22300 		 * probably holds other RTF_MULTIRT flagged ire
22301 		 * to the destination. In this call to ip_wput_ire,
22302 		 * we attempt to send the packet through all
22303 		 * those ires. Thus, we first ensure that ire is the
22304 		 * first RTF_MULTIRT ire in the bucket,
22305 		 * before walking the ire list.
22306 		 */
22307 		ire_t *first_ire;
22308 		irb_t *irb = ire->ire_bucket;
22309 		ASSERT(irb != NULL);
22310 
22311 		/* Make sure we do not omit any multiroute ire. */
22312 		IRB_REFHOLD(irb);
22313 		for (first_ire = irb->irb_ire;
22314 		    first_ire != NULL;
22315 		    first_ire = first_ire->ire_next) {
22316 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22317 			    (first_ire->ire_addr == ire->ire_addr) &&
22318 			    !(first_ire->ire_marks &
22319 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22320 				break;
22321 		}
22322 
22323 		if ((first_ire != NULL) && (first_ire != ire)) {
22324 			IRE_REFHOLD(first_ire);
22325 			ire_refrele(ire);
22326 			ire = first_ire;
22327 			ill = ire_to_ill(ire);
22328 		}
22329 		IRB_REFRELE(irb);
22330 	}
22331 
22332 	/*
22333 	 * conn_outgoing_ill is used only in the broadcast loop.
22334 	 * for performance we don't grab the mutexs in the fastpath
22335 	 */
22336 	if ((connp != NULL) &&
22337 	    (connp->conn_xmit_if_ill == NULL) &&
22338 	    (ire->ire_type == IRE_BROADCAST) &&
22339 	    ((connp->conn_nofailover_ill != NULL) ||
22340 	    (connp->conn_outgoing_ill != NULL))) {
22341 		/*
22342 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22343 		 * option. So, see if this endpoint is bound to a
22344 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22345 		 * that if the interface is failed, we will still send
22346 		 * the packet on the same ill which is what we want.
22347 		 */
22348 		conn_outgoing_ill = conn_get_held_ill(connp,
22349 		    &connp->conn_nofailover_ill, &err);
22350 		if (err == ILL_LOOKUP_FAILED) {
22351 			ire_refrele(ire);
22352 			freemsg(mp);
22353 			return;
22354 		}
22355 		if (conn_outgoing_ill == NULL) {
22356 			/*
22357 			 * Choose a good ill in the group to send the
22358 			 * packets on.
22359 			 */
22360 			ire = conn_set_outgoing_ill(connp, ire,
22361 			    &conn_outgoing_ill);
22362 			if (ire == NULL) {
22363 				freemsg(mp);
22364 				return;
22365 			}
22366 		}
22367 	}
22368 
22369 	if (mp->b_datap->db_type != M_CTL) {
22370 		ipha = (ipha_t *)mp->b_rptr;
22371 	} else {
22372 		io = (ipsec_out_t *)mp->b_rptr;
22373 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22374 		ASSERT(zoneid == io->ipsec_out_zoneid);
22375 		ASSERT(zoneid != ALL_ZONES);
22376 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22377 		dst = ipha->ipha_dst;
22378 		/*
22379 		 * For the multicast case, ipsec_out carries conn_dontroute and
22380 		 * conn_multicast_loop as conn may not be available here. We
22381 		 * need this for multicast loopback and forwarding which is done
22382 		 * later in the code.
22383 		 */
22384 		if (CLASSD(dst)) {
22385 			conn_dontroute = io->ipsec_out_dontroute;
22386 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22387 			/*
22388 			 * If conn_dontroute is not set or conn_multicast_loop
22389 			 * is set, we need to do forwarding/loopback. For
22390 			 * datagrams from ip_wput_multicast, conn_dontroute is
22391 			 * set to B_TRUE and conn_multicast_loop is set to
22392 			 * B_FALSE so that we neither do forwarding nor
22393 			 * loopback.
22394 			 */
22395 			if (!conn_dontroute || conn_multicast_loop)
22396 				multicast_forward = B_TRUE;
22397 		}
22398 	}
22399 
22400 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22401 	    ire->ire_zoneid != ALL_ZONES) {
22402 		/*
22403 		 * When a zone sends a packet to another zone, we try to deliver
22404 		 * the packet under the same conditions as if the destination
22405 		 * was a real node on the network. To do so, we look for a
22406 		 * matching route in the forwarding table.
22407 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22408 		 * ip_newroute() does.
22409 		 * Note that IRE_LOCAL are special, since they are used
22410 		 * when the zoneid doesn't match in some cases. This means that
22411 		 * we need to handle ipha_src differently since ire_src_addr
22412 		 * belongs to the receiving zone instead of the sending zone.
22413 		 * When ip_restrict_interzone_loopback is set, then
22414 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22415 		 * for loopback between zones when the logical "Ethernet" would
22416 		 * have looped them back.
22417 		 */
22418 		ire_t *src_ire;
22419 
22420 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22421 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22422 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22423 		if (src_ire != NULL &&
22424 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22425 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22426 		    ire_local_same_ill_group(ire, src_ire))) {
22427 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22428 				ipha->ipha_src = src_ire->ire_src_addr;
22429 			ire_refrele(src_ire);
22430 		} else {
22431 			ire_refrele(ire);
22432 			if (conn_outgoing_ill != NULL)
22433 				ill_refrele(conn_outgoing_ill);
22434 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22435 			if (src_ire != NULL) {
22436 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22437 					ire_refrele(src_ire);
22438 					freemsg(mp);
22439 					return;
22440 				}
22441 				ire_refrele(src_ire);
22442 			}
22443 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22444 				/* Failed */
22445 				freemsg(mp);
22446 				return;
22447 			}
22448 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22449 			    ipst);
22450 			return;
22451 		}
22452 	}
22453 
22454 	if (mp->b_datap->db_type == M_CTL ||
22455 	    ipss->ipsec_outbound_v4_policy_present) {
22456 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22457 		    unspec_src, zoneid);
22458 		if (mp == NULL) {
22459 			ire_refrele(ire);
22460 			if (conn_outgoing_ill != NULL)
22461 				ill_refrele(conn_outgoing_ill);
22462 			return;
22463 		}
22464 	}
22465 
22466 	first_mp = mp;
22467 	ipsec_len = 0;
22468 
22469 	if (first_mp->b_datap->db_type == M_CTL) {
22470 		io = (ipsec_out_t *)first_mp->b_rptr;
22471 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22472 		mp = first_mp->b_cont;
22473 		ipsec_len = ipsec_out_extra_length(first_mp);
22474 		ASSERT(ipsec_len >= 0);
22475 		/* We already picked up the zoneid from the M_CTL above */
22476 		ASSERT(zoneid == io->ipsec_out_zoneid);
22477 		ASSERT(zoneid != ALL_ZONES);
22478 
22479 		/*
22480 		 * Drop M_CTL here if IPsec processing is not needed.
22481 		 * (Non-IPsec use of M_CTL extracted any information it
22482 		 * needed above).
22483 		 */
22484 		if (ipsec_len == 0) {
22485 			freeb(first_mp);
22486 			first_mp = mp;
22487 		}
22488 	}
22489 
22490 	/*
22491 	 * Fast path for ip_wput_ire
22492 	 */
22493 
22494 	ipha = (ipha_t *)mp->b_rptr;
22495 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22496 	dst = ipha->ipha_dst;
22497 
22498 	/*
22499 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22500 	 * if the socket is a SOCK_RAW type. The transport checksum should
22501 	 * be provided in the pre-built packet, so we don't need to compute it.
22502 	 * Also, other application set flags, like DF, should not be altered.
22503 	 * Other transport MUST pass down zero.
22504 	 */
22505 	ip_hdr_included = ipha->ipha_ident;
22506 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22507 
22508 	if (CLASSD(dst)) {
22509 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22510 		    ntohl(dst),
22511 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22512 		    ntohl(ire->ire_addr)));
22513 	}
22514 
22515 /* Macros to extract header fields from data already in registers */
22516 #ifdef	_BIG_ENDIAN
22517 #define	V_HLEN	(v_hlen_tos_len >> 24)
22518 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22519 #define	PROTO	(ttl_protocol & 0xFF)
22520 #else
22521 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22522 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22523 #define	PROTO	(ttl_protocol >> 8)
22524 #endif
22525 
22526 
22527 	orig_src = src = ipha->ipha_src;
22528 	/* (The loop back to "another" is explained down below.) */
22529 another:;
22530 	/*
22531 	 * Assign an ident value for this packet.  We assign idents on
22532 	 * a per destination basis out of the IRE.  There could be
22533 	 * other threads targeting the same destination, so we have to
22534 	 * arrange for a atomic increment.  Note that we use a 32-bit
22535 	 * atomic add because it has better performance than its
22536 	 * 16-bit sibling.
22537 	 *
22538 	 * If running in cluster mode and if the source address
22539 	 * belongs to a replicated service then vector through
22540 	 * cl_inet_ipident vector to allocate ip identifier
22541 	 * NOTE: This is a contract private interface with the
22542 	 * clustering group.
22543 	 */
22544 	clusterwide = 0;
22545 	if (cl_inet_ipident) {
22546 		ASSERT(cl_inet_isclusterwide);
22547 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22548 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22549 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22550 			    AF_INET, (uint8_t *)(uintptr_t)src,
22551 			    (uint8_t *)(uintptr_t)dst);
22552 			clusterwide = 1;
22553 		}
22554 	}
22555 	if (!clusterwide) {
22556 		ipha->ipha_ident =
22557 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22558 	}
22559 
22560 #ifndef _BIG_ENDIAN
22561 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22562 #endif
22563 
22564 	/*
22565 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22566 	 * This is needed to obey conn_unspec_src when packets go through
22567 	 * ip_newroute + arp.
22568 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22569 	 */
22570 	if (src == INADDR_ANY && !unspec_src) {
22571 		/*
22572 		 * Assign the appropriate source address from the IRE if none
22573 		 * was specified.
22574 		 */
22575 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22576 
22577 		/*
22578 		 * With IP multipathing, broadcast packets are sent on the ire
22579 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22580 		 * the group. However, this ire might not be in the same zone so
22581 		 * we can't always use its source address. We look for a
22582 		 * broadcast ire in the same group and in the right zone.
22583 		 */
22584 		if (ire->ire_type == IRE_BROADCAST &&
22585 		    ire->ire_zoneid != zoneid) {
22586 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22587 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22588 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22589 			if (src_ire != NULL) {
22590 				src = src_ire->ire_src_addr;
22591 				ire_refrele(src_ire);
22592 			} else {
22593 				ire_refrele(ire);
22594 				if (conn_outgoing_ill != NULL)
22595 					ill_refrele(conn_outgoing_ill);
22596 				freemsg(first_mp);
22597 				if (ill != NULL) {
22598 					BUMP_MIB(ill->ill_ip_mib,
22599 					    ipIfStatsOutDiscards);
22600 				} else {
22601 					BUMP_MIB(&ipst->ips_ip_mib,
22602 					    ipIfStatsOutDiscards);
22603 				}
22604 				return;
22605 			}
22606 		} else {
22607 			src = ire->ire_src_addr;
22608 		}
22609 
22610 		if (connp == NULL) {
22611 			ip1dbg(("ip_wput_ire: no connp and no src "
22612 			    "address for dst 0x%x, using src 0x%x\n",
22613 			    ntohl(dst),
22614 			    ntohl(src)));
22615 		}
22616 		ipha->ipha_src = src;
22617 	}
22618 	stq = ire->ire_stq;
22619 
22620 	/*
22621 	 * We only allow ire chains for broadcasts since there will
22622 	 * be multiple IRE_CACHE entries for the same multicast
22623 	 * address (one per ipif).
22624 	 */
22625 	next_mp = NULL;
22626 
22627 	/* broadcast packet */
22628 	if (ire->ire_type == IRE_BROADCAST)
22629 		goto broadcast;
22630 
22631 	/* loopback ? */
22632 	if (stq == NULL)
22633 		goto nullstq;
22634 
22635 	/* The ill_index for outbound ILL */
22636 	ill_index = Q_TO_INDEX(stq);
22637 
22638 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22639 	ttl_protocol = ((uint16_t *)ipha)[4];
22640 
22641 	/* pseudo checksum (do it in parts for IP header checksum) */
22642 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22643 
22644 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22645 		queue_t *dev_q = stq->q_next;
22646 
22647 		/* flow controlled */
22648 		if ((dev_q->q_next || dev_q->q_first) &&
22649 		    !canput(dev_q))
22650 			goto blocked;
22651 		if ((PROTO == IPPROTO_UDP) &&
22652 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22653 			hlen = (V_HLEN & 0xF) << 2;
22654 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22655 			if (*up != 0) {
22656 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22657 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22658 				/* Software checksum? */
22659 				if (DB_CKSUMFLAGS(mp) == 0) {
22660 					IP_STAT(ipst, ip_out_sw_cksum);
22661 					IP_STAT_UPDATE(ipst,
22662 					    ip_udp_out_sw_cksum_bytes,
22663 					    LENGTH - hlen);
22664 				}
22665 			}
22666 		}
22667 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22668 		hlen = (V_HLEN & 0xF) << 2;
22669 		if (PROTO == IPPROTO_TCP) {
22670 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22671 			/*
22672 			 * The packet header is processed once and for all, even
22673 			 * in the multirouting case. We disable hardware
22674 			 * checksum if the packet is multirouted, as it will be
22675 			 * replicated via several interfaces, and not all of
22676 			 * them may have this capability.
22677 			 */
22678 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22679 			    LENGTH, max_frag, ipsec_len, cksum);
22680 			/* Software checksum? */
22681 			if (DB_CKSUMFLAGS(mp) == 0) {
22682 				IP_STAT(ipst, ip_out_sw_cksum);
22683 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22684 				    LENGTH - hlen);
22685 			}
22686 		} else {
22687 			sctp_hdr_t	*sctph;
22688 
22689 			ASSERT(PROTO == IPPROTO_SCTP);
22690 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22691 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22692 			/*
22693 			 * Zero out the checksum field to ensure proper
22694 			 * checksum calculation.
22695 			 */
22696 			sctph->sh_chksum = 0;
22697 #ifdef	DEBUG
22698 			if (!skip_sctp_cksum)
22699 #endif
22700 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22701 		}
22702 	}
22703 
22704 	/*
22705 	 * If this is a multicast packet and originated from ip_wput
22706 	 * we need to do loopback and forwarding checks. If it comes
22707 	 * from ip_wput_multicast, we SHOULD not do this.
22708 	 */
22709 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22710 
22711 	/* checksum */
22712 	cksum += ttl_protocol;
22713 
22714 	/* fragment the packet */
22715 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22716 		goto fragmentit;
22717 	/*
22718 	 * Don't use frag_flag if packet is pre-built or source
22719 	 * routed or if multicast (since multicast packets do
22720 	 * not solicit ICMP "packet too big" messages).
22721 	 */
22722 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22723 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22724 	    !ip_source_route_included(ipha)) &&
22725 	    !CLASSD(ipha->ipha_dst))
22726 		ipha->ipha_fragment_offset_and_flags |=
22727 		    htons(ire->ire_frag_flag);
22728 
22729 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22730 		/* calculate IP header checksum */
22731 		cksum += ipha->ipha_ident;
22732 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22733 		cksum += ipha->ipha_fragment_offset_and_flags;
22734 
22735 		/* IP options present */
22736 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22737 		if (hlen)
22738 			goto checksumoptions;
22739 
22740 		/* calculate hdr checksum */
22741 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22742 		cksum = ~(cksum + (cksum >> 16));
22743 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22744 	}
22745 	if (ipsec_len != 0) {
22746 		/*
22747 		 * We will do the rest of the processing after
22748 		 * we come back from IPSEC in ip_wput_ipsec_out().
22749 		 */
22750 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22751 
22752 		io = (ipsec_out_t *)first_mp->b_rptr;
22753 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22754 				ill_phyint->phyint_ifindex;
22755 
22756 		ipsec_out_process(q, first_mp, ire, ill_index);
22757 		ire_refrele(ire);
22758 		if (conn_outgoing_ill != NULL)
22759 			ill_refrele(conn_outgoing_ill);
22760 		return;
22761 	}
22762 
22763 	/*
22764 	 * In most cases, the emission loop below is entered only
22765 	 * once. Only in the case where the ire holds the
22766 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22767 	 * flagged ires in the bucket, and send the packet
22768 	 * through all crossed RTF_MULTIRT routes.
22769 	 */
22770 	if (ire->ire_flags & RTF_MULTIRT) {
22771 		multirt_send = B_TRUE;
22772 	}
22773 	do {
22774 		if (multirt_send) {
22775 			irb_t *irb;
22776 			/*
22777 			 * We are in a multiple send case, need to get
22778 			 * the next ire and make a duplicate of the packet.
22779 			 * ire1 holds here the next ire to process in the
22780 			 * bucket. If multirouting is expected,
22781 			 * any non-RTF_MULTIRT ire that has the
22782 			 * right destination address is ignored.
22783 			 */
22784 			irb = ire->ire_bucket;
22785 			ASSERT(irb != NULL);
22786 
22787 			IRB_REFHOLD(irb);
22788 			for (ire1 = ire->ire_next;
22789 			    ire1 != NULL;
22790 			    ire1 = ire1->ire_next) {
22791 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22792 					continue;
22793 				if (ire1->ire_addr != ire->ire_addr)
22794 					continue;
22795 				if (ire1->ire_marks &
22796 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22797 					continue;
22798 
22799 				/* Got one */
22800 				IRE_REFHOLD(ire1);
22801 				break;
22802 			}
22803 			IRB_REFRELE(irb);
22804 
22805 			if (ire1 != NULL) {
22806 				next_mp = copyb(mp);
22807 				if ((next_mp == NULL) ||
22808 				    ((mp->b_cont != NULL) &&
22809 				    ((next_mp->b_cont =
22810 				    dupmsg(mp->b_cont)) == NULL))) {
22811 					freemsg(next_mp);
22812 					next_mp = NULL;
22813 					ire_refrele(ire1);
22814 					ire1 = NULL;
22815 				}
22816 			}
22817 
22818 			/* Last multiroute ire; don't loop anymore. */
22819 			if (ire1 == NULL) {
22820 				multirt_send = B_FALSE;
22821 			}
22822 		}
22823 
22824 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22825 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22826 		    mblk_t *, mp);
22827 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22828 		    ipst->ips_ipv4firewall_physical_out,
22829 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22830 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22831 		if (mp == NULL)
22832 			goto release_ire_and_ill;
22833 
22834 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22835 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22836 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22837 		if ((pktxmit_state == SEND_FAILED) ||
22838 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22839 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22840 			    "- packet dropped\n"));
22841 release_ire_and_ill:
22842 			ire_refrele(ire);
22843 			if (next_mp != NULL) {
22844 				freemsg(next_mp);
22845 				ire_refrele(ire1);
22846 			}
22847 			if (conn_outgoing_ill != NULL)
22848 				ill_refrele(conn_outgoing_ill);
22849 			return;
22850 		}
22851 
22852 		if (CLASSD(dst)) {
22853 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22854 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22855 			    LENGTH);
22856 		}
22857 
22858 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22859 		    "ip_wput_ire_end: q %p (%S)",
22860 		    q, "last copy out");
22861 		IRE_REFRELE(ire);
22862 
22863 		if (multirt_send) {
22864 			ASSERT(ire1);
22865 			/*
22866 			 * Proceed with the next RTF_MULTIRT ire,
22867 			 * Also set up the send-to queue accordingly.
22868 			 */
22869 			ire = ire1;
22870 			ire1 = NULL;
22871 			stq = ire->ire_stq;
22872 			mp = next_mp;
22873 			next_mp = NULL;
22874 			ipha = (ipha_t *)mp->b_rptr;
22875 			ill_index = Q_TO_INDEX(stq);
22876 			ill = (ill_t *)stq->q_ptr;
22877 		}
22878 	} while (multirt_send);
22879 	if (conn_outgoing_ill != NULL)
22880 		ill_refrele(conn_outgoing_ill);
22881 	return;
22882 
22883 	/*
22884 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22885 	 */
22886 broadcast:
22887 	{
22888 		/*
22889 		 * Avoid broadcast storms by setting the ttl to 1
22890 		 * for broadcasts. This parameter can be set
22891 		 * via ndd, so make sure that for the SO_DONTROUTE
22892 		 * case that ipha_ttl is always set to 1.
22893 		 * In the event that we are replying to incoming
22894 		 * ICMP packets, conn could be NULL.
22895 		 */
22896 		if ((connp != NULL) && connp->conn_dontroute)
22897 			ipha->ipha_ttl = 1;
22898 		else
22899 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22900 
22901 		/*
22902 		 * Note that we are not doing a IRB_REFHOLD here.
22903 		 * Actually we don't care if the list changes i.e
22904 		 * if somebody deletes an IRE from the list while
22905 		 * we drop the lock, the next time we come around
22906 		 * ire_next will be NULL and hence we won't send
22907 		 * out multiple copies which is fine.
22908 		 */
22909 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22910 		ire1 = ire->ire_next;
22911 		if (conn_outgoing_ill != NULL) {
22912 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22913 				ASSERT(ire1 == ire->ire_next);
22914 				if (ire1 != NULL && ire1->ire_addr == dst) {
22915 					ire_refrele(ire);
22916 					ire = ire1;
22917 					IRE_REFHOLD(ire);
22918 					ire1 = ire->ire_next;
22919 					continue;
22920 				}
22921 				rw_exit(&ire->ire_bucket->irb_lock);
22922 				/* Did not find a matching ill */
22923 				ip1dbg(("ip_wput_ire: broadcast with no "
22924 				    "matching IP_BOUND_IF ill %s\n",
22925 				    conn_outgoing_ill->ill_name));
22926 				freemsg(first_mp);
22927 				if (ire != NULL)
22928 					ire_refrele(ire);
22929 				ill_refrele(conn_outgoing_ill);
22930 				return;
22931 			}
22932 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22933 			/*
22934 			 * If the next IRE has the same address and is not one
22935 			 * of the two copies that we need to send, try to see
22936 			 * whether this copy should be sent at all. This
22937 			 * assumes that we insert loopbacks first and then
22938 			 * non-loopbacks. This is acheived by inserting the
22939 			 * loopback always before non-loopback.
22940 			 * This is used to send a single copy of a broadcast
22941 			 * packet out all physical interfaces that have an
22942 			 * matching IRE_BROADCAST while also looping
22943 			 * back one copy (to ip_wput_local) for each
22944 			 * matching physical interface. However, we avoid
22945 			 * sending packets out different logical that match by
22946 			 * having ipif_up/ipif_down supress duplicate
22947 			 * IRE_BROADCASTS.
22948 			 *
22949 			 * This feature is currently used to get broadcasts
22950 			 * sent to multiple interfaces, when the broadcast
22951 			 * address being used applies to multiple interfaces.
22952 			 * For example, a whole net broadcast will be
22953 			 * replicated on every connected subnet of
22954 			 * the target net.
22955 			 *
22956 			 * Each zone has its own set of IRE_BROADCASTs, so that
22957 			 * we're able to distribute inbound packets to multiple
22958 			 * zones who share a broadcast address. We avoid looping
22959 			 * back outbound packets in different zones but on the
22960 			 * same ill, as the application would see duplicates.
22961 			 *
22962 			 * If the interfaces are part of the same group,
22963 			 * we would want to send only one copy out for
22964 			 * whole group.
22965 			 *
22966 			 * This logic assumes that ire_add_v4() groups the
22967 			 * IRE_BROADCAST entries so that those with the same
22968 			 * ire_addr and ill_group are kept together.
22969 			 */
22970 			ire_ill = ire->ire_ipif->ipif_ill;
22971 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22972 				if (ire_ill->ill_group != NULL &&
22973 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22974 					/*
22975 					 * If the current zone only has an ire
22976 					 * broadcast for this address marked
22977 					 * NORECV, the ire we want is ahead in
22978 					 * the bucket, so we look it up
22979 					 * deliberately ignoring the zoneid.
22980 					 */
22981 					for (ire1 = ire->ire_bucket->irb_ire;
22982 					    ire1 != NULL;
22983 					    ire1 = ire1->ire_next) {
22984 						ire1_ill =
22985 						    ire1->ire_ipif->ipif_ill;
22986 						if (ire1->ire_addr != dst)
22987 							continue;
22988 						/* skip over the current ire */
22989 						if (ire1 == ire)
22990 							continue;
22991 						/* skip over deleted ires */
22992 						if (ire1->ire_marks &
22993 						    IRE_MARK_CONDEMNED)
22994 							continue;
22995 						/*
22996 						 * non-loopback ire in our
22997 						 * group: use it for the next
22998 						 * pass in the loop
22999 						 */
23000 						if (ire1->ire_stq != NULL &&
23001 						    ire1_ill->ill_group ==
23002 						    ire_ill->ill_group)
23003 							break;
23004 					}
23005 				}
23006 			} else {
23007 				while (ire1 != NULL && ire1->ire_addr == dst) {
23008 					ire1_ill = ire1->ire_ipif->ipif_ill;
23009 					/*
23010 					 * We can have two broadcast ires on the
23011 					 * same ill in different zones; here
23012 					 * we'll send a copy of the packet on
23013 					 * each ill and the fanout code will
23014 					 * call conn_wantpacket() to check that
23015 					 * the zone has the broadcast address
23016 					 * configured on the ill. If the two
23017 					 * ires are in the same group we only
23018 					 * send one copy up.
23019 					 */
23020 					if (ire1_ill != ire_ill &&
23021 					    (ire1_ill->ill_group == NULL ||
23022 					    ire_ill->ill_group == NULL ||
23023 					    ire1_ill->ill_group !=
23024 					    ire_ill->ill_group)) {
23025 						break;
23026 					}
23027 					ire1 = ire1->ire_next;
23028 				}
23029 			}
23030 		}
23031 		ASSERT(multirt_send == B_FALSE);
23032 		if (ire1 != NULL && ire1->ire_addr == dst) {
23033 			if ((ire->ire_flags & RTF_MULTIRT) &&
23034 			    (ire1->ire_flags & RTF_MULTIRT)) {
23035 				/*
23036 				 * We are in the multirouting case.
23037 				 * The message must be sent at least
23038 				 * on both ires. These ires have been
23039 				 * inserted AFTER the standard ones
23040 				 * in ip_rt_add(). There are thus no
23041 				 * other ire entries for the destination
23042 				 * address in the rest of the bucket
23043 				 * that do not have the RTF_MULTIRT
23044 				 * flag. We don't process a copy
23045 				 * of the message here. This will be
23046 				 * done in the final sending loop.
23047 				 */
23048 				multirt_send = B_TRUE;
23049 			} else {
23050 				next_mp = ip_copymsg(first_mp);
23051 				if (next_mp != NULL)
23052 					IRE_REFHOLD(ire1);
23053 			}
23054 		}
23055 		rw_exit(&ire->ire_bucket->irb_lock);
23056 	}
23057 
23058 	if (stq) {
23059 		/*
23060 		 * A non-NULL send-to queue means this packet is going
23061 		 * out of this machine.
23062 		 */
23063 		out_ill = (ill_t *)stq->q_ptr;
23064 
23065 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23066 		ttl_protocol = ((uint16_t *)ipha)[4];
23067 		/*
23068 		 * We accumulate the pseudo header checksum in cksum.
23069 		 * This is pretty hairy code, so watch close.  One
23070 		 * thing to keep in mind is that UDP and TCP have
23071 		 * stored their respective datagram lengths in their
23072 		 * checksum fields.  This lines things up real nice.
23073 		 */
23074 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23075 		    (src >> 16) + (src & 0xFFFF);
23076 		/*
23077 		 * We assume the udp checksum field contains the
23078 		 * length, so to compute the pseudo header checksum,
23079 		 * all we need is the protocol number and src/dst.
23080 		 */
23081 		/* Provide the checksums for UDP and TCP. */
23082 		if ((PROTO == IPPROTO_TCP) &&
23083 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23084 			/* hlen gets the number of uchar_ts in the IP header */
23085 			hlen = (V_HLEN & 0xF) << 2;
23086 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23087 			IP_STAT(ipst, ip_out_sw_cksum);
23088 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23089 			    LENGTH - hlen);
23090 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23091 		} else if (PROTO == IPPROTO_SCTP &&
23092 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23093 			sctp_hdr_t	*sctph;
23094 
23095 			hlen = (V_HLEN & 0xF) << 2;
23096 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23097 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23098 			sctph->sh_chksum = 0;
23099 #ifdef	DEBUG
23100 			if (!skip_sctp_cksum)
23101 #endif
23102 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23103 		} else {
23104 			queue_t *dev_q = stq->q_next;
23105 
23106 			if ((dev_q->q_next || dev_q->q_first) &&
23107 			    !canput(dev_q)) {
23108 			    blocked:
23109 				ipha->ipha_ident = ip_hdr_included;
23110 				/*
23111 				 * If we don't have a conn to apply
23112 				 * backpressure, free the message.
23113 				 * In the ire_send path, we don't know
23114 				 * the position to requeue the packet. Rather
23115 				 * than reorder packets, we just drop this
23116 				 * packet.
23117 				 */
23118 				if (ipst->ips_ip_output_queue &&
23119 				    connp != NULL &&
23120 				    caller != IRE_SEND) {
23121 					if (caller == IP_WSRV) {
23122 						connp->conn_did_putbq = 1;
23123 						(void) putbq(connp->conn_wq,
23124 						    first_mp);
23125 						conn_drain_insert(connp);
23126 						/*
23127 						 * This is the service thread,
23128 						 * and the queue is already
23129 						 * noenabled. The check for
23130 						 * canput and the putbq is not
23131 						 * atomic. So we need to check
23132 						 * again.
23133 						 */
23134 						if (canput(stq->q_next))
23135 							connp->conn_did_putbq
23136 							    = 0;
23137 						IP_STAT(ipst, ip_conn_flputbq);
23138 					} else {
23139 						/*
23140 						 * We are not the service proc.
23141 						 * ip_wsrv will be scheduled or
23142 						 * is already running.
23143 						 */
23144 						(void) putq(connp->conn_wq,
23145 						    first_mp);
23146 					}
23147 				} else {
23148 					out_ill = (ill_t *)stq->q_ptr;
23149 					BUMP_MIB(out_ill->ill_ip_mib,
23150 					    ipIfStatsOutDiscards);
23151 					freemsg(first_mp);
23152 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23153 					    "ip_wput_ire_end: q %p (%S)",
23154 					    q, "discard");
23155 				}
23156 				ire_refrele(ire);
23157 				if (next_mp) {
23158 					ire_refrele(ire1);
23159 					freemsg(next_mp);
23160 				}
23161 				if (conn_outgoing_ill != NULL)
23162 					ill_refrele(conn_outgoing_ill);
23163 				return;
23164 			}
23165 			if ((PROTO == IPPROTO_UDP) &&
23166 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23167 				/*
23168 				 * hlen gets the number of uchar_ts in the
23169 				 * IP header
23170 				 */
23171 				hlen = (V_HLEN & 0xF) << 2;
23172 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23173 				max_frag = ire->ire_max_frag;
23174 				if (*up != 0) {
23175 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23176 					    up, PROTO, hlen, LENGTH, max_frag,
23177 					    ipsec_len, cksum);
23178 					/* Software checksum? */
23179 					if (DB_CKSUMFLAGS(mp) == 0) {
23180 						IP_STAT(ipst, ip_out_sw_cksum);
23181 						IP_STAT_UPDATE(ipst,
23182 						    ip_udp_out_sw_cksum_bytes,
23183 						    LENGTH - hlen);
23184 					}
23185 				}
23186 			}
23187 		}
23188 		/*
23189 		 * Need to do this even when fragmenting. The local
23190 		 * loopback can be done without computing checksums
23191 		 * but forwarding out other interface must be done
23192 		 * after the IP checksum (and ULP checksums) have been
23193 		 * computed.
23194 		 *
23195 		 * NOTE : multicast_forward is set only if this packet
23196 		 * originated from ip_wput. For packets originating from
23197 		 * ip_wput_multicast, it is not set.
23198 		 */
23199 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23200 		    multi_loopback:
23201 			ip2dbg(("ip_wput: multicast, loop %d\n",
23202 			    conn_multicast_loop));
23203 
23204 			/*  Forget header checksum offload */
23205 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23206 
23207 			/*
23208 			 * Local loopback of multicasts?  Check the
23209 			 * ill.
23210 			 *
23211 			 * Note that the loopback function will not come
23212 			 * in through ip_rput - it will only do the
23213 			 * client fanout thus we need to do an mforward
23214 			 * as well.  The is different from the BSD
23215 			 * logic.
23216 			 */
23217 			if (ill != NULL) {
23218 				ilm_t	*ilm;
23219 
23220 				ILM_WALKER_HOLD(ill);
23221 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23222 				    ALL_ZONES);
23223 				ILM_WALKER_RELE(ill);
23224 				if (ilm != NULL) {
23225 					/*
23226 					 * Pass along the virtual output q.
23227 					 * ip_wput_local() will distribute the
23228 					 * packet to all the matching zones,
23229 					 * except the sending zone when
23230 					 * IP_MULTICAST_LOOP is false.
23231 					 */
23232 					ip_multicast_loopback(q, ill, first_mp,
23233 					    conn_multicast_loop ? 0 :
23234 					    IP_FF_NO_MCAST_LOOP, zoneid);
23235 				}
23236 			}
23237 			if (ipha->ipha_ttl == 0) {
23238 				/*
23239 				 * 0 => only to this host i.e. we are
23240 				 * done. We are also done if this was the
23241 				 * loopback interface since it is sufficient
23242 				 * to loopback one copy of a multicast packet.
23243 				 */
23244 				freemsg(first_mp);
23245 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23246 				    "ip_wput_ire_end: q %p (%S)",
23247 				    q, "loopback");
23248 				ire_refrele(ire);
23249 				if (conn_outgoing_ill != NULL)
23250 					ill_refrele(conn_outgoing_ill);
23251 				return;
23252 			}
23253 			/*
23254 			 * ILLF_MULTICAST is checked in ip_newroute
23255 			 * i.e. we don't need to check it here since
23256 			 * all IRE_CACHEs come from ip_newroute.
23257 			 * For multicast traffic, SO_DONTROUTE is interpreted
23258 			 * to mean only send the packet out the interface
23259 			 * (optionally specified with IP_MULTICAST_IF)
23260 			 * and do not forward it out additional interfaces.
23261 			 * RSVP and the rsvp daemon is an example of a
23262 			 * protocol and user level process that
23263 			 * handles it's own routing. Hence, it uses the
23264 			 * SO_DONTROUTE option to accomplish this.
23265 			 */
23266 
23267 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23268 			    ill != NULL) {
23269 				/* Unconditionally redo the checksum */
23270 				ipha->ipha_hdr_checksum = 0;
23271 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23272 
23273 				/*
23274 				 * If this needs to go out secure, we need
23275 				 * to wait till we finish the IPSEC
23276 				 * processing.
23277 				 */
23278 				if (ipsec_len == 0 &&
23279 				    ip_mforward(ill, ipha, mp)) {
23280 					freemsg(first_mp);
23281 					ip1dbg(("ip_wput: mforward failed\n"));
23282 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23283 					    "ip_wput_ire_end: q %p (%S)",
23284 					    q, "mforward failed");
23285 					ire_refrele(ire);
23286 					if (conn_outgoing_ill != NULL)
23287 						ill_refrele(conn_outgoing_ill);
23288 					return;
23289 				}
23290 			}
23291 		}
23292 		max_frag = ire->ire_max_frag;
23293 		cksum += ttl_protocol;
23294 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23295 			/* No fragmentation required for this one. */
23296 			/*
23297 			 * Don't use frag_flag if packet is pre-built or source
23298 			 * routed or if multicast (since multicast packets do
23299 			 * not solicit ICMP "packet too big" messages).
23300 			 */
23301 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23302 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23303 			    !ip_source_route_included(ipha)) &&
23304 			    !CLASSD(ipha->ipha_dst))
23305 				ipha->ipha_fragment_offset_and_flags |=
23306 				    htons(ire->ire_frag_flag);
23307 
23308 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23309 				/* Complete the IP header checksum. */
23310 				cksum += ipha->ipha_ident;
23311 				cksum += (v_hlen_tos_len >> 16)+
23312 				    (v_hlen_tos_len & 0xFFFF);
23313 				cksum += ipha->ipha_fragment_offset_and_flags;
23314 				hlen = (V_HLEN & 0xF) -
23315 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23316 				if (hlen) {
23317 				    checksumoptions:
23318 					/*
23319 					 * Account for the IP Options in the IP
23320 					 * header checksum.
23321 					 */
23322 					up = (uint16_t *)(rptr+
23323 					    IP_SIMPLE_HDR_LENGTH);
23324 					do {
23325 						cksum += up[0];
23326 						cksum += up[1];
23327 						up += 2;
23328 					} while (--hlen);
23329 				}
23330 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23331 				cksum = ~(cksum + (cksum >> 16));
23332 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23333 			}
23334 			if (ipsec_len != 0) {
23335 				ipsec_out_process(q, first_mp, ire, ill_index);
23336 				if (!next_mp) {
23337 					ire_refrele(ire);
23338 					if (conn_outgoing_ill != NULL)
23339 						ill_refrele(conn_outgoing_ill);
23340 					return;
23341 				}
23342 				goto next;
23343 			}
23344 
23345 			/*
23346 			 * multirt_send has already been handled
23347 			 * for broadcast, but not yet for multicast
23348 			 * or IP options.
23349 			 */
23350 			if (next_mp == NULL) {
23351 				if (ire->ire_flags & RTF_MULTIRT) {
23352 					multirt_send = B_TRUE;
23353 				}
23354 			}
23355 
23356 			/*
23357 			 * In most cases, the emission loop below is
23358 			 * entered only once. Only in the case where
23359 			 * the ire holds the RTF_MULTIRT flag, do we loop
23360 			 * to process all RTF_MULTIRT ires in the bucket,
23361 			 * and send the packet through all crossed
23362 			 * RTF_MULTIRT routes.
23363 			 */
23364 			do {
23365 				if (multirt_send) {
23366 					irb_t *irb;
23367 
23368 					irb = ire->ire_bucket;
23369 					ASSERT(irb != NULL);
23370 					/*
23371 					 * We are in a multiple send case,
23372 					 * need to get the next IRE and make
23373 					 * a duplicate of the packet.
23374 					 */
23375 					IRB_REFHOLD(irb);
23376 					for (ire1 = ire->ire_next;
23377 					    ire1 != NULL;
23378 					    ire1 = ire1->ire_next) {
23379 						if (!(ire1->ire_flags &
23380 						    RTF_MULTIRT))
23381 							continue;
23382 						if (ire1->ire_addr !=
23383 						    ire->ire_addr)
23384 							continue;
23385 						if (ire1->ire_marks &
23386 						    (IRE_MARK_CONDEMNED|
23387 							IRE_MARK_HIDDEN))
23388 							continue;
23389 
23390 						/* Got one */
23391 						IRE_REFHOLD(ire1);
23392 						break;
23393 					}
23394 					IRB_REFRELE(irb);
23395 
23396 					if (ire1 != NULL) {
23397 						next_mp = copyb(mp);
23398 						if ((next_mp == NULL) ||
23399 						    ((mp->b_cont != NULL) &&
23400 						    ((next_mp->b_cont =
23401 						    dupmsg(mp->b_cont))
23402 						    == NULL))) {
23403 							freemsg(next_mp);
23404 							next_mp = NULL;
23405 							ire_refrele(ire1);
23406 							ire1 = NULL;
23407 						}
23408 					}
23409 
23410 					/*
23411 					 * Last multiroute ire; don't loop
23412 					 * anymore. The emission is over
23413 					 * and next_mp is NULL.
23414 					 */
23415 					if (ire1 == NULL) {
23416 						multirt_send = B_FALSE;
23417 					}
23418 				}
23419 
23420 				out_ill = ire->ire_ipif->ipif_ill;
23421 				DTRACE_PROBE4(ip4__physical__out__start,
23422 				    ill_t *, NULL,
23423 				    ill_t *, out_ill,
23424 				    ipha_t *, ipha, mblk_t *, mp);
23425 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23426 				    ipst->ips_ipv4firewall_physical_out,
23427 				    NULL, out_ill, ipha, mp, mp, ipst);
23428 				DTRACE_PROBE1(ip4__physical__out__end,
23429 				    mblk_t *, mp);
23430 				if (mp == NULL)
23431 					goto release_ire_and_ill_2;
23432 
23433 				ASSERT(ipsec_len == 0);
23434 				mp->b_prev =
23435 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23436 				DTRACE_PROBE2(ip__xmit__2,
23437 				    mblk_t *, mp, ire_t *, ire);
23438 				pktxmit_state = ip_xmit_v4(mp, ire,
23439 				    NULL, B_TRUE);
23440 				if ((pktxmit_state == SEND_FAILED) ||
23441 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23442 release_ire_and_ill_2:
23443 					if (next_mp) {
23444 						freemsg(next_mp);
23445 						ire_refrele(ire1);
23446 					}
23447 					ire_refrele(ire);
23448 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23449 					    "ip_wput_ire_end: q %p (%S)",
23450 					    q, "discard MDATA");
23451 					if (conn_outgoing_ill != NULL)
23452 						ill_refrele(conn_outgoing_ill);
23453 					return;
23454 				}
23455 
23456 				if (CLASSD(dst)) {
23457 					BUMP_MIB(out_ill->ill_ip_mib,
23458 					    ipIfStatsHCOutMcastPkts);
23459 					UPDATE_MIB(out_ill->ill_ip_mib,
23460 					    ipIfStatsHCOutMcastOctets,
23461 					    LENGTH);
23462 				} else if (ire->ire_type == IRE_BROADCAST) {
23463 					BUMP_MIB(out_ill->ill_ip_mib,
23464 					    ipIfStatsHCOutBcastPkts);
23465 				}
23466 
23467 				if (multirt_send) {
23468 					/*
23469 					 * We are in a multiple send case,
23470 					 * need to re-enter the sending loop
23471 					 * using the next ire.
23472 					 */
23473 					ire_refrele(ire);
23474 					ire = ire1;
23475 					stq = ire->ire_stq;
23476 					mp = next_mp;
23477 					next_mp = NULL;
23478 					ipha = (ipha_t *)mp->b_rptr;
23479 					ill_index = Q_TO_INDEX(stq);
23480 				}
23481 			} while (multirt_send);
23482 
23483 			if (!next_mp) {
23484 				/*
23485 				 * Last copy going out (the ultra-common
23486 				 * case).  Note that we intentionally replicate
23487 				 * the putnext rather than calling it before
23488 				 * the next_mp check in hopes of a little
23489 				 * tail-call action out of the compiler.
23490 				 */
23491 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23492 				    "ip_wput_ire_end: q %p (%S)",
23493 				    q, "last copy out(1)");
23494 				ire_refrele(ire);
23495 				if (conn_outgoing_ill != NULL)
23496 					ill_refrele(conn_outgoing_ill);
23497 				return;
23498 			}
23499 			/* More copies going out below. */
23500 		} else {
23501 			int offset;
23502 		    fragmentit:
23503 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23504 			/*
23505 			 * If this would generate a icmp_frag_needed message,
23506 			 * we need to handle it before we do the IPSEC
23507 			 * processing. Otherwise, we need to strip the IPSEC
23508 			 * headers before we send up the message to the ULPs
23509 			 * which becomes messy and difficult.
23510 			 */
23511 			if (ipsec_len != 0) {
23512 				if ((max_frag < (unsigned int)(LENGTH +
23513 				    ipsec_len)) && (offset & IPH_DF)) {
23514 					out_ill = (ill_t *)stq->q_ptr;
23515 					BUMP_MIB(out_ill->ill_ip_mib,
23516 					    ipIfStatsOutFragFails);
23517 					BUMP_MIB(out_ill->ill_ip_mib,
23518 					    ipIfStatsOutFragReqds);
23519 					ipha->ipha_hdr_checksum = 0;
23520 					ipha->ipha_hdr_checksum =
23521 					    (uint16_t)ip_csum_hdr(ipha);
23522 					icmp_frag_needed(ire->ire_stq, first_mp,
23523 					    max_frag, zoneid, ipst);
23524 					if (!next_mp) {
23525 						ire_refrele(ire);
23526 						if (conn_outgoing_ill != NULL) {
23527 							ill_refrele(
23528 							    conn_outgoing_ill);
23529 						}
23530 						return;
23531 					}
23532 				} else {
23533 					/*
23534 					 * This won't cause a icmp_frag_needed
23535 					 * message. to be generated. Send it on
23536 					 * the wire. Note that this could still
23537 					 * cause fragmentation and all we
23538 					 * do is the generation of the message
23539 					 * to the ULP if needed before IPSEC.
23540 					 */
23541 					if (!next_mp) {
23542 						ipsec_out_process(q, first_mp,
23543 						    ire, ill_index);
23544 						TRACE_2(TR_FAC_IP,
23545 						    TR_IP_WPUT_IRE_END,
23546 						    "ip_wput_ire_end: q %p "
23547 						    "(%S)", q,
23548 						    "last ipsec_out_process");
23549 						ire_refrele(ire);
23550 						if (conn_outgoing_ill != NULL) {
23551 							ill_refrele(
23552 							    conn_outgoing_ill);
23553 						}
23554 						return;
23555 					}
23556 					ipsec_out_process(q, first_mp,
23557 					    ire, ill_index);
23558 				}
23559 			} else {
23560 				/*
23561 				 * Initiate IPPF processing. For
23562 				 * fragmentable packets we finish
23563 				 * all QOS packet processing before
23564 				 * calling:
23565 				 * ip_wput_ire_fragmentit->ip_wput_frag
23566 				 */
23567 
23568 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23569 					ip_process(IPP_LOCAL_OUT, &mp,
23570 					    ill_index);
23571 					if (mp == NULL) {
23572 						out_ill = (ill_t *)stq->q_ptr;
23573 						BUMP_MIB(out_ill->ill_ip_mib,
23574 						    ipIfStatsOutDiscards);
23575 						if (next_mp != NULL) {
23576 							freemsg(next_mp);
23577 							ire_refrele(ire1);
23578 						}
23579 						ire_refrele(ire);
23580 						TRACE_2(TR_FAC_IP,
23581 						    TR_IP_WPUT_IRE_END,
23582 						    "ip_wput_ire: q %p (%S)",
23583 						    q, "discard MDATA");
23584 						if (conn_outgoing_ill != NULL) {
23585 							ill_refrele(
23586 							    conn_outgoing_ill);
23587 						}
23588 						return;
23589 					}
23590 				}
23591 				if (!next_mp) {
23592 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23593 					    "ip_wput_ire_end: q %p (%S)",
23594 					    q, "last fragmentation");
23595 					ip_wput_ire_fragmentit(mp, ire,
23596 					    zoneid, ipst);
23597 					ire_refrele(ire);
23598 					if (conn_outgoing_ill != NULL)
23599 						ill_refrele(conn_outgoing_ill);
23600 					return;
23601 				}
23602 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23603 			}
23604 		}
23605 	} else {
23606 	    nullstq:
23607 		/* A NULL stq means the destination address is local. */
23608 		UPDATE_OB_PKT_COUNT(ire);
23609 		ire->ire_last_used_time = lbolt;
23610 		ASSERT(ire->ire_ipif != NULL);
23611 		if (!next_mp) {
23612 			/*
23613 			 * Is there an "in" and "out" for traffic local
23614 			 * to a host (loopback)?  The code in Solaris doesn't
23615 			 * explicitly draw a line in its code for in vs out,
23616 			 * so we've had to draw a line in the sand: ip_wput_ire
23617 			 * is considered to be the "output" side and
23618 			 * ip_wput_local to be the "input" side.
23619 			 */
23620 			out_ill = ire->ire_ipif->ipif_ill;
23621 
23622 			DTRACE_PROBE4(ip4__loopback__out__start,
23623 			    ill_t *, NULL, ill_t *, out_ill,
23624 			    ipha_t *, ipha, mblk_t *, first_mp);
23625 
23626 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23627 			    ipst->ips_ipv4firewall_loopback_out,
23628 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23629 
23630 			DTRACE_PROBE1(ip4__loopback__out_end,
23631 			    mblk_t *, first_mp);
23632 
23633 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23634 			    "ip_wput_ire_end: q %p (%S)",
23635 			    q, "local address");
23636 
23637 			if (first_mp != NULL)
23638 				ip_wput_local(q, out_ill, ipha,
23639 				    first_mp, ire, 0, ire->ire_zoneid);
23640 			ire_refrele(ire);
23641 			if (conn_outgoing_ill != NULL)
23642 				ill_refrele(conn_outgoing_ill);
23643 			return;
23644 		}
23645 
23646 		out_ill = ire->ire_ipif->ipif_ill;
23647 
23648 		DTRACE_PROBE4(ip4__loopback__out__start,
23649 		    ill_t *, NULL, ill_t *, out_ill,
23650 		    ipha_t *, ipha, mblk_t *, first_mp);
23651 
23652 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23653 		    ipst->ips_ipv4firewall_loopback_out,
23654 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23655 
23656 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23657 
23658 		if (first_mp != NULL)
23659 			ip_wput_local(q, out_ill, ipha,
23660 			    first_mp, ire, 0, ire->ire_zoneid);
23661 	}
23662 next:
23663 	/*
23664 	 * More copies going out to additional interfaces.
23665 	 * ire1 has already been held. We don't need the
23666 	 * "ire" anymore.
23667 	 */
23668 	ire_refrele(ire);
23669 	ire = ire1;
23670 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23671 	mp = next_mp;
23672 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23673 	ill = ire_to_ill(ire);
23674 	first_mp = mp;
23675 	if (ipsec_len != 0) {
23676 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23677 		mp = mp->b_cont;
23678 	}
23679 	dst = ire->ire_addr;
23680 	ipha = (ipha_t *)mp->b_rptr;
23681 	/*
23682 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23683 	 * Restore ipha_ident "no checksum" flag.
23684 	 */
23685 	src = orig_src;
23686 	ipha->ipha_ident = ip_hdr_included;
23687 	goto another;
23688 
23689 #undef	rptr
23690 #undef	Q_TO_INDEX
23691 }
23692 
23693 /*
23694  * Routine to allocate a message that is used to notify the ULP about MDT.
23695  * The caller may provide a pointer to the link-layer MDT capabilities,
23696  * or NULL if MDT is to be disabled on the stream.
23697  */
23698 mblk_t *
23699 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23700 {
23701 	mblk_t *mp;
23702 	ip_mdt_info_t *mdti;
23703 	ill_mdt_capab_t *idst;
23704 
23705 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23706 		DB_TYPE(mp) = M_CTL;
23707 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23708 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23709 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23710 		idst = &(mdti->mdt_capab);
23711 
23712 		/*
23713 		 * If the caller provides us with the capability, copy
23714 		 * it over into our notification message; otherwise
23715 		 * we zero out the capability portion.
23716 		 */
23717 		if (isrc != NULL)
23718 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23719 		else
23720 			bzero((caddr_t)idst, sizeof (*idst));
23721 	}
23722 	return (mp);
23723 }
23724 
23725 /*
23726  * Routine which determines whether MDT can be enabled on the destination
23727  * IRE and IPC combination, and if so, allocates and returns the MDT
23728  * notification mblk that may be used by ULP.  We also check if we need to
23729  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23730  * MDT usage in the past have been lifted.  This gets called during IP
23731  * and ULP binding.
23732  */
23733 mblk_t *
23734 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23735     ill_mdt_capab_t *mdt_cap)
23736 {
23737 	mblk_t *mp;
23738 	boolean_t rc = B_FALSE;
23739 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23740 
23741 	ASSERT(dst_ire != NULL);
23742 	ASSERT(connp != NULL);
23743 	ASSERT(mdt_cap != NULL);
23744 
23745 	/*
23746 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23747 	 * Multidata, which is handled in tcp_multisend().  This
23748 	 * is the reason why we do all these checks here, to ensure
23749 	 * that we don't enable Multidata for the cases which we
23750 	 * can't handle at the moment.
23751 	 */
23752 	do {
23753 		/* Only do TCP at the moment */
23754 		if (connp->conn_ulp != IPPROTO_TCP)
23755 			break;
23756 
23757 		/*
23758 		 * IPSEC outbound policy present?  Note that we get here
23759 		 * after calling ipsec_conn_cache_policy() where the global
23760 		 * policy checking is performed.  conn_latch will be
23761 		 * non-NULL as long as there's a policy defined,
23762 		 * i.e. conn_out_enforce_policy may be NULL in such case
23763 		 * when the connection is non-secure, and hence we check
23764 		 * further if the latch refers to an outbound policy.
23765 		 */
23766 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23767 			break;
23768 
23769 		/* CGTP (multiroute) is enabled? */
23770 		if (dst_ire->ire_flags & RTF_MULTIRT)
23771 			break;
23772 
23773 		/* Outbound IPQoS enabled? */
23774 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23775 			/*
23776 			 * In this case, we disable MDT for this and all
23777 			 * future connections going over the interface.
23778 			 */
23779 			mdt_cap->ill_mdt_on = 0;
23780 			break;
23781 		}
23782 
23783 		/* socket option(s) present? */
23784 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23785 			break;
23786 
23787 		rc = B_TRUE;
23788 	/* CONSTCOND */
23789 	} while (0);
23790 
23791 	/* Remember the result */
23792 	connp->conn_mdt_ok = rc;
23793 
23794 	if (!rc)
23795 		return (NULL);
23796 	else if (!mdt_cap->ill_mdt_on) {
23797 		/*
23798 		 * If MDT has been previously turned off in the past, and we
23799 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23800 		 * then enable it for this interface.
23801 		 */
23802 		mdt_cap->ill_mdt_on = 1;
23803 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23804 		    "interface %s\n", ill_name));
23805 	}
23806 
23807 	/* Allocate the MDT info mblk */
23808 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23809 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23810 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23811 		return (NULL);
23812 	}
23813 	return (mp);
23814 }
23815 
23816 /*
23817  * Routine to allocate a message that is used to notify the ULP about LSO.
23818  * The caller may provide a pointer to the link-layer LSO capabilities,
23819  * or NULL if LSO is to be disabled on the stream.
23820  */
23821 mblk_t *
23822 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23823 {
23824 	mblk_t *mp;
23825 	ip_lso_info_t *lsoi;
23826 	ill_lso_capab_t *idst;
23827 
23828 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23829 		DB_TYPE(mp) = M_CTL;
23830 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23831 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23832 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23833 		idst = &(lsoi->lso_capab);
23834 
23835 		/*
23836 		 * If the caller provides us with the capability, copy
23837 		 * it over into our notification message; otherwise
23838 		 * we zero out the capability portion.
23839 		 */
23840 		if (isrc != NULL)
23841 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23842 		else
23843 			bzero((caddr_t)idst, sizeof (*idst));
23844 	}
23845 	return (mp);
23846 }
23847 
23848 /*
23849  * Routine which determines whether LSO can be enabled on the destination
23850  * IRE and IPC combination, and if so, allocates and returns the LSO
23851  * notification mblk that may be used by ULP.  We also check if we need to
23852  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23853  * LSO usage in the past have been lifted.  This gets called during IP
23854  * and ULP binding.
23855  */
23856 mblk_t *
23857 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23858     ill_lso_capab_t *lso_cap)
23859 {
23860 	mblk_t *mp;
23861 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23862 
23863 	ASSERT(dst_ire != NULL);
23864 	ASSERT(connp != NULL);
23865 	ASSERT(lso_cap != NULL);
23866 
23867 	connp->conn_lso_ok = B_TRUE;
23868 
23869 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23870 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23871 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23872 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23873 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23874 		connp->conn_lso_ok = B_FALSE;
23875 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23876 			/*
23877 			 * Disable LSO for this and all future connections going
23878 			 * over the interface.
23879 			 */
23880 			lso_cap->ill_lso_on = 0;
23881 		}
23882 	}
23883 
23884 	if (!connp->conn_lso_ok)
23885 		return (NULL);
23886 	else if (!lso_cap->ill_lso_on) {
23887 		/*
23888 		 * If LSO has been previously turned off in the past, and we
23889 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23890 		 * then enable it for this interface.
23891 		 */
23892 		lso_cap->ill_lso_on = 1;
23893 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23894 		    ill_name));
23895 	}
23896 
23897 	/* Allocate the LSO info mblk */
23898 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23899 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23900 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23901 
23902 	return (mp);
23903 }
23904 
23905 /*
23906  * Create destination address attribute, and fill it with the physical
23907  * destination address and SAP taken from the template DL_UNITDATA_REQ
23908  * message block.
23909  */
23910 boolean_t
23911 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23912 {
23913 	dl_unitdata_req_t *dlurp;
23914 	pattr_t *pa;
23915 	pattrinfo_t pa_info;
23916 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23917 	uint_t das_len, das_off;
23918 
23919 	ASSERT(dlmp != NULL);
23920 
23921 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23922 	das_len = dlurp->dl_dest_addr_length;
23923 	das_off = dlurp->dl_dest_addr_offset;
23924 
23925 	pa_info.type = PATTR_DSTADDRSAP;
23926 	pa_info.len = sizeof (**das) + das_len - 1;
23927 
23928 	/* create and associate the attribute */
23929 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23930 	if (pa != NULL) {
23931 		ASSERT(*das != NULL);
23932 		(*das)->addr_is_group = 0;
23933 		(*das)->addr_len = (uint8_t)das_len;
23934 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23935 	}
23936 
23937 	return (pa != NULL);
23938 }
23939 
23940 /*
23941  * Create hardware checksum attribute and fill it with the values passed.
23942  */
23943 boolean_t
23944 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23945     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23946 {
23947 	pattr_t *pa;
23948 	pattrinfo_t pa_info;
23949 
23950 	ASSERT(mmd != NULL);
23951 
23952 	pa_info.type = PATTR_HCKSUM;
23953 	pa_info.len = sizeof (pattr_hcksum_t);
23954 
23955 	/* create and associate the attribute */
23956 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23957 	if (pa != NULL) {
23958 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23959 
23960 		hck->hcksum_start_offset = start_offset;
23961 		hck->hcksum_stuff_offset = stuff_offset;
23962 		hck->hcksum_end_offset = end_offset;
23963 		hck->hcksum_flags = flags;
23964 	}
23965 	return (pa != NULL);
23966 }
23967 
23968 /*
23969  * Create zerocopy attribute and fill it with the specified flags
23970  */
23971 boolean_t
23972 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23973 {
23974 	pattr_t *pa;
23975 	pattrinfo_t pa_info;
23976 
23977 	ASSERT(mmd != NULL);
23978 	pa_info.type = PATTR_ZCOPY;
23979 	pa_info.len = sizeof (pattr_zcopy_t);
23980 
23981 	/* create and associate the attribute */
23982 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23983 	if (pa != NULL) {
23984 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23985 
23986 		zcopy->zcopy_flags = flags;
23987 	}
23988 	return (pa != NULL);
23989 }
23990 
23991 /*
23992  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23993  * block chain. We could rewrite to handle arbitrary message block chains but
23994  * that would make the code complicated and slow. Right now there three
23995  * restrictions:
23996  *
23997  *   1. The first message block must contain the complete IP header and
23998  *	at least 1 byte of payload data.
23999  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
24000  *	so that we can use a single Multidata message.
24001  *   3. No frag must be distributed over two or more message blocks so
24002  *	that we don't need more than two packet descriptors per frag.
24003  *
24004  * The above restrictions allow us to support userland applications (which
24005  * will send down a single message block) and NFS over UDP (which will
24006  * send down a chain of at most three message blocks).
24007  *
24008  * We also don't use MDT for payloads with less than or equal to
24009  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24010  */
24011 boolean_t
24012 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24013 {
24014 	int	blocks;
24015 	ssize_t	total, missing, size;
24016 
24017 	ASSERT(mp != NULL);
24018 	ASSERT(hdr_len > 0);
24019 
24020 	size = MBLKL(mp) - hdr_len;
24021 	if (size <= 0)
24022 		return (B_FALSE);
24023 
24024 	/* The first mblk contains the header and some payload. */
24025 	blocks = 1;
24026 	total = size;
24027 	size %= len;
24028 	missing = (size == 0) ? 0 : (len - size);
24029 	mp = mp->b_cont;
24030 
24031 	while (mp != NULL) {
24032 		/*
24033 		 * Give up if we encounter a zero length message block.
24034 		 * In practice, this should rarely happen and therefore
24035 		 * not worth the trouble of freeing and re-linking the
24036 		 * mblk from the chain to handle such case.
24037 		 */
24038 		if ((size = MBLKL(mp)) == 0)
24039 			return (B_FALSE);
24040 
24041 		/* Too many payload buffers for a single Multidata message? */
24042 		if (++blocks > MULTIDATA_MAX_PBUFS)
24043 			return (B_FALSE);
24044 
24045 		total += size;
24046 		/* Is a frag distributed over two or more message blocks? */
24047 		if (missing > size)
24048 			return (B_FALSE);
24049 		size -= missing;
24050 
24051 		size %= len;
24052 		missing = (size == 0) ? 0 : (len - size);
24053 
24054 		mp = mp->b_cont;
24055 	}
24056 
24057 	return (total > ip_wput_frag_mdt_min);
24058 }
24059 
24060 /*
24061  * Outbound IPv4 fragmentation routine using MDT.
24062  */
24063 static void
24064 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24065     uint32_t frag_flag, int offset)
24066 {
24067 	ipha_t		*ipha_orig;
24068 	int		i1, ip_data_end;
24069 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24070 	mblk_t		*hdr_mp, *md_mp = NULL;
24071 	unsigned char	*hdr_ptr, *pld_ptr;
24072 	multidata_t	*mmd;
24073 	ip_pdescinfo_t	pdi;
24074 	ill_t		*ill;
24075 	ip_stack_t	*ipst = ire->ire_ipst;
24076 
24077 	ASSERT(DB_TYPE(mp) == M_DATA);
24078 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24079 
24080 	ill = ire_to_ill(ire);
24081 	ASSERT(ill != NULL);
24082 
24083 	ipha_orig = (ipha_t *)mp->b_rptr;
24084 	mp->b_rptr += sizeof (ipha_t);
24085 
24086 	/* Calculate how many packets we will send out */
24087 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24088 	pkts = (i1 + len - 1) / len;
24089 	ASSERT(pkts > 1);
24090 
24091 	/* Allocate a message block which will hold all the IP Headers. */
24092 	wroff = ipst->ips_ip_wroff_extra;
24093 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24094 
24095 	i1 = pkts * hdr_chunk_len;
24096 	/*
24097 	 * Create the header buffer, Multidata and destination address
24098 	 * and SAP attribute that should be associated with it.
24099 	 */
24100 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24101 	    ((hdr_mp->b_wptr += i1),
24102 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24103 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24104 		freemsg(mp);
24105 		if (md_mp == NULL) {
24106 			freemsg(hdr_mp);
24107 		} else {
24108 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24109 			freemsg(md_mp);
24110 		}
24111 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24112 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24113 		return;
24114 	}
24115 	IP_STAT(ipst, ip_frag_mdt_allocd);
24116 
24117 	/*
24118 	 * Add a payload buffer to the Multidata; this operation must not
24119 	 * fail, or otherwise our logic in this routine is broken.  There
24120 	 * is no memory allocation done by the routine, so any returned
24121 	 * failure simply tells us that we've done something wrong.
24122 	 *
24123 	 * A failure tells us that either we're adding the same payload
24124 	 * buffer more than once, or we're trying to add more buffers than
24125 	 * allowed.  None of the above cases should happen, and we panic
24126 	 * because either there's horrible heap corruption, and/or
24127 	 * programming mistake.
24128 	 */
24129 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24130 		goto pbuf_panic;
24131 
24132 	hdr_ptr = hdr_mp->b_rptr;
24133 	pld_ptr = mp->b_rptr;
24134 
24135 	/* Establish the ending byte offset, based on the starting offset. */
24136 	offset <<= 3;
24137 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24138 	    IP_SIMPLE_HDR_LENGTH;
24139 
24140 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24141 
24142 	while (pld_ptr < mp->b_wptr) {
24143 		ipha_t		*ipha;
24144 		uint16_t	offset_and_flags;
24145 		uint16_t	ip_len;
24146 		int		error;
24147 
24148 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24149 		ipha = (ipha_t *)(hdr_ptr + wroff);
24150 		ASSERT(OK_32PTR(ipha));
24151 		*ipha = *ipha_orig;
24152 
24153 		if (ip_data_end - offset > len) {
24154 			offset_and_flags = IPH_MF;
24155 		} else {
24156 			/*
24157 			 * Last frag. Set len to the length of this last piece.
24158 			 */
24159 			len = ip_data_end - offset;
24160 			/* A frag of a frag might have IPH_MF non-zero */
24161 			offset_and_flags =
24162 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24163 			    IPH_MF;
24164 		}
24165 		offset_and_flags |= (uint16_t)(offset >> 3);
24166 		offset_and_flags |= (uint16_t)frag_flag;
24167 		/* Store the offset and flags in the IP header. */
24168 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24169 
24170 		/* Store the length in the IP header. */
24171 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24172 		ipha->ipha_length = htons(ip_len);
24173 
24174 		/*
24175 		 * Set the IP header checksum.  Note that mp is just
24176 		 * the header, so this is easy to pass to ip_csum.
24177 		 */
24178 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24179 
24180 		/*
24181 		 * Record offset and size of header and data of the next packet
24182 		 * in the multidata message.
24183 		 */
24184 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24185 		PDESC_PLD_INIT(&pdi);
24186 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24187 		ASSERT(i1 > 0);
24188 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24189 		if (i1 == len) {
24190 			pld_ptr += len;
24191 		} else {
24192 			i1 = len - i1;
24193 			mp = mp->b_cont;
24194 			ASSERT(mp != NULL);
24195 			ASSERT(MBLKL(mp) >= i1);
24196 			/*
24197 			 * Attach the next payload message block to the
24198 			 * multidata message.
24199 			 */
24200 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24201 				goto pbuf_panic;
24202 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24203 			pld_ptr = mp->b_rptr + i1;
24204 		}
24205 
24206 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24207 		    KM_NOSLEEP)) == NULL) {
24208 			/*
24209 			 * Any failure other than ENOMEM indicates that we
24210 			 * have passed in invalid pdesc info or parameters
24211 			 * to mmd_addpdesc, which must not happen.
24212 			 *
24213 			 * EINVAL is a result of failure on boundary checks
24214 			 * against the pdesc info contents.  It should not
24215 			 * happen, and we panic because either there's
24216 			 * horrible heap corruption, and/or programming
24217 			 * mistake.
24218 			 */
24219 			if (error != ENOMEM) {
24220 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24221 				    "pdesc logic error detected for "
24222 				    "mmd %p pinfo %p (%d)\n",
24223 				    (void *)mmd, (void *)&pdi, error);
24224 				/* NOTREACHED */
24225 			}
24226 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24227 			/* Free unattached payload message blocks as well */
24228 			md_mp->b_cont = mp->b_cont;
24229 			goto free_mmd;
24230 		}
24231 
24232 		/* Advance fragment offset. */
24233 		offset += len;
24234 
24235 		/* Advance to location for next header in the buffer. */
24236 		hdr_ptr += hdr_chunk_len;
24237 
24238 		/* Did we reach the next payload message block? */
24239 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24240 			mp = mp->b_cont;
24241 			/*
24242 			 * Attach the next message block with payload
24243 			 * data to the multidata message.
24244 			 */
24245 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24246 				goto pbuf_panic;
24247 			pld_ptr = mp->b_rptr;
24248 		}
24249 	}
24250 
24251 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24252 	ASSERT(mp->b_wptr == pld_ptr);
24253 
24254 	/* Update IP statistics */
24255 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24256 
24257 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24258 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24259 
24260 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24261 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24262 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24263 
24264 	if (pkt_type == OB_PKT) {
24265 		ire->ire_ob_pkt_count += pkts;
24266 		if (ire->ire_ipif != NULL)
24267 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24268 	} else {
24269 		/*
24270 		 * The type is IB_PKT in the forwarding path and in
24271 		 * the mobile IP case when the packet is being reverse-
24272 		 * tunneled to the home agent.
24273 		 */
24274 		ire->ire_ib_pkt_count += pkts;
24275 		ASSERT(!IRE_IS_LOCAL(ire));
24276 		if (ire->ire_type & IRE_BROADCAST) {
24277 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24278 		} else {
24279 			UPDATE_MIB(ill->ill_ip_mib,
24280 			    ipIfStatsHCOutForwDatagrams, pkts);
24281 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24282 		}
24283 	}
24284 	ire->ire_last_used_time = lbolt;
24285 	/* Send it down */
24286 	putnext(ire->ire_stq, md_mp);
24287 	return;
24288 
24289 pbuf_panic:
24290 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24291 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24292 	    pbuf_idx);
24293 	/* NOTREACHED */
24294 }
24295 
24296 /*
24297  * Outbound IP fragmentation routine.
24298  *
24299  * NOTE : This routine does not ire_refrele the ire that is passed in
24300  * as the argument.
24301  */
24302 static void
24303 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24304     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24305 {
24306 	int		i1;
24307 	mblk_t		*ll_hdr_mp;
24308 	int 		ll_hdr_len;
24309 	int		hdr_len;
24310 	mblk_t		*hdr_mp;
24311 	ipha_t		*ipha;
24312 	int		ip_data_end;
24313 	int		len;
24314 	mblk_t		*mp = mp_orig, *mp1;
24315 	int		offset;
24316 	queue_t		*q;
24317 	uint32_t	v_hlen_tos_len;
24318 	mblk_t		*first_mp;
24319 	boolean_t	mctl_present;
24320 	ill_t		*ill;
24321 	ill_t		*out_ill;
24322 	mblk_t		*xmit_mp;
24323 	mblk_t		*carve_mp;
24324 	ire_t		*ire1 = NULL;
24325 	ire_t		*save_ire = NULL;
24326 	mblk_t  	*next_mp = NULL;
24327 	boolean_t	last_frag = B_FALSE;
24328 	boolean_t	multirt_send = B_FALSE;
24329 	ire_t		*first_ire = NULL;
24330 	irb_t		*irb = NULL;
24331 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24332 
24333 	ill = ire_to_ill(ire);
24334 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24335 
24336 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24337 
24338 	/*
24339 	 * IPSEC does not allow hw accelerated packets to be fragmented
24340 	 * This check is made in ip_wput_ipsec_out prior to coming here
24341 	 * via ip_wput_ire_fragmentit.
24342 	 *
24343 	 * If at this point we have an ire whose ARP request has not
24344 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24345 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24346 	 * This packet and all fragmentable packets for this ire will
24347 	 * continue to get dropped while ire_nce->nce_state remains in
24348 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24349 	 * ND_REACHABLE, all subsquent large packets for this ire will
24350 	 * get fragemented and sent out by this function.
24351 	 */
24352 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24353 		/* If nce_state is ND_INITIAL, trigger ARP query */
24354 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24355 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24356 		    " -  dropping packet\n"));
24357 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24358 		freemsg(mp);
24359 		return;
24360 	}
24361 
24362 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24363 	    "ip_wput_frag_start:");
24364 
24365 	if (mp->b_datap->db_type == M_CTL) {
24366 		first_mp = mp;
24367 		mp_orig = mp = mp->b_cont;
24368 		mctl_present = B_TRUE;
24369 	} else {
24370 		first_mp = mp;
24371 		mctl_present = B_FALSE;
24372 	}
24373 
24374 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24375 	ipha = (ipha_t *)mp->b_rptr;
24376 
24377 	/*
24378 	 * If the Don't Fragment flag is on, generate an ICMP destination
24379 	 * unreachable, fragmentation needed.
24380 	 */
24381 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24382 	if (offset & IPH_DF) {
24383 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24384 		/*
24385 		 * Need to compute hdr checksum if called from ip_wput_ire.
24386 		 * Note that ip_rput_forward verifies the checksum before
24387 		 * calling this routine so in that case this is a noop.
24388 		 */
24389 		ipha->ipha_hdr_checksum = 0;
24390 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24391 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24392 		    ipst);
24393 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24394 		    "ip_wput_frag_end:(%S)",
24395 		    "don't fragment");
24396 		return;
24397 	}
24398 	if (mctl_present)
24399 		freeb(first_mp);
24400 	/*
24401 	 * Establish the starting offset.  May not be zero if we are fragging
24402 	 * a fragment that is being forwarded.
24403 	 */
24404 	offset = offset & IPH_OFFSET;
24405 
24406 	/* TODO why is this test needed? */
24407 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24408 	if (((max_frag - LENGTH) & ~7) < 8) {
24409 		/* TODO: notify ulp somehow */
24410 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24411 		freemsg(mp);
24412 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24413 		    "ip_wput_frag_end:(%S)",
24414 		    "len < 8");
24415 		return;
24416 	}
24417 
24418 	hdr_len = (V_HLEN & 0xF) << 2;
24419 
24420 	ipha->ipha_hdr_checksum = 0;
24421 
24422 	/*
24423 	 * Establish the number of bytes maximum per frag, after putting
24424 	 * in the header.
24425 	 */
24426 	len = (max_frag - hdr_len) & ~7;
24427 
24428 	/* Check if we can use MDT to send out the frags. */
24429 	ASSERT(!IRE_IS_LOCAL(ire));
24430 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24431 	    ipst->ips_ip_multidata_outbound &&
24432 	    !(ire->ire_flags & RTF_MULTIRT) &&
24433 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24434 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24435 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24436 		ASSERT(ill->ill_mdt_capab != NULL);
24437 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24438 			/*
24439 			 * If MDT has been previously turned off in the past,
24440 			 * and we currently can do MDT (due to IPQoS policy
24441 			 * removal, etc.) then enable it for this interface.
24442 			 */
24443 			ill->ill_mdt_capab->ill_mdt_on = 1;
24444 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24445 			    ill->ill_name));
24446 		}
24447 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24448 		    offset);
24449 		return;
24450 	}
24451 
24452 	/* Get a copy of the header for the trailing frags */
24453 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24454 	if (!hdr_mp) {
24455 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24456 		freemsg(mp);
24457 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24458 		    "ip_wput_frag_end:(%S)",
24459 		    "couldn't copy hdr");
24460 		return;
24461 	}
24462 	if (DB_CRED(mp) != NULL)
24463 		mblk_setcred(hdr_mp, DB_CRED(mp));
24464 
24465 	/* Store the starting offset, with the MoreFrags flag. */
24466 	i1 = offset | IPH_MF | frag_flag;
24467 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24468 
24469 	/* Establish the ending byte offset, based on the starting offset. */
24470 	offset <<= 3;
24471 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24472 
24473 	/* Store the length of the first fragment in the IP header. */
24474 	i1 = len + hdr_len;
24475 	ASSERT(i1 <= IP_MAXPACKET);
24476 	ipha->ipha_length = htons((uint16_t)i1);
24477 
24478 	/*
24479 	 * Compute the IP header checksum for the first frag.  We have to
24480 	 * watch out that we stop at the end of the header.
24481 	 */
24482 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24483 
24484 	/*
24485 	 * Now carve off the first frag.  Note that this will include the
24486 	 * original IP header.
24487 	 */
24488 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24489 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24490 		freeb(hdr_mp);
24491 		freemsg(mp_orig);
24492 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24493 		    "ip_wput_frag_end:(%S)",
24494 		    "couldn't carve first");
24495 		return;
24496 	}
24497 
24498 	/*
24499 	 * Multirouting case. Each fragment is replicated
24500 	 * via all non-condemned RTF_MULTIRT routes
24501 	 * currently resolved.
24502 	 * We ensure that first_ire is the first RTF_MULTIRT
24503 	 * ire in the bucket.
24504 	 */
24505 	if (ire->ire_flags & RTF_MULTIRT) {
24506 		irb = ire->ire_bucket;
24507 		ASSERT(irb != NULL);
24508 
24509 		multirt_send = B_TRUE;
24510 
24511 		/* Make sure we do not omit any multiroute ire. */
24512 		IRB_REFHOLD(irb);
24513 		for (first_ire = irb->irb_ire;
24514 		    first_ire != NULL;
24515 		    first_ire = first_ire->ire_next) {
24516 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24517 			    (first_ire->ire_addr == ire->ire_addr) &&
24518 			    !(first_ire->ire_marks &
24519 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24520 				break;
24521 		}
24522 
24523 		if (first_ire != NULL) {
24524 			if (first_ire != ire) {
24525 				IRE_REFHOLD(first_ire);
24526 				/*
24527 				 * Do not release the ire passed in
24528 				 * as the argument.
24529 				 */
24530 				ire = first_ire;
24531 			} else {
24532 				first_ire = NULL;
24533 			}
24534 		}
24535 		IRB_REFRELE(irb);
24536 
24537 		/*
24538 		 * Save the first ire; we will need to restore it
24539 		 * for the trailing frags.
24540 		 * We REFHOLD save_ire, as each iterated ire will be
24541 		 * REFRELEd.
24542 		 */
24543 		save_ire = ire;
24544 		IRE_REFHOLD(save_ire);
24545 	}
24546 
24547 	/*
24548 	 * First fragment emission loop.
24549 	 * In most cases, the emission loop below is entered only
24550 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24551 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24552 	 * bucket, and send the fragment through all crossed
24553 	 * RTF_MULTIRT routes.
24554 	 */
24555 	do {
24556 		if (ire->ire_flags & RTF_MULTIRT) {
24557 			/*
24558 			 * We are in a multiple send case, need to get
24559 			 * the next ire and make a copy of the packet.
24560 			 * ire1 holds here the next ire to process in the
24561 			 * bucket. If multirouting is expected,
24562 			 * any non-RTF_MULTIRT ire that has the
24563 			 * right destination address is ignored.
24564 			 *
24565 			 * We have to take into account the MTU of
24566 			 * each walked ire. max_frag is set by the
24567 			 * the caller and generally refers to
24568 			 * the primary ire entry. Here we ensure that
24569 			 * no route with a lower MTU will be used, as
24570 			 * fragments are carved once for all ires,
24571 			 * then replicated.
24572 			 */
24573 			ASSERT(irb != NULL);
24574 			IRB_REFHOLD(irb);
24575 			for (ire1 = ire->ire_next;
24576 			    ire1 != NULL;
24577 			    ire1 = ire1->ire_next) {
24578 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24579 					continue;
24580 				if (ire1->ire_addr != ire->ire_addr)
24581 					continue;
24582 				if (ire1->ire_marks &
24583 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24584 					continue;
24585 				/*
24586 				 * Ensure we do not exceed the MTU
24587 				 * of the next route.
24588 				 */
24589 				if (ire1->ire_max_frag < max_frag) {
24590 					ip_multirt_bad_mtu(ire1, max_frag);
24591 					continue;
24592 				}
24593 
24594 				/* Got one. */
24595 				IRE_REFHOLD(ire1);
24596 				break;
24597 			}
24598 			IRB_REFRELE(irb);
24599 
24600 			if (ire1 != NULL) {
24601 				next_mp = copyb(mp);
24602 				if ((next_mp == NULL) ||
24603 				    ((mp->b_cont != NULL) &&
24604 				    ((next_mp->b_cont =
24605 				    dupmsg(mp->b_cont)) == NULL))) {
24606 					freemsg(next_mp);
24607 					next_mp = NULL;
24608 					ire_refrele(ire1);
24609 					ire1 = NULL;
24610 				}
24611 			}
24612 
24613 			/* Last multiroute ire; don't loop anymore. */
24614 			if (ire1 == NULL) {
24615 				multirt_send = B_FALSE;
24616 			}
24617 		}
24618 
24619 		ll_hdr_len = 0;
24620 		LOCK_IRE_FP_MP(ire);
24621 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24622 		if (ll_hdr_mp != NULL) {
24623 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24624 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24625 		} else {
24626 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24627 		}
24628 
24629 		/* If there is a transmit header, get a copy for this frag. */
24630 		/*
24631 		 * TODO: should check db_ref before calling ip_carve_mp since
24632 		 * it might give us a dup.
24633 		 */
24634 		if (!ll_hdr_mp) {
24635 			/* No xmit header. */
24636 			xmit_mp = mp;
24637 
24638 		/* We have a link-layer header that can fit in our mblk. */
24639 		} else if (mp->b_datap->db_ref == 1 &&
24640 		    ll_hdr_len != 0 &&
24641 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24642 			/* M_DATA fastpath */
24643 			mp->b_rptr -= ll_hdr_len;
24644 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24645 			xmit_mp = mp;
24646 
24647 		/* Corner case if copyb has failed */
24648 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24649 			UNLOCK_IRE_FP_MP(ire);
24650 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24651 			freeb(hdr_mp);
24652 			freemsg(mp);
24653 			freemsg(mp_orig);
24654 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24655 			    "ip_wput_frag_end:(%S)",
24656 			    "discard");
24657 
24658 			if (multirt_send) {
24659 				ASSERT(ire1);
24660 				ASSERT(next_mp);
24661 
24662 				freemsg(next_mp);
24663 				ire_refrele(ire1);
24664 			}
24665 			if (save_ire != NULL)
24666 				IRE_REFRELE(save_ire);
24667 
24668 			if (first_ire != NULL)
24669 				ire_refrele(first_ire);
24670 			return;
24671 
24672 		/*
24673 		 * Case of res_mp OR the fastpath mp can't fit
24674 		 * in the mblk
24675 		 */
24676 		} else {
24677 			xmit_mp->b_cont = mp;
24678 			if (DB_CRED(mp) != NULL)
24679 				mblk_setcred(xmit_mp, DB_CRED(mp));
24680 			/*
24681 			 * Get priority marking, if any.
24682 			 * We propagate the CoS marking from the
24683 			 * original packet that went to QoS processing
24684 			 * in ip_wput_ire to the newly carved mp.
24685 			 */
24686 			if (DB_TYPE(xmit_mp) == M_DATA)
24687 				xmit_mp->b_band = mp->b_band;
24688 		}
24689 		UNLOCK_IRE_FP_MP(ire);
24690 
24691 		q = ire->ire_stq;
24692 		out_ill = (ill_t *)q->q_ptr;
24693 
24694 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24695 
24696 		DTRACE_PROBE4(ip4__physical__out__start,
24697 		    ill_t *, NULL, ill_t *, out_ill,
24698 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24699 
24700 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24701 		    ipst->ips_ipv4firewall_physical_out,
24702 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24703 
24704 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24705 
24706 		if (xmit_mp != NULL) {
24707 			putnext(q, xmit_mp);
24708 
24709 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24710 			UPDATE_MIB(out_ill->ill_ip_mib,
24711 			    ipIfStatsHCOutOctets, i1);
24712 
24713 			if (pkt_type != OB_PKT) {
24714 				/*
24715 				 * Update the packet count and MIB stats
24716 				 * of trailing RTF_MULTIRT ires.
24717 				 */
24718 				UPDATE_OB_PKT_COUNT(ire);
24719 				BUMP_MIB(out_ill->ill_ip_mib,
24720 				    ipIfStatsOutFragReqds);
24721 			}
24722 		}
24723 
24724 		if (multirt_send) {
24725 			/*
24726 			 * We are in a multiple send case; look for
24727 			 * the next ire and re-enter the loop.
24728 			 */
24729 			ASSERT(ire1);
24730 			ASSERT(next_mp);
24731 			/* REFRELE the current ire before looping */
24732 			ire_refrele(ire);
24733 			ire = ire1;
24734 			ire1 = NULL;
24735 			mp = next_mp;
24736 			next_mp = NULL;
24737 		}
24738 	} while (multirt_send);
24739 
24740 	ASSERT(ire1 == NULL);
24741 
24742 	/* Restore the original ire; we need it for the trailing frags */
24743 	if (save_ire != NULL) {
24744 		/* REFRELE the last iterated ire */
24745 		ire_refrele(ire);
24746 		/* save_ire has been REFHOLDed */
24747 		ire = save_ire;
24748 		save_ire = NULL;
24749 		q = ire->ire_stq;
24750 	}
24751 
24752 	if (pkt_type == OB_PKT) {
24753 		UPDATE_OB_PKT_COUNT(ire);
24754 	} else {
24755 		out_ill = (ill_t *)q->q_ptr;
24756 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24757 		UPDATE_IB_PKT_COUNT(ire);
24758 	}
24759 
24760 	/* Advance the offset to the second frag starting point. */
24761 	offset += len;
24762 	/*
24763 	 * Update hdr_len from the copied header - there might be less options
24764 	 * in the later fragments.
24765 	 */
24766 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24767 	/* Loop until done. */
24768 	for (;;) {
24769 		uint16_t	offset_and_flags;
24770 		uint16_t	ip_len;
24771 
24772 		if (ip_data_end - offset > len) {
24773 			/*
24774 			 * Carve off the appropriate amount from the original
24775 			 * datagram.
24776 			 */
24777 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24778 				mp = NULL;
24779 				break;
24780 			}
24781 			/*
24782 			 * More frags after this one.  Get another copy
24783 			 * of the header.
24784 			 */
24785 			if (carve_mp->b_datap->db_ref == 1 &&
24786 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24787 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24788 				/* Inline IP header */
24789 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24790 				    hdr_mp->b_rptr;
24791 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24792 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24793 				mp = carve_mp;
24794 			} else {
24795 				if (!(mp = copyb(hdr_mp))) {
24796 					freemsg(carve_mp);
24797 					break;
24798 				}
24799 				/* Get priority marking, if any. */
24800 				mp->b_band = carve_mp->b_band;
24801 				mp->b_cont = carve_mp;
24802 			}
24803 			ipha = (ipha_t *)mp->b_rptr;
24804 			offset_and_flags = IPH_MF;
24805 		} else {
24806 			/*
24807 			 * Last frag.  Consume the header. Set len to
24808 			 * the length of this last piece.
24809 			 */
24810 			len = ip_data_end - offset;
24811 
24812 			/*
24813 			 * Carve off the appropriate amount from the original
24814 			 * datagram.
24815 			 */
24816 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24817 				mp = NULL;
24818 				break;
24819 			}
24820 			if (carve_mp->b_datap->db_ref == 1 &&
24821 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24822 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24823 				/* Inline IP header */
24824 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24825 				    hdr_mp->b_rptr;
24826 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24827 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24828 				mp = carve_mp;
24829 				freeb(hdr_mp);
24830 				hdr_mp = mp;
24831 			} else {
24832 				mp = hdr_mp;
24833 				/* Get priority marking, if any. */
24834 				mp->b_band = carve_mp->b_band;
24835 				mp->b_cont = carve_mp;
24836 			}
24837 			ipha = (ipha_t *)mp->b_rptr;
24838 			/* A frag of a frag might have IPH_MF non-zero */
24839 			offset_and_flags =
24840 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24841 			    IPH_MF;
24842 		}
24843 		offset_and_flags |= (uint16_t)(offset >> 3);
24844 		offset_and_flags |= (uint16_t)frag_flag;
24845 		/* Store the offset and flags in the IP header. */
24846 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24847 
24848 		/* Store the length in the IP header. */
24849 		ip_len = (uint16_t)(len + hdr_len);
24850 		ipha->ipha_length = htons(ip_len);
24851 
24852 		/*
24853 		 * Set the IP header checksum.	Note that mp is just
24854 		 * the header, so this is easy to pass to ip_csum.
24855 		 */
24856 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24857 
24858 		/* Attach a transmit header, if any, and ship it. */
24859 		if (pkt_type == OB_PKT) {
24860 			UPDATE_OB_PKT_COUNT(ire);
24861 		} else {
24862 			out_ill = (ill_t *)q->q_ptr;
24863 			BUMP_MIB(out_ill->ill_ip_mib,
24864 			    ipIfStatsHCOutForwDatagrams);
24865 			UPDATE_IB_PKT_COUNT(ire);
24866 		}
24867 
24868 		if (ire->ire_flags & RTF_MULTIRT) {
24869 			irb = ire->ire_bucket;
24870 			ASSERT(irb != NULL);
24871 
24872 			multirt_send = B_TRUE;
24873 
24874 			/*
24875 			 * Save the original ire; we will need to restore it
24876 			 * for the tailing frags.
24877 			 */
24878 			save_ire = ire;
24879 			IRE_REFHOLD(save_ire);
24880 		}
24881 		/*
24882 		 * Emission loop for this fragment, similar
24883 		 * to what is done for the first fragment.
24884 		 */
24885 		do {
24886 			if (multirt_send) {
24887 				/*
24888 				 * We are in a multiple send case, need to get
24889 				 * the next ire and make a copy of the packet.
24890 				 */
24891 				ASSERT(irb != NULL);
24892 				IRB_REFHOLD(irb);
24893 				for (ire1 = ire->ire_next;
24894 				    ire1 != NULL;
24895 				    ire1 = ire1->ire_next) {
24896 					if (!(ire1->ire_flags & RTF_MULTIRT))
24897 						continue;
24898 					if (ire1->ire_addr != ire->ire_addr)
24899 						continue;
24900 					if (ire1->ire_marks &
24901 					    (IRE_MARK_CONDEMNED|
24902 						IRE_MARK_HIDDEN))
24903 						continue;
24904 					/*
24905 					 * Ensure we do not exceed the MTU
24906 					 * of the next route.
24907 					 */
24908 					if (ire1->ire_max_frag < max_frag) {
24909 						ip_multirt_bad_mtu(ire1,
24910 						    max_frag);
24911 						continue;
24912 					}
24913 
24914 					/* Got one. */
24915 					IRE_REFHOLD(ire1);
24916 					break;
24917 				}
24918 				IRB_REFRELE(irb);
24919 
24920 				if (ire1 != NULL) {
24921 					next_mp = copyb(mp);
24922 					if ((next_mp == NULL) ||
24923 					    ((mp->b_cont != NULL) &&
24924 					    ((next_mp->b_cont =
24925 					    dupmsg(mp->b_cont)) == NULL))) {
24926 						freemsg(next_mp);
24927 						next_mp = NULL;
24928 						ire_refrele(ire1);
24929 						ire1 = NULL;
24930 					}
24931 				}
24932 
24933 				/* Last multiroute ire; don't loop anymore. */
24934 				if (ire1 == NULL) {
24935 					multirt_send = B_FALSE;
24936 				}
24937 			}
24938 
24939 			/* Update transmit header */
24940 			ll_hdr_len = 0;
24941 			LOCK_IRE_FP_MP(ire);
24942 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24943 			if (ll_hdr_mp != NULL) {
24944 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24945 				ll_hdr_len = MBLKL(ll_hdr_mp);
24946 			} else {
24947 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24948 			}
24949 
24950 			if (!ll_hdr_mp) {
24951 				xmit_mp = mp;
24952 
24953 			/*
24954 			 * We have link-layer header that can fit in
24955 			 * our mblk.
24956 			 */
24957 			} else if (mp->b_datap->db_ref == 1 &&
24958 			    ll_hdr_len != 0 &&
24959 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24960 				/* M_DATA fastpath */
24961 				mp->b_rptr -= ll_hdr_len;
24962 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24963 				    ll_hdr_len);
24964 				xmit_mp = mp;
24965 
24966 			/*
24967 			 * Case of res_mp OR the fastpath mp can't fit
24968 			 * in the mblk
24969 			 */
24970 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24971 				xmit_mp->b_cont = mp;
24972 				if (DB_CRED(mp) != NULL)
24973 					mblk_setcred(xmit_mp, DB_CRED(mp));
24974 				/* Get priority marking, if any. */
24975 				if (DB_TYPE(xmit_mp) == M_DATA)
24976 					xmit_mp->b_band = mp->b_band;
24977 
24978 			/* Corner case if copyb failed */
24979 			} else {
24980 				/*
24981 				 * Exit both the replication and
24982 				 * fragmentation loops.
24983 				 */
24984 				UNLOCK_IRE_FP_MP(ire);
24985 				goto drop_pkt;
24986 			}
24987 			UNLOCK_IRE_FP_MP(ire);
24988 
24989 			mp1 = mp;
24990 			out_ill = (ill_t *)q->q_ptr;
24991 
24992 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24993 
24994 			DTRACE_PROBE4(ip4__physical__out__start,
24995 			    ill_t *, NULL, ill_t *, out_ill,
24996 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24997 
24998 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24999 			    ipst->ips_ipv4firewall_physical_out,
25000 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25001 
25002 			DTRACE_PROBE1(ip4__physical__out__end,
25003 			    mblk_t *, xmit_mp);
25004 
25005 			if (mp != mp1 && hdr_mp == mp1)
25006 				hdr_mp = mp;
25007 			if (mp != mp1 && mp_orig == mp1)
25008 				mp_orig = mp;
25009 
25010 			if (xmit_mp != NULL) {
25011 				putnext(q, xmit_mp);
25012 
25013 				BUMP_MIB(out_ill->ill_ip_mib,
25014 				    ipIfStatsHCOutTransmits);
25015 				UPDATE_MIB(out_ill->ill_ip_mib,
25016 				    ipIfStatsHCOutOctets, ip_len);
25017 
25018 				if (pkt_type != OB_PKT) {
25019 					/*
25020 					 * Update the packet count of trailing
25021 					 * RTF_MULTIRT ires.
25022 					 */
25023 					UPDATE_OB_PKT_COUNT(ire);
25024 				}
25025 			}
25026 
25027 			/* All done if we just consumed the hdr_mp. */
25028 			if (mp == hdr_mp) {
25029 				last_frag = B_TRUE;
25030 				BUMP_MIB(out_ill->ill_ip_mib,
25031 				    ipIfStatsOutFragOKs);
25032 			}
25033 
25034 			if (multirt_send) {
25035 				/*
25036 				 * We are in a multiple send case; look for
25037 				 * the next ire and re-enter the loop.
25038 				 */
25039 				ASSERT(ire1);
25040 				ASSERT(next_mp);
25041 				/* REFRELE the current ire before looping */
25042 				ire_refrele(ire);
25043 				ire = ire1;
25044 				ire1 = NULL;
25045 				q = ire->ire_stq;
25046 				mp = next_mp;
25047 				next_mp = NULL;
25048 			}
25049 		} while (multirt_send);
25050 		/*
25051 		 * Restore the original ire; we need it for the
25052 		 * trailing frags
25053 		 */
25054 		if (save_ire != NULL) {
25055 			ASSERT(ire1 == NULL);
25056 			/* REFRELE the last iterated ire */
25057 			ire_refrele(ire);
25058 			/* save_ire has been REFHOLDed */
25059 			ire = save_ire;
25060 			q = ire->ire_stq;
25061 			save_ire = NULL;
25062 		}
25063 
25064 		if (last_frag) {
25065 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25066 			    "ip_wput_frag_end:(%S)",
25067 			    "consumed hdr_mp");
25068 
25069 			if (first_ire != NULL)
25070 				ire_refrele(first_ire);
25071 			return;
25072 		}
25073 		/* Otherwise, advance and loop. */
25074 		offset += len;
25075 	}
25076 
25077 drop_pkt:
25078 	/* Clean up following allocation failure. */
25079 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25080 	freemsg(mp);
25081 	if (mp != hdr_mp)
25082 		freeb(hdr_mp);
25083 	if (mp != mp_orig)
25084 		freemsg(mp_orig);
25085 
25086 	if (save_ire != NULL)
25087 		IRE_REFRELE(save_ire);
25088 	if (first_ire != NULL)
25089 		ire_refrele(first_ire);
25090 
25091 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25092 	    "ip_wput_frag_end:(%S)",
25093 	    "end--alloc failure");
25094 }
25095 
25096 /*
25097  * Copy the header plus those options which have the copy bit set
25098  */
25099 static mblk_t *
25100 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25101 {
25102 	mblk_t	*mp;
25103 	uchar_t	*up;
25104 
25105 	/*
25106 	 * Quick check if we need to look for options without the copy bit
25107 	 * set
25108 	 */
25109 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25110 	if (!mp)
25111 		return (mp);
25112 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25113 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25114 		bcopy(rptr, mp->b_rptr, hdr_len);
25115 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25116 		return (mp);
25117 	}
25118 	up  = mp->b_rptr;
25119 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25120 	up += IP_SIMPLE_HDR_LENGTH;
25121 	rptr += IP_SIMPLE_HDR_LENGTH;
25122 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25123 	while (hdr_len > 0) {
25124 		uint32_t optval;
25125 		uint32_t optlen;
25126 
25127 		optval = *rptr;
25128 		if (optval == IPOPT_EOL)
25129 			break;
25130 		if (optval == IPOPT_NOP)
25131 			optlen = 1;
25132 		else
25133 			optlen = rptr[1];
25134 		if (optval & IPOPT_COPY) {
25135 			bcopy(rptr, up, optlen);
25136 			up += optlen;
25137 		}
25138 		rptr += optlen;
25139 		hdr_len -= optlen;
25140 	}
25141 	/*
25142 	 * Make sure that we drop an even number of words by filling
25143 	 * with EOL to the next word boundary.
25144 	 */
25145 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25146 	    hdr_len & 0x3; hdr_len++)
25147 		*up++ = IPOPT_EOL;
25148 	mp->b_wptr = up;
25149 	/* Update header length */
25150 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25151 	return (mp);
25152 }
25153 
25154 /*
25155  * Delivery to local recipients including fanout to multiple recipients.
25156  * Does not do checksumming of UDP/TCP.
25157  * Note: q should be the read side queue for either the ill or conn.
25158  * Note: rq should be the read side q for the lower (ill) stream.
25159  * We don't send packets to IPPF processing, thus the last argument
25160  * to all the fanout calls are B_FALSE.
25161  */
25162 void
25163 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25164     int fanout_flags, zoneid_t zoneid)
25165 {
25166 	uint32_t	protocol;
25167 	mblk_t		*first_mp;
25168 	boolean_t	mctl_present;
25169 	int		ire_type;
25170 #define	rptr	((uchar_t *)ipha)
25171 	ip_stack_t	*ipst = ill->ill_ipst;
25172 
25173 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25174 	    "ip_wput_local_start: q %p", q);
25175 
25176 	if (ire != NULL) {
25177 		ire_type = ire->ire_type;
25178 	} else {
25179 		/*
25180 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25181 		 * packet is not multicast, we can't tell the ire type.
25182 		 */
25183 		ASSERT(CLASSD(ipha->ipha_dst));
25184 		ire_type = IRE_BROADCAST;
25185 	}
25186 
25187 	first_mp = mp;
25188 	if (first_mp->b_datap->db_type == M_CTL) {
25189 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25190 		if (!io->ipsec_out_secure) {
25191 			/*
25192 			 * This ipsec_out_t was allocated in ip_wput
25193 			 * for multicast packets to store the ill_index.
25194 			 * As this is being delivered locally, we don't
25195 			 * need this anymore.
25196 			 */
25197 			mp = first_mp->b_cont;
25198 			freeb(first_mp);
25199 			first_mp = mp;
25200 			mctl_present = B_FALSE;
25201 		} else {
25202 			/*
25203 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25204 			 * security properties for the looped-back packet.
25205 			 */
25206 			mctl_present = B_TRUE;
25207 			mp = first_mp->b_cont;
25208 			ASSERT(mp != NULL);
25209 			ipsec_out_to_in(first_mp);
25210 		}
25211 	} else {
25212 		mctl_present = B_FALSE;
25213 	}
25214 
25215 	DTRACE_PROBE4(ip4__loopback__in__start,
25216 	    ill_t *, ill, ill_t *, NULL,
25217 	    ipha_t *, ipha, mblk_t *, first_mp);
25218 
25219 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25220 	    ipst->ips_ipv4firewall_loopback_in,
25221 	    ill, NULL, ipha, first_mp, mp, ipst);
25222 
25223 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25224 
25225 	if (first_mp == NULL)
25226 		return;
25227 
25228 	ipst->ips_loopback_packets++;
25229 
25230 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25231 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25232 	if (!IS_SIMPLE_IPH(ipha)) {
25233 		ip_wput_local_options(ipha, ipst);
25234 	}
25235 
25236 	protocol = ipha->ipha_protocol;
25237 	switch (protocol) {
25238 	case IPPROTO_ICMP: {
25239 		ire_t		*ire_zone;
25240 		ilm_t		*ilm;
25241 		mblk_t		*mp1;
25242 		zoneid_t	last_zoneid;
25243 
25244 		if (CLASSD(ipha->ipha_dst) &&
25245 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
25246 			ASSERT(ire_type == IRE_BROADCAST);
25247 			/*
25248 			 * In the multicast case, applications may have joined
25249 			 * the group from different zones, so we need to deliver
25250 			 * the packet to each of them. Loop through the
25251 			 * multicast memberships structures (ilm) on the receive
25252 			 * ill and send a copy of the packet up each matching
25253 			 * one. However, we don't do this for multicasts sent on
25254 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25255 			 * they must stay in the sender's zone.
25256 			 *
25257 			 * ilm_add_v6() ensures that ilms in the same zone are
25258 			 * contiguous in the ill_ilm list. We use this property
25259 			 * to avoid sending duplicates needed when two
25260 			 * applications in the same zone join the same group on
25261 			 * different logical interfaces: we ignore the ilm if
25262 			 * it's zoneid is the same as the last matching one.
25263 			 * In addition, the sending of the packet for
25264 			 * ire_zoneid is delayed until all of the other ilms
25265 			 * have been exhausted.
25266 			 */
25267 			last_zoneid = -1;
25268 			ILM_WALKER_HOLD(ill);
25269 			for (ilm = ill->ill_ilm; ilm != NULL;
25270 			    ilm = ilm->ilm_next) {
25271 				if ((ilm->ilm_flags & ILM_DELETED) ||
25272 				    ipha->ipha_dst != ilm->ilm_addr ||
25273 				    ilm->ilm_zoneid == last_zoneid ||
25274 				    ilm->ilm_zoneid == zoneid ||
25275 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25276 					continue;
25277 				mp1 = ip_copymsg(first_mp);
25278 				if (mp1 == NULL)
25279 					continue;
25280 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25281 				    mctl_present, B_FALSE, ill,
25282 				    ilm->ilm_zoneid);
25283 				last_zoneid = ilm->ilm_zoneid;
25284 			}
25285 			ILM_WALKER_RELE(ill);
25286 			/*
25287 			 * Loopback case: the sending endpoint has
25288 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25289 			 * dispatch the multicast packet to the sending zone.
25290 			 */
25291 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25292 				freemsg(first_mp);
25293 				return;
25294 			}
25295 		} else if (ire_type == IRE_BROADCAST) {
25296 			/*
25297 			 * In the broadcast case, there may be many zones
25298 			 * which need a copy of the packet delivered to them.
25299 			 * There is one IRE_BROADCAST per broadcast address
25300 			 * and per zone; we walk those using a helper function.
25301 			 * In addition, the sending of the packet for zoneid is
25302 			 * delayed until all of the other ires have been
25303 			 * processed.
25304 			 */
25305 			IRB_REFHOLD(ire->ire_bucket);
25306 			ire_zone = NULL;
25307 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25308 			    ire)) != NULL) {
25309 				mp1 = ip_copymsg(first_mp);
25310 				if (mp1 == NULL)
25311 					continue;
25312 
25313 				UPDATE_IB_PKT_COUNT(ire_zone);
25314 				ire_zone->ire_last_used_time = lbolt;
25315 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25316 				    mctl_present, B_FALSE, ill,
25317 				    ire_zone->ire_zoneid);
25318 			}
25319 			IRB_REFRELE(ire->ire_bucket);
25320 		}
25321 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25322 		    0, mctl_present, B_FALSE, ill, zoneid);
25323 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25324 		    "ip_wput_local_end: q %p (%S)",
25325 		    q, "icmp");
25326 		return;
25327 	}
25328 	case IPPROTO_IGMP:
25329 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25330 			/* Bad packet - discarded by igmp_input */
25331 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25332 			    "ip_wput_local_end: q %p (%S)",
25333 			    q, "igmp_input--bad packet");
25334 			if (mctl_present)
25335 				freeb(first_mp);
25336 			return;
25337 		}
25338 		/*
25339 		 * igmp_input() may have returned the pulled up message.
25340 		 * So first_mp and ipha need to be reinitialized.
25341 		 */
25342 		ipha = (ipha_t *)mp->b_rptr;
25343 		if (mctl_present)
25344 			first_mp->b_cont = mp;
25345 		else
25346 			first_mp = mp;
25347 		/* deliver to local raw users */
25348 		break;
25349 	case IPPROTO_ENCAP:
25350 		/*
25351 		 * This case is covered by either ip_fanout_proto, or by
25352 		 * the above security processing for self-tunneled packets.
25353 		 */
25354 		break;
25355 	case IPPROTO_UDP: {
25356 		uint16_t	*up;
25357 		uint32_t	ports;
25358 
25359 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25360 		    UDP_PORTS_OFFSET);
25361 		/* Force a 'valid' checksum. */
25362 		up[3] = 0;
25363 
25364 		ports = *(uint32_t *)up;
25365 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25366 		    (ire_type == IRE_BROADCAST),
25367 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25368 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25369 		    ill, zoneid);
25370 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25371 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25372 		return;
25373 	}
25374 	case IPPROTO_TCP: {
25375 
25376 		/*
25377 		 * For TCP, discard broadcast packets.
25378 		 */
25379 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25380 			freemsg(first_mp);
25381 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25382 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25383 			return;
25384 		}
25385 
25386 		if (mp->b_datap->db_type == M_DATA) {
25387 			/*
25388 			 * M_DATA mblk, so init mblk (chain) for no struio().
25389 			 */
25390 			mblk_t	*mp1 = mp;
25391 
25392 			do
25393 				mp1->b_datap->db_struioflag = 0;
25394 			while ((mp1 = mp1->b_cont) != NULL);
25395 		}
25396 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25397 		    <= mp->b_wptr);
25398 		ip_fanout_tcp(q, first_mp, ill, ipha,
25399 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25400 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25401 		    mctl_present, B_FALSE, zoneid);
25402 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25403 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25404 		return;
25405 	}
25406 	case IPPROTO_SCTP:
25407 	{
25408 		uint32_t	ports;
25409 
25410 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25411 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25412 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25413 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25414 		return;
25415 	}
25416 
25417 	default:
25418 		break;
25419 	}
25420 	/*
25421 	 * Find a client for some other protocol.  We give
25422 	 * copies to multiple clients, if more than one is
25423 	 * bound.
25424 	 */
25425 	ip_fanout_proto(q, first_mp, ill, ipha,
25426 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25427 	    mctl_present, B_FALSE, ill, zoneid);
25428 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25429 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25430 #undef	rptr
25431 }
25432 
25433 /*
25434  * Update any source route, record route, or timestamp options.
25435  * Check that we are at end of strict source route.
25436  * The options have been sanity checked by ip_wput_options().
25437  */
25438 static void
25439 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25440 {
25441 	ipoptp_t	opts;
25442 	uchar_t		*opt;
25443 	uint8_t		optval;
25444 	uint8_t		optlen;
25445 	ipaddr_t	dst;
25446 	uint32_t	ts;
25447 	ire_t		*ire;
25448 	timestruc_t	now;
25449 
25450 	ip2dbg(("ip_wput_local_options\n"));
25451 	for (optval = ipoptp_first(&opts, ipha);
25452 	    optval != IPOPT_EOL;
25453 	    optval = ipoptp_next(&opts)) {
25454 		opt = opts.ipoptp_cur;
25455 		optlen = opts.ipoptp_len;
25456 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25457 		switch (optval) {
25458 			uint32_t off;
25459 		case IPOPT_SSRR:
25460 		case IPOPT_LSRR:
25461 			off = opt[IPOPT_OFFSET];
25462 			off--;
25463 			if (optlen < IP_ADDR_LEN ||
25464 			    off > optlen - IP_ADDR_LEN) {
25465 				/* End of source route */
25466 				break;
25467 			}
25468 			/*
25469 			 * This will only happen if two consecutive entries
25470 			 * in the source route contains our address or if
25471 			 * it is a packet with a loose source route which
25472 			 * reaches us before consuming the whole source route
25473 			 */
25474 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25475 			if (optval == IPOPT_SSRR) {
25476 				return;
25477 			}
25478 			/*
25479 			 * Hack: instead of dropping the packet truncate the
25480 			 * source route to what has been used by filling the
25481 			 * rest with IPOPT_NOP.
25482 			 */
25483 			opt[IPOPT_OLEN] = (uint8_t)off;
25484 			while (off < optlen) {
25485 				opt[off++] = IPOPT_NOP;
25486 			}
25487 			break;
25488 		case IPOPT_RR:
25489 			off = opt[IPOPT_OFFSET];
25490 			off--;
25491 			if (optlen < IP_ADDR_LEN ||
25492 			    off > optlen - IP_ADDR_LEN) {
25493 				/* No more room - ignore */
25494 				ip1dbg((
25495 				    "ip_wput_forward_options: end of RR\n"));
25496 				break;
25497 			}
25498 			dst = htonl(INADDR_LOOPBACK);
25499 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25500 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25501 			break;
25502 		case IPOPT_TS:
25503 			/* Insert timestamp if there is romm */
25504 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25505 			case IPOPT_TS_TSONLY:
25506 				off = IPOPT_TS_TIMELEN;
25507 				break;
25508 			case IPOPT_TS_PRESPEC:
25509 			case IPOPT_TS_PRESPEC_RFC791:
25510 				/* Verify that the address matched */
25511 				off = opt[IPOPT_OFFSET] - 1;
25512 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25513 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25514 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25515 				    ipst);
25516 				if (ire == NULL) {
25517 					/* Not for us */
25518 					break;
25519 				}
25520 				ire_refrele(ire);
25521 				/* FALLTHRU */
25522 			case IPOPT_TS_TSANDADDR:
25523 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25524 				break;
25525 			default:
25526 				/*
25527 				 * ip_*put_options should have already
25528 				 * dropped this packet.
25529 				 */
25530 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25531 				    "unknown IT - bug in ip_wput_options?\n");
25532 				return;	/* Keep "lint" happy */
25533 			}
25534 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25535 				/* Increase overflow counter */
25536 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25537 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25538 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25539 				    (off << 4);
25540 				break;
25541 			}
25542 			off = opt[IPOPT_OFFSET] - 1;
25543 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25544 			case IPOPT_TS_PRESPEC:
25545 			case IPOPT_TS_PRESPEC_RFC791:
25546 			case IPOPT_TS_TSANDADDR:
25547 				dst = htonl(INADDR_LOOPBACK);
25548 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25549 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25550 				/* FALLTHRU */
25551 			case IPOPT_TS_TSONLY:
25552 				off = opt[IPOPT_OFFSET] - 1;
25553 				/* Compute # of milliseconds since midnight */
25554 				gethrestime(&now);
25555 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25556 				    now.tv_nsec / (NANOSEC / MILLISEC);
25557 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25558 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25559 				break;
25560 			}
25561 			break;
25562 		}
25563 	}
25564 }
25565 
25566 /*
25567  * Send out a multicast packet on interface ipif.
25568  * The sender does not have an conn.
25569  * Caller verifies that this isn't a PHYI_LOOPBACK.
25570  */
25571 void
25572 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25573 {
25574 	ipha_t	*ipha;
25575 	ire_t	*ire;
25576 	ipaddr_t	dst;
25577 	mblk_t		*first_mp;
25578 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25579 
25580 	/* igmp_sendpkt always allocates a ipsec_out_t */
25581 	ASSERT(mp->b_datap->db_type == M_CTL);
25582 	ASSERT(!ipif->ipif_isv6);
25583 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
25584 
25585 	first_mp = mp;
25586 	mp = first_mp->b_cont;
25587 	ASSERT(mp->b_datap->db_type == M_DATA);
25588 	ipha = (ipha_t *)mp->b_rptr;
25589 
25590 	/*
25591 	 * Find an IRE which matches the destination and the outgoing
25592 	 * queue (i.e. the outgoing interface.)
25593 	 */
25594 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25595 		dst = ipif->ipif_pp_dst_addr;
25596 	else
25597 		dst = ipha->ipha_dst;
25598 	/*
25599 	 * The source address has already been initialized by the
25600 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25601 	 * be sufficient rather than MATCH_IRE_IPIF.
25602 	 *
25603 	 * This function is used for sending IGMP packets. We need
25604 	 * to make sure that we send the packet out of the interface
25605 	 * (ipif->ipif_ill) where we joined the group. This is to
25606 	 * prevent from switches doing IGMP snooping to send us multicast
25607 	 * packets for a given group on the interface we have joined.
25608 	 * If we can't find an ire, igmp_sendpkt has already initialized
25609 	 * ipsec_out_attach_if so that this will not be load spread in
25610 	 * ip_newroute_ipif.
25611 	 */
25612 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25613 	    MATCH_IRE_ILL, ipst);
25614 	if (!ire) {
25615 		/*
25616 		 * Mark this packet to make it be delivered to
25617 		 * ip_wput_ire after the new ire has been
25618 		 * created.
25619 		 */
25620 		mp->b_prev = NULL;
25621 		mp->b_next = NULL;
25622 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25623 		    zoneid, &zero_info);
25624 		return;
25625 	}
25626 
25627 	/*
25628 	 * Honor the RTF_SETSRC flag; this is the only case
25629 	 * where we force this addr whatever the current src addr is,
25630 	 * because this address is set by igmp_sendpkt(), and
25631 	 * cannot be specified by any user.
25632 	 */
25633 	if (ire->ire_flags & RTF_SETSRC) {
25634 		ipha->ipha_src = ire->ire_src_addr;
25635 	}
25636 
25637 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25638 }
25639 
25640 /*
25641  * NOTE : This function does not ire_refrele the ire argument passed in.
25642  *
25643  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25644  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25645  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25646  * the ire_lock to access the nce_fp_mp in this case.
25647  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25648  * prepending a fastpath message IPQoS processing must precede it, we also set
25649  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25650  * (IPQoS might have set the b_band for CoS marking).
25651  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25652  * must follow it so that IPQoS can mark the dl_priority field for CoS
25653  * marking, if needed.
25654  */
25655 static mblk_t *
25656 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25657 {
25658 	uint_t	hlen;
25659 	ipha_t *ipha;
25660 	mblk_t *mp1;
25661 	boolean_t qos_done = B_FALSE;
25662 	uchar_t	*ll_hdr;
25663 	ip_stack_t	*ipst = ire->ire_ipst;
25664 
25665 #define	rptr	((uchar_t *)ipha)
25666 
25667 	ipha = (ipha_t *)mp->b_rptr;
25668 	hlen = 0;
25669 	LOCK_IRE_FP_MP(ire);
25670 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25671 		ASSERT(DB_TYPE(mp1) == M_DATA);
25672 		/* Initiate IPPF processing */
25673 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25674 			UNLOCK_IRE_FP_MP(ire);
25675 			ip_process(proc, &mp, ill_index);
25676 			if (mp == NULL)
25677 				return (NULL);
25678 
25679 			ipha = (ipha_t *)mp->b_rptr;
25680 			LOCK_IRE_FP_MP(ire);
25681 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25682 				qos_done = B_TRUE;
25683 				goto no_fp_mp;
25684 			}
25685 			ASSERT(DB_TYPE(mp1) == M_DATA);
25686 		}
25687 		hlen = MBLKL(mp1);
25688 		/*
25689 		 * Check if we have enough room to prepend fastpath
25690 		 * header
25691 		 */
25692 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25693 			ll_hdr = rptr - hlen;
25694 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25695 			/*
25696 			 * Set the b_rptr to the start of the link layer
25697 			 * header
25698 			 */
25699 			mp->b_rptr = ll_hdr;
25700 			mp1 = mp;
25701 		} else {
25702 			mp1 = copyb(mp1);
25703 			if (mp1 == NULL)
25704 				goto unlock_err;
25705 			mp1->b_band = mp->b_band;
25706 			mp1->b_cont = mp;
25707 			/*
25708 			 * certain system generated traffic may not
25709 			 * have cred/label in ip header block. This
25710 			 * is true even for a labeled system. But for
25711 			 * labeled traffic, inherit the label in the
25712 			 * new header.
25713 			 */
25714 			if (DB_CRED(mp) != NULL)
25715 				mblk_setcred(mp1, DB_CRED(mp));
25716 			/*
25717 			 * XXX disable ICK_VALID and compute checksum
25718 			 * here; can happen if nce_fp_mp changes and
25719 			 * it can't be copied now due to insufficient
25720 			 * space. (unlikely, fp mp can change, but it
25721 			 * does not increase in length)
25722 			 */
25723 		}
25724 		UNLOCK_IRE_FP_MP(ire);
25725 	} else {
25726 no_fp_mp:
25727 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25728 		if (mp1 == NULL) {
25729 unlock_err:
25730 			UNLOCK_IRE_FP_MP(ire);
25731 			freemsg(mp);
25732 			return (NULL);
25733 		}
25734 		UNLOCK_IRE_FP_MP(ire);
25735 		mp1->b_cont = mp;
25736 		/*
25737 		 * certain system generated traffic may not
25738 		 * have cred/label in ip header block. This
25739 		 * is true even for a labeled system. But for
25740 		 * labeled traffic, inherit the label in the
25741 		 * new header.
25742 		 */
25743 		if (DB_CRED(mp) != NULL)
25744 			mblk_setcred(mp1, DB_CRED(mp));
25745 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25746 			ip_process(proc, &mp1, ill_index);
25747 			if (mp1 == NULL)
25748 				return (NULL);
25749 		}
25750 	}
25751 	return (mp1);
25752 #undef rptr
25753 }
25754 
25755 /*
25756  * Finish the outbound IPsec processing for an IPv6 packet. This function
25757  * is called from ipsec_out_process() if the IPsec packet was processed
25758  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25759  * asynchronously.
25760  */
25761 void
25762 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25763     ire_t *ire_arg)
25764 {
25765 	in6_addr_t *v6dstp;
25766 	ire_t *ire;
25767 	mblk_t *mp;
25768 	ip6_t *ip6h1;
25769 	uint_t	ill_index;
25770 	ipsec_out_t *io;
25771 	boolean_t attach_if, hwaccel;
25772 	uint32_t flags = IP6_NO_IPPOLICY;
25773 	int match_flags;
25774 	zoneid_t zoneid;
25775 	boolean_t ill_need_rele = B_FALSE;
25776 	boolean_t ire_need_rele = B_FALSE;
25777 	ip_stack_t	*ipst;
25778 
25779 	mp = ipsec_mp->b_cont;
25780 	ip6h1 = (ip6_t *)mp->b_rptr;
25781 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25782 	ASSERT(io->ipsec_out_ns != NULL);
25783 	ipst = io->ipsec_out_ns->netstack_ip;
25784 	ill_index = io->ipsec_out_ill_index;
25785 	if (io->ipsec_out_reachable) {
25786 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25787 	}
25788 	attach_if = io->ipsec_out_attach_if;
25789 	hwaccel = io->ipsec_out_accelerated;
25790 	zoneid = io->ipsec_out_zoneid;
25791 	ASSERT(zoneid != ALL_ZONES);
25792 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25793 	/* Multicast addresses should have non-zero ill_index. */
25794 	v6dstp = &ip6h->ip6_dst;
25795 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25796 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25797 	ASSERT(!attach_if || ill_index != 0);
25798 	if (ill_index != 0) {
25799 		if (ill == NULL) {
25800 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25801 			    B_TRUE, ipst);
25802 
25803 			/* Failure case frees things for us. */
25804 			if (ill == NULL)
25805 				return;
25806 
25807 			ill_need_rele = B_TRUE;
25808 		}
25809 		/*
25810 		 * If this packet needs to go out on a particular interface
25811 		 * honor it.
25812 		 */
25813 		if (attach_if) {
25814 			match_flags = MATCH_IRE_ILL;
25815 
25816 			/*
25817 			 * Check if we need an ire that will not be
25818 			 * looked up by anybody else i.e. HIDDEN.
25819 			 */
25820 			if (ill_is_probeonly(ill)) {
25821 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25822 			}
25823 		}
25824 	}
25825 	ASSERT(mp != NULL);
25826 
25827 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25828 		boolean_t unspec_src;
25829 		ipif_t	*ipif;
25830 
25831 		/*
25832 		 * Use the ill_index to get the right ill.
25833 		 */
25834 		unspec_src = io->ipsec_out_unspec_src;
25835 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25836 		if (ipif == NULL) {
25837 			if (ill_need_rele)
25838 				ill_refrele(ill);
25839 			freemsg(ipsec_mp);
25840 			return;
25841 		}
25842 
25843 		if (ire_arg != NULL) {
25844 			ire = ire_arg;
25845 		} else {
25846 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25847 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25848 			ire_need_rele = B_TRUE;
25849 		}
25850 		if (ire != NULL) {
25851 			ipif_refrele(ipif);
25852 			/*
25853 			 * XXX Do the multicast forwarding now, as the IPSEC
25854 			 * processing has been done.
25855 			 */
25856 			goto send;
25857 		}
25858 
25859 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25860 		mp->b_prev = NULL;
25861 		mp->b_next = NULL;
25862 
25863 		/*
25864 		 * If the IPsec packet was processed asynchronously,
25865 		 * drop it now.
25866 		 */
25867 		if (q == NULL) {
25868 			if (ill_need_rele)
25869 				ill_refrele(ill);
25870 			freemsg(ipsec_mp);
25871 			return;
25872 		}
25873 
25874 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25875 		    unspec_src, zoneid);
25876 		ipif_refrele(ipif);
25877 	} else {
25878 		if (attach_if) {
25879 			ipif_t	*ipif;
25880 
25881 			ipif = ipif_get_next_ipif(NULL, ill);
25882 			if (ipif == NULL) {
25883 				if (ill_need_rele)
25884 					ill_refrele(ill);
25885 				freemsg(ipsec_mp);
25886 				return;
25887 			}
25888 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25889 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25890 			ire_need_rele = B_TRUE;
25891 			ipif_refrele(ipif);
25892 		} else {
25893 			if (ire_arg != NULL) {
25894 				ire = ire_arg;
25895 			} else {
25896 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25897 				    ipst);
25898 				ire_need_rele = B_TRUE;
25899 			}
25900 		}
25901 		if (ire != NULL)
25902 			goto send;
25903 		/*
25904 		 * ire disappeared underneath.
25905 		 *
25906 		 * What we need to do here is the ip_newroute
25907 		 * logic to get the ire without doing the IPSEC
25908 		 * processing. Follow the same old path. But this
25909 		 * time, ip_wput or ire_add_then_send will call us
25910 		 * directly as all the IPSEC operations are done.
25911 		 */
25912 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25913 		mp->b_prev = NULL;
25914 		mp->b_next = NULL;
25915 
25916 		/*
25917 		 * If the IPsec packet was processed asynchronously,
25918 		 * drop it now.
25919 		 */
25920 		if (q == NULL) {
25921 			if (ill_need_rele)
25922 				ill_refrele(ill);
25923 			freemsg(ipsec_mp);
25924 			return;
25925 		}
25926 
25927 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25928 		    zoneid, ipst);
25929 	}
25930 	if (ill != NULL && ill_need_rele)
25931 		ill_refrele(ill);
25932 	return;
25933 send:
25934 	if (ill != NULL && ill_need_rele)
25935 		ill_refrele(ill);
25936 
25937 	/* Local delivery */
25938 	if (ire->ire_stq == NULL) {
25939 		ill_t	*out_ill;
25940 		ASSERT(q != NULL);
25941 
25942 		/* PFHooks: LOOPBACK_OUT */
25943 		out_ill = ire->ire_ipif->ipif_ill;
25944 
25945 		DTRACE_PROBE4(ip6__loopback__out__start,
25946 		    ill_t *, NULL, ill_t *, out_ill,
25947 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25948 
25949 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25950 		    ipst->ips_ipv6firewall_loopback_out,
25951 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25952 
25953 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25954 
25955 		if (ipsec_mp != NULL)
25956 			ip_wput_local_v6(RD(q), out_ill,
25957 			    ip6h, ipsec_mp, ire, 0);
25958 		if (ire_need_rele)
25959 			ire_refrele(ire);
25960 		return;
25961 	}
25962 	/*
25963 	 * Everything is done. Send it out on the wire.
25964 	 * We force the insertion of a fragment header using the
25965 	 * IPH_FRAG_HDR flag in two cases:
25966 	 * - after reception of an ICMPv6 "packet too big" message
25967 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25968 	 * - for multirouted IPv6 packets, so that the receiver can
25969 	 *   discard duplicates according to their fragment identifier
25970 	 */
25971 	/* XXX fix flow control problems. */
25972 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25973 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25974 		if (hwaccel) {
25975 			/*
25976 			 * hardware acceleration does not handle these
25977 			 * "slow path" cases.
25978 			 */
25979 			/* IPsec KSTATS: should bump bean counter here. */
25980 			if (ire_need_rele)
25981 				ire_refrele(ire);
25982 			freemsg(ipsec_mp);
25983 			return;
25984 		}
25985 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25986 		    (mp->b_cont ? msgdsize(mp) :
25987 		    mp->b_wptr - (uchar_t *)ip6h)) {
25988 			/* IPsec KSTATS: should bump bean counter here. */
25989 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25990 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25991 			    msgdsize(mp)));
25992 			if (ire_need_rele)
25993 				ire_refrele(ire);
25994 			freemsg(ipsec_mp);
25995 			return;
25996 		}
25997 		ASSERT(mp->b_prev == NULL);
25998 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25999 		    ntohs(ip6h->ip6_plen) +
26000 		    IPV6_HDR_LEN, ire->ire_max_frag));
26001 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26002 		    ire->ire_max_frag);
26003 	} else {
26004 		UPDATE_OB_PKT_COUNT(ire);
26005 		ire->ire_last_used_time = lbolt;
26006 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26007 	}
26008 	if (ire_need_rele)
26009 		ire_refrele(ire);
26010 	freeb(ipsec_mp);
26011 }
26012 
26013 void
26014 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26015 {
26016 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26017 	da_ipsec_t *hada;	/* data attributes */
26018 	ill_t *ill = (ill_t *)q->q_ptr;
26019 
26020 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26021 
26022 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26023 		/* IPsec KSTATS: Bump lose counter here! */
26024 		freemsg(mp);
26025 		return;
26026 	}
26027 
26028 	/*
26029 	 * It's an IPsec packet that must be
26030 	 * accelerated by the Provider, and the
26031 	 * outbound ill is IPsec acceleration capable.
26032 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26033 	 * to the ill.
26034 	 * IPsec KSTATS: should bump packet counter here.
26035 	 */
26036 
26037 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26038 	if (hada_mp == NULL) {
26039 		/* IPsec KSTATS: should bump packet counter here. */
26040 		freemsg(mp);
26041 		return;
26042 	}
26043 
26044 	hada_mp->b_datap->db_type = M_CTL;
26045 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26046 	hada_mp->b_cont = mp;
26047 
26048 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26049 	bzero(hada, sizeof (da_ipsec_t));
26050 	hada->da_type = IPHADA_M_CTL;
26051 
26052 	putnext(q, hada_mp);
26053 }
26054 
26055 /*
26056  * Finish the outbound IPsec processing. This function is called from
26057  * ipsec_out_process() if the IPsec packet was processed
26058  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26059  * asynchronously.
26060  */
26061 void
26062 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26063     ire_t *ire_arg)
26064 {
26065 	uint32_t v_hlen_tos_len;
26066 	ipaddr_t	dst;
26067 	ipif_t	*ipif = NULL;
26068 	ire_t *ire;
26069 	ire_t *ire1 = NULL;
26070 	mblk_t *next_mp = NULL;
26071 	uint32_t max_frag;
26072 	boolean_t multirt_send = B_FALSE;
26073 	mblk_t *mp;
26074 	mblk_t *mp1;
26075 	ipha_t *ipha1;
26076 	uint_t	ill_index;
26077 	ipsec_out_t *io;
26078 	boolean_t attach_if;
26079 	int match_flags, offset;
26080 	irb_t *irb = NULL;
26081 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26082 	zoneid_t zoneid;
26083 	uint32_t cksum;
26084 	uint16_t *up;
26085 	ipxmit_state_t	pktxmit_state;
26086 	ip_stack_t	*ipst;
26087 
26088 #ifdef	_BIG_ENDIAN
26089 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26090 #else
26091 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26092 #endif
26093 
26094 	mp = ipsec_mp->b_cont;
26095 	ipha1 = (ipha_t *)mp->b_rptr;
26096 	ASSERT(mp != NULL);
26097 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26098 	dst = ipha->ipha_dst;
26099 
26100 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26101 	ill_index = io->ipsec_out_ill_index;
26102 	attach_if = io->ipsec_out_attach_if;
26103 	zoneid = io->ipsec_out_zoneid;
26104 	ASSERT(zoneid != ALL_ZONES);
26105 	ipst = io->ipsec_out_ns->netstack_ip;
26106 	ASSERT(io->ipsec_out_ns != NULL);
26107 
26108 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26109 	if (ill_index != 0) {
26110 		if (ill == NULL) {
26111 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26112 			    ill_index, B_FALSE, ipst);
26113 
26114 			/* Failure case frees things for us. */
26115 			if (ill == NULL)
26116 				return;
26117 
26118 			ill_need_rele = B_TRUE;
26119 		}
26120 		/*
26121 		 * If this packet needs to go out on a particular interface
26122 		 * honor it.
26123 		 */
26124 		if (attach_if) {
26125 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26126 
26127 			/*
26128 			 * Check if we need an ire that will not be
26129 			 * looked up by anybody else i.e. HIDDEN.
26130 			 */
26131 			if (ill_is_probeonly(ill)) {
26132 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26133 			}
26134 		}
26135 	}
26136 
26137 	if (CLASSD(dst)) {
26138 		boolean_t conn_dontroute;
26139 		/*
26140 		 * Use the ill_index to get the right ipif.
26141 		 */
26142 		conn_dontroute = io->ipsec_out_dontroute;
26143 		if (ill_index == 0)
26144 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26145 		else
26146 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26147 		if (ipif == NULL) {
26148 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26149 			    " multicast\n"));
26150 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26151 			freemsg(ipsec_mp);
26152 			goto done;
26153 		}
26154 		/*
26155 		 * ipha_src has already been intialized with the
26156 		 * value of the ipif in ip_wput. All we need now is
26157 		 * an ire to send this downstream.
26158 		 */
26159 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26160 		    MBLK_GETLABEL(mp), match_flags, ipst);
26161 		if (ire != NULL) {
26162 			ill_t *ill1;
26163 			/*
26164 			 * Do the multicast forwarding now, as the IPSEC
26165 			 * processing has been done.
26166 			 */
26167 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26168 			    (ill1 = ire_to_ill(ire))) {
26169 				if (ip_mforward(ill1, ipha, mp)) {
26170 					freemsg(ipsec_mp);
26171 					ip1dbg(("ip_wput_ipsec_out: mforward "
26172 					    "failed\n"));
26173 					ire_refrele(ire);
26174 					goto done;
26175 				}
26176 			}
26177 			goto send;
26178 		}
26179 
26180 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26181 		mp->b_prev = NULL;
26182 		mp->b_next = NULL;
26183 
26184 		/*
26185 		 * If the IPsec packet was processed asynchronously,
26186 		 * drop it now.
26187 		 */
26188 		if (q == NULL) {
26189 			freemsg(ipsec_mp);
26190 			goto done;
26191 		}
26192 
26193 		/*
26194 		 * We may be using a wrong ipif to create the ire.
26195 		 * But it is okay as the source address is assigned
26196 		 * for the packet already. Next outbound packet would
26197 		 * create the IRE with the right IPIF in ip_wput.
26198 		 *
26199 		 * Also handle RTF_MULTIRT routes.
26200 		 */
26201 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26202 		    zoneid, &zero_info);
26203 	} else {
26204 		if (attach_if) {
26205 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26206 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26207 		} else {
26208 			if (ire_arg != NULL) {
26209 				ire = ire_arg;
26210 				ire_need_rele = B_FALSE;
26211 			} else {
26212 				ire = ire_cache_lookup(dst, zoneid,
26213 				    MBLK_GETLABEL(mp), ipst);
26214 			}
26215 		}
26216 		if (ire != NULL) {
26217 			goto send;
26218 		}
26219 
26220 		/*
26221 		 * ire disappeared underneath.
26222 		 *
26223 		 * What we need to do here is the ip_newroute
26224 		 * logic to get the ire without doing the IPSEC
26225 		 * processing. Follow the same old path. But this
26226 		 * time, ip_wput or ire_add_then_put will call us
26227 		 * directly as all the IPSEC operations are done.
26228 		 */
26229 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26230 		mp->b_prev = NULL;
26231 		mp->b_next = NULL;
26232 
26233 		/*
26234 		 * If the IPsec packet was processed asynchronously,
26235 		 * drop it now.
26236 		 */
26237 		if (q == NULL) {
26238 			freemsg(ipsec_mp);
26239 			goto done;
26240 		}
26241 
26242 		/*
26243 		 * Since we're going through ip_newroute() again, we
26244 		 * need to make sure we don't:
26245 		 *
26246 		 *	1.) Trigger the ASSERT() with the ipha_ident
26247 		 *	    overloading.
26248 		 *	2.) Redo transport-layer checksumming, since we've
26249 		 *	    already done all that to get this far.
26250 		 *
26251 		 * The easiest way not do either of the above is to set
26252 		 * the ipha_ident field to IP_HDR_INCLUDED.
26253 		 */
26254 		ipha->ipha_ident = IP_HDR_INCLUDED;
26255 		ip_newroute(q, ipsec_mp, dst, NULL,
26256 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26257 	}
26258 	goto done;
26259 send:
26260 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26261 	    udp_compute_checksum(ipst->ips_netstack)) {
26262 		/*
26263 		 * ESP NAT-Traversal packet.
26264 		 *
26265 		 * Just do software checksum for now.
26266 		 */
26267 
26268 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26269 		IP_STAT(ipst, ip_out_sw_cksum);
26270 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26271 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26272 #define	iphs	((uint16_t *)ipha)
26273 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26274 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26275 		    IP_SIMPLE_HDR_LENGTH);
26276 #undef iphs
26277 		cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum);
26278 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26279 			if (mp1->b_wptr - mp1->b_rptr >=
26280 			    offset + sizeof (uint16_t)) {
26281 				up = (uint16_t *)(mp1->b_rptr + offset);
26282 				*up = cksum;
26283 				break;	/* out of for loop */
26284 			} else {
26285 				offset -= (mp->b_wptr - mp->b_rptr);
26286 			}
26287 	} /* Otherwise, just keep the all-zero checksum. */
26288 
26289 	if (ire->ire_stq == NULL) {
26290 		ill_t	*out_ill;
26291 		/*
26292 		 * Loopbacks go through ip_wput_local except for one case.
26293 		 * We come here if we generate a icmp_frag_needed message
26294 		 * after IPSEC processing is over. When this function calls
26295 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26296 		 * icmp_frag_needed. The message generated comes back here
26297 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26298 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26299 		 * source address as it is usually set in ip_wput_ire. As
26300 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26301 		 * and we end up here. We can't enter ip_wput_ire once the
26302 		 * IPSEC processing is over and hence we need to do it here.
26303 		 */
26304 		ASSERT(q != NULL);
26305 		UPDATE_OB_PKT_COUNT(ire);
26306 		ire->ire_last_used_time = lbolt;
26307 		if (ipha->ipha_src == 0)
26308 			ipha->ipha_src = ire->ire_src_addr;
26309 
26310 		/* PFHooks: LOOPBACK_OUT */
26311 		out_ill = ire->ire_ipif->ipif_ill;
26312 
26313 		DTRACE_PROBE4(ip4__loopback__out__start,
26314 		    ill_t *, NULL, ill_t *, out_ill,
26315 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26316 
26317 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26318 		    ipst->ips_ipv4firewall_loopback_out,
26319 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26320 
26321 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26322 
26323 		if (ipsec_mp != NULL)
26324 			ip_wput_local(RD(q), out_ill,
26325 			    ipha, ipsec_mp, ire, 0, zoneid);
26326 		if (ire_need_rele)
26327 			ire_refrele(ire);
26328 		goto done;
26329 	}
26330 
26331 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26332 		/*
26333 		 * We are through with IPSEC processing.
26334 		 * Fragment this and send it on the wire.
26335 		 */
26336 		if (io->ipsec_out_accelerated) {
26337 			/*
26338 			 * The packet has been accelerated but must
26339 			 * be fragmented. This should not happen
26340 			 * since AH and ESP must not accelerate
26341 			 * packets that need fragmentation, however
26342 			 * the configuration could have changed
26343 			 * since the AH or ESP processing.
26344 			 * Drop packet.
26345 			 * IPsec KSTATS: bump bean counter here.
26346 			 */
26347 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26348 			    "fragmented accelerated packet!\n"));
26349 			freemsg(ipsec_mp);
26350 		} else {
26351 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26352 		}
26353 		if (ire_need_rele)
26354 			ire_refrele(ire);
26355 		goto done;
26356 	}
26357 
26358 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26359 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26360 	    (void *)ire->ire_ipif, (void *)ipif));
26361 
26362 	/*
26363 	 * Multiroute the secured packet, unless IPsec really
26364 	 * requires the packet to go out only through a particular
26365 	 * interface.
26366 	 */
26367 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26368 		ire_t *first_ire;
26369 		irb = ire->ire_bucket;
26370 		ASSERT(irb != NULL);
26371 		/*
26372 		 * This ire has been looked up as the one that
26373 		 * goes through the given ipif;
26374 		 * make sure we do not omit any other multiroute ire
26375 		 * that may be present in the bucket before this one.
26376 		 */
26377 		IRB_REFHOLD(irb);
26378 		for (first_ire = irb->irb_ire;
26379 		    first_ire != NULL;
26380 		    first_ire = first_ire->ire_next) {
26381 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26382 			    (first_ire->ire_addr == ire->ire_addr) &&
26383 			    !(first_ire->ire_marks &
26384 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
26385 				break;
26386 		}
26387 
26388 		if ((first_ire != NULL) && (first_ire != ire)) {
26389 			/*
26390 			 * Don't change the ire if the packet must
26391 			 * be fragmented if sent via this new one.
26392 			 */
26393 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26394 				IRE_REFHOLD(first_ire);
26395 				if (ire_need_rele)
26396 					ire_refrele(ire);
26397 				else
26398 					ire_need_rele = B_TRUE;
26399 				ire = first_ire;
26400 			}
26401 		}
26402 		IRB_REFRELE(irb);
26403 
26404 		multirt_send = B_TRUE;
26405 		max_frag = ire->ire_max_frag;
26406 	} else {
26407 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26408 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26409 			    "flag, attach_if %d\n", attach_if));
26410 		}
26411 	}
26412 
26413 	/*
26414 	 * In most cases, the emission loop below is entered only once.
26415 	 * Only in the case where the ire holds the RTF_MULTIRT
26416 	 * flag, we loop to process all RTF_MULTIRT ires in the
26417 	 * bucket, and send the packet through all crossed
26418 	 * RTF_MULTIRT routes.
26419 	 */
26420 	do {
26421 		if (multirt_send) {
26422 			/*
26423 			 * ire1 holds here the next ire to process in the
26424 			 * bucket. If multirouting is expected,
26425 			 * any non-RTF_MULTIRT ire that has the
26426 			 * right destination address is ignored.
26427 			 */
26428 			ASSERT(irb != NULL);
26429 			IRB_REFHOLD(irb);
26430 			for (ire1 = ire->ire_next;
26431 			    ire1 != NULL;
26432 			    ire1 = ire1->ire_next) {
26433 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26434 					continue;
26435 				if (ire1->ire_addr != ire->ire_addr)
26436 					continue;
26437 				if (ire1->ire_marks &
26438 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26439 					continue;
26440 				/* No loopback here */
26441 				if (ire1->ire_stq == NULL)
26442 					continue;
26443 				/*
26444 				 * Ensure we do not exceed the MTU
26445 				 * of the next route.
26446 				 */
26447 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26448 					ip_multirt_bad_mtu(ire1, max_frag);
26449 					continue;
26450 				}
26451 
26452 				IRE_REFHOLD(ire1);
26453 				break;
26454 			}
26455 			IRB_REFRELE(irb);
26456 			if (ire1 != NULL) {
26457 				/*
26458 				 * We are in a multiple send case, need to
26459 				 * make a copy of the packet.
26460 				 */
26461 				next_mp = copymsg(ipsec_mp);
26462 				if (next_mp == NULL) {
26463 					ire_refrele(ire1);
26464 					ire1 = NULL;
26465 				}
26466 			}
26467 		}
26468 		/*
26469 		 * Everything is done. Send it out on the wire
26470 		 *
26471 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26472 		 * either send it on the wire or, in the case of
26473 		 * HW acceleration, call ipsec_hw_putnext.
26474 		 */
26475 		if (ire->ire_nce &&
26476 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26477 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26478 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26479 			/*
26480 			 * If ire's link-layer is unresolved (this
26481 			 * would only happen if the incomplete ire
26482 			 * was added to cachetable via forwarding path)
26483 			 * don't bother going to ip_xmit_v4. Just drop the
26484 			 * packet.
26485 			 * There is a slight risk here, in that, if we
26486 			 * have the forwarding path create an incomplete
26487 			 * IRE, then until the IRE is completed, any
26488 			 * transmitted IPSEC packets will be dropped
26489 			 * instead of being queued waiting for resolution.
26490 			 *
26491 			 * But the likelihood of a forwarding packet and a wput
26492 			 * packet sending to the same dst at the same time
26493 			 * and there not yet be an ARP entry for it is small.
26494 			 * Furthermore, if this actually happens, it might
26495 			 * be likely that wput would generate multiple
26496 			 * packets (and forwarding would also have a train
26497 			 * of packets) for that destination. If this is
26498 			 * the case, some of them would have been dropped
26499 			 * anyway, since ARP only queues a few packets while
26500 			 * waiting for resolution
26501 			 *
26502 			 * NOTE: We should really call ip_xmit_v4,
26503 			 * and let it queue the packet and send the
26504 			 * ARP query and have ARP come back thus:
26505 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26506 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26507 			 * hw accel work. But it's too complex to get
26508 			 * the IPsec hw  acceleration approach to fit
26509 			 * well with ip_xmit_v4 doing ARP without
26510 			 * doing IPSEC simplification. For now, we just
26511 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26512 			 * that we can continue with the send on the next
26513 			 * attempt.
26514 			 *
26515 			 * XXX THis should be revisited, when
26516 			 * the IPsec/IP interaction is cleaned up
26517 			 */
26518 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26519 			    " - dropping packet\n"));
26520 			freemsg(ipsec_mp);
26521 			/*
26522 			 * Call ip_xmit_v4() to trigger ARP query
26523 			 * in case the nce_state is ND_INITIAL
26524 			 */
26525 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26526 			goto drop_pkt;
26527 		}
26528 
26529 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26530 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26531 		    mblk_t *, mp);
26532 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26533 		    ipst->ips_ipv4firewall_physical_out,
26534 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp, ipst);
26535 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
26536 		if (mp == NULL)
26537 			goto drop_pkt;
26538 
26539 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26540 		pktxmit_state = ip_xmit_v4(mp, ire,
26541 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26542 
26543 		if ((pktxmit_state ==  SEND_FAILED) ||
26544 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26545 
26546 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26547 drop_pkt:
26548 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26549 			    ipIfStatsOutDiscards);
26550 			if (ire_need_rele)
26551 				ire_refrele(ire);
26552 			if (ire1 != NULL) {
26553 				ire_refrele(ire1);
26554 				freemsg(next_mp);
26555 			}
26556 			goto done;
26557 		}
26558 
26559 		freeb(ipsec_mp);
26560 		if (ire_need_rele)
26561 			ire_refrele(ire);
26562 
26563 		if (ire1 != NULL) {
26564 			ire = ire1;
26565 			ire_need_rele = B_TRUE;
26566 			ASSERT(next_mp);
26567 			ipsec_mp = next_mp;
26568 			mp = ipsec_mp->b_cont;
26569 			ire1 = NULL;
26570 			next_mp = NULL;
26571 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26572 		} else {
26573 			multirt_send = B_FALSE;
26574 		}
26575 	} while (multirt_send);
26576 done:
26577 	if (ill != NULL && ill_need_rele)
26578 		ill_refrele(ill);
26579 	if (ipif != NULL)
26580 		ipif_refrele(ipif);
26581 }
26582 
26583 /*
26584  * Get the ill corresponding to the specified ire, and compare its
26585  * capabilities with the protocol and algorithms specified by the
26586  * the SA obtained from ipsec_out. If they match, annotate the
26587  * ipsec_out structure to indicate that the packet needs acceleration.
26588  *
26589  *
26590  * A packet is eligible for outbound hardware acceleration if the
26591  * following conditions are satisfied:
26592  *
26593  * 1. the packet will not be fragmented
26594  * 2. the provider supports the algorithm
26595  * 3. there is no pending control message being exchanged
26596  * 4. snoop is not attached
26597  * 5. the destination address is not a broadcast or multicast address.
26598  *
26599  * Rationale:
26600  *	- Hardware drivers do not support fragmentation with
26601  *	  the current interface.
26602  *	- snoop, multicast, and broadcast may result in exposure of
26603  *	  a cleartext datagram.
26604  * We check all five of these conditions here.
26605  *
26606  * XXX would like to nuke "ire_t *" parameter here; problem is that
26607  * IRE is only way to figure out if a v4 address is a broadcast and
26608  * thus ineligible for acceleration...
26609  */
26610 static void
26611 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26612 {
26613 	ipsec_out_t *io;
26614 	mblk_t *data_mp;
26615 	uint_t plen, overhead;
26616 	ip_stack_t	*ipst;
26617 
26618 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26619 		return;
26620 
26621 	if (ill == NULL)
26622 		return;
26623 	ipst = ill->ill_ipst;
26624 	/*
26625 	 * Destination address is a broadcast or multicast.  Punt.
26626 	 */
26627 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26628 	    IRE_LOCAL)))
26629 		return;
26630 
26631 	data_mp = ipsec_mp->b_cont;
26632 
26633 	if (ill->ill_isv6) {
26634 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26635 
26636 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26637 			return;
26638 
26639 		plen = ip6h->ip6_plen;
26640 	} else {
26641 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26642 
26643 		if (CLASSD(ipha->ipha_dst))
26644 			return;
26645 
26646 		plen = ipha->ipha_length;
26647 	}
26648 	/*
26649 	 * Is there a pending DLPI control message being exchanged
26650 	 * between IP/IPsec and the DLS Provider? If there is, it
26651 	 * could be a SADB update, and the state of the DLS Provider
26652 	 * SADB might not be in sync with the SADB maintained by
26653 	 * IPsec. To avoid dropping packets or using the wrong keying
26654 	 * material, we do not accelerate this packet.
26655 	 */
26656 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26657 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26658 		    "ill_dlpi_pending! don't accelerate packet\n"));
26659 		return;
26660 	}
26661 
26662 	/*
26663 	 * Is the Provider in promiscous mode? If it does, we don't
26664 	 * accelerate the packet since it will bounce back up to the
26665 	 * listeners in the clear.
26666 	 */
26667 	if (ill->ill_promisc_on_phys) {
26668 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26669 		    "ill in promiscous mode, don't accelerate packet\n"));
26670 		return;
26671 	}
26672 
26673 	/*
26674 	 * Will the packet require fragmentation?
26675 	 */
26676 
26677 	/*
26678 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26679 	 * as is used elsewhere.
26680 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26681 	 *	+ 2-byte trailer
26682 	 */
26683 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26684 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26685 
26686 	if ((plen + overhead) > ill->ill_max_mtu)
26687 		return;
26688 
26689 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26690 
26691 	/*
26692 	 * Can the ill accelerate this IPsec protocol and algorithm
26693 	 * specified by the SA?
26694 	 */
26695 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26696 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26697 		return;
26698 	}
26699 
26700 	/*
26701 	 * Tell AH or ESP that the outbound ill is capable of
26702 	 * accelerating this packet.
26703 	 */
26704 	io->ipsec_out_is_capab_ill = B_TRUE;
26705 }
26706 
26707 /*
26708  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26709  *
26710  * If this function returns B_TRUE, the requested SA's have been filled
26711  * into the ipsec_out_*_sa pointers.
26712  *
26713  * If the function returns B_FALSE, the packet has been "consumed", most
26714  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26715  *
26716  * The SA references created by the protocol-specific "select"
26717  * function will be released when the ipsec_mp is freed, thanks to the
26718  * ipsec_out_free destructor -- see spd.c.
26719  */
26720 static boolean_t
26721 ipsec_out_select_sa(mblk_t *ipsec_mp)
26722 {
26723 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26724 	ipsec_out_t *io;
26725 	ipsec_policy_t *pp;
26726 	ipsec_action_t *ap;
26727 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26728 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26729 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26730 
26731 	if (!io->ipsec_out_secure) {
26732 		/*
26733 		 * We came here by mistake.
26734 		 * Don't bother with ipsec processing
26735 		 * We should "discourage" this path in the future.
26736 		 */
26737 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26738 		return (B_FALSE);
26739 	}
26740 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26741 	ASSERT((io->ipsec_out_policy != NULL) ||
26742 	    (io->ipsec_out_act != NULL));
26743 
26744 	ASSERT(io->ipsec_out_failed == B_FALSE);
26745 
26746 	/*
26747 	 * IPSEC processing has started.
26748 	 */
26749 	io->ipsec_out_proc_begin = B_TRUE;
26750 	ap = io->ipsec_out_act;
26751 	if (ap == NULL) {
26752 		pp = io->ipsec_out_policy;
26753 		ASSERT(pp != NULL);
26754 		ap = pp->ipsp_act;
26755 		ASSERT(ap != NULL);
26756 	}
26757 
26758 	/*
26759 	 * We have an action.  now, let's select SA's.
26760 	 * (In the future, we can cache this in the conn_t..)
26761 	 */
26762 	if (ap->ipa_want_esp) {
26763 		if (io->ipsec_out_esp_sa == NULL) {
26764 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26765 			    IPPROTO_ESP);
26766 		}
26767 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26768 	}
26769 
26770 	if (ap->ipa_want_ah) {
26771 		if (io->ipsec_out_ah_sa == NULL) {
26772 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26773 			    IPPROTO_AH);
26774 		}
26775 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26776 		/*
26777 		 * The ESP and AH processing order needs to be preserved
26778 		 * when both protocols are required (ESP should be applied
26779 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26780 		 * when both ESP and AH are required, and an AH ACQUIRE
26781 		 * is needed.
26782 		 */
26783 		if (ap->ipa_want_esp && need_ah_acquire)
26784 			need_esp_acquire = B_TRUE;
26785 	}
26786 
26787 	/*
26788 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26789 	 * Release SAs that got referenced, but will not be used until we
26790 	 * acquire _all_ of the SAs we need.
26791 	 */
26792 	if (need_ah_acquire || need_esp_acquire) {
26793 		if (io->ipsec_out_ah_sa != NULL) {
26794 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26795 			io->ipsec_out_ah_sa = NULL;
26796 		}
26797 		if (io->ipsec_out_esp_sa != NULL) {
26798 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26799 			io->ipsec_out_esp_sa = NULL;
26800 		}
26801 
26802 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26803 		return (B_FALSE);
26804 	}
26805 
26806 	return (B_TRUE);
26807 }
26808 
26809 /*
26810  * Process an IPSEC_OUT message and see what you can
26811  * do with it.
26812  * IPQoS Notes:
26813  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26814  * IPSec.
26815  * XXX would like to nuke ire_t.
26816  * XXX ill_index better be "real"
26817  */
26818 void
26819 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26820 {
26821 	ipsec_out_t *io;
26822 	ipsec_policy_t *pp;
26823 	ipsec_action_t *ap;
26824 	ipha_t *ipha;
26825 	ip6_t *ip6h;
26826 	mblk_t *mp;
26827 	ill_t *ill;
26828 	zoneid_t zoneid;
26829 	ipsec_status_t ipsec_rc;
26830 	boolean_t ill_need_rele = B_FALSE;
26831 	ip_stack_t	*ipst;
26832 	ipsec_stack_t	*ipss;
26833 
26834 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26835 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26836 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26837 	ipst = io->ipsec_out_ns->netstack_ip;
26838 	mp = ipsec_mp->b_cont;
26839 
26840 	/*
26841 	 * Initiate IPPF processing. We do it here to account for packets
26842 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26843 	 * We can check for ipsec_out_proc_begin even for such packets, as
26844 	 * they will always be false (asserted below).
26845 	 */
26846 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26847 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26848 		    io->ipsec_out_ill_index : ill_index);
26849 		if (mp == NULL) {
26850 			ip2dbg(("ipsec_out_process: packet dropped "\
26851 			    "during IPPF processing\n"));
26852 			freeb(ipsec_mp);
26853 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26854 			return;
26855 		}
26856 	}
26857 
26858 	if (!io->ipsec_out_secure) {
26859 		/*
26860 		 * We came here by mistake.
26861 		 * Don't bother with ipsec processing
26862 		 * Should "discourage" this path in the future.
26863 		 */
26864 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26865 		goto done;
26866 	}
26867 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26868 	ASSERT((io->ipsec_out_policy != NULL) ||
26869 	    (io->ipsec_out_act != NULL));
26870 	ASSERT(io->ipsec_out_failed == B_FALSE);
26871 
26872 	ipss = ipst->ips_netstack->netstack_ipsec;
26873 	if (!ipsec_loaded(ipss)) {
26874 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26875 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26876 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26877 		} else {
26878 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26879 		}
26880 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26881 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26882 		    &ipss->ipsec_dropper);
26883 		return;
26884 	}
26885 
26886 	/*
26887 	 * IPSEC processing has started.
26888 	 */
26889 	io->ipsec_out_proc_begin = B_TRUE;
26890 	ap = io->ipsec_out_act;
26891 	if (ap == NULL) {
26892 		pp = io->ipsec_out_policy;
26893 		ASSERT(pp != NULL);
26894 		ap = pp->ipsp_act;
26895 		ASSERT(ap != NULL);
26896 	}
26897 
26898 	/*
26899 	 * Save the outbound ill index. When the packet comes back
26900 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26901 	 * before sending it the accelerated packet.
26902 	 */
26903 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26904 		int ifindex;
26905 		ill = ire_to_ill(ire);
26906 		ifindex = ill->ill_phyint->phyint_ifindex;
26907 		io->ipsec_out_capab_ill_index = ifindex;
26908 	}
26909 
26910 	/*
26911 	 * The order of processing is first insert a IP header if needed.
26912 	 * Then insert the ESP header and then the AH header.
26913 	 */
26914 	if ((io->ipsec_out_se_done == B_FALSE) &&
26915 	    (ap->ipa_want_se)) {
26916 		/*
26917 		 * First get the outer IP header before sending
26918 		 * it to ESP.
26919 		 */
26920 		ipha_t *oipha, *iipha;
26921 		mblk_t *outer_mp, *inner_mp;
26922 
26923 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26924 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26925 			    "ipsec_out_process: "
26926 			    "Self-Encapsulation failed: Out of memory\n");
26927 			freemsg(ipsec_mp);
26928 			if (ill != NULL) {
26929 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26930 			} else {
26931 				BUMP_MIB(&ipst->ips_ip_mib,
26932 				    ipIfStatsOutDiscards);
26933 			}
26934 			return;
26935 		}
26936 		inner_mp = ipsec_mp->b_cont;
26937 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26938 		oipha = (ipha_t *)outer_mp->b_rptr;
26939 		iipha = (ipha_t *)inner_mp->b_rptr;
26940 		*oipha = *iipha;
26941 		outer_mp->b_wptr += sizeof (ipha_t);
26942 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26943 		    sizeof (ipha_t));
26944 		oipha->ipha_protocol = IPPROTO_ENCAP;
26945 		oipha->ipha_version_and_hdr_length =
26946 		    IP_SIMPLE_HDR_VERSION;
26947 		oipha->ipha_hdr_checksum = 0;
26948 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26949 		outer_mp->b_cont = inner_mp;
26950 		ipsec_mp->b_cont = outer_mp;
26951 
26952 		io->ipsec_out_se_done = B_TRUE;
26953 		io->ipsec_out_tunnel = B_TRUE;
26954 	}
26955 
26956 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26957 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26958 	    !ipsec_out_select_sa(ipsec_mp))
26959 		return;
26960 
26961 	/*
26962 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26963 	 * to do the heavy lifting.
26964 	 */
26965 	zoneid = io->ipsec_out_zoneid;
26966 	ASSERT(zoneid != ALL_ZONES);
26967 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26968 		ASSERT(io->ipsec_out_esp_sa != NULL);
26969 		io->ipsec_out_esp_done = B_TRUE;
26970 		/*
26971 		 * Note that since hw accel can only apply one transform,
26972 		 * not two, we skip hw accel for ESP if we also have AH
26973 		 * This is an design limitation of the interface
26974 		 * which should be revisited.
26975 		 */
26976 		ASSERT(ire != NULL);
26977 		if (io->ipsec_out_ah_sa == NULL) {
26978 			ill = (ill_t *)ire->ire_stq->q_ptr;
26979 			ipsec_out_is_accelerated(ipsec_mp,
26980 			    io->ipsec_out_esp_sa, ill, ire);
26981 		}
26982 
26983 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26984 		switch (ipsec_rc) {
26985 		case IPSEC_STATUS_SUCCESS:
26986 			break;
26987 		case IPSEC_STATUS_FAILED:
26988 			if (ill != NULL) {
26989 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26990 			} else {
26991 				BUMP_MIB(&ipst->ips_ip_mib,
26992 				    ipIfStatsOutDiscards);
26993 			}
26994 			/* FALLTHRU */
26995 		case IPSEC_STATUS_PENDING:
26996 			return;
26997 		}
26998 	}
26999 
27000 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27001 		ASSERT(io->ipsec_out_ah_sa != NULL);
27002 		io->ipsec_out_ah_done = B_TRUE;
27003 		if (ire == NULL) {
27004 			int idx = io->ipsec_out_capab_ill_index;
27005 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27006 			    NULL, NULL, NULL, NULL, ipst);
27007 			ill_need_rele = B_TRUE;
27008 		} else {
27009 			ill = (ill_t *)ire->ire_stq->q_ptr;
27010 		}
27011 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27012 		    ire);
27013 
27014 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27015 		switch (ipsec_rc) {
27016 		case IPSEC_STATUS_SUCCESS:
27017 			break;
27018 		case IPSEC_STATUS_FAILED:
27019 			if (ill != NULL) {
27020 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27021 			} else {
27022 				BUMP_MIB(&ipst->ips_ip_mib,
27023 				    ipIfStatsOutDiscards);
27024 			}
27025 			/* FALLTHRU */
27026 		case IPSEC_STATUS_PENDING:
27027 			if (ill != NULL && ill_need_rele)
27028 				ill_refrele(ill);
27029 			return;
27030 		}
27031 	}
27032 	/*
27033 	 * We are done with IPSEC processing. Send it over
27034 	 * the wire.
27035 	 */
27036 done:
27037 	mp = ipsec_mp->b_cont;
27038 	ipha = (ipha_t *)mp->b_rptr;
27039 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27040 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27041 	} else {
27042 		ip6h = (ip6_t *)ipha;
27043 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27044 	}
27045 	if (ill != NULL && ill_need_rele)
27046 		ill_refrele(ill);
27047 }
27048 
27049 /* ARGSUSED */
27050 void
27051 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27052 {
27053 	opt_restart_t	*or;
27054 	int	err;
27055 	conn_t	*connp;
27056 
27057 	ASSERT(CONN_Q(q));
27058 	connp = Q_TO_CONN(q);
27059 
27060 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27061 	or = (opt_restart_t *)first_mp->b_rptr;
27062 	/*
27063 	 * We don't need to pass any credentials here since this is just
27064 	 * a restart. The credentials are passed in when svr4_optcom_req
27065 	 * is called the first time (from ip_wput_nondata).
27066 	 */
27067 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27068 		err = svr4_optcom_req(q, first_mp, NULL,
27069 		    &ip_opt_obj);
27070 	} else {
27071 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27072 		err = tpi_optcom_req(q, first_mp, NULL,
27073 		    &ip_opt_obj);
27074 	}
27075 	if (err != EINPROGRESS) {
27076 		/* operation is done */
27077 		CONN_OPER_PENDING_DONE(connp);
27078 	}
27079 }
27080 
27081 /*
27082  * ioctls that go through a down/up sequence may need to wait for the down
27083  * to complete. This involves waiting for the ire and ipif refcnts to go down
27084  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27085  */
27086 /* ARGSUSED */
27087 void
27088 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27089 {
27090 	struct iocblk *iocp;
27091 	mblk_t *mp1;
27092 	ip_ioctl_cmd_t *ipip;
27093 	int err;
27094 	sin_t	*sin;
27095 	struct lifreq *lifr;
27096 	struct ifreq *ifr;
27097 
27098 	iocp = (struct iocblk *)mp->b_rptr;
27099 	ASSERT(ipsq != NULL);
27100 	/* Existence of mp1 verified in ip_wput_nondata */
27101 	mp1 = mp->b_cont->b_cont;
27102 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27103 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27104 		/*
27105 		 * Special case where ipsq_current_ipif is not set:
27106 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27107 		 * ill could also have become part of a ipmp group in the
27108 		 * process, we are here as were not able to complete the
27109 		 * operation in ipif_set_values because we could not become
27110 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27111 		 * will not be set so we need to set it.
27112 		 */
27113 		ill_t *ill = q->q_ptr;
27114 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27115 	}
27116 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27117 
27118 	if (ipip->ipi_cmd_type == IF_CMD) {
27119 		/* This a old style SIOC[GS]IF* command */
27120 		ifr = (struct ifreq *)mp1->b_rptr;
27121 		sin = (sin_t *)&ifr->ifr_addr;
27122 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27123 		/* This a new style SIOC[GS]LIF* command */
27124 		lifr = (struct lifreq *)mp1->b_rptr;
27125 		sin = (sin_t *)&lifr->lifr_addr;
27126 	} else {
27127 		sin = NULL;
27128 	}
27129 
27130 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27131 	    ipip, mp1->b_rptr);
27132 
27133 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27134 }
27135 
27136 /*
27137  * ioctl processing
27138  *
27139  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27140  * the ioctl command in the ioctl tables and determines the copyin data size
27141  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27142  * size.
27143  *
27144  * ioctl processing then continues when the M_IOCDATA makes its way down.
27145  * Now the ioctl is looked up again in the ioctl table, and its properties are
27146  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27147  * and the general ioctl processing function ip_process_ioctl is called.
27148  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27149  * so goes thru the serialization primitive ipsq_try_enter. Then the
27150  * appropriate function to handle the ioctl is called based on the entry in
27151  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27152  * which also refreleases the 'conn' that was refheld at the start of the
27153  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27154  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27155  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27156  *
27157  * Many exclusive ioctls go thru an internal down up sequence as part of
27158  * the operation. For example an attempt to change the IP address of an
27159  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27160  * does all the cleanup such as deleting all ires that use this address.
27161  * Then we need to wait till all references to the interface go away.
27162  */
27163 void
27164 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27165 {
27166 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27167 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27168 	cmd_info_t ci;
27169 	int err;
27170 	boolean_t entered_ipsq = B_FALSE;
27171 
27172 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27173 
27174 	if (ipip == NULL)
27175 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27176 
27177 	/*
27178 	 * SIOCLIFADDIF needs to go thru a special path since the
27179 	 * ill may not exist yet. This happens in the case of lo0
27180 	 * which is created using this ioctl.
27181 	 */
27182 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27183 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27184 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27185 		return;
27186 	}
27187 
27188 	ci.ci_ipif = NULL;
27189 	switch (ipip->ipi_cmd_type) {
27190 	case IF_CMD:
27191 	case LIF_CMD:
27192 		/*
27193 		 * ioctls that pass in a [l]ifreq appear here.
27194 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27195 		 * ci.ci_ipif
27196 		 */
27197 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27198 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27199 		if (err != 0) {
27200 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27201 			return;
27202 		}
27203 		ASSERT(ci.ci_ipif != NULL);
27204 		break;
27205 
27206 	case TUN_CMD:
27207 		/*
27208 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27209 		 * a refheld ipif in ci.ci_ipif
27210 		 */
27211 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27212 		if (err != 0) {
27213 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27214 			return;
27215 		}
27216 		ASSERT(ci.ci_ipif != NULL);
27217 		break;
27218 
27219 	case MISC_CMD:
27220 		/*
27221 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27222 		 * For eg. SIOCGLIFCONF will appear here.
27223 		 */
27224 		switch (ipip->ipi_cmd) {
27225 		case IF_UNITSEL:
27226 			/* ioctl comes down the ill */
27227 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27228 			ipif_refhold(ci.ci_ipif);
27229 			break;
27230 		case SIOCGMSFILTER:
27231 		case SIOCSMSFILTER:
27232 		case SIOCGIPMSFILTER:
27233 		case SIOCSIPMSFILTER:
27234 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27235 			    ip_process_ioctl);
27236 			if (err != 0) {
27237 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27238 				    NULL);
27239 			}
27240 			break;
27241 		}
27242 		err = 0;
27243 		ci.ci_sin = NULL;
27244 		ci.ci_sin6 = NULL;
27245 		ci.ci_lifr = NULL;
27246 		break;
27247 	}
27248 
27249 	/*
27250 	 * If ipsq is non-null, we are already being called exclusively
27251 	 */
27252 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27253 	if (!(ipip->ipi_flags & IPI_WR)) {
27254 		/*
27255 		 * A return value of EINPROGRESS means the ioctl is
27256 		 * either queued and waiting for some reason or has
27257 		 * already completed.
27258 		 */
27259 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27260 		    ci.ci_lifr);
27261 		if (ci.ci_ipif != NULL)
27262 			ipif_refrele(ci.ci_ipif);
27263 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27264 		return;
27265 	}
27266 
27267 	ASSERT(ci.ci_ipif != NULL);
27268 
27269 	if (ipsq == NULL) {
27270 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27271 		    ip_process_ioctl, NEW_OP, B_TRUE);
27272 		entered_ipsq = B_TRUE;
27273 	}
27274 	/*
27275 	 * Release the ipif so that ipif_down and friends that wait for
27276 	 * references to go away are not misled about the current ipif_refcnt
27277 	 * values. We are writer so we can access the ipif even after releasing
27278 	 * the ipif.
27279 	 */
27280 	ipif_refrele(ci.ci_ipif);
27281 	if (ipsq == NULL)
27282 		return;
27283 
27284 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27285 
27286 	/*
27287 	 * For most set ioctls that come here, this serves as a single point
27288 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27289 	 * be any new references to the ipif. This helps functions that go
27290 	 * through this path and end up trying to wait for the refcnts
27291 	 * associated with the ipif to go down to zero. Some exceptions are
27292 	 * Failover, Failback, and Groupname commands that operate on more than
27293 	 * just the ci.ci_ipif. These commands internally determine the
27294 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27295 	 * flags on that set. Another exception is the Removeif command that
27296 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27297 	 * ipif to operate on.
27298 	 */
27299 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27300 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27301 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27302 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27303 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27304 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27305 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27306 
27307 	/*
27308 	 * A return value of EINPROGRESS means the ioctl is
27309 	 * either queued and waiting for some reason or has
27310 	 * already completed.
27311 	 */
27312 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27313 
27314 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27315 
27316 	if (entered_ipsq)
27317 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27318 }
27319 
27320 /*
27321  * Complete the ioctl. Typically ioctls use the mi package and need to
27322  * do mi_copyout/mi_copy_done.
27323  */
27324 void
27325 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27326 {
27327 	conn_t	*connp = NULL;
27328 
27329 	if (err == EINPROGRESS)
27330 		return;
27331 
27332 	if (CONN_Q(q)) {
27333 		connp = Q_TO_CONN(q);
27334 		ASSERT(connp->conn_ref >= 2);
27335 	}
27336 
27337 	switch (mode) {
27338 	case COPYOUT:
27339 		if (err == 0)
27340 			mi_copyout(q, mp);
27341 		else
27342 			mi_copy_done(q, mp, err);
27343 		break;
27344 
27345 	case NO_COPYOUT:
27346 		mi_copy_done(q, mp, err);
27347 		break;
27348 
27349 	default:
27350 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27351 		break;
27352 	}
27353 
27354 	/*
27355 	 * The refhold placed at the start of the ioctl is released here.
27356 	 */
27357 	if (connp != NULL)
27358 		CONN_OPER_PENDING_DONE(connp);
27359 
27360 	if (ipsq != NULL)
27361 		ipsq_current_finish(ipsq);
27362 }
27363 
27364 /*
27365  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27366  */
27367 /* ARGSUSED */
27368 void
27369 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27370 {
27371 	conn_t *connp = arg;
27372 	tcp_t	*tcp;
27373 
27374 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27375 	tcp = connp->conn_tcp;
27376 
27377 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27378 		freemsg(mp);
27379 	else
27380 		tcp_rput_other(tcp, mp);
27381 	CONN_OPER_PENDING_DONE(connp);
27382 }
27383 
27384 /* Called from ip_wput for all non data messages */
27385 /* ARGSUSED */
27386 void
27387 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27388 {
27389 	mblk_t		*mp1;
27390 	ire_t		*ire, *fake_ire;
27391 	ill_t		*ill;
27392 	struct iocblk	*iocp;
27393 	ip_ioctl_cmd_t	*ipip;
27394 	cred_t		*cr;
27395 	conn_t		*connp;
27396 	int		cmd, err;
27397 	nce_t		*nce;
27398 	ipif_t		*ipif;
27399 	ip_stack_t	*ipst;
27400 	char		*proto_str;
27401 
27402 	if (CONN_Q(q)) {
27403 		connp = Q_TO_CONN(q);
27404 		ipst = connp->conn_netstack->netstack_ip;
27405 	} else {
27406 		connp = NULL;
27407 		ipst = ILLQ_TO_IPST(q);
27408 	}
27409 
27410 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27411 
27412 	/* Check if it is a queue to /dev/sctp. */
27413 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27414 	    connp->conn_rq == NULL) {
27415 		sctp_wput(q, mp);
27416 		return;
27417 	}
27418 
27419 	switch (DB_TYPE(mp)) {
27420 	case M_IOCTL:
27421 		/*
27422 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27423 		 * will arrange to copy in associated control structures.
27424 		 */
27425 		ip_sioctl_copyin_setup(q, mp);
27426 		return;
27427 	case M_IOCDATA:
27428 		/*
27429 		 * Ensure that this is associated with one of our trans-
27430 		 * parent ioctls.  If it's not ours, discard it if we're
27431 		 * running as a driver, or pass it on if we're a module.
27432 		 */
27433 		iocp = (struct iocblk *)mp->b_rptr;
27434 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27435 		if (ipip == NULL) {
27436 			if (q->q_next == NULL) {
27437 				goto nak;
27438 			} else {
27439 				putnext(q, mp);
27440 			}
27441 			return;
27442 		} else if ((q->q_next != NULL) &&
27443 		    !(ipip->ipi_flags & IPI_MODOK)) {
27444 			/*
27445 			 * the ioctl is one we recognise, but is not
27446 			 * consumed by IP as a module, pass M_IOCDATA
27447 			 * for processing downstream, but only for
27448 			 * common Streams ioctls.
27449 			 */
27450 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27451 				putnext(q, mp);
27452 				return;
27453 			} else {
27454 				goto nak;
27455 			}
27456 		}
27457 
27458 		/* IOCTL continuation following copyin or copyout. */
27459 		if (mi_copy_state(q, mp, NULL) == -1) {
27460 			/*
27461 			 * The copy operation failed.  mi_copy_state already
27462 			 * cleaned up, so we're out of here.
27463 			 */
27464 			return;
27465 		}
27466 		/*
27467 		 * If we just completed a copy in, we become writer and
27468 		 * continue processing in ip_sioctl_copyin_done.  If it
27469 		 * was a copy out, we call mi_copyout again.  If there is
27470 		 * nothing more to copy out, it will complete the IOCTL.
27471 		 */
27472 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27473 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27474 				mi_copy_done(q, mp, EPROTO);
27475 				return;
27476 			}
27477 			/*
27478 			 * Check for cases that need more copying.  A return
27479 			 * value of 0 means a second copyin has been started,
27480 			 * so we return; a return value of 1 means no more
27481 			 * copying is needed, so we continue.
27482 			 */
27483 			cmd = iocp->ioc_cmd;
27484 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27485 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27486 			    MI_COPY_COUNT(mp) == 1) {
27487 				if (ip_copyin_msfilter(q, mp) == 0)
27488 					return;
27489 			}
27490 			/*
27491 			 * Refhold the conn, till the ioctl completes. This is
27492 			 * needed in case the ioctl ends up in the pending mp
27493 			 * list. Every mp in the ill_pending_mp list and
27494 			 * the ipsq_pending_mp must have a refhold on the conn
27495 			 * to resume processing. The refhold is released when
27496 			 * the ioctl completes. (normally or abnormally)
27497 			 * In all cases ip_ioctl_finish is called to finish
27498 			 * the ioctl.
27499 			 */
27500 			if (connp != NULL) {
27501 				/* This is not a reentry */
27502 				ASSERT(ipsq == NULL);
27503 				CONN_INC_REF(connp);
27504 			} else {
27505 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27506 					mi_copy_done(q, mp, EINVAL);
27507 					return;
27508 				}
27509 			}
27510 
27511 			ip_process_ioctl(ipsq, q, mp, ipip);
27512 
27513 		} else {
27514 			mi_copyout(q, mp);
27515 		}
27516 		return;
27517 nak:
27518 		iocp->ioc_error = EINVAL;
27519 		mp->b_datap->db_type = M_IOCNAK;
27520 		iocp->ioc_count = 0;
27521 		qreply(q, mp);
27522 		return;
27523 
27524 	case M_IOCNAK:
27525 		/*
27526 		 * The only way we could get here is if a resolver didn't like
27527 		 * an IOCTL we sent it.	 This shouldn't happen.
27528 		 */
27529 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27530 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27531 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27532 		freemsg(mp);
27533 		return;
27534 	case M_IOCACK:
27535 		/* /dev/ip shouldn't see this */
27536 		if (CONN_Q(q))
27537 			goto nak;
27538 
27539 		/* Finish socket ioctls passed through to ARP. */
27540 		ip_sioctl_iocack(q, mp);
27541 		return;
27542 	case M_FLUSH:
27543 		if (*mp->b_rptr & FLUSHW)
27544 			flushq(q, FLUSHALL);
27545 		if (q->q_next) {
27546 			/*
27547 			 * M_FLUSH is sent up to IP by some drivers during
27548 			 * unbind. ip_rput has already replied to it. We are
27549 			 * here for the M_FLUSH that we originated in IP
27550 			 * before sending the unbind request to the driver.
27551 			 * Just free it as we don't queue packets in IP
27552 			 * on the write side of the device instance.
27553 			 */
27554 			freemsg(mp);
27555 			return;
27556 		}
27557 		if (*mp->b_rptr & FLUSHR) {
27558 			*mp->b_rptr &= ~FLUSHW;
27559 			qreply(q, mp);
27560 			return;
27561 		}
27562 		freemsg(mp);
27563 		return;
27564 	case IRE_DB_REQ_TYPE:
27565 		if (connp == NULL) {
27566 			proto_str = "IRE_DB_REQ_TYPE";
27567 			goto protonak;
27568 		}
27569 		/* An Upper Level Protocol wants a copy of an IRE. */
27570 		ip_ire_req(q, mp);
27571 		return;
27572 	case M_CTL:
27573 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27574 			break;
27575 
27576 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27577 		    TUN_HELLO) {
27578 			ASSERT(connp != NULL);
27579 			connp->conn_flags |= IPCL_IPTUN;
27580 			freeb(mp);
27581 			return;
27582 		}
27583 
27584 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27585 		    IP_ULP_OUT_LABELED) {
27586 			out_labeled_t *olp;
27587 
27588 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27589 				break;
27590 			olp = (out_labeled_t *)mp->b_rptr;
27591 			connp->conn_ulp_labeled = olp->out_qnext == q;
27592 			freemsg(mp);
27593 			return;
27594 		}
27595 
27596 		/* M_CTL messages are used by ARP to tell us things. */
27597 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27598 			break;
27599 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27600 		case AR_ENTRY_SQUERY:
27601 			ip_wput_ctl(q, mp);
27602 			return;
27603 		case AR_CLIENT_NOTIFY:
27604 			ip_arp_news(q, mp);
27605 			return;
27606 		case AR_DLPIOP_DONE:
27607 			ASSERT(q->q_next != NULL);
27608 			ill = (ill_t *)q->q_ptr;
27609 			/* qwriter_ip releases the refhold */
27610 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27611 			ill_refhold(ill);
27612 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
27613 			    CUR_OP, B_FALSE);
27614 			return;
27615 		case AR_ARP_CLOSING:
27616 			/*
27617 			 * ARP (above us) is closing. If no ARP bringup is
27618 			 * currently pending, ack the message so that ARP
27619 			 * can complete its close. Also mark ill_arp_closing
27620 			 * so that new ARP bringups will fail. If any
27621 			 * ARP bringup is currently in progress, we will
27622 			 * ack this when the current ARP bringup completes.
27623 			 */
27624 			ASSERT(q->q_next != NULL);
27625 			ill = (ill_t *)q->q_ptr;
27626 			mutex_enter(&ill->ill_lock);
27627 			ill->ill_arp_closing = 1;
27628 			if (!ill->ill_arp_bringup_pending) {
27629 				mutex_exit(&ill->ill_lock);
27630 				qreply(q, mp);
27631 			} else {
27632 				mutex_exit(&ill->ill_lock);
27633 				freemsg(mp);
27634 			}
27635 			return;
27636 		case AR_ARP_EXTEND:
27637 			/*
27638 			 * The ARP module above us is capable of duplicate
27639 			 * address detection.  Old ATM drivers will not send
27640 			 * this message.
27641 			 */
27642 			ASSERT(q->q_next != NULL);
27643 			ill = (ill_t *)q->q_ptr;
27644 			ill->ill_arp_extend = B_TRUE;
27645 			freemsg(mp);
27646 			return;
27647 		default:
27648 			break;
27649 		}
27650 		break;
27651 	case M_PROTO:
27652 	case M_PCPROTO:
27653 		/*
27654 		 * The only PROTO messages we expect are ULP binds and
27655 		 * copies of option negotiation acknowledgements.
27656 		 */
27657 		switch (((union T_primitives *)mp->b_rptr)->type) {
27658 		case O_T_BIND_REQ:
27659 		case T_BIND_REQ: {
27660 			/* Request can get queued in bind */
27661 			if (connp == NULL) {
27662 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27663 				goto protonak;
27664 			}
27665 			/*
27666 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27667 			 * instead of going through this path.  We only get
27668 			 * here in the following cases:
27669 			 *
27670 			 * a. Bind retries, where ipsq is non-NULL.
27671 			 * b. T_BIND_REQ is issued from non TCP/UDP
27672 			 *    transport, e.g. icmp for raw socket,
27673 			 *    in which case ipsq will be NULL.
27674 			 */
27675 			ASSERT(ipsq != NULL ||
27676 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27677 
27678 			/* Don't increment refcnt if this is a re-entry */
27679 			if (ipsq == NULL)
27680 				CONN_INC_REF(connp);
27681 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27682 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27683 			if (mp == NULL)
27684 				return;
27685 			if (IPCL_IS_TCP(connp)) {
27686 				/*
27687 				 * In the case of TCP endpoint we
27688 				 * come here only for bind retries
27689 				 */
27690 				ASSERT(ipsq != NULL);
27691 				CONN_INC_REF(connp);
27692 				squeue_fill(connp->conn_sqp, mp,
27693 				    ip_resume_tcp_bind, connp,
27694 				    SQTAG_BIND_RETRY);
27695 				return;
27696 			} else if (IPCL_IS_UDP(connp)) {
27697 				/*
27698 				 * In the case of UDP endpoint we
27699 				 * come here only for bind retries
27700 				 */
27701 				ASSERT(ipsq != NULL);
27702 				udp_resume_bind(connp, mp);
27703 				return;
27704 			}
27705 			qreply(q, mp);
27706 			CONN_OPER_PENDING_DONE(connp);
27707 			return;
27708 		}
27709 		case T_SVR4_OPTMGMT_REQ:
27710 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27711 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27712 
27713 			if (connp == NULL) {
27714 				proto_str = "T_SVR4_OPTMGMT_REQ";
27715 				goto protonak;
27716 			}
27717 
27718 			if (!snmpcom_req(q, mp, ip_snmp_set,
27719 			    ip_snmp_get, cr)) {
27720 				/*
27721 				 * Call svr4_optcom_req so that it can
27722 				 * generate the ack. We don't come here
27723 				 * if this operation is being restarted.
27724 				 * ip_restart_optmgmt will drop the conn ref.
27725 				 * In the case of ipsec option after the ipsec
27726 				 * load is complete conn_restart_ipsec_waiter
27727 				 * drops the conn ref.
27728 				 */
27729 				ASSERT(ipsq == NULL);
27730 				CONN_INC_REF(connp);
27731 				if (ip_check_for_ipsec_opt(q, mp))
27732 					return;
27733 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27734 				if (err != EINPROGRESS) {
27735 					/* Operation is done */
27736 					CONN_OPER_PENDING_DONE(connp);
27737 				}
27738 			}
27739 			return;
27740 		case T_OPTMGMT_REQ:
27741 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27742 			/*
27743 			 * Note: No snmpcom_req support through new
27744 			 * T_OPTMGMT_REQ.
27745 			 * Call tpi_optcom_req so that it can
27746 			 * generate the ack.
27747 			 */
27748 			if (connp == NULL) {
27749 				proto_str = "T_OPTMGMT_REQ";
27750 				goto protonak;
27751 			}
27752 
27753 			ASSERT(ipsq == NULL);
27754 			/*
27755 			 * We don't come here for restart. ip_restart_optmgmt
27756 			 * will drop the conn ref. In the case of ipsec option
27757 			 * after the ipsec load is complete
27758 			 * conn_restart_ipsec_waiter drops the conn ref.
27759 			 */
27760 			CONN_INC_REF(connp);
27761 			if (ip_check_for_ipsec_opt(q, mp))
27762 				return;
27763 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27764 			if (err != EINPROGRESS) {
27765 				/* Operation is done */
27766 				CONN_OPER_PENDING_DONE(connp);
27767 			}
27768 			return;
27769 		case T_UNBIND_REQ:
27770 			if (connp == NULL) {
27771 				proto_str = "T_UNBIND_REQ";
27772 				goto protonak;
27773 			}
27774 			mp = ip_unbind(q, mp);
27775 			qreply(q, mp);
27776 			return;
27777 		default:
27778 			/*
27779 			 * Have to drop any DLPI messages coming down from
27780 			 * arp (such as an info_req which would cause ip
27781 			 * to receive an extra info_ack if it was passed
27782 			 * through.
27783 			 */
27784 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27785 			    (int)*(uint_t *)mp->b_rptr));
27786 			freemsg(mp);
27787 			return;
27788 		}
27789 		/* NOTREACHED */
27790 	case IRE_DB_TYPE: {
27791 		nce_t		*nce;
27792 		ill_t		*ill;
27793 		in6_addr_t	gw_addr_v6;
27794 
27795 
27796 		/*
27797 		 * This is a response back from a resolver.  It
27798 		 * consists of a message chain containing:
27799 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27800 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27801 		 * The LL_HDR_MBLK is the DLPI header to use to get
27802 		 * the attached packet, and subsequent ones for the
27803 		 * same destination, transmitted.
27804 		 */
27805 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27806 			break;
27807 		/*
27808 		 * First, check to make sure the resolution succeeded.
27809 		 * If it failed, the second mblk will be empty.
27810 		 * If it is, free the chain, dropping the packet.
27811 		 * (We must ire_delete the ire; that frees the ire mblk)
27812 		 * We're doing this now to support PVCs for ATM; it's
27813 		 * a partial xresolv implementation. When we fully implement
27814 		 * xresolv interfaces, instead of freeing everything here
27815 		 * we'll initiate neighbor discovery.
27816 		 *
27817 		 * For v4 (ARP and other external resolvers) the resolver
27818 		 * frees the message, so no check is needed. This check
27819 		 * is required, though, for a full xresolve implementation.
27820 		 * Including this code here now both shows how external
27821 		 * resolvers can NACK a resolution request using an
27822 		 * existing design that has no specific provisions for NACKs,
27823 		 * and also takes into account that the current non-ARP
27824 		 * external resolver has been coded to use this method of
27825 		 * NACKing for all IPv6 (xresolv) cases,
27826 		 * whether our xresolv implementation is complete or not.
27827 		 *
27828 		 */
27829 		ire = (ire_t *)mp->b_rptr;
27830 		ill = ire_to_ill(ire);
27831 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27832 		if (mp1->b_rptr == mp1->b_wptr) {
27833 			if (ire->ire_ipversion == IPV6_VERSION) {
27834 				/*
27835 				 * XRESOLV interface.
27836 				 */
27837 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27838 				mutex_enter(&ire->ire_lock);
27839 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27840 				mutex_exit(&ire->ire_lock);
27841 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27842 					nce = ndp_lookup_v6(ill,
27843 					    &ire->ire_addr_v6, B_FALSE);
27844 				} else {
27845 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27846 					    B_FALSE);
27847 				}
27848 				if (nce != NULL) {
27849 					nce_resolv_failed(nce);
27850 					ndp_delete(nce);
27851 					NCE_REFRELE(nce);
27852 				}
27853 			}
27854 			mp->b_cont = NULL;
27855 			freemsg(mp1);		/* frees the pkt as well */
27856 			ASSERT(ire->ire_nce == NULL);
27857 			ire_delete((ire_t *)mp->b_rptr);
27858 			return;
27859 		}
27860 
27861 		/*
27862 		 * Split them into IRE_MBLK and pkt and feed it into
27863 		 * ire_add_then_send. Then in ire_add_then_send
27864 		 * the IRE will be added, and then the packet will be
27865 		 * run back through ip_wput. This time it will make
27866 		 * it to the wire.
27867 		 */
27868 		mp->b_cont = NULL;
27869 		mp = mp1->b_cont;		/* now, mp points to pkt */
27870 		mp1->b_cont = NULL;
27871 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27872 		if (ire->ire_ipversion == IPV6_VERSION) {
27873 			/*
27874 			 * XRESOLV interface. Find the nce and put a copy
27875 			 * of the dl_unitdata_req in nce_res_mp
27876 			 */
27877 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27878 			mutex_enter(&ire->ire_lock);
27879 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27880 			mutex_exit(&ire->ire_lock);
27881 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27882 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27883 				    B_FALSE);
27884 			} else {
27885 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27886 			}
27887 			if (nce != NULL) {
27888 				/*
27889 				 * We have to protect nce_res_mp here
27890 				 * from being accessed by other threads
27891 				 * while we change the mblk pointer.
27892 				 * Other functions will also lock the nce when
27893 				 * accessing nce_res_mp.
27894 				 *
27895 				 * The reason we change the mblk pointer
27896 				 * here rather than copying the resolved address
27897 				 * into the template is that, unlike with
27898 				 * ethernet, we have no guarantee that the
27899 				 * resolved address length will be
27900 				 * smaller than or equal to the lla length
27901 				 * with which the template was allocated,
27902 				 * (for ethernet, they're equal)
27903 				 * so we have to use the actual resolved
27904 				 * address mblk - which holds the real
27905 				 * dl_unitdata_req with the resolved address.
27906 				 *
27907 				 * Doing this is the same behavior as was
27908 				 * previously used in the v4 ARP case.
27909 				 */
27910 				mutex_enter(&nce->nce_lock);
27911 				if (nce->nce_res_mp != NULL)
27912 					freemsg(nce->nce_res_mp);
27913 				nce->nce_res_mp = mp1;
27914 				mutex_exit(&nce->nce_lock);
27915 				/*
27916 				 * We do a fastpath probe here because
27917 				 * we have resolved the address without
27918 				 * using Neighbor Discovery.
27919 				 * In the non-XRESOLV v6 case, the fastpath
27920 				 * probe is done right after neighbor
27921 				 * discovery completes.
27922 				 */
27923 				if (nce->nce_res_mp != NULL) {
27924 					int res;
27925 					nce_fastpath_list_add(nce);
27926 					res = ill_fastpath_probe(ill,
27927 					    nce->nce_res_mp);
27928 					if (res != 0 && res != EAGAIN)
27929 						nce_fastpath_list_delete(nce);
27930 				}
27931 
27932 				ire_add_then_send(q, ire, mp);
27933 				/*
27934 				 * Now we have to clean out any packets
27935 				 * that may have been queued on the nce
27936 				 * while it was waiting for address resolution
27937 				 * to complete.
27938 				 */
27939 				mutex_enter(&nce->nce_lock);
27940 				mp1 = nce->nce_qd_mp;
27941 				nce->nce_qd_mp = NULL;
27942 				mutex_exit(&nce->nce_lock);
27943 				while (mp1 != NULL) {
27944 					mblk_t *nxt_mp;
27945 					queue_t *fwdq = NULL;
27946 					ill_t   *inbound_ill;
27947 					uint_t ifindex;
27948 
27949 					nxt_mp = mp1->b_next;
27950 					mp1->b_next = NULL;
27951 					/*
27952 					 * Retrieve ifindex stored in
27953 					 * ip_rput_data_v6()
27954 					 */
27955 					ifindex =
27956 					    (uint_t)(uintptr_t)mp1->b_prev;
27957 					inbound_ill =
27958 						ill_lookup_on_ifindex(ifindex,
27959 						    B_TRUE, NULL, NULL, NULL,
27960 						    NULL, ipst);
27961 					mp1->b_prev = NULL;
27962 					if (inbound_ill != NULL)
27963 						fwdq = inbound_ill->ill_rq;
27964 
27965 					if (fwdq != NULL) {
27966 						put(fwdq, mp1);
27967 						ill_refrele(inbound_ill);
27968 					} else
27969 						put(WR(ill->ill_rq), mp1);
27970 					mp1 = nxt_mp;
27971 				}
27972 				NCE_REFRELE(nce);
27973 			} else {	/* nce is NULL; clean up */
27974 				ire_delete(ire);
27975 				freemsg(mp);
27976 				freemsg(mp1);
27977 				return;
27978 			}
27979 		} else {
27980 			nce_t *arpce;
27981 			/*
27982 			 * Link layer resolution succeeded. Recompute the
27983 			 * ire_nce.
27984 			 */
27985 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27986 			if ((arpce = ndp_lookup_v4(ill,
27987 			    (ire->ire_gateway_addr != INADDR_ANY ?
27988 			    &ire->ire_gateway_addr : &ire->ire_addr),
27989 			    B_FALSE)) == NULL) {
27990 				freeb(ire->ire_mp);
27991 				freeb(mp1);
27992 				freemsg(mp);
27993 				return;
27994 			}
27995 			mutex_enter(&arpce->nce_lock);
27996 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27997 			if (arpce->nce_state == ND_REACHABLE) {
27998 				/*
27999 				 * Someone resolved this before us;
28000 				 * cleanup the res_mp. Since ire has
28001 				 * not been added yet, the call to ire_add_v4
28002 				 * from ire_add_then_send (when a dup is
28003 				 * detected) will clean up the ire.
28004 				 */
28005 				freeb(mp1);
28006 			} else {
28007 				if (arpce->nce_res_mp != NULL)
28008 					freemsg(arpce->nce_res_mp);
28009 				arpce->nce_res_mp = mp1;
28010 				arpce->nce_state = ND_REACHABLE;
28011 			}
28012 			mutex_exit(&arpce->nce_lock);
28013 			if (ire->ire_marks & IRE_MARK_NOADD) {
28014 				/*
28015 				 * this ire will not be added to the ire
28016 				 * cache table, so we can set the ire_nce
28017 				 * here, as there are no atomicity constraints.
28018 				 */
28019 				ire->ire_nce = arpce;
28020 				/*
28021 				 * We are associating this nce with the ire
28022 				 * so change the nce ref taken in
28023 				 * ndp_lookup_v4() from
28024 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28025 				 */
28026 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28027 			} else {
28028 				NCE_REFRELE(arpce);
28029 			}
28030 			ire_add_then_send(q, ire, mp);
28031 		}
28032 		return;	/* All is well, the packet has been sent. */
28033 	}
28034 	case IRE_ARPRESOLVE_TYPE: {
28035 
28036 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28037 			break;
28038 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28039 		mp->b_cont = NULL;
28040 		/*
28041 		 * First, check to make sure the resolution succeeded.
28042 		 * If it failed, the second mblk will be empty.
28043 		 */
28044 		if (mp1->b_rptr == mp1->b_wptr) {
28045 			/* cleanup  the incomplete ire, free queued packets */
28046 			freemsg(mp); /* fake ire */
28047 			freeb(mp1);  /* dl_unitdata response */
28048 			return;
28049 		}
28050 
28051 		/*
28052 		 * update any incomplete nce_t found. we lookup the ctable
28053 		 * and find the nce from the ire->ire_nce because we need
28054 		 * to pass the ire to ip_xmit_v4 later, and can find both
28055 		 * ire and nce in one lookup from the ctable.
28056 		 */
28057 		fake_ire = (ire_t *)mp->b_rptr;
28058 		/*
28059 		 * By the time we come back here from ARP
28060 		 * the logical outgoing interface  of the incomplete ire
28061 		 * we added in ire_forward could have disappeared,
28062 		 * causing the incomplete ire to also have
28063 		 * dissapeared. So we need to retreive the
28064 		 * proper ipif for the ire  before looking
28065 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28066 		 */
28067 		ill = q->q_ptr;
28068 
28069 		/* Get the outgoing ipif */
28070 		mutex_enter(&ill->ill_lock);
28071 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28072 			mutex_exit(&ill->ill_lock);
28073 			freemsg(mp); /* fake ire */
28074 			freeb(mp1);  /* dl_unitdata response */
28075 			return;
28076 		}
28077 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28078 
28079 		if (ipif == NULL) {
28080 			mutex_exit(&ill->ill_lock);
28081 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28082 			freemsg(mp);
28083 			freeb(mp1);
28084 			return;
28085 		}
28086 		ipif_refhold_locked(ipif);
28087 		mutex_exit(&ill->ill_lock);
28088 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28089 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28090 		    ipif, fake_ire->ire_zoneid, NULL,
28091 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28092 		ipif_refrele(ipif);
28093 		if (ire == NULL) {
28094 			/*
28095 			 * no ire was found; check if there is an nce
28096 			 * for this lookup; if it has no ire's pointing at it
28097 			 * cleanup.
28098 			 */
28099 			if ((nce = ndp_lookup_v4(ill,
28100 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28101 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28102 			    B_FALSE)) != NULL) {
28103 				/*
28104 				 * cleanup:
28105 				 * We check for refcnt 2 (one for the nce
28106 				 * hash list + 1 for the ref taken by
28107 				 * ndp_lookup_v4) to check that there are
28108 				 * no ire's pointing at the nce.
28109 				 */
28110 				if (nce->nce_refcnt == 2)
28111 					ndp_delete(nce);
28112 				NCE_REFRELE(nce);
28113 			}
28114 			freeb(mp1);  /* dl_unitdata response */
28115 			freemsg(mp); /* fake ire */
28116 			return;
28117 		}
28118 		nce = ire->ire_nce;
28119 		DTRACE_PROBE2(ire__arpresolve__type,
28120 		    ire_t *, ire, nce_t *, nce);
28121 		ASSERT(nce->nce_state != ND_INITIAL);
28122 		mutex_enter(&nce->nce_lock);
28123 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28124 		if (nce->nce_state == ND_REACHABLE) {
28125 			/*
28126 			 * Someone resolved this before us;
28127 			 * our response is not needed any more.
28128 			 */
28129 			mutex_exit(&nce->nce_lock);
28130 			freeb(mp1);  /* dl_unitdata response */
28131 		} else {
28132 			if (nce->nce_res_mp != NULL) {
28133 				freemsg(nce->nce_res_mp);
28134 				/* existing dl_unitdata template */
28135 			}
28136 			nce->nce_res_mp = mp1;
28137 			nce->nce_state = ND_REACHABLE;
28138 			mutex_exit(&nce->nce_lock);
28139 			nce_fastpath(nce);
28140 		}
28141 		/*
28142 		 * The cached nce_t has been updated to be reachable;
28143 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
28144 		 */
28145 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28146 		freemsg(mp);
28147 		/*
28148 		 * send out queued packets.
28149 		 */
28150 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28151 
28152 		IRE_REFRELE(ire);
28153 		return;
28154 	}
28155 	default:
28156 		break;
28157 	}
28158 	if (q->q_next) {
28159 		putnext(q, mp);
28160 	} else
28161 		freemsg(mp);
28162 	return;
28163 
28164 protonak:
28165 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28166 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28167 		qreply(q, mp);
28168 }
28169 
28170 /*
28171  * Process IP options in an outbound packet.  Modify the destination if there
28172  * is a source route option.
28173  * Returns non-zero if something fails in which case an ICMP error has been
28174  * sent and mp freed.
28175  */
28176 static int
28177 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28178     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28179 {
28180 	ipoptp_t	opts;
28181 	uchar_t		*opt;
28182 	uint8_t		optval;
28183 	uint8_t		optlen;
28184 	ipaddr_t	dst;
28185 	intptr_t	code = 0;
28186 	mblk_t		*mp;
28187 	ire_t		*ire = NULL;
28188 
28189 	ip2dbg(("ip_wput_options\n"));
28190 	mp = ipsec_mp;
28191 	if (mctl_present) {
28192 		mp = ipsec_mp->b_cont;
28193 	}
28194 
28195 	dst = ipha->ipha_dst;
28196 	for (optval = ipoptp_first(&opts, ipha);
28197 	    optval != IPOPT_EOL;
28198 	    optval = ipoptp_next(&opts)) {
28199 		opt = opts.ipoptp_cur;
28200 		optlen = opts.ipoptp_len;
28201 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28202 		    optval, optlen));
28203 		switch (optval) {
28204 			uint32_t off;
28205 		case IPOPT_SSRR:
28206 		case IPOPT_LSRR:
28207 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28208 				ip1dbg((
28209 				    "ip_wput_options: bad option offset\n"));
28210 				code = (char *)&opt[IPOPT_OLEN] -
28211 				    (char *)ipha;
28212 				goto param_prob;
28213 			}
28214 			off = opt[IPOPT_OFFSET];
28215 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28216 			    ntohl(dst)));
28217 			/*
28218 			 * For strict: verify that dst is directly
28219 			 * reachable.
28220 			 */
28221 			if (optval == IPOPT_SSRR) {
28222 				ire = ire_ftable_lookup(dst, 0, 0,
28223 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28224 				    MBLK_GETLABEL(mp),
28225 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28226 				if (ire == NULL) {
28227 					ip1dbg(("ip_wput_options: SSRR not"
28228 					    " directly reachable: 0x%x\n",
28229 					    ntohl(dst)));
28230 					goto bad_src_route;
28231 				}
28232 				ire_refrele(ire);
28233 			}
28234 			break;
28235 		case IPOPT_RR:
28236 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28237 				ip1dbg((
28238 				    "ip_wput_options: bad option offset\n"));
28239 				code = (char *)&opt[IPOPT_OLEN] -
28240 				    (char *)ipha;
28241 				goto param_prob;
28242 			}
28243 			break;
28244 		case IPOPT_TS:
28245 			/*
28246 			 * Verify that length >=5 and that there is either
28247 			 * room for another timestamp or that the overflow
28248 			 * counter is not maxed out.
28249 			 */
28250 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28251 			if (optlen < IPOPT_MINLEN_IT) {
28252 				goto param_prob;
28253 			}
28254 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28255 				ip1dbg((
28256 				    "ip_wput_options: bad option offset\n"));
28257 				code = (char *)&opt[IPOPT_OFFSET] -
28258 				    (char *)ipha;
28259 				goto param_prob;
28260 			}
28261 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28262 			case IPOPT_TS_TSONLY:
28263 				off = IPOPT_TS_TIMELEN;
28264 				break;
28265 			case IPOPT_TS_TSANDADDR:
28266 			case IPOPT_TS_PRESPEC:
28267 			case IPOPT_TS_PRESPEC_RFC791:
28268 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28269 				break;
28270 			default:
28271 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28272 				    (char *)ipha;
28273 				goto param_prob;
28274 			}
28275 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28276 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28277 				/*
28278 				 * No room and the overflow counter is 15
28279 				 * already.
28280 				 */
28281 				goto param_prob;
28282 			}
28283 			break;
28284 		}
28285 	}
28286 
28287 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28288 		return (0);
28289 
28290 	ip1dbg(("ip_wput_options: error processing IP options."));
28291 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28292 
28293 param_prob:
28294 	/*
28295 	 * Since ip_wput() isn't close to finished, we fill
28296 	 * in enough of the header for credible error reporting.
28297 	 */
28298 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28299 		/* Failed */
28300 		freemsg(ipsec_mp);
28301 		return (-1);
28302 	}
28303 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28304 	return (-1);
28305 
28306 bad_src_route:
28307 	/*
28308 	 * Since ip_wput() isn't close to finished, we fill
28309 	 * in enough of the header for credible error reporting.
28310 	 */
28311 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28312 		/* Failed */
28313 		freemsg(ipsec_mp);
28314 		return (-1);
28315 	}
28316 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28317 	return (-1);
28318 }
28319 
28320 /*
28321  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28322  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28323  * thru /etc/system.
28324  */
28325 #define	CONN_MAXDRAINCNT	64
28326 
28327 static void
28328 conn_drain_init(ip_stack_t *ipst)
28329 {
28330 	int i;
28331 
28332 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28333 
28334 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28335 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28336 		/*
28337 		 * Default value of the number of drainers is the
28338 		 * number of cpus, subject to maximum of 8 drainers.
28339 		 */
28340 		if (boot_max_ncpus != -1)
28341 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28342 		else
28343 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28344 	}
28345 
28346 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28347 	    sizeof (idl_t), KM_SLEEP);
28348 
28349 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28350 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28351 		    MUTEX_DEFAULT, NULL);
28352 	}
28353 }
28354 
28355 static void
28356 conn_drain_fini(ip_stack_t *ipst)
28357 {
28358 	int i;
28359 
28360 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28361 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28362 	kmem_free(ipst->ips_conn_drain_list,
28363 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28364 	ipst->ips_conn_drain_list = NULL;
28365 }
28366 
28367 /*
28368  * Note: For an overview of how flowcontrol is handled in IP please see the
28369  * IP Flowcontrol notes at the top of this file.
28370  *
28371  * Flow control has blocked us from proceeding. Insert the given conn in one
28372  * of the conn drain lists. These conn wq's will be qenabled later on when
28373  * STREAMS flow control does a backenable. conn_walk_drain will enable
28374  * the first conn in each of these drain lists. Each of these qenabled conns
28375  * in turn enables the next in the list, after it runs, or when it closes,
28376  * thus sustaining the drain process.
28377  *
28378  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28379  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28380  * running at any time, on a given conn, since there can be only 1 service proc
28381  * running on a queue at any time.
28382  */
28383 void
28384 conn_drain_insert(conn_t *connp)
28385 {
28386 	idl_t	*idl;
28387 	uint_t	index;
28388 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28389 
28390 	mutex_enter(&connp->conn_lock);
28391 	if (connp->conn_state_flags & CONN_CLOSING) {
28392 		/*
28393 		 * The conn is closing as a result of which CONN_CLOSING
28394 		 * is set. Return.
28395 		 */
28396 		mutex_exit(&connp->conn_lock);
28397 		return;
28398 	} else if (connp->conn_idl == NULL) {
28399 		/*
28400 		 * Assign the next drain list round robin. We dont' use
28401 		 * a lock, and thus it may not be strictly round robin.
28402 		 * Atomicity of load/stores is enough to make sure that
28403 		 * conn_drain_list_index is always within bounds.
28404 		 */
28405 		index = ipst->ips_conn_drain_list_index;
28406 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28407 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28408 		index++;
28409 		if (index == ipst->ips_conn_drain_list_cnt)
28410 			index = 0;
28411 		ipst->ips_conn_drain_list_index = index;
28412 	}
28413 	mutex_exit(&connp->conn_lock);
28414 
28415 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28416 	if ((connp->conn_drain_prev != NULL) ||
28417 	    (connp->conn_state_flags & CONN_CLOSING)) {
28418 		/*
28419 		 * The conn is already in the drain list, OR
28420 		 * the conn is closing. We need to check again for
28421 		 * the closing case again since close can happen
28422 		 * after we drop the conn_lock, and before we
28423 		 * acquire the CONN_DRAIN_LIST_LOCK.
28424 		 */
28425 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28426 		return;
28427 	} else {
28428 		idl = connp->conn_idl;
28429 	}
28430 
28431 	/*
28432 	 * The conn is not in the drain list. Insert it at the
28433 	 * tail of the drain list. The drain list is circular
28434 	 * and doubly linked. idl_conn points to the 1st element
28435 	 * in the list.
28436 	 */
28437 	if (idl->idl_conn == NULL) {
28438 		idl->idl_conn = connp;
28439 		connp->conn_drain_next = connp;
28440 		connp->conn_drain_prev = connp;
28441 	} else {
28442 		conn_t *head = idl->idl_conn;
28443 
28444 		connp->conn_drain_next = head;
28445 		connp->conn_drain_prev = head->conn_drain_prev;
28446 		head->conn_drain_prev->conn_drain_next = connp;
28447 		head->conn_drain_prev = connp;
28448 	}
28449 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28450 }
28451 
28452 /*
28453  * This conn is closing, and we are called from ip_close. OR
28454  * This conn has been serviced by ip_wsrv, and we need to do the tail
28455  * processing.
28456  * If this conn is part of the drain list, we may need to sustain the drain
28457  * process by qenabling the next conn in the drain list. We may also need to
28458  * remove this conn from the list, if it is done.
28459  */
28460 static void
28461 conn_drain_tail(conn_t *connp, boolean_t closing)
28462 {
28463 	idl_t *idl;
28464 
28465 	/*
28466 	 * connp->conn_idl is stable at this point, and no lock is needed
28467 	 * to check it. If we are called from ip_close, close has already
28468 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28469 	 * called us only because conn_idl is non-null. If we are called thru
28470 	 * service, conn_idl could be null, but it cannot change because
28471 	 * service is single-threaded per queue, and there cannot be another
28472 	 * instance of service trying to call conn_drain_insert on this conn
28473 	 * now.
28474 	 */
28475 	ASSERT(!closing || (connp->conn_idl != NULL));
28476 
28477 	/*
28478 	 * If connp->conn_idl is null, the conn has not been inserted into any
28479 	 * drain list even once since creation of the conn. Just return.
28480 	 */
28481 	if (connp->conn_idl == NULL)
28482 		return;
28483 
28484 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28485 
28486 	if (connp->conn_drain_prev == NULL) {
28487 		/* This conn is currently not in the drain list.  */
28488 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28489 		return;
28490 	}
28491 	idl = connp->conn_idl;
28492 	if (idl->idl_conn_draining == connp) {
28493 		/*
28494 		 * This conn is the current drainer. If this is the last conn
28495 		 * in the drain list, we need to do more checks, in the 'if'
28496 		 * below. Otherwwise we need to just qenable the next conn,
28497 		 * to sustain the draining, and is handled in the 'else'
28498 		 * below.
28499 		 */
28500 		if (connp->conn_drain_next == idl->idl_conn) {
28501 			/*
28502 			 * This conn is the last in this list. This round
28503 			 * of draining is complete. If idl_repeat is set,
28504 			 * it means another flow enabling has happened from
28505 			 * the driver/streams and we need to another round
28506 			 * of draining.
28507 			 * If there are more than 2 conns in the drain list,
28508 			 * do a left rotate by 1, so that all conns except the
28509 			 * conn at the head move towards the head by 1, and the
28510 			 * the conn at the head goes to the tail. This attempts
28511 			 * a more even share for all queues that are being
28512 			 * drained.
28513 			 */
28514 			if ((connp->conn_drain_next != connp) &&
28515 			    (idl->idl_conn->conn_drain_next != connp)) {
28516 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28517 			}
28518 			if (idl->idl_repeat) {
28519 				qenable(idl->idl_conn->conn_wq);
28520 				idl->idl_conn_draining = idl->idl_conn;
28521 				idl->idl_repeat = 0;
28522 			} else {
28523 				idl->idl_conn_draining = NULL;
28524 			}
28525 		} else {
28526 			/*
28527 			 * If the next queue that we are now qenable'ing,
28528 			 * is closing, it will remove itself from this list
28529 			 * and qenable the subsequent queue in ip_close().
28530 			 * Serialization is acheived thru idl_lock.
28531 			 */
28532 			qenable(connp->conn_drain_next->conn_wq);
28533 			idl->idl_conn_draining = connp->conn_drain_next;
28534 		}
28535 	}
28536 	if (!connp->conn_did_putbq || closing) {
28537 		/*
28538 		 * Remove ourself from the drain list, if we did not do
28539 		 * a putbq, or if the conn is closing.
28540 		 * Note: It is possible that q->q_first is non-null. It means
28541 		 * that these messages landed after we did a enableok() in
28542 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28543 		 * service them.
28544 		 */
28545 		if (connp->conn_drain_next == connp) {
28546 			/* Singleton in the list */
28547 			ASSERT(connp->conn_drain_prev == connp);
28548 			idl->idl_conn = NULL;
28549 			idl->idl_conn_draining = NULL;
28550 		} else {
28551 			connp->conn_drain_prev->conn_drain_next =
28552 			    connp->conn_drain_next;
28553 			connp->conn_drain_next->conn_drain_prev =
28554 			    connp->conn_drain_prev;
28555 			if (idl->idl_conn == connp)
28556 				idl->idl_conn = connp->conn_drain_next;
28557 			ASSERT(idl->idl_conn_draining != connp);
28558 
28559 		}
28560 		connp->conn_drain_next = NULL;
28561 		connp->conn_drain_prev = NULL;
28562 	}
28563 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28564 }
28565 
28566 /*
28567  * Write service routine. Shared perimeter entry point.
28568  * ip_wsrv can be called in any of the following ways.
28569  * 1. The device queue's messages has fallen below the low water mark
28570  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28571  *    the drain lists and backenable the first conn in each list.
28572  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28573  *    qenabled non-tcp upper layers. We start dequeing messages and call
28574  *    ip_wput for each message.
28575  */
28576 
28577 void
28578 ip_wsrv(queue_t *q)
28579 {
28580 	conn_t	*connp;
28581 	ill_t	*ill;
28582 	mblk_t	*mp;
28583 
28584 	if (q->q_next) {
28585 		ill = (ill_t *)q->q_ptr;
28586 		if (ill->ill_state_flags == 0) {
28587 			/*
28588 			 * The device flow control has opened up.
28589 			 * Walk through conn drain lists and qenable the
28590 			 * first conn in each list. This makes sense only
28591 			 * if the stream is fully plumbed and setup.
28592 			 * Hence the if check above.
28593 			 */
28594 			ip1dbg(("ip_wsrv: walking\n"));
28595 			conn_walk_drain(ill->ill_ipst);
28596 		}
28597 		return;
28598 	}
28599 
28600 	connp = Q_TO_CONN(q);
28601 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28602 
28603 	/*
28604 	 * 1. Set conn_draining flag to signal that service is active.
28605 	 *
28606 	 * 2. ip_output determines whether it has been called from service,
28607 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28608 	 *    has been called from service.
28609 	 *
28610 	 * 3. Message ordering is preserved by the following logic.
28611 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28612 	 *    the message at the tail, if conn_draining is set (i.e. service
28613 	 *    is running) or if q->q_first is non-null.
28614 	 *
28615 	 *    ii. If ip_output is called from service, and if ip_output cannot
28616 	 *    putnext due to flow control, it does a putbq.
28617 	 *
28618 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28619 	 *    (causing an infinite loop).
28620 	 */
28621 	ASSERT(!connp->conn_did_putbq);
28622 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28623 		connp->conn_draining = 1;
28624 		noenable(q);
28625 		while ((mp = getq(q)) != NULL) {
28626 			ASSERT(CONN_Q(q));
28627 
28628 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28629 			if (connp->conn_did_putbq) {
28630 				/* ip_wput did a putbq */
28631 				break;
28632 			}
28633 		}
28634 		/*
28635 		 * At this point, a thread coming down from top, calling
28636 		 * ip_wput, may end up queueing the message. We have not yet
28637 		 * enabled the queue, so ip_wsrv won't be called again.
28638 		 * To avoid this race, check q->q_first again (in the loop)
28639 		 * If the other thread queued the message before we call
28640 		 * enableok(), we will catch it in the q->q_first check.
28641 		 * If the other thread queues the message after we call
28642 		 * enableok(), ip_wsrv will be called again by STREAMS.
28643 		 */
28644 		connp->conn_draining = 0;
28645 		enableok(q);
28646 	}
28647 
28648 	/* Enable the next conn for draining */
28649 	conn_drain_tail(connp, B_FALSE);
28650 
28651 	connp->conn_did_putbq = 0;
28652 }
28653 
28654 /*
28655  * Walk the list of all conn's calling the function provided with the
28656  * specified argument for each.	 Note that this only walks conn's that
28657  * have been bound.
28658  * Applies to both IPv4 and IPv6.
28659  */
28660 static void
28661 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28662 {
28663 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28664 	    ipst->ips_ipcl_udp_fanout_size,
28665 	    func, arg, zoneid);
28666 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28667 	    ipst->ips_ipcl_conn_fanout_size,
28668 	    func, arg, zoneid);
28669 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28670 	    ipst->ips_ipcl_bind_fanout_size,
28671 	    func, arg, zoneid);
28672 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28673 	    IPPROTO_MAX, func, arg, zoneid);
28674 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28675 	    IPPROTO_MAX, func, arg, zoneid);
28676 }
28677 
28678 /*
28679  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28680  * of conns that need to be drained, check if drain is already in progress.
28681  * If so set the idl_repeat bit, indicating that the last conn in the list
28682  * needs to reinitiate the drain once again, for the list. If drain is not
28683  * in progress for the list, initiate the draining, by qenabling the 1st
28684  * conn in the list. The drain is self-sustaining, each qenabled conn will
28685  * in turn qenable the next conn, when it is done/blocked/closing.
28686  */
28687 static void
28688 conn_walk_drain(ip_stack_t *ipst)
28689 {
28690 	int i;
28691 	idl_t *idl;
28692 
28693 	IP_STAT(ipst, ip_conn_walk_drain);
28694 
28695 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28696 		idl = &ipst->ips_conn_drain_list[i];
28697 		mutex_enter(&idl->idl_lock);
28698 		if (idl->idl_conn == NULL) {
28699 			mutex_exit(&idl->idl_lock);
28700 			continue;
28701 		}
28702 		/*
28703 		 * If this list is not being drained currently by
28704 		 * an ip_wsrv thread, start the process.
28705 		 */
28706 		if (idl->idl_conn_draining == NULL) {
28707 			ASSERT(idl->idl_repeat == 0);
28708 			qenable(idl->idl_conn->conn_wq);
28709 			idl->idl_conn_draining = idl->idl_conn;
28710 		} else {
28711 			idl->idl_repeat = 1;
28712 		}
28713 		mutex_exit(&idl->idl_lock);
28714 	}
28715 }
28716 
28717 /*
28718  * Walk an conn hash table of `count' buckets, calling func for each entry.
28719  */
28720 static void
28721 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28722     zoneid_t zoneid)
28723 {
28724 	conn_t	*connp;
28725 
28726 	while (count-- > 0) {
28727 		mutex_enter(&connfp->connf_lock);
28728 		for (connp = connfp->connf_head; connp != NULL;
28729 		    connp = connp->conn_next) {
28730 			if (zoneid == GLOBAL_ZONEID ||
28731 			    zoneid == connp->conn_zoneid) {
28732 				CONN_INC_REF(connp);
28733 				mutex_exit(&connfp->connf_lock);
28734 				(*func)(connp, arg);
28735 				mutex_enter(&connfp->connf_lock);
28736 				CONN_DEC_REF(connp);
28737 			}
28738 		}
28739 		mutex_exit(&connfp->connf_lock);
28740 		connfp++;
28741 	}
28742 }
28743 
28744 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28745 static void
28746 conn_report1(conn_t *connp, void *mp)
28747 {
28748 	char	buf1[INET6_ADDRSTRLEN];
28749 	char	buf2[INET6_ADDRSTRLEN];
28750 	uint_t	print_len, buf_len;
28751 
28752 	ASSERT(connp != NULL);
28753 
28754 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28755 	if (buf_len <= 0)
28756 		return;
28757 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
28758 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
28759 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28760 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28761 	    "%5d %s/%05d %s/%05d\n",
28762 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28763 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28764 	    buf1, connp->conn_lport,
28765 	    buf2, connp->conn_fport);
28766 	if (print_len < buf_len) {
28767 		((mblk_t *)mp)->b_wptr += print_len;
28768 	} else {
28769 		((mblk_t *)mp)->b_wptr += buf_len;
28770 	}
28771 }
28772 
28773 /*
28774  * Named Dispatch routine to produce a formatted report on all conns
28775  * that are listed in one of the fanout tables.
28776  * This report is accessed by using the ndd utility to "get" ND variable
28777  * "ip_conn_status".
28778  */
28779 /* ARGSUSED */
28780 static int
28781 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28782 {
28783 	conn_t *connp = Q_TO_CONN(q);
28784 
28785 	(void) mi_mpprintf(mp,
28786 	    "CONN      " MI_COL_HDRPAD_STR
28787 	    "rfq      " MI_COL_HDRPAD_STR
28788 	    "stq      " MI_COL_HDRPAD_STR
28789 	    " zone local                 remote");
28790 
28791 	/*
28792 	 * Because of the ndd constraint, at most we can have 64K buffer
28793 	 * to put in all conn info.  So to be more efficient, just
28794 	 * allocate a 64K buffer here, assuming we need that large buffer.
28795 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28796 	 */
28797 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28798 		/* The following may work even if we cannot get a large buf. */
28799 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28800 		return (0);
28801 	}
28802 
28803 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28804 	    connp->conn_netstack->netstack_ip);
28805 	return (0);
28806 }
28807 
28808 /*
28809  * Determine if the ill and multicast aspects of that packets
28810  * "matches" the conn.
28811  */
28812 boolean_t
28813 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28814     zoneid_t zoneid)
28815 {
28816 	ill_t *in_ill;
28817 	boolean_t found;
28818 	ipif_t *ipif;
28819 	ire_t *ire;
28820 	ipaddr_t dst, src;
28821 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28822 
28823 	dst = ipha->ipha_dst;
28824 	src = ipha->ipha_src;
28825 
28826 	/*
28827 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28828 	 * unicast, broadcast and multicast reception to
28829 	 * conn_incoming_ill. conn_wantpacket itself is called
28830 	 * only for BROADCAST and multicast.
28831 	 *
28832 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28833 	 *    is part of a group. Hence, we should be receiving
28834 	 *    just one copy of broadcast for the whole group.
28835 	 *    Thus, if it is part of the group the packet could
28836 	 *    come on any ill of the group and hence we need a
28837 	 *    match on the group. Otherwise, match on ill should
28838 	 *    be sufficient.
28839 	 *
28840 	 * 2) ip_rput does not suppress duplicate multicast packets.
28841 	 *    If there are two interfaces in a ill group and we have
28842 	 *    2 applications (conns) joined a multicast group G on
28843 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28844 	 *    will give us two packets because we join G on both the
28845 	 *    interfaces rather than nominating just one interface
28846 	 *    for receiving multicast like broadcast above. So,
28847 	 *    we have to call ilg_lookup_ill to filter out duplicate
28848 	 *    copies, if ill is part of a group.
28849 	 */
28850 	in_ill = connp->conn_incoming_ill;
28851 	if (in_ill != NULL) {
28852 		if (in_ill->ill_group == NULL) {
28853 			if (in_ill != ill)
28854 				return (B_FALSE);
28855 		} else if (in_ill->ill_group != ill->ill_group) {
28856 			return (B_FALSE);
28857 		}
28858 	}
28859 
28860 	if (!CLASSD(dst)) {
28861 		if (IPCL_ZONE_MATCH(connp, zoneid))
28862 			return (B_TRUE);
28863 		/*
28864 		 * The conn is in a different zone; we need to check that this
28865 		 * broadcast address is configured in the application's zone and
28866 		 * on one ill in the group.
28867 		 */
28868 		ipif = ipif_get_next_ipif(NULL, ill);
28869 		if (ipif == NULL)
28870 			return (B_FALSE);
28871 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28872 		    connp->conn_zoneid, NULL,
28873 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28874 		ipif_refrele(ipif);
28875 		if (ire != NULL) {
28876 			ire_refrele(ire);
28877 			return (B_TRUE);
28878 		} else {
28879 			return (B_FALSE);
28880 		}
28881 	}
28882 
28883 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28884 	    connp->conn_zoneid == zoneid) {
28885 		/*
28886 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28887 		 * disabled, therefore we don't dispatch the multicast packet to
28888 		 * the sending zone.
28889 		 */
28890 		return (B_FALSE);
28891 	}
28892 
28893 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
28894 	    connp->conn_zoneid != zoneid) {
28895 		/*
28896 		 * Multicast packet on the loopback interface: we only match
28897 		 * conns who joined the group in the specified zone.
28898 		 */
28899 		return (B_FALSE);
28900 	}
28901 
28902 	if (connp->conn_multi_router) {
28903 		/* multicast packet and multicast router socket: send up */
28904 		return (B_TRUE);
28905 	}
28906 
28907 	mutex_enter(&connp->conn_lock);
28908 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28909 	mutex_exit(&connp->conn_lock);
28910 	return (found);
28911 }
28912 
28913 /*
28914  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28915  */
28916 /* ARGSUSED */
28917 static void
28918 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28919 {
28920 	ill_t *ill = (ill_t *)q->q_ptr;
28921 	mblk_t	*mp1, *mp2;
28922 	ipif_t  *ipif;
28923 	int err = 0;
28924 	conn_t *connp = NULL;
28925 	ipsq_t	*ipsq;
28926 	arc_t	*arc;
28927 
28928 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28929 
28930 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28931 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28932 
28933 	ASSERT(IAM_WRITER_ILL(ill));
28934 	mp2 = mp->b_cont;
28935 	mp->b_cont = NULL;
28936 
28937 	/*
28938 	 * We have now received the arp bringup completion message
28939 	 * from ARP. Mark the arp bringup as done. Also if the arp
28940 	 * stream has already started closing, send up the AR_ARP_CLOSING
28941 	 * ack now since ARP is waiting in close for this ack.
28942 	 */
28943 	mutex_enter(&ill->ill_lock);
28944 	ill->ill_arp_bringup_pending = 0;
28945 	if (ill->ill_arp_closing) {
28946 		mutex_exit(&ill->ill_lock);
28947 		/* Let's reuse the mp for sending the ack */
28948 		arc = (arc_t *)mp->b_rptr;
28949 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28950 		arc->arc_cmd = AR_ARP_CLOSING;
28951 		qreply(q, mp);
28952 	} else {
28953 		mutex_exit(&ill->ill_lock);
28954 		freeb(mp);
28955 	}
28956 
28957 	ipsq = ill->ill_phyint->phyint_ipsq;
28958 	ipif = ipsq->ipsq_pending_ipif;
28959 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28960 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28961 	if (mp1 == NULL) {
28962 		/* bringup was aborted by the user */
28963 		freemsg(mp2);
28964 		return;
28965 	}
28966 
28967 	/*
28968 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28969 	 * must have an associated conn_t.  Otherwise, we're bringing this
28970 	 * interface back up as part of handling an asynchronous event (e.g.,
28971 	 * physical address change).
28972 	 */
28973 	if (ipsq->ipsq_current_ioctl != 0) {
28974 		ASSERT(connp != NULL);
28975 		q = CONNP_TO_WQ(connp);
28976 	} else {
28977 		ASSERT(connp == NULL);
28978 		q = ill->ill_rq;
28979 	}
28980 
28981 	/*
28982 	 * If the DL_BIND_REQ fails, it is noted
28983 	 * in arc_name_offset.
28984 	 */
28985 	err = *((int *)mp2->b_rptr);
28986 	if (err == 0) {
28987 		if (ipif->ipif_isv6) {
28988 			if ((err = ipif_up_done_v6(ipif)) != 0)
28989 				ip0dbg(("ip_arp_done: init failed\n"));
28990 		} else {
28991 			if ((err = ipif_up_done(ipif)) != 0)
28992 				ip0dbg(("ip_arp_done: init failed\n"));
28993 		}
28994 	} else {
28995 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28996 	}
28997 
28998 	freemsg(mp2);
28999 
29000 	if ((err == 0) && (ill->ill_up_ipifs)) {
29001 		err = ill_up_ipifs(ill, q, mp1);
29002 		if (err == EINPROGRESS)
29003 			return;
29004 	}
29005 
29006 	if (ill->ill_up_ipifs)
29007 		ill_group_cleanup(ill);
29008 
29009 	/*
29010 	 * The operation must complete without EINPROGRESS since
29011 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29012 	 * Otherwise, the operation will be stuck forever in the ipsq.
29013 	 */
29014 	ASSERT(err != EINPROGRESS);
29015 	if (ipsq->ipsq_current_ioctl != 0)
29016 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29017 	else
29018 		ipsq_current_finish(ipsq);
29019 }
29020 
29021 /* Allocate the private structure */
29022 static int
29023 ip_priv_alloc(void **bufp)
29024 {
29025 	void	*buf;
29026 
29027 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29028 		return (ENOMEM);
29029 
29030 	*bufp = buf;
29031 	return (0);
29032 }
29033 
29034 /* Function to delete the private structure */
29035 void
29036 ip_priv_free(void *buf)
29037 {
29038 	ASSERT(buf != NULL);
29039 	kmem_free(buf, sizeof (ip_priv_t));
29040 }
29041 
29042 /*
29043  * The entry point for IPPF processing.
29044  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29045  * routine just returns.
29046  *
29047  * When called, ip_process generates an ipp_packet_t structure
29048  * which holds the state information for this packet and invokes the
29049  * the classifier (via ipp_packet_process). The classification, depending on
29050  * configured filters, results in a list of actions for this packet. Invoking
29051  * an action may cause the packet to be dropped, in which case the resulting
29052  * mblk (*mpp) is NULL. proc indicates the callout position for
29053  * this packet and ill_index is the interface this packet on or will leave
29054  * on (inbound and outbound resp.).
29055  */
29056 void
29057 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29058 {
29059 	mblk_t		*mp;
29060 	ip_priv_t	*priv;
29061 	ipp_action_id_t	aid;
29062 	int		rc = 0;
29063 	ipp_packet_t	*pp;
29064 #define	IP_CLASS	"ip"
29065 
29066 	/* If the classifier is not loaded, return  */
29067 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29068 		return;
29069 	}
29070 
29071 	mp = *mpp;
29072 	ASSERT(mp != NULL);
29073 
29074 	/* Allocate the packet structure */
29075 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29076 	if (rc != 0) {
29077 		*mpp = NULL;
29078 		freemsg(mp);
29079 		return;
29080 	}
29081 
29082 	/* Allocate the private structure */
29083 	rc = ip_priv_alloc((void **)&priv);
29084 	if (rc != 0) {
29085 		*mpp = NULL;
29086 		freemsg(mp);
29087 		ipp_packet_free(pp);
29088 		return;
29089 	}
29090 	priv->proc = proc;
29091 	priv->ill_index = ill_index;
29092 	ipp_packet_set_private(pp, priv, ip_priv_free);
29093 	ipp_packet_set_data(pp, mp);
29094 
29095 	/* Invoke the classifier */
29096 	rc = ipp_packet_process(&pp);
29097 	if (pp != NULL) {
29098 		mp = ipp_packet_get_data(pp);
29099 		ipp_packet_free(pp);
29100 		if (rc != 0) {
29101 			freemsg(mp);
29102 			*mpp = NULL;
29103 		}
29104 	} else {
29105 		*mpp = NULL;
29106 	}
29107 #undef	IP_CLASS
29108 }
29109 
29110 /*
29111  * Propagate a multicast group membership operation (add/drop) on
29112  * all the interfaces crossed by the related multirt routes.
29113  * The call is considered successful if the operation succeeds
29114  * on at least one interface.
29115  */
29116 static int
29117 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29118     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29119     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29120     mblk_t *first_mp)
29121 {
29122 	ire_t		*ire_gw;
29123 	irb_t		*irb;
29124 	int		error = 0;
29125 	opt_restart_t	*or;
29126 	ip_stack_t	*ipst = ire->ire_ipst;
29127 
29128 	irb = ire->ire_bucket;
29129 	ASSERT(irb != NULL);
29130 
29131 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29132 
29133 	or = (opt_restart_t *)first_mp->b_rptr;
29134 	IRB_REFHOLD(irb);
29135 	for (; ire != NULL; ire = ire->ire_next) {
29136 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29137 			continue;
29138 		if (ire->ire_addr != group)
29139 			continue;
29140 
29141 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29142 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29143 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29144 		/* No resolver exists for the gateway; skip this ire. */
29145 		if (ire_gw == NULL)
29146 			continue;
29147 
29148 		/*
29149 		 * This function can return EINPROGRESS. If so the operation
29150 		 * will be restarted from ip_restart_optmgmt which will
29151 		 * call ip_opt_set and option processing will restart for
29152 		 * this option. So we may end up calling 'fn' more than once.
29153 		 * This requires that 'fn' is idempotent except for the
29154 		 * return value. The operation is considered a success if
29155 		 * it succeeds at least once on any one interface.
29156 		 */
29157 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29158 		    NULL, fmode, src, first_mp);
29159 		if (error == 0)
29160 			or->or_private = CGTP_MCAST_SUCCESS;
29161 
29162 		if (ip_debug > 0) {
29163 			ulong_t	off;
29164 			char	*ksym;
29165 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29166 			ip2dbg(("ip_multirt_apply_membership: "
29167 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29168 			    "error %d [success %u]\n",
29169 			    ksym ? ksym : "?",
29170 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29171 			    error, or->or_private));
29172 		}
29173 
29174 		ire_refrele(ire_gw);
29175 		if (error == EINPROGRESS) {
29176 			IRB_REFRELE(irb);
29177 			return (error);
29178 		}
29179 	}
29180 	IRB_REFRELE(irb);
29181 	/*
29182 	 * Consider the call as successful if we succeeded on at least
29183 	 * one interface. Otherwise, return the last encountered error.
29184 	 */
29185 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29186 }
29187 
29188 
29189 /*
29190  * Issue a warning regarding a route crossing an interface with an
29191  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29192  * amount of time is logged.
29193  */
29194 static void
29195 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29196 {
29197 	hrtime_t	current = gethrtime();
29198 	char		buf[INET_ADDRSTRLEN];
29199 	ip_stack_t	*ipst = ire->ire_ipst;
29200 
29201 	/* Convert interval in ms to hrtime in ns */
29202 	if (ipst->ips_multirt_bad_mtu_last_time +
29203 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29204 	    current) {
29205 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29206 		    "to %s, incorrect MTU %u (expected %u)\n",
29207 		    ip_dot_addr(ire->ire_addr, buf),
29208 		    ire->ire_max_frag, max_frag);
29209 
29210 		ipst->ips_multirt_bad_mtu_last_time = current;
29211 	}
29212 }
29213 
29214 
29215 /*
29216  * Get the CGTP (multirouting) filtering status.
29217  * If 0, the CGTP hooks are transparent.
29218  */
29219 /* ARGSUSED */
29220 static int
29221 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29222 {
29223 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29224 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29225 
29226 	/*
29227 	 * Only applies to the shared stack since the filter_ops
29228 	 * do not carry an ip_stack_t or zoneid.
29229 	 */
29230 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29231 		return (ENOTSUP);
29232 
29233 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29234 	return (0);
29235 }
29236 
29237 
29238 /*
29239  * Set the CGTP (multirouting) filtering status.
29240  * If the status is changed from active to transparent
29241  * or from transparent to active, forward the new status
29242  * to the filtering module (if loaded).
29243  */
29244 /* ARGSUSED */
29245 static int
29246 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29247     cred_t *ioc_cr)
29248 {
29249 	long		new_value;
29250 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29251 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29252 
29253 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
29254 		return (EPERM);
29255 
29256 	/*
29257 	 * Only applies to the shared stack since the filter_ops
29258 	 * do not carry an ip_stack_t or zoneid.
29259 	 */
29260 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29261 		return (ENOTSUP);
29262 
29263 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29264 	    new_value < 0 || new_value > 1) {
29265 		return (EINVAL);
29266 	}
29267 
29268 	/*
29269 	 * Do not enable CGTP filtering - thus preventing the hooks
29270 	 * from being invoked - if the version number of the
29271 	 * filtering module hooks does not match.
29272 	 */
29273 	if ((ip_cgtp_filter_ops != NULL) &&
29274 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29275 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29276 		    "(module hooks version %d, expecting %d)\n",
29277 		    ip_cgtp_filter_ops->cfo_filter_rev,
29278 		    CGTP_FILTER_REV);
29279 		return (ENOTSUP);
29280 	}
29281 
29282 	if ((!*ip_cgtp_filter_value) && new_value) {
29283 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29284 		    ip_cgtp_filter_ops == NULL ?
29285 		    " (module not loaded)" : "");
29286 	}
29287 	if (*ip_cgtp_filter_value && (!new_value)) {
29288 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29289 		    ip_cgtp_filter_ops == NULL ?
29290 		    " (module not loaded)" : "");
29291 	}
29292 
29293 	if (ip_cgtp_filter_ops != NULL) {
29294 		int	res;
29295 
29296 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
29297 		if (res)
29298 			return (res);
29299 	}
29300 
29301 	*ip_cgtp_filter_value = (boolean_t)new_value;
29302 
29303 	return (0);
29304 }
29305 
29306 
29307 /*
29308  * Return the expected CGTP hooks version number.
29309  */
29310 int
29311 ip_cgtp_filter_supported(void)
29312 {
29313 	ip_stack_t *ipst;
29314 	int ret;
29315 
29316 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29317 	if (ipst == NULL)
29318 		return (-1);
29319 	ret = ip_cgtp_filter_rev;
29320 	netstack_rele(ipst->ips_netstack);
29321 	return (ret);
29322 }
29323 
29324 
29325 /*
29326  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29327  * or by invoking this function. In the first case, the version number
29328  * of the registered structure is checked at hooks activation time
29329  * in ip_cgtp_filter_set().
29330  *
29331  * Only applies to the shared stack since the filter_ops
29332  * do not carry an ip_stack_t or zoneid.
29333  */
29334 int
29335 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29336 {
29337 	ip_stack_t *ipst;
29338 
29339 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29340 		return (ENOTSUP);
29341 
29342 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29343 	if (ipst == NULL)
29344 		return (EINVAL);
29345 
29346 	ip_cgtp_filter_ops = ops;
29347 	netstack_rele(ipst->ips_netstack);
29348 	return (0);
29349 }
29350 
29351 static squeue_func_t
29352 ip_squeue_switch(int val)
29353 {
29354 	squeue_func_t rval = squeue_fill;
29355 
29356 	switch (val) {
29357 	case IP_SQUEUE_ENTER_NODRAIN:
29358 		rval = squeue_enter_nodrain;
29359 		break;
29360 	case IP_SQUEUE_ENTER:
29361 		rval = squeue_enter;
29362 		break;
29363 	default:
29364 		break;
29365 	}
29366 	return (rval);
29367 }
29368 
29369 /* ARGSUSED */
29370 static int
29371 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29372     caddr_t addr, cred_t *cr)
29373 {
29374 	int *v = (int *)addr;
29375 	long new_value;
29376 
29377 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29378 		return (EPERM);
29379 
29380 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29381 		return (EINVAL);
29382 
29383 	ip_input_proc = ip_squeue_switch(new_value);
29384 	*v = new_value;
29385 	return (0);
29386 }
29387 
29388 /* ARGSUSED */
29389 static int
29390 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29391     caddr_t addr, cred_t *cr)
29392 {
29393 	int *v = (int *)addr;
29394 	long new_value;
29395 
29396 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29397 		return (EPERM);
29398 
29399 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29400 		return (EINVAL);
29401 
29402 	*v = new_value;
29403 	return (0);
29404 }
29405 
29406 /*
29407  * Handle changes to ipmp_hook_emulation ndd variable.
29408  * Need to update phyint_hook_ifindex.
29409  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29410  */
29411 static void
29412 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29413 {
29414 	phyint_t *phyi;
29415 	phyint_t *phyi_tmp;
29416 	char *groupname;
29417 	int namelen;
29418 	ill_t	*ill;
29419 	boolean_t new_group;
29420 
29421 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29422 	/*
29423 	 * Group indicies are stored in the phyint - a common structure
29424 	 * to both IPv4 and IPv6.
29425 	 */
29426 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29427 	for (; phyi != NULL;
29428 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29429 	    phyi, AVL_AFTER)) {
29430 		/* Ignore the ones that do not have a group */
29431 		if (phyi->phyint_groupname_len == 0)
29432 			continue;
29433 
29434 		/*
29435 		 * Look for other phyint in group.
29436 		 * Clear name/namelen so the lookup doesn't find ourselves.
29437 		 */
29438 		namelen = phyi->phyint_groupname_len;
29439 		groupname = phyi->phyint_groupname;
29440 		phyi->phyint_groupname_len = 0;
29441 		phyi->phyint_groupname = NULL;
29442 
29443 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29444 		/* Restore */
29445 		phyi->phyint_groupname_len = namelen;
29446 		phyi->phyint_groupname = groupname;
29447 
29448 		new_group = B_FALSE;
29449 		if (ipst->ips_ipmp_hook_emulation) {
29450 			/*
29451 			 * If the group already exists and has already
29452 			 * been assigned a group ifindex, we use the existing
29453 			 * group_ifindex, otherwise we pick a new group_ifindex
29454 			 * here.
29455 			 */
29456 			if (phyi_tmp != NULL &&
29457 			    phyi_tmp->phyint_group_ifindex != 0) {
29458 				phyi->phyint_group_ifindex =
29459 				    phyi_tmp->phyint_group_ifindex;
29460 			} else {
29461 				/* XXX We need a recovery strategy here. */
29462 				if (!ip_assign_ifindex(
29463 				    &phyi->phyint_group_ifindex, ipst))
29464 					cmn_err(CE_PANIC,
29465 					    "ip_assign_ifindex() failed");
29466 				new_group = B_TRUE;
29467 			}
29468 		} else {
29469 			phyi->phyint_group_ifindex = 0;
29470 		}
29471 		if (ipst->ips_ipmp_hook_emulation)
29472 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29473 		else
29474 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29475 
29476 		/*
29477 		 * For IP Filter to find out the relationship between
29478 		 * names and interface indicies, we need to generate
29479 		 * a NE_PLUMB event when a new group can appear.
29480 		 * We always generate events when a new interface appears
29481 		 * (even when ipmp_hook_emulation is set) so there
29482 		 * is no need to generate NE_PLUMB events when
29483 		 * ipmp_hook_emulation is turned off.
29484 		 * And since it isn't critical for IP Filter to get
29485 		 * the NE_UNPLUMB events we skip those here.
29486 		 */
29487 		if (new_group) {
29488 			/*
29489 			 * First phyint in group - generate group PLUMB event.
29490 			 * Since we are not running inside the ipsq we do
29491 			 * the dispatch immediately.
29492 			 */
29493 			if (phyi->phyint_illv4 != NULL)
29494 				ill = phyi->phyint_illv4;
29495 			else
29496 				ill = phyi->phyint_illv6;
29497 
29498 			if (ill != NULL) {
29499 				mutex_enter(&ill->ill_lock);
29500 				ill_nic_info_plumb(ill, B_TRUE);
29501 				ill_nic_info_dispatch(ill);
29502 				mutex_exit(&ill->ill_lock);
29503 			}
29504 		}
29505 	}
29506 	rw_exit(&ipst->ips_ill_g_lock);
29507 }
29508 
29509 /* ARGSUSED */
29510 static int
29511 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29512     caddr_t addr, cred_t *cr)
29513 {
29514 	int *v = (int *)addr;
29515 	long new_value;
29516 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29517 
29518 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29519 		return (EINVAL);
29520 
29521 	if (*v != new_value) {
29522 		*v = new_value;
29523 		ipmp_hook_emulation_changed(ipst);
29524 	}
29525 	return (0);
29526 }
29527 
29528 static void *
29529 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29530 {
29531 	kstat_t *ksp;
29532 
29533 	ip_stat_t template = {
29534 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29535 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29536 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29537 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29538 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29539 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29540 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29541 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29542 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29543 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29544 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29545 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29546 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29547 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29548 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29549 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29550 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29551 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29552 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29553 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29554 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29555 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29556 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29557 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29558 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29559 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29560 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29561 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29562 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29563 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29564 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29565 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29566 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29567 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29568 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29569 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29570 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29571 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29572 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29573 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29574 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29575 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29576 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29577 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29578 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29579 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29580 	};
29581 
29582 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29583 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29584 	    KSTAT_FLAG_VIRTUAL, stackid);
29585 
29586 	if (ksp == NULL)
29587 		return (NULL);
29588 
29589 	bcopy(&template, ip_statisticsp, sizeof (template));
29590 	ksp->ks_data = (void *)ip_statisticsp;
29591 	ksp->ks_private = (void *)(uintptr_t)stackid;
29592 
29593 	kstat_install(ksp);
29594 	return (ksp);
29595 }
29596 
29597 static void
29598 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29599 {
29600 	if (ksp != NULL) {
29601 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29602 		kstat_delete_netstack(ksp, stackid);
29603 	}
29604 }
29605 
29606 static void *
29607 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29608 {
29609 	kstat_t	*ksp;
29610 
29611 	ip_named_kstat_t template = {
29612 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29613 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29614 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29615 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29616 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29617 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29618 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29619 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29620 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29621 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29622 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29623 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29624 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29625 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29626 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29627 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29628 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29629 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29630 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29631 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29632 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29633 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29634 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29635 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29636 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29637 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29638 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29639 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29640 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29641 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29642 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29643 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29644 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29645 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29646 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29647 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29648 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29649 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29650 	};
29651 
29652 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29653 					NUM_OF_FIELDS(ip_named_kstat_t),
29654 					0, stackid);
29655 	if (ksp == NULL || ksp->ks_data == NULL)
29656 		return (NULL);
29657 
29658 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29659 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29660 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29661 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29662 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29663 
29664 	template.netToMediaEntrySize.value.i32 =
29665 		sizeof (mib2_ipNetToMediaEntry_t);
29666 
29667 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29668 
29669 	bcopy(&template, ksp->ks_data, sizeof (template));
29670 	ksp->ks_update = ip_kstat_update;
29671 	ksp->ks_private = (void *)(uintptr_t)stackid;
29672 
29673 	kstat_install(ksp);
29674 	return (ksp);
29675 }
29676 
29677 static void
29678 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29679 {
29680 	if (ksp != NULL) {
29681 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29682 		kstat_delete_netstack(ksp, stackid);
29683 	}
29684 }
29685 
29686 static int
29687 ip_kstat_update(kstat_t *kp, int rw)
29688 {
29689 	ip_named_kstat_t *ipkp;
29690 	mib2_ipIfStatsEntry_t ipmib;
29691 	ill_walk_context_t ctx;
29692 	ill_t *ill;
29693 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29694 	netstack_t	*ns;
29695 	ip_stack_t	*ipst;
29696 
29697 	if (kp == NULL || kp->ks_data == NULL)
29698 		return (EIO);
29699 
29700 	if (rw == KSTAT_WRITE)
29701 		return (EACCES);
29702 
29703 	ns = netstack_find_by_stackid(stackid);
29704 	if (ns == NULL)
29705 		return (-1);
29706 	ipst = ns->netstack_ip;
29707 	if (ipst == NULL) {
29708 		netstack_rele(ns);
29709 		return (-1);
29710 	}
29711 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29712 
29713 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29714 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29715 	ill = ILL_START_WALK_V4(&ctx, ipst);
29716 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29717 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29718 	rw_exit(&ipst->ips_ill_g_lock);
29719 
29720 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29721 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29722 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29723 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29724 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29725 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29726 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29727 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29728 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29729 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29730 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29731 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29732 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29733 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29734 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29735 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29736 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29737 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29738 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29739 
29740 	ipkp->routingDiscards.value.ui32 =	0;
29741 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29742 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29743 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29744 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29745 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29746 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29747 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29748 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29749 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29750 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29751 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29752 
29753 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29754 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29755 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29756 
29757 	netstack_rele(ns);
29758 
29759 	return (0);
29760 }
29761 
29762 static void *
29763 icmp_kstat_init(netstackid_t stackid)
29764 {
29765 	kstat_t	*ksp;
29766 
29767 	icmp_named_kstat_t template = {
29768 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29769 		{ "inErrors",		KSTAT_DATA_UINT32 },
29770 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29771 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29772 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29773 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29774 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29775 		{ "inEchos",		KSTAT_DATA_UINT32 },
29776 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29777 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29778 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29779 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29780 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29781 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29782 		{ "outErrors",		KSTAT_DATA_UINT32 },
29783 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29784 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29785 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29786 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29787 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29788 		{ "outEchos",		KSTAT_DATA_UINT32 },
29789 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29790 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29791 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29792 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29793 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29794 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29795 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29796 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29797 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29798 		{ "outDrops",		KSTAT_DATA_UINT32 },
29799 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29800 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29801 	};
29802 
29803 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29804 					NUM_OF_FIELDS(icmp_named_kstat_t),
29805 					0, stackid);
29806 	if (ksp == NULL || ksp->ks_data == NULL)
29807 		return (NULL);
29808 
29809 	bcopy(&template, ksp->ks_data, sizeof (template));
29810 
29811 	ksp->ks_update = icmp_kstat_update;
29812 	ksp->ks_private = (void *)(uintptr_t)stackid;
29813 
29814 	kstat_install(ksp);
29815 	return (ksp);
29816 }
29817 
29818 static void
29819 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29820 {
29821 	if (ksp != NULL) {
29822 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29823 		kstat_delete_netstack(ksp, stackid);
29824 	}
29825 }
29826 
29827 static int
29828 icmp_kstat_update(kstat_t *kp, int rw)
29829 {
29830 	icmp_named_kstat_t *icmpkp;
29831 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29832 	netstack_t	*ns;
29833 	ip_stack_t	*ipst;
29834 
29835 	if ((kp == NULL) || (kp->ks_data == NULL))
29836 		return (EIO);
29837 
29838 	if (rw == KSTAT_WRITE)
29839 		return (EACCES);
29840 
29841 	ns = netstack_find_by_stackid(stackid);
29842 	if (ns == NULL)
29843 		return (-1);
29844 	ipst = ns->netstack_ip;
29845 	if (ipst == NULL) {
29846 		netstack_rele(ns);
29847 		return (-1);
29848 	}
29849 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29850 
29851 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29852 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29853 	icmpkp->inDestUnreachs.value.ui32 =
29854 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29855 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29856 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29857 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29858 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29859 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29860 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29861 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29862 	icmpkp->inTimestampReps.value.ui32 =
29863 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29864 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29865 	icmpkp->inAddrMaskReps.value.ui32 =
29866 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29867 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29868 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29869 	icmpkp->outDestUnreachs.value.ui32 =
29870 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29871 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29872 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29873 	icmpkp->outSrcQuenchs.value.ui32 =
29874 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29875 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29876 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29877 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29878 	icmpkp->outTimestamps.value.ui32 =
29879 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29880 	icmpkp->outTimestampReps.value.ui32 =
29881 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29882 	icmpkp->outAddrMasks.value.ui32 =
29883 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29884 	icmpkp->outAddrMaskReps.value.ui32 =
29885 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29886 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29887 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29888 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29889 	icmpkp->outFragNeeded.value.ui32 =
29890 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29891 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29892 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29893 	icmpkp->inBadRedirects.value.ui32 =
29894 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29895 
29896 	netstack_rele(ns);
29897 	return (0);
29898 }
29899 
29900 /*
29901  * This is the fanout function for raw socket opened for SCTP.  Note
29902  * that it is called after SCTP checks that there is no socket which
29903  * wants a packet.  Then before SCTP handles this out of the blue packet,
29904  * this function is called to see if there is any raw socket for SCTP.
29905  * If there is and it is bound to the correct address, the packet will
29906  * be sent to that socket.  Note that only one raw socket can be bound to
29907  * a port.  This is assured in ipcl_sctp_hash_insert();
29908  */
29909 void
29910 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29911     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29912     zoneid_t zoneid)
29913 {
29914 	conn_t		*connp;
29915 	queue_t		*rq;
29916 	mblk_t		*first_mp;
29917 	boolean_t	secure;
29918 	ip6_t		*ip6h;
29919 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29920 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29921 
29922 	first_mp = mp;
29923 	if (mctl_present) {
29924 		mp = first_mp->b_cont;
29925 		secure = ipsec_in_is_secure(first_mp);
29926 		ASSERT(mp != NULL);
29927 	} else {
29928 		secure = B_FALSE;
29929 	}
29930 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29931 
29932 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29933 	if (connp == NULL) {
29934 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29935 		return;
29936 	}
29937 	rq = connp->conn_rq;
29938 	if (!canputnext(rq)) {
29939 		CONN_DEC_REF(connp);
29940 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29941 		freemsg(first_mp);
29942 		return;
29943 	}
29944 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29945 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29946 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29947 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29948 		if (first_mp == NULL) {
29949 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29950 			CONN_DEC_REF(connp);
29951 			return;
29952 		}
29953 	}
29954 	/*
29955 	 * We probably should not send M_CTL message up to
29956 	 * raw socket.
29957 	 */
29958 	if (mctl_present)
29959 		freeb(first_mp);
29960 
29961 	/* Initiate IPPF processing here if needed. */
29962 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29963 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29964 		ip_process(IPP_LOCAL_IN, &mp,
29965 		    recv_ill->ill_phyint->phyint_ifindex);
29966 		if (mp == NULL) {
29967 			CONN_DEC_REF(connp);
29968 			return;
29969 		}
29970 	}
29971 
29972 	if (connp->conn_recvif || connp->conn_recvslla ||
29973 	    ((connp->conn_ip_recvpktinfo ||
29974 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29975 	    (flags & IP_FF_IPINFO))) {
29976 		int in_flags = 0;
29977 
29978 		/*
29979 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29980 		 * IPF_RECVIF.
29981 		 */
29982 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29983 			in_flags = IPF_RECVIF;
29984 		}
29985 		if (connp->conn_recvslla) {
29986 			in_flags |= IPF_RECVSLLA;
29987 		}
29988 		if (isv4) {
29989 			mp = ip_add_info(mp, recv_ill, in_flags,
29990 			    IPCL_ZONEID(connp), ipst);
29991 		} else {
29992 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29993 			if (mp == NULL) {
29994 				BUMP_MIB(recv_ill->ill_ip_mib,
29995 				    ipIfStatsInDiscards);
29996 				CONN_DEC_REF(connp);
29997 				return;
29998 			}
29999 		}
30000 	}
30001 
30002 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
30003 	/*
30004 	 * We are sending the IPSEC_IN message also up. Refer
30005 	 * to comments above this function.
30006 	 */
30007 	putnext(rq, mp);
30008 	CONN_DEC_REF(connp);
30009 }
30010 
30011 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30012 {									\
30013 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30014 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30015 }
30016 /*
30017  * This function should be called only if all packet processing
30018  * including fragmentation is complete. Callers of this function
30019  * must set mp->b_prev to one of these values:
30020  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30021  * prior to handing over the mp as first argument to this function.
30022  *
30023  * If the ire passed by caller is incomplete, this function
30024  * queues the packet and if necessary, sends ARP request and bails.
30025  * If the ire passed is fully resolved, we simply prepend
30026  * the link-layer header to the packet, do ipsec hw acceleration
30027  * work if necessary, and send the packet out on the wire.
30028  *
30029  * NOTE: IPSEC will only call this function with fully resolved
30030  * ires if hw acceleration is involved.
30031  * TODO list :
30032  * 	a Handle M_MULTIDATA so that
30033  *	  tcp_multisend->tcp_multisend_data can
30034  *	  call ip_xmit_v4 directly
30035  *	b Handle post-ARP work for fragments so that
30036  *	  ip_wput_frag can call this function.
30037  */
30038 ipxmit_state_t
30039 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
30040 {
30041 	nce_t		*arpce;
30042 	queue_t		*q;
30043 	int		ill_index;
30044 	mblk_t		*nxt_mp, *first_mp;
30045 	boolean_t	xmit_drop = B_FALSE;
30046 	ip_proc_t	proc;
30047 	ill_t		*out_ill;
30048 	int		pkt_len;
30049 
30050 	arpce = ire->ire_nce;
30051 	ASSERT(arpce != NULL);
30052 
30053 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30054 
30055 	mutex_enter(&arpce->nce_lock);
30056 	switch (arpce->nce_state) {
30057 	case ND_REACHABLE:
30058 		/* If there are other queued packets, queue this packet */
30059 		if (arpce->nce_qd_mp != NULL) {
30060 			if (mp != NULL)
30061 				nce_queue_mp_common(arpce, mp, B_FALSE);
30062 			mp = arpce->nce_qd_mp;
30063 		}
30064 		arpce->nce_qd_mp = NULL;
30065 		mutex_exit(&arpce->nce_lock);
30066 
30067 		/*
30068 		 * Flush the queue.  In the common case, where the
30069 		 * ARP is already resolved,  it will go through the
30070 		 * while loop only once.
30071 		 */
30072 		while (mp != NULL) {
30073 
30074 			nxt_mp = mp->b_next;
30075 			mp->b_next = NULL;
30076 			ASSERT(mp->b_datap->db_type != M_CTL);
30077 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30078 			/*
30079 			 * This info is needed for IPQOS to do COS marking
30080 			 * in ip_wput_attach_llhdr->ip_process.
30081 			 */
30082 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30083 			mp->b_prev = NULL;
30084 
30085 			/* set up ill index for outbound qos processing */
30086 			out_ill = ire->ire_ipif->ipif_ill;
30087 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30088 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30089 			    ill_index);
30090 			if (first_mp == NULL) {
30091 				xmit_drop = B_TRUE;
30092 				BUMP_MIB(out_ill->ill_ip_mib,
30093 				    ipIfStatsOutDiscards);
30094 				goto next_mp;
30095 			}
30096 			/* non-ipsec hw accel case */
30097 			if (io == NULL || !io->ipsec_out_accelerated) {
30098 				/* send it */
30099 				q = ire->ire_stq;
30100 				if (proc == IPP_FWD_OUT) {
30101 					UPDATE_IB_PKT_COUNT(ire);
30102 				} else {
30103 					UPDATE_OB_PKT_COUNT(ire);
30104 				}
30105 				ire->ire_last_used_time = lbolt;
30106 
30107 				if (flow_ctl_enabled || canputnext(q))  {
30108 					if (proc == IPP_FWD_OUT) {
30109 						BUMP_MIB(out_ill->ill_ip_mib,
30110 						ipIfStatsHCOutForwDatagrams);
30111 					}
30112 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30113 					    pkt_len);
30114 
30115 					putnext(q, first_mp);
30116 				} else {
30117 					BUMP_MIB(out_ill->ill_ip_mib,
30118 					    ipIfStatsOutDiscards);
30119 					xmit_drop = B_TRUE;
30120 					freemsg(first_mp);
30121 				}
30122 			} else {
30123 				/*
30124 				 * Safety Pup says: make sure this
30125 				 *  is going to the right interface!
30126 				 */
30127 				ill_t *ill1 =
30128 				    (ill_t *)ire->ire_stq->q_ptr;
30129 				int ifindex =
30130 				    ill1->ill_phyint->phyint_ifindex;
30131 				if (ifindex !=
30132 				    io->ipsec_out_capab_ill_index) {
30133 					xmit_drop = B_TRUE;
30134 					freemsg(mp);
30135 				} else {
30136 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30137 					    pkt_len);
30138 					ipsec_hw_putnext(ire->ire_stq, mp);
30139 				}
30140 			}
30141 next_mp:
30142 			mp = nxt_mp;
30143 		} /* while (mp != NULL) */
30144 		if (xmit_drop)
30145 			return (SEND_FAILED);
30146 		else
30147 			return (SEND_PASSED);
30148 
30149 	case ND_INITIAL:
30150 	case ND_INCOMPLETE:
30151 
30152 		/*
30153 		 * While we do send off packets to dests that
30154 		 * use fully-resolved CGTP routes, we do not
30155 		 * handle unresolved CGTP routes.
30156 		 */
30157 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30158 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30159 
30160 		if (mp != NULL) {
30161 			/* queue the packet */
30162 			nce_queue_mp_common(arpce, mp, B_FALSE);
30163 		}
30164 
30165 		if (arpce->nce_state == ND_INCOMPLETE) {
30166 			mutex_exit(&arpce->nce_lock);
30167 			DTRACE_PROBE3(ip__xmit__incomplete,
30168 			    (ire_t *), ire, (mblk_t *), mp,
30169 			    (ipsec_out_t *), io);
30170 			return (LOOKUP_IN_PROGRESS);
30171 		}
30172 
30173 		arpce->nce_state = ND_INCOMPLETE;
30174 		mutex_exit(&arpce->nce_lock);
30175 		/*
30176 		 * Note that ire_add() (called from ire_forward())
30177 		 * holds a ref on the ire until ARP is completed.
30178 		 */
30179 
30180 		ire_arpresolve(ire, ire_to_ill(ire));
30181 		return (LOOKUP_IN_PROGRESS);
30182 	default:
30183 		ASSERT(0);
30184 		mutex_exit(&arpce->nce_lock);
30185 		return (LLHDR_RESLV_FAILED);
30186 	}
30187 }
30188 
30189 #undef	UPDATE_IP_MIB_OB_COUNTERS
30190 
30191 /*
30192  * Return B_TRUE if the buffers differ in length or content.
30193  * This is used for comparing extension header buffers.
30194  * Note that an extension header would be declared different
30195  * even if all that changed was the next header value in that header i.e.
30196  * what really changed is the next extension header.
30197  */
30198 boolean_t
30199 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30200     uint_t blen)
30201 {
30202 	if (!b_valid)
30203 		blen = 0;
30204 
30205 	if (alen != blen)
30206 		return (B_TRUE);
30207 	if (alen == 0)
30208 		return (B_FALSE);	/* Both zero length */
30209 	return (bcmp(abuf, bbuf, alen));
30210 }
30211 
30212 /*
30213  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30214  * Return B_FALSE if memory allocation fails - don't change any state!
30215  */
30216 boolean_t
30217 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30218     const void *src, uint_t srclen)
30219 {
30220 	void *dst;
30221 
30222 	if (!src_valid)
30223 		srclen = 0;
30224 
30225 	ASSERT(*dstlenp == 0);
30226 	if (src != NULL && srclen != 0) {
30227 		dst = mi_alloc(srclen, BPRI_MED);
30228 		if (dst == NULL)
30229 			return (B_FALSE);
30230 	} else {
30231 		dst = NULL;
30232 	}
30233 	if (*dstp != NULL)
30234 		mi_free(*dstp);
30235 	*dstp = dst;
30236 	*dstlenp = dst == NULL ? 0 : srclen;
30237 	return (B_TRUE);
30238 }
30239 
30240 /*
30241  * Replace what is in *dst, *dstlen with the source.
30242  * Assumes ip_allocbuf has already been called.
30243  */
30244 void
30245 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30246     const void *src, uint_t srclen)
30247 {
30248 	if (!src_valid)
30249 		srclen = 0;
30250 
30251 	ASSERT(*dstlenp == srclen);
30252 	if (src != NULL && srclen != 0)
30253 		bcopy(src, *dstp, srclen);
30254 }
30255 
30256 /*
30257  * Free the storage pointed to by the members of an ip6_pkt_t.
30258  */
30259 void
30260 ip6_pkt_free(ip6_pkt_t *ipp)
30261 {
30262 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30263 
30264 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30265 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30266 		ipp->ipp_hopopts = NULL;
30267 		ipp->ipp_hopoptslen = 0;
30268 	}
30269 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30270 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30271 		ipp->ipp_rtdstopts = NULL;
30272 		ipp->ipp_rtdstoptslen = 0;
30273 	}
30274 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30275 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30276 		ipp->ipp_dstopts = NULL;
30277 		ipp->ipp_dstoptslen = 0;
30278 	}
30279 	if (ipp->ipp_fields & IPPF_RTHDR) {
30280 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30281 		ipp->ipp_rthdr = NULL;
30282 		ipp->ipp_rthdrlen = 0;
30283 	}
30284 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30285 	    IPPF_RTHDR);
30286 }
30287