xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision fbd1c0dae6f4a2ccc2ce0527c7f19d3dd5ea90b8)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/optcom.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <sys/sunddi.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
131  * IP_SQUEUE_ENTER: squeue_enter
132  * IP_SQUEUE_FILL: squeue_fill
133  */
134 int ip_squeue_enter = 2;	/* Setable in /etc/system */
135 
136 squeue_func_t ip_input_proc;
137 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
138 
139 #define	TCP6 "tcp6"
140 #define	TCP "tcp"
141 #define	SCTP "sctp"
142 #define	SCTP6 "sctp6"
143 
144 major_t TCP6_MAJ;
145 major_t TCP_MAJ;
146 major_t SCTP_MAJ;
147 major_t SCTP6_MAJ;
148 
149 /*
150  * Setable in /etc/system
151  */
152 int ip_poll_normal_ms = 100;
153 int ip_poll_normal_ticks = 0;
154 int ip_modclose_ackwait_ms = 3000;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	listptr_t	ird_route;	/* ipRouteEntryTable */
174 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
175 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
176 } iproutedata_t;
177 
178 /*
179  * Cluster specific hooks. These should be NULL when booted as a non-cluster
180  */
181 
182 /*
183  * Hook functions to enable cluster networking
184  * On non-clustered systems these vectors must always be NULL.
185  *
186  * Hook function to Check ip specified ip address is a shared ip address
187  * in the cluster
188  *
189  */
190 int (*cl_inet_isclusterwide)(uint8_t protocol,
191     sa_family_t addr_family, uint8_t *laddrp) = NULL;
192 
193 /*
194  * Hook function to generate cluster wide ip fragment identifier
195  */
196 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
197     uint8_t *laddrp, uint8_t *faddrp) = NULL;
198 
199 /*
200  * Synchronization notes:
201  *
202  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
203  * MT level protection given by STREAMS. IP uses a combination of its own
204  * internal serialization mechanism and standard Solaris locking techniques.
205  * The internal serialization is per phyint (no IPMP) or per IPMP group.
206  * This is used to serialize plumbing operations, IPMP operations, certain
207  * multicast operations, most set ioctls, igmp/mld timers etc.
208  *
209  * Plumbing is a long sequence of operations involving message
210  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
211  * involved in plumbing operations. A natural model is to serialize these
212  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
213  * parallel without any interference. But various set ioctls on hme0 are best
214  * serialized. However if the system uses IPMP, the operations are easier if
215  * they are serialized on a per IPMP group basis since IPMP operations
216  * happen across ill's of a group. Thus the lowest common denominator is to
217  * serialize most set ioctls, multicast join/leave operations, IPMP operations
218  * igmp/mld timer operations, and processing of DLPI control messages received
219  * from drivers on a per IPMP group basis. If the system does not employ
220  * IPMP the serialization is on a per phyint basis. This serialization is
221  * provided by the ipsq_t and primitives operating on this. Details can
222  * be found in ip_if.c above the core primitives operating on ipsq_t.
223  *
224  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
225  * Simiarly lookup of an ire by a thread also returns a refheld ire.
226  * In addition ipif's and ill's referenced by the ire are also indirectly
227  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
228  * the ipif's address or netmask change as long as an ipif is refheld
229  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
230  * address of an ipif has to go through the ipsq_t. This ensures that only
231  * 1 such exclusive operation proceeds at any time on the ipif. It then
232  * deletes all ires associated with this ipif, and waits for all refcnts
233  * associated with this ipif to come down to zero. The address is changed
234  * only after the ipif has been quiesced. Then the ipif is brought up again.
235  * More details are described above the comment in ip_sioctl_flags.
236  *
237  * Packet processing is based mostly on IREs and are fully multi-threaded
238  * using standard Solaris MT techniques.
239  *
240  * There are explicit locks in IP to handle:
241  * - The ip_g_head list maintained by mi_open_link() and friends.
242  *
243  * - The reassembly data structures (one lock per hash bucket)
244  *
245  * - conn_lock is meant to protect conn_t fields. The fields actually
246  *   protected by conn_lock are documented in the conn_t definition.
247  *
248  * - ire_lock to protect some of the fields of the ire, IRE tables
249  *   (one lock per hash bucket). Refer to ip_ire.c for details.
250  *
251  * - ndp_g_lock and nce_lock for protecting NCEs.
252  *
253  * - ill_lock protects fields of the ill and ipif. Details in ip.h
254  *
255  * - ill_g_lock: This is a global reader/writer lock. Protects the following
256  *	* The AVL tree based global multi list of all ills.
257  *	* The linked list of all ipifs of an ill
258  *	* The <ill-ipsq> mapping
259  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
260  *	* The illgroup list threaded by ill_group_next.
261  *	* <ill-phyint> association
262  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
263  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
264  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
265  *   will all have to hold the ill_g_lock as writer for the actual duration
266  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
267  *   may be found in the IPMP section.
268  *
269  * - ill_lock:  This is a per ill mutex.
270  *   It protects some members of the ill and is documented below.
271  *   It also protects the <ill-ipsq> mapping
272  *   It also protects the illgroup list threaded by ill_group_next.
273  *   It also protects the <ill-phyint> assoc.
274  *   It also protects the list of ipifs hanging off the ill.
275  *
276  * - ipsq_lock: This is a per ipsq_t mutex lock.
277  *   This protects all the other members of the ipsq struct except
278  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
279  *
280  * - illgrp_lock: This is a per ill_group mutex lock.
281  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
282  *   which dictates which is the next ill in an ill_group that is to be chosen
283  *   for sending outgoing packets, through creation of an IRE_CACHE that
284  *   references this ill.
285  *
286  * - phyint_lock: This is a per phyint mutex lock. Protects just the
287  *   phyint_flags
288  *
289  * - ip_g_nd_lock: This is a global reader/writer lock.
290  *   Any call to nd_load to load a new parameter to the ND table must hold the
291  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
292  *   as reader.
293  *
294  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
295  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
296  *   uniqueness check also done atomically.
297  *
298  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
299  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
300  *   as a writer when adding or deleting elements from these lists, and
301  *   as a reader when walking these lists to send a SADB update to the
302  *   IPsec capable ills.
303  *
304  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
305  *   group list linked by ill_usesrc_grp_next. It also protects the
306  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
307  *   group is being added or deleted.  This lock is taken as a reader when
308  *   walking the list/group(eg: to get the number of members in a usesrc group).
309  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
310  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
311  *   example, it is not necessary to take this lock in the initial portion
312  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
313  *   ip_sioctl_flags since the these operations are executed exclusively and
314  *   that ensures that the "usesrc group state" cannot change. The "usesrc
315  *   group state" change can happen only in the latter part of
316  *   ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
325  * and the ill_lock of the ill in question must be held.
326  *
327  * To change the <ill-illgroup> association the ill_g_lock must be held as
328  * writer and the ill_lock of the ill in question must be held.
329  *
330  * To add or delete an ipif from the list of ipifs hanging off the ill,
331  * ill_g_lock (writer) and ill_lock must be held and the thread must be
332  * a writer on the associated ipsq,.
333  *
334  * To add or delete an ill to the system, the ill_g_lock must be held as
335  * writer and the thread must be a writer on the associated ipsq.
336  *
337  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
338  * must be a writer on the associated ipsq.
339  *
340  * Lock hierarchy
341  *
342  * Some lock hierarchy scenarios are listed below.
343  *
344  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
345  * ill_g_lock -> illgrp_lock -> ill_lock
346  * ill_g_lock -> ill_lock(s) -> phyint_lock
347  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
348  * ill_g_lock -> ip_addr_avail_lock
349  * conn_lock -> irb_lock -> ill_lock -> ire_lock
350  * ill_g_lock -> ip_g_nd_lock
351  *
352  * When more than 1 ill lock is needed to be held, all ill lock addresses
353  * are sorted on address and locked starting from highest addressed lock
354  * downward.
355  *
356  * Mobile-IP scenarios
357  *
358  * irb_lock -> ill_lock -> ire_mrtun_lock
359  * irb_lock -> ill_lock -> ire_srcif_table_lock
360  *
361  * IPsec scenarios
362  *
363  * ipsa_lock -> ill_g_lock -> ill_lock
364  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
365  * ipsec_capab_ills_lock -> ipsa_lock
366  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
367  *
368  * Trusted Solaris scenarios
369  *
370  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
371  * igsa_lock -> gcdb_lock
372  * gcgrp_rwlock -> ire_lock
373  * gcgrp_rwlock -> gcdb_lock
374  *
375  *
376  * Routing/forwarding table locking notes:
377  *
378  * Lock acquisition order: Radix tree lock, irb_lock.
379  * Requirements:
380  * i.  Walker must not hold any locks during the walker callback.
381  * ii  Walker must not see a truncated tree during the walk because of any node
382  *     deletion.
383  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
384  *     in many places in the code to walk the irb list. Thus even if all the
385  *     ires in a bucket have been deleted, we still can't free the radix node
386  *     until the ires have actually been inactive'd (freed).
387  *
388  * Tree traversal - Need to hold the global tree lock in read mode.
389  * Before dropping the global tree lock, need to either increment the ire_refcnt
390  * to ensure that the radix node can't be deleted.
391  *
392  * Tree add - Need to hold the global tree lock in write mode to add a
393  * radix node. To prevent the node from being deleted, increment the
394  * irb_refcnt, after the node is added to the tree. The ire itself is
395  * added later while holding the irb_lock, but not the tree lock.
396  *
397  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
398  * All associated ires must be inactive (i.e. freed), and irb_refcnt
399  * must be zero.
400  *
401  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
402  * global tree lock (read mode) for traversal.
403  *
404  * IPSEC notes :
405  *
406  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
407  * in front of the actual packet. For outbound datagrams, the M_CTL
408  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
409  * information used by the IPSEC code for applying the right level of
410  * protection. The information initialized by IP in the ipsec_out_t
411  * is determined by the per-socket policy or global policy in the system.
412  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
413  * ipsec_info.h) which starts out with nothing in it. It gets filled
414  * with the right information if it goes through the AH/ESP code, which
415  * happens if the incoming packet is secure. The information initialized
416  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
417  * the policy requirements needed by per-socket policy or global policy
418  * is met or not.
419  *
420  * If there is both per-socket policy (set using setsockopt) and there
421  * is also global policy match for the 5 tuples of the socket,
422  * ipsec_override_policy() makes the decision of which one to use.
423  *
424  * For fully connected sockets i.e dst, src [addr, port] is known,
425  * conn_policy_cached is set indicating that policy has been cached.
426  * conn_in_enforce_policy may or may not be set depending on whether
427  * there is a global policy match or per-socket policy match.
428  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
429  * Once the right policy is set on the conn_t, policy cannot change for
430  * this socket. This makes life simpler for TCP (UDP ?) where
431  * re-transmissions go out with the same policy. For symmetry, policy
432  * is cached for fully connected UDP sockets also. Thus if policy is cached,
433  * it also implies that policy is latched i.e policy cannot change
434  * on these sockets. As we have the right policy on the conn, we don't
435  * have to lookup global policy for every outbound and inbound datagram
436  * and thus serving as an optimization. Note that a global policy change
437  * does not affect fully connected sockets if they have policy. If fully
438  * connected sockets did not have any policy associated with it, global
439  * policy change may affect them.
440  *
441  * IP Flow control notes:
442  *
443  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
444  * cannot be sent down to the driver by IP, because of a canput failure, IP
445  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
446  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
447  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
448  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
449  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
450  * the queued messages, and removes the conn from the drain list, if all
451  * messages were drained. It also qenables the next conn in the drain list to
452  * continue the drain process.
453  *
454  * In reality the drain list is not a single list, but a configurable number
455  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
456  * list. If the ip_wsrv of the next qenabled conn does not run, because the
457  * stream closes, ip_close takes responsibility to qenable the next conn in
458  * the drain list. The directly called ip_wput path always does a putq, if
459  * it cannot putnext. Thus synchronization problems are handled between
460  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
461  * functions that manipulate this drain list. Furthermore conn_drain_insert
462  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
463  * running on a queue at any time. conn_drain_tail can be simultaneously called
464  * from both ip_wsrv and ip_close.
465  *
466  * IPQOS notes:
467  *
468  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
469  * and IPQoS modules. IPPF includes hooks in IP at different control points
470  * (callout positions) which direct packets to IPQoS modules for policy
471  * processing. Policies, if present, are global.
472  *
473  * The callout positions are located in the following paths:
474  *		o local_in (packets destined for this host)
475  *		o local_out (packets orginating from this host )
476  *		o fwd_in  (packets forwarded by this m/c - inbound)
477  *		o fwd_out (packets forwarded by this m/c - outbound)
478  * Hooks at these callout points can be enabled/disabled using the ndd variable
479  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
480  * By default all the callout positions are enabled.
481  *
482  * Outbound (local_out)
483  * Hooks are placed in ip_wput_ire and ipsec_out_process.
484  *
485  * Inbound (local_in)
486  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
487  * TCP and UDP fanout routines.
488  *
489  * Forwarding (in and out)
490  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
491  *
492  * IP Policy Framework processing (IPPF processing)
493  * Policy processing for a packet is initiated by ip_process, which ascertains
494  * that the classifier (ipgpc) is loaded and configured, failing which the
495  * packet resumes normal processing in IP. If the clasifier is present, the
496  * packet is acted upon by one or more IPQoS modules (action instances), per
497  * filters configured in ipgpc and resumes normal IP processing thereafter.
498  * An action instance can drop a packet in course of its processing.
499  *
500  * A boolean variable, ip_policy, is used in all the fanout routines that can
501  * invoke ip_process for a packet. This variable indicates if the packet should
502  * to be sent for policy processing. The variable is set to B_TRUE by default,
503  * i.e. when the routines are invoked in the normal ip procesing path for a
504  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
505  * ip_policy is set to B_FALSE for all the routines called in these two
506  * functions because, in the former case,  we don't process loopback traffic
507  * currently while in the latter, the packets have already been processed in
508  * icmp_inbound.
509  *
510  * Zones notes:
511  *
512  * The partitioning rules for networking are as follows:
513  * 1) Packets coming from a zone must have a source address belonging to that
514  * zone.
515  * 2) Packets coming from a zone can only be sent on a physical interface on
516  * which the zone has an IP address.
517  * 3) Between two zones on the same machine, packet delivery is only allowed if
518  * there's a matching route for the destination and zone in the forwarding
519  * table.
520  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
521  * different zones can bind to the same port with the wildcard address
522  * (INADDR_ANY).
523  *
524  * The granularity of interface partitioning is at the logical interface level.
525  * Therefore, every zone has its own IP addresses, and incoming packets can be
526  * attributed to a zone unambiguously. A logical interface is placed into a zone
527  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
528  * structure. Rule (1) is implemented by modifying the source address selection
529  * algorithm so that the list of eligible addresses is filtered based on the
530  * sending process zone.
531  *
532  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
533  * across all zones, depending on their type. Here is the break-up:
534  *
535  * IRE type				Shared/exclusive
536  * --------				----------------
537  * IRE_BROADCAST			Exclusive
538  * IRE_DEFAULT (default routes)		Shared (*)
539  * IRE_LOCAL				Exclusive (x)
540  * IRE_LOOPBACK				Exclusive
541  * IRE_PREFIX (net routes)		Shared (*)
542  * IRE_CACHE				Exclusive
543  * IRE_IF_NORESOLVER (interface routes)	Exclusive
544  * IRE_IF_RESOLVER (interface routes)	Exclusive
545  * IRE_HOST (host routes)		Shared (*)
546  *
547  * (*) A zone can only use a default or off-subnet route if the gateway is
548  * directly reachable from the zone, that is, if the gateway's address matches
549  * one of the zone's logical interfaces.
550  *
551  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
552  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
553  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
554  * address of the zone itself (the destination). Since IRE_LOCAL is used
555  * for communication between zones, ip_wput_ire has special logic to set
556  * the right source address when sending using an IRE_LOCAL.
557  *
558  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
559  * ire_cache_lookup restricts loopback using an IRE_LOCAL
560  * between zone to the case when L2 would have conceptually looped the packet
561  * back, i.e. the loopback which is required since neither Ethernet drivers
562  * nor Ethernet hardware loops them back. This is the case when the normal
563  * routes (ignoring IREs with different zoneids) would send out the packet on
564  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
565  * associated.
566  *
567  * Multiple zones can share a common broadcast address; typically all zones
568  * share the 255.255.255.255 address. Incoming as well as locally originated
569  * broadcast packets must be dispatched to all the zones on the broadcast
570  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
571  * since some zones may not be on the 10.16.72/24 network. To handle this, each
572  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
573  * sent to every zone that has an IRE_BROADCAST entry for the destination
574  * address on the input ill, see conn_wantpacket().
575  *
576  * Applications in different zones can join the same multicast group address.
577  * For IPv4, group memberships are per-logical interface, so they're already
578  * inherently part of a zone. For IPv6, group memberships are per-physical
579  * interface, so we distinguish IPv6 group memberships based on group address,
580  * interface and zoneid. In both cases, received multicast packets are sent to
581  * every zone for which a group membership entry exists. On IPv6 we need to
582  * check that the target zone still has an address on the receiving physical
583  * interface; it could have been removed since the application issued the
584  * IPV6_JOIN_GROUP.
585  */
586 
587 /*
588  * Squeue Fanout flags:
589  *	0: No fanout.
590  *	1: Fanout across all squeues
591  */
592 boolean_t	ip_squeue_fanout = 0;
593 
594 /*
595  * Maximum dups allowed per packet.
596  */
597 uint_t ip_max_frag_dups = 10;
598 
599 #define	IS_SIMPLE_IPH(ipha)						\
600 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
601 
602 /* RFC1122 Conformance */
603 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
604 
605 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
606 
607 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
608 
609 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
610 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
611 
612 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
613 		    ip_stack_t *);
614 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
615 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
616 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
617 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
618 		    mblk_t *, int, ip_stack_t *);
619 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
620 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
621 		    ill_t *, zoneid_t);
622 static void	icmp_options_update(ipha_t *);
623 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
624 		    ip_stack_t *);
625 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
626 		    zoneid_t zoneid, ip_stack_t *);
627 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
628 static void	icmp_redirect(ill_t *, mblk_t *);
629 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
630 		    ip_stack_t *);
631 
632 static void	ip_arp_news(queue_t *, mblk_t *);
633 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
634 		    ip_stack_t *);
635 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
636 char		*ip_dot_addr(ipaddr_t, char *);
637 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
638 int		ip_close(queue_t *, int);
639 static char	*ip_dot_saddr(uchar_t *, char *);
640 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
641 		    boolean_t, boolean_t, ill_t *, zoneid_t);
642 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
643 		    boolean_t, boolean_t, zoneid_t);
644 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
645 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
646 static void	ip_lrput(queue_t *, mblk_t *);
647 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
648 ipaddr_t	ip_net_mask(ipaddr_t);
649 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
650 		    zoneid_t, ip_stack_t *);
651 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
652 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
653 char		*ip_nv_lookup(nv_t *, int);
654 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
655 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
656 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
657 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
658     ipndp_t *, size_t);
659 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
660 void	ip_rput(queue_t *, mblk_t *);
661 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
662 		    void *dummy_arg);
663 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
664 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
665     ip_stack_t *);
666 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
667 			    ire_t *, ip_stack_t *);
668 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
669 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
670 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
671     ip_stack_t *);
672 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
673 		    uint16_t *);
674 int		ip_snmp_get(queue_t *, mblk_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
676 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
678 		    ip_stack_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
680 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
703 		    ip_stack_t *ipst);
704 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
705 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
706 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
707 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
708 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
709 static boolean_t	ip_source_route_included(ipha_t *);
710 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
711 
712 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
713 		    zoneid_t, ip_stack_t *);
714 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
715 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
716 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
717 		    zoneid_t, ip_stack_t *);
718 
719 static void	conn_drain_init(ip_stack_t *);
720 static void	conn_drain_fini(ip_stack_t *);
721 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
722 
723 static void	conn_walk_drain(ip_stack_t *);
724 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
725     zoneid_t);
726 
727 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
728 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
729 static void	ip_stack_fini(netstackid_t stackid, void *arg);
730 
731 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
732     zoneid_t);
733 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
734     void *dummy_arg);
735 
736 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
737 
738 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
739     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
740     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
741 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
742 
743 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
744 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
745     caddr_t, cred_t *);
746 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
747     caddr_t cp, cred_t *cr);
748 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
749     cred_t *);
750 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
751     caddr_t cp, cred_t *cr);
752 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
753     cred_t *);
754 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
755     cred_t *);
756 static squeue_func_t ip_squeue_switch(int);
757 
758 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
759 static void	ip_kstat_fini(netstackid_t, kstat_t *);
760 static int	ip_kstat_update(kstat_t *kp, int rw);
761 static void	*icmp_kstat_init(netstackid_t);
762 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
763 static int	icmp_kstat_update(kstat_t *kp, int rw);
764 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
765 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
766 
767 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
768 
769 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
770     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
771 
772 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
773     ipha_t *, ill_t *, boolean_t);
774 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
775 
776 /* How long, in seconds, we allow frags to hang around. */
777 #define	IP_FRAG_TIMEOUT	60
778 
779 /*
780  * Threshold which determines whether MDT should be used when
781  * generating IP fragments; payload size must be greater than
782  * this threshold for MDT to take place.
783  */
784 #define	IP_WPUT_FRAG_MDT_MIN	32768
785 
786 /* Setable in /etc/system only */
787 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
788 
789 static long ip_rput_pullups;
790 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
791 
792 vmem_t *ip_minor_arena;
793 
794 int	ip_debug;
795 
796 #ifdef DEBUG
797 uint32_t ipsechw_debug = 0;
798 #endif
799 
800 /*
801  * Multirouting/CGTP stuff
802  */
803 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
804 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
805 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
806 
807 /*
808  * XXX following really should only be in a header. Would need more
809  * header and .c clean up first.
810  */
811 extern optdb_obj_t	ip_opt_obj;
812 
813 ulong_t ip_squeue_enter_unbound = 0;
814 
815 /*
816  * Named Dispatch Parameter Table.
817  * All of these are alterable, within the min/max values given, at run time.
818  */
819 static ipparam_t	lcl_param_arr[] = {
820 	/* min	max	value	name */
821 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
822 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
823 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
824 	{  0,	1,	0,	"ip_respond_to_timestamp"},
825 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
826 	{  0,	1,	1,	"ip_send_redirects"},
827 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
828 	{  0,	10,	0,	"ip_debug"},
829 	{  0,	10,	0,	"ip_mrtdebug"},
830 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
831 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
832 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
833 	{  1,	255,	255,	"ip_def_ttl" },
834 	{  0,	1,	0,	"ip_forward_src_routed"},
835 	{  0,	256,	32,	"ip_wroff_extra" },
836 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
837 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
838 	{  0,	1,	1,	"ip_path_mtu_discovery" },
839 	{  0,	240,	30,	"ip_ignore_delete_time" },
840 	{  0,	1,	0,	"ip_ignore_redirect" },
841 	{  0,	1,	1,	"ip_output_queue" },
842 	{  1,	254,	1,	"ip_broadcast_ttl" },
843 	{  0,	99999,	100,	"ip_icmp_err_interval" },
844 	{  1,	99999,	10,	"ip_icmp_err_burst" },
845 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
846 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
847 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
848 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
849 	{  0,	1,	1,	"icmp_accept_clear_messages" },
850 	{  0,	1,	1,	"igmp_accept_clear_messages" },
851 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
852 				"ip_ndp_delay_first_probe_time"},
853 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
854 				"ip_ndp_max_unicast_solicit"},
855 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
856 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
857 	{  0,	1,	0,	"ip6_forward_src_routed"},
858 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
859 	{  0,	1,	1,	"ip6_send_redirects"},
860 	{  0,	1,	0,	"ip6_ignore_redirect" },
861 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
862 
863 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
864 
865 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
866 
867 	{  0,	1,	1,	"pim_accept_clear_messages" },
868 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
869 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
870 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
871 	{  0,	15,	0,	"ip_policy_mask" },
872 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
873 	{  0,	255,	1,	"ip_multirt_ttl" },
874 	{  0,	1,	1,	"ip_multidata_outbound" },
875 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
876 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
877 	{  0,	1000,	1,	"ip_max_temp_defend" },
878 	{  0,	1000,	3,	"ip_max_defend" },
879 	{  0,	999999,	30,	"ip_defend_interval" },
880 	{  0,	3600000, 300000, "ip_dup_recovery" },
881 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
882 	{  0,	1,	1,	"ip_lso_outbound" },
883 #ifdef DEBUG
884 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
885 #else
886 	{  0,	0,	0,	"" },
887 #endif
888 };
889 
890 /*
891  * Extended NDP table
892  * The addresses for the first two are filled in to be ips_ip_g_forward
893  * and ips_ipv6_forward at init time.
894  */
895 static ipndp_t	lcl_ndp_arr[] = {
896 	/* getf			setf		data			name */
897 #define	IPNDP_IP_FORWARDING_OFFSET	0
898 	{  ip_param_generic_get,	ip_forward_set,	NULL,
899 	    "ip_forwarding" },
900 #define	IPNDP_IP6_FORWARDING_OFFSET	1
901 	{  ip_param_generic_get,	ip_forward_set,	NULL,
902 	    "ip6_forwarding" },
903 	{  ip_ill_report,	NULL,		NULL,
904 	    "ip_ill_status" },
905 	{  ip_ipif_report,	NULL,		NULL,
906 	    "ip_ipif_status" },
907 	{  ip_ire_report,	NULL,		NULL,
908 	    "ipv4_ire_status" },
909 	{  ip_ire_report_mrtun,	NULL,		NULL,
910 	    "ipv4_mrtun_ire_status" },
911 	{  ip_ire_report_srcif,	NULL,		NULL,
912 	    "ipv4_srcif_ire_status" },
913 	{  ip_ire_report_v6,	NULL,		NULL,
914 	    "ipv6_ire_status" },
915 	{  ip_conn_report,	NULL,		NULL,
916 	    "ip_conn_status" },
917 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
918 	    "ip_rput_pullups" },
919 	{  ndp_report,		NULL,		NULL,
920 	    "ip_ndp_cache_report" },
921 	{  ip_srcid_report,	NULL,		NULL,
922 	    "ip_srcid_status" },
923 	{ ip_param_generic_get, ip_squeue_profile_set,
924 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
925 	{ ip_param_generic_get, ip_squeue_bind_set,
926 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
927 	{ ip_param_generic_get, ip_input_proc_set,
928 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
929 	{ ip_param_generic_get, ip_int_set,
930 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
931 #define	IPNDP_CGTP_FILTER_OFFSET	16
932 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
933 	    "ip_cgtp_filter" },
934 	{ ip_param_generic_get, ip_int_set,
935 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
936 #define	IPNDP_IPMP_HOOK_OFFSET	18
937 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
938 	    "ipmp_hook_emulation" },
939 };
940 
941 /*
942  * Table of IP ioctls encoding the various properties of the ioctl and
943  * indexed based on the last byte of the ioctl command. Occasionally there
944  * is a clash, and there is more than 1 ioctl with the same last byte.
945  * In such a case 1 ioctl is encoded in the ndx table and the remaining
946  * ioctls are encoded in the misc table. An entry in the ndx table is
947  * retrieved by indexing on the last byte of the ioctl command and comparing
948  * the ioctl command with the value in the ndx table. In the event of a
949  * mismatch the misc table is then searched sequentially for the desired
950  * ioctl command.
951  *
952  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
953  */
954 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
955 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
961 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
962 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
963 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
964 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
965 
966 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
967 			MISC_CMD, ip_siocaddrt, NULL },
968 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
969 			MISC_CMD, ip_siocdelrt, NULL },
970 
971 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
972 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
973 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
974 			IF_CMD, ip_sioctl_get_addr, NULL },
975 
976 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
977 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
978 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
979 			IPI_GET_CMD | IPI_REPL,
980 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
981 
982 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
983 			IPI_PRIV | IPI_WR | IPI_REPL,
984 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
985 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
986 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
987 			IF_CMD, ip_sioctl_get_flags, NULL },
988 
989 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
990 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
991 
992 	/* copyin size cannot be coded for SIOCGIFCONF */
993 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
994 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
995 
996 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
997 			IF_CMD, ip_sioctl_mtu, NULL },
998 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
999 			IF_CMD, ip_sioctl_get_mtu, NULL },
1000 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1001 			IPI_GET_CMD | IPI_REPL,
1002 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1003 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1004 			IF_CMD, ip_sioctl_brdaddr, NULL },
1005 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1006 			IPI_GET_CMD | IPI_REPL,
1007 			IF_CMD, ip_sioctl_get_netmask, NULL },
1008 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1009 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1010 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1011 			IPI_GET_CMD | IPI_REPL,
1012 			IF_CMD, ip_sioctl_get_metric, NULL },
1013 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1014 			IF_CMD, ip_sioctl_metric, NULL },
1015 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 
1017 	/* See 166-168 below for extended SIOC*XARP ioctls */
1018 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1019 			MISC_CMD, ip_sioctl_arp, NULL },
1020 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1021 			MISC_CMD, ip_sioctl_arp, NULL },
1022 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1023 			MISC_CMD, ip_sioctl_arp, NULL },
1024 
1025 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 
1047 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1048 			MISC_CMD, if_unitsel, if_unitsel_restart },
1049 
1050 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 
1069 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1070 			IPI_PRIV | IPI_WR | IPI_MODOK,
1071 			IF_CMD, ip_sioctl_sifname, NULL },
1072 
1073 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 
1087 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1088 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1089 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1090 			IF_CMD, ip_sioctl_get_muxid, NULL },
1091 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1092 			IPI_PRIV | IPI_WR | IPI_REPL,
1093 			IF_CMD, ip_sioctl_muxid, NULL },
1094 
1095 	/* Both if and lif variants share same func */
1096 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1097 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1098 	/* Both if and lif variants share same func */
1099 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1100 			IPI_PRIV | IPI_WR | IPI_REPL,
1101 			IF_CMD, ip_sioctl_slifindex, NULL },
1102 
1103 	/* copyin size cannot be coded for SIOCGIFCONF */
1104 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1105 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1106 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 
1124 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1125 			IPI_PRIV | IPI_WR | IPI_REPL,
1126 			LIF_CMD, ip_sioctl_removeif,
1127 			ip_sioctl_removeif_restart },
1128 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1129 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1130 			LIF_CMD, ip_sioctl_addif, NULL },
1131 #define	SIOCLIFADDR_NDX 112
1132 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1133 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1134 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1135 			IPI_GET_CMD | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_get_addr, NULL },
1137 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1138 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1139 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1140 			IPI_GET_CMD | IPI_REPL,
1141 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1142 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1143 			IPI_PRIV | IPI_WR | IPI_REPL,
1144 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1145 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1146 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1147 			LIF_CMD, ip_sioctl_get_flags, NULL },
1148 
1149 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 
1152 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1153 			ip_sioctl_get_lifconf, NULL },
1154 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1155 			LIF_CMD, ip_sioctl_mtu, NULL },
1156 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1157 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1158 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1159 			IPI_GET_CMD | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1161 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1162 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1163 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1164 			IPI_GET_CMD | IPI_REPL,
1165 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1166 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1167 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1168 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1169 			IPI_GET_CMD | IPI_REPL,
1170 			LIF_CMD, ip_sioctl_get_metric, NULL },
1171 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1172 			LIF_CMD, ip_sioctl_metric, NULL },
1173 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1174 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1175 			LIF_CMD, ip_sioctl_slifname,
1176 			ip_sioctl_slifname_restart },
1177 
1178 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1179 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1180 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1181 			IPI_GET_CMD | IPI_REPL,
1182 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1183 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1184 			IPI_PRIV | IPI_WR | IPI_REPL,
1185 			LIF_CMD, ip_sioctl_muxid, NULL },
1186 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1187 			IPI_GET_CMD | IPI_REPL,
1188 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1189 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1190 			IPI_PRIV | IPI_WR | IPI_REPL,
1191 			LIF_CMD, ip_sioctl_slifindex, 0 },
1192 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_token, NULL },
1194 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1195 			IPI_GET_CMD | IPI_REPL,
1196 			LIF_CMD, ip_sioctl_get_token, NULL },
1197 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1198 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1199 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1200 			IPI_GET_CMD | IPI_REPL,
1201 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1202 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1203 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1204 
1205 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1206 			IPI_GET_CMD | IPI_REPL,
1207 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1208 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1209 			LIF_CMD, ip_siocdelndp_v6, NULL },
1210 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1211 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1212 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1213 			LIF_CMD, ip_siocsetndp_v6, NULL },
1214 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1215 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1216 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1217 			MISC_CMD, ip_sioctl_tonlink, NULL },
1218 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1219 			MISC_CMD, ip_sioctl_tmysite, NULL },
1220 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1221 			TUN_CMD, ip_sioctl_tunparam, NULL },
1222 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1223 			IPI_PRIV | IPI_WR,
1224 			TUN_CMD, ip_sioctl_tunparam, NULL },
1225 
1226 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1227 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1228 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1229 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1230 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1231 
1232 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1233 			IPI_PRIV | IPI_WR | IPI_REPL,
1234 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1235 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1236 			IPI_PRIV | IPI_WR | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1238 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1239 			IPI_PRIV | IPI_WR,
1240 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1241 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1242 			IPI_GET_CMD | IPI_REPL,
1243 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1244 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1245 			IPI_GET_CMD | IPI_REPL,
1246 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1247 
1248 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1249 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1250 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1251 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1252 
1253 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1254 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1255 
1256 	/* These are handled in ip_sioctl_copyin_setup itself */
1257 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1258 			MISC_CMD, NULL, NULL },
1259 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1260 			MISC_CMD, NULL, NULL },
1261 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1262 
1263 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1264 			ip_sioctl_get_lifconf, NULL },
1265 
1266 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1267 			MISC_CMD, ip_sioctl_xarp, NULL },
1268 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1269 			MISC_CMD, ip_sioctl_xarp, NULL },
1270 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1271 			MISC_CMD, ip_sioctl_xarp, NULL },
1272 
1273 	/* SIOCPOPSOCKFS is not handled by IP */
1274 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1275 
1276 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1277 			IPI_GET_CMD | IPI_REPL,
1278 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1279 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1280 			IPI_PRIV | IPI_WR | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_slifzone,
1282 			ip_sioctl_slifzone_restart },
1283 	/* 172-174 are SCTP ioctls and not handled by IP */
1284 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1285 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1286 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1287 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1288 			IPI_GET_CMD, LIF_CMD,
1289 			ip_sioctl_get_lifusesrc, 0 },
1290 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1291 			IPI_PRIV | IPI_WR,
1292 			LIF_CMD, ip_sioctl_slifusesrc,
1293 			NULL },
1294 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1295 			ip_sioctl_get_lifsrcof, NULL },
1296 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1297 			MISC_CMD, ip_sioctl_msfilter, NULL },
1298 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1299 			MISC_CMD, ip_sioctl_msfilter, NULL },
1300 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1301 			MISC_CMD, ip_sioctl_msfilter, NULL },
1302 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1303 			MISC_CMD, ip_sioctl_msfilter, NULL },
1304 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1305 			ip_sioctl_set_ipmpfailback, NULL }
1306 };
1307 
1308 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1309 
1310 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1311 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1312 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1313 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1314 		TUN_CMD, ip_sioctl_tunparam, NULL },
1315 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1317 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1318 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1319 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1320 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1321 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1322 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1323 		MISC_CMD, mrt_ioctl},
1324 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1325 		MISC_CMD, mrt_ioctl},
1326 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1327 		MISC_CMD, mrt_ioctl}
1328 };
1329 
1330 int ip_misc_ioctl_count =
1331     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1332 
1333 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1334 					/* Settable in /etc/system */
1335 /* Defined in ip_ire.c */
1336 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1337 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1338 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1339 
1340 static nv_t	ire_nv_arr[] = {
1341 	{ IRE_BROADCAST, "BROADCAST" },
1342 	{ IRE_LOCAL, "LOCAL" },
1343 	{ IRE_LOOPBACK, "LOOPBACK" },
1344 	{ IRE_CACHE, "CACHE" },
1345 	{ IRE_DEFAULT, "DEFAULT" },
1346 	{ IRE_PREFIX, "PREFIX" },
1347 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1348 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1349 	{ IRE_HOST, "HOST" },
1350 	{ 0 }
1351 };
1352 
1353 nv_t	*ire_nv_tbl = ire_nv_arr;
1354 
1355 /* Defined in ip_netinfo.c */
1356 extern ddi_taskq_t	*eventq_queue_nic;
1357 
1358 /* Simple ICMP IP Header Template */
1359 static ipha_t icmp_ipha = {
1360 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1361 };
1362 
1363 struct module_info ip_mod_info = {
1364 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1365 };
1366 
1367 /*
1368  * Duplicate static symbols within a module confuses mdb; so we avoid the
1369  * problem by making the symbols here distinct from those in udp.c.
1370  */
1371 
1372 static struct qinit iprinit = {
1373 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1374 	&ip_mod_info
1375 };
1376 
1377 static struct qinit ipwinit = {
1378 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1379 	&ip_mod_info
1380 };
1381 
1382 static struct qinit iplrinit = {
1383 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1384 	&ip_mod_info
1385 };
1386 
1387 static struct qinit iplwinit = {
1388 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1389 	&ip_mod_info
1390 };
1391 
1392 struct streamtab ipinfo = {
1393 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1394 };
1395 
1396 #ifdef	DEBUG
1397 static boolean_t skip_sctp_cksum = B_FALSE;
1398 #endif
1399 
1400 /*
1401  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1402  * ip_rput_v6(), ip_output(), etc.  If the message
1403  * block already has a M_CTL at the front of it, then simply set the zoneid
1404  * appropriately.
1405  */
1406 mblk_t *
1407 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1408 {
1409 	mblk_t		*first_mp;
1410 	ipsec_out_t	*io;
1411 
1412 	ASSERT(zoneid != ALL_ZONES);
1413 	if (mp->b_datap->db_type == M_CTL) {
1414 		io = (ipsec_out_t *)mp->b_rptr;
1415 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1416 		io->ipsec_out_zoneid = zoneid;
1417 		return (mp);
1418 	}
1419 
1420 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1421 	if (first_mp == NULL)
1422 		return (NULL);
1423 	io = (ipsec_out_t *)first_mp->b_rptr;
1424 	/* This is not a secure packet */
1425 	io->ipsec_out_secure = B_FALSE;
1426 	io->ipsec_out_zoneid = zoneid;
1427 	first_mp->b_cont = mp;
1428 	return (first_mp);
1429 }
1430 
1431 /*
1432  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1433  */
1434 mblk_t *
1435 ip_copymsg(mblk_t *mp)
1436 {
1437 	mblk_t *nmp;
1438 	ipsec_info_t *in;
1439 
1440 	if (mp->b_datap->db_type != M_CTL)
1441 		return (copymsg(mp));
1442 
1443 	in = (ipsec_info_t *)mp->b_rptr;
1444 
1445 	/*
1446 	 * Note that M_CTL is also used for delivering ICMP error messages
1447 	 * upstream to transport layers.
1448 	 */
1449 	if (in->ipsec_info_type != IPSEC_OUT &&
1450 	    in->ipsec_info_type != IPSEC_IN)
1451 		return (copymsg(mp));
1452 
1453 	nmp = copymsg(mp->b_cont);
1454 
1455 	if (in->ipsec_info_type == IPSEC_OUT) {
1456 		return (ipsec_out_tag(mp, nmp,
1457 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1458 	} else {
1459 		return (ipsec_in_tag(mp, nmp,
1460 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1461 	}
1462 }
1463 
1464 /* Generate an ICMP fragmentation needed message. */
1465 static void
1466 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1467     ip_stack_t *ipst)
1468 {
1469 	icmph_t	icmph;
1470 	mblk_t *first_mp;
1471 	boolean_t mctl_present;
1472 
1473 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1474 
1475 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1476 		if (mctl_present)
1477 			freeb(first_mp);
1478 		return;
1479 	}
1480 
1481 	bzero(&icmph, sizeof (icmph_t));
1482 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1483 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1484 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1485 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1486 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1487 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1488 	    ipst);
1489 }
1490 
1491 /*
1492  * icmp_inbound deals with ICMP messages in the following ways.
1493  *
1494  * 1) It needs to send a reply back and possibly delivering it
1495  *    to the "interested" upper clients.
1496  * 2) It needs to send it to the upper clients only.
1497  * 3) It needs to change some values in IP only.
1498  * 4) It needs to change some values in IP and upper layers e.g TCP.
1499  *
1500  * We need to accomodate icmp messages coming in clear until we get
1501  * everything secure from the wire. If icmp_accept_clear_messages
1502  * is zero we check with the global policy and act accordingly. If
1503  * it is non-zero, we accept the message without any checks. But
1504  * *this does not mean* that this will be delivered to the upper
1505  * clients. By accepting we might send replies back, change our MTU
1506  * value etc. but delivery to the ULP/clients depends on their policy
1507  * dispositions.
1508  *
1509  * We handle the above 4 cases in the context of IPSEC in the
1510  * following way :
1511  *
1512  * 1) Send the reply back in the same way as the request came in.
1513  *    If it came in encrypted, it goes out encrypted. If it came in
1514  *    clear, it goes out in clear. Thus, this will prevent chosen
1515  *    plain text attack.
1516  * 2) The client may or may not expect things to come in secure.
1517  *    If it comes in secure, the policy constraints are checked
1518  *    before delivering it to the upper layers. If it comes in
1519  *    clear, ipsec_inbound_accept_clear will decide whether to
1520  *    accept this in clear or not. In both the cases, if the returned
1521  *    message (IP header + 8 bytes) that caused the icmp message has
1522  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1523  *    sending up. If there are only 8 bytes of returned message, then
1524  *    upper client will not be notified.
1525  * 3) Check with global policy to see whether it matches the constaints.
1526  *    But this will be done only if icmp_accept_messages_in_clear is
1527  *    zero.
1528  * 4) If we need to change both in IP and ULP, then the decision taken
1529  *    while affecting the values in IP and while delivering up to TCP
1530  *    should be the same.
1531  *
1532  * 	There are two cases.
1533  *
1534  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1535  *	   failed), we will not deliver it to the ULP, even though they
1536  *	   are *willing* to accept in *clear*. This is fine as our global
1537  *	   disposition to icmp messages asks us reject the datagram.
1538  *
1539  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1540  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1541  *	   to deliver it to ULP (policy failed), it can lead to
1542  *	   consistency problems. The cases known at this time are
1543  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1544  *	   values :
1545  *
1546  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1547  *	     and Upper layer rejects. Then the communication will
1548  *	     come to a stop. This is solved by making similar decisions
1549  *	     at both levels. Currently, when we are unable to deliver
1550  *	     to the Upper Layer (due to policy failures) while IP has
1551  *	     adjusted ire_max_frag, the next outbound datagram would
1552  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1553  *	     will be with the right level of protection. Thus the right
1554  *	     value will be communicated even if we are not able to
1555  *	     communicate when we get from the wire initially. But this
1556  *	     assumes there would be at least one outbound datagram after
1557  *	     IP has adjusted its ire_max_frag value. To make things
1558  *	     simpler, we accept in clear after the validation of
1559  *	     AH/ESP headers.
1560  *
1561  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1562  *	     upper layer depending on the level of protection the upper
1563  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1564  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1565  *	     should be accepted in clear when the Upper layer expects secure.
1566  *	     Thus the communication may get aborted by some bad ICMP
1567  *	     packets.
1568  *
1569  * IPQoS Notes:
1570  * The only instance when a packet is sent for processing is when there
1571  * isn't an ICMP client and if we are interested in it.
1572  * If there is a client, IPPF processing will take place in the
1573  * ip_fanout_proto routine.
1574  *
1575  * Zones notes:
1576  * The packet is only processed in the context of the specified zone: typically
1577  * only this zone will reply to an echo request, and only interested clients in
1578  * this zone will receive a copy of the packet. This means that the caller must
1579  * call icmp_inbound() for each relevant zone.
1580  */
1581 static void
1582 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1583     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1584     ill_t *recv_ill, zoneid_t zoneid)
1585 {
1586 	icmph_t	*icmph;
1587 	ipha_t	*ipha;
1588 	int	iph_hdr_length;
1589 	int	hdr_length;
1590 	boolean_t	interested;
1591 	uint32_t	ts;
1592 	uchar_t	*wptr;
1593 	ipif_t	*ipif;
1594 	mblk_t *first_mp;
1595 	ipsec_in_t *ii;
1596 	ire_t *src_ire;
1597 	boolean_t onlink;
1598 	timestruc_t now;
1599 	uint32_t ill_index;
1600 	ip_stack_t *ipst;
1601 
1602 	ASSERT(ill != NULL);
1603 	ipst = ill->ill_ipst;
1604 
1605 	first_mp = mp;
1606 	if (mctl_present) {
1607 		mp = first_mp->b_cont;
1608 		ASSERT(mp != NULL);
1609 	}
1610 
1611 	ipha = (ipha_t *)mp->b_rptr;
1612 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1613 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1614 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1615 		if (first_mp == NULL)
1616 			return;
1617 	}
1618 
1619 	/*
1620 	 * On a labeled system, we have to check whether the zone itself is
1621 	 * permitted to receive raw traffic.
1622 	 */
1623 	if (is_system_labeled()) {
1624 		if (zoneid == ALL_ZONES)
1625 			zoneid = tsol_packet_to_zoneid(mp);
1626 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1627 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1628 			    zoneid));
1629 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1630 			freemsg(first_mp);
1631 			return;
1632 		}
1633 	}
1634 
1635 	/*
1636 	 * We have accepted the ICMP message. It means that we will
1637 	 * respond to the packet if needed. It may not be delivered
1638 	 * to the upper client depending on the policy constraints
1639 	 * and the disposition in ipsec_inbound_accept_clear.
1640 	 */
1641 
1642 	ASSERT(ill != NULL);
1643 
1644 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1645 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1646 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1647 		/* Last chance to get real. */
1648 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1649 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1650 			freemsg(first_mp);
1651 			return;
1652 		}
1653 		/* Refresh iph following the pullup. */
1654 		ipha = (ipha_t *)mp->b_rptr;
1655 	}
1656 	/* ICMP header checksum, including checksum field, should be zero. */
1657 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1658 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1659 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1660 		freemsg(first_mp);
1661 		return;
1662 	}
1663 	/* The IP header will always be a multiple of four bytes */
1664 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1665 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1666 	    icmph->icmph_code));
1667 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1668 	/* We will set "interested" to "true" if we want a copy */
1669 	interested = B_FALSE;
1670 	switch (icmph->icmph_type) {
1671 	case ICMP_ECHO_REPLY:
1672 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1673 		break;
1674 	case ICMP_DEST_UNREACHABLE:
1675 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1676 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1677 		interested = B_TRUE;	/* Pass up to transport */
1678 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1679 		break;
1680 	case ICMP_SOURCE_QUENCH:
1681 		interested = B_TRUE;	/* Pass up to transport */
1682 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1683 		break;
1684 	case ICMP_REDIRECT:
1685 		if (!ipst->ips_ip_ignore_redirect)
1686 			interested = B_TRUE;
1687 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1688 		break;
1689 	case ICMP_ECHO_REQUEST:
1690 		/*
1691 		 * Whether to respond to echo requests that come in as IP
1692 		 * broadcasts or as IP multicast is subject to debate
1693 		 * (what isn't?).  We aim to please, you pick it.
1694 		 * Default is do it.
1695 		 */
1696 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1697 			/* unicast: always respond */
1698 			interested = B_TRUE;
1699 		} else if (CLASSD(ipha->ipha_dst)) {
1700 			/* multicast: respond based on tunable */
1701 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1702 		} else if (broadcast) {
1703 			/* broadcast: respond based on tunable */
1704 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1705 		}
1706 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1707 		break;
1708 	case ICMP_ROUTER_ADVERTISEMENT:
1709 	case ICMP_ROUTER_SOLICITATION:
1710 		break;
1711 	case ICMP_TIME_EXCEEDED:
1712 		interested = B_TRUE;	/* Pass up to transport */
1713 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1714 		break;
1715 	case ICMP_PARAM_PROBLEM:
1716 		interested = B_TRUE;	/* Pass up to transport */
1717 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1718 		break;
1719 	case ICMP_TIME_STAMP_REQUEST:
1720 		/* Response to Time Stamp Requests is local policy. */
1721 		if (ipst->ips_ip_g_resp_to_timestamp &&
1722 		    /* So is whether to respond if it was an IP broadcast. */
1723 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1724 			int tstamp_len = 3 * sizeof (uint32_t);
1725 
1726 			if (wptr +  tstamp_len > mp->b_wptr) {
1727 				if (!pullupmsg(mp, wptr + tstamp_len -
1728 				    mp->b_rptr)) {
1729 					BUMP_MIB(ill->ill_ip_mib,
1730 					    ipIfStatsInDiscards);
1731 					freemsg(first_mp);
1732 					return;
1733 				}
1734 				/* Refresh ipha following the pullup. */
1735 				ipha = (ipha_t *)mp->b_rptr;
1736 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1737 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1738 			}
1739 			interested = B_TRUE;
1740 		}
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1742 		break;
1743 	case ICMP_TIME_STAMP_REPLY:
1744 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1745 		break;
1746 	case ICMP_INFO_REQUEST:
1747 		/* Per RFC 1122 3.2.2.7, ignore this. */
1748 	case ICMP_INFO_REPLY:
1749 		break;
1750 	case ICMP_ADDRESS_MASK_REQUEST:
1751 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1752 		    !broadcast) &&
1753 		    /* TODO m_pullup of complete header? */
1754 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1755 			interested = B_TRUE;
1756 		}
1757 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1758 		break;
1759 	case ICMP_ADDRESS_MASK_REPLY:
1760 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1761 		break;
1762 	default:
1763 		interested = B_TRUE;	/* Pass up to transport */
1764 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1765 		break;
1766 	}
1767 	/* See if there is an ICMP client. */
1768 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1769 		/* If there is an ICMP client and we want one too, copy it. */
1770 		mblk_t *first_mp1;
1771 
1772 		if (!interested) {
1773 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1774 			    ip_policy, recv_ill, zoneid);
1775 			return;
1776 		}
1777 		first_mp1 = ip_copymsg(first_mp);
1778 		if (first_mp1 != NULL) {
1779 			ip_fanout_proto(q, first_mp1, ill, ipha,
1780 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1781 		}
1782 	} else if (!interested) {
1783 		freemsg(first_mp);
1784 		return;
1785 	} else {
1786 		/*
1787 		 * Initiate policy processing for this packet if ip_policy
1788 		 * is true.
1789 		 */
1790 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1791 			ill_index = ill->ill_phyint->phyint_ifindex;
1792 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1793 			if (mp == NULL) {
1794 				if (mctl_present) {
1795 					freeb(first_mp);
1796 				}
1797 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1798 				return;
1799 			}
1800 		}
1801 	}
1802 	/* We want to do something with it. */
1803 	/* Check db_ref to make sure we can modify the packet. */
1804 	if (mp->b_datap->db_ref > 1) {
1805 		mblk_t	*first_mp1;
1806 
1807 		first_mp1 = ip_copymsg(first_mp);
1808 		freemsg(first_mp);
1809 		if (!first_mp1) {
1810 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1811 			return;
1812 		}
1813 		first_mp = first_mp1;
1814 		if (mctl_present) {
1815 			mp = first_mp->b_cont;
1816 			ASSERT(mp != NULL);
1817 		} else {
1818 			mp = first_mp;
1819 		}
1820 		ipha = (ipha_t *)mp->b_rptr;
1821 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1822 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1823 	}
1824 	switch (icmph->icmph_type) {
1825 	case ICMP_ADDRESS_MASK_REQUEST:
1826 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1827 		if (ipif == NULL) {
1828 			freemsg(first_mp);
1829 			return;
1830 		}
1831 		/*
1832 		 * outging interface must be IPv4
1833 		 */
1834 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1835 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1836 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1837 		ipif_refrele(ipif);
1838 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1839 		break;
1840 	case ICMP_ECHO_REQUEST:
1841 		icmph->icmph_type = ICMP_ECHO_REPLY;
1842 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1843 		break;
1844 	case ICMP_TIME_STAMP_REQUEST: {
1845 		uint32_t *tsp;
1846 
1847 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1848 		tsp = (uint32_t *)wptr;
1849 		tsp++;		/* Skip past 'originate time' */
1850 		/* Compute # of milliseconds since midnight */
1851 		gethrestime(&now);
1852 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1853 		    now.tv_nsec / (NANOSEC / MILLISEC);
1854 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1855 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1856 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1857 		break;
1858 	}
1859 	default:
1860 		ipha = (ipha_t *)&icmph[1];
1861 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1862 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1863 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1864 				freemsg(first_mp);
1865 				return;
1866 			}
1867 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1868 			ipha = (ipha_t *)&icmph[1];
1869 		}
1870 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1871 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1872 			freemsg(first_mp);
1873 			return;
1874 		}
1875 		hdr_length = IPH_HDR_LENGTH(ipha);
1876 		if (hdr_length < sizeof (ipha_t)) {
1877 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1878 			freemsg(first_mp);
1879 			return;
1880 		}
1881 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1882 			if (!pullupmsg(mp,
1883 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1884 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1885 				freemsg(first_mp);
1886 				return;
1887 			}
1888 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1889 			ipha = (ipha_t *)&icmph[1];
1890 		}
1891 		switch (icmph->icmph_type) {
1892 		case ICMP_REDIRECT:
1893 			/*
1894 			 * As there is no upper client to deliver, we don't
1895 			 * need the first_mp any more.
1896 			 */
1897 			if (mctl_present) {
1898 				freeb(first_mp);
1899 			}
1900 			icmp_redirect(ill, mp);
1901 			return;
1902 		case ICMP_DEST_UNREACHABLE:
1903 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1904 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1905 				    zoneid, mp, iph_hdr_length, ipst)) {
1906 					freemsg(first_mp);
1907 					return;
1908 				}
1909 				/*
1910 				 * icmp_inbound_too_big() may alter mp.
1911 				 * Resynch ipha and icmph accordingly.
1912 				 */
1913 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1914 				ipha = (ipha_t *)&icmph[1];
1915 			}
1916 			/* FALLTHRU */
1917 		default :
1918 			/*
1919 			 * IPQoS notes: Since we have already done IPQoS
1920 			 * processing we don't want to do it again in
1921 			 * the fanout routines called by
1922 			 * icmp_inbound_error_fanout, hence the last
1923 			 * argument, ip_policy, is B_FALSE.
1924 			 */
1925 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1926 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1927 			    B_FALSE, recv_ill, zoneid);
1928 		}
1929 		return;
1930 	}
1931 	/* Send out an ICMP packet */
1932 	icmph->icmph_checksum = 0;
1933 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1934 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1935 		ipif_t	*ipif_chosen;
1936 		/*
1937 		 * Make it look like it was directed to us, so we don't look
1938 		 * like a fool with a broadcast or multicast source address.
1939 		 */
1940 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1941 		/*
1942 		 * Make sure that we haven't grabbed an interface that's DOWN.
1943 		 */
1944 		if (ipif != NULL) {
1945 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1946 			    ipha->ipha_src, zoneid);
1947 			if (ipif_chosen != NULL) {
1948 				ipif_refrele(ipif);
1949 				ipif = ipif_chosen;
1950 			}
1951 		}
1952 		if (ipif == NULL) {
1953 			ip0dbg(("icmp_inbound: "
1954 			    "No source for broadcast/multicast:\n"
1955 			    "\tsrc 0x%x dst 0x%x ill %p "
1956 			    "ipif_lcl_addr 0x%x\n",
1957 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1958 			    (void *)ill,
1959 			    ill->ill_ipif->ipif_lcl_addr));
1960 			freemsg(first_mp);
1961 			return;
1962 		}
1963 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1964 		ipha->ipha_dst = ipif->ipif_src_addr;
1965 		ipif_refrele(ipif);
1966 	}
1967 	/* Reset time to live. */
1968 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1969 	{
1970 		/* Swap source and destination addresses */
1971 		ipaddr_t tmp;
1972 
1973 		tmp = ipha->ipha_src;
1974 		ipha->ipha_src = ipha->ipha_dst;
1975 		ipha->ipha_dst = tmp;
1976 	}
1977 	ipha->ipha_ident = 0;
1978 	if (!IS_SIMPLE_IPH(ipha))
1979 		icmp_options_update(ipha);
1980 
1981 	/*
1982 	 * ICMP echo replies should go out on the same interface
1983 	 * the request came on as probes used by in.mpathd for detecting
1984 	 * NIC failures are ECHO packets. We turn-off load spreading
1985 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1986 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1987 	 * function. This is in turn handled by ip_wput and ip_newroute
1988 	 * to make sure that the packet goes out on the interface it came
1989 	 * in on. If we don't turnoff load spreading, the packets might get
1990 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1991 	 * to go out and in.mpathd would wrongly detect a failure or
1992 	 * mis-detect a NIC failure for link failure. As load spreading
1993 	 * can happen only if ill_group is not NULL, we do only for
1994 	 * that case and this does not affect the normal case.
1995 	 *
1996 	 * We turn off load spreading only on echo packets that came from
1997 	 * on-link hosts. If the interface route has been deleted, this will
1998 	 * not be enforced as we can't do much. For off-link hosts, as the
1999 	 * default routes in IPv4 does not typically have an ire_ipif
2000 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2001 	 * Moreover, expecting a default route through this interface may
2002 	 * not be correct. We use ipha_dst because of the swap above.
2003 	 */
2004 	onlink = B_FALSE;
2005 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2006 		/*
2007 		 * First, we need to make sure that it is not one of our
2008 		 * local addresses. If we set onlink when it is one of
2009 		 * our local addresses, we will end up creating IRE_CACHES
2010 		 * for one of our local addresses. Then, we will never
2011 		 * accept packets for them afterwards.
2012 		 */
2013 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2014 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2015 		if (src_ire == NULL) {
2016 			ipif = ipif_get_next_ipif(NULL, ill);
2017 			if (ipif == NULL) {
2018 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2019 				freemsg(mp);
2020 				return;
2021 			}
2022 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2023 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2024 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2025 			ipif_refrele(ipif);
2026 			if (src_ire != NULL) {
2027 				onlink = B_TRUE;
2028 				ire_refrele(src_ire);
2029 			}
2030 		} else {
2031 			ire_refrele(src_ire);
2032 		}
2033 	}
2034 	if (!mctl_present) {
2035 		/*
2036 		 * This packet should go out the same way as it
2037 		 * came in i.e in clear. To make sure that global
2038 		 * policy will not be applied to this in ip_wput_ire,
2039 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2040 		 */
2041 		ASSERT(first_mp == mp);
2042 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2043 		if (first_mp == NULL) {
2044 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2045 			freemsg(mp);
2046 			return;
2047 		}
2048 		ii = (ipsec_in_t *)first_mp->b_rptr;
2049 
2050 		/* This is not a secure packet */
2051 		ii->ipsec_in_secure = B_FALSE;
2052 		if (onlink) {
2053 			ii->ipsec_in_attach_if = B_TRUE;
2054 			ii->ipsec_in_ill_index =
2055 			    ill->ill_phyint->phyint_ifindex;
2056 			ii->ipsec_in_rill_index =
2057 			    recv_ill->ill_phyint->phyint_ifindex;
2058 		}
2059 		first_mp->b_cont = mp;
2060 	} else if (onlink) {
2061 		ii = (ipsec_in_t *)first_mp->b_rptr;
2062 		ii->ipsec_in_attach_if = B_TRUE;
2063 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2064 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2065 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2066 	} else {
2067 		ii = (ipsec_in_t *)first_mp->b_rptr;
2068 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2069 	}
2070 	ii->ipsec_in_zoneid = zoneid;
2071 	ASSERT(zoneid != ALL_ZONES);
2072 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2073 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2074 		return;
2075 	}
2076 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2077 	put(WR(q), first_mp);
2078 }
2079 
2080 static ipaddr_t
2081 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2082 {
2083 	conn_t *connp;
2084 	connf_t *connfp;
2085 	ipaddr_t nexthop_addr = INADDR_ANY;
2086 	int hdr_length = IPH_HDR_LENGTH(ipha);
2087 	uint16_t *up;
2088 	uint32_t ports;
2089 	ip_stack_t *ipst = ill->ill_ipst;
2090 
2091 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2092 	switch (ipha->ipha_protocol) {
2093 		case IPPROTO_TCP:
2094 		{
2095 			tcph_t *tcph;
2096 
2097 			/* do a reverse lookup */
2098 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2099 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2100 			    TCPS_LISTEN, ipst);
2101 			break;
2102 		}
2103 		case IPPROTO_UDP:
2104 		{
2105 			uint32_t dstport, srcport;
2106 
2107 			((uint16_t *)&ports)[0] = up[1];
2108 			((uint16_t *)&ports)[1] = up[0];
2109 
2110 			/* Extract ports in net byte order */
2111 			dstport = htons(ntohl(ports) & 0xFFFF);
2112 			srcport = htons(ntohl(ports) >> 16);
2113 
2114 			connfp = &ipst->ips_ipcl_udp_fanout[
2115 			    IPCL_UDP_HASH(dstport, ipst)];
2116 			mutex_enter(&connfp->connf_lock);
2117 			connp = connfp->connf_head;
2118 
2119 			/* do a reverse lookup */
2120 			while ((connp != NULL) &&
2121 			    (!IPCL_UDP_MATCH(connp, dstport,
2122 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2123 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2124 				connp = connp->conn_next;
2125 			}
2126 			if (connp != NULL)
2127 				CONN_INC_REF(connp);
2128 			mutex_exit(&connfp->connf_lock);
2129 			break;
2130 		}
2131 		case IPPROTO_SCTP:
2132 		{
2133 			in6_addr_t map_src, map_dst;
2134 
2135 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2136 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2137 			((uint16_t *)&ports)[0] = up[1];
2138 			((uint16_t *)&ports)[1] = up[0];
2139 
2140 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2141 			    zoneid, ipst->ips_netstack->netstack_sctp);
2142 			if (connp == NULL) {
2143 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2144 				    zoneid, ports, ipha, ipst);
2145 			} else {
2146 				CONN_INC_REF(connp);
2147 				SCTP_REFRELE(CONN2SCTP(connp));
2148 			}
2149 			break;
2150 		}
2151 		default:
2152 		{
2153 			ipha_t ripha;
2154 
2155 			ripha.ipha_src = ipha->ipha_dst;
2156 			ripha.ipha_dst = ipha->ipha_src;
2157 			ripha.ipha_protocol = ipha->ipha_protocol;
2158 
2159 			connfp = &ipst->ips_ipcl_proto_fanout[
2160 			    ipha->ipha_protocol];
2161 			mutex_enter(&connfp->connf_lock);
2162 			connp = connfp->connf_head;
2163 			for (connp = connfp->connf_head; connp != NULL;
2164 			    connp = connp->conn_next) {
2165 				if (IPCL_PROTO_MATCH(connp,
2166 				    ipha->ipha_protocol, &ripha, ill,
2167 				    0, zoneid)) {
2168 					CONN_INC_REF(connp);
2169 					break;
2170 				}
2171 			}
2172 			mutex_exit(&connfp->connf_lock);
2173 		}
2174 	}
2175 	if (connp != NULL) {
2176 		if (connp->conn_nexthop_set)
2177 			nexthop_addr = connp->conn_nexthop_v4;
2178 		CONN_DEC_REF(connp);
2179 	}
2180 	return (nexthop_addr);
2181 }
2182 
2183 /* Table from RFC 1191 */
2184 static int icmp_frag_size_table[] =
2185 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2186 
2187 /*
2188  * Process received ICMP Packet too big.
2189  * After updating any IRE it does the fanout to any matching transport streams.
2190  * Assumes the message has been pulled up till the IP header that caused
2191  * the error.
2192  *
2193  * Returns B_FALSE on failure and B_TRUE on success.
2194  */
2195 static boolean_t
2196 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2197     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2198     ip_stack_t *ipst)
2199 {
2200 	ire_t	*ire, *first_ire;
2201 	int	mtu;
2202 	int	hdr_length;
2203 	ipaddr_t nexthop_addr;
2204 
2205 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2206 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2207 	ASSERT(ill != NULL);
2208 
2209 	hdr_length = IPH_HDR_LENGTH(ipha);
2210 
2211 	/* Drop if the original packet contained a source route */
2212 	if (ip_source_route_included(ipha)) {
2213 		return (B_FALSE);
2214 	}
2215 	/*
2216 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2217 	 * header.
2218 	 */
2219 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2220 	    mp->b_wptr) {
2221 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2222 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2223 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2224 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2225 			return (B_FALSE);
2226 		}
2227 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2228 		ipha = (ipha_t *)&icmph[1];
2229 	}
2230 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2231 	if (nexthop_addr != INADDR_ANY) {
2232 		/* nexthop set */
2233 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2234 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2235 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2236 	} else {
2237 		/* nexthop not set */
2238 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2239 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2240 	}
2241 
2242 	if (!first_ire) {
2243 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2244 		    ntohl(ipha->ipha_dst)));
2245 		return (B_FALSE);
2246 	}
2247 	/* Check for MTU discovery advice as described in RFC 1191 */
2248 	mtu = ntohs(icmph->icmph_du_mtu);
2249 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2250 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2251 	    ire = ire->ire_next) {
2252 		/*
2253 		 * Look for the connection to which this ICMP message is
2254 		 * directed. If it has the IP_NEXTHOP option set, then the
2255 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2256 		 * option. Else the search is limited to regular IREs.
2257 		 */
2258 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2259 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2260 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2261 		    (nexthop_addr != INADDR_ANY)))
2262 			continue;
2263 
2264 		mutex_enter(&ire->ire_lock);
2265 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2266 			/* Reduce the IRE max frag value as advised. */
2267 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2268 			    mtu, ire->ire_max_frag));
2269 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2270 		} else {
2271 			uint32_t length;
2272 			int	i;
2273 
2274 			/*
2275 			 * Use the table from RFC 1191 to figure out
2276 			 * the next "plateau" based on the length in
2277 			 * the original IP packet.
2278 			 */
2279 			length = ntohs(ipha->ipha_length);
2280 			if (ire->ire_max_frag <= length &&
2281 			    ire->ire_max_frag >= length - hdr_length) {
2282 				/*
2283 				 * Handle broken BSD 4.2 systems that
2284 				 * return the wrong iph_length in ICMP
2285 				 * errors.
2286 				 */
2287 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2288 				    length, ire->ire_max_frag));
2289 				length -= hdr_length;
2290 			}
2291 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2292 				if (length > icmp_frag_size_table[i])
2293 					break;
2294 			}
2295 			if (i == A_CNT(icmp_frag_size_table)) {
2296 				/* Smaller than 68! */
2297 				ip1dbg(("Too big for packet size %d\n",
2298 				    length));
2299 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2300 				ire->ire_frag_flag = 0;
2301 			} else {
2302 				mtu = icmp_frag_size_table[i];
2303 				ip1dbg(("Calculated mtu %d, packet size %d, "
2304 				    "before %d", mtu, length,
2305 				    ire->ire_max_frag));
2306 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2307 				ip1dbg((", after %d\n", ire->ire_max_frag));
2308 			}
2309 			/* Record the new max frag size for the ULP. */
2310 			icmph->icmph_du_zero = 0;
2311 			icmph->icmph_du_mtu =
2312 			    htons((uint16_t)ire->ire_max_frag);
2313 		}
2314 		mutex_exit(&ire->ire_lock);
2315 	}
2316 	rw_exit(&first_ire->ire_bucket->irb_lock);
2317 	ire_refrele(first_ire);
2318 	return (B_TRUE);
2319 }
2320 
2321 /*
2322  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2323  * calls this function.
2324  */
2325 static mblk_t *
2326 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2327 {
2328 	ipha_t *ipha;
2329 	icmph_t *icmph;
2330 	ipha_t *in_ipha;
2331 	int length;
2332 
2333 	ASSERT(mp->b_datap->db_type == M_DATA);
2334 
2335 	/*
2336 	 * For Self-encapsulated packets, we added an extra IP header
2337 	 * without the options. Inner IP header is the one from which
2338 	 * the outer IP header was formed. Thus, we need to remove the
2339 	 * outer IP header. To do this, we pullup the whole message
2340 	 * and overlay whatever follows the outer IP header over the
2341 	 * outer IP header.
2342 	 */
2343 
2344 	if (!pullupmsg(mp, -1))
2345 		return (NULL);
2346 
2347 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2348 	ipha = (ipha_t *)&icmph[1];
2349 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2350 
2351 	/*
2352 	 * The length that we want to overlay is following the inner
2353 	 * IP header. Subtracting the IP header + icmp header + outer
2354 	 * IP header's length should give us the length that we want to
2355 	 * overlay.
2356 	 */
2357 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2358 	    hdr_length;
2359 	/*
2360 	 * Overlay whatever follows the inner header over the
2361 	 * outer header.
2362 	 */
2363 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2364 
2365 	/* Set the wptr to account for the outer header */
2366 	mp->b_wptr -= hdr_length;
2367 	return (mp);
2368 }
2369 
2370 /*
2371  * Try to pass the ICMP message upstream in case the ULP cares.
2372  *
2373  * If the packet that caused the ICMP error is secure, we send
2374  * it to AH/ESP to make sure that the attached packet has a
2375  * valid association. ipha in the code below points to the
2376  * IP header of the packet that caused the error.
2377  *
2378  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2379  * in the context of IPSEC. Normally we tell the upper layer
2380  * whenever we send the ire (including ip_bind), the IPSEC header
2381  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2382  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2383  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2384  * same thing. As TCP has the IPSEC options size that needs to be
2385  * adjusted, we just pass the MTU unchanged.
2386  *
2387  * IFN could have been generated locally or by some router.
2388  *
2389  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2390  *	    This happens because IP adjusted its value of MTU on an
2391  *	    earlier IFN message and could not tell the upper layer,
2392  *	    the new adjusted value of MTU e.g. Packet was encrypted
2393  *	    or there was not enough information to fanout to upper
2394  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2395  *	    generates the IFN, where IPSEC processing has *not* been
2396  *	    done.
2397  *
2398  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2399  *	    could have generated this. This happens because ire_max_frag
2400  *	    value in IP was set to a new value, while the IPSEC processing
2401  *	    was being done and after we made the fragmentation check in
2402  *	    ip_wput_ire. Thus on return from IPSEC processing,
2403  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2404  *	    and generates the IFN. As IPSEC processing is over, we fanout
2405  *	    to AH/ESP to remove the header.
2406  *
2407  *	    In both these cases, ipsec_in_loopback will be set indicating
2408  *	    that IFN was generated locally.
2409  *
2410  * ROUTER : IFN could be secure or non-secure.
2411  *
2412  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2413  *	      packet in error has AH/ESP headers to validate the AH/ESP
2414  *	      headers. AH/ESP will verify whether there is a valid SA or
2415  *	      not and send it back. We will fanout again if we have more
2416  *	      data in the packet.
2417  *
2418  *	      If the packet in error does not have AH/ESP, we handle it
2419  *	      like any other case.
2420  *
2421  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2422  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2423  *	      for validation. AH/ESP will verify whether there is a
2424  *	      valid SA or not and send it back. We will fanout again if
2425  *	      we have more data in the packet.
2426  *
2427  *	      If the packet in error does not have AH/ESP, we handle it
2428  *	      like any other case.
2429  */
2430 static void
2431 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2432     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2433     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2434     zoneid_t zoneid)
2435 {
2436 	uint16_t *up;	/* Pointer to ports in ULP header */
2437 	uint32_t ports;	/* reversed ports for fanout */
2438 	ipha_t ripha;	/* With reversed addresses */
2439 	mblk_t *first_mp;
2440 	ipsec_in_t *ii;
2441 	tcph_t	*tcph;
2442 	conn_t	*connp;
2443 	ip_stack_t *ipst;
2444 
2445 	ASSERT(ill != NULL);
2446 
2447 	ASSERT(recv_ill != NULL);
2448 	ipst = recv_ill->ill_ipst;
2449 
2450 	first_mp = mp;
2451 	if (mctl_present) {
2452 		mp = first_mp->b_cont;
2453 		ASSERT(mp != NULL);
2454 
2455 		ii = (ipsec_in_t *)first_mp->b_rptr;
2456 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2457 	} else {
2458 		ii = NULL;
2459 	}
2460 
2461 	switch (ipha->ipha_protocol) {
2462 	case IPPROTO_UDP:
2463 		/*
2464 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2465 		 * transport header.
2466 		 */
2467 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2468 		    mp->b_wptr) {
2469 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2470 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2471 				goto discard_pkt;
2472 			}
2473 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2474 			ipha = (ipha_t *)&icmph[1];
2475 		}
2476 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2477 
2478 		/*
2479 		 * Attempt to find a client stream based on port.
2480 		 * Note that we do a reverse lookup since the header is
2481 		 * in the form we sent it out.
2482 		 * The ripha header is only used for the IP_UDP_MATCH and we
2483 		 * only set the src and dst addresses and protocol.
2484 		 */
2485 		ripha.ipha_src = ipha->ipha_dst;
2486 		ripha.ipha_dst = ipha->ipha_src;
2487 		ripha.ipha_protocol = ipha->ipha_protocol;
2488 		((uint16_t *)&ports)[0] = up[1];
2489 		((uint16_t *)&ports)[1] = up[0];
2490 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2491 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2492 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2493 		    icmph->icmph_type, icmph->icmph_code));
2494 
2495 		/* Have to change db_type after any pullupmsg */
2496 		DB_TYPE(mp) = M_CTL;
2497 
2498 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2499 		    mctl_present, ip_policy, recv_ill, zoneid);
2500 		return;
2501 
2502 	case IPPROTO_TCP:
2503 		/*
2504 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2505 		 * transport header.
2506 		 */
2507 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2508 		    mp->b_wptr) {
2509 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2510 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2511 				goto discard_pkt;
2512 			}
2513 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2514 			ipha = (ipha_t *)&icmph[1];
2515 		}
2516 		/*
2517 		 * Find a TCP client stream for this packet.
2518 		 * Note that we do a reverse lookup since the header is
2519 		 * in the form we sent it out.
2520 		 */
2521 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2522 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2523 		    ipst);
2524 		if (connp == NULL)
2525 			goto discard_pkt;
2526 
2527 		/* Have to change db_type after any pullupmsg */
2528 		DB_TYPE(mp) = M_CTL;
2529 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2530 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2531 		return;
2532 
2533 	case IPPROTO_SCTP:
2534 		/*
2535 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2536 		 * transport header.
2537 		 */
2538 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2539 		    mp->b_wptr) {
2540 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2541 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2542 				goto discard_pkt;
2543 			}
2544 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2545 			ipha = (ipha_t *)&icmph[1];
2546 		}
2547 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2548 		/*
2549 		 * Find a SCTP client stream for this packet.
2550 		 * Note that we do a reverse lookup since the header is
2551 		 * in the form we sent it out.
2552 		 * The ripha header is only used for the matching and we
2553 		 * only set the src and dst addresses, protocol, and version.
2554 		 */
2555 		ripha.ipha_src = ipha->ipha_dst;
2556 		ripha.ipha_dst = ipha->ipha_src;
2557 		ripha.ipha_protocol = ipha->ipha_protocol;
2558 		ripha.ipha_version_and_hdr_length =
2559 		    ipha->ipha_version_and_hdr_length;
2560 		((uint16_t *)&ports)[0] = up[1];
2561 		((uint16_t *)&ports)[1] = up[0];
2562 
2563 		/* Have to change db_type after any pullupmsg */
2564 		DB_TYPE(mp) = M_CTL;
2565 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2566 		    mctl_present, ip_policy, zoneid);
2567 		return;
2568 
2569 	case IPPROTO_ESP:
2570 	case IPPROTO_AH: {
2571 		int ipsec_rc;
2572 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2573 
2574 		/*
2575 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2576 		 * We will re-use the IPSEC_IN if it is already present as
2577 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2578 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2579 		 * one and attach it in the front.
2580 		 */
2581 		if (ii != NULL) {
2582 			/*
2583 			 * ip_fanout_proto_again converts the ICMP errors
2584 			 * that come back from AH/ESP to M_DATA so that
2585 			 * if it is non-AH/ESP and we do a pullupmsg in
2586 			 * this function, it would work. Convert it back
2587 			 * to M_CTL before we send up as this is a ICMP
2588 			 * error. This could have been generated locally or
2589 			 * by some router. Validate the inner IPSEC
2590 			 * headers.
2591 			 *
2592 			 * NOTE : ill_index is used by ip_fanout_proto_again
2593 			 * to locate the ill.
2594 			 */
2595 			ASSERT(ill != NULL);
2596 			ii->ipsec_in_ill_index =
2597 			    ill->ill_phyint->phyint_ifindex;
2598 			ii->ipsec_in_rill_index =
2599 			    recv_ill->ill_phyint->phyint_ifindex;
2600 			DB_TYPE(first_mp->b_cont) = M_CTL;
2601 		} else {
2602 			/*
2603 			 * IPSEC_IN is not present. We attach a ipsec_in
2604 			 * message and send up to IPSEC for validating
2605 			 * and removing the IPSEC headers. Clear
2606 			 * ipsec_in_secure so that when we return
2607 			 * from IPSEC, we don't mistakenly think that this
2608 			 * is a secure packet came from the network.
2609 			 *
2610 			 * NOTE : ill_index is used by ip_fanout_proto_again
2611 			 * to locate the ill.
2612 			 */
2613 			ASSERT(first_mp == mp);
2614 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2615 			if (first_mp == NULL) {
2616 				freemsg(mp);
2617 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2618 				return;
2619 			}
2620 			ii = (ipsec_in_t *)first_mp->b_rptr;
2621 
2622 			/* This is not a secure packet */
2623 			ii->ipsec_in_secure = B_FALSE;
2624 			first_mp->b_cont = mp;
2625 			DB_TYPE(mp) = M_CTL;
2626 			ASSERT(ill != NULL);
2627 			ii->ipsec_in_ill_index =
2628 			    ill->ill_phyint->phyint_ifindex;
2629 			ii->ipsec_in_rill_index =
2630 			    recv_ill->ill_phyint->phyint_ifindex;
2631 		}
2632 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2633 
2634 		if (!ipsec_loaded(ipss)) {
2635 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2636 			return;
2637 		}
2638 
2639 		if (ipha->ipha_protocol == IPPROTO_ESP)
2640 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2641 		else
2642 			ipsec_rc = ipsecah_icmp_error(first_mp);
2643 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2644 			return;
2645 
2646 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2647 		return;
2648 	}
2649 	default:
2650 		/*
2651 		 * The ripha header is only used for the lookup and we
2652 		 * only set the src and dst addresses and protocol.
2653 		 */
2654 		ripha.ipha_src = ipha->ipha_dst;
2655 		ripha.ipha_dst = ipha->ipha_src;
2656 		ripha.ipha_protocol = ipha->ipha_protocol;
2657 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2658 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2659 		    ntohl(ipha->ipha_dst),
2660 		    icmph->icmph_type, icmph->icmph_code));
2661 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2662 			ipha_t *in_ipha;
2663 
2664 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2665 			    mp->b_wptr) {
2666 				if (!pullupmsg(mp, (uchar_t *)ipha +
2667 				    hdr_length + sizeof (ipha_t) -
2668 				    mp->b_rptr)) {
2669 					goto discard_pkt;
2670 				}
2671 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2672 				ipha = (ipha_t *)&icmph[1];
2673 			}
2674 			/*
2675 			 * Caller has verified that length has to be
2676 			 * at least the size of IP header.
2677 			 */
2678 			ASSERT(hdr_length >= sizeof (ipha_t));
2679 			/*
2680 			 * Check the sanity of the inner IP header like
2681 			 * we did for the outer header.
2682 			 */
2683 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2684 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2685 				goto discard_pkt;
2686 			}
2687 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2688 				goto discard_pkt;
2689 			}
2690 			/* Check for Self-encapsulated tunnels */
2691 			if (in_ipha->ipha_src == ipha->ipha_src &&
2692 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2693 
2694 				mp = icmp_inbound_self_encap_error(mp,
2695 				    iph_hdr_length, hdr_length);
2696 				if (mp == NULL)
2697 					goto discard_pkt;
2698 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2699 				ipha = (ipha_t *)&icmph[1];
2700 				hdr_length = IPH_HDR_LENGTH(ipha);
2701 				/*
2702 				 * The packet in error is self-encapsualted.
2703 				 * And we are finding it further encapsulated
2704 				 * which we could not have possibly generated.
2705 				 */
2706 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2707 					goto discard_pkt;
2708 				}
2709 				icmp_inbound_error_fanout(q, ill, first_mp,
2710 				    icmph, ipha, iph_hdr_length, hdr_length,
2711 				    mctl_present, ip_policy, recv_ill, zoneid);
2712 				return;
2713 			}
2714 		}
2715 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2716 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2717 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2718 		    ii != NULL &&
2719 		    ii->ipsec_in_loopback &&
2720 		    ii->ipsec_in_secure) {
2721 			/*
2722 			 * For IP tunnels that get a looped-back
2723 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2724 			 * reported new MTU to take into account the IPsec
2725 			 * headers protecting this configured tunnel.
2726 			 *
2727 			 * This allows the tunnel module (tun.c) to blindly
2728 			 * accept the MTU reported in an ICMP "too big"
2729 			 * message.
2730 			 *
2731 			 * Non-looped back ICMP messages will just be
2732 			 * handled by the security protocols (if needed),
2733 			 * and the first subsequent packet will hit this
2734 			 * path.
2735 			 */
2736 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2737 			    ipsec_in_extra_length(first_mp));
2738 		}
2739 		/* Have to change db_type after any pullupmsg */
2740 		DB_TYPE(mp) = M_CTL;
2741 
2742 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2743 		    ip_policy, recv_ill, zoneid);
2744 		return;
2745 	}
2746 	/* NOTREACHED */
2747 discard_pkt:
2748 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2749 drop_pkt:;
2750 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2751 	freemsg(first_mp);
2752 }
2753 
2754 /*
2755  * Common IP options parser.
2756  *
2757  * Setup routine: fill in *optp with options-parsing state, then
2758  * tail-call ipoptp_next to return the first option.
2759  */
2760 uint8_t
2761 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2762 {
2763 	uint32_t totallen; /* total length of all options */
2764 
2765 	totallen = ipha->ipha_version_and_hdr_length -
2766 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2767 	totallen <<= 2;
2768 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2769 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2770 	optp->ipoptp_flags = 0;
2771 	return (ipoptp_next(optp));
2772 }
2773 
2774 /*
2775  * Common IP options parser: extract next option.
2776  */
2777 uint8_t
2778 ipoptp_next(ipoptp_t *optp)
2779 {
2780 	uint8_t *end = optp->ipoptp_end;
2781 	uint8_t *cur = optp->ipoptp_next;
2782 	uint8_t opt, len, pointer;
2783 
2784 	/*
2785 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2786 	 * has been corrupted.
2787 	 */
2788 	ASSERT(cur <= end);
2789 
2790 	if (cur == end)
2791 		return (IPOPT_EOL);
2792 
2793 	opt = cur[IPOPT_OPTVAL];
2794 
2795 	/*
2796 	 * Skip any NOP options.
2797 	 */
2798 	while (opt == IPOPT_NOP) {
2799 		cur++;
2800 		if (cur == end)
2801 			return (IPOPT_EOL);
2802 		opt = cur[IPOPT_OPTVAL];
2803 	}
2804 
2805 	if (opt == IPOPT_EOL)
2806 		return (IPOPT_EOL);
2807 
2808 	/*
2809 	 * Option requiring a length.
2810 	 */
2811 	if ((cur + 1) >= end) {
2812 		optp->ipoptp_flags |= IPOPTP_ERROR;
2813 		return (IPOPT_EOL);
2814 	}
2815 	len = cur[IPOPT_OLEN];
2816 	if (len < 2) {
2817 		optp->ipoptp_flags |= IPOPTP_ERROR;
2818 		return (IPOPT_EOL);
2819 	}
2820 	optp->ipoptp_cur = cur;
2821 	optp->ipoptp_len = len;
2822 	optp->ipoptp_next = cur + len;
2823 	if (cur + len > end) {
2824 		optp->ipoptp_flags |= IPOPTP_ERROR;
2825 		return (IPOPT_EOL);
2826 	}
2827 
2828 	/*
2829 	 * For the options which require a pointer field, make sure
2830 	 * its there, and make sure it points to either something
2831 	 * inside this option, or the end of the option.
2832 	 */
2833 	switch (opt) {
2834 	case IPOPT_RR:
2835 	case IPOPT_TS:
2836 	case IPOPT_LSRR:
2837 	case IPOPT_SSRR:
2838 		if (len <= IPOPT_OFFSET) {
2839 			optp->ipoptp_flags |= IPOPTP_ERROR;
2840 			return (opt);
2841 		}
2842 		pointer = cur[IPOPT_OFFSET];
2843 		if (pointer - 1 > len) {
2844 			optp->ipoptp_flags |= IPOPTP_ERROR;
2845 			return (opt);
2846 		}
2847 		break;
2848 	}
2849 
2850 	/*
2851 	 * Sanity check the pointer field based on the type of the
2852 	 * option.
2853 	 */
2854 	switch (opt) {
2855 	case IPOPT_RR:
2856 	case IPOPT_SSRR:
2857 	case IPOPT_LSRR:
2858 		if (pointer < IPOPT_MINOFF_SR)
2859 			optp->ipoptp_flags |= IPOPTP_ERROR;
2860 		break;
2861 	case IPOPT_TS:
2862 		if (pointer < IPOPT_MINOFF_IT)
2863 			optp->ipoptp_flags |= IPOPTP_ERROR;
2864 		/*
2865 		 * Note that the Internet Timestamp option also
2866 		 * contains two four bit fields (the Overflow field,
2867 		 * and the Flag field), which follow the pointer
2868 		 * field.  We don't need to check that these fields
2869 		 * fall within the length of the option because this
2870 		 * was implicitely done above.  We've checked that the
2871 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2872 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2873 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2874 		 */
2875 		ASSERT(len > IPOPT_POS_OV_FLG);
2876 		break;
2877 	}
2878 
2879 	return (opt);
2880 }
2881 
2882 /*
2883  * Use the outgoing IP header to create an IP_OPTIONS option the way
2884  * it was passed down from the application.
2885  */
2886 int
2887 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2888 {
2889 	ipoptp_t	opts;
2890 	const uchar_t	*opt;
2891 	uint8_t		optval;
2892 	uint8_t		optlen;
2893 	uint32_t	len = 0;
2894 	uchar_t	*buf1 = buf;
2895 
2896 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2897 	len += IP_ADDR_LEN;
2898 	bzero(buf1, IP_ADDR_LEN);
2899 
2900 	/*
2901 	 * OK to cast away const here, as we don't store through the returned
2902 	 * opts.ipoptp_cur pointer.
2903 	 */
2904 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2905 	    optval != IPOPT_EOL;
2906 	    optval = ipoptp_next(&opts)) {
2907 		int	off;
2908 
2909 		opt = opts.ipoptp_cur;
2910 		optlen = opts.ipoptp_len;
2911 		switch (optval) {
2912 		case IPOPT_SSRR:
2913 		case IPOPT_LSRR:
2914 
2915 			/*
2916 			 * Insert ipha_dst as the first entry in the source
2917 			 * route and move down the entries on step.
2918 			 * The last entry gets placed at buf1.
2919 			 */
2920 			buf[IPOPT_OPTVAL] = optval;
2921 			buf[IPOPT_OLEN] = optlen;
2922 			buf[IPOPT_OFFSET] = optlen;
2923 
2924 			off = optlen - IP_ADDR_LEN;
2925 			if (off < 0) {
2926 				/* No entries in source route */
2927 				break;
2928 			}
2929 			/* Last entry in source route */
2930 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2931 			off -= IP_ADDR_LEN;
2932 
2933 			while (off > 0) {
2934 				bcopy(opt + off,
2935 				    buf + off + IP_ADDR_LEN,
2936 				    IP_ADDR_LEN);
2937 				off -= IP_ADDR_LEN;
2938 			}
2939 			/* ipha_dst into first slot */
2940 			bcopy(&ipha->ipha_dst,
2941 			    buf + off + IP_ADDR_LEN,
2942 			    IP_ADDR_LEN);
2943 			buf += optlen;
2944 			len += optlen;
2945 			break;
2946 
2947 		case IPOPT_COMSEC:
2948 		case IPOPT_SECURITY:
2949 			/* if passing up a label is not ok, then remove */
2950 			if (is_system_labeled())
2951 				break;
2952 			/* FALLTHROUGH */
2953 		default:
2954 			bcopy(opt, buf, optlen);
2955 			buf += optlen;
2956 			len += optlen;
2957 			break;
2958 		}
2959 	}
2960 done:
2961 	/* Pad the resulting options */
2962 	while (len & 0x3) {
2963 		*buf++ = IPOPT_EOL;
2964 		len++;
2965 	}
2966 	return (len);
2967 }
2968 
2969 /*
2970  * Update any record route or timestamp options to include this host.
2971  * Reverse any source route option.
2972  * This routine assumes that the options are well formed i.e. that they
2973  * have already been checked.
2974  */
2975 static void
2976 icmp_options_update(ipha_t *ipha)
2977 {
2978 	ipoptp_t	opts;
2979 	uchar_t		*opt;
2980 	uint8_t		optval;
2981 	ipaddr_t	src;		/* Our local address */
2982 	ipaddr_t	dst;
2983 
2984 	ip2dbg(("icmp_options_update\n"));
2985 	src = ipha->ipha_src;
2986 	dst = ipha->ipha_dst;
2987 
2988 	for (optval = ipoptp_first(&opts, ipha);
2989 	    optval != IPOPT_EOL;
2990 	    optval = ipoptp_next(&opts)) {
2991 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2992 		opt = opts.ipoptp_cur;
2993 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2994 		    optval, opts.ipoptp_len));
2995 		switch (optval) {
2996 			int off1, off2;
2997 		case IPOPT_SSRR:
2998 		case IPOPT_LSRR:
2999 			/*
3000 			 * Reverse the source route.  The first entry
3001 			 * should be the next to last one in the current
3002 			 * source route (the last entry is our address).
3003 			 * The last entry should be the final destination.
3004 			 */
3005 			off1 = IPOPT_MINOFF_SR - 1;
3006 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3007 			if (off2 < 0) {
3008 				/* No entries in source route */
3009 				ip1dbg((
3010 				    "icmp_options_update: bad src route\n"));
3011 				break;
3012 			}
3013 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3014 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3015 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3016 			off2 -= IP_ADDR_LEN;
3017 
3018 			while (off1 < off2) {
3019 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3020 				bcopy((char *)opt + off2, (char *)opt + off1,
3021 				    IP_ADDR_LEN);
3022 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3023 				off1 += IP_ADDR_LEN;
3024 				off2 -= IP_ADDR_LEN;
3025 			}
3026 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3027 			break;
3028 		}
3029 	}
3030 }
3031 
3032 /*
3033  * Process received ICMP Redirect messages.
3034  */
3035 static void
3036 icmp_redirect(ill_t *ill, mblk_t *mp)
3037 {
3038 	ipha_t	*ipha;
3039 	int	iph_hdr_length;
3040 	icmph_t	*icmph;
3041 	ipha_t	*ipha_err;
3042 	ire_t	*ire;
3043 	ire_t	*prev_ire;
3044 	ire_t	*save_ire;
3045 	ipaddr_t  src, dst, gateway;
3046 	iulp_t	ulp_info = { 0 };
3047 	int	error;
3048 	ip_stack_t *ipst;
3049 
3050 	ASSERT(ill != NULL);
3051 	ipst = ill->ill_ipst;
3052 
3053 	ipha = (ipha_t *)mp->b_rptr;
3054 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3055 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3056 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3057 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3058 		freemsg(mp);
3059 		return;
3060 	}
3061 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3062 	ipha_err = (ipha_t *)&icmph[1];
3063 	src = ipha->ipha_src;
3064 	dst = ipha_err->ipha_dst;
3065 	gateway = icmph->icmph_rd_gateway;
3066 	/* Make sure the new gateway is reachable somehow. */
3067 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3068 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3069 	/*
3070 	 * Make sure we had a route for the dest in question and that
3071 	 * that route was pointing to the old gateway (the source of the
3072 	 * redirect packet.)
3073 	 */
3074 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3075 	    NULL, MATCH_IRE_GW, ipst);
3076 	/*
3077 	 * Check that
3078 	 *	the redirect was not from ourselves
3079 	 *	the new gateway and the old gateway are directly reachable
3080 	 */
3081 	if (!prev_ire ||
3082 	    !ire ||
3083 	    ire->ire_type == IRE_LOCAL) {
3084 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3085 		freemsg(mp);
3086 		if (ire != NULL)
3087 			ire_refrele(ire);
3088 		if (prev_ire != NULL)
3089 			ire_refrele(prev_ire);
3090 		return;
3091 	}
3092 
3093 	/*
3094 	 * Should we use the old ULP info to create the new gateway?  From
3095 	 * a user's perspective, we should inherit the info so that it
3096 	 * is a "smooth" transition.  If we do not do that, then new
3097 	 * connections going thru the new gateway will have no route metrics,
3098 	 * which is counter-intuitive to user.  From a network point of
3099 	 * view, this may or may not make sense even though the new gateway
3100 	 * is still directly connected to us so the route metrics should not
3101 	 * change much.
3102 	 *
3103 	 * But if the old ire_uinfo is not initialized, we do another
3104 	 * recursive lookup on the dest using the new gateway.  There may
3105 	 * be a route to that.  If so, use it to initialize the redirect
3106 	 * route.
3107 	 */
3108 	if (prev_ire->ire_uinfo.iulp_set) {
3109 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3110 	} else {
3111 		ire_t *tmp_ire;
3112 		ire_t *sire;
3113 
3114 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3115 		    ALL_ZONES, 0, NULL,
3116 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3117 		    ipst);
3118 		if (sire != NULL) {
3119 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3120 			/*
3121 			 * If sire != NULL, ire_ftable_lookup() should not
3122 			 * return a NULL value.
3123 			 */
3124 			ASSERT(tmp_ire != NULL);
3125 			ire_refrele(tmp_ire);
3126 			ire_refrele(sire);
3127 		} else if (tmp_ire != NULL) {
3128 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3129 			    sizeof (iulp_t));
3130 			ire_refrele(tmp_ire);
3131 		}
3132 	}
3133 	if (prev_ire->ire_type == IRE_CACHE)
3134 		ire_delete(prev_ire);
3135 	ire_refrele(prev_ire);
3136 	/*
3137 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3138 	 * require TOS routing
3139 	 */
3140 	switch (icmph->icmph_code) {
3141 	case 0:
3142 	case 1:
3143 		/* TODO: TOS specificity for cases 2 and 3 */
3144 	case 2:
3145 	case 3:
3146 		break;
3147 	default:
3148 		freemsg(mp);
3149 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3150 		ire_refrele(ire);
3151 		return;
3152 	}
3153 	/*
3154 	 * Create a Route Association.  This will allow us to remember that
3155 	 * someone we believe told us to use the particular gateway.
3156 	 */
3157 	save_ire = ire;
3158 	ire = ire_create(
3159 	    (uchar_t *)&dst,			/* dest addr */
3160 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3161 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3162 	    (uchar_t *)&gateway,		/* gateway addr */
3163 	    NULL,				/* no in_srcaddr */
3164 	    &save_ire->ire_max_frag,		/* max frag */
3165 	    NULL,				/* no src nce */
3166 	    NULL,				/* no rfq */
3167 	    NULL,				/* no stq */
3168 	    IRE_HOST,
3169 	    NULL,				/* ipif */
3170 	    NULL,				/* in_ill */
3171 	    0,					/* cmask */
3172 	    0,					/* phandle */
3173 	    0,					/* ihandle */
3174 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3175 	    &ulp_info,
3176 	    NULL,				/* tsol_gc_t */
3177 	    NULL,				/* gcgrp */
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 to
3410 	 * the IP header.  We try to send 64 bytes of data and the internal
3411 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3412 	 */
3413 	len_needed = IPH_HDR_LENGTH(ipha);
3414 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3415 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3416 
3417 		if (!pullupmsg(mp, -1)) {
3418 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3419 			freemsg(ipsec_mp);
3420 			return;
3421 		}
3422 		ipha = (ipha_t *)mp->b_rptr;
3423 
3424 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3425 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3426 			    len_needed));
3427 		} else {
3428 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3429 
3430 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3431 			len_needed += ip_hdr_length_v6(mp, ip6h);
3432 		}
3433 	}
3434 	len_needed += ipst->ips_ip_icmp_return;
3435 	msg_len = msgdsize(mp);
3436 	if (msg_len > len_needed) {
3437 		(void) adjmsg(mp, len_needed - msg_len);
3438 		msg_len = len_needed;
3439 	}
3440 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3441 	if (mp1 == NULL) {
3442 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3443 		freemsg(ipsec_mp);
3444 		return;
3445 	}
3446 	mp1->b_cont = mp;
3447 	mp = mp1;
3448 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3449 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3450 	    io->ipsec_out_type == IPSEC_OUT);
3451 	ipsec_mp->b_cont = mp;
3452 
3453 	/*
3454 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3455 	 * node generates be accepted in peace by all on-host destinations.
3456 	 * If we do NOT assume that all on-host destinations trust
3457 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3458 	 * (Look for ipsec_out_icmp_loopback).
3459 	 */
3460 	io->ipsec_out_icmp_loopback = B_TRUE;
3461 
3462 	ipha = (ipha_t *)mp->b_rptr;
3463 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3464 	*ipha = icmp_ipha;
3465 	ipha->ipha_src = src;
3466 	ipha->ipha_dst = dst;
3467 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3468 	msg_len += sizeof (icmp_ipha) + len;
3469 	if (msg_len > IP_MAXPACKET) {
3470 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3471 		msg_len = IP_MAXPACKET;
3472 	}
3473 	ipha->ipha_length = htons((uint16_t)msg_len);
3474 	icmph = (icmph_t *)&ipha[1];
3475 	bcopy(stuff, icmph, len);
3476 	icmph->icmph_checksum = 0;
3477 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3478 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3479 	put(q, ipsec_mp);
3480 }
3481 
3482 /*
3483  * Determine if an ICMP error packet can be sent given the rate limit.
3484  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3485  * in milliseconds) and a burst size. Burst size number of packets can
3486  * be sent arbitrarely closely spaced.
3487  * The state is tracked using two variables to implement an approximate
3488  * token bucket filter:
3489  *	icmp_pkt_err_last - lbolt value when the last burst started
3490  *	icmp_pkt_err_sent - number of packets sent in current burst
3491  */
3492 boolean_t
3493 icmp_err_rate_limit(ip_stack_t *ipst)
3494 {
3495 	clock_t now = TICK_TO_MSEC(lbolt);
3496 	uint_t refilled; /* Number of packets refilled in tbf since last */
3497 	/* Guard against changes by loading into local variable */
3498 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3499 
3500 	if (err_interval == 0)
3501 		return (B_FALSE);
3502 
3503 	if (ipst->ips_icmp_pkt_err_last > now) {
3504 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3505 		ipst->ips_icmp_pkt_err_last = 0;
3506 		ipst->ips_icmp_pkt_err_sent = 0;
3507 	}
3508 	/*
3509 	 * If we are in a burst update the token bucket filter.
3510 	 * Update the "last" time to be close to "now" but make sure
3511 	 * we don't loose precision.
3512 	 */
3513 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3514 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3515 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3516 			ipst->ips_icmp_pkt_err_sent = 0;
3517 		} else {
3518 			ipst->ips_icmp_pkt_err_sent -= refilled;
3519 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3520 		}
3521 	}
3522 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3523 		/* Start of new burst */
3524 		ipst->ips_icmp_pkt_err_last = now;
3525 	}
3526 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3527 		ipst->ips_icmp_pkt_err_sent++;
3528 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3529 		    ipst->ips_icmp_pkt_err_sent));
3530 		return (B_FALSE);
3531 	}
3532 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3533 	return (B_TRUE);
3534 }
3535 
3536 /*
3537  * Check if it is ok to send an IPv4 ICMP error packet in
3538  * response to the IPv4 packet in mp.
3539  * Free the message and return null if no
3540  * ICMP error packet should be sent.
3541  */
3542 static mblk_t *
3543 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3544 {
3545 	icmph_t	*icmph;
3546 	ipha_t	*ipha;
3547 	uint_t	len_needed;
3548 	ire_t	*src_ire;
3549 	ire_t	*dst_ire;
3550 
3551 	if (!mp)
3552 		return (NULL);
3553 	ipha = (ipha_t *)mp->b_rptr;
3554 	if (ip_csum_hdr(ipha)) {
3555 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3556 		freemsg(mp);
3557 		return (NULL);
3558 	}
3559 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3560 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3561 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3562 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3563 	if (src_ire != NULL || dst_ire != NULL ||
3564 	    CLASSD(ipha->ipha_dst) ||
3565 	    CLASSD(ipha->ipha_src) ||
3566 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3567 		/* Note: only errors to the fragment with offset 0 */
3568 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3569 		freemsg(mp);
3570 		if (src_ire != NULL)
3571 			ire_refrele(src_ire);
3572 		if (dst_ire != NULL)
3573 			ire_refrele(dst_ire);
3574 		return (NULL);
3575 	}
3576 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3577 		/*
3578 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3579 		 * errors in response to any ICMP errors.
3580 		 */
3581 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3582 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3583 			if (!pullupmsg(mp, len_needed)) {
3584 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3585 				freemsg(mp);
3586 				return (NULL);
3587 			}
3588 			ipha = (ipha_t *)mp->b_rptr;
3589 		}
3590 		icmph = (icmph_t *)
3591 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3592 		switch (icmph->icmph_type) {
3593 		case ICMP_DEST_UNREACHABLE:
3594 		case ICMP_SOURCE_QUENCH:
3595 		case ICMP_TIME_EXCEEDED:
3596 		case ICMP_PARAM_PROBLEM:
3597 		case ICMP_REDIRECT:
3598 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3599 			freemsg(mp);
3600 			return (NULL);
3601 		default:
3602 			break;
3603 		}
3604 	}
3605 	/*
3606 	 * If this is a labeled system, then check to see if we're allowed to
3607 	 * send a response to this particular sender.  If not, then just drop.
3608 	 */
3609 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3610 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3611 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3612 		freemsg(mp);
3613 		return (NULL);
3614 	}
3615 	if (icmp_err_rate_limit(ipst)) {
3616 		/*
3617 		 * Only send ICMP error packets every so often.
3618 		 * This should be done on a per port/source basis,
3619 		 * but for now this will suffice.
3620 		 */
3621 		freemsg(mp);
3622 		return (NULL);
3623 	}
3624 	return (mp);
3625 }
3626 
3627 /*
3628  * Generate an ICMP redirect message.
3629  */
3630 static void
3631 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3632 {
3633 	icmph_t	icmph;
3634 
3635 	/*
3636 	 * We are called from ip_rput where we could
3637 	 * not have attached an IPSEC_IN.
3638 	 */
3639 	ASSERT(mp->b_datap->db_type == M_DATA);
3640 
3641 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3642 		return;
3643 	}
3644 
3645 	bzero(&icmph, sizeof (icmph_t));
3646 	icmph.icmph_type = ICMP_REDIRECT;
3647 	icmph.icmph_code = 1;
3648 	icmph.icmph_rd_gateway = gateway;
3649 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3650 	/* Redirects sent by router, and router is global zone */
3651 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3652 }
3653 
3654 /*
3655  * Generate an ICMP time exceeded message.
3656  */
3657 void
3658 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3659     ip_stack_t *ipst)
3660 {
3661 	icmph_t	icmph;
3662 	boolean_t mctl_present;
3663 	mblk_t *first_mp;
3664 
3665 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3666 
3667 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3668 		if (mctl_present)
3669 			freeb(first_mp);
3670 		return;
3671 	}
3672 
3673 	bzero(&icmph, sizeof (icmph_t));
3674 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3675 	icmph.icmph_code = code;
3676 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3677 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3678 	    ipst);
3679 }
3680 
3681 /*
3682  * Generate an ICMP unreachable message.
3683  */
3684 void
3685 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3686     ip_stack_t *ipst)
3687 {
3688 	icmph_t	icmph;
3689 	mblk_t *first_mp;
3690 	boolean_t mctl_present;
3691 
3692 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3693 
3694 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3695 		if (mctl_present)
3696 			freeb(first_mp);
3697 		return;
3698 	}
3699 
3700 	bzero(&icmph, sizeof (icmph_t));
3701 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3702 	icmph.icmph_code = code;
3703 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3704 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3705 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3706 	    zoneid, ipst);
3707 }
3708 
3709 /*
3710  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3711  * duplicate.  As long as someone else holds the address, the interface will
3712  * stay down.  When that conflict goes away, the interface is brought back up.
3713  * This is done so that accidental shutdowns of addresses aren't made
3714  * permanent.  Your server will recover from a failure.
3715  *
3716  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3717  * user space process (dhcpagent).
3718  *
3719  * Recovery completes if ARP reports that the address is now ours (via
3720  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3721  *
3722  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3723  */
3724 static void
3725 ipif_dup_recovery(void *arg)
3726 {
3727 	ipif_t *ipif = arg;
3728 	ill_t *ill = ipif->ipif_ill;
3729 	mblk_t *arp_add_mp;
3730 	mblk_t *arp_del_mp;
3731 	area_t *area;
3732 	ip_stack_t *ipst = ill->ill_ipst;
3733 
3734 	ipif->ipif_recovery_id = 0;
3735 
3736 	/*
3737 	 * No lock needed for moving or condemned check, as this is just an
3738 	 * optimization.
3739 	 */
3740 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3741 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3742 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3743 		/* No reason to try to bring this address back. */
3744 		return;
3745 	}
3746 
3747 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3748 		goto alloc_fail;
3749 
3750 	if (ipif->ipif_arp_del_mp == NULL) {
3751 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3752 			goto alloc_fail;
3753 		ipif->ipif_arp_del_mp = arp_del_mp;
3754 	}
3755 
3756 	/* Setting the 'unverified' flag restarts DAD */
3757 	area = (area_t *)arp_add_mp->b_rptr;
3758 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3759 	    ACE_F_UNVERIFIED;
3760 	putnext(ill->ill_rq, arp_add_mp);
3761 	return;
3762 
3763 alloc_fail:
3764 	/*
3765 	 * On allocation failure, just restart the timer.  Note that the ipif
3766 	 * is down here, so no other thread could be trying to start a recovery
3767 	 * timer.  The ill_lock protects the condemned flag and the recovery
3768 	 * timer ID.
3769 	 */
3770 	freemsg(arp_add_mp);
3771 	mutex_enter(&ill->ill_lock);
3772 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3773 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3774 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3775 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3776 	}
3777 	mutex_exit(&ill->ill_lock);
3778 }
3779 
3780 /*
3781  * This is for exclusive changes due to ARP.  Either tear down an interface due
3782  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3783  */
3784 /* ARGSUSED */
3785 static void
3786 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3787 {
3788 	ill_t	*ill = rq->q_ptr;
3789 	arh_t *arh;
3790 	ipaddr_t src;
3791 	ipif_t	*ipif;
3792 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3793 	char hbuf[MAC_STR_LEN];
3794 	char sbuf[INET_ADDRSTRLEN];
3795 	const char *failtype;
3796 	boolean_t bring_up;
3797 	ip_stack_t *ipst = ill->ill_ipst;
3798 
3799 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3800 	case AR_CN_READY:
3801 		failtype = NULL;
3802 		bring_up = B_TRUE;
3803 		break;
3804 	case AR_CN_FAILED:
3805 		failtype = "in use";
3806 		bring_up = B_FALSE;
3807 		break;
3808 	default:
3809 		failtype = "claimed";
3810 		bring_up = B_FALSE;
3811 		break;
3812 	}
3813 
3814 	arh = (arh_t *)mp->b_cont->b_rptr;
3815 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3816 
3817 	/* Handle failures due to probes */
3818 	if (src == 0) {
3819 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3820 		    IP_ADDR_LEN);
3821 	}
3822 
3823 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3824 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3825 	    sizeof (hbuf));
3826 	(void) ip_dot_addr(src, sbuf);
3827 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3828 
3829 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3830 		    ipif->ipif_lcl_addr != src) {
3831 			continue;
3832 		}
3833 
3834 		/*
3835 		 * If we failed on a recovery probe, then restart the timer to
3836 		 * try again later.
3837 		 */
3838 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3839 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3840 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3841 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3842 		    ipst->ips_ip_dup_recovery > 0 &&
3843 		    ipif->ipif_recovery_id == 0) {
3844 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3845 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3846 			continue;
3847 		}
3848 
3849 		/*
3850 		 * If what we're trying to do has already been done, then do
3851 		 * nothing.
3852 		 */
3853 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3854 			continue;
3855 
3856 		if (ipif->ipif_id != 0) {
3857 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3858 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3859 			    ipif->ipif_id);
3860 		}
3861 		if (failtype == NULL) {
3862 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3863 			    ibuf);
3864 		} else {
3865 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3866 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3867 		}
3868 
3869 		if (bring_up) {
3870 			ASSERT(ill->ill_dl_up);
3871 			/*
3872 			 * Free up the ARP delete message so we can allocate
3873 			 * a fresh one through the normal path.
3874 			 */
3875 			freemsg(ipif->ipif_arp_del_mp);
3876 			ipif->ipif_arp_del_mp = NULL;
3877 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3878 			    EINPROGRESS) {
3879 				ipif->ipif_addr_ready = 1;
3880 				(void) ipif_up_done(ipif);
3881 			}
3882 			continue;
3883 		}
3884 
3885 		mutex_enter(&ill->ill_lock);
3886 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3887 		ipif->ipif_flags |= IPIF_DUPLICATE;
3888 		ill->ill_ipif_dup_count++;
3889 		mutex_exit(&ill->ill_lock);
3890 		/*
3891 		 * Already exclusive on the ill; no need to handle deferred
3892 		 * processing here.
3893 		 */
3894 		(void) ipif_down(ipif, NULL, NULL);
3895 		ipif_down_tail(ipif);
3896 		mutex_enter(&ill->ill_lock);
3897 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3898 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3899 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3900 		    ipst->ips_ip_dup_recovery > 0) {
3901 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3902 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3903 		}
3904 		mutex_exit(&ill->ill_lock);
3905 	}
3906 	freemsg(mp);
3907 }
3908 
3909 /* ARGSUSED */
3910 static void
3911 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3912 {
3913 	ill_t	*ill = rq->q_ptr;
3914 	arh_t *arh;
3915 	ipaddr_t src;
3916 	ipif_t	*ipif;
3917 
3918 	arh = (arh_t *)mp->b_cont->b_rptr;
3919 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3920 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3921 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3922 			(void) ipif_resolver_up(ipif, Res_act_defend);
3923 	}
3924 	freemsg(mp);
3925 }
3926 
3927 /*
3928  * News from ARP.  ARP sends notification of interesting events down
3929  * to its clients using M_CTL messages with the interesting ARP packet
3930  * attached via b_cont.
3931  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3932  * queue as opposed to ARP sending the message to all the clients, i.e. all
3933  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3934  * table if a cache IRE is found to delete all the entries for the address in
3935  * the packet.
3936  */
3937 static void
3938 ip_arp_news(queue_t *q, mblk_t *mp)
3939 {
3940 	arcn_t		*arcn;
3941 	arh_t		*arh;
3942 	ire_t		*ire = NULL;
3943 	char		hbuf[MAC_STR_LEN];
3944 	char		sbuf[INET_ADDRSTRLEN];
3945 	ipaddr_t	src;
3946 	in6_addr_t	v6src;
3947 	boolean_t	isv6 = B_FALSE;
3948 	ipif_t		*ipif;
3949 	ill_t		*ill;
3950 	ip_stack_t	*ipst;
3951 
3952 	if (CONN_Q(q)) {
3953 		conn_t *connp = Q_TO_CONN(q);
3954 
3955 		ipst = connp->conn_netstack->netstack_ip;
3956 	} else {
3957 		ill_t *ill = (ill_t *)q->q_ptr;
3958 
3959 		ipst = ill->ill_ipst;
3960 	}
3961 
3962 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3963 		if (q->q_next) {
3964 			putnext(q, mp);
3965 		} else
3966 			freemsg(mp);
3967 		return;
3968 	}
3969 	arh = (arh_t *)mp->b_cont->b_rptr;
3970 	/* Is it one we are interested in? */
3971 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3972 		isv6 = B_TRUE;
3973 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3974 		    IPV6_ADDR_LEN);
3975 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3976 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3977 		    IP_ADDR_LEN);
3978 	} else {
3979 		freemsg(mp);
3980 		return;
3981 	}
3982 
3983 	ill = q->q_ptr;
3984 
3985 	arcn = (arcn_t *)mp->b_rptr;
3986 	switch (arcn->arcn_code) {
3987 	case AR_CN_BOGON:
3988 		/*
3989 		 * Someone is sending ARP packets with a source protocol
3990 		 * address that we have published and for which we believe our
3991 		 * entry is authoritative and (when ill_arp_extend is set)
3992 		 * verified to be unique on the network.
3993 		 *
3994 		 * The ARP module internally handles the cases where the sender
3995 		 * is just probing (for DAD) and where the hardware address of
3996 		 * a non-authoritative entry has changed.  Thus, these are the
3997 		 * real conflicts, and we have to do resolution.
3998 		 *
3999 		 * We back away quickly from the address if it's from DHCP or
4000 		 * otherwise temporary and hasn't been used recently (or at
4001 		 * all).  We'd like to include "deprecated" addresses here as
4002 		 * well (as there's no real reason to defend something we're
4003 		 * discarding), but IPMP "reuses" this flag to mean something
4004 		 * other than the standard meaning.
4005 		 *
4006 		 * If the ARP module above is not extended (meaning that it
4007 		 * doesn't know how to defend the address), then we just log
4008 		 * the problem as we always did and continue on.  It's not
4009 		 * right, but there's little else we can do, and those old ATM
4010 		 * users are going away anyway.
4011 		 */
4012 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4013 		    hbuf, sizeof (hbuf));
4014 		(void) ip_dot_addr(src, sbuf);
4015 		if (isv6) {
4016 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4017 			    ipst);
4018 		} else {
4019 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4020 		}
4021 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4022 			uint32_t now;
4023 			uint32_t maxage;
4024 			clock_t lused;
4025 			uint_t maxdefense;
4026 			uint_t defs;
4027 
4028 			/*
4029 			 * First, figure out if this address hasn't been used
4030 			 * in a while.  If it hasn't, then it's a better
4031 			 * candidate for abandoning.
4032 			 */
4033 			ipif = ire->ire_ipif;
4034 			ASSERT(ipif != NULL);
4035 			now = gethrestime_sec();
4036 			maxage = now - ire->ire_create_time;
4037 			if (maxage > ipst->ips_ip_max_temp_idle)
4038 				maxage = ipst->ips_ip_max_temp_idle;
4039 			lused = drv_hztousec(ddi_get_lbolt() -
4040 			    ire->ire_last_used_time) / MICROSEC + 1;
4041 			if (lused >= maxage && (ipif->ipif_flags &
4042 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4043 				maxdefense = ipst->ips_ip_max_temp_defend;
4044 			else
4045 				maxdefense = ipst->ips_ip_max_defend;
4046 
4047 			/*
4048 			 * Now figure out how many times we've defended
4049 			 * ourselves.  Ignore defenses that happened long in
4050 			 * the past.
4051 			 */
4052 			mutex_enter(&ire->ire_lock);
4053 			if ((defs = ire->ire_defense_count) > 0 &&
4054 			    now - ire->ire_defense_time >
4055 			    ipst->ips_ip_defend_interval) {
4056 				ire->ire_defense_count = defs = 0;
4057 			}
4058 			ire->ire_defense_count++;
4059 			ire->ire_defense_time = now;
4060 			mutex_exit(&ire->ire_lock);
4061 			ill_refhold(ill);
4062 			ire_refrele(ire);
4063 
4064 			/*
4065 			 * If we've defended ourselves too many times already,
4066 			 * then give up and tear down the interface(s) using
4067 			 * this address.  Otherwise, defend by sending out a
4068 			 * gratuitous ARP.
4069 			 */
4070 			if (defs >= maxdefense && ill->ill_arp_extend) {
4071 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4072 				    B_FALSE);
4073 			} else {
4074 				cmn_err(CE_WARN,
4075 				    "node %s is using our IP address %s on %s",
4076 				    hbuf, sbuf, ill->ill_name);
4077 				/*
4078 				 * If this is an old (ATM) ARP module, then
4079 				 * don't try to defend the address.  Remain
4080 				 * compatible with the old behavior.  Defend
4081 				 * only with new ARP.
4082 				 */
4083 				if (ill->ill_arp_extend) {
4084 					qwriter_ip(ill, q, mp, ip_arp_defend,
4085 					    NEW_OP, B_FALSE);
4086 				} else {
4087 					ill_refrele(ill);
4088 				}
4089 			}
4090 			return;
4091 		}
4092 		cmn_err(CE_WARN,
4093 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4094 		    hbuf, sbuf, ill->ill_name);
4095 		if (ire != NULL)
4096 			ire_refrele(ire);
4097 		break;
4098 	case AR_CN_ANNOUNCE:
4099 		if (isv6) {
4100 			/*
4101 			 * For XRESOLV interfaces.
4102 			 * Delete the IRE cache entry and NCE for this
4103 			 * v6 address
4104 			 */
4105 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4106 			/*
4107 			 * If v6src is a non-zero, it's a router address
4108 			 * as below. Do the same sort of thing to clean
4109 			 * out off-net IRE_CACHE entries that go through
4110 			 * the router.
4111 			 */
4112 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4113 				ire_walk_v6(ire_delete_cache_gw_v6,
4114 				    (char *)&v6src, ALL_ZONES, ipst);
4115 			}
4116 		} else {
4117 			nce_hw_map_t hwm;
4118 
4119 			/*
4120 			 * ARP gives us a copy of any packet where it thinks
4121 			 * the address has changed, so that we can update our
4122 			 * caches.  We're responsible for caching known answers
4123 			 * in the current design.  We check whether the
4124 			 * hardware address really has changed in all of our
4125 			 * entries that have cached this mapping, and if so, we
4126 			 * blow them away.  This way we will immediately pick
4127 			 * up the rare case of a host changing hardware
4128 			 * address.
4129 			 */
4130 			if (src == 0)
4131 				break;
4132 			hwm.hwm_addr = src;
4133 			hwm.hwm_hwlen = arh->arh_hlen;
4134 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4135 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4136 			ndp_walk_common(ipst->ips_ndp4, NULL,
4137 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4138 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4139 		}
4140 		break;
4141 	case AR_CN_READY:
4142 		/* No external v6 resolver has a contract to use this */
4143 		if (isv6)
4144 			break;
4145 		/* If the link is down, we'll retry this later */
4146 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4147 			break;
4148 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4149 		    NULL, NULL, ipst);
4150 		if (ipif != NULL) {
4151 			/*
4152 			 * If this is a duplicate recovery, then we now need to
4153 			 * go exclusive to bring this thing back up.
4154 			 */
4155 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4156 			    IPIF_DUPLICATE) {
4157 				ipif_refrele(ipif);
4158 				ill_refhold(ill);
4159 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4160 				    B_FALSE);
4161 				return;
4162 			}
4163 			/*
4164 			 * If this is the first notice that this address is
4165 			 * ready, then let the user know now.
4166 			 */
4167 			if ((ipif->ipif_flags & IPIF_UP) &&
4168 			    !ipif->ipif_addr_ready) {
4169 				ipif_mask_reply(ipif);
4170 				ip_rts_ifmsg(ipif);
4171 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4172 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4173 			}
4174 			ipif->ipif_addr_ready = 1;
4175 			ipif_refrele(ipif);
4176 		}
4177 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4178 		if (ire != NULL) {
4179 			ire->ire_defense_count = 0;
4180 			ire_refrele(ire);
4181 		}
4182 		break;
4183 	case AR_CN_FAILED:
4184 		/* No external v6 resolver has a contract to use this */
4185 		if (isv6)
4186 			break;
4187 		ill_refhold(ill);
4188 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4189 		return;
4190 	}
4191 	freemsg(mp);
4192 }
4193 
4194 /*
4195  * Create a mblk suitable for carrying the interface index and/or source link
4196  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4197  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4198  * application.
4199  */
4200 mblk_t *
4201 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4202     ip_stack_t *ipst)
4203 {
4204 	mblk_t		*mp;
4205 	ip_pktinfo_t	*pinfo;
4206 	ipha_t *ipha;
4207 	struct ether_header *pether;
4208 
4209 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4210 	if (mp == NULL) {
4211 		ip1dbg(("ip_add_info: allocation failure.\n"));
4212 		return (data_mp);
4213 	}
4214 
4215 	ipha	= (ipha_t *)data_mp->b_rptr;
4216 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4217 	bzero(pinfo, sizeof (ip_pktinfo_t));
4218 	pinfo->ip_pkt_flags = (uchar_t)flags;
4219 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4220 
4221 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4222 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4223 	if (flags & IPF_RECVADDR) {
4224 		ipif_t	*ipif;
4225 		ire_t	*ire;
4226 
4227 		/*
4228 		 * Only valid for V4
4229 		 */
4230 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4231 		    (IPV4_VERSION << 4));
4232 
4233 		ipif = ipif_get_next_ipif(NULL, ill);
4234 		if (ipif != NULL) {
4235 			/*
4236 			 * Since a decision has already been made to deliver the
4237 			 * packet, there is no need to test for SECATTR and
4238 			 * ZONEONLY.
4239 			 * When a multicast packet is transmitted
4240 			 * a cache entry is created for the multicast address.
4241 			 * When delivering a copy of the packet or when new
4242 			 * packets are received we do not want to match on the
4243 			 * cached entry so explicitly match on
4244 			 * IRE_LOCAL and IRE_LOOPBACK
4245 			 */
4246 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4247 			    IRE_LOCAL | IRE_LOOPBACK,
4248 			    ipif, zoneid, NULL,
4249 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4250 			if (ire == NULL) {
4251 				/*
4252 				 * packet must have come on a different
4253 				 * interface.
4254 				 * Since a decision has already been made to
4255 				 * deliver the packet, there is no need to test
4256 				 * for SECATTR and ZONEONLY.
4257 				 * Only match on local and broadcast ire's.
4258 				 * See detailed comment above.
4259 				 */
4260 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4261 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4262 				    NULL, MATCH_IRE_TYPE, ipst);
4263 			}
4264 
4265 			if (ire == NULL) {
4266 				/*
4267 				 * This is either a multicast packet or
4268 				 * the address has been removed since
4269 				 * the packet was received.
4270 				 * Return INADDR_ANY so that normal source
4271 				 * selection occurs for the response.
4272 				 */
4273 
4274 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4275 			} else {
4276 				pinfo->ip_pkt_match_addr.s_addr =
4277 				    ire->ire_src_addr;
4278 				ire_refrele(ire);
4279 			}
4280 			ipif_refrele(ipif);
4281 		} else {
4282 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4283 		}
4284 	}
4285 
4286 	pether = (struct ether_header *)((char *)ipha
4287 	    - sizeof (struct ether_header));
4288 	/*
4289 	 * Make sure the interface is an ethernet type, since this option
4290 	 * is currently supported only on this type of interface. Also make
4291 	 * sure we are pointing correctly above db_base.
4292 	 */
4293 
4294 	if ((flags & IPF_RECVSLLA) &&
4295 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4296 	    (ill->ill_type == IFT_ETHER) &&
4297 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4298 
4299 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4300 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4301 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4302 	} else {
4303 		/*
4304 		 * Clear the bit. Indicate to upper layer that IP is not
4305 		 * sending this ancillary info.
4306 		 */
4307 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4308 	}
4309 
4310 	mp->b_datap->db_type = M_CTL;
4311 	mp->b_wptr += sizeof (ip_pktinfo_t);
4312 	mp->b_cont = data_mp;
4313 
4314 	return (mp);
4315 }
4316 
4317 /*
4318  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4319  * part of the bind request.
4320  */
4321 
4322 boolean_t
4323 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4324 {
4325 	ipsec_in_t *ii;
4326 
4327 	ASSERT(policy_mp != NULL);
4328 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4329 
4330 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4331 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4332 
4333 	connp->conn_policy = ii->ipsec_in_policy;
4334 	ii->ipsec_in_policy = NULL;
4335 
4336 	if (ii->ipsec_in_action != NULL) {
4337 		if (connp->conn_latch == NULL) {
4338 			connp->conn_latch = iplatch_create();
4339 			if (connp->conn_latch == NULL)
4340 				return (B_FALSE);
4341 		}
4342 		ipsec_latch_inbound(connp->conn_latch, ii);
4343 	}
4344 	return (B_TRUE);
4345 }
4346 
4347 /*
4348  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4349  * and to arrange for power-fanout assist.  The ULP is identified by
4350  * adding a single byte at the end of the original bind message.
4351  * A ULP other than UDP or TCP that wishes to be recognized passes
4352  * down a bind with a zero length address.
4353  *
4354  * The binding works as follows:
4355  * - A zero byte address means just bind to the protocol.
4356  * - A four byte address is treated as a request to validate
4357  *   that the address is a valid local address, appropriate for
4358  *   an application to bind to. This does not affect any fanout
4359  *   information in IP.
4360  * - A sizeof sin_t byte address is used to bind to only the local address
4361  *   and port.
4362  * - A sizeof ipa_conn_t byte address contains complete fanout information
4363  *   consisting of local and remote addresses and ports.  In
4364  *   this case, the addresses are both validated as appropriate
4365  *   for this operation, and, if so, the information is retained
4366  *   for use in the inbound fanout.
4367  *
4368  * The ULP (except in the zero-length bind) can append an
4369  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4370  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4371  * a copy of the source or destination IRE (source for local bind;
4372  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4373  * policy information contained should be copied on to the conn.
4374  *
4375  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4376  */
4377 mblk_t *
4378 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4379 {
4380 	ssize_t		len;
4381 	struct T_bind_req	*tbr;
4382 	sin_t		*sin;
4383 	ipa_conn_t	*ac;
4384 	uchar_t		*ucp;
4385 	mblk_t		*mp1;
4386 	boolean_t	ire_requested;
4387 	boolean_t	ipsec_policy_set = B_FALSE;
4388 	int		error = 0;
4389 	int		protocol;
4390 	ipa_conn_x_t	*acx;
4391 
4392 	ASSERT(!connp->conn_af_isv6);
4393 	connp->conn_pkt_isv6 = B_FALSE;
4394 
4395 	len = MBLKL(mp);
4396 	if (len < (sizeof (*tbr) + 1)) {
4397 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4398 		    "ip_bind: bogus msg, len %ld", len);
4399 		/* XXX: Need to return something better */
4400 		goto bad_addr;
4401 	}
4402 	/* Back up and extract the protocol identifier. */
4403 	mp->b_wptr--;
4404 	protocol = *mp->b_wptr & 0xFF;
4405 	tbr = (struct T_bind_req *)mp->b_rptr;
4406 	/* Reset the message type in preparation for shipping it back. */
4407 	DB_TYPE(mp) = M_PCPROTO;
4408 
4409 	connp->conn_ulp = (uint8_t)protocol;
4410 
4411 	/*
4412 	 * Check for a zero length address.  This is from a protocol that
4413 	 * wants to register to receive all packets of its type.
4414 	 */
4415 	if (tbr->ADDR_length == 0) {
4416 		/*
4417 		 * These protocols are now intercepted in ip_bind_v6().
4418 		 * Reject protocol-level binds here for now.
4419 		 *
4420 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4421 		 * so that the protocol type cannot be SCTP.
4422 		 */
4423 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4424 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4425 			goto bad_addr;
4426 		}
4427 
4428 		/*
4429 		 *
4430 		 * The udp module never sends down a zero-length address,
4431 		 * and allowing this on a labeled system will break MLP
4432 		 * functionality.
4433 		 */
4434 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4435 			goto bad_addr;
4436 
4437 		if (connp->conn_mac_exempt)
4438 			goto bad_addr;
4439 
4440 		/* No hash here really.  The table is big enough. */
4441 		connp->conn_srcv6 = ipv6_all_zeros;
4442 
4443 		ipcl_proto_insert(connp, protocol);
4444 
4445 		tbr->PRIM_type = T_BIND_ACK;
4446 		return (mp);
4447 	}
4448 
4449 	/* Extract the address pointer from the message. */
4450 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4451 	    tbr->ADDR_length);
4452 	if (ucp == NULL) {
4453 		ip1dbg(("ip_bind: no address\n"));
4454 		goto bad_addr;
4455 	}
4456 	if (!OK_32PTR(ucp)) {
4457 		ip1dbg(("ip_bind: unaligned address\n"));
4458 		goto bad_addr;
4459 	}
4460 	/*
4461 	 * Check for trailing mps.
4462 	 */
4463 
4464 	mp1 = mp->b_cont;
4465 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4466 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4467 
4468 	switch (tbr->ADDR_length) {
4469 	default:
4470 		ip1dbg(("ip_bind: bad address length %d\n",
4471 		    (int)tbr->ADDR_length));
4472 		goto bad_addr;
4473 
4474 	case IP_ADDR_LEN:
4475 		/* Verification of local address only */
4476 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4477 		    ire_requested, ipsec_policy_set, B_FALSE);
4478 		break;
4479 
4480 	case sizeof (sin_t):
4481 		sin = (sin_t *)ucp;
4482 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4483 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4484 		break;
4485 
4486 	case sizeof (ipa_conn_t):
4487 		ac = (ipa_conn_t *)ucp;
4488 		/* For raw socket, the local port is not set. */
4489 		if (ac->ac_lport == 0)
4490 			ac->ac_lport = connp->conn_lport;
4491 		/* Always verify destination reachability. */
4492 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4493 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4494 		    ipsec_policy_set, B_TRUE, B_TRUE);
4495 		break;
4496 
4497 	case sizeof (ipa_conn_x_t):
4498 		acx = (ipa_conn_x_t *)ucp;
4499 		/*
4500 		 * Whether or not to verify destination reachability depends
4501 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4502 		 */
4503 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4504 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4505 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4506 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4507 		break;
4508 	}
4509 	if (error == EINPROGRESS)
4510 		return (NULL);
4511 	else if (error != 0)
4512 		goto bad_addr;
4513 	/*
4514 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4515 	 * We can't do this in ip_bind_insert_ire because the policy
4516 	 * may not have been inherited at that point in time and hence
4517 	 * conn_out_enforce_policy may not be set.
4518 	 */
4519 	mp1 = mp->b_cont;
4520 	if (ire_requested && connp->conn_out_enforce_policy &&
4521 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4522 		ire_t *ire = (ire_t *)mp1->b_rptr;
4523 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4524 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4525 	}
4526 
4527 	/* Send it home. */
4528 	mp->b_datap->db_type = M_PCPROTO;
4529 	tbr->PRIM_type = T_BIND_ACK;
4530 	return (mp);
4531 
4532 bad_addr:
4533 	/*
4534 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4535 	 * a unix errno.
4536 	 */
4537 	if (error > 0)
4538 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4539 	else
4540 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4541 	return (mp);
4542 }
4543 
4544 /*
4545  * Here address is verified to be a valid local address.
4546  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4547  * address is also considered a valid local address.
4548  * In the case of a broadcast/multicast address, however, the
4549  * upper protocol is expected to reset the src address
4550  * to 0 if it sees a IRE_BROADCAST type returned so that
4551  * no packets are emitted with broadcast/multicast address as
4552  * source address (that violates hosts requirements RFC1122)
4553  * The addresses valid for bind are:
4554  *	(1) - INADDR_ANY (0)
4555  *	(2) - IP address of an UP interface
4556  *	(3) - IP address of a DOWN interface
4557  *	(4) - valid local IP broadcast addresses. In this case
4558  *	the conn will only receive packets destined to
4559  *	the specified broadcast address.
4560  *	(5) - a multicast address. In this case
4561  *	the conn will only receive packets destined to
4562  *	the specified multicast address. Note: the
4563  *	application still has to issue an
4564  *	IP_ADD_MEMBERSHIP socket option.
4565  *
4566  * On error, return -1 for TBADADDR otherwise pass the
4567  * errno with TSYSERR reply.
4568  *
4569  * In all the above cases, the bound address must be valid in the current zone.
4570  * When the address is loopback, multicast or broadcast, there might be many
4571  * matching IREs so bind has to look up based on the zone.
4572  *
4573  * Note: lport is in network byte order.
4574  */
4575 int
4576 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4577     boolean_t ire_requested, boolean_t ipsec_policy_set,
4578     boolean_t fanout_insert)
4579 {
4580 	int		error = 0;
4581 	ire_t		*src_ire;
4582 	mblk_t		*policy_mp;
4583 	ipif_t		*ipif;
4584 	zoneid_t	zoneid;
4585 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4586 
4587 	if (ipsec_policy_set) {
4588 		policy_mp = mp->b_cont;
4589 	}
4590 
4591 	/*
4592 	 * If it was previously connected, conn_fully_bound would have
4593 	 * been set.
4594 	 */
4595 	connp->conn_fully_bound = B_FALSE;
4596 
4597 	src_ire = NULL;
4598 	ipif = NULL;
4599 
4600 	zoneid = IPCL_ZONEID(connp);
4601 
4602 	if (src_addr) {
4603 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4604 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4605 		/*
4606 		 * If an address other than 0.0.0.0 is requested,
4607 		 * we verify that it is a valid address for bind
4608 		 * Note: Following code is in if-else-if form for
4609 		 * readability compared to a condition check.
4610 		 */
4611 		/* LINTED - statement has no consequent */
4612 		if (IRE_IS_LOCAL(src_ire)) {
4613 			/*
4614 			 * (2) Bind to address of local UP interface
4615 			 */
4616 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4617 			/*
4618 			 * (4) Bind to broadcast address
4619 			 * Note: permitted only from transports that
4620 			 * request IRE
4621 			 */
4622 			if (!ire_requested)
4623 				error = EADDRNOTAVAIL;
4624 		} else {
4625 			/*
4626 			 * (3) Bind to address of local DOWN interface
4627 			 * (ipif_lookup_addr() looks up all interfaces
4628 			 * but we do not get here for UP interfaces
4629 			 * - case (2) above)
4630 			 * We put the protocol byte back into the mblk
4631 			 * since we may come back via ip_wput_nondata()
4632 			 * later with this mblk if ipif_lookup_addr chooses
4633 			 * to defer processing.
4634 			 */
4635 			*mp->b_wptr++ = (char)connp->conn_ulp;
4636 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4637 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4638 			    &error, ipst)) != NULL) {
4639 				ipif_refrele(ipif);
4640 			} else if (error == EINPROGRESS) {
4641 				if (src_ire != NULL)
4642 					ire_refrele(src_ire);
4643 				return (EINPROGRESS);
4644 			} else if (CLASSD(src_addr)) {
4645 				error = 0;
4646 				if (src_ire != NULL)
4647 					ire_refrele(src_ire);
4648 				/*
4649 				 * (5) bind to multicast address.
4650 				 * Fake out the IRE returned to upper
4651 				 * layer to be a broadcast IRE.
4652 				 */
4653 				src_ire = ire_ctable_lookup(
4654 				    INADDR_BROADCAST, INADDR_ANY,
4655 				    IRE_BROADCAST, NULL, zoneid, NULL,
4656 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4657 				    ipst);
4658 				if (src_ire == NULL || !ire_requested)
4659 					error = EADDRNOTAVAIL;
4660 			} else {
4661 				/*
4662 				 * Not a valid address for bind
4663 				 */
4664 				error = EADDRNOTAVAIL;
4665 			}
4666 			/*
4667 			 * Just to keep it consistent with the processing in
4668 			 * ip_bind_v4()
4669 			 */
4670 			mp->b_wptr--;
4671 		}
4672 		if (error) {
4673 			/* Red Alert!  Attempting to be a bogon! */
4674 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4675 			    ntohl(src_addr)));
4676 			goto bad_addr;
4677 		}
4678 	}
4679 
4680 	/*
4681 	 * Allow setting new policies. For example, disconnects come
4682 	 * down as ipa_t bind. As we would have set conn_policy_cached
4683 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4684 	 * can change after the disconnect.
4685 	 */
4686 	connp->conn_policy_cached = B_FALSE;
4687 
4688 	/*
4689 	 * If not fanout_insert this was just an address verification
4690 	 */
4691 	if (fanout_insert) {
4692 		/*
4693 		 * The addresses have been verified. Time to insert in
4694 		 * the correct fanout list.
4695 		 */
4696 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4697 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4698 		connp->conn_lport = lport;
4699 		connp->conn_fport = 0;
4700 		/*
4701 		 * Do we need to add a check to reject Multicast packets
4702 		 *
4703 		 * We need to make sure that the conn_recv is set to a non-null
4704 		 * value before we insert the conn into the classifier table.
4705 		 * This is to avoid a race with an incoming packet which does an
4706 		 * ipcl_classify().
4707 		 */
4708 		if (*mp->b_wptr == IPPROTO_TCP)
4709 			connp->conn_recv = tcp_conn_request;
4710 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4711 	}
4712 
4713 	if (error == 0) {
4714 		if (ire_requested) {
4715 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4716 				error = -1;
4717 				/* Falls through to bad_addr */
4718 			}
4719 		} else if (ipsec_policy_set) {
4720 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4721 				error = -1;
4722 				/* Falls through to bad_addr */
4723 			}
4724 		}
4725 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4726 		connp->conn_recv = tcp_input;
4727 	}
4728 bad_addr:
4729 	if (error != 0) {
4730 		if (connp->conn_anon_port) {
4731 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4732 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4733 			    B_FALSE);
4734 		}
4735 		connp->conn_mlp_type = mlptSingle;
4736 	}
4737 	if (src_ire != NULL)
4738 		IRE_REFRELE(src_ire);
4739 	if (ipsec_policy_set) {
4740 		ASSERT(policy_mp == mp->b_cont);
4741 		ASSERT(policy_mp != NULL);
4742 		freeb(policy_mp);
4743 		/*
4744 		 * As of now assume that nothing else accompanies
4745 		 * IPSEC_POLICY_SET.
4746 		 */
4747 		mp->b_cont = NULL;
4748 	}
4749 	return (error);
4750 }
4751 
4752 /*
4753  * Verify that both the source and destination addresses
4754  * are valid.  If verify_dst is false, then the destination address may be
4755  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4756  * destination reachability, while tunnels do not.
4757  * Note that we allow connect to broadcast and multicast
4758  * addresses when ire_requested is set. Thus the ULP
4759  * has to check for IRE_BROADCAST and multicast.
4760  *
4761  * Returns zero if ok.
4762  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4763  * (for use with TSYSERR reply).
4764  *
4765  * Note: lport and fport are in network byte order.
4766  */
4767 int
4768 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4769     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4770     boolean_t ire_requested, boolean_t ipsec_policy_set,
4771     boolean_t fanout_insert, boolean_t verify_dst)
4772 {
4773 	ire_t		*src_ire;
4774 	ire_t		*dst_ire;
4775 	int		error = 0;
4776 	int 		protocol;
4777 	mblk_t		*policy_mp;
4778 	ire_t		*sire = NULL;
4779 	ire_t		*md_dst_ire = NULL;
4780 	ire_t		*lso_dst_ire = NULL;
4781 	ill_t		*ill = NULL;
4782 	zoneid_t	zoneid;
4783 	ipaddr_t	src_addr = *src_addrp;
4784 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4785 
4786 	src_ire = dst_ire = NULL;
4787 	protocol = *mp->b_wptr & 0xFF;
4788 
4789 	/*
4790 	 * If we never got a disconnect before, clear it now.
4791 	 */
4792 	connp->conn_fully_bound = B_FALSE;
4793 
4794 	if (ipsec_policy_set) {
4795 		policy_mp = mp->b_cont;
4796 	}
4797 
4798 	zoneid = IPCL_ZONEID(connp);
4799 
4800 	if (CLASSD(dst_addr)) {
4801 		/* Pick up an IRE_BROADCAST */
4802 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4803 		    NULL, zoneid, MBLK_GETLABEL(mp),
4804 		    (MATCH_IRE_RECURSIVE |
4805 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4806 		    MATCH_IRE_SECATTR), ipst);
4807 	} else {
4808 		/*
4809 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4810 		 * and onlink ipif is not found set ENETUNREACH error.
4811 		 */
4812 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4813 			ipif_t *ipif;
4814 
4815 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4816 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4817 			if (ipif == NULL) {
4818 				error = ENETUNREACH;
4819 				goto bad_addr;
4820 			}
4821 			ipif_refrele(ipif);
4822 		}
4823 
4824 		if (connp->conn_nexthop_set) {
4825 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4826 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4827 			    MATCH_IRE_SECATTR, ipst);
4828 		} else {
4829 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4830 			    &sire, zoneid, MBLK_GETLABEL(mp),
4831 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4832 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4833 			    MATCH_IRE_SECATTR), ipst);
4834 		}
4835 	}
4836 	/*
4837 	 * dst_ire can't be a broadcast when not ire_requested.
4838 	 * We also prevent ire's with src address INADDR_ANY to
4839 	 * be used, which are created temporarily for
4840 	 * sending out packets from endpoints that have
4841 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4842 	 * reachable.  If verify_dst is false, the destination needn't be
4843 	 * reachable.
4844 	 *
4845 	 * If we match on a reject or black hole, then we've got a
4846 	 * local failure.  May as well fail out the connect() attempt,
4847 	 * since it's never going to succeed.
4848 	 */
4849 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4850 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4851 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4852 		/*
4853 		 * If we're verifying destination reachability, we always want
4854 		 * to complain here.
4855 		 *
4856 		 * If we're not verifying destination reachability but the
4857 		 * destination has a route, we still want to fail on the
4858 		 * temporary address and broadcast address tests.
4859 		 */
4860 		if (verify_dst || (dst_ire != NULL)) {
4861 			if (ip_debug > 2) {
4862 				pr_addr_dbg("ip_bind_connected: bad connected "
4863 				    "dst %s\n", AF_INET, &dst_addr);
4864 			}
4865 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4866 				error = ENETUNREACH;
4867 			else
4868 				error = EHOSTUNREACH;
4869 			goto bad_addr;
4870 		}
4871 	}
4872 
4873 	/*
4874 	 * We now know that routing will allow us to reach the destination.
4875 	 * Check whether Trusted Solaris policy allows communication with this
4876 	 * host, and pretend that the destination is unreachable if not.
4877 	 *
4878 	 * This is never a problem for TCP, since that transport is known to
4879 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4880 	 * handling.  If the remote is unreachable, it will be detected at that
4881 	 * point, so there's no reason to check it here.
4882 	 *
4883 	 * Note that for sendto (and other datagram-oriented friends), this
4884 	 * check is done as part of the data path label computation instead.
4885 	 * The check here is just to make non-TCP connect() report the right
4886 	 * error.
4887 	 */
4888 	if (dst_ire != NULL && is_system_labeled() &&
4889 	    !IPCL_IS_TCP(connp) &&
4890 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4891 	    connp->conn_mac_exempt, ipst) != 0) {
4892 		error = EHOSTUNREACH;
4893 		if (ip_debug > 2) {
4894 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4895 			    AF_INET, &dst_addr);
4896 		}
4897 		goto bad_addr;
4898 	}
4899 
4900 	/*
4901 	 * If the app does a connect(), it means that it will most likely
4902 	 * send more than 1 packet to the destination.  It makes sense
4903 	 * to clear the temporary flag.
4904 	 */
4905 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4906 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4907 		irb_t *irb = dst_ire->ire_bucket;
4908 
4909 		rw_enter(&irb->irb_lock, RW_WRITER);
4910 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4911 		irb->irb_tmp_ire_cnt--;
4912 		rw_exit(&irb->irb_lock);
4913 	}
4914 
4915 	/*
4916 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4917 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4918 	 * eligibility tests for passive connects are handled separately
4919 	 * through tcp_adapt_ire().  We do this before the source address
4920 	 * selection, because dst_ire may change after a call to
4921 	 * ipif_select_source().  This is a best-effort check, as the
4922 	 * packet for this connection may not actually go through
4923 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4924 	 * calling ip_newroute().  This is why we further check on the
4925 	 * IRE during LSO/Multidata packet transmission in
4926 	 * tcp_lsosend()/tcp_multisend().
4927 	 */
4928 	if (!ipsec_policy_set && dst_ire != NULL &&
4929 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4930 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4931 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4932 			lso_dst_ire = dst_ire;
4933 			IRE_REFHOLD(lso_dst_ire);
4934 		} else if (ipst->ips_ip_multidata_outbound &&
4935 		    ILL_MDT_CAPABLE(ill)) {
4936 			md_dst_ire = dst_ire;
4937 			IRE_REFHOLD(md_dst_ire);
4938 		}
4939 	}
4940 
4941 	if (dst_ire != NULL &&
4942 	    dst_ire->ire_type == IRE_LOCAL &&
4943 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4944 		/*
4945 		 * If the IRE belongs to a different zone, look for a matching
4946 		 * route in the forwarding table and use the source address from
4947 		 * that route.
4948 		 */
4949 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4950 		    zoneid, 0, NULL,
4951 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4952 		    MATCH_IRE_RJ_BHOLE, ipst);
4953 		if (src_ire == NULL) {
4954 			error = EHOSTUNREACH;
4955 			goto bad_addr;
4956 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4957 			if (!(src_ire->ire_type & IRE_HOST))
4958 				error = ENETUNREACH;
4959 			else
4960 				error = EHOSTUNREACH;
4961 			goto bad_addr;
4962 		}
4963 		if (src_addr == INADDR_ANY)
4964 			src_addr = src_ire->ire_src_addr;
4965 		ire_refrele(src_ire);
4966 		src_ire = NULL;
4967 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4968 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4969 			src_addr = sire->ire_src_addr;
4970 			ire_refrele(dst_ire);
4971 			dst_ire = sire;
4972 			sire = NULL;
4973 		} else {
4974 			/*
4975 			 * Pick a source address so that a proper inbound
4976 			 * load spreading would happen.
4977 			 */
4978 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4979 			ipif_t *src_ipif = NULL;
4980 			ire_t *ipif_ire;
4981 
4982 			/*
4983 			 * Supply a local source address such that inbound
4984 			 * load spreading happens.
4985 			 *
4986 			 * Determine the best source address on this ill for
4987 			 * the destination.
4988 			 *
4989 			 * 1) For broadcast, we should return a broadcast ire
4990 			 *    found above so that upper layers know that the
4991 			 *    destination address is a broadcast address.
4992 			 *
4993 			 * 2) If this is part of a group, select a better
4994 			 *    source address so that better inbound load
4995 			 *    balancing happens. Do the same if the ipif
4996 			 *    is DEPRECATED.
4997 			 *
4998 			 * 3) If the outgoing interface is part of a usesrc
4999 			 *    group, then try selecting a source address from
5000 			 *    the usesrc ILL.
5001 			 */
5002 			if ((dst_ire->ire_zoneid != zoneid &&
5003 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5004 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5005 			    ((dst_ill->ill_group != NULL) ||
5006 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5007 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
5008 				/*
5009 				 * If the destination is reachable via a
5010 				 * given gateway, the selected source address
5011 				 * should be in the same subnet as the gateway.
5012 				 * Otherwise, the destination is not reachable.
5013 				 *
5014 				 * If there are no interfaces on the same subnet
5015 				 * as the destination, ipif_select_source gives
5016 				 * first non-deprecated interface which might be
5017 				 * on a different subnet than the gateway.
5018 				 * This is not desirable. Hence pass the dst_ire
5019 				 * source address to ipif_select_source.
5020 				 * It is sure that the destination is reachable
5021 				 * with the dst_ire source address subnet.
5022 				 * So passing dst_ire source address to
5023 				 * ipif_select_source will make sure that the
5024 				 * selected source will be on the same subnet
5025 				 * as dst_ire source address.
5026 				 */
5027 				ipaddr_t saddr =
5028 				    dst_ire->ire_ipif->ipif_src_addr;
5029 				src_ipif = ipif_select_source(dst_ill,
5030 				    saddr, zoneid);
5031 				if (src_ipif != NULL) {
5032 					if (IS_VNI(src_ipif->ipif_ill)) {
5033 						/*
5034 						 * For VNI there is no
5035 						 * interface route
5036 						 */
5037 						src_addr =
5038 						    src_ipif->ipif_src_addr;
5039 					} else {
5040 						ipif_ire =
5041 						    ipif_to_ire(src_ipif);
5042 						if (ipif_ire != NULL) {
5043 							IRE_REFRELE(dst_ire);
5044 							dst_ire = ipif_ire;
5045 						}
5046 						src_addr =
5047 						    dst_ire->ire_src_addr;
5048 					}
5049 					ipif_refrele(src_ipif);
5050 				} else {
5051 					src_addr = dst_ire->ire_src_addr;
5052 				}
5053 			} else {
5054 				src_addr = dst_ire->ire_src_addr;
5055 			}
5056 		}
5057 	}
5058 
5059 	/*
5060 	 * We do ire_route_lookup() here (and not
5061 	 * interface lookup as we assert that
5062 	 * src_addr should only come from an
5063 	 * UP interface for hard binding.
5064 	 */
5065 	ASSERT(src_ire == NULL);
5066 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5067 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5068 	/* src_ire must be a local|loopback */
5069 	if (!IRE_IS_LOCAL(src_ire)) {
5070 		if (ip_debug > 2) {
5071 			pr_addr_dbg("ip_bind_connected: bad connected "
5072 			    "src %s\n", AF_INET, &src_addr);
5073 		}
5074 		error = EADDRNOTAVAIL;
5075 		goto bad_addr;
5076 	}
5077 
5078 	/*
5079 	 * If the source address is a loopback address, the
5080 	 * destination had best be local or multicast.
5081 	 * The transports that can't handle multicast will reject
5082 	 * those addresses.
5083 	 */
5084 	if (src_ire->ire_type == IRE_LOOPBACK &&
5085 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5086 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5087 		error = -1;
5088 		goto bad_addr;
5089 	}
5090 
5091 	/*
5092 	 * Allow setting new policies. For example, disconnects come
5093 	 * down as ipa_t bind. As we would have set conn_policy_cached
5094 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5095 	 * can change after the disconnect.
5096 	 */
5097 	connp->conn_policy_cached = B_FALSE;
5098 
5099 	/*
5100 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5101 	 * can handle their passed-in conn's.
5102 	 */
5103 
5104 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5105 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5106 	connp->conn_lport = lport;
5107 	connp->conn_fport = fport;
5108 	*src_addrp = src_addr;
5109 
5110 	ASSERT(!(ipsec_policy_set && ire_requested));
5111 	if (ire_requested) {
5112 		iulp_t *ulp_info = NULL;
5113 
5114 		/*
5115 		 * Note that sire will not be NULL if this is an off-link
5116 		 * connection and there is not cache for that dest yet.
5117 		 *
5118 		 * XXX Because of an existing bug, if there are multiple
5119 		 * default routes, the IRE returned now may not be the actual
5120 		 * default route used (default routes are chosen in a
5121 		 * round robin fashion).  So if the metrics for different
5122 		 * default routes are different, we may return the wrong
5123 		 * metrics.  This will not be a problem if the existing
5124 		 * bug is fixed.
5125 		 */
5126 		if (sire != NULL) {
5127 			ulp_info = &(sire->ire_uinfo);
5128 		}
5129 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5130 			error = -1;
5131 			goto bad_addr;
5132 		}
5133 	} else if (ipsec_policy_set) {
5134 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5135 			error = -1;
5136 			goto bad_addr;
5137 		}
5138 	}
5139 
5140 	/*
5141 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5142 	 * we'll cache that.  If we don't, we'll inherit global policy.
5143 	 *
5144 	 * We can't insert until the conn reflects the policy. Note that
5145 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5146 	 * connections where we don't have a policy. This is to prevent
5147 	 * global policy lookups in the inbound path.
5148 	 *
5149 	 * If we insert before we set conn_policy_cached,
5150 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5151 	 * because global policy cound be non-empty. We normally call
5152 	 * ipsec_check_policy() for conn_policy_cached connections only if
5153 	 * ipc_in_enforce_policy is set. But in this case,
5154 	 * conn_policy_cached can get set anytime since we made the
5155 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5156 	 * called, which will make the above assumption false.  Thus, we
5157 	 * need to insert after we set conn_policy_cached.
5158 	 */
5159 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5160 		goto bad_addr;
5161 
5162 	if (fanout_insert) {
5163 		/*
5164 		 * The addresses have been verified. Time to insert in
5165 		 * the correct fanout list.
5166 		 * We need to make sure that the conn_recv is set to a non-null
5167 		 * value before we insert into the classifier table to avoid a
5168 		 * race with an incoming packet which does an ipcl_classify().
5169 		 */
5170 		if (protocol == IPPROTO_TCP)
5171 			connp->conn_recv = tcp_input;
5172 		error = ipcl_conn_insert(connp, protocol, src_addr,
5173 		    dst_addr, connp->conn_ports);
5174 	}
5175 
5176 	if (error == 0) {
5177 		connp->conn_fully_bound = B_TRUE;
5178 		/*
5179 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5180 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5181 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5182 		 * ip_xxinfo_return(), which performs further checks
5183 		 * against them and upon success, returns the LSO/MDT info
5184 		 * mblk which we will attach to the bind acknowledgment.
5185 		 */
5186 		if (lso_dst_ire != NULL) {
5187 			mblk_t *lsoinfo_mp;
5188 
5189 			ASSERT(ill->ill_lso_capab != NULL);
5190 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5191 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5192 				linkb(mp, lsoinfo_mp);
5193 		} else if (md_dst_ire != NULL) {
5194 			mblk_t *mdinfo_mp;
5195 
5196 			ASSERT(ill->ill_mdt_capab != NULL);
5197 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5198 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5199 				linkb(mp, mdinfo_mp);
5200 		}
5201 	}
5202 bad_addr:
5203 	if (ipsec_policy_set) {
5204 		ASSERT(policy_mp == mp->b_cont);
5205 		ASSERT(policy_mp != NULL);
5206 		freeb(policy_mp);
5207 		/*
5208 		 * As of now assume that nothing else accompanies
5209 		 * IPSEC_POLICY_SET.
5210 		 */
5211 		mp->b_cont = NULL;
5212 	}
5213 	if (src_ire != NULL)
5214 		IRE_REFRELE(src_ire);
5215 	if (dst_ire != NULL)
5216 		IRE_REFRELE(dst_ire);
5217 	if (sire != NULL)
5218 		IRE_REFRELE(sire);
5219 	if (md_dst_ire != NULL)
5220 		IRE_REFRELE(md_dst_ire);
5221 	if (lso_dst_ire != NULL)
5222 		IRE_REFRELE(lso_dst_ire);
5223 	return (error);
5224 }
5225 
5226 /*
5227  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5228  * Prefers dst_ire over src_ire.
5229  */
5230 static boolean_t
5231 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5232 {
5233 	mblk_t	*mp1;
5234 	ire_t *ret_ire = NULL;
5235 
5236 	mp1 = mp->b_cont;
5237 	ASSERT(mp1 != NULL);
5238 
5239 	if (ire != NULL) {
5240 		/*
5241 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5242 		 * appended mblk. Its <upper protocol>'s
5243 		 * job to make sure there is room.
5244 		 */
5245 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5246 			return (0);
5247 
5248 		mp1->b_datap->db_type = IRE_DB_TYPE;
5249 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5250 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5251 		ret_ire = (ire_t *)mp1->b_rptr;
5252 		/*
5253 		 * Pass the latest setting of the ip_path_mtu_discovery and
5254 		 * copy the ulp info if any.
5255 		 */
5256 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5257 		    IPH_DF : 0;
5258 		if (ulp_info != NULL) {
5259 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5260 			    sizeof (iulp_t));
5261 		}
5262 		ret_ire->ire_mp = mp1;
5263 	} else {
5264 		/*
5265 		 * No IRE was found. Remove IRE mblk.
5266 		 */
5267 		mp->b_cont = mp1->b_cont;
5268 		freeb(mp1);
5269 	}
5270 
5271 	return (1);
5272 }
5273 
5274 /*
5275  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5276  * the final piece where we don't.  Return a pointer to the first mblk in the
5277  * result, and update the pointer to the next mblk to chew on.  If anything
5278  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5279  * NULL pointer.
5280  */
5281 mblk_t *
5282 ip_carve_mp(mblk_t **mpp, ssize_t len)
5283 {
5284 	mblk_t	*mp0;
5285 	mblk_t	*mp1;
5286 	mblk_t	*mp2;
5287 
5288 	if (!len || !mpp || !(mp0 = *mpp))
5289 		return (NULL);
5290 	/* If we aren't going to consume the first mblk, we need a dup. */
5291 	if (mp0->b_wptr - mp0->b_rptr > len) {
5292 		mp1 = dupb(mp0);
5293 		if (mp1) {
5294 			/* Partition the data between the two mblks. */
5295 			mp1->b_wptr = mp1->b_rptr + len;
5296 			mp0->b_rptr = mp1->b_wptr;
5297 			/*
5298 			 * after adjustments if mblk not consumed is now
5299 			 * unaligned, try to align it. If this fails free
5300 			 * all messages and let upper layer recover.
5301 			 */
5302 			if (!OK_32PTR(mp0->b_rptr)) {
5303 				if (!pullupmsg(mp0, -1)) {
5304 					freemsg(mp0);
5305 					freemsg(mp1);
5306 					*mpp = NULL;
5307 					return (NULL);
5308 				}
5309 			}
5310 		}
5311 		return (mp1);
5312 	}
5313 	/* Eat through as many mblks as we need to get len bytes. */
5314 	len -= mp0->b_wptr - mp0->b_rptr;
5315 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5316 		if (mp2->b_wptr - mp2->b_rptr > len) {
5317 			/*
5318 			 * We won't consume the entire last mblk.  Like
5319 			 * above, dup and partition it.
5320 			 */
5321 			mp1->b_cont = dupb(mp2);
5322 			mp1 = mp1->b_cont;
5323 			if (!mp1) {
5324 				/*
5325 				 * Trouble.  Rather than go to a lot of
5326 				 * trouble to clean up, we free the messages.
5327 				 * This won't be any worse than losing it on
5328 				 * the wire.
5329 				 */
5330 				freemsg(mp0);
5331 				freemsg(mp2);
5332 				*mpp = NULL;
5333 				return (NULL);
5334 			}
5335 			mp1->b_wptr = mp1->b_rptr + len;
5336 			mp2->b_rptr = mp1->b_wptr;
5337 			/*
5338 			 * after adjustments if mblk not consumed is now
5339 			 * unaligned, try to align it. If this fails free
5340 			 * all messages and let upper layer recover.
5341 			 */
5342 			if (!OK_32PTR(mp2->b_rptr)) {
5343 				if (!pullupmsg(mp2, -1)) {
5344 					freemsg(mp0);
5345 					freemsg(mp2);
5346 					*mpp = NULL;
5347 					return (NULL);
5348 				}
5349 			}
5350 			*mpp = mp2;
5351 			return (mp0);
5352 		}
5353 		/* Decrement len by the amount we just got. */
5354 		len -= mp2->b_wptr - mp2->b_rptr;
5355 	}
5356 	/*
5357 	 * len should be reduced to zero now.  If not our caller has
5358 	 * screwed up.
5359 	 */
5360 	if (len) {
5361 		/* Shouldn't happen! */
5362 		freemsg(mp0);
5363 		*mpp = NULL;
5364 		return (NULL);
5365 	}
5366 	/*
5367 	 * We consumed up to exactly the end of an mblk.  Detach the part
5368 	 * we are returning from the rest of the chain.
5369 	 */
5370 	mp1->b_cont = NULL;
5371 	*mpp = mp2;
5372 	return (mp0);
5373 }
5374 
5375 /* The ill stream is being unplumbed. Called from ip_close */
5376 int
5377 ip_modclose(ill_t *ill)
5378 {
5379 	boolean_t success;
5380 	ipsq_t	*ipsq;
5381 	ipif_t	*ipif;
5382 	queue_t	*q = ill->ill_rq;
5383 	ip_stack_t	*ipst = ill->ill_ipst;
5384 	clock_t timeout;
5385 
5386 	/*
5387 	 * Wait for the ACKs of all deferred control messages to be processed.
5388 	 * In particular, we wait for a potential capability reset initiated
5389 	 * in ip_sioctl_plink() to complete before proceeding.
5390 	 *
5391 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5392 	 * in case the driver never replies.
5393 	 */
5394 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5395 	mutex_enter(&ill->ill_lock);
5396 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5397 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5398 			/* Timeout */
5399 			break;
5400 		}
5401 	}
5402 	mutex_exit(&ill->ill_lock);
5403 
5404 	/*
5405 	 * Forcibly enter the ipsq after some delay. This is to take
5406 	 * care of the case when some ioctl does not complete because
5407 	 * we sent a control message to the driver and it did not
5408 	 * send us a reply. We want to be able to at least unplumb
5409 	 * and replumb rather than force the user to reboot the system.
5410 	 */
5411 	success = ipsq_enter(ill, B_FALSE);
5412 
5413 	/*
5414 	 * Open/close/push/pop is guaranteed to be single threaded
5415 	 * per stream by STREAMS. FS guarantees that all references
5416 	 * from top are gone before close is called. So there can't
5417 	 * be another close thread that has set CONDEMNED on this ill.
5418 	 * and cause ipsq_enter to return failure.
5419 	 */
5420 	ASSERT(success);
5421 	ipsq = ill->ill_phyint->phyint_ipsq;
5422 
5423 	/*
5424 	 * Mark it condemned. No new reference will be made to this ill.
5425 	 * Lookup functions will return an error. Threads that try to
5426 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5427 	 * that the refcnt will drop down to zero.
5428 	 */
5429 	mutex_enter(&ill->ill_lock);
5430 	ill->ill_state_flags |= ILL_CONDEMNED;
5431 	for (ipif = ill->ill_ipif; ipif != NULL;
5432 	    ipif = ipif->ipif_next) {
5433 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5434 	}
5435 	/*
5436 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5437 	 * returns  error if ILL_CONDEMNED is set
5438 	 */
5439 	cv_broadcast(&ill->ill_cv);
5440 	mutex_exit(&ill->ill_lock);
5441 
5442 	/*
5443 	 * Send all the deferred DLPI messages downstream which came in
5444 	 * during the small window right before ipsq_enter(). We do this
5445 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5446 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5447 	 */
5448 	ill_dlpi_send_deferred(ill);
5449 
5450 	/*
5451 	 * Shut down fragmentation reassembly.
5452 	 * ill_frag_timer won't start a timer again.
5453 	 * Now cancel any existing timer
5454 	 */
5455 	(void) untimeout(ill->ill_frag_timer_id);
5456 	(void) ill_frag_timeout(ill, 0);
5457 
5458 	/*
5459 	 * If MOVE was in progress, clear the
5460 	 * move_in_progress fields also.
5461 	 */
5462 	if (ill->ill_move_in_progress) {
5463 		ILL_CLEAR_MOVE(ill);
5464 	}
5465 
5466 	/*
5467 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5468 	 * this ill. Then wait for the refcnts to drop to zero.
5469 	 * ill_is_quiescent checks whether the ill is really quiescent.
5470 	 * Then make sure that threads that are waiting to enter the
5471 	 * ipsq have seen the error returned by ipsq_enter and have
5472 	 * gone away. Then we call ill_delete_tail which does the
5473 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5474 	 */
5475 	ill_delete(ill);
5476 	mutex_enter(&ill->ill_lock);
5477 	while (!ill_is_quiescent(ill))
5478 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5479 	while (ill->ill_waiters)
5480 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5481 
5482 	mutex_exit(&ill->ill_lock);
5483 
5484 	/*
5485 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5486 	 * it held until the end of the function since the cleanup
5487 	 * below needs to be able to use the ip_stack_t.
5488 	 */
5489 	netstack_hold(ipst->ips_netstack);
5490 
5491 	/* qprocsoff is called in ill_delete_tail */
5492 	ill_delete_tail(ill);
5493 	ASSERT(ill->ill_ipst == NULL);
5494 
5495 	/*
5496 	 * Walk through all upper (conn) streams and qenable
5497 	 * those that have queued data.
5498 	 * close synchronization needs this to
5499 	 * be done to ensure that all upper layers blocked
5500 	 * due to flow control to the closing device
5501 	 * get unblocked.
5502 	 */
5503 	ip1dbg(("ip_wsrv: walking\n"));
5504 	conn_walk_drain(ipst);
5505 
5506 	mutex_enter(&ipst->ips_ip_mi_lock);
5507 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5508 	mutex_exit(&ipst->ips_ip_mi_lock);
5509 
5510 	/*
5511 	 * credp could be null if the open didn't succeed and ip_modopen
5512 	 * itself calls ip_close.
5513 	 */
5514 	if (ill->ill_credp != NULL)
5515 		crfree(ill->ill_credp);
5516 
5517 	mutex_enter(&ill->ill_lock);
5518 	ill_nic_info_dispatch(ill);
5519 	mutex_exit(&ill->ill_lock);
5520 
5521 	/*
5522 	 * Now we are done with the module close pieces that
5523 	 * need the netstack_t.
5524 	 */
5525 	netstack_rele(ipst->ips_netstack);
5526 
5527 	mi_close_free((IDP)ill);
5528 	q->q_ptr = WR(q)->q_ptr = NULL;
5529 
5530 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5531 
5532 	return (0);
5533 }
5534 
5535 /*
5536  * This is called as part of close() for both IP and UDP
5537  * in order to quiesce the conn.
5538  */
5539 void
5540 ip_quiesce_conn(conn_t *connp)
5541 {
5542 	boolean_t	drain_cleanup_reqd = B_FALSE;
5543 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5544 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5545 	ip_stack_t	*ipst;
5546 
5547 	ASSERT(!IPCL_IS_TCP(connp));
5548 	ipst = connp->conn_netstack->netstack_ip;
5549 
5550 	/*
5551 	 * Mark the conn as closing, and this conn must not be
5552 	 * inserted in future into any list. Eg. conn_drain_insert(),
5553 	 * won't insert this conn into the conn_drain_list.
5554 	 * Similarly ill_pending_mp_add() will not add any mp to
5555 	 * the pending mp list, after this conn has started closing.
5556 	 *
5557 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5558 	 * cannot get set henceforth.
5559 	 */
5560 	mutex_enter(&connp->conn_lock);
5561 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5562 	connp->conn_state_flags |= CONN_CLOSING;
5563 	if (connp->conn_idl != NULL)
5564 		drain_cleanup_reqd = B_TRUE;
5565 	if (connp->conn_oper_pending_ill != NULL)
5566 		conn_ioctl_cleanup_reqd = B_TRUE;
5567 	if (connp->conn_ilg_inuse != 0)
5568 		ilg_cleanup_reqd = B_TRUE;
5569 	mutex_exit(&connp->conn_lock);
5570 
5571 	if (IPCL_IS_UDP(connp))
5572 		udp_quiesce_conn(connp);
5573 
5574 	if (conn_ioctl_cleanup_reqd)
5575 		conn_ioctl_cleanup(connp);
5576 
5577 	if (is_system_labeled() && connp->conn_anon_port) {
5578 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5579 		    connp->conn_mlp_type, connp->conn_ulp,
5580 		    ntohs(connp->conn_lport), B_FALSE);
5581 		connp->conn_anon_port = 0;
5582 	}
5583 	connp->conn_mlp_type = mlptSingle;
5584 
5585 	/*
5586 	 * Remove this conn from any fanout list it is on.
5587 	 * and then wait for any threads currently operating
5588 	 * on this endpoint to finish
5589 	 */
5590 	ipcl_hash_remove(connp);
5591 
5592 	/*
5593 	 * Remove this conn from the drain list, and do
5594 	 * any other cleanup that may be required.
5595 	 * (Only non-tcp streams may have a non-null conn_idl.
5596 	 * TCP streams are never flow controlled, and
5597 	 * conn_idl will be null)
5598 	 */
5599 	if (drain_cleanup_reqd)
5600 		conn_drain_tail(connp, B_TRUE);
5601 
5602 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5603 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5604 		(void) ip_mrouter_done(NULL, ipst);
5605 
5606 	if (ilg_cleanup_reqd)
5607 		ilg_delete_all(connp);
5608 
5609 	conn_delete_ire(connp, NULL);
5610 
5611 	/*
5612 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5613 	 * callers from write side can't be there now because close
5614 	 * is in progress. The only other caller is ipcl_walk
5615 	 * which checks for the condemned flag.
5616 	 */
5617 	mutex_enter(&connp->conn_lock);
5618 	connp->conn_state_flags |= CONN_CONDEMNED;
5619 	while (connp->conn_ref != 1)
5620 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5621 	connp->conn_state_flags |= CONN_QUIESCED;
5622 	mutex_exit(&connp->conn_lock);
5623 }
5624 
5625 /* ARGSUSED */
5626 int
5627 ip_close(queue_t *q, int flags)
5628 {
5629 	conn_t		*connp;
5630 
5631 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5632 
5633 	/*
5634 	 * Call the appropriate delete routine depending on whether this is
5635 	 * a module or device.
5636 	 */
5637 	if (WR(q)->q_next != NULL) {
5638 		/* This is a module close */
5639 		return (ip_modclose((ill_t *)q->q_ptr));
5640 	}
5641 
5642 	connp = q->q_ptr;
5643 	ip_quiesce_conn(connp);
5644 
5645 	qprocsoff(q);
5646 
5647 	/*
5648 	 * Now we are truly single threaded on this stream, and can
5649 	 * delete the things hanging off the connp, and finally the connp.
5650 	 * We removed this connp from the fanout list, it cannot be
5651 	 * accessed thru the fanouts, and we already waited for the
5652 	 * conn_ref to drop to 0. We are already in close, so
5653 	 * there cannot be any other thread from the top. qprocsoff
5654 	 * has completed, and service has completed or won't run in
5655 	 * future.
5656 	 */
5657 	ASSERT(connp->conn_ref == 1);
5658 
5659 	/*
5660 	 * A conn which was previously marked as IPCL_UDP cannot
5661 	 * retain the flag because it would have been cleared by
5662 	 * udp_close().
5663 	 */
5664 	ASSERT(!IPCL_IS_UDP(connp));
5665 
5666 	if (connp->conn_latch != NULL) {
5667 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5668 		connp->conn_latch = NULL;
5669 	}
5670 	if (connp->conn_policy != NULL) {
5671 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5672 		connp->conn_policy = NULL;
5673 	}
5674 	if (connp->conn_ipsec_opt_mp != NULL) {
5675 		freemsg(connp->conn_ipsec_opt_mp);
5676 		connp->conn_ipsec_opt_mp = NULL;
5677 	}
5678 
5679 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5680 
5681 	connp->conn_ref--;
5682 	ipcl_conn_destroy(connp);
5683 
5684 	q->q_ptr = WR(q)->q_ptr = NULL;
5685 	return (0);
5686 }
5687 
5688 int
5689 ip_snmpmod_close(queue_t *q)
5690 {
5691 	conn_t *connp = Q_TO_CONN(q);
5692 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5693 
5694 	qprocsoff(q);
5695 
5696 	if (connp->conn_flags & IPCL_UDPMOD)
5697 		udp_close_free(connp);
5698 
5699 	if (connp->conn_cred != NULL) {
5700 		crfree(connp->conn_cred);
5701 		connp->conn_cred = NULL;
5702 	}
5703 	CONN_DEC_REF(connp);
5704 	q->q_ptr = WR(q)->q_ptr = NULL;
5705 	return (0);
5706 }
5707 
5708 /*
5709  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5710  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5711  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5712  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5713  * queues as we never enqueue messages there and we don't handle any ioctls.
5714  * Everything else is freed.
5715  */
5716 void
5717 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5718 {
5719 	conn_t	*connp = q->q_ptr;
5720 	pfi_t	setfn;
5721 	pfi_t	getfn;
5722 
5723 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5724 
5725 	switch (DB_TYPE(mp)) {
5726 	case M_PROTO:
5727 	case M_PCPROTO:
5728 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5729 		    ((((union T_primitives *)mp->b_rptr)->type ==
5730 		    T_SVR4_OPTMGMT_REQ) ||
5731 		    (((union T_primitives *)mp->b_rptr)->type ==
5732 		    T_OPTMGMT_REQ))) {
5733 			/*
5734 			 * This is the only TPI primitive supported. Its
5735 			 * handling does not require tcp_t, but it does require
5736 			 * conn_t to check permissions.
5737 			 */
5738 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5739 
5740 			if (connp->conn_flags & IPCL_TCPMOD) {
5741 				setfn = tcp_snmp_set;
5742 				getfn = tcp_snmp_get;
5743 			} else {
5744 				setfn = udp_snmp_set;
5745 				getfn = udp_snmp_get;
5746 			}
5747 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5748 				freemsg(mp);
5749 				return;
5750 			}
5751 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5752 		    != NULL)
5753 			qreply(q, mp);
5754 		break;
5755 	case M_FLUSH:
5756 	case M_IOCTL:
5757 		putnext(q, mp);
5758 		break;
5759 	default:
5760 		freemsg(mp);
5761 		break;
5762 	}
5763 }
5764 
5765 /* Return the IP checksum for the IP header at "iph". */
5766 uint16_t
5767 ip_csum_hdr(ipha_t *ipha)
5768 {
5769 	uint16_t	*uph;
5770 	uint32_t	sum;
5771 	int		opt_len;
5772 
5773 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5774 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5775 	uph = (uint16_t *)ipha;
5776 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5777 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5778 	if (opt_len > 0) {
5779 		do {
5780 			sum += uph[10];
5781 			sum += uph[11];
5782 			uph += 2;
5783 		} while (--opt_len);
5784 	}
5785 	sum = (sum & 0xFFFF) + (sum >> 16);
5786 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5787 	if (sum == 0xffff)
5788 		sum = 0;
5789 	return ((uint16_t)sum);
5790 }
5791 
5792 /*
5793  * Called when the module is about to be unloaded
5794  */
5795 void
5796 ip_ddi_destroy(void)
5797 {
5798 	tnet_fini();
5799 
5800 	sctp_ddi_g_destroy();
5801 	tcp_ddi_g_destroy();
5802 	ipsec_policy_g_destroy();
5803 	ipcl_g_destroy();
5804 	ip_net_g_destroy();
5805 	ip_ire_g_fini();
5806 	inet_minor_destroy(ip_minor_arena);
5807 
5808 	netstack_unregister(NS_IP);
5809 }
5810 
5811 /*
5812  * First step in cleanup.
5813  */
5814 /* ARGSUSED */
5815 static void
5816 ip_stack_shutdown(netstackid_t stackid, void *arg)
5817 {
5818 	ip_stack_t *ipst = (ip_stack_t *)arg;
5819 
5820 #ifdef NS_DEBUG
5821 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5822 #endif
5823 
5824 	/* Get rid of loopback interfaces and their IREs */
5825 	ip_loopback_cleanup(ipst);
5826 }
5827 
5828 /*
5829  * Free the IP stack instance.
5830  */
5831 static void
5832 ip_stack_fini(netstackid_t stackid, void *arg)
5833 {
5834 	ip_stack_t *ipst = (ip_stack_t *)arg;
5835 	int ret;
5836 
5837 #ifdef NS_DEBUG
5838 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5839 #endif
5840 	ipv4_hook_destroy(ipst);
5841 	ipv6_hook_destroy(ipst);
5842 	ip_net_destroy(ipst);
5843 
5844 	rw_destroy(&ipst->ips_srcid_lock);
5845 
5846 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5847 	ipst->ips_ip_mibkp = NULL;
5848 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5849 	ipst->ips_icmp_mibkp = NULL;
5850 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5851 	ipst->ips_ip_kstat = NULL;
5852 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5853 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5854 	ipst->ips_ip6_kstat = NULL;
5855 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5856 
5857 	nd_free(&ipst->ips_ip_g_nd);
5858 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5859 	ipst->ips_param_arr = NULL;
5860 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5861 	ipst->ips_ndp_arr = NULL;
5862 
5863 	ip_mrouter_stack_destroy(ipst);
5864 
5865 	mutex_destroy(&ipst->ips_ip_mi_lock);
5866 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5867 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5868 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5869 
5870 	ret = untimeout(ipst->ips_igmp_timeout_id);
5871 	if (ret == -1) {
5872 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5873 	} else {
5874 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5875 		ipst->ips_igmp_timeout_id = 0;
5876 	}
5877 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5878 	if (ret == -1) {
5879 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5880 	} else {
5881 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5882 		ipst->ips_igmp_slowtimeout_id = 0;
5883 	}
5884 	ret = untimeout(ipst->ips_mld_timeout_id);
5885 	if (ret == -1) {
5886 		ASSERT(ipst->ips_mld_timeout_id == 0);
5887 	} else {
5888 		ASSERT(ipst->ips_mld_timeout_id != 0);
5889 		ipst->ips_mld_timeout_id = 0;
5890 	}
5891 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5892 	if (ret == -1) {
5893 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5894 	} else {
5895 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5896 		ipst->ips_mld_slowtimeout_id = 0;
5897 	}
5898 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5899 	if (ret == -1) {
5900 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5901 	} else {
5902 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5903 		ipst->ips_ip_ire_expire_id = 0;
5904 	}
5905 
5906 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5907 	mutex_destroy(&ipst->ips_mld_timer_lock);
5908 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5909 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5910 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5911 	rw_destroy(&ipst->ips_ill_g_lock);
5912 
5913 	ip_ire_fini(ipst);
5914 	ip6_asp_free(ipst);
5915 	conn_drain_fini(ipst);
5916 	ipcl_destroy(ipst);
5917 
5918 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5919 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5920 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5921 	ipst->ips_ndp4 = NULL;
5922 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5923 	ipst->ips_ndp6 = NULL;
5924 
5925 	if (ipst->ips_loopback_ksp != NULL) {
5926 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5927 		ipst->ips_loopback_ksp = NULL;
5928 	}
5929 
5930 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5931 	ipst->ips_phyint_g_list = NULL;
5932 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5933 	ipst->ips_ill_g_heads = NULL;
5934 
5935 	kmem_free(ipst, sizeof (*ipst));
5936 }
5937 
5938 /*
5939  * Called when the IP kernel module is loaded into the kernel
5940  */
5941 void
5942 ip_ddi_init(void)
5943 {
5944 	TCP6_MAJ = ddi_name_to_major(TCP6);
5945 	TCP_MAJ	= ddi_name_to_major(TCP);
5946 	SCTP_MAJ = ddi_name_to_major(SCTP);
5947 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5948 
5949 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5950 
5951 	/*
5952 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5953 	 * initial devices: ip, ip6, tcp, tcp6.
5954 	 */
5955 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5956 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5957 		cmn_err(CE_PANIC,
5958 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5959 	}
5960 
5961 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5962 
5963 	ipcl_g_init();
5964 	ip_ire_g_init();
5965 	ip_net_g_init();
5966 
5967 #ifdef ILL_DEBUG
5968 	/* Default cleanup function */
5969 	ip_cleanup_func = ip_thread_exit;
5970 #endif
5971 
5972 	/*
5973 	 * We want to be informed each time a stack is created or
5974 	 * destroyed in the kernel, so we can maintain the
5975 	 * set of udp_stack_t's.
5976 	 */
5977 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5978 	    ip_stack_fini);
5979 
5980 	ipsec_policy_g_init();
5981 	tcp_ddi_g_init();
5982 	sctp_ddi_g_init();
5983 
5984 	tnet_init();
5985 }
5986 
5987 /*
5988  * Initialize the IP stack instance.
5989  */
5990 static void *
5991 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5992 {
5993 	ip_stack_t	*ipst;
5994 	ipparam_t	*pa;
5995 	ipndp_t		*na;
5996 
5997 #ifdef NS_DEBUG
5998 	printf("ip_stack_init(stack %d)\n", stackid);
5999 #endif
6000 
6001 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6002 	ipst->ips_netstack = ns;
6003 
6004 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6005 	    KM_SLEEP);
6006 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6007 	    KM_SLEEP);
6008 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6009 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6010 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6011 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6012 
6013 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6014 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6015 	ipst->ips_igmp_deferred_next = INFINITY;
6016 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6017 	ipst->ips_mld_deferred_next = INFINITY;
6018 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6019 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6020 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6021 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6022 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6023 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6024 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6025 
6026 	ipcl_init(ipst);
6027 	ip_ire_init(ipst);
6028 	ip6_asp_init(ipst);
6029 	ipif_init(ipst);
6030 	conn_drain_init(ipst);
6031 	ip_mrouter_stack_init(ipst);
6032 
6033 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6034 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6035 
6036 	ipst->ips_ip_multirt_log_interval = 1000;
6037 
6038 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6039 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6040 	ipst->ips_ill_index = 1;
6041 
6042 	ipst->ips_saved_ip_g_forward = -1;
6043 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6044 
6045 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6046 	ipst->ips_param_arr = pa;
6047 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6048 
6049 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6050 	ipst->ips_ndp_arr = na;
6051 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6052 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6053 	    (caddr_t)&ipst->ips_ip_g_forward;
6054 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6055 	    (caddr_t)&ipst->ips_ipv6_forward;
6056 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6057 	    "ip_cgtp_filter") == 0);
6058 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6059 	    (caddr_t)&ip_cgtp_filter;
6060 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6061 	    "ipmp_hook_emulation") == 0);
6062 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6063 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6064 
6065 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6066 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6067 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6068 
6069 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6070 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6071 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6072 	ipst->ips_ip6_kstat =
6073 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6074 
6075 	ipst->ips_ipmp_enable_failback = B_TRUE;
6076 
6077 	ipst->ips_ip_src_id = 1;
6078 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6079 
6080 	ip_net_init(ipst, ns);
6081 	ipv4_hook_init(ipst);
6082 	ipv6_hook_init(ipst);
6083 
6084 	return (ipst);
6085 }
6086 
6087 /*
6088  * Allocate and initialize a DLPI template of the specified length.  (May be
6089  * called as writer.)
6090  */
6091 mblk_t *
6092 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6093 {
6094 	mblk_t	*mp;
6095 
6096 	mp = allocb(len, BPRI_MED);
6097 	if (!mp)
6098 		return (NULL);
6099 
6100 	/*
6101 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6102 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6103 	 * that other DLPI are M_PROTO.
6104 	 */
6105 	if (prim == DL_INFO_REQ) {
6106 		mp->b_datap->db_type = M_PCPROTO;
6107 	} else {
6108 		mp->b_datap->db_type = M_PROTO;
6109 	}
6110 
6111 	mp->b_wptr = mp->b_rptr + len;
6112 	bzero(mp->b_rptr, len);
6113 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6114 	return (mp);
6115 }
6116 
6117 const char *
6118 dlpi_prim_str(int prim)
6119 {
6120 	switch (prim) {
6121 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6122 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6123 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6124 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6125 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6126 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6127 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6128 	case DL_OK_ACK:		return ("DL_OK_ACK");
6129 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6130 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6131 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6132 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6133 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6134 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6135 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6136 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6137 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6138 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6139 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6140 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6141 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6142 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6143 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6144 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6145 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6146 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6147 	default:		return ("<unknown primitive>");
6148 	}
6149 }
6150 
6151 const char *
6152 dlpi_err_str(int err)
6153 {
6154 	switch (err) {
6155 	case DL_ACCESS:		return ("DL_ACCESS");
6156 	case DL_BADADDR:	return ("DL_BADADDR");
6157 	case DL_BADCORR:	return ("DL_BADCORR");
6158 	case DL_BADDATA:	return ("DL_BADDATA");
6159 	case DL_BADPPA:		return ("DL_BADPPA");
6160 	case DL_BADPRIM:	return ("DL_BADPRIM");
6161 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6162 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6163 	case DL_BADSAP:		return ("DL_BADSAP");
6164 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6165 	case DL_BOUND:		return ("DL_BOUND");
6166 	case DL_INITFAILED:	return ("DL_INITFAILED");
6167 	case DL_NOADDR:		return ("DL_NOADDR");
6168 	case DL_NOTINIT:	return ("DL_NOTINIT");
6169 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6170 	case DL_SYSERR:		return ("DL_SYSERR");
6171 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6172 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6173 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6174 	case DL_TOOMANY:	return ("DL_TOOMANY");
6175 	case DL_NOTENAB:	return ("DL_NOTENAB");
6176 	case DL_BUSY:		return ("DL_BUSY");
6177 	case DL_NOAUTO:		return ("DL_NOAUTO");
6178 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6179 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6180 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6181 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6182 	case DL_PENDING:	return ("DL_PENDING");
6183 	default:		return ("<unknown error>");
6184 	}
6185 }
6186 
6187 /*
6188  * Debug formatting routine.  Returns a character string representation of the
6189  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6190  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6191  *
6192  * Once the ndd table-printing interfaces are removed, this can be changed to
6193  * standard dotted-decimal form.
6194  */
6195 char *
6196 ip_dot_addr(ipaddr_t addr, char *buf)
6197 {
6198 	uint8_t *ap = (uint8_t *)&addr;
6199 
6200 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6201 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6202 	return (buf);
6203 }
6204 
6205 /*
6206  * Write the given MAC address as a printable string in the usual colon-
6207  * separated format.
6208  */
6209 const char *
6210 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6211 {
6212 	char *bp;
6213 
6214 	if (alen == 0 || buflen < 4)
6215 		return ("?");
6216 	bp = buf;
6217 	for (;;) {
6218 		/*
6219 		 * If there are more MAC address bytes available, but we won't
6220 		 * have any room to print them, then add "..." to the string
6221 		 * instead.  See below for the 'magic number' explanation.
6222 		 */
6223 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6224 			(void) strcpy(bp, "...");
6225 			break;
6226 		}
6227 		(void) sprintf(bp, "%02x", *addr++);
6228 		bp += 2;
6229 		if (--alen == 0)
6230 			break;
6231 		*bp++ = ':';
6232 		buflen -= 3;
6233 		/*
6234 		 * At this point, based on the first 'if' statement above,
6235 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6236 		 * buflen >= 4.  The first case leaves room for the final "xx"
6237 		 * number and trailing NUL byte.  The second leaves room for at
6238 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6239 		 * that statement.
6240 		 */
6241 	}
6242 	return (buf);
6243 }
6244 
6245 /*
6246  * Send an ICMP error after patching up the packet appropriately.  Returns
6247  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6248  */
6249 static boolean_t
6250 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6251     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6252     zoneid_t zoneid, ip_stack_t *ipst)
6253 {
6254 	ipha_t *ipha;
6255 	mblk_t *first_mp;
6256 	boolean_t secure;
6257 	unsigned char db_type;
6258 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6259 
6260 	first_mp = mp;
6261 	if (mctl_present) {
6262 		mp = mp->b_cont;
6263 		secure = ipsec_in_is_secure(first_mp);
6264 		ASSERT(mp != NULL);
6265 	} else {
6266 		/*
6267 		 * If this is an ICMP error being reported - which goes
6268 		 * up as M_CTLs, we need to convert them to M_DATA till
6269 		 * we finish checking with global policy because
6270 		 * ipsec_check_global_policy() assumes M_DATA as clear
6271 		 * and M_CTL as secure.
6272 		 */
6273 		db_type = DB_TYPE(mp);
6274 		DB_TYPE(mp) = M_DATA;
6275 		secure = B_FALSE;
6276 	}
6277 	/*
6278 	 * We are generating an icmp error for some inbound packet.
6279 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6280 	 * Before we generate an error, check with global policy
6281 	 * to see whether this is allowed to enter the system. As
6282 	 * there is no "conn", we are checking with global policy.
6283 	 */
6284 	ipha = (ipha_t *)mp->b_rptr;
6285 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6286 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6287 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6288 		if (first_mp == NULL)
6289 			return (B_FALSE);
6290 	}
6291 
6292 	if (!mctl_present)
6293 		DB_TYPE(mp) = db_type;
6294 
6295 	if (flags & IP_FF_SEND_ICMP) {
6296 		if (flags & IP_FF_HDR_COMPLETE) {
6297 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6298 				freemsg(first_mp);
6299 				return (B_TRUE);
6300 			}
6301 		}
6302 		if (flags & IP_FF_CKSUM) {
6303 			/*
6304 			 * Have to correct checksum since
6305 			 * the packet might have been
6306 			 * fragmented and the reassembly code in ip_rput
6307 			 * does not restore the IP checksum.
6308 			 */
6309 			ipha->ipha_hdr_checksum = 0;
6310 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6311 		}
6312 		switch (icmp_type) {
6313 		case ICMP_DEST_UNREACHABLE:
6314 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6315 			    ipst);
6316 			break;
6317 		default:
6318 			freemsg(first_mp);
6319 			break;
6320 		}
6321 	} else {
6322 		freemsg(first_mp);
6323 		return (B_FALSE);
6324 	}
6325 
6326 	return (B_TRUE);
6327 }
6328 
6329 /*
6330  * Used to send an ICMP error message when a packet is received for
6331  * a protocol that is not supported. The mblk passed as argument
6332  * is consumed by this function.
6333  */
6334 void
6335 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6336     ip_stack_t *ipst)
6337 {
6338 	mblk_t *mp;
6339 	ipha_t *ipha;
6340 	ill_t *ill;
6341 	ipsec_in_t *ii;
6342 
6343 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6344 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6345 
6346 	mp = ipsec_mp->b_cont;
6347 	ipsec_mp->b_cont = NULL;
6348 	ipha = (ipha_t *)mp->b_rptr;
6349 	/* Get ill from index in ipsec_in_t. */
6350 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6351 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6352 	    ipst);
6353 	if (ill != NULL) {
6354 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6355 			if (ip_fanout_send_icmp(q, mp, flags,
6356 			    ICMP_DEST_UNREACHABLE,
6357 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6358 				BUMP_MIB(ill->ill_ip_mib,
6359 				    ipIfStatsInUnknownProtos);
6360 			}
6361 		} else {
6362 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6363 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6364 			    0, B_FALSE, zoneid, ipst)) {
6365 				BUMP_MIB(ill->ill_ip_mib,
6366 				    ipIfStatsInUnknownProtos);
6367 			}
6368 		}
6369 		ill_refrele(ill);
6370 	} else { /* re-link for the freemsg() below. */
6371 		ipsec_mp->b_cont = mp;
6372 	}
6373 
6374 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6375 	freemsg(ipsec_mp);
6376 }
6377 
6378 /*
6379  * See if the inbound datagram has had IPsec processing applied to it.
6380  */
6381 boolean_t
6382 ipsec_in_is_secure(mblk_t *ipsec_mp)
6383 {
6384 	ipsec_in_t *ii;
6385 
6386 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6387 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6388 
6389 	if (ii->ipsec_in_loopback) {
6390 		return (ii->ipsec_in_secure);
6391 	} else {
6392 		return (ii->ipsec_in_ah_sa != NULL ||
6393 		    ii->ipsec_in_esp_sa != NULL ||
6394 		    ii->ipsec_in_decaps);
6395 	}
6396 }
6397 
6398 /*
6399  * Handle protocols with which IP is less intimate.  There
6400  * can be more than one stream bound to a particular
6401  * protocol.  When this is the case, normally each one gets a copy
6402  * of any incoming packets.
6403  *
6404  * IPSEC NOTE :
6405  *
6406  * Don't allow a secure packet going up a non-secure connection.
6407  * We don't allow this because
6408  *
6409  * 1) Reply might go out in clear which will be dropped at
6410  *    the sending side.
6411  * 2) If the reply goes out in clear it will give the
6412  *    adversary enough information for getting the key in
6413  *    most of the cases.
6414  *
6415  * Moreover getting a secure packet when we expect clear
6416  * implies that SA's were added without checking for
6417  * policy on both ends. This should not happen once ISAKMP
6418  * is used to negotiate SAs as SAs will be added only after
6419  * verifying the policy.
6420  *
6421  * NOTE : If the packet was tunneled and not multicast we only send
6422  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6423  * back to delivering packets to AF_INET6 raw sockets.
6424  *
6425  * IPQoS Notes:
6426  * Once we have determined the client, invoke IPPF processing.
6427  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6428  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6429  * ip_policy will be false.
6430  *
6431  * Zones notes:
6432  * Currently only applications in the global zone can create raw sockets for
6433  * protocols other than ICMP. So unlike the broadcast / multicast case of
6434  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6435  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6436  */
6437 static void
6438 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6439     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6440     zoneid_t zoneid)
6441 {
6442 	queue_t	*rq;
6443 	mblk_t	*mp1, *first_mp1;
6444 	uint_t	protocol = ipha->ipha_protocol;
6445 	ipaddr_t dst;
6446 	boolean_t one_only;
6447 	mblk_t *first_mp = mp;
6448 	boolean_t secure;
6449 	uint32_t ill_index;
6450 	conn_t	*connp, *first_connp, *next_connp;
6451 	connf_t	*connfp;
6452 	boolean_t shared_addr;
6453 	mib2_ipIfStatsEntry_t *mibptr;
6454 	ip_stack_t *ipst = recv_ill->ill_ipst;
6455 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6456 
6457 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6458 	if (mctl_present) {
6459 		mp = first_mp->b_cont;
6460 		secure = ipsec_in_is_secure(first_mp);
6461 		ASSERT(mp != NULL);
6462 	} else {
6463 		secure = B_FALSE;
6464 	}
6465 	dst = ipha->ipha_dst;
6466 	/*
6467 	 * If the packet was tunneled and not multicast we only send to it
6468 	 * the first match.
6469 	 */
6470 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6471 	    !CLASSD(dst));
6472 
6473 	shared_addr = (zoneid == ALL_ZONES);
6474 	if (shared_addr) {
6475 		/*
6476 		 * We don't allow multilevel ports for raw IP, so no need to
6477 		 * check for that here.
6478 		 */
6479 		zoneid = tsol_packet_to_zoneid(mp);
6480 	}
6481 
6482 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6483 	mutex_enter(&connfp->connf_lock);
6484 	connp = connfp->connf_head;
6485 	for (connp = connfp->connf_head; connp != NULL;
6486 	    connp = connp->conn_next) {
6487 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6488 		    zoneid) &&
6489 		    (!is_system_labeled() ||
6490 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6491 		    connp))) {
6492 			break;
6493 		}
6494 	}
6495 
6496 	if (connp == NULL || connp->conn_upq == NULL) {
6497 		/*
6498 		 * No one bound to these addresses.  Is
6499 		 * there a client that wants all
6500 		 * unclaimed datagrams?
6501 		 */
6502 		mutex_exit(&connfp->connf_lock);
6503 		/*
6504 		 * Check for IPPROTO_ENCAP...
6505 		 */
6506 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6507 			/*
6508 			 * If an IPsec mblk is here on a multicast
6509 			 * tunnel (using ip_mroute stuff), check policy here,
6510 			 * THEN ship off to ip_mroute_decap().
6511 			 *
6512 			 * BTW,  If I match a configured IP-in-IP
6513 			 * tunnel, this path will not be reached, and
6514 			 * ip_mroute_decap will never be called.
6515 			 */
6516 			first_mp = ipsec_check_global_policy(first_mp, connp,
6517 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6518 			if (first_mp != NULL) {
6519 				if (mctl_present)
6520 					freeb(first_mp);
6521 				ip_mroute_decap(q, mp, ill);
6522 			} /* Else we already freed everything! */
6523 		} else {
6524 			/*
6525 			 * Otherwise send an ICMP protocol unreachable.
6526 			 */
6527 			if (ip_fanout_send_icmp(q, first_mp, flags,
6528 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6529 			    mctl_present, zoneid, ipst)) {
6530 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6531 			}
6532 		}
6533 		return;
6534 	}
6535 	CONN_INC_REF(connp);
6536 	first_connp = connp;
6537 
6538 	/*
6539 	 * Only send message to one tunnel driver by immediately
6540 	 * terminating the loop.
6541 	 */
6542 	connp = one_only ? NULL : connp->conn_next;
6543 
6544 	for (;;) {
6545 		while (connp != NULL) {
6546 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6547 			    flags, zoneid) &&
6548 			    (!is_system_labeled() ||
6549 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6550 			    shared_addr, connp)))
6551 				break;
6552 			connp = connp->conn_next;
6553 		}
6554 
6555 		/*
6556 		 * Copy the packet.
6557 		 */
6558 		if (connp == NULL || connp->conn_upq == NULL ||
6559 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6560 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6561 			/*
6562 			 * No more interested clients or memory
6563 			 * allocation failed
6564 			 */
6565 			connp = first_connp;
6566 			break;
6567 		}
6568 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6569 		CONN_INC_REF(connp);
6570 		mutex_exit(&connfp->connf_lock);
6571 		rq = connp->conn_rq;
6572 		if (!canputnext(rq)) {
6573 			if (flags & IP_FF_RAWIP) {
6574 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6575 			} else {
6576 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6577 			}
6578 
6579 			freemsg(first_mp1);
6580 		} else {
6581 			/*
6582 			 * Don't enforce here if we're an actual tunnel -
6583 			 * let "tun" do it instead.
6584 			 */
6585 			if (!IPCL_IS_IPTUN(connp) &&
6586 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6587 			    secure)) {
6588 				first_mp1 = ipsec_check_inbound_policy
6589 				    (first_mp1, connp, ipha, NULL,
6590 				    mctl_present);
6591 			}
6592 			if (first_mp1 != NULL) {
6593 				int in_flags = 0;
6594 				/*
6595 				 * ip_fanout_proto also gets called from
6596 				 * icmp_inbound_error_fanout, in which case
6597 				 * the msg type is M_CTL.  Don't add info
6598 				 * in this case for the time being. In future
6599 				 * when there is a need for knowing the
6600 				 * inbound iface index for ICMP error msgs,
6601 				 * then this can be changed.
6602 				 */
6603 				if (connp->conn_recvif)
6604 					in_flags = IPF_RECVIF;
6605 				/*
6606 				 * The ULP may support IP_RECVPKTINFO for both
6607 				 * IP v4 and v6 so pass the appropriate argument
6608 				 * based on conn IP version.
6609 				 */
6610 				if (connp->conn_ip_recvpktinfo) {
6611 					if (connp->conn_af_isv6) {
6612 						/*
6613 						 * V6 only needs index
6614 						 */
6615 						in_flags |= IPF_RECVIF;
6616 					} else {
6617 						/*
6618 						 * V4 needs index +
6619 						 * matching address.
6620 						 */
6621 						in_flags |= IPF_RECVADDR;
6622 					}
6623 				}
6624 				if ((in_flags != 0) &&
6625 				    (mp->b_datap->db_type != M_CTL)) {
6626 					/*
6627 					 * the actual data will be
6628 					 * contained in b_cont upon
6629 					 * successful return of the
6630 					 * following call else
6631 					 * original mblk is returned
6632 					 */
6633 					ASSERT(recv_ill != NULL);
6634 					mp1 = ip_add_info(mp1, recv_ill,
6635 					    in_flags, IPCL_ZONEID(connp), ipst);
6636 				}
6637 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6638 				if (mctl_present)
6639 					freeb(first_mp1);
6640 				putnext(rq, mp1);
6641 			}
6642 		}
6643 		mutex_enter(&connfp->connf_lock);
6644 		/* Follow the next pointer before releasing the conn. */
6645 		next_connp = connp->conn_next;
6646 		CONN_DEC_REF(connp);
6647 		connp = next_connp;
6648 	}
6649 
6650 	/* Last one.  Send it upstream. */
6651 	mutex_exit(&connfp->connf_lock);
6652 
6653 	/*
6654 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6655 	 * will be set to false.
6656 	 */
6657 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6658 		ill_index = ill->ill_phyint->phyint_ifindex;
6659 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6660 		if (mp == NULL) {
6661 			CONN_DEC_REF(connp);
6662 			if (mctl_present) {
6663 				freeb(first_mp);
6664 			}
6665 			return;
6666 		}
6667 	}
6668 
6669 	rq = connp->conn_rq;
6670 	if (!canputnext(rq)) {
6671 		if (flags & IP_FF_RAWIP) {
6672 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6673 		} else {
6674 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6675 		}
6676 
6677 		freemsg(first_mp);
6678 	} else {
6679 		if (IPCL_IS_IPTUN(connp)) {
6680 			/*
6681 			 * Tunneled packet.  We enforce policy in the tunnel
6682 			 * module itself.
6683 			 *
6684 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6685 			 * a policy check.
6686 			 */
6687 			putnext(rq, first_mp);
6688 			CONN_DEC_REF(connp);
6689 			return;
6690 		}
6691 
6692 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6693 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6694 			    ipha, NULL, mctl_present);
6695 		}
6696 
6697 		if (first_mp != NULL) {
6698 			int in_flags = 0;
6699 
6700 			/*
6701 			 * ip_fanout_proto also gets called
6702 			 * from icmp_inbound_error_fanout, in
6703 			 * which case the msg type is M_CTL.
6704 			 * Don't add info in this case for time
6705 			 * being. In future when there is a
6706 			 * need for knowing the inbound iface
6707 			 * index for ICMP error msgs, then this
6708 			 * can be changed
6709 			 */
6710 			if (connp->conn_recvif)
6711 				in_flags = IPF_RECVIF;
6712 			if (connp->conn_ip_recvpktinfo) {
6713 				if (connp->conn_af_isv6) {
6714 					/*
6715 					 * V6 only needs index
6716 					 */
6717 					in_flags |= IPF_RECVIF;
6718 				} else {
6719 					/*
6720 					 * V4 needs index +
6721 					 * matching address.
6722 					 */
6723 					in_flags |= IPF_RECVADDR;
6724 				}
6725 			}
6726 			if ((in_flags != 0) &&
6727 			    (mp->b_datap->db_type != M_CTL)) {
6728 
6729 				/*
6730 				 * the actual data will be contained in
6731 				 * b_cont upon successful return
6732 				 * of the following call else original
6733 				 * mblk is returned
6734 				 */
6735 				ASSERT(recv_ill != NULL);
6736 				mp = ip_add_info(mp, recv_ill,
6737 				    in_flags, IPCL_ZONEID(connp), ipst);
6738 			}
6739 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6740 			putnext(rq, mp);
6741 			if (mctl_present)
6742 				freeb(first_mp);
6743 		}
6744 	}
6745 	CONN_DEC_REF(connp);
6746 }
6747 
6748 /*
6749  * Fanout for TCP packets
6750  * The caller puts <fport, lport> in the ports parameter.
6751  *
6752  * IPQoS Notes
6753  * Before sending it to the client, invoke IPPF processing.
6754  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6755  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6756  * ip_policy is false.
6757  */
6758 static void
6759 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6760     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6761 {
6762 	mblk_t  *first_mp;
6763 	boolean_t secure;
6764 	uint32_t ill_index;
6765 	int	ip_hdr_len;
6766 	tcph_t	*tcph;
6767 	boolean_t syn_present = B_FALSE;
6768 	conn_t	*connp;
6769 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6770 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6771 
6772 	ASSERT(recv_ill != NULL);
6773 
6774 	first_mp = mp;
6775 	if (mctl_present) {
6776 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6777 		mp = first_mp->b_cont;
6778 		secure = ipsec_in_is_secure(first_mp);
6779 		ASSERT(mp != NULL);
6780 	} else {
6781 		secure = B_FALSE;
6782 	}
6783 
6784 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6785 
6786 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6787 	    zoneid, ipst)) == NULL) {
6788 		/*
6789 		 * No connected connection or listener. Send a
6790 		 * TH_RST via tcp_xmit_listeners_reset.
6791 		 */
6792 
6793 		/* Initiate IPPf processing, if needed. */
6794 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6795 			uint32_t ill_index;
6796 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6797 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6798 			if (first_mp == NULL)
6799 				return;
6800 		}
6801 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6802 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6803 		    zoneid));
6804 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6805 		    ipst->ips_netstack->netstack_tcp);
6806 		return;
6807 	}
6808 
6809 	/*
6810 	 * Allocate the SYN for the TCP connection here itself
6811 	 */
6812 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6813 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6814 		if (IPCL_IS_TCP(connp)) {
6815 			squeue_t *sqp;
6816 
6817 			/*
6818 			 * For fused tcp loopback, assign the eager's
6819 			 * squeue to be that of the active connect's.
6820 			 * Note that we don't check for IP_FF_LOOPBACK
6821 			 * here since this routine gets called only
6822 			 * for loopback (unlike the IPv6 counterpart).
6823 			 */
6824 			ASSERT(Q_TO_CONN(q) != NULL);
6825 			if (do_tcp_fusion &&
6826 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6827 			    !secure &&
6828 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6829 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6830 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6831 				sqp = Q_TO_CONN(q)->conn_sqp;
6832 			} else {
6833 				sqp = IP_SQUEUE_GET(lbolt);
6834 			}
6835 
6836 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6837 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6838 			syn_present = B_TRUE;
6839 		}
6840 	}
6841 
6842 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6843 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6844 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6845 		if ((flags & TH_RST) || (flags & TH_URG)) {
6846 			CONN_DEC_REF(connp);
6847 			freemsg(first_mp);
6848 			return;
6849 		}
6850 		if (flags & TH_ACK) {
6851 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6852 			    ipst->ips_netstack->netstack_tcp);
6853 			CONN_DEC_REF(connp);
6854 			return;
6855 		}
6856 
6857 		CONN_DEC_REF(connp);
6858 		freemsg(first_mp);
6859 		return;
6860 	}
6861 
6862 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6863 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6864 		    NULL, mctl_present);
6865 		if (first_mp == NULL) {
6866 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6867 			CONN_DEC_REF(connp);
6868 			return;
6869 		}
6870 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6871 			ASSERT(syn_present);
6872 			if (mctl_present) {
6873 				ASSERT(first_mp != mp);
6874 				first_mp->b_datap->db_struioflag |=
6875 				    STRUIO_POLICY;
6876 			} else {
6877 				ASSERT(first_mp == mp);
6878 				mp->b_datap->db_struioflag &=
6879 				    ~STRUIO_EAGER;
6880 				mp->b_datap->db_struioflag |=
6881 				    STRUIO_POLICY;
6882 			}
6883 		} else {
6884 			/*
6885 			 * Discard first_mp early since we're dealing with a
6886 			 * fully-connected conn_t and tcp doesn't do policy in
6887 			 * this case.
6888 			 */
6889 			if (mctl_present) {
6890 				freeb(first_mp);
6891 				mctl_present = B_FALSE;
6892 			}
6893 			first_mp = mp;
6894 		}
6895 	}
6896 
6897 	/*
6898 	 * Initiate policy processing here if needed. If we get here from
6899 	 * icmp_inbound_error_fanout, ip_policy is false.
6900 	 */
6901 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6902 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6903 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6904 		if (mp == NULL) {
6905 			CONN_DEC_REF(connp);
6906 			if (mctl_present)
6907 				freeb(first_mp);
6908 			return;
6909 		} else if (mctl_present) {
6910 			ASSERT(first_mp != mp);
6911 			first_mp->b_cont = mp;
6912 		} else {
6913 			first_mp = mp;
6914 		}
6915 	}
6916 
6917 
6918 
6919 	/* Handle socket options. */
6920 	if (!syn_present &&
6921 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6922 		/* Add header */
6923 		ASSERT(recv_ill != NULL);
6924 		/*
6925 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6926 		 * IPF_RECVIF.
6927 		 */
6928 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6929 		    ipst);
6930 		if (mp == NULL) {
6931 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6932 			CONN_DEC_REF(connp);
6933 			if (mctl_present)
6934 				freeb(first_mp);
6935 			return;
6936 		} else if (mctl_present) {
6937 			/*
6938 			 * ip_add_info might return a new mp.
6939 			 */
6940 			ASSERT(first_mp != mp);
6941 			first_mp->b_cont = mp;
6942 		} else {
6943 			first_mp = mp;
6944 		}
6945 	}
6946 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6947 	if (IPCL_IS_TCP(connp)) {
6948 		/* do not drain, certain use cases can blow the stack */
6949 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6950 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6951 	} else {
6952 		putnext(connp->conn_rq, first_mp);
6953 		CONN_DEC_REF(connp);
6954 	}
6955 }
6956 
6957 /*
6958  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6959  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6960  * Caller is responsible for dropping references to the conn, and freeing
6961  * first_mp.
6962  *
6963  * IPQoS Notes
6964  * Before sending it to the client, invoke IPPF processing. Policy processing
6965  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6966  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6967  * ip_wput_local, ip_policy is false.
6968  */
6969 static void
6970 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6971     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6972     boolean_t ip_policy)
6973 {
6974 	boolean_t	mctl_present = (first_mp != NULL);
6975 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6976 	uint32_t	ill_index;
6977 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6978 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6979 
6980 	ASSERT(ill != NULL);
6981 
6982 	if (mctl_present)
6983 		first_mp->b_cont = mp;
6984 	else
6985 		first_mp = mp;
6986 
6987 	if (CONN_UDP_FLOWCTLD(connp)) {
6988 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6989 		freemsg(first_mp);
6990 		return;
6991 	}
6992 
6993 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6994 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6995 		    NULL, mctl_present);
6996 		if (first_mp == NULL) {
6997 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6998 			return;	/* Freed by ipsec_check_inbound_policy(). */
6999 		}
7000 	}
7001 	if (mctl_present)
7002 		freeb(first_mp);
7003 
7004 	/* Handle options. */
7005 	if (connp->conn_recvif)
7006 		in_flags = IPF_RECVIF;
7007 	/*
7008 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7009 	 * passed to ip_add_info is based on IP version of connp.
7010 	 */
7011 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7012 		if (connp->conn_af_isv6) {
7013 			/*
7014 			 * V6 only needs index
7015 			 */
7016 			in_flags |= IPF_RECVIF;
7017 		} else {
7018 			/*
7019 			 * V4 needs index + matching address.
7020 			 */
7021 			in_flags |= IPF_RECVADDR;
7022 		}
7023 	}
7024 
7025 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7026 		in_flags |= IPF_RECVSLLA;
7027 
7028 	/*
7029 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7030 	 * freed if the packet is dropped. The caller will do so.
7031 	 */
7032 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7033 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7034 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7035 		if (mp == NULL) {
7036 			return;
7037 		}
7038 	}
7039 	if ((in_flags != 0) &&
7040 	    (mp->b_datap->db_type != M_CTL)) {
7041 		/*
7042 		 * The actual data will be contained in b_cont
7043 		 * upon successful return of the following call
7044 		 * else original mblk is returned
7045 		 */
7046 		ASSERT(recv_ill != NULL);
7047 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7048 		    ipst);
7049 	}
7050 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7051 	/* Send it upstream */
7052 	CONN_UDP_RECV(connp, mp);
7053 }
7054 
7055 /*
7056  * Fanout for UDP packets.
7057  * The caller puts <fport, lport> in the ports parameter.
7058  *
7059  * If SO_REUSEADDR is set all multicast and broadcast packets
7060  * will be delivered to all streams bound to the same port.
7061  *
7062  * Zones notes:
7063  * Multicast and broadcast packets will be distributed to streams in all zones.
7064  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7065  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7066  * packets. To maintain this behavior with multiple zones, the conns are grouped
7067  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7068  * each zone. If unset, all the following conns in the same zone are skipped.
7069  */
7070 static void
7071 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7072     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7073     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7074 {
7075 	uint32_t	dstport, srcport;
7076 	ipaddr_t	dst;
7077 	mblk_t		*first_mp;
7078 	boolean_t	secure;
7079 	in6_addr_t	v6src;
7080 	conn_t		*connp;
7081 	connf_t		*connfp;
7082 	conn_t		*first_connp;
7083 	conn_t		*next_connp;
7084 	mblk_t		*mp1, *first_mp1;
7085 	ipaddr_t	src;
7086 	zoneid_t	last_zoneid;
7087 	boolean_t	reuseaddr;
7088 	boolean_t	shared_addr;
7089 	ip_stack_t	*ipst;
7090 
7091 	ASSERT(recv_ill != NULL);
7092 	ipst = recv_ill->ill_ipst;
7093 
7094 	first_mp = mp;
7095 	if (mctl_present) {
7096 		mp = first_mp->b_cont;
7097 		first_mp->b_cont = NULL;
7098 		secure = ipsec_in_is_secure(first_mp);
7099 		ASSERT(mp != NULL);
7100 	} else {
7101 		first_mp = NULL;
7102 		secure = B_FALSE;
7103 	}
7104 
7105 	/* Extract ports in net byte order */
7106 	dstport = htons(ntohl(ports) & 0xFFFF);
7107 	srcport = htons(ntohl(ports) >> 16);
7108 	dst = ipha->ipha_dst;
7109 	src = ipha->ipha_src;
7110 
7111 	shared_addr = (zoneid == ALL_ZONES);
7112 	if (shared_addr) {
7113 		/*
7114 		 * No need to handle exclusive-stack zones since ALL_ZONES
7115 		 * only applies to the shared stack.
7116 		 */
7117 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7118 		if (zoneid == ALL_ZONES)
7119 			zoneid = tsol_packet_to_zoneid(mp);
7120 	}
7121 
7122 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7123 	mutex_enter(&connfp->connf_lock);
7124 	connp = connfp->connf_head;
7125 	if (!broadcast && !CLASSD(dst)) {
7126 		/*
7127 		 * Not broadcast or multicast. Send to the one (first)
7128 		 * client we find. No need to check conn_wantpacket()
7129 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7130 		 * IPv4 unicast packets.
7131 		 */
7132 		while ((connp != NULL) &&
7133 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7134 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7135 			connp = connp->conn_next;
7136 		}
7137 
7138 		if (connp == NULL || connp->conn_upq == NULL)
7139 			goto notfound;
7140 
7141 		if (is_system_labeled() &&
7142 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7143 		    connp))
7144 			goto notfound;
7145 
7146 		CONN_INC_REF(connp);
7147 		mutex_exit(&connfp->connf_lock);
7148 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7149 		    flags, recv_ill, ip_policy);
7150 		IP_STAT(ipst, ip_udp_fannorm);
7151 		CONN_DEC_REF(connp);
7152 		return;
7153 	}
7154 
7155 	/*
7156 	 * Broadcast and multicast case
7157 	 *
7158 	 * Need to check conn_wantpacket().
7159 	 * If SO_REUSEADDR has been set on the first we send the
7160 	 * packet to all clients that have joined the group and
7161 	 * match the port.
7162 	 */
7163 
7164 	while (connp != NULL) {
7165 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7166 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7167 		    (!is_system_labeled() ||
7168 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7169 		    connp)))
7170 			break;
7171 		connp = connp->conn_next;
7172 	}
7173 
7174 	if (connp == NULL || connp->conn_upq == NULL)
7175 		goto notfound;
7176 
7177 	first_connp = connp;
7178 	/*
7179 	 * When SO_REUSEADDR is not set, send the packet only to the first
7180 	 * matching connection in its zone by keeping track of the zoneid.
7181 	 */
7182 	reuseaddr = first_connp->conn_reuseaddr;
7183 	last_zoneid = first_connp->conn_zoneid;
7184 
7185 	CONN_INC_REF(connp);
7186 	connp = connp->conn_next;
7187 	for (;;) {
7188 		while (connp != NULL) {
7189 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7190 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7191 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7192 			    (!is_system_labeled() ||
7193 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7194 			    shared_addr, connp)))
7195 				break;
7196 			connp = connp->conn_next;
7197 		}
7198 		/*
7199 		 * Just copy the data part alone. The mctl part is
7200 		 * needed just for verifying policy and it is never
7201 		 * sent up.
7202 		 */
7203 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7204 		    ((mp1 = copymsg(mp)) == NULL))) {
7205 			/*
7206 			 * No more interested clients or memory
7207 			 * allocation failed
7208 			 */
7209 			connp = first_connp;
7210 			break;
7211 		}
7212 		if (connp->conn_zoneid != last_zoneid) {
7213 			/*
7214 			 * Update the zoneid so that the packet isn't sent to
7215 			 * any more conns in the same zone unless SO_REUSEADDR
7216 			 * is set.
7217 			 */
7218 			reuseaddr = connp->conn_reuseaddr;
7219 			last_zoneid = connp->conn_zoneid;
7220 		}
7221 		if (first_mp != NULL) {
7222 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7223 			    ipsec_info_type == IPSEC_IN);
7224 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7225 			    ipst->ips_netstack);
7226 			if (first_mp1 == NULL) {
7227 				freemsg(mp1);
7228 				connp = first_connp;
7229 				break;
7230 			}
7231 		} else {
7232 			first_mp1 = NULL;
7233 		}
7234 		CONN_INC_REF(connp);
7235 		mutex_exit(&connfp->connf_lock);
7236 		/*
7237 		 * IPQoS notes: We don't send the packet for policy
7238 		 * processing here, will do it for the last one (below).
7239 		 * i.e. we do it per-packet now, but if we do policy
7240 		 * processing per-conn, then we would need to do it
7241 		 * here too.
7242 		 */
7243 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7244 		    ipha, flags, recv_ill, B_FALSE);
7245 		mutex_enter(&connfp->connf_lock);
7246 		/* Follow the next pointer before releasing the conn. */
7247 		next_connp = connp->conn_next;
7248 		IP_STAT(ipst, ip_udp_fanmb);
7249 		CONN_DEC_REF(connp);
7250 		connp = next_connp;
7251 	}
7252 
7253 	/* Last one.  Send it upstream. */
7254 	mutex_exit(&connfp->connf_lock);
7255 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7256 	    recv_ill, ip_policy);
7257 	IP_STAT(ipst, ip_udp_fanmb);
7258 	CONN_DEC_REF(connp);
7259 	return;
7260 
7261 notfound:
7262 
7263 	mutex_exit(&connfp->connf_lock);
7264 	IP_STAT(ipst, ip_udp_fanothers);
7265 	/*
7266 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7267 	 * have already been matched above, since they live in the IPv4
7268 	 * fanout tables. This implies we only need to
7269 	 * check for IPv6 in6addr_any endpoints here.
7270 	 * Thus we compare using ipv6_all_zeros instead of the destination
7271 	 * address, except for the multicast group membership lookup which
7272 	 * uses the IPv4 destination.
7273 	 */
7274 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7275 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7276 	mutex_enter(&connfp->connf_lock);
7277 	connp = connfp->connf_head;
7278 	if (!broadcast && !CLASSD(dst)) {
7279 		while (connp != NULL) {
7280 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7281 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7282 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7283 			    !connp->conn_ipv6_v6only)
7284 				break;
7285 			connp = connp->conn_next;
7286 		}
7287 
7288 		if (connp != NULL && is_system_labeled() &&
7289 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7290 		    connp))
7291 			connp = NULL;
7292 
7293 		if (connp == NULL || connp->conn_upq == NULL) {
7294 			/*
7295 			 * No one bound to this port.  Is
7296 			 * there a client that wants all
7297 			 * unclaimed datagrams?
7298 			 */
7299 			mutex_exit(&connfp->connf_lock);
7300 
7301 			if (mctl_present)
7302 				first_mp->b_cont = mp;
7303 			else
7304 				first_mp = mp;
7305 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7306 			    connf_head != NULL) {
7307 				ip_fanout_proto(q, first_mp, ill, ipha,
7308 				    flags | IP_FF_RAWIP, mctl_present,
7309 				    ip_policy, recv_ill, zoneid);
7310 			} else {
7311 				if (ip_fanout_send_icmp(q, first_mp, flags,
7312 				    ICMP_DEST_UNREACHABLE,
7313 				    ICMP_PORT_UNREACHABLE,
7314 				    mctl_present, zoneid, ipst)) {
7315 					BUMP_MIB(ill->ill_ip_mib,
7316 					    udpIfStatsNoPorts);
7317 				}
7318 			}
7319 			return;
7320 		}
7321 
7322 		CONN_INC_REF(connp);
7323 		mutex_exit(&connfp->connf_lock);
7324 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7325 		    flags, recv_ill, ip_policy);
7326 		CONN_DEC_REF(connp);
7327 		return;
7328 	}
7329 	/*
7330 	 * IPv4 multicast packet being delivered to an AF_INET6
7331 	 * in6addr_any endpoint.
7332 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7333 	 * and not conn_wantpacket_v6() since any multicast membership is
7334 	 * for an IPv4-mapped multicast address.
7335 	 * The packet is sent to all clients in all zones that have joined the
7336 	 * group and match the port.
7337 	 */
7338 	while (connp != NULL) {
7339 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7340 		    srcport, v6src) &&
7341 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7342 		    (!is_system_labeled() ||
7343 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7344 		    connp)))
7345 			break;
7346 		connp = connp->conn_next;
7347 	}
7348 
7349 	if (connp == NULL || connp->conn_upq == NULL) {
7350 		/*
7351 		 * No one bound to this port.  Is
7352 		 * there a client that wants all
7353 		 * unclaimed datagrams?
7354 		 */
7355 		mutex_exit(&connfp->connf_lock);
7356 
7357 		if (mctl_present)
7358 			first_mp->b_cont = mp;
7359 		else
7360 			first_mp = mp;
7361 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7362 		    NULL) {
7363 			ip_fanout_proto(q, first_mp, ill, ipha,
7364 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7365 			    recv_ill, zoneid);
7366 		} else {
7367 			/*
7368 			 * We used to attempt to send an icmp error here, but
7369 			 * since this is known to be a multicast packet
7370 			 * and we don't send icmp errors in response to
7371 			 * multicast, just drop the packet and give up sooner.
7372 			 */
7373 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7374 			freemsg(first_mp);
7375 		}
7376 		return;
7377 	}
7378 
7379 	first_connp = connp;
7380 
7381 	CONN_INC_REF(connp);
7382 	connp = connp->conn_next;
7383 	for (;;) {
7384 		while (connp != NULL) {
7385 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7386 			    ipv6_all_zeros, srcport, v6src) &&
7387 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7388 			    (!is_system_labeled() ||
7389 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7390 			    shared_addr, connp)))
7391 				break;
7392 			connp = connp->conn_next;
7393 		}
7394 		/*
7395 		 * Just copy the data part alone. The mctl part is
7396 		 * needed just for verifying policy and it is never
7397 		 * sent up.
7398 		 */
7399 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7400 		    ((mp1 = copymsg(mp)) == NULL))) {
7401 			/*
7402 			 * No more intested clients or memory
7403 			 * allocation failed
7404 			 */
7405 			connp = first_connp;
7406 			break;
7407 		}
7408 		if (first_mp != NULL) {
7409 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7410 			    ipsec_info_type == IPSEC_IN);
7411 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7412 			    ipst->ips_netstack);
7413 			if (first_mp1 == NULL) {
7414 				freemsg(mp1);
7415 				connp = first_connp;
7416 				break;
7417 			}
7418 		} else {
7419 			first_mp1 = NULL;
7420 		}
7421 		CONN_INC_REF(connp);
7422 		mutex_exit(&connfp->connf_lock);
7423 		/*
7424 		 * IPQoS notes: We don't send the packet for policy
7425 		 * processing here, will do it for the last one (below).
7426 		 * i.e. we do it per-packet now, but if we do policy
7427 		 * processing per-conn, then we would need to do it
7428 		 * here too.
7429 		 */
7430 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7431 		    ipha, flags, recv_ill, B_FALSE);
7432 		mutex_enter(&connfp->connf_lock);
7433 		/* Follow the next pointer before releasing the conn. */
7434 		next_connp = connp->conn_next;
7435 		CONN_DEC_REF(connp);
7436 		connp = next_connp;
7437 	}
7438 
7439 	/* Last one.  Send it upstream. */
7440 	mutex_exit(&connfp->connf_lock);
7441 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7442 	    recv_ill, ip_policy);
7443 	CONN_DEC_REF(connp);
7444 }
7445 
7446 /*
7447  * Complete the ip_wput header so that it
7448  * is possible to generate ICMP
7449  * errors.
7450  */
7451 int
7452 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7453 {
7454 	ire_t *ire;
7455 
7456 	if (ipha->ipha_src == INADDR_ANY) {
7457 		ire = ire_lookup_local(zoneid, ipst);
7458 		if (ire == NULL) {
7459 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7460 			return (1);
7461 		}
7462 		ipha->ipha_src = ire->ire_addr;
7463 		ire_refrele(ire);
7464 	}
7465 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7466 	ipha->ipha_hdr_checksum = 0;
7467 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7468 	return (0);
7469 }
7470 
7471 /*
7472  * Nobody should be sending
7473  * packets up this stream
7474  */
7475 static void
7476 ip_lrput(queue_t *q, mblk_t *mp)
7477 {
7478 	mblk_t *mp1;
7479 
7480 	switch (mp->b_datap->db_type) {
7481 	case M_FLUSH:
7482 		/* Turn around */
7483 		if (*mp->b_rptr & FLUSHW) {
7484 			*mp->b_rptr &= ~FLUSHR;
7485 			qreply(q, mp);
7486 			return;
7487 		}
7488 		break;
7489 	}
7490 	/* Could receive messages that passed through ar_rput */
7491 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7492 		mp1->b_prev = mp1->b_next = NULL;
7493 	freemsg(mp);
7494 }
7495 
7496 /* Nobody should be sending packets down this stream */
7497 /* ARGSUSED */
7498 void
7499 ip_lwput(queue_t *q, mblk_t *mp)
7500 {
7501 	freemsg(mp);
7502 }
7503 
7504 /*
7505  * Move the first hop in any source route to ipha_dst and remove that part of
7506  * the source route.  Called by other protocols.  Errors in option formatting
7507  * are ignored - will be handled by ip_wput_options Return the final
7508  * destination (either ipha_dst or the last entry in a source route.)
7509  */
7510 ipaddr_t
7511 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7512 {
7513 	ipoptp_t	opts;
7514 	uchar_t		*opt;
7515 	uint8_t		optval;
7516 	uint8_t		optlen;
7517 	ipaddr_t	dst;
7518 	int		i;
7519 	ire_t		*ire;
7520 	ip_stack_t	*ipst = ns->netstack_ip;
7521 
7522 	ip2dbg(("ip_massage_options\n"));
7523 	dst = ipha->ipha_dst;
7524 	for (optval = ipoptp_first(&opts, ipha);
7525 	    optval != IPOPT_EOL;
7526 	    optval = ipoptp_next(&opts)) {
7527 		opt = opts.ipoptp_cur;
7528 		switch (optval) {
7529 			uint8_t off;
7530 		case IPOPT_SSRR:
7531 		case IPOPT_LSRR:
7532 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7533 				ip1dbg(("ip_massage_options: bad src route\n"));
7534 				break;
7535 			}
7536 			optlen = opts.ipoptp_len;
7537 			off = opt[IPOPT_OFFSET];
7538 			off--;
7539 		redo_srr:
7540 			if (optlen < IP_ADDR_LEN ||
7541 			    off > optlen - IP_ADDR_LEN) {
7542 				/* End of source route */
7543 				ip1dbg(("ip_massage_options: end of SR\n"));
7544 				break;
7545 			}
7546 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7547 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7548 			    ntohl(dst)));
7549 			/*
7550 			 * Check if our address is present more than
7551 			 * once as consecutive hops in source route.
7552 			 * XXX verify per-interface ip_forwarding
7553 			 * for source route?
7554 			 */
7555 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7556 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7557 			if (ire != NULL) {
7558 				ire_refrele(ire);
7559 				off += IP_ADDR_LEN;
7560 				goto redo_srr;
7561 			}
7562 			if (dst == htonl(INADDR_LOOPBACK)) {
7563 				ip1dbg(("ip_massage_options: loopback addr in "
7564 				    "source route!\n"));
7565 				break;
7566 			}
7567 			/*
7568 			 * Update ipha_dst to be the first hop and remove the
7569 			 * first hop from the source route (by overwriting
7570 			 * part of the option with NOP options).
7571 			 */
7572 			ipha->ipha_dst = dst;
7573 			/* Put the last entry in dst */
7574 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7575 			    3;
7576 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7577 
7578 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7579 			    ntohl(dst)));
7580 			/* Move down and overwrite */
7581 			opt[IP_ADDR_LEN] = opt[0];
7582 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7583 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7584 			for (i = 0; i < IP_ADDR_LEN; i++)
7585 				opt[i] = IPOPT_NOP;
7586 			break;
7587 		}
7588 	}
7589 	return (dst);
7590 }
7591 
7592 /*
7593  * This function's job is to forward data to the reverse tunnel (FA->HA)
7594  * after doing a few checks. It is assumed that the incoming interface
7595  * of the packet is always different than the outgoing interface and the
7596  * ire_type of the found ire has to be a non-resolver type.
7597  *
7598  * IPQoS notes
7599  * IP policy is invoked twice for a forwarded packet, once on the read side
7600  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7601  * enabled.
7602  */
7603 static void
7604 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7605 {
7606 	ipha_t		*ipha;
7607 	queue_t		*q;
7608 	uint32_t 	pkt_len;
7609 #define	rptr    ((uchar_t *)ipha)
7610 	uint32_t 	sum;
7611 	uint32_t 	max_frag;
7612 	mblk_t		*first_mp;
7613 	uint32_t	ill_index;
7614 	ipxmit_state_t	pktxmit_state;
7615 	ill_t		*out_ill;
7616 	ip_stack_t	*ipst = in_ill->ill_ipst;
7617 
7618 	ASSERT(ire != NULL);
7619 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7620 	ASSERT(ire->ire_stq != NULL);
7621 
7622 	/* Initiate read side IPPF processing */
7623 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
7624 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7625 		ip_process(IPP_FWD_IN, &mp, ill_index);
7626 		if (mp == NULL) {
7627 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7628 			    "dropped during IPPF processing\n"));
7629 			return;
7630 		}
7631 	}
7632 
7633 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7634 	    ILLF_ROUTER) == 0) ||
7635 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7636 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7637 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7638 		    "forwarding is not turned on\n"));
7639 		goto drop_pkt;
7640 	}
7641 
7642 	/*
7643 	 * Don't forward if the interface is down
7644 	 */
7645 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7646 		goto discard_pkt;
7647 	}
7648 
7649 	ipha = (ipha_t *)mp->b_rptr;
7650 	pkt_len = ntohs(ipha->ipha_length);
7651 	/* Adjust the checksum to reflect the ttl decrement. */
7652 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7653 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7654 	if (ipha->ipha_ttl-- <= 1) {
7655 		if (ip_csum_hdr(ipha)) {
7656 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7657 			goto drop_pkt;
7658 		}
7659 		q = ire->ire_stq;
7660 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7661 		    BPRI_HI)) == NULL) {
7662 			goto discard_pkt;
7663 		}
7664 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7665 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7666 		/* Sent by forwarding path, and router is global zone */
7667 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7668 		    GLOBAL_ZONEID, ipst);
7669 		return;
7670 	}
7671 
7672 	/* Get the ill_index of the ILL */
7673 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7674 
7675 	/*
7676 	 * This location is chosen for the placement of the forwarding hook
7677 	 * because at this point we know that we have a path out for the
7678 	 * packet but haven't yet applied any logic (such as fragmenting)
7679 	 * that happen as part of transmitting the packet out.
7680 	 */
7681 	out_ill = ire->ire_ipif->ipif_ill;
7682 
7683 	DTRACE_PROBE4(ip4__forwarding__start,
7684 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7685 
7686 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
7687 	    ipst->ips_ipv4firewall_forwarding,
7688 	    in_ill, out_ill, ipha, mp, mp, ipst);
7689 
7690 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7691 
7692 	if (mp == NULL)
7693 		return;
7694 	pkt_len = ntohs(ipha->ipha_length);
7695 
7696 	/*
7697 	 * ip_mrtun_forward is only used by foreign agent to reverse
7698 	 * tunnel the incoming packet. So it does not do any option
7699 	 * processing for source routing.
7700 	 */
7701 	max_frag = ire->ire_max_frag;
7702 	if (pkt_len > max_frag) {
7703 		/*
7704 		 * It needs fragging on its way out.  We haven't
7705 		 * verified the header checksum yet.  Since we
7706 		 * are going to put a surely good checksum in the
7707 		 * outgoing header, we have to make sure that it
7708 		 * was good coming in.
7709 		 */
7710 		if (ip_csum_hdr(ipha)) {
7711 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7712 			goto drop_pkt;
7713 		}
7714 
7715 		/* Initiate write side IPPF processing */
7716 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
7717 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7718 			if (mp == NULL) {
7719 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7720 				    "dropped/deferred during ip policy "\
7721 				    "processing\n"));
7722 				return;
7723 			}
7724 		}
7725 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7726 		    BPRI_HI)) == NULL) {
7727 			goto discard_pkt;
7728 		}
7729 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7730 		mp = first_mp;
7731 
7732 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
7733 		return;
7734 	}
7735 
7736 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7737 
7738 	ASSERT(ire->ire_ipif != NULL);
7739 
7740 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7741 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7742 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
7743 	    ipst->ips_ipv4firewall_physical_out,
7744 	    NULL, out_ill, ipha, mp, mp, ipst);
7745 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7746 	if (mp == NULL)
7747 		return;
7748 
7749 	/* Now send the packet to the tunnel interface */
7750 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7751 	q = ire->ire_stq;
7752 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7753 	if ((pktxmit_state == SEND_FAILED) ||
7754 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7755 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7756 		    q->q_ptr));
7757 	}
7758 
7759 	return;
7760 discard_pkt:
7761 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7762 drop_pkt:;
7763 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7764 	freemsg(mp);
7765 #undef	rptr
7766 }
7767 
7768 /*
7769  * Fills the ipsec_out_t data structure with appropriate fields and
7770  * prepends it to mp which contains the IP hdr + data that was meant
7771  * to be forwarded. Please note that ipsec_out_info data structure
7772  * is used here to communicate the outgoing ill path at ip_wput()
7773  * for the ICMP error packet. This has nothing to do with ipsec IP
7774  * security. ipsec_out_t is really used to pass the info to the module
7775  * IP where this information cannot be extracted from conn.
7776  * This functions is called by ip_mrtun_forward().
7777  */
7778 void
7779 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7780 {
7781 	ipsec_out_t	*io;
7782 
7783 	ASSERT(xmit_ill != NULL);
7784 	first_mp->b_datap->db_type = M_CTL;
7785 	first_mp->b_wptr += sizeof (ipsec_info_t);
7786 	/*
7787 	 * This is to pass info to ip_wput in absence of conn.
7788 	 * ipsec_out_secure will be B_FALSE because of this.
7789 	 * Thus ipsec_out_secure being B_FALSE indicates that
7790 	 * this is not IPSEC security related information.
7791 	 */
7792 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7793 	io = (ipsec_out_t *)first_mp->b_rptr;
7794 	io->ipsec_out_type = IPSEC_OUT;
7795 	io->ipsec_out_len = sizeof (ipsec_out_t);
7796 	first_mp->b_cont = mp;
7797 	io->ipsec_out_ill_index =
7798 	    xmit_ill->ill_phyint->phyint_ifindex;
7799 	io->ipsec_out_xmit_if = B_TRUE;
7800 	io->ipsec_out_ns = xmit_ill->ill_ipst->ips_netstack;
7801 }
7802 
7803 /*
7804  * Return the network mask
7805  * associated with the specified address.
7806  */
7807 ipaddr_t
7808 ip_net_mask(ipaddr_t addr)
7809 {
7810 	uchar_t	*up = (uchar_t *)&addr;
7811 	ipaddr_t mask = 0;
7812 	uchar_t	*maskp = (uchar_t *)&mask;
7813 
7814 #if defined(__i386) || defined(__amd64)
7815 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7816 #endif
7817 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7818 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7819 #endif
7820 	if (CLASSD(addr)) {
7821 		maskp[0] = 0xF0;
7822 		return (mask);
7823 	}
7824 	if (addr == 0)
7825 		return (0);
7826 	maskp[0] = 0xFF;
7827 	if ((up[0] & 0x80) == 0)
7828 		return (mask);
7829 
7830 	maskp[1] = 0xFF;
7831 	if ((up[0] & 0xC0) == 0x80)
7832 		return (mask);
7833 
7834 	maskp[2] = 0xFF;
7835 	if ((up[0] & 0xE0) == 0xC0)
7836 		return (mask);
7837 
7838 	/* Must be experimental or multicast, indicate as much */
7839 	return ((ipaddr_t)0);
7840 }
7841 
7842 /*
7843  * Select an ill for the packet by considering load spreading across
7844  * a different ill in the group if dst_ill is part of some group.
7845  */
7846 ill_t *
7847 ip_newroute_get_dst_ill(ill_t *dst_ill)
7848 {
7849 	ill_t *ill;
7850 
7851 	/*
7852 	 * We schedule irrespective of whether the source address is
7853 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7854 	 */
7855 	ill = illgrp_scheduler(dst_ill);
7856 	if (ill == NULL)
7857 		return (NULL);
7858 
7859 	/*
7860 	 * For groups with names ip_sioctl_groupname ensures that all
7861 	 * ills are of same type. For groups without names, ifgrp_insert
7862 	 * ensures this.
7863 	 */
7864 	ASSERT(dst_ill->ill_type == ill->ill_type);
7865 
7866 	return (ill);
7867 }
7868 
7869 /*
7870  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7871  */
7872 ill_t *
7873 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7874     ip_stack_t *ipst)
7875 {
7876 	ill_t *ret_ill;
7877 
7878 	ASSERT(ifindex != 0);
7879 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7880 	    ipst);
7881 	if (ret_ill == NULL ||
7882 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7883 		if (isv6) {
7884 			if (ill != NULL) {
7885 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7886 			} else {
7887 				BUMP_MIB(&ipst->ips_ip6_mib,
7888 				    ipIfStatsOutDiscards);
7889 			}
7890 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7891 			    "bad ifindex %d.\n", ifindex));
7892 		} else {
7893 			if (ill != NULL) {
7894 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7895 			} else {
7896 				BUMP_MIB(&ipst->ips_ip_mib,
7897 				    ipIfStatsOutDiscards);
7898 			}
7899 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7900 			    "bad ifindex %d.\n", ifindex));
7901 		}
7902 		if (ret_ill != NULL)
7903 			ill_refrele(ret_ill);
7904 		freemsg(first_mp);
7905 		return (NULL);
7906 	}
7907 
7908 	return (ret_ill);
7909 }
7910 
7911 /*
7912  * IPv4 -
7913  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7914  * out a packet to a destination address for which we do not have specific
7915  * (or sufficient) routing information.
7916  *
7917  * NOTE : These are the scopes of some of the variables that point at IRE,
7918  *	  which needs to be followed while making any future modifications
7919  *	  to avoid memory leaks.
7920  *
7921  *	- ire and sire are the entries looked up initially by
7922  *	  ire_ftable_lookup.
7923  *	- ipif_ire is used to hold the interface ire associated with
7924  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7925  *	  it before branching out to error paths.
7926  *	- save_ire is initialized before ire_create, so that ire returned
7927  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7928  *	  before breaking out of the switch.
7929  *
7930  *	Thus on failures, we have to REFRELE only ire and sire, if they
7931  *	are not NULL.
7932  */
7933 void
7934 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7935     zoneid_t zoneid, ip_stack_t *ipst)
7936 {
7937 	areq_t	*areq;
7938 	ipaddr_t gw = 0;
7939 	ire_t	*ire = NULL;
7940 	mblk_t	*res_mp;
7941 	ipaddr_t *addrp;
7942 	ipaddr_t nexthop_addr;
7943 	ipif_t  *src_ipif = NULL;
7944 	ill_t	*dst_ill = NULL;
7945 	ipha_t  *ipha;
7946 	ire_t	*sire = NULL;
7947 	mblk_t	*first_mp;
7948 	ire_t	*save_ire;
7949 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7950 	ushort_t ire_marks = 0;
7951 	boolean_t mctl_present;
7952 	ipsec_out_t *io;
7953 	mblk_t	*saved_mp;
7954 	ire_t	*first_sire = NULL;
7955 	mblk_t	*copy_mp = NULL;
7956 	mblk_t	*xmit_mp = NULL;
7957 	ipaddr_t save_dst;
7958 	uint32_t multirt_flags =
7959 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7960 	boolean_t multirt_is_resolvable;
7961 	boolean_t multirt_resolve_next;
7962 	boolean_t do_attach_ill = B_FALSE;
7963 	boolean_t ip_nexthop = B_FALSE;
7964 	tsol_ire_gw_secattr_t *attrp = NULL;
7965 	tsol_gcgrp_t *gcgrp = NULL;
7966 	tsol_gcgrp_addr_t ga;
7967 
7968 	if (ip_debug > 2) {
7969 		/* ip1dbg */
7970 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7971 	}
7972 
7973 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7974 	if (mctl_present) {
7975 		io = (ipsec_out_t *)first_mp->b_rptr;
7976 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7977 		ASSERT(zoneid == io->ipsec_out_zoneid);
7978 		ASSERT(zoneid != ALL_ZONES);
7979 	}
7980 
7981 	ipha = (ipha_t *)mp->b_rptr;
7982 
7983 	/* All multicast lookups come through ip_newroute_ipif() */
7984 	if (CLASSD(dst)) {
7985 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7986 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7987 		freemsg(first_mp);
7988 		return;
7989 	}
7990 
7991 	if (mctl_present && io->ipsec_out_attach_if) {
7992 		/* ip_grab_attach_ill returns a held ill */
7993 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7994 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7995 
7996 		/* Failure case frees things for us. */
7997 		if (attach_ill == NULL)
7998 			return;
7999 
8000 		/*
8001 		 * Check if we need an ire that will not be
8002 		 * looked up by anybody else i.e. HIDDEN.
8003 		 */
8004 		if (ill_is_probeonly(attach_ill))
8005 			ire_marks = IRE_MARK_HIDDEN;
8006 	}
8007 	if (mctl_present && io->ipsec_out_ip_nexthop) {
8008 		ip_nexthop = B_TRUE;
8009 		nexthop_addr = io->ipsec_out_nexthop_addr;
8010 	}
8011 	/*
8012 	 * If this IRE is created for forwarding or it is not for
8013 	 * traffic for congestion controlled protocols, mark it as temporary.
8014 	 */
8015 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
8016 		ire_marks |= IRE_MARK_TEMPORARY;
8017 
8018 	/*
8019 	 * Get what we can from ire_ftable_lookup which will follow an IRE
8020 	 * chain until it gets the most specific information available.
8021 	 * For example, we know that there is no IRE_CACHE for this dest,
8022 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
8023 	 * ire_ftable_lookup will look up the gateway, etc.
8024 	 * Check if in_ill != NULL. If it is true, the packet must be
8025 	 * from an incoming interface where RTA_SRCIFP is set.
8026 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
8027 	 * to the destination, of equal netmask length in the forward table,
8028 	 * will be recursively explored. If no information is available
8029 	 * for the final gateway of that route, we force the returned ire
8030 	 * to be equal to sire using MATCH_IRE_PARENT.
8031 	 * At least, in this case we have a starting point (in the buckets)
8032 	 * to look for other routes to the destination in the forward table.
8033 	 * This is actually used only for multirouting, where a list
8034 	 * of routes has to be processed in sequence.
8035 	 *
8036 	 * In the process of coming up with the most specific information,
8037 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8038 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8039 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8040 	 * Two caveats when handling incomplete ire's in ip_newroute:
8041 	 * - we should be careful when accessing its ire_nce (specifically
8042 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8043 	 * - not all legacy code path callers are prepared to handle
8044 	 *   incomplete ire's, so we should not create/add incomplete
8045 	 *   ire_cache entries here. (See discussion about temporary solution
8046 	 *   further below).
8047 	 *
8048 	 * In order to minimize packet dropping, and to preserve existing
8049 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8050 	 * gateway, and instead use the IF_RESOLVER ire to send out
8051 	 * another request to ARP (this is achieved by passing the
8052 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8053 	 * arp response comes back in ip_wput_nondata, we will create
8054 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8055 	 *
8056 	 * Note that this is a temporary solution; the correct solution is
8057 	 * to create an incomplete  per-dst ire_cache entry, and send the
8058 	 * packet out when the gw's nce is resolved. In order to achieve this,
8059 	 * all packet processing must have been completed prior to calling
8060 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8061 	 * to be modified to accomodate this solution.
8062 	 */
8063 	if (in_ill != NULL) {
8064 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
8065 		    in_ill, MATCH_IRE_TYPE);
8066 	} else if (ip_nexthop) {
8067 		/*
8068 		 * The first time we come here, we look for an IRE_INTERFACE
8069 		 * entry for the specified nexthop, set the dst to be the
8070 		 * nexthop address and create an IRE_CACHE entry for the
8071 		 * nexthop. The next time around, we are able to find an
8072 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8073 		 * nexthop address and create an IRE_CACHE entry for the
8074 		 * destination address via the specified nexthop.
8075 		 */
8076 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8077 		    MBLK_GETLABEL(mp), ipst);
8078 		if (ire != NULL) {
8079 			gw = nexthop_addr;
8080 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8081 		} else {
8082 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8083 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8084 			    MBLK_GETLABEL(mp),
8085 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8086 			    ipst);
8087 			if (ire != NULL) {
8088 				dst = nexthop_addr;
8089 			}
8090 		}
8091 	} else if (attach_ill == NULL) {
8092 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8093 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8094 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8095 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8096 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8097 		    ipst);
8098 	} else {
8099 		/*
8100 		 * attach_ill is set only for communicating with
8101 		 * on-link hosts. So, don't look for DEFAULT.
8102 		 */
8103 		ipif_t	*attach_ipif;
8104 
8105 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8106 		if (attach_ipif == NULL) {
8107 			ill_refrele(attach_ill);
8108 			goto icmp_err_ret;
8109 		}
8110 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8111 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8112 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8113 		    MATCH_IRE_SECATTR, ipst);
8114 		ipif_refrele(attach_ipif);
8115 	}
8116 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8117 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8118 
8119 	/*
8120 	 * This loop is run only once in most cases.
8121 	 * We loop to resolve further routes only when the destination
8122 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8123 	 */
8124 	do {
8125 		/* Clear the previous iteration's values */
8126 		if (src_ipif != NULL) {
8127 			ipif_refrele(src_ipif);
8128 			src_ipif = NULL;
8129 		}
8130 		if (dst_ill != NULL) {
8131 			ill_refrele(dst_ill);
8132 			dst_ill = NULL;
8133 		}
8134 
8135 		multirt_resolve_next = B_FALSE;
8136 		/*
8137 		 * We check if packets have to be multirouted.
8138 		 * In this case, given the current <ire, sire> couple,
8139 		 * we look for the next suitable <ire, sire>.
8140 		 * This check is done in ire_multirt_lookup(),
8141 		 * which applies various criteria to find the next route
8142 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8143 		 * unchanged if it detects it has not been tried yet.
8144 		 */
8145 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8146 			ip3dbg(("ip_newroute: starting next_resolution "
8147 			    "with first_mp %p, tag %d\n",
8148 			    (void *)first_mp,
8149 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8150 
8151 			ASSERT(sire != NULL);
8152 			multirt_is_resolvable =
8153 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8154 			    MBLK_GETLABEL(mp), ipst);
8155 
8156 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8157 			    "ire %p, sire %p\n",
8158 			    multirt_is_resolvable,
8159 			    (void *)ire, (void *)sire));
8160 
8161 			if (!multirt_is_resolvable) {
8162 				/*
8163 				 * No more multirt route to resolve; give up
8164 				 * (all routes resolved or no more
8165 				 * resolvable routes).
8166 				 */
8167 				if (ire != NULL) {
8168 					ire_refrele(ire);
8169 					ire = NULL;
8170 				}
8171 			} else {
8172 				ASSERT(sire != NULL);
8173 				ASSERT(ire != NULL);
8174 				/*
8175 				 * We simply use first_sire as a flag that
8176 				 * indicates if a resolvable multirt route
8177 				 * has already been found.
8178 				 * If it is not the case, we may have to send
8179 				 * an ICMP error to report that the
8180 				 * destination is unreachable.
8181 				 * We do not IRE_REFHOLD first_sire.
8182 				 */
8183 				if (first_sire == NULL) {
8184 					first_sire = sire;
8185 				}
8186 			}
8187 		}
8188 		if (ire == NULL) {
8189 			if (ip_debug > 3) {
8190 				/* ip2dbg */
8191 				pr_addr_dbg("ip_newroute: "
8192 				    "can't resolve %s\n", AF_INET, &dst);
8193 			}
8194 			ip3dbg(("ip_newroute: "
8195 			    "ire %p, sire %p, first_sire %p\n",
8196 			    (void *)ire, (void *)sire, (void *)first_sire));
8197 
8198 			if (sire != NULL) {
8199 				ire_refrele(sire);
8200 				sire = NULL;
8201 			}
8202 
8203 			if (first_sire != NULL) {
8204 				/*
8205 				 * At least one multirt route has been found
8206 				 * in the same call to ip_newroute();
8207 				 * there is no need to report an ICMP error.
8208 				 * first_sire was not IRE_REFHOLDed.
8209 				 */
8210 				MULTIRT_DEBUG_UNTAG(first_mp);
8211 				freemsg(first_mp);
8212 				return;
8213 			}
8214 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8215 			    RTA_DST, ipst);
8216 			if (attach_ill != NULL)
8217 				ill_refrele(attach_ill);
8218 			goto icmp_err_ret;
8219 		}
8220 
8221 		/*
8222 		 * When RTA_SRCIFP is used to add a route, then an interface
8223 		 * route is added in the source interface's routing table.
8224 		 * If the outgoing interface of this route is of type
8225 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8226 		 * ire_nce->nce_res_mp is set to NULL.
8227 		 * Later, when this route is first used for forwarding
8228 		 * a packet, ip_newroute() is called
8229 		 * to resolve the hardware address of the outgoing ipif.
8230 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8231 		 * source interface based table. We only come here if the
8232 		 * outgoing interface is a resolver interface and we don't
8233 		 * have the ire_nce->nce_res_mp information yet.
8234 		 * If in_ill is not null that means it is called from
8235 		 * ip_rput.
8236 		 */
8237 
8238 		ASSERT(ire->ire_in_ill == NULL ||
8239 		    (ire->ire_type == IRE_IF_RESOLVER &&
8240 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8241 
8242 		/*
8243 		 * Verify that the returned IRE does not have either
8244 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8245 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8246 		 */
8247 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8248 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8249 			if (attach_ill != NULL)
8250 				ill_refrele(attach_ill);
8251 			goto icmp_err_ret;
8252 		}
8253 		/*
8254 		 * Increment the ire_ob_pkt_count field for ire if it is an
8255 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8256 		 * increment the same for the parent IRE, sire, if it is some
8257 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8258 		 */
8259 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8260 			UPDATE_OB_PKT_COUNT(ire);
8261 			ire->ire_last_used_time = lbolt;
8262 		}
8263 
8264 		if (sire != NULL) {
8265 			gw = sire->ire_gateway_addr;
8266 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8267 			    IRE_INTERFACE)) == 0);
8268 			UPDATE_OB_PKT_COUNT(sire);
8269 			sire->ire_last_used_time = lbolt;
8270 		}
8271 		/*
8272 		 * We have a route to reach the destination.
8273 		 *
8274 		 * 1) If the interface is part of ill group, try to get a new
8275 		 *    ill taking load spreading into account.
8276 		 *
8277 		 * 2) After selecting the ill, get a source address that
8278 		 *    might create good inbound load spreading.
8279 		 *    ipif_select_source does this for us.
8280 		 *
8281 		 * If the application specified the ill (ifindex), we still
8282 		 * load spread. Only if the packets needs to go out
8283 		 * specifically on a given ill e.g. binding to
8284 		 * IPIF_NOFAILOVER address, then we don't try to use a
8285 		 * different ill for load spreading.
8286 		 */
8287 		if (attach_ill == NULL) {
8288 			/*
8289 			 * Don't perform outbound load spreading in the
8290 			 * case of an RTF_MULTIRT route, as we actually
8291 			 * typically want to replicate outgoing packets
8292 			 * through particular interfaces.
8293 			 */
8294 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8295 				dst_ill = ire->ire_ipif->ipif_ill;
8296 				/* for uniformity */
8297 				ill_refhold(dst_ill);
8298 			} else {
8299 				/*
8300 				 * If we are here trying to create an IRE_CACHE
8301 				 * for an offlink destination and have the
8302 				 * IRE_CACHE for the next hop and the latter is
8303 				 * using virtual IP source address selection i.e
8304 				 * it's ire->ire_ipif is pointing to a virtual
8305 				 * network interface (vni) then
8306 				 * ip_newroute_get_dst_ll() will return the vni
8307 				 * interface as the dst_ill. Since the vni is
8308 				 * virtual i.e not associated with any physical
8309 				 * interface, it cannot be the dst_ill, hence
8310 				 * in such a case call ip_newroute_get_dst_ll()
8311 				 * with the stq_ill instead of the ire_ipif ILL.
8312 				 * The function returns a refheld ill.
8313 				 */
8314 				if ((ire->ire_type == IRE_CACHE) &&
8315 				    IS_VNI(ire->ire_ipif->ipif_ill))
8316 					dst_ill = ip_newroute_get_dst_ill(
8317 					    ire->ire_stq->q_ptr);
8318 				else
8319 					dst_ill = ip_newroute_get_dst_ill(
8320 					    ire->ire_ipif->ipif_ill);
8321 			}
8322 			if (dst_ill == NULL) {
8323 				if (ip_debug > 2) {
8324 					pr_addr_dbg("ip_newroute: "
8325 					    "no dst ill for dst"
8326 					    " %s\n", AF_INET, &dst);
8327 				}
8328 				goto icmp_err_ret;
8329 			}
8330 		} else {
8331 			dst_ill = ire->ire_ipif->ipif_ill;
8332 			/* for uniformity */
8333 			ill_refhold(dst_ill);
8334 			/*
8335 			 * We should have found a route matching ill as we
8336 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8337 			 * Rather than asserting, when there is a mismatch,
8338 			 * we just drop the packet.
8339 			 */
8340 			if (dst_ill != attach_ill) {
8341 				ip0dbg(("ip_newroute: Packet dropped as "
8342 				    "IPIF_NOFAILOVER ill is %s, "
8343 				    "ire->ire_ipif->ipif_ill is %s\n",
8344 				    attach_ill->ill_name,
8345 				    dst_ill->ill_name));
8346 				ill_refrele(attach_ill);
8347 				goto icmp_err_ret;
8348 			}
8349 		}
8350 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8351 		if (attach_ill != NULL) {
8352 			ill_refrele(attach_ill);
8353 			attach_ill = NULL;
8354 			do_attach_ill = B_TRUE;
8355 		}
8356 		ASSERT(dst_ill != NULL);
8357 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8358 
8359 		/*
8360 		 * Pick the best source address from dst_ill.
8361 		 *
8362 		 * 1) If it is part of a multipathing group, we would
8363 		 *    like to spread the inbound packets across different
8364 		 *    interfaces. ipif_select_source picks a random source
8365 		 *    across the different ills in the group.
8366 		 *
8367 		 * 2) If it is not part of a multipathing group, we try
8368 		 *    to pick the source address from the destination
8369 		 *    route. Clustering assumes that when we have multiple
8370 		 *    prefixes hosted on an interface, the prefix of the
8371 		 *    source address matches the prefix of the destination
8372 		 *    route. We do this only if the address is not
8373 		 *    DEPRECATED.
8374 		 *
8375 		 * 3) If the conn is in a different zone than the ire, we
8376 		 *    need to pick a source address from the right zone.
8377 		 *
8378 		 * NOTE : If we hit case (1) above, the prefix of the source
8379 		 *	  address picked may not match the prefix of the
8380 		 *	  destination routes prefix as ipif_select_source
8381 		 *	  does not look at "dst" while picking a source
8382 		 *	  address.
8383 		 *	  If we want the same behavior as (2), we will need
8384 		 *	  to change the behavior of ipif_select_source.
8385 		 */
8386 		ASSERT(src_ipif == NULL);
8387 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8388 			/*
8389 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8390 			 * Check that the ipif matching the requested source
8391 			 * address still exists.
8392 			 */
8393 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8394 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8395 		}
8396 		if (src_ipif == NULL) {
8397 			ire_marks |= IRE_MARK_USESRC_CHECK;
8398 			if ((dst_ill->ill_group != NULL) ||
8399 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8400 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8401 			    ire->ire_zoneid != ALL_ZONES) ||
8402 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8403 				/*
8404 				 * If the destination is reachable via a
8405 				 * given gateway, the selected source address
8406 				 * should be in the same subnet as the gateway.
8407 				 * Otherwise, the destination is not reachable.
8408 				 *
8409 				 * If there are no interfaces on the same subnet
8410 				 * as the destination, ipif_select_source gives
8411 				 * first non-deprecated interface which might be
8412 				 * on a different subnet than the gateway.
8413 				 * This is not desirable. Hence pass the dst_ire
8414 				 * source address to ipif_select_source.
8415 				 * It is sure that the destination is reachable
8416 				 * with the dst_ire source address subnet.
8417 				 * So passing dst_ire source address to
8418 				 * ipif_select_source will make sure that the
8419 				 * selected source will be on the same subnet
8420 				 * as dst_ire source address.
8421 				 */
8422 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8423 				src_ipif = ipif_select_source(dst_ill, saddr,
8424 				    zoneid);
8425 				if (src_ipif == NULL) {
8426 					if (ip_debug > 2) {
8427 						pr_addr_dbg("ip_newroute: "
8428 						    "no src for dst %s ",
8429 						    AF_INET, &dst);
8430 						printf("through interface %s\n",
8431 						    dst_ill->ill_name);
8432 					}
8433 					goto icmp_err_ret;
8434 				}
8435 			} else {
8436 				src_ipif = ire->ire_ipif;
8437 				ASSERT(src_ipif != NULL);
8438 				/* hold src_ipif for uniformity */
8439 				ipif_refhold(src_ipif);
8440 			}
8441 		}
8442 
8443 		/*
8444 		 * Assign a source address while we have the conn.
8445 		 * We can't have ip_wput_ire pick a source address when the
8446 		 * packet returns from arp since we need to look at
8447 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8448 		 * going through arp.
8449 		 *
8450 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8451 		 *	  it uses ip6i to store this information.
8452 		 */
8453 		if (ipha->ipha_src == INADDR_ANY &&
8454 		    (connp == NULL || !connp->conn_unspec_src)) {
8455 			ipha->ipha_src = src_ipif->ipif_src_addr;
8456 		}
8457 		if (ip_debug > 3) {
8458 			/* ip2dbg */
8459 			pr_addr_dbg("ip_newroute: first hop %s\n",
8460 			    AF_INET, &gw);
8461 		}
8462 		ip2dbg(("\tire type %s (%d)\n",
8463 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8464 
8465 		/*
8466 		 * The TTL of multirouted packets is bounded by the
8467 		 * ip_multirt_ttl ndd variable.
8468 		 */
8469 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8470 			/* Force TTL of multirouted packets */
8471 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8472 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8473 				ip2dbg(("ip_newroute: forcing multirt TTL "
8474 				    "to %d (was %d), dst 0x%08x\n",
8475 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8476 				    ntohl(sire->ire_addr)));
8477 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8478 			}
8479 		}
8480 		/*
8481 		 * At this point in ip_newroute(), ire is either the
8482 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8483 		 * destination or an IRE_INTERFACE type that should be used
8484 		 * to resolve an on-subnet destination or an on-subnet
8485 		 * next-hop gateway.
8486 		 *
8487 		 * In the IRE_CACHE case, we have the following :
8488 		 *
8489 		 * 1) src_ipif - used for getting a source address.
8490 		 *
8491 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8492 		 *    means packets using this IRE_CACHE will go out on
8493 		 *    dst_ill.
8494 		 *
8495 		 * 3) The IRE sire will point to the prefix that is the
8496 		 *    longest  matching route for the destination. These
8497 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8498 		 *
8499 		 *    The newly created IRE_CACHE entry for the off-subnet
8500 		 *    destination is tied to both the prefix route and the
8501 		 *    interface route used to resolve the next-hop gateway
8502 		 *    via the ire_phandle and ire_ihandle fields,
8503 		 *    respectively.
8504 		 *
8505 		 * In the IRE_INTERFACE case, we have the following :
8506 		 *
8507 		 * 1) src_ipif - used for getting a source address.
8508 		 *
8509 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8510 		 *    means packets using the IRE_CACHE that we will build
8511 		 *    here will go out on dst_ill.
8512 		 *
8513 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8514 		 *    to be created will only be tied to the IRE_INTERFACE
8515 		 *    that was derived from the ire_ihandle field.
8516 		 *
8517 		 *    If sire is non-NULL, it means the destination is
8518 		 *    off-link and we will first create the IRE_CACHE for the
8519 		 *    gateway. Next time through ip_newroute, we will create
8520 		 *    the IRE_CACHE for the final destination as described
8521 		 *    above.
8522 		 *
8523 		 * In both cases, after the current resolution has been
8524 		 * completed (or possibly initialised, in the IRE_INTERFACE
8525 		 * case), the loop may be re-entered to attempt the resolution
8526 		 * of another RTF_MULTIRT route.
8527 		 *
8528 		 * When an IRE_CACHE entry for the off-subnet destination is
8529 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8530 		 * for further processing in emission loops.
8531 		 */
8532 		save_ire = ire;
8533 		switch (ire->ire_type) {
8534 		case IRE_CACHE: {
8535 			ire_t	*ipif_ire;
8536 
8537 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8538 			if (gw == 0)
8539 				gw = ire->ire_gateway_addr;
8540 			/*
8541 			 * We need 3 ire's to create a new cache ire for an
8542 			 * off-link destination from the cache ire of the
8543 			 * gateway.
8544 			 *
8545 			 *	1. The prefix ire 'sire' (Note that this does
8546 			 *	   not apply to the conn_nexthop_set case)
8547 			 *	2. The cache ire of the gateway 'ire'
8548 			 *	3. The interface ire 'ipif_ire'
8549 			 *
8550 			 * We have (1) and (2). We lookup (3) below.
8551 			 *
8552 			 * If there is no interface route to the gateway,
8553 			 * it is a race condition, where we found the cache
8554 			 * but the interface route has been deleted.
8555 			 */
8556 			if (ip_nexthop) {
8557 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8558 			} else {
8559 				ipif_ire =
8560 				    ire_ihandle_lookup_offlink(ire, sire);
8561 			}
8562 			if (ipif_ire == NULL) {
8563 				ip1dbg(("ip_newroute: "
8564 				    "ire_ihandle_lookup_offlink failed\n"));
8565 				goto icmp_err_ret;
8566 			}
8567 
8568 			/*
8569 			 * Check cached gateway IRE for any security
8570 			 * attributes; if found, associate the gateway
8571 			 * credentials group to the destination IRE.
8572 			 */
8573 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8574 				mutex_enter(&attrp->igsa_lock);
8575 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8576 					GCGRP_REFHOLD(gcgrp);
8577 				mutex_exit(&attrp->igsa_lock);
8578 			}
8579 
8580 			/*
8581 			 * XXX For the source of the resolver mp,
8582 			 * we are using the same DL_UNITDATA_REQ
8583 			 * (from save_ire->ire_nce->nce_res_mp)
8584 			 * though the save_ire is not pointing at the same ill.
8585 			 * This is incorrect. We need to send it up to the
8586 			 * resolver to get the right res_mp. For ethernets
8587 			 * this may be okay (ill_type == DL_ETHER).
8588 			 */
8589 
8590 			ire = ire_create(
8591 			    (uchar_t *)&dst,		/* dest address */
8592 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8593 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8594 			    (uchar_t *)&gw,		/* gateway address */
8595 			    NULL,
8596 			    &save_ire->ire_max_frag,
8597 			    save_ire->ire_nce,		/* src nce */
8598 			    dst_ill->ill_rq,		/* recv-from queue */
8599 			    dst_ill->ill_wq,		/* send-to queue */
8600 			    IRE_CACHE,			/* IRE type */
8601 			    src_ipif,
8602 			    in_ill,			/* incoming ill */
8603 			    (sire != NULL) ?
8604 			    sire->ire_mask : 0, 	/* Parent mask */
8605 			    (sire != NULL) ?
8606 			    sire->ire_phandle : 0,	/* Parent handle */
8607 			    ipif_ire->ire_ihandle,	/* Interface handle */
8608 			    (sire != NULL) ? (sire->ire_flags &
8609 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8610 			    (sire != NULL) ?
8611 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8612 			    NULL,
8613 			    gcgrp,
8614 			    ipst);
8615 
8616 			if (ire == NULL) {
8617 				if (gcgrp != NULL) {
8618 					GCGRP_REFRELE(gcgrp);
8619 					gcgrp = NULL;
8620 				}
8621 				ire_refrele(ipif_ire);
8622 				ire_refrele(save_ire);
8623 				break;
8624 			}
8625 
8626 			/* reference now held by IRE */
8627 			gcgrp = NULL;
8628 
8629 			ire->ire_marks |= ire_marks;
8630 
8631 			/*
8632 			 * Prevent sire and ipif_ire from getting deleted.
8633 			 * The newly created ire is tied to both of them via
8634 			 * the phandle and ihandle respectively.
8635 			 */
8636 			if (sire != NULL) {
8637 				IRB_REFHOLD(sire->ire_bucket);
8638 				/* Has it been removed already ? */
8639 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8640 					IRB_REFRELE(sire->ire_bucket);
8641 					ire_refrele(ipif_ire);
8642 					ire_refrele(save_ire);
8643 					break;
8644 				}
8645 			}
8646 
8647 			IRB_REFHOLD(ipif_ire->ire_bucket);
8648 			/* Has it been removed already ? */
8649 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8650 				IRB_REFRELE(ipif_ire->ire_bucket);
8651 				if (sire != NULL)
8652 					IRB_REFRELE(sire->ire_bucket);
8653 				ire_refrele(ipif_ire);
8654 				ire_refrele(save_ire);
8655 				break;
8656 			}
8657 
8658 			xmit_mp = first_mp;
8659 			/*
8660 			 * In the case of multirouting, a copy
8661 			 * of the packet is done before its sending.
8662 			 * The copy is used to attempt another
8663 			 * route resolution, in a next loop.
8664 			 */
8665 			if (ire->ire_flags & RTF_MULTIRT) {
8666 				copy_mp = copymsg(first_mp);
8667 				if (copy_mp != NULL) {
8668 					xmit_mp = copy_mp;
8669 					MULTIRT_DEBUG_TAG(first_mp);
8670 				}
8671 			}
8672 			ire_add_then_send(q, ire, xmit_mp);
8673 			ire_refrele(save_ire);
8674 
8675 			/* Assert that sire is not deleted yet. */
8676 			if (sire != NULL) {
8677 				ASSERT(sire->ire_ptpn != NULL);
8678 				IRB_REFRELE(sire->ire_bucket);
8679 			}
8680 
8681 			/* Assert that ipif_ire is not deleted yet. */
8682 			ASSERT(ipif_ire->ire_ptpn != NULL);
8683 			IRB_REFRELE(ipif_ire->ire_bucket);
8684 			ire_refrele(ipif_ire);
8685 
8686 			/*
8687 			 * If copy_mp is not NULL, multirouting was
8688 			 * requested. We loop to initiate a next
8689 			 * route resolution attempt, starting from sire.
8690 			 */
8691 			if (copy_mp != NULL) {
8692 				/*
8693 				 * Search for the next unresolved
8694 				 * multirt route.
8695 				 */
8696 				copy_mp = NULL;
8697 				ipif_ire = NULL;
8698 				ire = NULL;
8699 				multirt_resolve_next = B_TRUE;
8700 				continue;
8701 			}
8702 			if (sire != NULL)
8703 				ire_refrele(sire);
8704 			ipif_refrele(src_ipif);
8705 			ill_refrele(dst_ill);
8706 			return;
8707 		}
8708 		case IRE_IF_NORESOLVER: {
8709 
8710 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8711 			    dst_ill->ill_resolver_mp == NULL) {
8712 				ip1dbg(("ip_newroute: dst_ill %p "
8713 				    "for IRE_IF_NORESOLVER ire %p has "
8714 				    "no ill_resolver_mp\n",
8715 				    (void *)dst_ill, (void *)ire));
8716 				break;
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,			/* no src nce */
8744 			    dst_ill->ill_rq,		/* recv-from queue */
8745 			    dst_ill->ill_wq,		/* send-to queue */
8746 			    IRE_CACHE,
8747 			    src_ipif,
8748 			    in_ill,			/* Incoming ill */
8749 			    save_ire->ire_mask,		/* Parent mask */
8750 			    (sire != NULL) ?		/* Parent handle */
8751 			    sire->ire_phandle : 0,
8752 			    save_ire->ire_ihandle,	/* Interface handle */
8753 			    (sire != NULL) ? sire->ire_flags &
8754 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8755 			    &(save_ire->ire_uinfo),
8756 			    NULL,
8757 			    gcgrp,
8758 			    ipst);
8759 
8760 			if (ire == NULL) {
8761 				if (gcgrp != NULL) {
8762 					GCGRP_REFRELE(gcgrp);
8763 					gcgrp = NULL;
8764 				}
8765 				ire_refrele(save_ire);
8766 				break;
8767 			}
8768 
8769 			/* reference now held by IRE */
8770 			gcgrp = NULL;
8771 
8772 			ire->ire_marks |= ire_marks;
8773 
8774 			/* Prevent save_ire from getting deleted */
8775 			IRB_REFHOLD(save_ire->ire_bucket);
8776 			/* Has it been removed already ? */
8777 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8778 				IRB_REFRELE(save_ire->ire_bucket);
8779 				ire_refrele(save_ire);
8780 				break;
8781 			}
8782 
8783 			/*
8784 			 * In the case of multirouting, a copy
8785 			 * of the packet is made before it is sent.
8786 			 * The copy is used in the next
8787 			 * loop to attempt another resolution.
8788 			 */
8789 			xmit_mp = first_mp;
8790 			if ((sire != NULL) &&
8791 			    (sire->ire_flags & RTF_MULTIRT)) {
8792 				copy_mp = copymsg(first_mp);
8793 				if (copy_mp != NULL) {
8794 					xmit_mp = copy_mp;
8795 					MULTIRT_DEBUG_TAG(first_mp);
8796 				}
8797 			}
8798 			ire_add_then_send(q, ire, xmit_mp);
8799 
8800 			/* Assert that it is not deleted yet. */
8801 			ASSERT(save_ire->ire_ptpn != NULL);
8802 			IRB_REFRELE(save_ire->ire_bucket);
8803 			ire_refrele(save_ire);
8804 
8805 			if (copy_mp != NULL) {
8806 				/*
8807 				 * If we found a (no)resolver, we ignore any
8808 				 * trailing top priority IRE_CACHE in further
8809 				 * loops. This ensures that we do not omit any
8810 				 * (no)resolver.
8811 				 * This IRE_CACHE, if any, will be processed
8812 				 * by another thread entering ip_newroute().
8813 				 * IRE_CACHE entries, if any, will be processed
8814 				 * by another thread entering ip_newroute(),
8815 				 * (upon resolver response, for instance).
8816 				 * This aims to force parallel multirt
8817 				 * resolutions as soon as a packet must be sent.
8818 				 * In the best case, after the tx of only one
8819 				 * packet, all reachable routes are resolved.
8820 				 * Otherwise, the resolution of all RTF_MULTIRT
8821 				 * routes would require several emissions.
8822 				 */
8823 				multirt_flags &= ~MULTIRT_CACHEGW;
8824 
8825 				/*
8826 				 * Search for the next unresolved multirt
8827 				 * route.
8828 				 */
8829 				copy_mp = NULL;
8830 				save_ire = NULL;
8831 				ire = NULL;
8832 				multirt_resolve_next = B_TRUE;
8833 				continue;
8834 			}
8835 
8836 			/*
8837 			 * Don't need sire anymore
8838 			 */
8839 			if (sire != NULL)
8840 				ire_refrele(sire);
8841 
8842 			ipif_refrele(src_ipif);
8843 			ill_refrele(dst_ill);
8844 			return;
8845 		}
8846 		case IRE_IF_RESOLVER:
8847 			/*
8848 			 * We can't build an IRE_CACHE yet, but at least we
8849 			 * found a resolver that can help.
8850 			 */
8851 			res_mp = dst_ill->ill_resolver_mp;
8852 			if (!OK_RESOLVER_MP(res_mp))
8853 				break;
8854 
8855 			/*
8856 			 * To be at this point in the code with a non-zero gw
8857 			 * means that dst is reachable through a gateway that
8858 			 * we have never resolved.  By changing dst to the gw
8859 			 * addr we resolve the gateway first.
8860 			 * When ire_add_then_send() tries to put the IP dg
8861 			 * to dst, it will reenter ip_newroute() at which
8862 			 * time we will find the IRE_CACHE for the gw and
8863 			 * create another IRE_CACHE in case IRE_CACHE above.
8864 			 */
8865 			if (gw != INADDR_ANY) {
8866 				/*
8867 				 * The source ipif that was determined above was
8868 				 * relative to the destination address, not the
8869 				 * gateway's. If src_ipif was not taken out of
8870 				 * the IRE_IF_RESOLVER entry, we'll need to call
8871 				 * ipif_select_source() again.
8872 				 */
8873 				if (src_ipif != ire->ire_ipif) {
8874 					ipif_refrele(src_ipif);
8875 					src_ipif = ipif_select_source(dst_ill,
8876 					    gw, zoneid);
8877 					if (src_ipif == NULL) {
8878 						if (ip_debug > 2) {
8879 							pr_addr_dbg(
8880 							    "ip_newroute: no "
8881 							    "src for gw %s ",
8882 							    AF_INET, &gw);
8883 							printf("through "
8884 							    "interface %s\n",
8885 							    dst_ill->ill_name);
8886 						}
8887 						goto icmp_err_ret;
8888 					}
8889 				}
8890 				save_dst = dst;
8891 				dst = gw;
8892 				gw = INADDR_ANY;
8893 			}
8894 
8895 			/*
8896 			 * We obtain a partial IRE_CACHE which we will pass
8897 			 * along with the resolver query.  When the response
8898 			 * comes back it will be there ready for us to add.
8899 			 * The ire_max_frag is atomically set under the
8900 			 * irebucket lock in ire_add_v[46].
8901 			 */
8902 
8903 			ire = ire_create_mp(
8904 			    (uchar_t *)&dst,		/* dest address */
8905 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8906 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8907 			    (uchar_t *)&gw,		/* gateway address */
8908 			    NULL,			/* no in_src_addr */
8909 			    NULL,			/* ire_max_frag */
8910 			    NULL,			/* no src nce */
8911 			    dst_ill->ill_rq,		/* recv-from queue */
8912 			    dst_ill->ill_wq,		/* send-to queue */
8913 			    IRE_CACHE,
8914 			    src_ipif,			/* Interface ipif */
8915 			    in_ill,			/* Incoming ILL */
8916 			    save_ire->ire_mask,		/* Parent mask */
8917 			    0,
8918 			    save_ire->ire_ihandle,	/* Interface handle */
8919 			    0,				/* flags if any */
8920 			    &(save_ire->ire_uinfo),
8921 			    NULL,
8922 			    NULL,
8923 			    ipst);
8924 
8925 			if (ire == NULL) {
8926 				ire_refrele(save_ire);
8927 				break;
8928 			}
8929 
8930 			if ((sire != NULL) &&
8931 			    (sire->ire_flags & RTF_MULTIRT)) {
8932 				copy_mp = copymsg(first_mp);
8933 				if (copy_mp != NULL)
8934 					MULTIRT_DEBUG_TAG(copy_mp);
8935 			}
8936 
8937 			ire->ire_marks |= ire_marks;
8938 
8939 			/*
8940 			 * Construct message chain for the resolver
8941 			 * of the form:
8942 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8943 			 * Packet could contain a IPSEC_OUT mp.
8944 			 *
8945 			 * NOTE : ire will be added later when the response
8946 			 * comes back from ARP. If the response does not
8947 			 * come back, ARP frees the packet. For this reason,
8948 			 * we can't REFHOLD the bucket of save_ire to prevent
8949 			 * deletions. We may not be able to REFRELE the bucket
8950 			 * if the response never comes back. Thus, before
8951 			 * adding the ire, ire_add_v4 will make sure that the
8952 			 * interface route does not get deleted. This is the
8953 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8954 			 * where we can always prevent deletions because of
8955 			 * the synchronous nature of adding IRES i.e
8956 			 * ire_add_then_send is called after creating the IRE.
8957 			 */
8958 			ASSERT(ire->ire_mp != NULL);
8959 			ire->ire_mp->b_cont = first_mp;
8960 			/* Have saved_mp handy, for cleanup if canput fails */
8961 			saved_mp = mp;
8962 			mp = copyb(res_mp);
8963 			if (mp == NULL) {
8964 				/* Prepare for cleanup */
8965 				mp = saved_mp; /* pkt */
8966 				ire_delete(ire); /* ire_mp */
8967 				ire = NULL;
8968 				ire_refrele(save_ire);
8969 				if (copy_mp != NULL) {
8970 					MULTIRT_DEBUG_UNTAG(copy_mp);
8971 					freemsg(copy_mp);
8972 					copy_mp = NULL;
8973 				}
8974 				break;
8975 			}
8976 			linkb(mp, ire->ire_mp);
8977 
8978 			/*
8979 			 * Fill in the source and dest addrs for the resolver.
8980 			 * NOTE: this depends on memory layouts imposed by
8981 			 * ill_init().
8982 			 */
8983 			areq = (areq_t *)mp->b_rptr;
8984 			addrp = (ipaddr_t *)((char *)areq +
8985 			    areq->areq_sender_addr_offset);
8986 			if (do_attach_ill) {
8987 				/*
8988 				 * This is bind to no failover case.
8989 				 * arp packet also must go out on attach_ill.
8990 				 */
8991 				ASSERT(ipha->ipha_src != NULL);
8992 				*addrp = ipha->ipha_src;
8993 			} else {
8994 				*addrp = save_ire->ire_src_addr;
8995 			}
8996 
8997 			ire_refrele(save_ire);
8998 			addrp = (ipaddr_t *)((char *)areq +
8999 			    areq->areq_target_addr_offset);
9000 			*addrp = dst;
9001 			/* Up to the resolver. */
9002 			if (canputnext(dst_ill->ill_rq) &&
9003 			    !(dst_ill->ill_arp_closing)) {
9004 				putnext(dst_ill->ill_rq, mp);
9005 				ire = NULL;
9006 				if (copy_mp != NULL) {
9007 					/*
9008 					 * If we found a resolver, we ignore
9009 					 * any trailing top priority IRE_CACHE
9010 					 * in the further loops. This ensures
9011 					 * that we do not omit any resolver.
9012 					 * IRE_CACHE entries, if any, will be
9013 					 * processed next time we enter
9014 					 * ip_newroute().
9015 					 */
9016 					multirt_flags &= ~MULTIRT_CACHEGW;
9017 					/*
9018 					 * Search for the next unresolved
9019 					 * multirt route.
9020 					 */
9021 					first_mp = copy_mp;
9022 					copy_mp = NULL;
9023 					/* Prepare the next resolution loop. */
9024 					mp = first_mp;
9025 					EXTRACT_PKT_MP(mp, first_mp,
9026 					    mctl_present);
9027 					if (mctl_present)
9028 						io = (ipsec_out_t *)
9029 						    first_mp->b_rptr;
9030 					ipha = (ipha_t *)mp->b_rptr;
9031 
9032 					ASSERT(sire != NULL);
9033 
9034 					dst = save_dst;
9035 					multirt_resolve_next = B_TRUE;
9036 					continue;
9037 				}
9038 
9039 				if (sire != NULL)
9040 					ire_refrele(sire);
9041 
9042 				/*
9043 				 * The response will come back in ip_wput
9044 				 * with db_type IRE_DB_TYPE.
9045 				 */
9046 				ipif_refrele(src_ipif);
9047 				ill_refrele(dst_ill);
9048 				return;
9049 			} else {
9050 				/* Prepare for cleanup */
9051 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
9052 				    mp);
9053 				mp->b_cont = NULL;
9054 				freeb(mp); /* areq */
9055 				/*
9056 				 * this is an ire that is not added to the
9057 				 * cache. ire_freemblk will handle the release
9058 				 * of any resources associated with the ire.
9059 				 */
9060 				ire_delete(ire); /* ire_mp */
9061 				mp = saved_mp; /* pkt */
9062 				ire = NULL;
9063 				if (copy_mp != NULL) {
9064 					MULTIRT_DEBUG_UNTAG(copy_mp);
9065 					freemsg(copy_mp);
9066 					copy_mp = NULL;
9067 				}
9068 				break;
9069 			}
9070 		default:
9071 			break;
9072 		}
9073 	} while (multirt_resolve_next);
9074 
9075 	ip1dbg(("ip_newroute: dropped\n"));
9076 	/* Did this packet originate externally? */
9077 	if (mp->b_prev) {
9078 		mp->b_next = NULL;
9079 		mp->b_prev = NULL;
9080 		if (in_ill != NULL) {
9081 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
9082 		} else {
9083 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9084 		}
9085 	} else {
9086 		if (dst_ill != NULL) {
9087 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
9088 		} else {
9089 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
9090 		}
9091 	}
9092 	ASSERT(copy_mp == NULL);
9093 	MULTIRT_DEBUG_UNTAG(first_mp);
9094 	freemsg(first_mp);
9095 	if (ire != NULL)
9096 		ire_refrele(ire);
9097 	if (sire != NULL)
9098 		ire_refrele(sire);
9099 	if (src_ipif != NULL)
9100 		ipif_refrele(src_ipif);
9101 	if (dst_ill != NULL)
9102 		ill_refrele(dst_ill);
9103 	return;
9104 
9105 icmp_err_ret:
9106 	ip1dbg(("ip_newroute: no route\n"));
9107 	if (src_ipif != NULL)
9108 		ipif_refrele(src_ipif);
9109 	if (dst_ill != NULL)
9110 		ill_refrele(dst_ill);
9111 	if (sire != NULL)
9112 		ire_refrele(sire);
9113 	/* Did this packet originate externally? */
9114 	if (mp->b_prev) {
9115 		mp->b_next = NULL;
9116 		mp->b_prev = NULL;
9117 		if (in_ill != NULL) {
9118 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
9119 		} else {
9120 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9121 		}
9122 		q = WR(q);
9123 	} else {
9124 		/*
9125 		 * There is no outgoing ill, so just increment the
9126 		 * system MIB.
9127 		 */
9128 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9129 		/*
9130 		 * Since ip_wput() isn't close to finished, we fill
9131 		 * in enough of the header for credible error reporting.
9132 		 */
9133 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9134 			/* Failed */
9135 			MULTIRT_DEBUG_UNTAG(first_mp);
9136 			freemsg(first_mp);
9137 			if (ire != NULL)
9138 				ire_refrele(ire);
9139 			return;
9140 		}
9141 	}
9142 
9143 	/*
9144 	 * At this point we will have ire only if RTF_BLACKHOLE
9145 	 * or RTF_REJECT flags are set on the IRE. It will not
9146 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9147 	 */
9148 	if (ire != NULL) {
9149 		if (ire->ire_flags & RTF_BLACKHOLE) {
9150 			ire_refrele(ire);
9151 			MULTIRT_DEBUG_UNTAG(first_mp);
9152 			freemsg(first_mp);
9153 			return;
9154 		}
9155 		ire_refrele(ire);
9156 	}
9157 	if (ip_source_routed(ipha, ipst)) {
9158 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9159 		    zoneid, ipst);
9160 		return;
9161 	}
9162 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9163 }
9164 
9165 ip_opt_info_t zero_info;
9166 
9167 /*
9168  * IPv4 -
9169  * ip_newroute_ipif is called by ip_wput_multicast and
9170  * ip_rput_forward_multicast whenever we need to send
9171  * out a packet to a destination address for which we do not have specific
9172  * routing information. It is used when the packet will be sent out
9173  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9174  * socket option is set or icmp error message wants to go out on a particular
9175  * interface for a unicast packet.
9176  *
9177  * In most cases, the destination address is resolved thanks to the ipif
9178  * intrinsic resolver. However, there are some cases where the call to
9179  * ip_newroute_ipif must take into account the potential presence of
9180  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9181  * that uses the interface. This is specified through flags,
9182  * which can be a combination of:
9183  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9184  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9185  *   and flags. Additionally, the packet source address has to be set to
9186  *   the specified address. The caller is thus expected to set this flag
9187  *   if the packet has no specific source address yet.
9188  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9189  *   flag, the resulting ire will inherit the flag. All unresolved routes
9190  *   to the destination must be explored in the same call to
9191  *   ip_newroute_ipif().
9192  */
9193 static void
9194 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9195     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9196 {
9197 	areq_t	*areq;
9198 	ire_t	*ire = NULL;
9199 	mblk_t	*res_mp;
9200 	ipaddr_t *addrp;
9201 	mblk_t *first_mp;
9202 	ire_t	*save_ire = NULL;
9203 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9204 	ipif_t	*src_ipif = NULL;
9205 	ushort_t ire_marks = 0;
9206 	ill_t	*dst_ill = NULL;
9207 	boolean_t mctl_present;
9208 	ipsec_out_t *io;
9209 	ipha_t *ipha;
9210 	int	ihandle = 0;
9211 	mblk_t	*saved_mp;
9212 	ire_t   *fire = NULL;
9213 	mblk_t  *copy_mp = NULL;
9214 	boolean_t multirt_resolve_next;
9215 	ipaddr_t ipha_dst;
9216 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9217 
9218 	/*
9219 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9220 	 * here for uniformity
9221 	 */
9222 	ipif_refhold(ipif);
9223 
9224 	/*
9225 	 * This loop is run only once in most cases.
9226 	 * We loop to resolve further routes only when the destination
9227 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9228 	 */
9229 	do {
9230 		if (dst_ill != NULL) {
9231 			ill_refrele(dst_ill);
9232 			dst_ill = NULL;
9233 		}
9234 		if (src_ipif != NULL) {
9235 			ipif_refrele(src_ipif);
9236 			src_ipif = NULL;
9237 		}
9238 		multirt_resolve_next = B_FALSE;
9239 
9240 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9241 		    ipif->ipif_ill->ill_name));
9242 
9243 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9244 		if (mctl_present)
9245 			io = (ipsec_out_t *)first_mp->b_rptr;
9246 
9247 		ipha = (ipha_t *)mp->b_rptr;
9248 
9249 		/*
9250 		 * Save the packet destination address, we may need it after
9251 		 * the packet has been consumed.
9252 		 */
9253 		ipha_dst = ipha->ipha_dst;
9254 
9255 		/*
9256 		 * If the interface is a pt-pt interface we look for an
9257 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9258 		 * local_address and the pt-pt destination address. Otherwise
9259 		 * we just match the local address.
9260 		 * NOTE: dst could be different than ipha->ipha_dst in case
9261 		 * of sending igmp multicast packets over a point-to-point
9262 		 * connection.
9263 		 * Thus we must be careful enough to check ipha_dst to be a
9264 		 * multicast address, otherwise it will take xmit_if path for
9265 		 * multicast packets resulting into kernel stack overflow by
9266 		 * repeated calls to ip_newroute_ipif from ire_send().
9267 		 */
9268 		if (CLASSD(ipha_dst) &&
9269 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9270 			goto err_ret;
9271 		}
9272 
9273 		/*
9274 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9275 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9276 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9277 		 * propagate its flags to the new ire.
9278 		 */
9279 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9280 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9281 			ip2dbg(("ip_newroute_ipif: "
9282 			    "ipif_lookup_multi_ire("
9283 			    "ipif %p, dst %08x) = fire %p\n",
9284 			    (void *)ipif, ntohl(dst), (void *)fire));
9285 		}
9286 
9287 		if (mctl_present && io->ipsec_out_attach_if) {
9288 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9289 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9290 
9291 			/* Failure case frees things for us. */
9292 			if (attach_ill == NULL) {
9293 				ipif_refrele(ipif);
9294 				if (fire != NULL)
9295 					ire_refrele(fire);
9296 				return;
9297 			}
9298 
9299 			/*
9300 			 * Check if we need an ire that will not be
9301 			 * looked up by anybody else i.e. HIDDEN.
9302 			 */
9303 			if (ill_is_probeonly(attach_ill)) {
9304 				ire_marks = IRE_MARK_HIDDEN;
9305 			}
9306 			/*
9307 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9308 			 * case.
9309 			 */
9310 			dst_ill = ipif->ipif_ill;
9311 			/* attach_ill has been refheld by ip_grab_attach_ill */
9312 			ASSERT(dst_ill == attach_ill);
9313 		} else {
9314 			/*
9315 			 * If this is set by IP_XMIT_IF, then make sure that
9316 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9317 			 * specified ill.
9318 			 */
9319 			ASSERT((connp == NULL) ||
9320 			    (connp->conn_xmit_if_ill == NULL) ||
9321 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9322 			/*
9323 			 * If the interface belongs to an interface group,
9324 			 * make sure the next possible interface in the group
9325 			 * is used.  This encourages load spreading among
9326 			 * peers in an interface group.
9327 			 * Note: load spreading is disabled for RTF_MULTIRT
9328 			 * routes.
9329 			 */
9330 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9331 			    (fire->ire_flags & RTF_MULTIRT)) {
9332 				/*
9333 				 * Don't perform outbound load spreading
9334 				 * in the case of an RTF_MULTIRT issued route,
9335 				 * we actually typically want to replicate
9336 				 * outgoing packets through particular
9337 				 * interfaces.
9338 				 */
9339 				dst_ill = ipif->ipif_ill;
9340 				ill_refhold(dst_ill);
9341 			} else {
9342 				dst_ill = ip_newroute_get_dst_ill(
9343 				    ipif->ipif_ill);
9344 			}
9345 			if (dst_ill == NULL) {
9346 				if (ip_debug > 2) {
9347 					pr_addr_dbg("ip_newroute_ipif: "
9348 					    "no dst ill for dst %s\n",
9349 					    AF_INET, &dst);
9350 				}
9351 				goto err_ret;
9352 			}
9353 		}
9354 
9355 		/*
9356 		 * Pick a source address preferring non-deprecated ones.
9357 		 * Unlike ip_newroute, we don't do any source address
9358 		 * selection here since for multicast it really does not help
9359 		 * in inbound load spreading as in the unicast case.
9360 		 */
9361 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9362 		    (fire->ire_flags & RTF_SETSRC)) {
9363 			/*
9364 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9365 			 * on that interface. This ire has RTF_SETSRC flag, so
9366 			 * the source address of the packet must be changed.
9367 			 * Check that the ipif matching the requested source
9368 			 * address still exists.
9369 			 */
9370 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9371 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9372 		}
9373 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9374 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9375 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9376 		    (src_ipif == NULL)) {
9377 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9378 			if (src_ipif == NULL) {
9379 				if (ip_debug > 2) {
9380 					/* ip1dbg */
9381 					pr_addr_dbg("ip_newroute_ipif: "
9382 					    "no src for dst %s",
9383 					    AF_INET, &dst);
9384 				}
9385 				ip1dbg((" through interface %s\n",
9386 				    dst_ill->ill_name));
9387 				goto err_ret;
9388 			}
9389 			ipif_refrele(ipif);
9390 			ipif = src_ipif;
9391 			ipif_refhold(ipif);
9392 		}
9393 		if (src_ipif == NULL) {
9394 			src_ipif = ipif;
9395 			ipif_refhold(src_ipif);
9396 		}
9397 
9398 		/*
9399 		 * Assign a source address while we have the conn.
9400 		 * We can't have ip_wput_ire pick a source address when the
9401 		 * packet returns from arp since conn_unspec_src might be set
9402 		 * and we loose the conn when going through arp.
9403 		 */
9404 		if (ipha->ipha_src == INADDR_ANY &&
9405 		    (connp == NULL || !connp->conn_unspec_src)) {
9406 			ipha->ipha_src = src_ipif->ipif_src_addr;
9407 		}
9408 
9409 		/*
9410 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9411 		 * interface does not have an interface ire.
9412 		 * Example: Thousands of mobileip PPP interfaces to mobile
9413 		 * nodes. We don't want to create interface ires because
9414 		 * packets from other mobile nodes must not take the route
9415 		 * via interface ires to the visiting mobile node without
9416 		 * going through the home agent, in absence of mobileip
9417 		 * route optimization.
9418 		 */
9419 		if (CLASSD(ipha_dst) && (connp == NULL ||
9420 		    connp->conn_xmit_if_ill == NULL) &&
9421 		    infop->ip_opt_ill_index == 0) {
9422 			/* ipif_to_ire returns an held ire */
9423 			ire = ipif_to_ire(ipif);
9424 			if (ire == NULL)
9425 				goto err_ret;
9426 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9427 				goto err_ret;
9428 			/*
9429 			 * ihandle is needed when the ire is added to
9430 			 * cache table.
9431 			 */
9432 			save_ire = ire;
9433 			ihandle = save_ire->ire_ihandle;
9434 
9435 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9436 			    "flags %04x\n",
9437 			    (void *)ire, (void *)ipif, flags));
9438 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9439 			    (fire->ire_flags & RTF_MULTIRT)) {
9440 				/*
9441 				 * As requested by flags, an IRE_OFFSUBNET was
9442 				 * looked up on that interface. This ire has
9443 				 * RTF_MULTIRT flag, so the resolution loop will
9444 				 * be re-entered to resolve additional routes on
9445 				 * other interfaces. For that purpose, a copy of
9446 				 * the packet is performed at this point.
9447 				 */
9448 				fire->ire_last_used_time = lbolt;
9449 				copy_mp = copymsg(first_mp);
9450 				if (copy_mp) {
9451 					MULTIRT_DEBUG_TAG(copy_mp);
9452 				}
9453 			}
9454 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9455 			    (fire->ire_flags & RTF_SETSRC)) {
9456 				/*
9457 				 * As requested by flags, an IRE_OFFSUBET was
9458 				 * looked up on that interface. This ire has
9459 				 * RTF_SETSRC flag, so the source address of the
9460 				 * packet must be changed.
9461 				 */
9462 				ipha->ipha_src = fire->ire_src_addr;
9463 			}
9464 		} else {
9465 			ASSERT((connp == NULL) ||
9466 			    (connp->conn_xmit_if_ill != NULL) ||
9467 			    (connp->conn_dontroute) ||
9468 			    infop->ip_opt_ill_index != 0);
9469 			/*
9470 			 * The only ways we can come here are:
9471 			 * 1) IP_XMIT_IF socket option is set
9472 			 * 2) ICMP error message generated from
9473 			 *    ip_mrtun_forward() routine and it needs
9474 			 *    to go through the specified ill.
9475 			 * 3) SO_DONTROUTE socket option is set
9476 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9477 			 * In all cases, the new ire will not be added
9478 			 * into cache table.
9479 			 */
9480 			ire_marks |= IRE_MARK_NOADD;
9481 		}
9482 
9483 		switch (ipif->ipif_net_type) {
9484 		case IRE_IF_NORESOLVER: {
9485 			/* We have what we need to build an IRE_CACHE. */
9486 
9487 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9488 			    (dst_ill->ill_resolver_mp == NULL)) {
9489 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9490 				    "for IRE_IF_NORESOLVER ire %p has "
9491 				    "no ill_resolver_mp\n",
9492 				    (void *)dst_ill, (void *)ire));
9493 				break;
9494 			}
9495 
9496 			/*
9497 			 * The new ire inherits the IRE_OFFSUBNET flags
9498 			 * and source address, if this was requested.
9499 			 */
9500 			ire = ire_create(
9501 			    (uchar_t *)&dst,		/* dest address */
9502 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9503 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9504 			    NULL,			/* gateway address */
9505 			    NULL,
9506 			    &ipif->ipif_mtu,
9507 			    NULL,			/* no src nce */
9508 			    dst_ill->ill_rq,		/* recv-from queue */
9509 			    dst_ill->ill_wq,		/* send-to queue */
9510 			    IRE_CACHE,
9511 			    src_ipif,
9512 			    NULL,
9513 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9514 			    (fire != NULL) ?		/* Parent handle */
9515 			    fire->ire_phandle : 0,
9516 			    ihandle,			/* Interface handle */
9517 			    (fire != NULL) ?
9518 			    (fire->ire_flags &
9519 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9520 			    (save_ire == NULL ? &ire_uinfo_null :
9521 			    &save_ire->ire_uinfo),
9522 			    NULL,
9523 			    NULL,
9524 			    ipst);
9525 
9526 			if (ire == NULL) {
9527 				if (save_ire != NULL)
9528 					ire_refrele(save_ire);
9529 				break;
9530 			}
9531 
9532 			ire->ire_marks |= ire_marks;
9533 
9534 			/*
9535 			 * If IRE_MARK_NOADD is set then we need to convert
9536 			 * the max_fragp to a useable value now. This is
9537 			 * normally done in ire_add_v[46]. We also need to
9538 			 * associate the ire with an nce (normally would be
9539 			 * done in ip_wput_nondata()).
9540 			 *
9541 			 * Note that IRE_MARK_NOADD packets created here
9542 			 * do not have a non-null ire_mp pointer. The null
9543 			 * value of ire_bucket indicates that they were
9544 			 * never added.
9545 			 */
9546 			if (ire->ire_marks & IRE_MARK_NOADD) {
9547 				uint_t  max_frag;
9548 
9549 				max_frag = *ire->ire_max_fragp;
9550 				ire->ire_max_fragp = NULL;
9551 				ire->ire_max_frag = max_frag;
9552 
9553 				if ((ire->ire_nce = ndp_lookup_v4(
9554 				    ire_to_ill(ire),
9555 				    (ire->ire_gateway_addr != INADDR_ANY ?
9556 				    &ire->ire_gateway_addr : &ire->ire_addr),
9557 				    B_FALSE)) == NULL) {
9558 					if (save_ire != NULL)
9559 						ire_refrele(save_ire);
9560 					break;
9561 				}
9562 				ASSERT(ire->ire_nce->nce_state ==
9563 				    ND_REACHABLE);
9564 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9565 			}
9566 
9567 			/* Prevent save_ire from getting deleted */
9568 			if (save_ire != NULL) {
9569 				IRB_REFHOLD(save_ire->ire_bucket);
9570 				/* Has it been removed already ? */
9571 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9572 					IRB_REFRELE(save_ire->ire_bucket);
9573 					ire_refrele(save_ire);
9574 					break;
9575 				}
9576 			}
9577 
9578 			ire_add_then_send(q, ire, first_mp);
9579 
9580 			/* Assert that save_ire is not deleted yet. */
9581 			if (save_ire != NULL) {
9582 				ASSERT(save_ire->ire_ptpn != NULL);
9583 				IRB_REFRELE(save_ire->ire_bucket);
9584 				ire_refrele(save_ire);
9585 				save_ire = NULL;
9586 			}
9587 			if (fire != NULL) {
9588 				ire_refrele(fire);
9589 				fire = NULL;
9590 			}
9591 
9592 			/*
9593 			 * the resolution loop is re-entered if this
9594 			 * was requested through flags and if we
9595 			 * actually are in a multirouting case.
9596 			 */
9597 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9598 				boolean_t need_resolve =
9599 				    ire_multirt_need_resolve(ipha_dst,
9600 				    MBLK_GETLABEL(copy_mp), ipst);
9601 				if (!need_resolve) {
9602 					MULTIRT_DEBUG_UNTAG(copy_mp);
9603 					freemsg(copy_mp);
9604 					copy_mp = NULL;
9605 				} else {
9606 					/*
9607 					 * ipif_lookup_group() calls
9608 					 * ire_lookup_multi() that uses
9609 					 * ire_ftable_lookup() to find
9610 					 * an IRE_INTERFACE for the group.
9611 					 * In the multirt case,
9612 					 * ire_lookup_multi() then invokes
9613 					 * ire_multirt_lookup() to find
9614 					 * the next resolvable ire.
9615 					 * As a result, we obtain an new
9616 					 * interface, derived from the
9617 					 * next ire.
9618 					 */
9619 					ipif_refrele(ipif);
9620 					ipif = ipif_lookup_group(ipha_dst,
9621 					    zoneid, ipst);
9622 					ip2dbg(("ip_newroute_ipif: "
9623 					    "multirt dst %08x, ipif %p\n",
9624 					    htonl(dst), (void *)ipif));
9625 					if (ipif != NULL) {
9626 						mp = copy_mp;
9627 						copy_mp = NULL;
9628 						multirt_resolve_next = B_TRUE;
9629 						continue;
9630 					} else {
9631 						freemsg(copy_mp);
9632 					}
9633 				}
9634 			}
9635 			if (ipif != NULL)
9636 				ipif_refrele(ipif);
9637 			ill_refrele(dst_ill);
9638 			ipif_refrele(src_ipif);
9639 			return;
9640 		}
9641 		case IRE_IF_RESOLVER:
9642 			/*
9643 			 * We can't build an IRE_CACHE yet, but at least
9644 			 * we found a resolver that can help.
9645 			 */
9646 			res_mp = dst_ill->ill_resolver_mp;
9647 			if (!OK_RESOLVER_MP(res_mp))
9648 				break;
9649 
9650 			/*
9651 			 * We obtain a partial IRE_CACHE which we will pass
9652 			 * along with the resolver query.  When the response
9653 			 * comes back it will be there ready for us to add.
9654 			 * The new ire inherits the IRE_OFFSUBNET flags
9655 			 * and source address, if this was requested.
9656 			 * The ire_max_frag is atomically set under the
9657 			 * irebucket lock in ire_add_v[46]. Only in the
9658 			 * case of IRE_MARK_NOADD, we set it here itself.
9659 			 */
9660 			ire = ire_create_mp(
9661 			    (uchar_t *)&dst,		/* dest address */
9662 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9663 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9664 			    NULL,			/* gateway address */
9665 			    NULL,			/* no in_src_addr */
9666 			    (ire_marks & IRE_MARK_NOADD) ?
9667 			    ipif->ipif_mtu : 0,		/* max_frag */
9668 			    NULL,			/* no src nce */
9669 			    dst_ill->ill_rq,		/* recv-from queue */
9670 			    dst_ill->ill_wq,		/* send-to queue */
9671 			    IRE_CACHE,
9672 			    src_ipif,
9673 			    NULL,
9674 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9675 			    (fire != NULL) ?		/* Parent handle */
9676 			    fire->ire_phandle : 0,
9677 			    ihandle,			/* Interface handle */
9678 			    (fire != NULL) ?		/* flags if any */
9679 			    (fire->ire_flags &
9680 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9681 			    (save_ire == NULL ? &ire_uinfo_null :
9682 			    &save_ire->ire_uinfo),
9683 			    NULL,
9684 			    NULL,
9685 			    ipst);
9686 
9687 			if (save_ire != NULL) {
9688 				ire_refrele(save_ire);
9689 				save_ire = NULL;
9690 			}
9691 			if (ire == NULL)
9692 				break;
9693 
9694 			ire->ire_marks |= ire_marks;
9695 			/*
9696 			 * Construct message chain for the resolver of the
9697 			 * form:
9698 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9699 			 *
9700 			 * NOTE : ire will be added later when the response
9701 			 * comes back from ARP. If the response does not
9702 			 * come back, ARP frees the packet. For this reason,
9703 			 * we can't REFHOLD the bucket of save_ire to prevent
9704 			 * deletions. We may not be able to REFRELE the
9705 			 * bucket if the response never comes back.
9706 			 * Thus, before adding the ire, ire_add_v4 will make
9707 			 * sure that the interface route does not get deleted.
9708 			 * This is the only case unlike ip_newroute_v6,
9709 			 * ip_newroute_ipif_v6 where we can always prevent
9710 			 * deletions because ire_add_then_send is called after
9711 			 * creating the IRE.
9712 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9713 			 * does not add this IRE into the IRE CACHE.
9714 			 */
9715 			ASSERT(ire->ire_mp != NULL);
9716 			ire->ire_mp->b_cont = first_mp;
9717 			/* Have saved_mp handy, for cleanup if canput fails */
9718 			saved_mp = mp;
9719 			mp = copyb(res_mp);
9720 			if (mp == NULL) {
9721 				/* Prepare for cleanup */
9722 				mp = saved_mp; /* pkt */
9723 				ire_delete(ire); /* ire_mp */
9724 				ire = NULL;
9725 				if (copy_mp != NULL) {
9726 					MULTIRT_DEBUG_UNTAG(copy_mp);
9727 					freemsg(copy_mp);
9728 					copy_mp = NULL;
9729 				}
9730 				break;
9731 			}
9732 			linkb(mp, ire->ire_mp);
9733 
9734 			/*
9735 			 * Fill in the source and dest addrs for the resolver.
9736 			 * NOTE: this depends on memory layouts imposed by
9737 			 * ill_init().
9738 			 */
9739 			areq = (areq_t *)mp->b_rptr;
9740 			addrp = (ipaddr_t *)((char *)areq +
9741 			    areq->areq_sender_addr_offset);
9742 			*addrp = ire->ire_src_addr;
9743 			addrp = (ipaddr_t *)((char *)areq +
9744 			    areq->areq_target_addr_offset);
9745 			*addrp = dst;
9746 			/* Up to the resolver. */
9747 			if (canputnext(dst_ill->ill_rq) &&
9748 			    !(dst_ill->ill_arp_closing)) {
9749 				putnext(dst_ill->ill_rq, mp);
9750 				/*
9751 				 * The response will come back in ip_wput
9752 				 * with db_type IRE_DB_TYPE.
9753 				 */
9754 			} else {
9755 				mp->b_cont = NULL;
9756 				freeb(mp); /* areq */
9757 				ire_delete(ire); /* ire_mp */
9758 				saved_mp->b_next = NULL;
9759 				saved_mp->b_prev = NULL;
9760 				freemsg(first_mp); /* pkt */
9761 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9762 			}
9763 
9764 			if (fire != NULL) {
9765 				ire_refrele(fire);
9766 				fire = NULL;
9767 			}
9768 
9769 
9770 			/*
9771 			 * The resolution loop is re-entered if this was
9772 			 * requested through flags and we actually are
9773 			 * in a multirouting case.
9774 			 */
9775 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9776 				boolean_t need_resolve =
9777 				    ire_multirt_need_resolve(ipha_dst,
9778 				    MBLK_GETLABEL(copy_mp), ipst);
9779 				if (!need_resolve) {
9780 					MULTIRT_DEBUG_UNTAG(copy_mp);
9781 					freemsg(copy_mp);
9782 					copy_mp = NULL;
9783 				} else {
9784 					/*
9785 					 * ipif_lookup_group() calls
9786 					 * ire_lookup_multi() that uses
9787 					 * ire_ftable_lookup() to find
9788 					 * an IRE_INTERFACE for the group.
9789 					 * In the multirt case,
9790 					 * ire_lookup_multi() then invokes
9791 					 * ire_multirt_lookup() to find
9792 					 * the next resolvable ire.
9793 					 * As a result, we obtain an new
9794 					 * interface, derived from the
9795 					 * next ire.
9796 					 */
9797 					ipif_refrele(ipif);
9798 					ipif = ipif_lookup_group(ipha_dst,
9799 					    zoneid, ipst);
9800 					if (ipif != NULL) {
9801 						mp = copy_mp;
9802 						copy_mp = NULL;
9803 						multirt_resolve_next = B_TRUE;
9804 						continue;
9805 					} else {
9806 						freemsg(copy_mp);
9807 					}
9808 				}
9809 			}
9810 			if (ipif != NULL)
9811 				ipif_refrele(ipif);
9812 			ill_refrele(dst_ill);
9813 			ipif_refrele(src_ipif);
9814 			return;
9815 		default:
9816 			break;
9817 		}
9818 	} while (multirt_resolve_next);
9819 
9820 err_ret:
9821 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9822 	if (fire != NULL)
9823 		ire_refrele(fire);
9824 	ipif_refrele(ipif);
9825 	/* Did this packet originate externally? */
9826 	if (dst_ill != NULL)
9827 		ill_refrele(dst_ill);
9828 	if (src_ipif != NULL)
9829 		ipif_refrele(src_ipif);
9830 	if (mp->b_prev || mp->b_next) {
9831 		mp->b_next = NULL;
9832 		mp->b_prev = NULL;
9833 	} else {
9834 		/*
9835 		 * Since ip_wput() isn't close to finished, we fill
9836 		 * in enough of the header for credible error reporting.
9837 		 */
9838 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9839 			/* Failed */
9840 			freemsg(first_mp);
9841 			if (ire != NULL)
9842 				ire_refrele(ire);
9843 			return;
9844 		}
9845 	}
9846 	/*
9847 	 * At this point we will have ire only if RTF_BLACKHOLE
9848 	 * or RTF_REJECT flags are set on the IRE. It will not
9849 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9850 	 */
9851 	if (ire != NULL) {
9852 		if (ire->ire_flags & RTF_BLACKHOLE) {
9853 			ire_refrele(ire);
9854 			freemsg(first_mp);
9855 			return;
9856 		}
9857 		ire_refrele(ire);
9858 	}
9859 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9860 }
9861 
9862 /* Name/Value Table Lookup Routine */
9863 char *
9864 ip_nv_lookup(nv_t *nv, int value)
9865 {
9866 	if (!nv)
9867 		return (NULL);
9868 	for (; nv->nv_name; nv++) {
9869 		if (nv->nv_value == value)
9870 			return (nv->nv_name);
9871 	}
9872 	return ("unknown");
9873 }
9874 
9875 /*
9876  * This is a module open, i.e. this is a control stream for access
9877  * to a DLPI device.  We allocate an ill_t as the instance data in
9878  * this case.
9879  */
9880 int
9881 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9882 {
9883 	ill_t	*ill;
9884 	int	err;
9885 	zoneid_t zoneid;
9886 	netstack_t *ns;
9887 	ip_stack_t *ipst;
9888 
9889 	/*
9890 	 * Prevent unprivileged processes from pushing IP so that
9891 	 * they can't send raw IP.
9892 	 */
9893 	if (secpolicy_net_rawaccess(credp) != 0)
9894 		return (EPERM);
9895 
9896 	ns = netstack_find_by_cred(credp);
9897 	ASSERT(ns != NULL);
9898 	ipst = ns->netstack_ip;
9899 	ASSERT(ipst != NULL);
9900 
9901 	/*
9902 	 * For exclusive stacks we set the zoneid to zero
9903 	 * to make IP operate as if in the global zone.
9904 	 */
9905 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9906 		zoneid = GLOBAL_ZONEID;
9907 	else
9908 		zoneid = crgetzoneid(credp);
9909 
9910 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9911 	q->q_ptr = WR(q)->q_ptr = ill;
9912 	ill->ill_ipst = ipst;
9913 	ill->ill_zoneid = zoneid;
9914 
9915 	/*
9916 	 * ill_init initializes the ill fields and then sends down
9917 	 * down a DL_INFO_REQ after calling qprocson.
9918 	 */
9919 	err = ill_init(q, ill);
9920 	if (err != 0) {
9921 		mi_free(ill);
9922 		netstack_rele(ipst->ips_netstack);
9923 		q->q_ptr = NULL;
9924 		WR(q)->q_ptr = NULL;
9925 		return (err);
9926 	}
9927 
9928 	/* ill_init initializes the ipsq marking this thread as writer */
9929 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9930 	/* Wait for the DL_INFO_ACK */
9931 	mutex_enter(&ill->ill_lock);
9932 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9933 		/*
9934 		 * Return value of 0 indicates a pending signal.
9935 		 */
9936 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9937 		if (err == 0) {
9938 			mutex_exit(&ill->ill_lock);
9939 			(void) ip_close(q, 0);
9940 			return (EINTR);
9941 		}
9942 	}
9943 	mutex_exit(&ill->ill_lock);
9944 
9945 	/*
9946 	 * ip_rput_other could have set an error  in ill_error on
9947 	 * receipt of M_ERROR.
9948 	 */
9949 
9950 	err = ill->ill_error;
9951 	if (err != 0) {
9952 		(void) ip_close(q, 0);
9953 		return (err);
9954 	}
9955 
9956 	ill->ill_credp = credp;
9957 	crhold(credp);
9958 
9959 	mutex_enter(&ipst->ips_ip_mi_lock);
9960 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9961 	    credp);
9962 	mutex_exit(&ipst->ips_ip_mi_lock);
9963 	if (err) {
9964 		(void) ip_close(q, 0);
9965 		return (err);
9966 	}
9967 	return (0);
9968 }
9969 
9970 /* IP open routine. */
9971 int
9972 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9973 {
9974 	conn_t 		*connp;
9975 	major_t		maj;
9976 	zoneid_t	zoneid;
9977 	netstack_t	*ns;
9978 	ip_stack_t	*ipst;
9979 
9980 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9981 
9982 	/* Allow reopen. */
9983 	if (q->q_ptr != NULL)
9984 		return (0);
9985 
9986 	if (sflag & MODOPEN) {
9987 		/* This is a module open */
9988 		return (ip_modopen(q, devp, flag, sflag, credp));
9989 	}
9990 
9991 	ns = netstack_find_by_cred(credp);
9992 	ASSERT(ns != NULL);
9993 	ipst = ns->netstack_ip;
9994 	ASSERT(ipst != NULL);
9995 
9996 	/*
9997 	 * For exclusive stacks we set the zoneid to zero
9998 	 * to make IP operate as if in the global zone.
9999 	 */
10000 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
10001 		zoneid = GLOBAL_ZONEID;
10002 	else
10003 		zoneid = crgetzoneid(credp);
10004 
10005 	/*
10006 	 * We are opening as a device. This is an IP client stream, and we
10007 	 * allocate an conn_t as the instance data.
10008 	 */
10009 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
10010 
10011 	/*
10012 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
10013 	 * done by netstack_find_by_cred()
10014 	 */
10015 	netstack_rele(ipst->ips_netstack);
10016 
10017 	connp->conn_zoneid = zoneid;
10018 
10019 	connp->conn_upq = q;
10020 	q->q_ptr = WR(q)->q_ptr = connp;
10021 
10022 	if (flag & SO_SOCKSTR)
10023 		connp->conn_flags |= IPCL_SOCKET;
10024 
10025 	/* Minor tells us which /dev entry was opened */
10026 	if (geteminor(*devp) == IPV6_MINOR) {
10027 		connp->conn_flags |= IPCL_ISV6;
10028 		connp->conn_af_isv6 = B_TRUE;
10029 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
10030 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
10031 	} else {
10032 		connp->conn_af_isv6 = B_FALSE;
10033 		connp->conn_pkt_isv6 = B_FALSE;
10034 	}
10035 
10036 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
10037 		/* CONN_DEC_REF takes care of netstack_rele() */
10038 		q->q_ptr = WR(q)->q_ptr = NULL;
10039 		CONN_DEC_REF(connp);
10040 		return (EBUSY);
10041 	}
10042 
10043 	maj = getemajor(*devp);
10044 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
10045 
10046 	/*
10047 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
10048 	 */
10049 	connp->conn_cred = credp;
10050 	crhold(connp->conn_cred);
10051 
10052 	/*
10053 	 * If the caller has the process-wide flag set, then default to MAC
10054 	 * exempt mode.  This allows read-down to unlabeled hosts.
10055 	 */
10056 	if (getpflags(NET_MAC_AWARE, credp) != 0)
10057 		connp->conn_mac_exempt = B_TRUE;
10058 
10059 	/*
10060 	 * This should only happen for ndd, netstat, raw socket or other SCTP
10061 	 * administrative ops.  In these cases, we just need a normal conn_t
10062 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
10063 	 * an error will be returned.
10064 	 */
10065 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
10066 		connp->conn_rq = q;
10067 		connp->conn_wq = WR(q);
10068 	} else {
10069 		connp->conn_ulp = IPPROTO_SCTP;
10070 		connp->conn_rq = connp->conn_wq = NULL;
10071 	}
10072 	/* Non-zero default values */
10073 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
10074 
10075 	/*
10076 	 * Make the conn globally visible to walkers
10077 	 */
10078 	mutex_enter(&connp->conn_lock);
10079 	connp->conn_state_flags &= ~CONN_INCIPIENT;
10080 	mutex_exit(&connp->conn_lock);
10081 	ASSERT(connp->conn_ref == 1);
10082 
10083 	qprocson(q);
10084 
10085 	return (0);
10086 }
10087 
10088 /*
10089  * Change q_qinfo based on the value of isv6.
10090  * This can not called on an ill queue.
10091  * Note that there is no race since either q_qinfo works for conn queues - it
10092  * is just an optimization to enter the best wput routine directly.
10093  */
10094 void
10095 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
10096 {
10097 	ASSERT(q->q_flag & QREADR);
10098 	ASSERT(WR(q)->q_next == NULL);
10099 	ASSERT(q->q_ptr != NULL);
10100 
10101 	if (minor == IPV6_MINOR)  {
10102 		if (bump_mib) {
10103 			BUMP_MIB(&ipst->ips_ip6_mib,
10104 			    ipIfStatsOutSwitchIPVersion);
10105 		}
10106 		q->q_qinfo = &rinit_ipv6;
10107 		WR(q)->q_qinfo = &winit_ipv6;
10108 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
10109 	} else {
10110 		if (bump_mib) {
10111 			BUMP_MIB(&ipst->ips_ip_mib,
10112 			    ipIfStatsOutSwitchIPVersion);
10113 		}
10114 		q->q_qinfo = &iprinit;
10115 		WR(q)->q_qinfo = &ipwinit;
10116 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
10117 	}
10118 
10119 }
10120 
10121 /*
10122  * See if IPsec needs loading because of the options in mp.
10123  */
10124 static boolean_t
10125 ipsec_opt_present(mblk_t *mp)
10126 {
10127 	uint8_t *optcp, *next_optcp, *opt_endcp;
10128 	struct opthdr *opt;
10129 	struct T_opthdr *topt;
10130 	int opthdr_len;
10131 	t_uscalar_t optname, optlevel;
10132 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10133 	ipsec_req_t *ipsr;
10134 
10135 	/*
10136 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10137 	 * return TRUE.
10138 	 */
10139 
10140 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10141 	opt_endcp = optcp + tor->OPT_length;
10142 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10143 		opthdr_len = sizeof (struct T_opthdr);
10144 	} else {		/* O_OPTMGMT_REQ */
10145 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10146 		opthdr_len = sizeof (struct opthdr);
10147 	}
10148 	for (; optcp < opt_endcp; optcp = next_optcp) {
10149 		if (optcp + opthdr_len > opt_endcp)
10150 			return (B_FALSE);	/* Not enough option header. */
10151 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10152 			topt = (struct T_opthdr *)optcp;
10153 			optlevel = topt->level;
10154 			optname = topt->name;
10155 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10156 		} else {
10157 			opt = (struct opthdr *)optcp;
10158 			optlevel = opt->level;
10159 			optname = opt->name;
10160 			next_optcp = optcp + opthdr_len +
10161 			    _TPI_ALIGN_OPT(opt->len);
10162 		}
10163 		if ((next_optcp < optcp) || /* wraparound pointer space */
10164 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10165 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10166 			return (B_FALSE); /* bad option buffer */
10167 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10168 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10169 			/*
10170 			 * Check to see if it's an all-bypass or all-zeroes
10171 			 * IPsec request.  Don't bother loading IPsec if
10172 			 * the socket doesn't want to use it.  (A good example
10173 			 * is a bypass request.)
10174 			 *
10175 			 * Basically, if any of the non-NEVER bits are set,
10176 			 * load IPsec.
10177 			 */
10178 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10179 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10180 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10181 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10182 			    != 0)
10183 				return (B_TRUE);
10184 		}
10185 	}
10186 	return (B_FALSE);
10187 }
10188 
10189 /*
10190  * If conn is is waiting for ipsec to finish loading, kick it.
10191  */
10192 /* ARGSUSED */
10193 static void
10194 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10195 {
10196 	t_scalar_t	optreq_prim;
10197 	mblk_t		*mp;
10198 	cred_t		*cr;
10199 	int		err = 0;
10200 
10201 	/*
10202 	 * This function is called, after ipsec loading is complete.
10203 	 * Since IP checks exclusively and atomically (i.e it prevents
10204 	 * ipsec load from completing until ip_optcom_req completes)
10205 	 * whether ipsec load is complete, there cannot be a race with IP
10206 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10207 	 */
10208 	mutex_enter(&connp->conn_lock);
10209 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10210 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10211 		mp = connp->conn_ipsec_opt_mp;
10212 		connp->conn_ipsec_opt_mp = NULL;
10213 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10214 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10215 		mutex_exit(&connp->conn_lock);
10216 
10217 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10218 
10219 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10220 		if (optreq_prim == T_OPTMGMT_REQ) {
10221 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10222 			    &ip_opt_obj);
10223 		} else {
10224 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10225 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10226 			    &ip_opt_obj);
10227 		}
10228 		if (err != EINPROGRESS)
10229 			CONN_OPER_PENDING_DONE(connp);
10230 		return;
10231 	}
10232 	mutex_exit(&connp->conn_lock);
10233 }
10234 
10235 /*
10236  * Called from the ipsec_loader thread, outside any perimeter, to tell
10237  * ip qenable any of the queues waiting for the ipsec loader to
10238  * complete.
10239  */
10240 void
10241 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10242 {
10243 	netstack_t *ns = ipss->ipsec_netstack;
10244 
10245 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10246 }
10247 
10248 /*
10249  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10250  * determines the grp on which it has to become exclusive, queues the mp
10251  * and sq draining restarts the optmgmt
10252  */
10253 static boolean_t
10254 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10255 {
10256 	conn_t *connp = Q_TO_CONN(q);
10257 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10258 
10259 	/*
10260 	 * Take IPsec requests and treat them special.
10261 	 */
10262 	if (ipsec_opt_present(mp)) {
10263 		/* First check if IPsec is loaded. */
10264 		mutex_enter(&ipss->ipsec_loader_lock);
10265 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10266 			mutex_exit(&ipss->ipsec_loader_lock);
10267 			return (B_FALSE);
10268 		}
10269 		mutex_enter(&connp->conn_lock);
10270 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10271 
10272 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10273 		connp->conn_ipsec_opt_mp = mp;
10274 		mutex_exit(&connp->conn_lock);
10275 		mutex_exit(&ipss->ipsec_loader_lock);
10276 
10277 		ipsec_loader_loadnow(ipss);
10278 		return (B_TRUE);
10279 	}
10280 	return (B_FALSE);
10281 }
10282 
10283 /*
10284  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10285  * all of them are copied to the conn_t. If the req is "zero", the policy is
10286  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10287  * fields.
10288  * We keep only the latest setting of the policy and thus policy setting
10289  * is not incremental/cumulative.
10290  *
10291  * Requests to set policies with multiple alternative actions will
10292  * go through a different API.
10293  */
10294 int
10295 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10296 {
10297 	uint_t ah_req = 0;
10298 	uint_t esp_req = 0;
10299 	uint_t se_req = 0;
10300 	ipsec_selkey_t sel;
10301 	ipsec_act_t *actp = NULL;
10302 	uint_t nact;
10303 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10304 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10305 	ipsec_policy_root_t *pr;
10306 	ipsec_policy_head_t *ph;
10307 	int fam;
10308 	boolean_t is_pol_reset;
10309 	int error = 0;
10310 	netstack_t	*ns = connp->conn_netstack;
10311 	ip_stack_t	*ipst = ns->netstack_ip;
10312 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10313 
10314 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10315 
10316 	/*
10317 	 * The IP_SEC_OPT option does not allow variable length parameters,
10318 	 * hence a request cannot be NULL.
10319 	 */
10320 	if (req == NULL)
10321 		return (EINVAL);
10322 
10323 	ah_req = req->ipsr_ah_req;
10324 	esp_req = req->ipsr_esp_req;
10325 	se_req = req->ipsr_self_encap_req;
10326 
10327 	/*
10328 	 * Are we dealing with a request to reset the policy (i.e.
10329 	 * zero requests).
10330 	 */
10331 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10332 	    (esp_req & REQ_MASK) == 0 &&
10333 	    (se_req & REQ_MASK) == 0);
10334 
10335 	if (!is_pol_reset) {
10336 		/*
10337 		 * If we couldn't load IPsec, fail with "protocol
10338 		 * not supported".
10339 		 * IPsec may not have been loaded for a request with zero
10340 		 * policies, so we don't fail in this case.
10341 		 */
10342 		mutex_enter(&ipss->ipsec_loader_lock);
10343 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10344 			mutex_exit(&ipss->ipsec_loader_lock);
10345 			return (EPROTONOSUPPORT);
10346 		}
10347 		mutex_exit(&ipss->ipsec_loader_lock);
10348 
10349 		/*
10350 		 * Test for valid requests. Invalid algorithms
10351 		 * need to be tested by IPSEC code because new
10352 		 * algorithms can be added dynamically.
10353 		 */
10354 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10355 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10356 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10357 			return (EINVAL);
10358 		}
10359 
10360 		/*
10361 		 * Only privileged users can issue these
10362 		 * requests.
10363 		 */
10364 		if (((ah_req & IPSEC_PREF_NEVER) ||
10365 		    (esp_req & IPSEC_PREF_NEVER) ||
10366 		    (se_req & IPSEC_PREF_NEVER)) &&
10367 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10368 			return (EPERM);
10369 		}
10370 
10371 		/*
10372 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10373 		 * are mutually exclusive.
10374 		 */
10375 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10376 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10377 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10378 			/* Both of them are set */
10379 			return (EINVAL);
10380 		}
10381 	}
10382 
10383 	mutex_enter(&connp->conn_lock);
10384 
10385 	/*
10386 	 * If we have already cached policies in ip_bind_connected*(), don't
10387 	 * let them change now. We cache policies for connections
10388 	 * whose src,dst [addr, port] is known.
10389 	 */
10390 	if (connp->conn_policy_cached) {
10391 		mutex_exit(&connp->conn_lock);
10392 		return (EINVAL);
10393 	}
10394 
10395 	/*
10396 	 * We have a zero policies, reset the connection policy if already
10397 	 * set. This will cause the connection to inherit the
10398 	 * global policy, if any.
10399 	 */
10400 	if (is_pol_reset) {
10401 		if (connp->conn_policy != NULL) {
10402 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10403 			connp->conn_policy = NULL;
10404 		}
10405 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10406 		connp->conn_in_enforce_policy = B_FALSE;
10407 		connp->conn_out_enforce_policy = B_FALSE;
10408 		mutex_exit(&connp->conn_lock);
10409 		return (0);
10410 	}
10411 
10412 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10413 	    ipst->ips_netstack);
10414 	if (ph == NULL)
10415 		goto enomem;
10416 
10417 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10418 	if (actp == NULL)
10419 		goto enomem;
10420 
10421 	/*
10422 	 * Always allocate IPv4 policy entries, since they can also
10423 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10424 	 */
10425 	bzero(&sel, sizeof (sel));
10426 	sel.ipsl_valid = IPSL_IPV4;
10427 
10428 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10429 	    ipst->ips_netstack);
10430 	if (pin4 == NULL)
10431 		goto enomem;
10432 
10433 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10434 	    ipst->ips_netstack);
10435 	if (pout4 == NULL)
10436 		goto enomem;
10437 
10438 	if (connp->conn_pkt_isv6) {
10439 		/*
10440 		 * We're looking at a v6 socket, also allocate the
10441 		 * v6-specific entries...
10442 		 */
10443 		sel.ipsl_valid = IPSL_IPV6;
10444 		pin6 = ipsec_policy_create(&sel, actp, nact,
10445 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10446 		if (pin6 == NULL)
10447 			goto enomem;
10448 
10449 		pout6 = ipsec_policy_create(&sel, actp, nact,
10450 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10451 		if (pout6 == NULL)
10452 			goto enomem;
10453 
10454 		/*
10455 		 * .. and file them away in the right place.
10456 		 */
10457 		fam = IPSEC_AF_V6;
10458 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10459 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10460 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10461 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10462 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10463 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10464 	}
10465 
10466 	ipsec_actvec_free(actp, nact);
10467 
10468 	/*
10469 	 * File the v4 policies.
10470 	 */
10471 	fam = IPSEC_AF_V4;
10472 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10473 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10474 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10475 
10476 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10477 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10478 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10479 
10480 	/*
10481 	 * If the requests need security, set enforce_policy.
10482 	 * If the requests are IPSEC_PREF_NEVER, one should
10483 	 * still set conn_out_enforce_policy so that an ipsec_out
10484 	 * gets attached in ip_wput. This is needed so that
10485 	 * for connections that we don't cache policy in ip_bind,
10486 	 * if global policy matches in ip_wput_attach_policy, we
10487 	 * don't wrongly inherit global policy. Similarly, we need
10488 	 * to set conn_in_enforce_policy also so that we don't verify
10489 	 * policy wrongly.
10490 	 */
10491 	if ((ah_req & REQ_MASK) != 0 ||
10492 	    (esp_req & REQ_MASK) != 0 ||
10493 	    (se_req & REQ_MASK) != 0) {
10494 		connp->conn_in_enforce_policy = B_TRUE;
10495 		connp->conn_out_enforce_policy = B_TRUE;
10496 		connp->conn_flags |= IPCL_CHECK_POLICY;
10497 	}
10498 
10499 	mutex_exit(&connp->conn_lock);
10500 	return (error);
10501 #undef REQ_MASK
10502 
10503 	/*
10504 	 * Common memory-allocation-failure exit path.
10505 	 */
10506 enomem:
10507 	mutex_exit(&connp->conn_lock);
10508 	if (actp != NULL)
10509 		ipsec_actvec_free(actp, nact);
10510 	if (pin4 != NULL)
10511 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10512 	if (pout4 != NULL)
10513 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10514 	if (pin6 != NULL)
10515 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10516 	if (pout6 != NULL)
10517 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10518 	return (ENOMEM);
10519 }
10520 
10521 /*
10522  * Only for options that pass in an IP addr. Currently only V4 options
10523  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10524  * So this function assumes level is IPPROTO_IP
10525  */
10526 int
10527 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10528     mblk_t *first_mp)
10529 {
10530 	ipif_t *ipif = NULL;
10531 	int error;
10532 	ill_t *ill;
10533 	int zoneid;
10534 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10535 
10536 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10537 
10538 	if (addr != INADDR_ANY || checkonly) {
10539 		ASSERT(connp != NULL);
10540 		zoneid = IPCL_ZONEID(connp);
10541 		if (option == IP_NEXTHOP) {
10542 			ipif = ipif_lookup_onlink_addr(addr,
10543 			    connp->conn_zoneid, ipst);
10544 		} else {
10545 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10546 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10547 			    &error, ipst);
10548 		}
10549 		if (ipif == NULL) {
10550 			if (error == EINPROGRESS)
10551 				return (error);
10552 			else if ((option == IP_MULTICAST_IF) ||
10553 			    (option == IP_NEXTHOP))
10554 				return (EHOSTUNREACH);
10555 			else
10556 				return (EINVAL);
10557 		} else if (checkonly) {
10558 			if (option == IP_MULTICAST_IF) {
10559 				ill = ipif->ipif_ill;
10560 				/* not supported by the virtual network iface */
10561 				if (IS_VNI(ill)) {
10562 					ipif_refrele(ipif);
10563 					return (EINVAL);
10564 				}
10565 			}
10566 			ipif_refrele(ipif);
10567 			return (0);
10568 		}
10569 		ill = ipif->ipif_ill;
10570 		mutex_enter(&connp->conn_lock);
10571 		mutex_enter(&ill->ill_lock);
10572 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10573 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10574 			mutex_exit(&ill->ill_lock);
10575 			mutex_exit(&connp->conn_lock);
10576 			ipif_refrele(ipif);
10577 			return (option == IP_MULTICAST_IF ?
10578 			    EHOSTUNREACH : EINVAL);
10579 		}
10580 	} else {
10581 		mutex_enter(&connp->conn_lock);
10582 	}
10583 
10584 	/* None of the options below are supported on the VNI */
10585 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10586 		mutex_exit(&ill->ill_lock);
10587 		mutex_exit(&connp->conn_lock);
10588 		ipif_refrele(ipif);
10589 		return (EINVAL);
10590 	}
10591 
10592 	switch (option) {
10593 	case IP_DONTFAILOVER_IF:
10594 		/*
10595 		 * This option is used by in.mpathd to ensure
10596 		 * that IPMP probe packets only go out on the
10597 		 * test interfaces. in.mpathd sets this option
10598 		 * on the non-failover interfaces.
10599 		 * For backward compatibility, this option
10600 		 * implicitly sets IP_MULTICAST_IF, as used
10601 		 * be done in bind(), so that ip_wput gets
10602 		 * this ipif to send mcast packets.
10603 		 */
10604 		if (ipif != NULL) {
10605 			ASSERT(addr != INADDR_ANY);
10606 			connp->conn_nofailover_ill = ipif->ipif_ill;
10607 			connp->conn_multicast_ipif = ipif;
10608 		} else {
10609 			ASSERT(addr == INADDR_ANY);
10610 			connp->conn_nofailover_ill = NULL;
10611 			connp->conn_multicast_ipif = NULL;
10612 		}
10613 		break;
10614 
10615 	case IP_MULTICAST_IF:
10616 		connp->conn_multicast_ipif = ipif;
10617 		break;
10618 	case IP_NEXTHOP:
10619 		connp->conn_nexthop_v4 = addr;
10620 		connp->conn_nexthop_set = B_TRUE;
10621 		break;
10622 	}
10623 
10624 	if (ipif != NULL) {
10625 		mutex_exit(&ill->ill_lock);
10626 		mutex_exit(&connp->conn_lock);
10627 		ipif_refrele(ipif);
10628 		return (0);
10629 	}
10630 	mutex_exit(&connp->conn_lock);
10631 	/* We succeded in cleared the option */
10632 	return (0);
10633 }
10634 
10635 /*
10636  * For options that pass in an ifindex specifying the ill. V6 options always
10637  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10638  */
10639 int
10640 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10641     int level, int option, mblk_t *first_mp)
10642 {
10643 	ill_t *ill = NULL;
10644 	int error = 0;
10645 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10646 
10647 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10648 	if (ifindex != 0) {
10649 		ASSERT(connp != NULL);
10650 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10651 		    first_mp, ip_restart_optmgmt, &error, ipst);
10652 		if (ill != NULL) {
10653 			if (checkonly) {
10654 				/* not supported by the virtual network iface */
10655 				if (IS_VNI(ill)) {
10656 					ill_refrele(ill);
10657 					return (EINVAL);
10658 				}
10659 				ill_refrele(ill);
10660 				return (0);
10661 			}
10662 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10663 			    0, NULL)) {
10664 				ill_refrele(ill);
10665 				ill = NULL;
10666 				mutex_enter(&connp->conn_lock);
10667 				goto setit;
10668 			}
10669 			mutex_enter(&connp->conn_lock);
10670 			mutex_enter(&ill->ill_lock);
10671 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10672 				mutex_exit(&ill->ill_lock);
10673 				mutex_exit(&connp->conn_lock);
10674 				ill_refrele(ill);
10675 				ill = NULL;
10676 				mutex_enter(&connp->conn_lock);
10677 			}
10678 			goto setit;
10679 		} else if (error == EINPROGRESS) {
10680 			return (error);
10681 		} else {
10682 			error = 0;
10683 		}
10684 	}
10685 	mutex_enter(&connp->conn_lock);
10686 setit:
10687 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10688 
10689 	/*
10690 	 * The options below assume that the ILL (if any) transmits and/or
10691 	 * receives traffic. Neither of which is true for the virtual network
10692 	 * interface, so fail setting these on a VNI.
10693 	 */
10694 	if (IS_VNI(ill)) {
10695 		ASSERT(ill != NULL);
10696 		mutex_exit(&ill->ill_lock);
10697 		mutex_exit(&connp->conn_lock);
10698 		ill_refrele(ill);
10699 		return (EINVAL);
10700 	}
10701 
10702 	if (level == IPPROTO_IP) {
10703 		switch (option) {
10704 		case IP_BOUND_IF:
10705 			connp->conn_incoming_ill = ill;
10706 			connp->conn_outgoing_ill = ill;
10707 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10708 			    0 : ifindex;
10709 			break;
10710 
10711 		case IP_XMIT_IF:
10712 			/*
10713 			 * Similar to IP_BOUND_IF, but this only
10714 			 * determines the outgoing interface for
10715 			 * unicast packets. Also no IRE_CACHE entry
10716 			 * is added for the destination of the
10717 			 * outgoing packets. This feature is needed
10718 			 * for mobile IP.
10719 			 */
10720 			connp->conn_xmit_if_ill = ill;
10721 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10722 			    0 : ifindex;
10723 			break;
10724 
10725 		case IP_MULTICAST_IF:
10726 			/*
10727 			 * This option is an internal special. The socket
10728 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10729 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10730 			 * specifies an ifindex and we try first on V6 ill's.
10731 			 * If we don't find one, we they try using on v4 ill's
10732 			 * intenally and we come here.
10733 			 */
10734 			if (!checkonly && ill != NULL) {
10735 				ipif_t	*ipif;
10736 				ipif = ill->ill_ipif;
10737 
10738 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10739 					mutex_exit(&ill->ill_lock);
10740 					mutex_exit(&connp->conn_lock);
10741 					ill_refrele(ill);
10742 					ill = NULL;
10743 					mutex_enter(&connp->conn_lock);
10744 				} else {
10745 					connp->conn_multicast_ipif = ipif;
10746 				}
10747 			}
10748 			break;
10749 		}
10750 	} else {
10751 		switch (option) {
10752 		case IPV6_BOUND_IF:
10753 			connp->conn_incoming_ill = ill;
10754 			connp->conn_outgoing_ill = ill;
10755 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10756 			    0 : ifindex;
10757 			break;
10758 
10759 		case IPV6_BOUND_PIF:
10760 			/*
10761 			 * Limit all transmit to this ill.
10762 			 * Unlike IPV6_BOUND_IF, using this option
10763 			 * prevents load spreading and failover from
10764 			 * happening when the interface is part of the
10765 			 * group. That's why we don't need to remember
10766 			 * the ifindex in orig_bound_ifindex as in
10767 			 * IPV6_BOUND_IF.
10768 			 */
10769 			connp->conn_outgoing_pill = ill;
10770 			break;
10771 
10772 		case IPV6_DONTFAILOVER_IF:
10773 			/*
10774 			 * This option is used by in.mpathd to ensure
10775 			 * that IPMP probe packets only go out on the
10776 			 * test interfaces. in.mpathd sets this option
10777 			 * on the non-failover interfaces.
10778 			 */
10779 			connp->conn_nofailover_ill = ill;
10780 			/*
10781 			 * For backward compatibility, this option
10782 			 * implicitly sets ip_multicast_ill as used in
10783 			 * IP_MULTICAST_IF so that ip_wput gets
10784 			 * this ipif to send mcast packets.
10785 			 */
10786 			connp->conn_multicast_ill = ill;
10787 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10788 			    0 : ifindex;
10789 			break;
10790 
10791 		case IPV6_MULTICAST_IF:
10792 			/*
10793 			 * Set conn_multicast_ill to be the IPv6 ill.
10794 			 * Set conn_multicast_ipif to be an IPv4 ipif
10795 			 * for ifindex to make IPv4 mapped addresses
10796 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10797 			 * Even if no IPv6 ill exists for the ifindex
10798 			 * we need to check for an IPv4 ifindex in order
10799 			 * for this to work with mapped addresses. In that
10800 			 * case only set conn_multicast_ipif.
10801 			 */
10802 			if (!checkonly) {
10803 				if (ifindex == 0) {
10804 					connp->conn_multicast_ill = NULL;
10805 					connp->conn_orig_multicast_ifindex = 0;
10806 					connp->conn_multicast_ipif = NULL;
10807 				} else if (ill != NULL) {
10808 					connp->conn_multicast_ill = ill;
10809 					connp->conn_orig_multicast_ifindex =
10810 					    ifindex;
10811 				}
10812 			}
10813 			break;
10814 		}
10815 	}
10816 
10817 	if (ill != NULL) {
10818 		mutex_exit(&ill->ill_lock);
10819 		mutex_exit(&connp->conn_lock);
10820 		ill_refrele(ill);
10821 		return (0);
10822 	}
10823 	mutex_exit(&connp->conn_lock);
10824 	/*
10825 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10826 	 * locate the ill and could not set the option (ifindex != 0)
10827 	 */
10828 	return (ifindex == 0 ? 0 : EINVAL);
10829 }
10830 
10831 /* This routine sets socket options. */
10832 /* ARGSUSED */
10833 int
10834 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10835     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10836     void *dummy, cred_t *cr, mblk_t *first_mp)
10837 {
10838 	int		*i1 = (int *)invalp;
10839 	conn_t		*connp = Q_TO_CONN(q);
10840 	int		error = 0;
10841 	boolean_t	checkonly;
10842 	ire_t		*ire;
10843 	boolean_t	found;
10844 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10845 
10846 	switch (optset_context) {
10847 
10848 	case SETFN_OPTCOM_CHECKONLY:
10849 		checkonly = B_TRUE;
10850 		/*
10851 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10852 		 * inlen != 0 implies value supplied and
10853 		 * 	we have to "pretend" to set it.
10854 		 * inlen == 0 implies that there is no
10855 		 * 	value part in T_CHECK request and just validation
10856 		 * done elsewhere should be enough, we just return here.
10857 		 */
10858 		if (inlen == 0) {
10859 			*outlenp = 0;
10860 			return (0);
10861 		}
10862 		break;
10863 	case SETFN_OPTCOM_NEGOTIATE:
10864 	case SETFN_UD_NEGOTIATE:
10865 	case SETFN_CONN_NEGOTIATE:
10866 		checkonly = B_FALSE;
10867 		break;
10868 	default:
10869 		/*
10870 		 * We should never get here
10871 		 */
10872 		*outlenp = 0;
10873 		return (EINVAL);
10874 	}
10875 
10876 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10877 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10878 
10879 	/*
10880 	 * For fixed length options, no sanity check
10881 	 * of passed in length is done. It is assumed *_optcom_req()
10882 	 * routines do the right thing.
10883 	 */
10884 
10885 	switch (level) {
10886 	case SOL_SOCKET:
10887 		/*
10888 		 * conn_lock protects the bitfields, and is used to
10889 		 * set the fields atomically.
10890 		 */
10891 		switch (name) {
10892 		case SO_BROADCAST:
10893 			if (!checkonly) {
10894 				/* TODO: use value someplace? */
10895 				mutex_enter(&connp->conn_lock);
10896 				connp->conn_broadcast = *i1 ? 1 : 0;
10897 				mutex_exit(&connp->conn_lock);
10898 			}
10899 			break;	/* goto sizeof (int) option return */
10900 		case SO_USELOOPBACK:
10901 			if (!checkonly) {
10902 				/* TODO: use value someplace? */
10903 				mutex_enter(&connp->conn_lock);
10904 				connp->conn_loopback = *i1 ? 1 : 0;
10905 				mutex_exit(&connp->conn_lock);
10906 			}
10907 			break;	/* goto sizeof (int) option return */
10908 		case SO_DONTROUTE:
10909 			if (!checkonly) {
10910 				mutex_enter(&connp->conn_lock);
10911 				connp->conn_dontroute = *i1 ? 1 : 0;
10912 				mutex_exit(&connp->conn_lock);
10913 			}
10914 			break;	/* goto sizeof (int) option return */
10915 		case SO_REUSEADDR:
10916 			if (!checkonly) {
10917 				mutex_enter(&connp->conn_lock);
10918 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10919 				mutex_exit(&connp->conn_lock);
10920 			}
10921 			break;	/* goto sizeof (int) option return */
10922 		case SO_PROTOTYPE:
10923 			if (!checkonly) {
10924 				mutex_enter(&connp->conn_lock);
10925 				connp->conn_proto = *i1;
10926 				mutex_exit(&connp->conn_lock);
10927 			}
10928 			break;	/* goto sizeof (int) option return */
10929 		case SO_ALLZONES:
10930 			if (!checkonly) {
10931 				mutex_enter(&connp->conn_lock);
10932 				if (IPCL_IS_BOUND(connp)) {
10933 					mutex_exit(&connp->conn_lock);
10934 					return (EINVAL);
10935 				}
10936 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10937 				mutex_exit(&connp->conn_lock);
10938 			}
10939 			break;	/* goto sizeof (int) option return */
10940 		case SO_ANON_MLP:
10941 			if (!checkonly) {
10942 				mutex_enter(&connp->conn_lock);
10943 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10944 				mutex_exit(&connp->conn_lock);
10945 			}
10946 			break;	/* goto sizeof (int) option return */
10947 		case SO_MAC_EXEMPT:
10948 			if (secpolicy_net_mac_aware(cr) != 0 ||
10949 			    IPCL_IS_BOUND(connp))
10950 				return (EACCES);
10951 			if (!checkonly) {
10952 				mutex_enter(&connp->conn_lock);
10953 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10954 				mutex_exit(&connp->conn_lock);
10955 			}
10956 			break;	/* goto sizeof (int) option return */
10957 		default:
10958 			/*
10959 			 * "soft" error (negative)
10960 			 * option not handled at this level
10961 			 * Note: Do not modify *outlenp
10962 			 */
10963 			return (-EINVAL);
10964 		}
10965 		break;
10966 	case IPPROTO_IP:
10967 		switch (name) {
10968 		case IP_NEXTHOP:
10969 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10970 				return (EPERM);
10971 			/* FALLTHRU */
10972 		case IP_MULTICAST_IF:
10973 		case IP_DONTFAILOVER_IF: {
10974 			ipaddr_t addr = *i1;
10975 
10976 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10977 			    first_mp);
10978 			if (error != 0)
10979 				return (error);
10980 			break;	/* goto sizeof (int) option return */
10981 		}
10982 
10983 		case IP_MULTICAST_TTL:
10984 			/* Recorded in transport above IP */
10985 			*outvalp = *invalp;
10986 			*outlenp = sizeof (uchar_t);
10987 			return (0);
10988 		case IP_MULTICAST_LOOP:
10989 			if (!checkonly) {
10990 				mutex_enter(&connp->conn_lock);
10991 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10992 				mutex_exit(&connp->conn_lock);
10993 			}
10994 			*outvalp = *invalp;
10995 			*outlenp = sizeof (uchar_t);
10996 			return (0);
10997 		case IP_ADD_MEMBERSHIP:
10998 		case MCAST_JOIN_GROUP:
10999 		case IP_DROP_MEMBERSHIP:
11000 		case MCAST_LEAVE_GROUP: {
11001 			struct ip_mreq *mreqp;
11002 			struct group_req *greqp;
11003 			ire_t *ire;
11004 			boolean_t done = B_FALSE;
11005 			ipaddr_t group, ifaddr;
11006 			struct sockaddr_in *sin;
11007 			uint32_t *ifindexp;
11008 			boolean_t mcast_opt = B_TRUE;
11009 			mcast_record_t fmode;
11010 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11011 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11012 
11013 			switch (name) {
11014 			case IP_ADD_MEMBERSHIP:
11015 				mcast_opt = B_FALSE;
11016 				/* FALLTHRU */
11017 			case MCAST_JOIN_GROUP:
11018 				fmode = MODE_IS_EXCLUDE;
11019 				optfn = ip_opt_add_group;
11020 				break;
11021 
11022 			case IP_DROP_MEMBERSHIP:
11023 				mcast_opt = B_FALSE;
11024 				/* FALLTHRU */
11025 			case MCAST_LEAVE_GROUP:
11026 				fmode = MODE_IS_INCLUDE;
11027 				optfn = ip_opt_delete_group;
11028 				break;
11029 			}
11030 
11031 			if (mcast_opt) {
11032 				greqp = (struct group_req *)i1;
11033 				sin = (struct sockaddr_in *)&greqp->gr_group;
11034 				if (sin->sin_family != AF_INET) {
11035 					*outlenp = 0;
11036 					return (ENOPROTOOPT);
11037 				}
11038 				group = (ipaddr_t)sin->sin_addr.s_addr;
11039 				ifaddr = INADDR_ANY;
11040 				ifindexp = &greqp->gr_interface;
11041 			} else {
11042 				mreqp = (struct ip_mreq *)i1;
11043 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
11044 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
11045 				ifindexp = NULL;
11046 			}
11047 
11048 			/*
11049 			 * In the multirouting case, we need to replicate
11050 			 * the request on all interfaces that will take part
11051 			 * in replication.  We do so because multirouting is
11052 			 * reflective, thus we will probably receive multi-
11053 			 * casts on those interfaces.
11054 			 * The ip_multirt_apply_membership() succeeds if the
11055 			 * operation succeeds on at least one interface.
11056 			 */
11057 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
11058 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11059 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11060 			if (ire != NULL) {
11061 				if (ire->ire_flags & RTF_MULTIRT) {
11062 					error = ip_multirt_apply_membership(
11063 					    optfn, ire, connp, checkonly, group,
11064 					    fmode, INADDR_ANY, first_mp);
11065 					done = B_TRUE;
11066 				}
11067 				ire_refrele(ire);
11068 			}
11069 			if (!done) {
11070 				error = optfn(connp, checkonly, group, ifaddr,
11071 				    ifindexp, fmode, INADDR_ANY, first_mp);
11072 			}
11073 			if (error) {
11074 				/*
11075 				 * EINPROGRESS is a soft error, needs retry
11076 				 * so don't make *outlenp zero.
11077 				 */
11078 				if (error != EINPROGRESS)
11079 					*outlenp = 0;
11080 				return (error);
11081 			}
11082 			/* OK return - copy input buffer into output buffer */
11083 			if (invalp != outvalp) {
11084 				/* don't trust bcopy for identical src/dst */
11085 				bcopy(invalp, outvalp, inlen);
11086 			}
11087 			*outlenp = inlen;
11088 			return (0);
11089 		}
11090 		case IP_BLOCK_SOURCE:
11091 		case IP_UNBLOCK_SOURCE:
11092 		case IP_ADD_SOURCE_MEMBERSHIP:
11093 		case IP_DROP_SOURCE_MEMBERSHIP:
11094 		case MCAST_BLOCK_SOURCE:
11095 		case MCAST_UNBLOCK_SOURCE:
11096 		case MCAST_JOIN_SOURCE_GROUP:
11097 		case MCAST_LEAVE_SOURCE_GROUP: {
11098 			struct ip_mreq_source *imreqp;
11099 			struct group_source_req *gsreqp;
11100 			in_addr_t grp, src, ifaddr = INADDR_ANY;
11101 			uint32_t ifindex = 0;
11102 			mcast_record_t fmode;
11103 			struct sockaddr_in *sin;
11104 			ire_t *ire;
11105 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11106 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11107 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11108 
11109 			switch (name) {
11110 			case IP_BLOCK_SOURCE:
11111 				mcast_opt = B_FALSE;
11112 				/* FALLTHRU */
11113 			case MCAST_BLOCK_SOURCE:
11114 				fmode = MODE_IS_EXCLUDE;
11115 				optfn = ip_opt_add_group;
11116 				break;
11117 
11118 			case IP_UNBLOCK_SOURCE:
11119 				mcast_opt = B_FALSE;
11120 				/* FALLTHRU */
11121 			case MCAST_UNBLOCK_SOURCE:
11122 				fmode = MODE_IS_EXCLUDE;
11123 				optfn = ip_opt_delete_group;
11124 				break;
11125 
11126 			case IP_ADD_SOURCE_MEMBERSHIP:
11127 				mcast_opt = B_FALSE;
11128 				/* FALLTHRU */
11129 			case MCAST_JOIN_SOURCE_GROUP:
11130 				fmode = MODE_IS_INCLUDE;
11131 				optfn = ip_opt_add_group;
11132 				break;
11133 
11134 			case IP_DROP_SOURCE_MEMBERSHIP:
11135 				mcast_opt = B_FALSE;
11136 				/* FALLTHRU */
11137 			case MCAST_LEAVE_SOURCE_GROUP:
11138 				fmode = MODE_IS_INCLUDE;
11139 				optfn = ip_opt_delete_group;
11140 				break;
11141 			}
11142 
11143 			if (mcast_opt) {
11144 				gsreqp = (struct group_source_req *)i1;
11145 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11146 					*outlenp = 0;
11147 					return (ENOPROTOOPT);
11148 				}
11149 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11150 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11151 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11152 				src = (ipaddr_t)sin->sin_addr.s_addr;
11153 				ifindex = gsreqp->gsr_interface;
11154 			} else {
11155 				imreqp = (struct ip_mreq_source *)i1;
11156 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11157 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11158 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11159 			}
11160 
11161 			/*
11162 			 * In the multirouting case, we need to replicate
11163 			 * the request as noted in the mcast cases above.
11164 			 */
11165 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11166 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11167 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11168 			if (ire != NULL) {
11169 				if (ire->ire_flags & RTF_MULTIRT) {
11170 					error = ip_multirt_apply_membership(
11171 					    optfn, ire, connp, checkonly, grp,
11172 					    fmode, src, first_mp);
11173 					done = B_TRUE;
11174 				}
11175 				ire_refrele(ire);
11176 			}
11177 			if (!done) {
11178 				error = optfn(connp, checkonly, grp, ifaddr,
11179 				    &ifindex, fmode, src, first_mp);
11180 			}
11181 			if (error != 0) {
11182 				/*
11183 				 * EINPROGRESS is a soft error, needs retry
11184 				 * so don't make *outlenp zero.
11185 				 */
11186 				if (error != EINPROGRESS)
11187 					*outlenp = 0;
11188 				return (error);
11189 			}
11190 			/* OK return - copy input buffer into output buffer */
11191 			if (invalp != outvalp) {
11192 				bcopy(invalp, outvalp, inlen);
11193 			}
11194 			*outlenp = inlen;
11195 			return (0);
11196 		}
11197 		case IP_SEC_OPT:
11198 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11199 			if (error != 0) {
11200 				*outlenp = 0;
11201 				return (error);
11202 			}
11203 			break;
11204 		case IP_HDRINCL:
11205 		case IP_OPTIONS:
11206 		case T_IP_OPTIONS:
11207 		case IP_TOS:
11208 		case T_IP_TOS:
11209 		case IP_TTL:
11210 		case IP_RECVDSTADDR:
11211 		case IP_RECVOPTS:
11212 			/* OK return - copy input buffer into output buffer */
11213 			if (invalp != outvalp) {
11214 				/* don't trust bcopy for identical src/dst */
11215 				bcopy(invalp, outvalp, inlen);
11216 			}
11217 			*outlenp = inlen;
11218 			return (0);
11219 		case IP_RECVIF:
11220 			/* Retrieve the inbound interface index */
11221 			if (!checkonly) {
11222 				mutex_enter(&connp->conn_lock);
11223 				connp->conn_recvif = *i1 ? 1 : 0;
11224 				mutex_exit(&connp->conn_lock);
11225 			}
11226 			break;	/* goto sizeof (int) option return */
11227 		case IP_RECVPKTINFO:
11228 			if (!checkonly) {
11229 				mutex_enter(&connp->conn_lock);
11230 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11231 				mutex_exit(&connp->conn_lock);
11232 			}
11233 			break;	/* goto sizeof (int) option return */
11234 		case IP_RECVSLLA:
11235 			/* Retrieve the source link layer address */
11236 			if (!checkonly) {
11237 				mutex_enter(&connp->conn_lock);
11238 				connp->conn_recvslla = *i1 ? 1 : 0;
11239 				mutex_exit(&connp->conn_lock);
11240 			}
11241 			break;	/* goto sizeof (int) option return */
11242 		case MRT_INIT:
11243 		case MRT_DONE:
11244 		case MRT_ADD_VIF:
11245 		case MRT_DEL_VIF:
11246 		case MRT_ADD_MFC:
11247 		case MRT_DEL_MFC:
11248 		case MRT_ASSERT:
11249 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11250 				*outlenp = 0;
11251 				return (error);
11252 			}
11253 			error = ip_mrouter_set((int)name, q, checkonly,
11254 			    (uchar_t *)invalp, inlen, first_mp);
11255 			if (error) {
11256 				*outlenp = 0;
11257 				return (error);
11258 			}
11259 			/* OK return - copy input buffer into output buffer */
11260 			if (invalp != outvalp) {
11261 				/* don't trust bcopy for identical src/dst */
11262 				bcopy(invalp, outvalp, inlen);
11263 			}
11264 			*outlenp = inlen;
11265 			return (0);
11266 		case IP_BOUND_IF:
11267 		case IP_XMIT_IF:
11268 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11269 			    level, name, first_mp);
11270 			if (error != 0)
11271 				return (error);
11272 			break; 		/* goto sizeof (int) option return */
11273 
11274 		case IP_UNSPEC_SRC:
11275 			/* Allow sending with a zero source address */
11276 			if (!checkonly) {
11277 				mutex_enter(&connp->conn_lock);
11278 				connp->conn_unspec_src = *i1 ? 1 : 0;
11279 				mutex_exit(&connp->conn_lock);
11280 			}
11281 			break;	/* goto sizeof (int) option return */
11282 		default:
11283 			/*
11284 			 * "soft" error (negative)
11285 			 * option not handled at this level
11286 			 * Note: Do not modify *outlenp
11287 			 */
11288 			return (-EINVAL);
11289 		}
11290 		break;
11291 	case IPPROTO_IPV6:
11292 		switch (name) {
11293 		case IPV6_BOUND_IF:
11294 		case IPV6_BOUND_PIF:
11295 		case IPV6_DONTFAILOVER_IF:
11296 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11297 			    level, name, first_mp);
11298 			if (error != 0)
11299 				return (error);
11300 			break; 		/* goto sizeof (int) option return */
11301 
11302 		case IPV6_MULTICAST_IF:
11303 			/*
11304 			 * The only possible errors are EINPROGRESS and
11305 			 * EINVAL. EINPROGRESS will be restarted and is not
11306 			 * a hard error. We call this option on both V4 and V6
11307 			 * If both return EINVAL, then this call returns
11308 			 * EINVAL. If at least one of them succeeds we
11309 			 * return success.
11310 			 */
11311 			found = B_FALSE;
11312 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11313 			    level, name, first_mp);
11314 			if (error == EINPROGRESS)
11315 				return (error);
11316 			if (error == 0)
11317 				found = B_TRUE;
11318 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11319 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11320 			if (error == 0)
11321 				found = B_TRUE;
11322 			if (!found)
11323 				return (error);
11324 			break; 		/* goto sizeof (int) option return */
11325 
11326 		case IPV6_MULTICAST_HOPS:
11327 			/* Recorded in transport above IP */
11328 			break;	/* goto sizeof (int) option return */
11329 		case IPV6_MULTICAST_LOOP:
11330 			if (!checkonly) {
11331 				mutex_enter(&connp->conn_lock);
11332 				connp->conn_multicast_loop = *i1;
11333 				mutex_exit(&connp->conn_lock);
11334 			}
11335 			break;	/* goto sizeof (int) option return */
11336 		case IPV6_JOIN_GROUP:
11337 		case MCAST_JOIN_GROUP:
11338 		case IPV6_LEAVE_GROUP:
11339 		case MCAST_LEAVE_GROUP: {
11340 			struct ipv6_mreq *ip_mreqp;
11341 			struct group_req *greqp;
11342 			ire_t *ire;
11343 			boolean_t done = B_FALSE;
11344 			in6_addr_t groupv6;
11345 			uint32_t ifindex;
11346 			boolean_t mcast_opt = B_TRUE;
11347 			mcast_record_t fmode;
11348 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11349 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11350 
11351 			switch (name) {
11352 			case IPV6_JOIN_GROUP:
11353 				mcast_opt = B_FALSE;
11354 				/* FALLTHRU */
11355 			case MCAST_JOIN_GROUP:
11356 				fmode = MODE_IS_EXCLUDE;
11357 				optfn = ip_opt_add_group_v6;
11358 				break;
11359 
11360 			case IPV6_LEAVE_GROUP:
11361 				mcast_opt = B_FALSE;
11362 				/* FALLTHRU */
11363 			case MCAST_LEAVE_GROUP:
11364 				fmode = MODE_IS_INCLUDE;
11365 				optfn = ip_opt_delete_group_v6;
11366 				break;
11367 			}
11368 
11369 			if (mcast_opt) {
11370 				struct sockaddr_in *sin;
11371 				struct sockaddr_in6 *sin6;
11372 				greqp = (struct group_req *)i1;
11373 				if (greqp->gr_group.ss_family == AF_INET) {
11374 					sin = (struct sockaddr_in *)
11375 					    &(greqp->gr_group);
11376 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11377 					    &groupv6);
11378 				} else {
11379 					sin6 = (struct sockaddr_in6 *)
11380 					    &(greqp->gr_group);
11381 					groupv6 = sin6->sin6_addr;
11382 				}
11383 				ifindex = greqp->gr_interface;
11384 			} else {
11385 				ip_mreqp = (struct ipv6_mreq *)i1;
11386 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11387 				ifindex = ip_mreqp->ipv6mr_interface;
11388 			}
11389 			/*
11390 			 * In the multirouting case, we need to replicate
11391 			 * the request on all interfaces that will take part
11392 			 * in replication.  We do so because multirouting is
11393 			 * reflective, thus we will probably receive multi-
11394 			 * casts on those interfaces.
11395 			 * The ip_multirt_apply_membership_v6() succeeds if
11396 			 * the operation succeeds on at least one interface.
11397 			 */
11398 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11399 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11400 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11401 			if (ire != NULL) {
11402 				if (ire->ire_flags & RTF_MULTIRT) {
11403 					error = ip_multirt_apply_membership_v6(
11404 					    optfn, ire, connp, checkonly,
11405 					    &groupv6, fmode, &ipv6_all_zeros,
11406 					    first_mp);
11407 					done = B_TRUE;
11408 				}
11409 				ire_refrele(ire);
11410 			}
11411 			if (!done) {
11412 				error = optfn(connp, checkonly, &groupv6,
11413 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11414 			}
11415 			if (error) {
11416 				/*
11417 				 * EINPROGRESS is a soft error, needs retry
11418 				 * so don't make *outlenp zero.
11419 				 */
11420 				if (error != EINPROGRESS)
11421 					*outlenp = 0;
11422 				return (error);
11423 			}
11424 			/* OK return - copy input buffer into output buffer */
11425 			if (invalp != outvalp) {
11426 				/* don't trust bcopy for identical src/dst */
11427 				bcopy(invalp, outvalp, inlen);
11428 			}
11429 			*outlenp = inlen;
11430 			return (0);
11431 		}
11432 		case MCAST_BLOCK_SOURCE:
11433 		case MCAST_UNBLOCK_SOURCE:
11434 		case MCAST_JOIN_SOURCE_GROUP:
11435 		case MCAST_LEAVE_SOURCE_GROUP: {
11436 			struct group_source_req *gsreqp;
11437 			in6_addr_t v6grp, v6src;
11438 			uint32_t ifindex;
11439 			mcast_record_t fmode;
11440 			ire_t *ire;
11441 			boolean_t done = B_FALSE;
11442 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11443 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11444 
11445 			switch (name) {
11446 			case MCAST_BLOCK_SOURCE:
11447 				fmode = MODE_IS_EXCLUDE;
11448 				optfn = ip_opt_add_group_v6;
11449 				break;
11450 			case MCAST_UNBLOCK_SOURCE:
11451 				fmode = MODE_IS_EXCLUDE;
11452 				optfn = ip_opt_delete_group_v6;
11453 				break;
11454 			case MCAST_JOIN_SOURCE_GROUP:
11455 				fmode = MODE_IS_INCLUDE;
11456 				optfn = ip_opt_add_group_v6;
11457 				break;
11458 			case MCAST_LEAVE_SOURCE_GROUP:
11459 				fmode = MODE_IS_INCLUDE;
11460 				optfn = ip_opt_delete_group_v6;
11461 				break;
11462 			}
11463 
11464 			gsreqp = (struct group_source_req *)i1;
11465 			ifindex = gsreqp->gsr_interface;
11466 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11467 				struct sockaddr_in *s;
11468 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11469 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11470 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11471 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11472 			} else {
11473 				struct sockaddr_in6 *s6;
11474 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11475 				v6grp = s6->sin6_addr;
11476 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11477 				v6src = s6->sin6_addr;
11478 			}
11479 
11480 			/*
11481 			 * In the multirouting case, we need to replicate
11482 			 * the request as noted in the mcast cases above.
11483 			 */
11484 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11485 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11486 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11487 			if (ire != NULL) {
11488 				if (ire->ire_flags & RTF_MULTIRT) {
11489 					error = ip_multirt_apply_membership_v6(
11490 					    optfn, ire, connp, checkonly,
11491 					    &v6grp, fmode, &v6src, first_mp);
11492 					done = B_TRUE;
11493 				}
11494 				ire_refrele(ire);
11495 			}
11496 			if (!done) {
11497 				error = optfn(connp, checkonly, &v6grp,
11498 				    ifindex, fmode, &v6src, first_mp);
11499 			}
11500 			if (error != 0) {
11501 				/*
11502 				 * EINPROGRESS is a soft error, needs retry
11503 				 * so don't make *outlenp zero.
11504 				 */
11505 				if (error != EINPROGRESS)
11506 					*outlenp = 0;
11507 				return (error);
11508 			}
11509 			/* OK return - copy input buffer into output buffer */
11510 			if (invalp != outvalp) {
11511 				bcopy(invalp, outvalp, inlen);
11512 			}
11513 			*outlenp = inlen;
11514 			return (0);
11515 		}
11516 		case IPV6_UNICAST_HOPS:
11517 			/* Recorded in transport above IP */
11518 			break;	/* goto sizeof (int) option return */
11519 		case IPV6_UNSPEC_SRC:
11520 			/* Allow sending with a zero source address */
11521 			if (!checkonly) {
11522 				mutex_enter(&connp->conn_lock);
11523 				connp->conn_unspec_src = *i1 ? 1 : 0;
11524 				mutex_exit(&connp->conn_lock);
11525 			}
11526 			break;	/* goto sizeof (int) option return */
11527 		case IPV6_RECVPKTINFO:
11528 			if (!checkonly) {
11529 				mutex_enter(&connp->conn_lock);
11530 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11531 				mutex_exit(&connp->conn_lock);
11532 			}
11533 			break;	/* goto sizeof (int) option return */
11534 		case IPV6_RECVTCLASS:
11535 			if (!checkonly) {
11536 				if (*i1 < 0 || *i1 > 1) {
11537 					return (EINVAL);
11538 				}
11539 				mutex_enter(&connp->conn_lock);
11540 				connp->conn_ipv6_recvtclass = *i1;
11541 				mutex_exit(&connp->conn_lock);
11542 			}
11543 			break;
11544 		case IPV6_RECVPATHMTU:
11545 			if (!checkonly) {
11546 				if (*i1 < 0 || *i1 > 1) {
11547 					return (EINVAL);
11548 				}
11549 				mutex_enter(&connp->conn_lock);
11550 				connp->conn_ipv6_recvpathmtu = *i1;
11551 				mutex_exit(&connp->conn_lock);
11552 			}
11553 			break;
11554 		case IPV6_RECVHOPLIMIT:
11555 			if (!checkonly) {
11556 				mutex_enter(&connp->conn_lock);
11557 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11558 				mutex_exit(&connp->conn_lock);
11559 			}
11560 			break;	/* goto sizeof (int) option return */
11561 		case IPV6_RECVHOPOPTS:
11562 			if (!checkonly) {
11563 				mutex_enter(&connp->conn_lock);
11564 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11565 				mutex_exit(&connp->conn_lock);
11566 			}
11567 			break;	/* goto sizeof (int) option return */
11568 		case IPV6_RECVDSTOPTS:
11569 			if (!checkonly) {
11570 				mutex_enter(&connp->conn_lock);
11571 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11572 				mutex_exit(&connp->conn_lock);
11573 			}
11574 			break;	/* goto sizeof (int) option return */
11575 		case IPV6_RECVRTHDR:
11576 			if (!checkonly) {
11577 				mutex_enter(&connp->conn_lock);
11578 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11579 				mutex_exit(&connp->conn_lock);
11580 			}
11581 			break;	/* goto sizeof (int) option return */
11582 		case IPV6_RECVRTHDRDSTOPTS:
11583 			if (!checkonly) {
11584 				mutex_enter(&connp->conn_lock);
11585 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11586 				mutex_exit(&connp->conn_lock);
11587 			}
11588 			break;	/* goto sizeof (int) option return */
11589 		case IPV6_PKTINFO:
11590 			if (inlen == 0)
11591 				return (-EINVAL);	/* clearing option */
11592 			error = ip6_set_pktinfo(cr, connp,
11593 			    (struct in6_pktinfo *)invalp, first_mp);
11594 			if (error != 0)
11595 				*outlenp = 0;
11596 			else
11597 				*outlenp = inlen;
11598 			return (error);
11599 		case IPV6_NEXTHOP: {
11600 			struct sockaddr_in6 *sin6;
11601 
11602 			/* Verify that the nexthop is reachable */
11603 			if (inlen == 0)
11604 				return (-EINVAL);	/* clearing option */
11605 
11606 			sin6 = (struct sockaddr_in6 *)invalp;
11607 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11608 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11609 			    NULL, MATCH_IRE_DEFAULT, ipst);
11610 
11611 			if (ire == NULL) {
11612 				*outlenp = 0;
11613 				return (EHOSTUNREACH);
11614 			}
11615 			ire_refrele(ire);
11616 			return (-EINVAL);
11617 		}
11618 		case IPV6_SEC_OPT:
11619 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11620 			if (error != 0) {
11621 				*outlenp = 0;
11622 				return (error);
11623 			}
11624 			break;
11625 		case IPV6_SRC_PREFERENCES: {
11626 			/*
11627 			 * This is implemented strictly in the ip module
11628 			 * (here and in tcp_opt_*() to accomodate tcp
11629 			 * sockets).  Modules above ip pass this option
11630 			 * down here since ip is the only one that needs to
11631 			 * be aware of source address preferences.
11632 			 *
11633 			 * This socket option only affects connected
11634 			 * sockets that haven't already bound to a specific
11635 			 * IPv6 address.  In other words, sockets that
11636 			 * don't call bind() with an address other than the
11637 			 * unspecified address and that call connect().
11638 			 * ip_bind_connected_v6() passes these preferences
11639 			 * to the ipif_select_source_v6() function.
11640 			 */
11641 			if (inlen != sizeof (uint32_t))
11642 				return (EINVAL);
11643 			error = ip6_set_src_preferences(connp,
11644 			    *(uint32_t *)invalp);
11645 			if (error != 0) {
11646 				*outlenp = 0;
11647 				return (error);
11648 			} else {
11649 				*outlenp = sizeof (uint32_t);
11650 			}
11651 			break;
11652 		}
11653 		case IPV6_V6ONLY:
11654 			if (*i1 < 0 || *i1 > 1) {
11655 				return (EINVAL);
11656 			}
11657 			mutex_enter(&connp->conn_lock);
11658 			connp->conn_ipv6_v6only = *i1;
11659 			mutex_exit(&connp->conn_lock);
11660 			break;
11661 		default:
11662 			return (-EINVAL);
11663 		}
11664 		break;
11665 	default:
11666 		/*
11667 		 * "soft" error (negative)
11668 		 * option not handled at this level
11669 		 * Note: Do not modify *outlenp
11670 		 */
11671 		return (-EINVAL);
11672 	}
11673 	/*
11674 	 * Common case of return from an option that is sizeof (int)
11675 	 */
11676 	*(int *)outvalp = *i1;
11677 	*outlenp = sizeof (int);
11678 	return (0);
11679 }
11680 
11681 /*
11682  * This routine gets default values of certain options whose default
11683  * values are maintained by protocol specific code
11684  */
11685 /* ARGSUSED */
11686 int
11687 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11688 {
11689 	int *i1 = (int *)ptr;
11690 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11691 
11692 	switch (level) {
11693 	case IPPROTO_IP:
11694 		switch (name) {
11695 		case IP_MULTICAST_TTL:
11696 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11697 			return (sizeof (uchar_t));
11698 		case IP_MULTICAST_LOOP:
11699 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11700 			return (sizeof (uchar_t));
11701 		default:
11702 			return (-1);
11703 		}
11704 	case IPPROTO_IPV6:
11705 		switch (name) {
11706 		case IPV6_UNICAST_HOPS:
11707 			*i1 = ipst->ips_ipv6_def_hops;
11708 			return (sizeof (int));
11709 		case IPV6_MULTICAST_HOPS:
11710 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11711 			return (sizeof (int));
11712 		case IPV6_MULTICAST_LOOP:
11713 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11714 			return (sizeof (int));
11715 		case IPV6_V6ONLY:
11716 			*i1 = 1;
11717 			return (sizeof (int));
11718 		default:
11719 			return (-1);
11720 		}
11721 	default:
11722 		return (-1);
11723 	}
11724 	/* NOTREACHED */
11725 }
11726 
11727 /*
11728  * Given a destination address and a pointer to where to put the information
11729  * this routine fills in the mtuinfo.
11730  */
11731 int
11732 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11733     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11734 {
11735 	ire_t *ire;
11736 	ip_stack_t	*ipst = ns->netstack_ip;
11737 
11738 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11739 		return (-1);
11740 
11741 	bzero(mtuinfo, sizeof (*mtuinfo));
11742 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11743 	mtuinfo->ip6m_addr.sin6_port = port;
11744 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11745 
11746 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11747 	if (ire != NULL) {
11748 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11749 		ire_refrele(ire);
11750 	} else {
11751 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11752 	}
11753 	return (sizeof (struct ip6_mtuinfo));
11754 }
11755 
11756 /*
11757  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11758  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11759  * isn't.  This doesn't matter as the error checking is done properly for the
11760  * other MRT options coming in through ip_opt_set.
11761  */
11762 int
11763 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11764 {
11765 	conn_t		*connp = Q_TO_CONN(q);
11766 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11767 
11768 	switch (level) {
11769 	case IPPROTO_IP:
11770 		switch (name) {
11771 		case MRT_VERSION:
11772 		case MRT_ASSERT:
11773 			(void) ip_mrouter_get(name, q, ptr);
11774 			return (sizeof (int));
11775 		case IP_SEC_OPT:
11776 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11777 		case IP_NEXTHOP:
11778 			if (connp->conn_nexthop_set) {
11779 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11780 				return (sizeof (ipaddr_t));
11781 			} else
11782 				return (0);
11783 		case IP_RECVPKTINFO:
11784 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11785 			return (sizeof (int));
11786 		default:
11787 			break;
11788 		}
11789 		break;
11790 	case IPPROTO_IPV6:
11791 		switch (name) {
11792 		case IPV6_SEC_OPT:
11793 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11794 		case IPV6_SRC_PREFERENCES: {
11795 			return (ip6_get_src_preferences(connp,
11796 			    (uint32_t *)ptr));
11797 		}
11798 		case IPV6_V6ONLY:
11799 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11800 			return (sizeof (int));
11801 		case IPV6_PATHMTU:
11802 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11803 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11804 		default:
11805 			break;
11806 		}
11807 		break;
11808 	default:
11809 		break;
11810 	}
11811 	return (-1);
11812 }
11813 
11814 /* Named Dispatch routine to get a current value out of our parameter table. */
11815 /* ARGSUSED */
11816 static int
11817 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11818 {
11819 	ipparam_t *ippa = (ipparam_t *)cp;
11820 
11821 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11822 	return (0);
11823 }
11824 
11825 /* ARGSUSED */
11826 static int
11827 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11828 {
11829 
11830 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11831 	return (0);
11832 }
11833 
11834 /*
11835  * Set ip{,6}_forwarding values.  This means walking through all of the
11836  * ill's and toggling their forwarding values.
11837  */
11838 /* ARGSUSED */
11839 static int
11840 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11841 {
11842 	long new_value;
11843 	int *forwarding_value = (int *)cp;
11844 	ill_t *ill;
11845 	boolean_t isv6;
11846 	ill_walk_context_t ctx;
11847 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11848 
11849 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11850 
11851 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11852 	    new_value < 0 || new_value > 1) {
11853 		return (EINVAL);
11854 	}
11855 
11856 	*forwarding_value = new_value;
11857 
11858 	/*
11859 	 * Regardless of the current value of ip_forwarding, set all per-ill
11860 	 * values of ip_forwarding to the value being set.
11861 	 *
11862 	 * Bring all the ill's up to date with the new global value.
11863 	 */
11864 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11865 
11866 	if (isv6)
11867 		ill = ILL_START_WALK_V6(&ctx, ipst);
11868 	else
11869 		ill = ILL_START_WALK_V4(&ctx, ipst);
11870 
11871 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11872 		(void) ill_forward_set(ill, new_value != 0);
11873 
11874 	rw_exit(&ipst->ips_ill_g_lock);
11875 	return (0);
11876 }
11877 
11878 /*
11879  * Walk through the param array specified registering each element with the
11880  * Named Dispatch handler. This is called only during init. So it is ok
11881  * not to acquire any locks
11882  */
11883 static boolean_t
11884 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11885     ipndp_t *ipnd, size_t ipnd_cnt)
11886 {
11887 	for (; ippa_cnt-- > 0; ippa++) {
11888 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11889 			if (!nd_load(ndp, ippa->ip_param_name,
11890 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11891 				nd_free(ndp);
11892 				return (B_FALSE);
11893 			}
11894 		}
11895 	}
11896 
11897 	for (; ipnd_cnt-- > 0; ipnd++) {
11898 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11899 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11900 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11901 			    ipnd->ip_ndp_data)) {
11902 				nd_free(ndp);
11903 				return (B_FALSE);
11904 			}
11905 		}
11906 	}
11907 
11908 	return (B_TRUE);
11909 }
11910 
11911 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11912 /* ARGSUSED */
11913 static int
11914 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11915 {
11916 	long		new_value;
11917 	ipparam_t	*ippa = (ipparam_t *)cp;
11918 
11919 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11920 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11921 		return (EINVAL);
11922 	}
11923 	ippa->ip_param_value = new_value;
11924 	return (0);
11925 }
11926 
11927 /*
11928  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11929  * When an ipf is passed here for the first time, if
11930  * we already have in-order fragments on the queue, we convert from the fast-
11931  * path reassembly scheme to the hard-case scheme.  From then on, additional
11932  * fragments are reassembled here.  We keep track of the start and end offsets
11933  * of each piece, and the number of holes in the chain.  When the hole count
11934  * goes to zero, we are done!
11935  *
11936  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11937  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11938  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11939  * after the call to ip_reassemble().
11940  */
11941 int
11942 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11943     size_t msg_len)
11944 {
11945 	uint_t	end;
11946 	mblk_t	*next_mp;
11947 	mblk_t	*mp1;
11948 	uint_t	offset;
11949 	boolean_t incr_dups = B_TRUE;
11950 	boolean_t offset_zero_seen = B_FALSE;
11951 	boolean_t pkt_boundary_checked = B_FALSE;
11952 
11953 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11954 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11955 
11956 	/* Add in byte count */
11957 	ipf->ipf_count += msg_len;
11958 	if (ipf->ipf_end) {
11959 		/*
11960 		 * We were part way through in-order reassembly, but now there
11961 		 * is a hole.  We walk through messages already queued, and
11962 		 * mark them for hard case reassembly.  We know that up till
11963 		 * now they were in order starting from offset zero.
11964 		 */
11965 		offset = 0;
11966 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11967 			IP_REASS_SET_START(mp1, offset);
11968 			if (offset == 0) {
11969 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11970 				offset = -ipf->ipf_nf_hdr_len;
11971 			}
11972 			offset += mp1->b_wptr - mp1->b_rptr;
11973 			IP_REASS_SET_END(mp1, offset);
11974 		}
11975 		/* One hole at the end. */
11976 		ipf->ipf_hole_cnt = 1;
11977 		/* Brand it as a hard case, forever. */
11978 		ipf->ipf_end = 0;
11979 	}
11980 	/* Walk through all the new pieces. */
11981 	do {
11982 		end = start + (mp->b_wptr - mp->b_rptr);
11983 		/*
11984 		 * If start is 0, decrease 'end' only for the first mblk of
11985 		 * the fragment. Otherwise 'end' can get wrong value in the
11986 		 * second pass of the loop if first mblk is exactly the
11987 		 * size of ipf_nf_hdr_len.
11988 		 */
11989 		if (start == 0 && !offset_zero_seen) {
11990 			/* First segment */
11991 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11992 			end -= ipf->ipf_nf_hdr_len;
11993 			offset_zero_seen = B_TRUE;
11994 		}
11995 		next_mp = mp->b_cont;
11996 		/*
11997 		 * We are checking to see if there is any interesing data
11998 		 * to process.  If there isn't and the mblk isn't the
11999 		 * one which carries the unfragmentable header then we
12000 		 * drop it.  It's possible to have just the unfragmentable
12001 		 * header come through without any data.  That needs to be
12002 		 * saved.
12003 		 *
12004 		 * If the assert at the top of this function holds then the
12005 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
12006 		 * is infrequently traveled enough that the test is left in
12007 		 * to protect against future code changes which break that
12008 		 * invariant.
12009 		 */
12010 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
12011 			/* Empty.  Blast it. */
12012 			IP_REASS_SET_START(mp, 0);
12013 			IP_REASS_SET_END(mp, 0);
12014 			/*
12015 			 * If the ipf points to the mblk we are about to free,
12016 			 * update ipf to point to the next mblk (or NULL
12017 			 * if none).
12018 			 */
12019 			if (ipf->ipf_mp->b_cont == mp)
12020 				ipf->ipf_mp->b_cont = next_mp;
12021 			freeb(mp);
12022 			continue;
12023 		}
12024 		mp->b_cont = NULL;
12025 		IP_REASS_SET_START(mp, start);
12026 		IP_REASS_SET_END(mp, end);
12027 		if (!ipf->ipf_tail_mp) {
12028 			ipf->ipf_tail_mp = mp;
12029 			ipf->ipf_mp->b_cont = mp;
12030 			if (start == 0 || !more) {
12031 				ipf->ipf_hole_cnt = 1;
12032 				/*
12033 				 * if the first fragment comes in more than one
12034 				 * mblk, this loop will be executed for each
12035 				 * mblk. Need to adjust hole count so exiting
12036 				 * this routine will leave hole count at 1.
12037 				 */
12038 				if (next_mp)
12039 					ipf->ipf_hole_cnt++;
12040 			} else
12041 				ipf->ipf_hole_cnt = 2;
12042 			continue;
12043 		} else if (ipf->ipf_last_frag_seen && !more &&
12044 		    !pkt_boundary_checked) {
12045 			/*
12046 			 * We check datagram boundary only if this fragment
12047 			 * claims to be the last fragment and we have seen a
12048 			 * last fragment in the past too. We do this only
12049 			 * once for a given fragment.
12050 			 *
12051 			 * start cannot be 0 here as fragments with start=0
12052 			 * and MF=0 gets handled as a complete packet. These
12053 			 * fragments should not reach here.
12054 			 */
12055 
12056 			if (start + msgdsize(mp) !=
12057 			    IP_REASS_END(ipf->ipf_tail_mp)) {
12058 				/*
12059 				 * We have two fragments both of which claim
12060 				 * to be the last fragment but gives conflicting
12061 				 * information about the whole datagram size.
12062 				 * Something fishy is going on. Drop the
12063 				 * fragment and free up the reassembly list.
12064 				 */
12065 				return (IP_REASS_FAILED);
12066 			}
12067 
12068 			/*
12069 			 * We shouldn't come to this code block again for this
12070 			 * particular fragment.
12071 			 */
12072 			pkt_boundary_checked = B_TRUE;
12073 		}
12074 
12075 		/* New stuff at or beyond tail? */
12076 		offset = IP_REASS_END(ipf->ipf_tail_mp);
12077 		if (start >= offset) {
12078 			if (ipf->ipf_last_frag_seen) {
12079 				/* current fragment is beyond last fragment */
12080 				return (IP_REASS_FAILED);
12081 			}
12082 			/* Link it on end. */
12083 			ipf->ipf_tail_mp->b_cont = mp;
12084 			ipf->ipf_tail_mp = mp;
12085 			if (more) {
12086 				if (start != offset)
12087 					ipf->ipf_hole_cnt++;
12088 			} else if (start == offset && next_mp == NULL)
12089 					ipf->ipf_hole_cnt--;
12090 			continue;
12091 		}
12092 		mp1 = ipf->ipf_mp->b_cont;
12093 		offset = IP_REASS_START(mp1);
12094 		/* New stuff at the front? */
12095 		if (start < offset) {
12096 			if (start == 0) {
12097 				if (end >= offset) {
12098 					/* Nailed the hole at the begining. */
12099 					ipf->ipf_hole_cnt--;
12100 				}
12101 			} else if (end < offset) {
12102 				/*
12103 				 * A hole, stuff, and a hole where there used
12104 				 * to be just a hole.
12105 				 */
12106 				ipf->ipf_hole_cnt++;
12107 			}
12108 			mp->b_cont = mp1;
12109 			/* Check for overlap. */
12110 			while (end > offset) {
12111 				if (end < IP_REASS_END(mp1)) {
12112 					mp->b_wptr -= end - offset;
12113 					IP_REASS_SET_END(mp, offset);
12114 					BUMP_MIB(ill->ill_ip_mib,
12115 					    ipIfStatsReasmPartDups);
12116 					break;
12117 				}
12118 				/* Did we cover another hole? */
12119 				if ((mp1->b_cont &&
12120 				    IP_REASS_END(mp1) !=
12121 				    IP_REASS_START(mp1->b_cont) &&
12122 				    end >= IP_REASS_START(mp1->b_cont)) ||
12123 				    (!ipf->ipf_last_frag_seen && !more)) {
12124 					ipf->ipf_hole_cnt--;
12125 				}
12126 				/* Clip out mp1. */
12127 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12128 					/*
12129 					 * After clipping out mp1, this guy
12130 					 * is now hanging off the end.
12131 					 */
12132 					ipf->ipf_tail_mp = mp;
12133 				}
12134 				IP_REASS_SET_START(mp1, 0);
12135 				IP_REASS_SET_END(mp1, 0);
12136 				/* Subtract byte count */
12137 				ipf->ipf_count -= mp1->b_datap->db_lim -
12138 				    mp1->b_datap->db_base;
12139 				freeb(mp1);
12140 				BUMP_MIB(ill->ill_ip_mib,
12141 				    ipIfStatsReasmPartDups);
12142 				mp1 = mp->b_cont;
12143 				if (!mp1)
12144 					break;
12145 				offset = IP_REASS_START(mp1);
12146 			}
12147 			ipf->ipf_mp->b_cont = mp;
12148 			continue;
12149 		}
12150 		/*
12151 		 * The new piece starts somewhere between the start of the head
12152 		 * and before the end of the tail.
12153 		 */
12154 		for (; mp1; mp1 = mp1->b_cont) {
12155 			offset = IP_REASS_END(mp1);
12156 			if (start < offset) {
12157 				if (end <= offset) {
12158 					/* Nothing new. */
12159 					IP_REASS_SET_START(mp, 0);
12160 					IP_REASS_SET_END(mp, 0);
12161 					/* Subtract byte count */
12162 					ipf->ipf_count -= mp->b_datap->db_lim -
12163 					    mp->b_datap->db_base;
12164 					if (incr_dups) {
12165 						ipf->ipf_num_dups++;
12166 						incr_dups = B_FALSE;
12167 					}
12168 					freeb(mp);
12169 					BUMP_MIB(ill->ill_ip_mib,
12170 					    ipIfStatsReasmDuplicates);
12171 					break;
12172 				}
12173 				/*
12174 				 * Trim redundant stuff off beginning of new
12175 				 * piece.
12176 				 */
12177 				IP_REASS_SET_START(mp, offset);
12178 				mp->b_rptr += offset - start;
12179 				BUMP_MIB(ill->ill_ip_mib,
12180 				    ipIfStatsReasmPartDups);
12181 				start = offset;
12182 				if (!mp1->b_cont) {
12183 					/*
12184 					 * After trimming, this guy is now
12185 					 * hanging off the end.
12186 					 */
12187 					mp1->b_cont = mp;
12188 					ipf->ipf_tail_mp = mp;
12189 					if (!more) {
12190 						ipf->ipf_hole_cnt--;
12191 					}
12192 					break;
12193 				}
12194 			}
12195 			if (start >= IP_REASS_START(mp1->b_cont))
12196 				continue;
12197 			/* Fill a hole */
12198 			if (start > offset)
12199 				ipf->ipf_hole_cnt++;
12200 			mp->b_cont = mp1->b_cont;
12201 			mp1->b_cont = mp;
12202 			mp1 = mp->b_cont;
12203 			offset = IP_REASS_START(mp1);
12204 			if (end >= offset) {
12205 				ipf->ipf_hole_cnt--;
12206 				/* Check for overlap. */
12207 				while (end > offset) {
12208 					if (end < IP_REASS_END(mp1)) {
12209 						mp->b_wptr -= end - offset;
12210 						IP_REASS_SET_END(mp, offset);
12211 						/*
12212 						 * TODO we might bump
12213 						 * this up twice if there is
12214 						 * overlap at both ends.
12215 						 */
12216 						BUMP_MIB(ill->ill_ip_mib,
12217 						    ipIfStatsReasmPartDups);
12218 						break;
12219 					}
12220 					/* Did we cover another hole? */
12221 					if ((mp1->b_cont &&
12222 					    IP_REASS_END(mp1)
12223 					    != IP_REASS_START(mp1->b_cont) &&
12224 					    end >=
12225 					    IP_REASS_START(mp1->b_cont)) ||
12226 					    (!ipf->ipf_last_frag_seen &&
12227 					    !more)) {
12228 						ipf->ipf_hole_cnt--;
12229 					}
12230 					/* Clip out mp1. */
12231 					if ((mp->b_cont = mp1->b_cont) ==
12232 					    NULL) {
12233 						/*
12234 						 * After clipping out mp1,
12235 						 * this guy is now hanging
12236 						 * off the end.
12237 						 */
12238 						ipf->ipf_tail_mp = mp;
12239 					}
12240 					IP_REASS_SET_START(mp1, 0);
12241 					IP_REASS_SET_END(mp1, 0);
12242 					/* Subtract byte count */
12243 					ipf->ipf_count -=
12244 					    mp1->b_datap->db_lim -
12245 					    mp1->b_datap->db_base;
12246 					freeb(mp1);
12247 					BUMP_MIB(ill->ill_ip_mib,
12248 					    ipIfStatsReasmPartDups);
12249 					mp1 = mp->b_cont;
12250 					if (!mp1)
12251 						break;
12252 					offset = IP_REASS_START(mp1);
12253 				}
12254 			}
12255 			break;
12256 		}
12257 	} while (start = end, mp = next_mp);
12258 
12259 	/* Fragment just processed could be the last one. Remember this fact */
12260 	if (!more)
12261 		ipf->ipf_last_frag_seen = B_TRUE;
12262 
12263 	/* Still got holes? */
12264 	if (ipf->ipf_hole_cnt)
12265 		return (IP_REASS_PARTIAL);
12266 	/* Clean up overloaded fields to avoid upstream disasters. */
12267 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12268 		IP_REASS_SET_START(mp1, 0);
12269 		IP_REASS_SET_END(mp1, 0);
12270 	}
12271 	return (IP_REASS_COMPLETE);
12272 }
12273 
12274 /*
12275  * ipsec processing for the fast path, used for input UDP Packets
12276  */
12277 static boolean_t
12278 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12279     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12280 {
12281 	uint32_t	ill_index;
12282 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12283 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12284 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12285 
12286 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12287 	/* The ill_index of the incoming ILL */
12288 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12289 
12290 	/* pass packet up to the transport */
12291 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12292 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12293 		    NULL, mctl_present);
12294 		if (*first_mpp == NULL) {
12295 			return (B_FALSE);
12296 		}
12297 	}
12298 
12299 	/* Initiate IPPF processing for fastpath UDP */
12300 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12301 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12302 		if (*mpp == NULL) {
12303 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12304 			    "deferred/dropped during IPPF processing\n"));
12305 			return (B_FALSE);
12306 		}
12307 	}
12308 	/*
12309 	 * We make the checks as below since we are in the fast path
12310 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12311 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12312 	 */
12313 	if (connp->conn_recvif || connp->conn_recvslla ||
12314 	    connp->conn_ip_recvpktinfo) {
12315 		if (connp->conn_recvif) {
12316 			in_flags = IPF_RECVIF;
12317 		}
12318 		/*
12319 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12320 		 * so the flag passed to ip_add_info is based on IP version
12321 		 * of connp.
12322 		 */
12323 		if (connp->conn_ip_recvpktinfo) {
12324 			if (connp->conn_af_isv6) {
12325 				/*
12326 				 * V6 only needs index
12327 				 */
12328 				in_flags |= IPF_RECVIF;
12329 			} else {
12330 				/*
12331 				 * V4 needs index + matching address.
12332 				 */
12333 				in_flags |= IPF_RECVADDR;
12334 			}
12335 		}
12336 		if (connp->conn_recvslla) {
12337 			in_flags |= IPF_RECVSLLA;
12338 		}
12339 		/*
12340 		 * since in_flags are being set ill will be
12341 		 * referenced in ip_add_info, so it better not
12342 		 * be NULL.
12343 		 */
12344 		/*
12345 		 * the actual data will be contained in b_cont
12346 		 * upon successful return of the following call.
12347 		 * If the call fails then the original mblk is
12348 		 * returned.
12349 		 */
12350 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12351 		    ipst);
12352 	}
12353 
12354 	return (B_TRUE);
12355 }
12356 
12357 /*
12358  * Fragmentation reassembly.  Each ILL has a hash table for
12359  * queuing packets undergoing reassembly for all IPIFs
12360  * associated with the ILL.  The hash is based on the packet
12361  * IP ident field.  The ILL frag hash table was allocated
12362  * as a timer block at the time the ILL was created.  Whenever
12363  * there is anything on the reassembly queue, the timer will
12364  * be running.  Returns B_TRUE if successful else B_FALSE;
12365  * frees mp on failure.
12366  */
12367 static boolean_t
12368 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12369     uint32_t *cksum_val, uint16_t *cksum_flags)
12370 {
12371 	uint32_t	frag_offset_flags;
12372 	ill_t		*ill = (ill_t *)q->q_ptr;
12373 	mblk_t		*mp = *mpp;
12374 	mblk_t		*t_mp;
12375 	ipaddr_t	dst;
12376 	uint8_t		proto = ipha->ipha_protocol;
12377 	uint32_t	sum_val;
12378 	uint16_t	sum_flags;
12379 	ipf_t		*ipf;
12380 	ipf_t		**ipfp;
12381 	ipfb_t		*ipfb;
12382 	uint16_t	ident;
12383 	uint32_t	offset;
12384 	ipaddr_t	src;
12385 	uint_t		hdr_length;
12386 	uint32_t	end;
12387 	mblk_t		*mp1;
12388 	mblk_t		*tail_mp;
12389 	size_t		count;
12390 	size_t		msg_len;
12391 	uint8_t		ecn_info = 0;
12392 	uint32_t	packet_size;
12393 	boolean_t	pruned = B_FALSE;
12394 	ip_stack_t *ipst = ill->ill_ipst;
12395 
12396 	if (cksum_val != NULL)
12397 		*cksum_val = 0;
12398 	if (cksum_flags != NULL)
12399 		*cksum_flags = 0;
12400 
12401 	/*
12402 	 * Drop the fragmented as early as possible, if
12403 	 * we don't have resource(s) to re-assemble.
12404 	 */
12405 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12406 		freemsg(mp);
12407 		return (B_FALSE);
12408 	}
12409 
12410 	/* Check for fragmentation offset; return if there's none */
12411 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12412 	    (IPH_MF | IPH_OFFSET)) == 0)
12413 		return (B_TRUE);
12414 
12415 	/*
12416 	 * We utilize hardware computed checksum info only for UDP since
12417 	 * IP fragmentation is a normal occurence for the protocol.  In
12418 	 * addition, checksum offload support for IP fragments carrying
12419 	 * UDP payload is commonly implemented across network adapters.
12420 	 */
12421 	ASSERT(ill != NULL);
12422 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12423 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12424 		mblk_t *mp1 = mp->b_cont;
12425 		int32_t len;
12426 
12427 		/* Record checksum information from the packet */
12428 		sum_val = (uint32_t)DB_CKSUM16(mp);
12429 		sum_flags = DB_CKSUMFLAGS(mp);
12430 
12431 		/* IP payload offset from beginning of mblk */
12432 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12433 
12434 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12435 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12436 		    offset >= DB_CKSUMSTART(mp) &&
12437 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12438 			uint32_t adj;
12439 			/*
12440 			 * Partial checksum has been calculated by hardware
12441 			 * and attached to the packet; in addition, any
12442 			 * prepended extraneous data is even byte aligned.
12443 			 * If any such data exists, we adjust the checksum;
12444 			 * this would also handle any postpended data.
12445 			 */
12446 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12447 			    mp, mp1, len, adj);
12448 
12449 			/* One's complement subtract extraneous checksum */
12450 			if (adj >= sum_val)
12451 				sum_val = ~(adj - sum_val) & 0xFFFF;
12452 			else
12453 				sum_val -= adj;
12454 		}
12455 	} else {
12456 		sum_val = 0;
12457 		sum_flags = 0;
12458 	}
12459 
12460 	/* Clear hardware checksumming flag */
12461 	DB_CKSUMFLAGS(mp) = 0;
12462 
12463 	ident = ipha->ipha_ident;
12464 	offset = (frag_offset_flags << 3) & 0xFFFF;
12465 	src = ipha->ipha_src;
12466 	dst = ipha->ipha_dst;
12467 	hdr_length = IPH_HDR_LENGTH(ipha);
12468 	end = ntohs(ipha->ipha_length) - hdr_length;
12469 
12470 	/* If end == 0 then we have a packet with no data, so just free it */
12471 	if (end == 0) {
12472 		freemsg(mp);
12473 		return (B_FALSE);
12474 	}
12475 
12476 	/* Record the ECN field info. */
12477 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12478 	if (offset != 0) {
12479 		/*
12480 		 * If this isn't the first piece, strip the header, and
12481 		 * add the offset to the end value.
12482 		 */
12483 		mp->b_rptr += hdr_length;
12484 		end += offset;
12485 	}
12486 
12487 	msg_len = MBLKSIZE(mp);
12488 	tail_mp = mp;
12489 	while (tail_mp->b_cont != NULL) {
12490 		tail_mp = tail_mp->b_cont;
12491 		msg_len += MBLKSIZE(tail_mp);
12492 	}
12493 
12494 	/* If the reassembly list for this ILL will get too big, prune it */
12495 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12496 	    ipst->ips_ip_reass_queue_bytes) {
12497 		ill_frag_prune(ill,
12498 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12499 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12500 		pruned = B_TRUE;
12501 	}
12502 
12503 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12504 	mutex_enter(&ipfb->ipfb_lock);
12505 
12506 	ipfp = &ipfb->ipfb_ipf;
12507 	/* Try to find an existing fragment queue for this packet. */
12508 	for (;;) {
12509 		ipf = ipfp[0];
12510 		if (ipf != NULL) {
12511 			/*
12512 			 * It has to match on ident and src/dst address.
12513 			 */
12514 			if (ipf->ipf_ident == ident &&
12515 			    ipf->ipf_src == src &&
12516 			    ipf->ipf_dst == dst &&
12517 			    ipf->ipf_protocol == proto) {
12518 				/*
12519 				 * If we have received too many
12520 				 * duplicate fragments for this packet
12521 				 * free it.
12522 				 */
12523 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12524 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12525 					freemsg(mp);
12526 					mutex_exit(&ipfb->ipfb_lock);
12527 					return (B_FALSE);
12528 				}
12529 				/* Found it. */
12530 				break;
12531 			}
12532 			ipfp = &ipf->ipf_hash_next;
12533 			continue;
12534 		}
12535 
12536 		/*
12537 		 * If we pruned the list, do we want to store this new
12538 		 * fragment?. We apply an optimization here based on the
12539 		 * fact that most fragments will be received in order.
12540 		 * So if the offset of this incoming fragment is zero,
12541 		 * it is the first fragment of a new packet. We will
12542 		 * keep it.  Otherwise drop the fragment, as we have
12543 		 * probably pruned the packet already (since the
12544 		 * packet cannot be found).
12545 		 */
12546 		if (pruned && offset != 0) {
12547 			mutex_exit(&ipfb->ipfb_lock);
12548 			freemsg(mp);
12549 			return (B_FALSE);
12550 		}
12551 
12552 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12553 			/*
12554 			 * Too many fragmented packets in this hash
12555 			 * bucket. Free the oldest.
12556 			 */
12557 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12558 		}
12559 
12560 		/* New guy.  Allocate a frag message. */
12561 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12562 		if (mp1 == NULL) {
12563 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12564 			freemsg(mp);
12565 reass_done:
12566 			mutex_exit(&ipfb->ipfb_lock);
12567 			return (B_FALSE);
12568 		}
12569 
12570 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12571 		mp1->b_cont = mp;
12572 
12573 		/* Initialize the fragment header. */
12574 		ipf = (ipf_t *)mp1->b_rptr;
12575 		ipf->ipf_mp = mp1;
12576 		ipf->ipf_ptphn = ipfp;
12577 		ipfp[0] = ipf;
12578 		ipf->ipf_hash_next = NULL;
12579 		ipf->ipf_ident = ident;
12580 		ipf->ipf_protocol = proto;
12581 		ipf->ipf_src = src;
12582 		ipf->ipf_dst = dst;
12583 		ipf->ipf_nf_hdr_len = 0;
12584 		/* Record reassembly start time. */
12585 		ipf->ipf_timestamp = gethrestime_sec();
12586 		/* Record ipf generation and account for frag header */
12587 		ipf->ipf_gen = ill->ill_ipf_gen++;
12588 		ipf->ipf_count = MBLKSIZE(mp1);
12589 		ipf->ipf_last_frag_seen = B_FALSE;
12590 		ipf->ipf_ecn = ecn_info;
12591 		ipf->ipf_num_dups = 0;
12592 		ipfb->ipfb_frag_pkts++;
12593 		ipf->ipf_checksum = 0;
12594 		ipf->ipf_checksum_flags = 0;
12595 
12596 		/* Store checksum value in fragment header */
12597 		if (sum_flags != 0) {
12598 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12599 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12600 			ipf->ipf_checksum = sum_val;
12601 			ipf->ipf_checksum_flags = sum_flags;
12602 		}
12603 
12604 		/*
12605 		 * We handle reassembly two ways.  In the easy case,
12606 		 * where all the fragments show up in order, we do
12607 		 * minimal bookkeeping, and just clip new pieces on
12608 		 * the end.  If we ever see a hole, then we go off
12609 		 * to ip_reassemble which has to mark the pieces and
12610 		 * keep track of the number of holes, etc.  Obviously,
12611 		 * the point of having both mechanisms is so we can
12612 		 * handle the easy case as efficiently as possible.
12613 		 */
12614 		if (offset == 0) {
12615 			/* Easy case, in-order reassembly so far. */
12616 			ipf->ipf_count += msg_len;
12617 			ipf->ipf_tail_mp = tail_mp;
12618 			/*
12619 			 * Keep track of next expected offset in
12620 			 * ipf_end.
12621 			 */
12622 			ipf->ipf_end = end;
12623 			ipf->ipf_nf_hdr_len = hdr_length;
12624 		} else {
12625 			/* Hard case, hole at the beginning. */
12626 			ipf->ipf_tail_mp = NULL;
12627 			/*
12628 			 * ipf_end == 0 means that we have given up
12629 			 * on easy reassembly.
12630 			 */
12631 			ipf->ipf_end = 0;
12632 
12633 			/* Forget checksum offload from now on */
12634 			ipf->ipf_checksum_flags = 0;
12635 
12636 			/*
12637 			 * ipf_hole_cnt is set by ip_reassemble.
12638 			 * ipf_count is updated by ip_reassemble.
12639 			 * No need to check for return value here
12640 			 * as we don't expect reassembly to complete
12641 			 * or fail for the first fragment itself.
12642 			 */
12643 			(void) ip_reassemble(mp, ipf,
12644 			    (frag_offset_flags & IPH_OFFSET) << 3,
12645 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12646 		}
12647 		/* Update per ipfb and ill byte counts */
12648 		ipfb->ipfb_count += ipf->ipf_count;
12649 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12650 		ill->ill_frag_count += ipf->ipf_count;
12651 		/* If the frag timer wasn't already going, start it. */
12652 		mutex_enter(&ill->ill_lock);
12653 		ill_frag_timer_start(ill);
12654 		mutex_exit(&ill->ill_lock);
12655 		goto reass_done;
12656 	}
12657 
12658 	/*
12659 	 * If the packet's flag has changed (it could be coming up
12660 	 * from an interface different than the previous, therefore
12661 	 * possibly different checksum capability), then forget about
12662 	 * any stored checksum states.  Otherwise add the value to
12663 	 * the existing one stored in the fragment header.
12664 	 */
12665 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12666 		sum_val += ipf->ipf_checksum;
12667 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12668 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12669 		ipf->ipf_checksum = sum_val;
12670 	} else if (ipf->ipf_checksum_flags != 0) {
12671 		/* Forget checksum offload from now on */
12672 		ipf->ipf_checksum_flags = 0;
12673 	}
12674 
12675 	/*
12676 	 * We have a new piece of a datagram which is already being
12677 	 * reassembled.  Update the ECN info if all IP fragments
12678 	 * are ECN capable.  If there is one which is not, clear
12679 	 * all the info.  If there is at least one which has CE
12680 	 * code point, IP needs to report that up to transport.
12681 	 */
12682 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12683 		if (ecn_info == IPH_ECN_CE)
12684 			ipf->ipf_ecn = IPH_ECN_CE;
12685 	} else {
12686 		ipf->ipf_ecn = IPH_ECN_NECT;
12687 	}
12688 	if (offset && ipf->ipf_end == offset) {
12689 		/* The new fragment fits at the end */
12690 		ipf->ipf_tail_mp->b_cont = mp;
12691 		/* Update the byte count */
12692 		ipf->ipf_count += msg_len;
12693 		/* Update per ipfb and ill byte counts */
12694 		ipfb->ipfb_count += msg_len;
12695 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12696 		ill->ill_frag_count += msg_len;
12697 		if (frag_offset_flags & IPH_MF) {
12698 			/* More to come. */
12699 			ipf->ipf_end = end;
12700 			ipf->ipf_tail_mp = tail_mp;
12701 			goto reass_done;
12702 		}
12703 	} else {
12704 		/* Go do the hard cases. */
12705 		int ret;
12706 
12707 		if (offset == 0)
12708 			ipf->ipf_nf_hdr_len = hdr_length;
12709 
12710 		/* Save current byte count */
12711 		count = ipf->ipf_count;
12712 		ret = ip_reassemble(mp, ipf,
12713 		    (frag_offset_flags & IPH_OFFSET) << 3,
12714 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12715 		/* Count of bytes added and subtracted (freeb()ed) */
12716 		count = ipf->ipf_count - count;
12717 		if (count) {
12718 			/* Update per ipfb and ill byte counts */
12719 			ipfb->ipfb_count += count;
12720 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12721 			ill->ill_frag_count += count;
12722 		}
12723 		if (ret == IP_REASS_PARTIAL) {
12724 			goto reass_done;
12725 		} else if (ret == IP_REASS_FAILED) {
12726 			/* Reassembly failed. Free up all resources */
12727 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12728 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12729 				IP_REASS_SET_START(t_mp, 0);
12730 				IP_REASS_SET_END(t_mp, 0);
12731 			}
12732 			freemsg(mp);
12733 			goto reass_done;
12734 		}
12735 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12736 	}
12737 	/*
12738 	 * We have completed reassembly.  Unhook the frag header from
12739 	 * the reassembly list.
12740 	 *
12741 	 * Before we free the frag header, record the ECN info
12742 	 * to report back to the transport.
12743 	 */
12744 	ecn_info = ipf->ipf_ecn;
12745 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12746 	ipfp = ipf->ipf_ptphn;
12747 
12748 	/* We need to supply these to caller */
12749 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12750 		sum_val = ipf->ipf_checksum;
12751 	else
12752 		sum_val = 0;
12753 
12754 	mp1 = ipf->ipf_mp;
12755 	count = ipf->ipf_count;
12756 	ipf = ipf->ipf_hash_next;
12757 	if (ipf != NULL)
12758 		ipf->ipf_ptphn = ipfp;
12759 	ipfp[0] = ipf;
12760 	ill->ill_frag_count -= count;
12761 	ASSERT(ipfb->ipfb_count >= count);
12762 	ipfb->ipfb_count -= count;
12763 	ipfb->ipfb_frag_pkts--;
12764 	mutex_exit(&ipfb->ipfb_lock);
12765 	/* Ditch the frag header. */
12766 	mp = mp1->b_cont;
12767 
12768 	freeb(mp1);
12769 
12770 	/* Restore original IP length in header. */
12771 	packet_size = (uint32_t)msgdsize(mp);
12772 	if (packet_size > IP_MAXPACKET) {
12773 		freemsg(mp);
12774 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12775 		return (B_FALSE);
12776 	}
12777 
12778 	if (DB_REF(mp) > 1) {
12779 		mblk_t *mp2 = copymsg(mp);
12780 
12781 		freemsg(mp);
12782 		if (mp2 == NULL) {
12783 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12784 			return (B_FALSE);
12785 		}
12786 		mp = mp2;
12787 	}
12788 	ipha = (ipha_t *)mp->b_rptr;
12789 
12790 	ipha->ipha_length = htons((uint16_t)packet_size);
12791 	/* We're now complete, zip the frag state */
12792 	ipha->ipha_fragment_offset_and_flags = 0;
12793 	/* Record the ECN info. */
12794 	ipha->ipha_type_of_service &= 0xFC;
12795 	ipha->ipha_type_of_service |= ecn_info;
12796 	*mpp = mp;
12797 
12798 	/* Reassembly is successful; return checksum information if needed */
12799 	if (cksum_val != NULL)
12800 		*cksum_val = sum_val;
12801 	if (cksum_flags != NULL)
12802 		*cksum_flags = sum_flags;
12803 
12804 	return (B_TRUE);
12805 }
12806 
12807 /*
12808  * Perform ip header check sum update local options.
12809  * return B_TRUE if all is well, else return B_FALSE and release
12810  * the mp. caller is responsible for decrementing ire ref cnt.
12811  */
12812 static boolean_t
12813 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12814     ip_stack_t *ipst)
12815 {
12816 	mblk_t		*first_mp;
12817 	boolean_t	mctl_present;
12818 	uint16_t	sum;
12819 
12820 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12821 	/*
12822 	 * Don't do the checksum if it has gone through AH/ESP
12823 	 * processing.
12824 	 */
12825 	if (!mctl_present) {
12826 		sum = ip_csum_hdr(ipha);
12827 		if (sum != 0) {
12828 			if (ill != NULL) {
12829 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12830 			} else {
12831 				BUMP_MIB(&ipst->ips_ip_mib,
12832 				    ipIfStatsInCksumErrs);
12833 			}
12834 			freemsg(first_mp);
12835 			return (B_FALSE);
12836 		}
12837 	}
12838 
12839 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12840 		if (mctl_present)
12841 			freeb(first_mp);
12842 		return (B_FALSE);
12843 	}
12844 
12845 	return (B_TRUE);
12846 }
12847 
12848 /*
12849  * All udp packet are delivered to the local host via this routine.
12850  */
12851 void
12852 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12853     ill_t *recv_ill)
12854 {
12855 	uint32_t	sum;
12856 	uint32_t	u1;
12857 	boolean_t	mctl_present;
12858 	conn_t		*connp;
12859 	mblk_t		*first_mp;
12860 	uint16_t	*up;
12861 	ill_t		*ill = (ill_t *)q->q_ptr;
12862 	uint16_t	reass_hck_flags = 0;
12863 	ip_stack_t	*ipst;
12864 
12865 	ASSERT(recv_ill != NULL);
12866 	ipst = recv_ill->ill_ipst;
12867 
12868 #define	rptr    ((uchar_t *)ipha)
12869 
12870 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12871 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12872 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12873 	ASSERT(ill != NULL);
12874 
12875 	/*
12876 	 * FAST PATH for udp packets
12877 	 */
12878 
12879 	/* u1 is # words of IP options */
12880 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12881 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12882 
12883 	/* IP options present */
12884 	if (u1 != 0)
12885 		goto ipoptions;
12886 
12887 	/* Check the IP header checksum.  */
12888 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12889 		/* Clear the IP header h/w cksum flag */
12890 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12891 	} else {
12892 #define	uph	((uint16_t *)ipha)
12893 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12894 		    uph[6] + uph[7] + uph[8] + uph[9];
12895 #undef	uph
12896 		/* finish doing IP checksum */
12897 		sum = (sum & 0xFFFF) + (sum >> 16);
12898 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12899 		/*
12900 		 * Don't verify header checksum if this packet is coming
12901 		 * back from AH/ESP as we already did it.
12902 		 */
12903 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12904 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12905 			freemsg(first_mp);
12906 			return;
12907 		}
12908 	}
12909 
12910 	/*
12911 	 * Count for SNMP of inbound packets for ire.
12912 	 * if mctl is present this might be a secure packet and
12913 	 * has already been counted for in ip_proto_input().
12914 	 */
12915 	if (!mctl_present) {
12916 		UPDATE_IB_PKT_COUNT(ire);
12917 		ire->ire_last_used_time = lbolt;
12918 	}
12919 
12920 	/* packet part of fragmented IP packet? */
12921 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12922 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12923 		goto fragmented;
12924 	}
12925 
12926 	/* u1 = IP header length (20 bytes) */
12927 	u1 = IP_SIMPLE_HDR_LENGTH;
12928 
12929 	/* packet does not contain complete IP & UDP headers */
12930 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12931 		goto udppullup;
12932 
12933 	/* up points to UDP header */
12934 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12935 #define	iphs    ((uint16_t *)ipha)
12936 
12937 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12938 	if (up[3] != 0) {
12939 		mblk_t *mp1 = mp->b_cont;
12940 		boolean_t cksum_err;
12941 		uint16_t hck_flags = 0;
12942 
12943 		/* Pseudo-header checksum */
12944 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12945 		    iphs[9] + up[2];
12946 
12947 		/*
12948 		 * Revert to software checksum calculation if the interface
12949 		 * isn't capable of checksum offload or if IPsec is present.
12950 		 */
12951 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12952 			hck_flags = DB_CKSUMFLAGS(mp);
12953 
12954 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12955 			IP_STAT(ipst, ip_in_sw_cksum);
12956 
12957 		IP_CKSUM_RECV(hck_flags, u1,
12958 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12959 		    (int32_t)((uchar_t *)up - rptr),
12960 		    mp, mp1, cksum_err);
12961 
12962 		if (cksum_err) {
12963 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12964 			if (hck_flags & HCK_FULLCKSUM)
12965 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12966 			else if (hck_flags & HCK_PARTIALCKSUM)
12967 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12968 			else
12969 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12970 
12971 			freemsg(first_mp);
12972 			return;
12973 		}
12974 	}
12975 
12976 	/* Non-fragmented broadcast or multicast packet? */
12977 	if (ire->ire_type == IRE_BROADCAST)
12978 		goto udpslowpath;
12979 
12980 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12981 	    ire->ire_zoneid, ipst)) != NULL) {
12982 		ASSERT(connp->conn_upq != NULL);
12983 		IP_STAT(ipst, ip_udp_fast_path);
12984 
12985 		if (CONN_UDP_FLOWCTLD(connp)) {
12986 			freemsg(mp);
12987 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12988 		} else {
12989 			if (!mctl_present) {
12990 				BUMP_MIB(ill->ill_ip_mib,
12991 				    ipIfStatsHCInDelivers);
12992 			}
12993 			/*
12994 			 * mp and first_mp can change.
12995 			 */
12996 			if (ip_udp_check(q, connp, recv_ill,
12997 			    ipha, &mp, &first_mp, mctl_present)) {
12998 				/* Send it upstream */
12999 				CONN_UDP_RECV(connp, mp);
13000 			}
13001 		}
13002 		/*
13003 		 * freeb() cannot deal with null mblk being passed
13004 		 * in and first_mp can be set to null in the call
13005 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
13006 		 */
13007 		if (mctl_present && first_mp != NULL) {
13008 			freeb(first_mp);
13009 		}
13010 		CONN_DEC_REF(connp);
13011 		return;
13012 	}
13013 
13014 	/*
13015 	 * if we got here we know the packet is not fragmented and
13016 	 * has no options. The classifier could not find a conn_t and
13017 	 * most likely its an icmp packet so send it through slow path.
13018 	 */
13019 
13020 	goto udpslowpath;
13021 
13022 ipoptions:
13023 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
13024 		goto slow_done;
13025 	}
13026 
13027 	UPDATE_IB_PKT_COUNT(ire);
13028 	ire->ire_last_used_time = lbolt;
13029 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13030 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13031 fragmented:
13032 		/*
13033 		 * "sum" and "reass_hck_flags" are non-zero if the
13034 		 * reassembled packet has a valid hardware computed
13035 		 * checksum information associated with it.
13036 		 */
13037 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
13038 			goto slow_done;
13039 		/*
13040 		 * Make sure that first_mp points back to mp as
13041 		 * the mp we came in with could have changed in
13042 		 * ip_rput_fragment().
13043 		 */
13044 		ASSERT(!mctl_present);
13045 		ipha = (ipha_t *)mp->b_rptr;
13046 		first_mp = mp;
13047 	}
13048 
13049 	/* Now we have a complete datagram, destined for this machine. */
13050 	u1 = IPH_HDR_LENGTH(ipha);
13051 	/* Pull up the UDP header, if necessary. */
13052 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
13053 udppullup:
13054 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
13055 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13056 			freemsg(first_mp);
13057 			goto slow_done;
13058 		}
13059 		ipha = (ipha_t *)mp->b_rptr;
13060 	}
13061 
13062 	/*
13063 	 * Validate the checksum for the reassembled packet; for the
13064 	 * pullup case we calculate the payload checksum in software.
13065 	 */
13066 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
13067 	if (up[3] != 0) {
13068 		boolean_t cksum_err;
13069 
13070 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13071 			IP_STAT(ipst, ip_in_sw_cksum);
13072 
13073 		IP_CKSUM_RECV_REASS(reass_hck_flags,
13074 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
13075 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13076 		    iphs[9] + up[2], sum, cksum_err);
13077 
13078 		if (cksum_err) {
13079 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13080 
13081 			if (reass_hck_flags & HCK_FULLCKSUM)
13082 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13083 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13084 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13085 			else
13086 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13087 
13088 			freemsg(first_mp);
13089 			goto slow_done;
13090 		}
13091 	}
13092 udpslowpath:
13093 
13094 	/* Clear hardware checksum flag to be safe */
13095 	DB_CKSUMFLAGS(mp) = 0;
13096 
13097 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13098 	    (ire->ire_type == IRE_BROADCAST),
13099 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13100 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13101 
13102 slow_done:
13103 	IP_STAT(ipst, ip_udp_slow_path);
13104 	return;
13105 
13106 #undef  iphs
13107 #undef  rptr
13108 }
13109 
13110 /* ARGSUSED */
13111 static mblk_t *
13112 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13113     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13114     ill_rx_ring_t *ill_ring)
13115 {
13116 	conn_t		*connp;
13117 	uint32_t	sum;
13118 	uint32_t	u1;
13119 	uint16_t	*up;
13120 	int		offset;
13121 	ssize_t		len;
13122 	mblk_t		*mp1;
13123 	boolean_t	syn_present = B_FALSE;
13124 	tcph_t		*tcph;
13125 	uint_t		ip_hdr_len;
13126 	ill_t		*ill = (ill_t *)q->q_ptr;
13127 	zoneid_t	zoneid = ire->ire_zoneid;
13128 	boolean_t	cksum_err;
13129 	uint16_t	hck_flags = 0;
13130 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13131 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13132 
13133 #define	rptr	((uchar_t *)ipha)
13134 
13135 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13136 	ASSERT(ill != NULL);
13137 
13138 	/*
13139 	 * FAST PATH for tcp packets
13140 	 */
13141 
13142 	/* u1 is # words of IP options */
13143 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13144 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13145 
13146 	/* IP options present */
13147 	if (u1) {
13148 		goto ipoptions;
13149 	} else {
13150 		/* Check the IP header checksum.  */
13151 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13152 			/* Clear the IP header h/w cksum flag */
13153 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13154 		} else {
13155 #define	uph	((uint16_t *)ipha)
13156 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13157 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13158 #undef	uph
13159 			/* finish doing IP checksum */
13160 			sum = (sum & 0xFFFF) + (sum >> 16);
13161 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13162 			/*
13163 			 * Don't verify header checksum if this packet
13164 			 * is coming back from AH/ESP as we already did it.
13165 			 */
13166 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13167 				BUMP_MIB(ill->ill_ip_mib,
13168 				    ipIfStatsInCksumErrs);
13169 				goto error;
13170 			}
13171 		}
13172 	}
13173 
13174 	if (!mctl_present) {
13175 		UPDATE_IB_PKT_COUNT(ire);
13176 		ire->ire_last_used_time = lbolt;
13177 	}
13178 
13179 	/* packet part of fragmented IP packet? */
13180 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13181 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13182 		goto fragmented;
13183 	}
13184 
13185 	/* u1 = IP header length (20 bytes) */
13186 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13187 
13188 	/* does packet contain IP+TCP headers? */
13189 	len = mp->b_wptr - rptr;
13190 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13191 		IP_STAT(ipst, ip_tcppullup);
13192 		goto tcppullup;
13193 	}
13194 
13195 	/* TCP options present? */
13196 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13197 
13198 	/*
13199 	 * If options need to be pulled up, then goto tcpoptions.
13200 	 * otherwise we are still in the fast path
13201 	 */
13202 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13203 		IP_STAT(ipst, ip_tcpoptions);
13204 		goto tcpoptions;
13205 	}
13206 
13207 	/* multiple mblks of tcp data? */
13208 	if ((mp1 = mp->b_cont) != NULL) {
13209 		/* more then two? */
13210 		if (mp1->b_cont != NULL) {
13211 			IP_STAT(ipst, ip_multipkttcp);
13212 			goto multipkttcp;
13213 		}
13214 		len += mp1->b_wptr - mp1->b_rptr;
13215 	}
13216 
13217 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13218 
13219 	/* part of pseudo checksum */
13220 
13221 	/* TCP datagram length */
13222 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13223 
13224 #define	iphs    ((uint16_t *)ipha)
13225 
13226 #ifdef	_BIG_ENDIAN
13227 	u1 += IPPROTO_TCP;
13228 #else
13229 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13230 #endif
13231 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13232 
13233 	/*
13234 	 * Revert to software checksum calculation if the interface
13235 	 * isn't capable of checksum offload or if IPsec is present.
13236 	 */
13237 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13238 		hck_flags = DB_CKSUMFLAGS(mp);
13239 
13240 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13241 		IP_STAT(ipst, ip_in_sw_cksum);
13242 
13243 	IP_CKSUM_RECV(hck_flags, u1,
13244 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13245 	    (int32_t)((uchar_t *)up - rptr),
13246 	    mp, mp1, cksum_err);
13247 
13248 	if (cksum_err) {
13249 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13250 
13251 		if (hck_flags & HCK_FULLCKSUM)
13252 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13253 		else if (hck_flags & HCK_PARTIALCKSUM)
13254 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13255 		else
13256 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13257 
13258 		goto error;
13259 	}
13260 
13261 try_again:
13262 
13263 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13264 	    zoneid, ipst)) == NULL) {
13265 		/* Send the TH_RST */
13266 		goto no_conn;
13267 	}
13268 
13269 	/*
13270 	 * TCP FAST PATH for AF_INET socket.
13271 	 *
13272 	 * TCP fast path to avoid extra work. An AF_INET socket type
13273 	 * does not have facility to receive extra information via
13274 	 * ip_process or ip_add_info. Also, when the connection was
13275 	 * established, we made a check if this connection is impacted
13276 	 * by any global IPSec policy or per connection policy (a
13277 	 * policy that comes in effect later will not apply to this
13278 	 * connection). Since all this can be determined at the
13279 	 * connection establishment time, a quick check of flags
13280 	 * can avoid extra work.
13281 	 */
13282 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13283 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13284 		ASSERT(first_mp == mp);
13285 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13286 		SET_SQUEUE(mp, tcp_rput_data, connp);
13287 		return (mp);
13288 	}
13289 
13290 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13291 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13292 		if (IPCL_IS_TCP(connp)) {
13293 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13294 			DB_CKSUMSTART(mp) =
13295 			    (intptr_t)ip_squeue_get(ill_ring);
13296 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13297 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13298 				BUMP_MIB(ill->ill_ip_mib,
13299 				    ipIfStatsHCInDelivers);
13300 				SET_SQUEUE(mp, connp->conn_recv, connp);
13301 				return (mp);
13302 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13303 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13304 				BUMP_MIB(ill->ill_ip_mib,
13305 				    ipIfStatsHCInDelivers);
13306 				ip_squeue_enter_unbound++;
13307 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13308 				    connp);
13309 				return (mp);
13310 			}
13311 			syn_present = B_TRUE;
13312 		}
13313 
13314 	}
13315 
13316 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13317 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13318 
13319 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13320 		/* No need to send this packet to TCP */
13321 		if ((flags & TH_RST) || (flags & TH_URG)) {
13322 			CONN_DEC_REF(connp);
13323 			freemsg(first_mp);
13324 			return (NULL);
13325 		}
13326 		if (flags & TH_ACK) {
13327 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13328 			    ipst->ips_netstack->netstack_tcp);
13329 			CONN_DEC_REF(connp);
13330 			return (NULL);
13331 		}
13332 
13333 		CONN_DEC_REF(connp);
13334 		freemsg(first_mp);
13335 		return (NULL);
13336 	}
13337 
13338 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13339 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13340 		    ipha, NULL, mctl_present);
13341 		if (first_mp == NULL) {
13342 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13343 			CONN_DEC_REF(connp);
13344 			return (NULL);
13345 		}
13346 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13347 			ASSERT(syn_present);
13348 			if (mctl_present) {
13349 				ASSERT(first_mp != mp);
13350 				first_mp->b_datap->db_struioflag |=
13351 				    STRUIO_POLICY;
13352 			} else {
13353 				ASSERT(first_mp == mp);
13354 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13355 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13356 			}
13357 		} else {
13358 			/*
13359 			 * Discard first_mp early since we're dealing with a
13360 			 * fully-connected conn_t and tcp doesn't do policy in
13361 			 * this case.
13362 			 */
13363 			if (mctl_present) {
13364 				freeb(first_mp);
13365 				mctl_present = B_FALSE;
13366 			}
13367 			first_mp = mp;
13368 		}
13369 	}
13370 
13371 	/* Initiate IPPF processing for fastpath */
13372 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13373 		uint32_t	ill_index;
13374 
13375 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13376 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13377 		if (mp == NULL) {
13378 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13379 			    "deferred/dropped during IPPF processing\n"));
13380 			CONN_DEC_REF(connp);
13381 			if (mctl_present)
13382 				freeb(first_mp);
13383 			return (NULL);
13384 		} else if (mctl_present) {
13385 			/*
13386 			 * ip_process might return a new mp.
13387 			 */
13388 			ASSERT(first_mp != mp);
13389 			first_mp->b_cont = mp;
13390 		} else {
13391 			first_mp = mp;
13392 		}
13393 
13394 	}
13395 
13396 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13397 		/*
13398 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13399 		 * make sure IPF_RECVIF is passed to ip_add_info.
13400 		 */
13401 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13402 		    IPCL_ZONEID(connp), ipst);
13403 		if (mp == NULL) {
13404 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13405 			CONN_DEC_REF(connp);
13406 			if (mctl_present)
13407 				freeb(first_mp);
13408 			return (NULL);
13409 		} else if (mctl_present) {
13410 			/*
13411 			 * ip_add_info might return a new mp.
13412 			 */
13413 			ASSERT(first_mp != mp);
13414 			first_mp->b_cont = mp;
13415 		} else {
13416 			first_mp = mp;
13417 		}
13418 	}
13419 
13420 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13421 	if (IPCL_IS_TCP(connp)) {
13422 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13423 		return (first_mp);
13424 	} else {
13425 		putnext(connp->conn_rq, first_mp);
13426 		CONN_DEC_REF(connp);
13427 		return (NULL);
13428 	}
13429 
13430 no_conn:
13431 	/* Initiate IPPf processing, if needed. */
13432 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13433 		uint32_t ill_index;
13434 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13435 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13436 		if (first_mp == NULL) {
13437 			return (NULL);
13438 		}
13439 	}
13440 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13441 
13442 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13443 	    ipst->ips_netstack->netstack_tcp);
13444 	return (NULL);
13445 ipoptions:
13446 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13447 		goto slow_done;
13448 	}
13449 
13450 	UPDATE_IB_PKT_COUNT(ire);
13451 	ire->ire_last_used_time = lbolt;
13452 
13453 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13454 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13455 fragmented:
13456 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13457 			if (mctl_present)
13458 				freeb(first_mp);
13459 			goto slow_done;
13460 		}
13461 		/*
13462 		 * Make sure that first_mp points back to mp as
13463 		 * the mp we came in with could have changed in
13464 		 * ip_rput_fragment().
13465 		 */
13466 		ASSERT(!mctl_present);
13467 		ipha = (ipha_t *)mp->b_rptr;
13468 		first_mp = mp;
13469 	}
13470 
13471 	/* Now we have a complete datagram, destined for this machine. */
13472 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13473 
13474 	len = mp->b_wptr - mp->b_rptr;
13475 	/* Pull up a minimal TCP header, if necessary. */
13476 	if (len < (u1 + 20)) {
13477 tcppullup:
13478 		if (!pullupmsg(mp, u1 + 20)) {
13479 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13480 			goto error;
13481 		}
13482 		ipha = (ipha_t *)mp->b_rptr;
13483 		len = mp->b_wptr - mp->b_rptr;
13484 	}
13485 
13486 	/*
13487 	 * Extract the offset field from the TCP header.  As usual, we
13488 	 * try to help the compiler more than the reader.
13489 	 */
13490 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13491 	if (offset != 5) {
13492 tcpoptions:
13493 		if (offset < 5) {
13494 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13495 			goto error;
13496 		}
13497 		/*
13498 		 * There must be TCP options.
13499 		 * Make sure we can grab them.
13500 		 */
13501 		offset <<= 2;
13502 		offset += u1;
13503 		if (len < offset) {
13504 			if (!pullupmsg(mp, offset)) {
13505 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13506 				goto error;
13507 			}
13508 			ipha = (ipha_t *)mp->b_rptr;
13509 			len = mp->b_wptr - rptr;
13510 		}
13511 	}
13512 
13513 	/* Get the total packet length in len, including headers. */
13514 	if (mp->b_cont) {
13515 multipkttcp:
13516 		len = msgdsize(mp);
13517 	}
13518 
13519 	/*
13520 	 * Check the TCP checksum by pulling together the pseudo-
13521 	 * header checksum, and passing it to ip_csum to be added in
13522 	 * with the TCP datagram.
13523 	 *
13524 	 * Since we are not using the hwcksum if available we must
13525 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13526 	 * If either of these fails along the way the mblk is freed.
13527 	 * If this logic ever changes and mblk is reused to say send
13528 	 * ICMP's back, then this flag may need to be cleared in
13529 	 * other places as well.
13530 	 */
13531 	DB_CKSUMFLAGS(mp) = 0;
13532 
13533 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13534 
13535 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13536 #ifdef	_BIG_ENDIAN
13537 	u1 += IPPROTO_TCP;
13538 #else
13539 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13540 #endif
13541 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13542 	/*
13543 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13544 	 */
13545 	IP_STAT(ipst, ip_in_sw_cksum);
13546 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13547 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13548 		goto error;
13549 	}
13550 
13551 	IP_STAT(ipst, ip_tcp_slow_path);
13552 	goto try_again;
13553 #undef  iphs
13554 #undef  rptr
13555 
13556 error:
13557 	freemsg(first_mp);
13558 slow_done:
13559 	return (NULL);
13560 }
13561 
13562 /* ARGSUSED */
13563 static void
13564 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13565     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13566 {
13567 	conn_t		*connp;
13568 	uint32_t	sum;
13569 	uint32_t	u1;
13570 	ssize_t		len;
13571 	sctp_hdr_t	*sctph;
13572 	zoneid_t	zoneid = ire->ire_zoneid;
13573 	uint32_t	pktsum;
13574 	uint32_t	calcsum;
13575 	uint32_t	ports;
13576 	in6_addr_t	map_src, map_dst;
13577 	ill_t		*ill = (ill_t *)q->q_ptr;
13578 	ip_stack_t	*ipst;
13579 	sctp_stack_t	*sctps;
13580 
13581 	ASSERT(recv_ill != NULL);
13582 	ipst = recv_ill->ill_ipst;
13583 	sctps = ipst->ips_netstack->netstack_sctp;
13584 
13585 #define	rptr	((uchar_t *)ipha)
13586 
13587 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13588 	ASSERT(ill != NULL);
13589 
13590 	/* u1 is # words of IP options */
13591 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13592 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13593 
13594 	/* IP options present */
13595 	if (u1 > 0) {
13596 		goto ipoptions;
13597 	} else {
13598 		/* Check the IP header checksum.  */
13599 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13600 #define	uph	((uint16_t *)ipha)
13601 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13602 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13603 #undef	uph
13604 			/* finish doing IP checksum */
13605 			sum = (sum & 0xFFFF) + (sum >> 16);
13606 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13607 			/*
13608 			 * Don't verify header checksum if this packet
13609 			 * is coming back from AH/ESP as we already did it.
13610 			 */
13611 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13612 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13613 				goto error;
13614 			}
13615 		}
13616 		/*
13617 		 * Since there is no SCTP h/w cksum support yet, just
13618 		 * clear the flag.
13619 		 */
13620 		DB_CKSUMFLAGS(mp) = 0;
13621 	}
13622 
13623 	/*
13624 	 * Don't verify header checksum if this packet is coming
13625 	 * back from AH/ESP as we already did it.
13626 	 */
13627 	if (!mctl_present) {
13628 		UPDATE_IB_PKT_COUNT(ire);
13629 		ire->ire_last_used_time = lbolt;
13630 	}
13631 
13632 	/* packet part of fragmented IP packet? */
13633 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13634 	if (u1 & (IPH_MF | IPH_OFFSET))
13635 		goto fragmented;
13636 
13637 	/* u1 = IP header length (20 bytes) */
13638 	u1 = IP_SIMPLE_HDR_LENGTH;
13639 
13640 find_sctp_client:
13641 	/* Pullup if we don't have the sctp common header. */
13642 	len = MBLKL(mp);
13643 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13644 		if (mp->b_cont == NULL ||
13645 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13646 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13647 			goto error;
13648 		}
13649 		ipha = (ipha_t *)mp->b_rptr;
13650 		len = MBLKL(mp);
13651 	}
13652 
13653 	sctph = (sctp_hdr_t *)(rptr + u1);
13654 #ifdef	DEBUG
13655 	if (!skip_sctp_cksum) {
13656 #endif
13657 		pktsum = sctph->sh_chksum;
13658 		sctph->sh_chksum = 0;
13659 		calcsum = sctp_cksum(mp, u1);
13660 		if (calcsum != pktsum) {
13661 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13662 			goto error;
13663 		}
13664 		sctph->sh_chksum = pktsum;
13665 #ifdef	DEBUG	/* skip_sctp_cksum */
13666 	}
13667 #endif
13668 	/* get the ports */
13669 	ports = *(uint32_t *)&sctph->sh_sport;
13670 
13671 	IRE_REFRELE(ire);
13672 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13673 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13674 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13675 	    sctps)) == NULL) {
13676 		/* Check for raw socket or OOTB handling */
13677 		goto no_conn;
13678 	}
13679 
13680 	/* Found a client; up it goes */
13681 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13682 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13683 	return;
13684 
13685 no_conn:
13686 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13687 	    ports, mctl_present, flags, B_TRUE, zoneid);
13688 	return;
13689 
13690 ipoptions:
13691 	DB_CKSUMFLAGS(mp) = 0;
13692 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13693 		goto slow_done;
13694 
13695 	UPDATE_IB_PKT_COUNT(ire);
13696 	ire->ire_last_used_time = lbolt;
13697 
13698 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13699 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13700 fragmented:
13701 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13702 			goto slow_done;
13703 		/*
13704 		 * Make sure that first_mp points back to mp as
13705 		 * the mp we came in with could have changed in
13706 		 * ip_rput_fragment().
13707 		 */
13708 		ASSERT(!mctl_present);
13709 		ipha = (ipha_t *)mp->b_rptr;
13710 		first_mp = mp;
13711 	}
13712 
13713 	/* Now we have a complete datagram, destined for this machine. */
13714 	u1 = IPH_HDR_LENGTH(ipha);
13715 	goto find_sctp_client;
13716 #undef  iphs
13717 #undef  rptr
13718 
13719 error:
13720 	freemsg(first_mp);
13721 slow_done:
13722 	IRE_REFRELE(ire);
13723 }
13724 
13725 #define	VER_BITS	0xF0
13726 #define	VERSION_6	0x60
13727 
13728 static boolean_t
13729 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13730     ipaddr_t *dstp, ip_stack_t *ipst)
13731 {
13732 	uint_t	opt_len;
13733 	ipha_t *ipha;
13734 	ssize_t len;
13735 	uint_t	pkt_len;
13736 
13737 	ASSERT(ill != NULL);
13738 	IP_STAT(ipst, ip_ipoptions);
13739 	ipha = *iphapp;
13740 
13741 #define	rptr    ((uchar_t *)ipha)
13742 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13743 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13744 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13745 		freemsg(mp);
13746 		return (B_FALSE);
13747 	}
13748 
13749 	/* multiple mblk or too short */
13750 	pkt_len = ntohs(ipha->ipha_length);
13751 
13752 	/* Get the number of words of IP options in the IP header. */
13753 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13754 	if (opt_len) {
13755 		/* IP Options present!  Validate and process. */
13756 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13757 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13758 			goto done;
13759 		}
13760 		/*
13761 		 * Recompute complete header length and make sure we
13762 		 * have access to all of it.
13763 		 */
13764 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13765 		if (len > (mp->b_wptr - rptr)) {
13766 			if (len > pkt_len) {
13767 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13768 				goto done;
13769 			}
13770 			if (!pullupmsg(mp, len)) {
13771 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13772 				goto done;
13773 			}
13774 			ipha = (ipha_t *)mp->b_rptr;
13775 		}
13776 		/*
13777 		 * Go off to ip_rput_options which returns the next hop
13778 		 * destination address, which may have been affected
13779 		 * by source routing.
13780 		 */
13781 		IP_STAT(ipst, ip_opt);
13782 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13783 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13784 			return (B_FALSE);
13785 		}
13786 	}
13787 	*iphapp = ipha;
13788 	return (B_TRUE);
13789 done:
13790 	/* clear b_prev - used by ip_mroute_decap */
13791 	mp->b_prev = NULL;
13792 	freemsg(mp);
13793 	return (B_FALSE);
13794 #undef  rptr
13795 }
13796 
13797 /*
13798  * Deal with the fact that there is no ire for the destination.
13799  * The incoming ill (in_ill) is passed in to ip_newroute only
13800  * in the case of packets coming from mobile ip forward tunnel.
13801  * It must be null otherwise.
13802  */
13803 static ire_t *
13804 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13805     ipaddr_t dst)
13806 {
13807 	ipha_t	*ipha;
13808 	ill_t	*ill;
13809 	ire_t	*ire;
13810 	boolean_t	check_multirt = B_FALSE;
13811 	ip_stack_t *ipst;
13812 
13813 	ipha = (ipha_t *)mp->b_rptr;
13814 	ill = (ill_t *)q->q_ptr;
13815 
13816 	ASSERT(ill != NULL);
13817 	ipst = ill->ill_ipst;
13818 
13819 	/*
13820 	 * No IRE for this destination, so it can't be for us.
13821 	 * Unless we are forwarding, drop the packet.
13822 	 * We have to let source routed packets through
13823 	 * since we don't yet know if they are 'ping -l'
13824 	 * packets i.e. if they will go out over the
13825 	 * same interface as they came in on.
13826 	 */
13827 	if (ll_multicast) {
13828 		freemsg(mp);
13829 		return (NULL);
13830 	}
13831 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13832 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13833 		freemsg(mp);
13834 		return (NULL);
13835 	}
13836 
13837 	/*
13838 	 * Mark this packet as having originated externally.
13839 	 *
13840 	 * For non-forwarding code path, ire_send later double
13841 	 * checks this interface to see if it is still exists
13842 	 * post-ARP resolution.
13843 	 *
13844 	 * Also, IPQOS uses this to differentiate between
13845 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13846 	 * QOS packet processing in ip_wput_attach_llhdr().
13847 	 * The QoS module can mark the b_band for a fastpath message
13848 	 * or the dl_priority field in a unitdata_req header for
13849 	 * CoS marking. This info can only be found in
13850 	 * ip_wput_attach_llhdr().
13851 	 */
13852 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13853 	/*
13854 	 * Clear the indication that this may have a hardware checksum
13855 	 * as we are not using it
13856 	 */
13857 	DB_CKSUMFLAGS(mp) = 0;
13858 
13859 	if (in_ill != NULL) {
13860 		/*
13861 		 * Now hand the packet to ip_newroute.
13862 		 */
13863 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13864 		return (NULL);
13865 	}
13866 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13867 	    MBLK_GETLABEL(mp), ipst);
13868 
13869 	if (ire == NULL && check_multirt) {
13870 		/* Let ip_newroute handle CGTP  */
13871 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13872 		return (NULL);
13873 	}
13874 
13875 	if (ire != NULL)
13876 		return (ire);
13877 
13878 	mp->b_prev = mp->b_next = 0;
13879 	/* send icmp unreachable */
13880 	q = WR(q);
13881 	/* Sent by forwarding path, and router is global zone */
13882 	if (ip_source_routed(ipha, ipst)) {
13883 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13884 		    GLOBAL_ZONEID, ipst);
13885 	} else {
13886 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13887 		    ipst);
13888 	}
13889 
13890 	return (NULL);
13891 
13892 }
13893 
13894 /*
13895  * check ip header length and align it.
13896  */
13897 static boolean_t
13898 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13899 {
13900 	ssize_t len;
13901 	ill_t *ill;
13902 	ipha_t	*ipha;
13903 
13904 	len = MBLKL(mp);
13905 
13906 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13907 		ill = (ill_t *)q->q_ptr;
13908 
13909 		if (!OK_32PTR(mp->b_rptr))
13910 			IP_STAT(ipst, ip_notaligned1);
13911 		else
13912 			IP_STAT(ipst, ip_notaligned2);
13913 		/* Guard against bogus device drivers */
13914 		if (len < 0) {
13915 			/* clear b_prev - used by ip_mroute_decap */
13916 			mp->b_prev = NULL;
13917 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13918 			freemsg(mp);
13919 			return (B_FALSE);
13920 		}
13921 
13922 		if (ip_rput_pullups++ == 0) {
13923 			ipha = (ipha_t *)mp->b_rptr;
13924 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13925 			    "ip_check_and_align_header: %s forced us to "
13926 			    " pullup pkt, hdr len %ld, hdr addr %p",
13927 			    ill->ill_name, len, ipha);
13928 		}
13929 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13930 			/* clear b_prev - used by ip_mroute_decap */
13931 			mp->b_prev = NULL;
13932 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13933 			freemsg(mp);
13934 			return (B_FALSE);
13935 		}
13936 	}
13937 	return (B_TRUE);
13938 }
13939 
13940 ire_t *
13941 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13942 {
13943 	ire_t		*new_ire;
13944 	ill_t		*ire_ill;
13945 	uint_t		ifindex;
13946 	ip_stack_t	*ipst = ill->ill_ipst;
13947 	boolean_t	strict_check = B_FALSE;
13948 
13949 	/*
13950 	 * This packet came in on an interface other than the one associated
13951 	 * with the first ire we found for the destination address. We do
13952 	 * another ire lookup here, using the ingress ill, to see if the
13953 	 * interface is in an interface group.
13954 	 * As long as the ills belong to the same group, we don't consider
13955 	 * them to be arriving on the wrong interface. Thus, if the switch
13956 	 * is doing inbound load spreading, we won't drop packets when the
13957 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13958 	 * for 'usesrc groups' where the destination address may belong to
13959 	 * another interface to allow multipathing to happen.
13960 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13961 	 * where the local address may not be unique. In this case we were
13962 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13963 	 * actually returned. The new lookup, which is more specific, should
13964 	 * only find the IRE_LOCAL associated with the ingress ill if one
13965 	 * exists.
13966 	 */
13967 
13968 	if (ire->ire_ipversion == IPV4_VERSION) {
13969 		if (ipst->ips_ip_strict_dst_multihoming)
13970 			strict_check = B_TRUE;
13971 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13972 		    ill->ill_ipif, ALL_ZONES, NULL,
13973 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13974 	} else {
13975 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13976 		if (ipst->ips_ipv6_strict_dst_multihoming)
13977 			strict_check = B_TRUE;
13978 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13979 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13980 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13981 	}
13982 	/*
13983 	 * If the same ire that was returned in ip_input() is found then this
13984 	 * is an indication that interface groups are in use. The packet
13985 	 * arrived on a different ill in the group than the one associated with
13986 	 * the destination address.  If a different ire was found then the same
13987 	 * IP address must be hosted on multiple ills. This is possible with
13988 	 * unnumbered point2point interfaces. We switch to use this new ire in
13989 	 * order to have accurate interface statistics.
13990 	 */
13991 	if (new_ire != NULL) {
13992 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13993 			ire_refrele(ire);
13994 			ire = new_ire;
13995 		} else {
13996 			ire_refrele(new_ire);
13997 		}
13998 		return (ire);
13999 	} else if ((ire->ire_rfq == NULL) &&
14000 	    (ire->ire_ipversion == IPV4_VERSION)) {
14001 		/*
14002 		 * The best match could have been the original ire which
14003 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
14004 		 * the strict multihoming checks are irrelevant as we consider
14005 		 * local addresses hosted on lo0 to be interface agnostic. We
14006 		 * only expect a null ire_rfq on IREs which are associated with
14007 		 * lo0 hence we can return now.
14008 		 */
14009 		return (ire);
14010 	}
14011 
14012 	/*
14013 	 * Chase pointers once and store locally.
14014 	 */
14015 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
14016 	    (ill_t *)(ire->ire_rfq->q_ptr);
14017 	ifindex = ill->ill_usesrc_ifindex;
14018 
14019 	/*
14020 	 * Check if it's a legal address on the 'usesrc' interface.
14021 	 */
14022 	if ((ifindex != 0) && (ire_ill != NULL) &&
14023 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
14024 		return (ire);
14025 	}
14026 
14027 	/*
14028 	 * If the ip*_strict_dst_multihoming switch is on then we can
14029 	 * only accept this packet if the interface is marked as routing.
14030 	 */
14031 	if (!(strict_check))
14032 		return (ire);
14033 
14034 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
14035 	    ILLF_ROUTER) != 0) {
14036 		return (ire);
14037 	}
14038 
14039 	ire_refrele(ire);
14040 	return (NULL);
14041 }
14042 
14043 ire_t *
14044 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
14045 {
14046 	ipha_t	*ipha;
14047 	ipaddr_t ip_dst, ip_src;
14048 	ire_t	*src_ire = NULL;
14049 	ill_t	*stq_ill;
14050 	uint_t	hlen;
14051 	uint_t	pkt_len;
14052 	uint32_t sum;
14053 	queue_t	*dev_q;
14054 	boolean_t check_multirt = B_FALSE;
14055 	ip_stack_t *ipst = ill->ill_ipst;
14056 
14057 	ipha = (ipha_t *)mp->b_rptr;
14058 
14059 	/*
14060 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14061 	 * The loopback address check for both src and dst has already
14062 	 * been checked in ip_input
14063 	 */
14064 	ip_dst = ntohl(dst);
14065 	ip_src = ntohl(ipha->ipha_src);
14066 
14067 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
14068 	    IN_CLASSD(ip_src)) {
14069 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14070 		goto drop;
14071 	}
14072 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14073 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14074 
14075 	if (src_ire != NULL) {
14076 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14077 		goto drop;
14078 	}
14079 
14080 
14081 	/* No ire cache of nexthop. So first create one  */
14082 	if (ire == NULL) {
14083 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
14084 		/*
14085 		 * We only come to ip_fast_forward if ip_cgtp_filter is
14086 		 * is not set. So upon return from ire_forward
14087 		 * check_multirt should remain as false.
14088 		 */
14089 		ASSERT(!check_multirt);
14090 		if (ire == NULL) {
14091 			/* An attempt was made to forward the packet */
14092 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14093 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14094 			mp->b_prev = mp->b_next = 0;
14095 			/* send icmp unreachable */
14096 			/* Sent by forwarding path, and router is global zone */
14097 			if (ip_source_routed(ipha, ipst)) {
14098 				icmp_unreachable(ill->ill_wq, mp,
14099 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
14100 				    ipst);
14101 			} else {
14102 				icmp_unreachable(ill->ill_wq, mp,
14103 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
14104 				    ipst);
14105 			}
14106 			return (ire);
14107 		}
14108 	}
14109 
14110 	/*
14111 	 * Forwarding fastpath exception case:
14112 	 * If either of the follwoing case is true, we take
14113 	 * the slowpath
14114 	 *	o forwarding is not enabled
14115 	 *	o incoming and outgoing interface are the same, or the same
14116 	 *	  IPMP group
14117 	 *	o corresponding ire is in incomplete state
14118 	 *	o packet needs fragmentation
14119 	 *
14120 	 * The codeflow from here on is thus:
14121 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14122 	 */
14123 	pkt_len = ntohs(ipha->ipha_length);
14124 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14125 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14126 	    !(ill->ill_flags & ILLF_ROUTER) ||
14127 	    (ill == stq_ill) ||
14128 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14129 	    (ire->ire_nce == NULL) ||
14130 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14131 	    (pkt_len > ire->ire_max_frag) ||
14132 	    ipha->ipha_ttl <= 1) {
14133 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14134 		    ipha, ill, B_FALSE);
14135 		return (ire);
14136 	}
14137 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14138 
14139 	DTRACE_PROBE4(ip4__forwarding__start,
14140 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14141 
14142 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14143 	    ipst->ips_ipv4firewall_forwarding,
14144 	    ill, stq_ill, ipha, mp, mp, ipst);
14145 
14146 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14147 
14148 	if (mp == NULL)
14149 		goto drop;
14150 
14151 	mp->b_datap->db_struioun.cksum.flags = 0;
14152 	/* Adjust the checksum to reflect the ttl decrement. */
14153 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14154 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14155 	ipha->ipha_ttl--;
14156 
14157 	dev_q = ire->ire_stq->q_next;
14158 	if ((dev_q->q_next != NULL ||
14159 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14160 		goto indiscard;
14161 	}
14162 
14163 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14164 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14165 
14166 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14167 		mblk_t *mpip = mp;
14168 
14169 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14170 		if (mp != NULL) {
14171 			DTRACE_PROBE4(ip4__physical__out__start,
14172 			    ill_t *, NULL, ill_t *, stq_ill,
14173 			    ipha_t *, ipha, mblk_t *, mp);
14174 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14175 			    ipst->ips_ipv4firewall_physical_out,
14176 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14177 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14178 			    mp);
14179 			if (mp == NULL)
14180 				goto drop;
14181 
14182 			UPDATE_IB_PKT_COUNT(ire);
14183 			ire->ire_last_used_time = lbolt;
14184 			BUMP_MIB(stq_ill->ill_ip_mib,
14185 			    ipIfStatsHCOutForwDatagrams);
14186 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14187 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14188 			    pkt_len);
14189 			putnext(ire->ire_stq, mp);
14190 			return (ire);
14191 		}
14192 	}
14193 
14194 indiscard:
14195 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14196 drop:
14197 	if (mp != NULL)
14198 		freemsg(mp);
14199 	if (src_ire != NULL)
14200 		ire_refrele(src_ire);
14201 	return (ire);
14202 
14203 }
14204 
14205 /*
14206  * This function is called in the forwarding slowpath, when
14207  * either the ire lacks the link-layer address, or the packet needs
14208  * further processing(eg. fragmentation), before transmission.
14209  */
14210 
14211 static void
14212 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14213     ill_t *ill, boolean_t ll_multicast)
14214 {
14215 	ill_group_t	*ill_group;
14216 	ill_group_t	*ire_group;
14217 	queue_t		*dev_q;
14218 	ire_t		*src_ire;
14219 	ip_stack_t	*ipst = ill->ill_ipst;
14220 
14221 	ASSERT(ire->ire_stq != NULL);
14222 
14223 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14224 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14225 
14226 	if (ll_multicast != 0) {
14227 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14228 		goto drop_pkt;
14229 	}
14230 
14231 	/*
14232 	 * check if ipha_src is a broadcast address. Note that this
14233 	 * check is redundant when we get here from ip_fast_forward()
14234 	 * which has already done this check. However, since we can
14235 	 * also get here from ip_rput_process_broadcast() or, for
14236 	 * for the slow path through ip_fast_forward(), we perform
14237 	 * the check again for code-reusability
14238 	 */
14239 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14240 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14241 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14242 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14243 		if (src_ire != NULL)
14244 			ire_refrele(src_ire);
14245 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14246 		ip2dbg(("ip_rput_process_forward: Received packet with"
14247 		    " bad src/dst address on %s\n", ill->ill_name));
14248 		goto drop_pkt;
14249 	}
14250 
14251 	ill_group = ill->ill_group;
14252 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14253 	/*
14254 	 * Check if we want to forward this one at this time.
14255 	 * We allow source routed packets on a host provided that
14256 	 * they go out the same interface or same interface group
14257 	 * as they came in on.
14258 	 *
14259 	 * XXX To be quicker, we may wish to not chase pointers to
14260 	 * get the ILLF_ROUTER flag and instead store the
14261 	 * forwarding policy in the ire.  An unfortunate
14262 	 * side-effect of that would be requiring an ire flush
14263 	 * whenever the ILLF_ROUTER flag changes.
14264 	 */
14265 	if (((ill->ill_flags &
14266 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14267 	    ILLF_ROUTER) == 0) &&
14268 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14269 	    (ill_group != NULL && ill_group == ire_group)))) {
14270 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14271 		if (ip_source_routed(ipha, ipst)) {
14272 			q = WR(q);
14273 			/*
14274 			 * Clear the indication that this may have
14275 			 * hardware checksum as we are not using it.
14276 			 */
14277 			DB_CKSUMFLAGS(mp) = 0;
14278 			/* Sent by forwarding path, and router is global zone */
14279 			icmp_unreachable(q, mp,
14280 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14281 			return;
14282 		}
14283 		goto drop_pkt;
14284 	}
14285 
14286 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14287 
14288 	/* Packet is being forwarded. Turning off hwcksum flag. */
14289 	DB_CKSUMFLAGS(mp) = 0;
14290 	if (ipst->ips_ip_g_send_redirects) {
14291 		/*
14292 		 * Check whether the incoming interface and outgoing
14293 		 * interface is part of the same group. If so,
14294 		 * send redirects.
14295 		 *
14296 		 * Check the source address to see if it originated
14297 		 * on the same logical subnet it is going back out on.
14298 		 * If so, we should be able to send it a redirect.
14299 		 * Avoid sending a redirect if the destination
14300 		 * is directly connected (i.e., ipha_dst is the same
14301 		 * as ire_gateway_addr or the ire_addr of the
14302 		 * nexthop IRE_CACHE ), or if the packet was source
14303 		 * routed out this interface.
14304 		 */
14305 		ipaddr_t src, nhop;
14306 		mblk_t	*mp1;
14307 		ire_t	*nhop_ire = NULL;
14308 
14309 		/*
14310 		 * Check whether ire_rfq and q are from the same ill
14311 		 * or if they are not same, they at least belong
14312 		 * to the same group. If so, send redirects.
14313 		 */
14314 		if ((ire->ire_rfq == q ||
14315 		    (ill_group != NULL && ill_group == ire_group)) &&
14316 		    !ip_source_routed(ipha, ipst)) {
14317 
14318 			nhop = (ire->ire_gateway_addr != 0 ?
14319 			    ire->ire_gateway_addr : ire->ire_addr);
14320 
14321 			if (ipha->ipha_dst == nhop) {
14322 				/*
14323 				 * We avoid sending a redirect if the
14324 				 * destination is directly connected
14325 				 * because it is possible that multiple
14326 				 * IP subnets may have been configured on
14327 				 * the link, and the source may not
14328 				 * be on the same subnet as ip destination,
14329 				 * even though they are on the same
14330 				 * physical link.
14331 				 */
14332 				goto sendit;
14333 			}
14334 
14335 			src = ipha->ipha_src;
14336 
14337 			/*
14338 			 * We look up the interface ire for the nexthop,
14339 			 * to see if ipha_src is in the same subnet
14340 			 * as the nexthop.
14341 			 *
14342 			 * Note that, if, in the future, IRE_CACHE entries
14343 			 * are obsoleted,  this lookup will not be needed,
14344 			 * as the ire passed to this function will be the
14345 			 * same as the nhop_ire computed below.
14346 			 */
14347 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14348 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14349 			    0, NULL, MATCH_IRE_TYPE, ipst);
14350 
14351 			if (nhop_ire != NULL) {
14352 				if ((src & nhop_ire->ire_mask) ==
14353 				    (nhop & nhop_ire->ire_mask)) {
14354 					/*
14355 					 * The source is directly connected.
14356 					 * Just copy the ip header (which is
14357 					 * in the first mblk)
14358 					 */
14359 					mp1 = copyb(mp);
14360 					if (mp1 != NULL) {
14361 						icmp_send_redirect(WR(q), mp1,
14362 						    nhop, ipst);
14363 					}
14364 				}
14365 				ire_refrele(nhop_ire);
14366 			}
14367 		}
14368 	}
14369 sendit:
14370 	dev_q = ire->ire_stq->q_next;
14371 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14372 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14373 		freemsg(mp);
14374 		return;
14375 	}
14376 
14377 	ip_rput_forward(ire, ipha, mp, ill);
14378 	return;
14379 
14380 drop_pkt:
14381 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14382 	freemsg(mp);
14383 }
14384 
14385 ire_t *
14386 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14387     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14388 {
14389 	queue_t		*q;
14390 	uint16_t	hcksumflags;
14391 	ip_stack_t	*ipst = ill->ill_ipst;
14392 
14393 	q = *qp;
14394 
14395 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14396 
14397 	/*
14398 	 * Clear the indication that this may have hardware
14399 	 * checksum as we are not using it for forwarding.
14400 	 */
14401 	hcksumflags = DB_CKSUMFLAGS(mp);
14402 	DB_CKSUMFLAGS(mp) = 0;
14403 
14404 	/*
14405 	 * Directed broadcast forwarding: if the packet came in over a
14406 	 * different interface then it is routed out over we can forward it.
14407 	 */
14408 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14409 		ire_refrele(ire);
14410 		freemsg(mp);
14411 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14412 		return (NULL);
14413 	}
14414 	/*
14415 	 * For multicast we have set dst to be INADDR_BROADCAST
14416 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14417 	 * only for broadcast packets.
14418 	 */
14419 	if (!CLASSD(ipha->ipha_dst)) {
14420 		ire_t *new_ire;
14421 		ipif_t *ipif;
14422 		/*
14423 		 * For ill groups, as the switch duplicates broadcasts
14424 		 * across all the ports, we need to filter out and
14425 		 * send up only one copy. There is one copy for every
14426 		 * broadcast address on each ill. Thus, we look for a
14427 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14428 		 * later to see whether this ill is eligible to receive
14429 		 * them or not. ill_nominate_bcast_rcv() nominates only
14430 		 * one set of IREs for receiving.
14431 		 */
14432 
14433 		ipif = ipif_get_next_ipif(NULL, ill);
14434 		if (ipif == NULL) {
14435 			ire_refrele(ire);
14436 			freemsg(mp);
14437 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14438 			return (NULL);
14439 		}
14440 		new_ire = ire_ctable_lookup(dst, 0, 0,
14441 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14442 		ipif_refrele(ipif);
14443 
14444 		if (new_ire != NULL) {
14445 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14446 				ire_refrele(ire);
14447 				ire_refrele(new_ire);
14448 				freemsg(mp);
14449 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14450 				return (NULL);
14451 			}
14452 			/*
14453 			 * In the special case of multirouted broadcast
14454 			 * packets, we unconditionally need to "gateway"
14455 			 * them to the appropriate interface here.
14456 			 * In the normal case, this cannot happen, because
14457 			 * there is no broadcast IRE tagged with the
14458 			 * RTF_MULTIRT flag.
14459 			 */
14460 			if (new_ire->ire_flags & RTF_MULTIRT) {
14461 				ire_refrele(new_ire);
14462 				if (ire->ire_rfq != NULL) {
14463 					q = ire->ire_rfq;
14464 					*qp = q;
14465 				}
14466 			} else {
14467 				ire_refrele(ire);
14468 				ire = new_ire;
14469 			}
14470 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14471 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14472 				/*
14473 				 * Free the message if
14474 				 * ip_g_forward_directed_bcast is turned
14475 				 * off for non-local broadcast.
14476 				 */
14477 				ire_refrele(ire);
14478 				freemsg(mp);
14479 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14480 				return (NULL);
14481 			}
14482 		} else {
14483 			/*
14484 			 * This CGTP packet successfully passed the
14485 			 * CGTP filter, but the related CGTP
14486 			 * broadcast IRE has not been found,
14487 			 * meaning that the redundant ipif is
14488 			 * probably down. However, if we discarded
14489 			 * this packet, its duplicate would be
14490 			 * filtered out by the CGTP filter so none
14491 			 * of them would get through. So we keep
14492 			 * going with this one.
14493 			 */
14494 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14495 			if (ire->ire_rfq != NULL) {
14496 				q = ire->ire_rfq;
14497 				*qp = q;
14498 			}
14499 		}
14500 	}
14501 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14502 		/*
14503 		 * Verify that there are not more then one
14504 		 * IRE_BROADCAST with this broadcast address which
14505 		 * has ire_stq set.
14506 		 * TODO: simplify, loop over all IRE's
14507 		 */
14508 		ire_t	*ire1;
14509 		int	num_stq = 0;
14510 		mblk_t	*mp1;
14511 
14512 		/* Find the first one with ire_stq set */
14513 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14514 		for (ire1 = ire; ire1 &&
14515 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14516 		    ire1 = ire1->ire_next)
14517 			;
14518 		if (ire1) {
14519 			ire_refrele(ire);
14520 			ire = ire1;
14521 			IRE_REFHOLD(ire);
14522 		}
14523 
14524 		/* Check if there are additional ones with stq set */
14525 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14526 			if (ire->ire_addr != ire1->ire_addr)
14527 				break;
14528 			if (ire1->ire_stq) {
14529 				num_stq++;
14530 				break;
14531 			}
14532 		}
14533 		rw_exit(&ire->ire_bucket->irb_lock);
14534 		if (num_stq == 1 && ire->ire_stq != NULL) {
14535 			ip1dbg(("ip_rput_process_broadcast: directed "
14536 			    "broadcast to 0x%x\n",
14537 			    ntohl(ire->ire_addr)));
14538 			mp1 = copymsg(mp);
14539 			if (mp1) {
14540 				switch (ipha->ipha_protocol) {
14541 				case IPPROTO_UDP:
14542 					ip_udp_input(q, mp1, ipha, ire, ill);
14543 					break;
14544 				default:
14545 					ip_proto_input(q, mp1, ipha, ire, ill);
14546 					break;
14547 				}
14548 			}
14549 			/*
14550 			 * Adjust ttl to 2 (1+1 - the forward engine
14551 			 * will decrement it by one.
14552 			 */
14553 			if (ip_csum_hdr(ipha)) {
14554 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14555 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14556 				freemsg(mp);
14557 				ire_refrele(ire);
14558 				return (NULL);
14559 			}
14560 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14561 			ipha->ipha_hdr_checksum = 0;
14562 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14563 			ip_rput_process_forward(q, mp, ire, ipha,
14564 			    ill, ll_multicast);
14565 			ire_refrele(ire);
14566 			return (NULL);
14567 		}
14568 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14569 		    ntohl(ire->ire_addr)));
14570 	}
14571 
14572 
14573 	/* Restore any hardware checksum flags */
14574 	DB_CKSUMFLAGS(mp) = hcksumflags;
14575 	return (ire);
14576 }
14577 
14578 /* ARGSUSED */
14579 static boolean_t
14580 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14581     int *ll_multicast, ipaddr_t *dstp)
14582 {
14583 	ip_stack_t	*ipst = ill->ill_ipst;
14584 
14585 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14586 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14587 	    ntohs(ipha->ipha_length));
14588 
14589 	/*
14590 	 * Forward packets only if we have joined the allmulti
14591 	 * group on this interface.
14592 	 */
14593 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14594 		int retval;
14595 
14596 		/*
14597 		 * Clear the indication that this may have hardware
14598 		 * checksum as we are not using it.
14599 		 */
14600 		DB_CKSUMFLAGS(mp) = 0;
14601 		retval = ip_mforward(ill, ipha, mp);
14602 		/* ip_mforward updates mib variables if needed */
14603 		/* clear b_prev - used by ip_mroute_decap */
14604 		mp->b_prev = NULL;
14605 
14606 		switch (retval) {
14607 		case 0:
14608 			/*
14609 			 * pkt is okay and arrived on phyint.
14610 			 *
14611 			 * If we are running as a multicast router
14612 			 * we need to see all IGMP and/or PIM packets.
14613 			 */
14614 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14615 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14616 				goto done;
14617 			}
14618 			break;
14619 		case -1:
14620 			/* pkt is mal-formed, toss it */
14621 			goto drop_pkt;
14622 		case 1:
14623 			/* pkt is okay and arrived on a tunnel */
14624 			/*
14625 			 * If we are running a multicast router
14626 			 *  we need to see all igmp packets.
14627 			 */
14628 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14629 				*dstp = INADDR_BROADCAST;
14630 				*ll_multicast = 1;
14631 				return (B_FALSE);
14632 			}
14633 
14634 			goto drop_pkt;
14635 		}
14636 	}
14637 
14638 	ILM_WALKER_HOLD(ill);
14639 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14640 		/*
14641 		 * This might just be caused by the fact that
14642 		 * multiple IP Multicast addresses map to the same
14643 		 * link layer multicast - no need to increment counter!
14644 		 */
14645 		ILM_WALKER_RELE(ill);
14646 		freemsg(mp);
14647 		return (B_TRUE);
14648 	}
14649 	ILM_WALKER_RELE(ill);
14650 done:
14651 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14652 	/*
14653 	 * This assumes the we deliver to all streams for multicast
14654 	 * and broadcast packets.
14655 	 */
14656 	*dstp = INADDR_BROADCAST;
14657 	*ll_multicast = 1;
14658 	return (B_FALSE);
14659 drop_pkt:
14660 	ip2dbg(("ip_rput: drop pkt\n"));
14661 	freemsg(mp);
14662 	return (B_TRUE);
14663 }
14664 
14665 static boolean_t
14666 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14667     int *ll_multicast, mblk_t **mpp)
14668 {
14669 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14670 	boolean_t must_copy = B_FALSE;
14671 	struct iocblk   *iocp;
14672 	ipha_t		*ipha;
14673 	ip_stack_t	*ipst = ill->ill_ipst;
14674 
14675 #define	rptr    ((uchar_t *)ipha)
14676 
14677 	first_mp = *first_mpp;
14678 	mp = *mpp;
14679 
14680 	ASSERT(first_mp == mp);
14681 
14682 	/*
14683 	 * if db_ref > 1 then copymsg and free original. Packet may be
14684 	 * changed and do not want other entity who has a reference to this
14685 	 * message to trip over the changes. This is a blind change because
14686 	 * trying to catch all places that might change packet is too
14687 	 * difficult (since it may be a module above this one)
14688 	 *
14689 	 * This corresponds to the non-fast path case. We walk down the full
14690 	 * chain in this case, and check the db_ref count of all the dblks,
14691 	 * and do a copymsg if required. It is possible that the db_ref counts
14692 	 * of the data blocks in the mblk chain can be different.
14693 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14694 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14695 	 * 'snoop' is running.
14696 	 */
14697 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14698 		if (mp1->b_datap->db_ref > 1) {
14699 			must_copy = B_TRUE;
14700 			break;
14701 		}
14702 	}
14703 
14704 	if (must_copy) {
14705 		mp1 = copymsg(mp);
14706 		if (mp1 == NULL) {
14707 			for (mp1 = mp; mp1 != NULL;
14708 			    mp1 = mp1->b_cont) {
14709 				mp1->b_next = NULL;
14710 				mp1->b_prev = NULL;
14711 			}
14712 			freemsg(mp);
14713 			if (ill != NULL) {
14714 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14715 			} else {
14716 				BUMP_MIB(&ipst->ips_ip_mib,
14717 				    ipIfStatsInDiscards);
14718 			}
14719 			return (B_TRUE);
14720 		}
14721 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14722 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14723 			/* Copy b_prev - used by ip_mroute_decap */
14724 			to_mp->b_prev = from_mp->b_prev;
14725 			from_mp->b_prev = NULL;
14726 		}
14727 		*first_mpp = first_mp = mp1;
14728 		freemsg(mp);
14729 		mp = mp1;
14730 		*mpp = mp1;
14731 	}
14732 
14733 	ipha = (ipha_t *)mp->b_rptr;
14734 
14735 	/*
14736 	 * previous code has a case for M_DATA.
14737 	 * We want to check how that happens.
14738 	 */
14739 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14740 	switch (first_mp->b_datap->db_type) {
14741 	case M_PROTO:
14742 	case M_PCPROTO:
14743 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14744 		    DL_UNITDATA_IND) {
14745 			/* Go handle anything other than data elsewhere. */
14746 			ip_rput_dlpi(q, mp);
14747 			return (B_TRUE);
14748 		}
14749 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14750 		/* Ditch the DLPI header. */
14751 		mp1 = mp->b_cont;
14752 		ASSERT(first_mp == mp);
14753 		*first_mpp = mp1;
14754 		freeb(mp);
14755 		*mpp = mp1;
14756 		return (B_FALSE);
14757 	case M_IOCACK:
14758 		ip1dbg(("got iocack "));
14759 		iocp = (struct iocblk *)mp->b_rptr;
14760 		switch (iocp->ioc_cmd) {
14761 		case DL_IOC_HDR_INFO:
14762 			ill = (ill_t *)q->q_ptr;
14763 			ill_fastpath_ack(ill, mp);
14764 			return (B_TRUE);
14765 		case SIOCSTUNPARAM:
14766 		case OSIOCSTUNPARAM:
14767 			/* Go through qwriter_ip */
14768 			break;
14769 		case SIOCGTUNPARAM:
14770 		case OSIOCGTUNPARAM:
14771 			ip_rput_other(NULL, q, mp, NULL);
14772 			return (B_TRUE);
14773 		default:
14774 			putnext(q, mp);
14775 			return (B_TRUE);
14776 		}
14777 		/* FALLTHRU */
14778 	case M_ERROR:
14779 	case M_HANGUP:
14780 		/*
14781 		 * Since this is on the ill stream we unconditionally
14782 		 * bump up the refcount
14783 		 */
14784 		ill_refhold(ill);
14785 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14786 		return (B_TRUE);
14787 	case M_CTL:
14788 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14789 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14790 		    IPHADA_M_CTL)) {
14791 			/*
14792 			 * It's an IPsec accelerated packet.
14793 			 * Make sure that the ill from which we received the
14794 			 * packet has enabled IPsec hardware acceleration.
14795 			 */
14796 			if (!(ill->ill_capabilities &
14797 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14798 				/* IPsec kstats: bean counter */
14799 				freemsg(mp);
14800 				return (B_TRUE);
14801 			}
14802 
14803 			/*
14804 			 * Make mp point to the mblk following the M_CTL,
14805 			 * then process according to type of mp.
14806 			 * After this processing, first_mp will point to
14807 			 * the data-attributes and mp to the pkt following
14808 			 * the M_CTL.
14809 			 */
14810 			mp = first_mp->b_cont;
14811 			if (mp == NULL) {
14812 				freemsg(first_mp);
14813 				return (B_TRUE);
14814 			}
14815 			/*
14816 			 * A Hardware Accelerated packet can only be M_DATA
14817 			 * ESP or AH packet.
14818 			 */
14819 			if (mp->b_datap->db_type != M_DATA) {
14820 				/* non-M_DATA IPsec accelerated packet */
14821 				IPSECHW_DEBUG(IPSECHW_PKT,
14822 				    ("non-M_DATA IPsec accelerated pkt\n"));
14823 				freemsg(first_mp);
14824 				return (B_TRUE);
14825 			}
14826 			ipha = (ipha_t *)mp->b_rptr;
14827 			if (ipha->ipha_protocol != IPPROTO_AH &&
14828 			    ipha->ipha_protocol != IPPROTO_ESP) {
14829 				IPSECHW_DEBUG(IPSECHW_PKT,
14830 				    ("non-M_DATA IPsec accelerated pkt\n"));
14831 				freemsg(first_mp);
14832 				return (B_TRUE);
14833 			}
14834 			*mpp = mp;
14835 			return (B_FALSE);
14836 		}
14837 		putnext(q, mp);
14838 		return (B_TRUE);
14839 	case M_IOCNAK:
14840 		ip1dbg(("got iocnak "));
14841 		iocp = (struct iocblk *)mp->b_rptr;
14842 		switch (iocp->ioc_cmd) {
14843 		case SIOCSTUNPARAM:
14844 		case OSIOCSTUNPARAM:
14845 			/*
14846 			 * Since this is on the ill stream we unconditionally
14847 			 * bump up the refcount
14848 			 */
14849 			ill_refhold(ill);
14850 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14851 			return (B_TRUE);
14852 		case DL_IOC_HDR_INFO:
14853 		case SIOCGTUNPARAM:
14854 		case OSIOCGTUNPARAM:
14855 			ip_rput_other(NULL, q, mp, NULL);
14856 			return (B_TRUE);
14857 		default:
14858 			break;
14859 		}
14860 		/* FALLTHRU */
14861 	default:
14862 		putnext(q, mp);
14863 		return (B_TRUE);
14864 	}
14865 }
14866 
14867 /* Read side put procedure.  Packets coming from the wire arrive here. */
14868 void
14869 ip_rput(queue_t *q, mblk_t *mp)
14870 {
14871 	ill_t		*ill = (ill_t *)q->q_ptr;
14872 	ip_stack_t	*ipst = ill->ill_ipst;
14873 	union DL_primitives *dl;
14874 
14875 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14876 
14877 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14878 		/*
14879 		 * If things are opening or closing, only accept high-priority
14880 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14881 		 * created; on close, things hanging off the ill may have been
14882 		 * freed already.)
14883 		 */
14884 		dl = (union DL_primitives *)mp->b_rptr;
14885 		if (DB_TYPE(mp) != M_PCPROTO ||
14886 		    dl->dl_primitive == DL_UNITDATA_IND) {
14887 			/*
14888 			 * SIOC[GS]TUNPARAM ioctls can come here.
14889 			 */
14890 			inet_freemsg(mp);
14891 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14892 			    "ip_rput_end: q %p (%S)", q, "uninit");
14893 			return;
14894 		}
14895 	}
14896 
14897 	/*
14898 	 * if db_ref > 1 then copymsg and free original. Packet may be
14899 	 * changed and we do not want the other entity who has a reference to
14900 	 * this message to trip over the changes. This is a blind change because
14901 	 * trying to catch all places that might change the packet is too
14902 	 * difficult.
14903 	 *
14904 	 * This corresponds to the fast path case, where we have a chain of
14905 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14906 	 * in the mblk chain. There doesn't seem to be a reason why a device
14907 	 * driver would send up data with varying db_ref counts in the mblk
14908 	 * chain. In any case the Fast path is a private interface, and our
14909 	 * drivers don't do such a thing. Given the above assumption, there is
14910 	 * no need to walk down the entire mblk chain (which could have a
14911 	 * potential performance problem)
14912 	 */
14913 	if (mp->b_datap->db_ref > 1) {
14914 		mblk_t  *mp1;
14915 		boolean_t adjusted = B_FALSE;
14916 		IP_STAT(ipst, ip_db_ref);
14917 
14918 		/*
14919 		 * The IP_RECVSLLA option depends on having the link layer
14920 		 * header. First check that:
14921 		 * a> the underlying device is of type ether, since this
14922 		 * option is currently supported only over ethernet.
14923 		 * b> there is enough room to copy over the link layer header.
14924 		 *
14925 		 * Once the checks are done, adjust rptr so that the link layer
14926 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14927 		 * be returned by some non-ethernet drivers but in this case the
14928 		 * second check will fail.
14929 		 */
14930 		if (ill->ill_type == IFT_ETHER &&
14931 		    (mp->b_rptr - mp->b_datap->db_base) >=
14932 		    sizeof (struct ether_header)) {
14933 			mp->b_rptr -= sizeof (struct ether_header);
14934 			adjusted = B_TRUE;
14935 		}
14936 		mp1 = copymsg(mp);
14937 		if (mp1 == NULL) {
14938 			mp->b_next = NULL;
14939 			/* clear b_prev - used by ip_mroute_decap */
14940 			mp->b_prev = NULL;
14941 			freemsg(mp);
14942 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14943 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14944 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14945 			return;
14946 		}
14947 		if (adjusted) {
14948 			/*
14949 			 * Copy is done. Restore the pointer in the _new_ mblk
14950 			 */
14951 			mp1->b_rptr += sizeof (struct ether_header);
14952 		}
14953 		/* Copy b_prev - used by ip_mroute_decap */
14954 		mp1->b_prev = mp->b_prev;
14955 		mp->b_prev = NULL;
14956 		freemsg(mp);
14957 		mp = mp1;
14958 	}
14959 
14960 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14961 	    "ip_rput_end: q %p (%S)", q, "end");
14962 
14963 	ip_input(ill, NULL, mp, NULL);
14964 }
14965 
14966 /*
14967  * Direct read side procedure capable of dealing with chains. GLDv3 based
14968  * drivers call this function directly with mblk chains while STREAMS
14969  * read side procedure ip_rput() calls this for single packet with ip_ring
14970  * set to NULL to process one packet at a time.
14971  *
14972  * The ill will always be valid if this function is called directly from
14973  * the driver.
14974  *
14975  * If ip_input() is called from GLDv3:
14976  *
14977  *   - This must be a non-VLAN IP stream.
14978  *   - 'mp' is either an untagged or a special priority-tagged packet.
14979  *   - Any VLAN tag that was in the MAC header has been stripped.
14980  *
14981  * If the IP header in packet is not 32-bit aligned, every message in the
14982  * chain will be aligned before further operations. This is required on SPARC
14983  * platform.
14984  */
14985 /* ARGSUSED */
14986 void
14987 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14988     struct mac_header_info_s *mhip)
14989 {
14990 	ipaddr_t		dst = NULL;
14991 	ipaddr_t		prev_dst;
14992 	ire_t			*ire = NULL;
14993 	ipha_t			*ipha;
14994 	uint_t			pkt_len;
14995 	ssize_t			len;
14996 	uint_t			opt_len;
14997 	int			ll_multicast;
14998 	int			cgtp_flt_pkt;
14999 	queue_t			*q = ill->ill_rq;
15000 	squeue_t		*curr_sqp = NULL;
15001 	mblk_t 			*head = NULL;
15002 	mblk_t			*tail = NULL;
15003 	mblk_t			*first_mp;
15004 	mblk_t 			*mp;
15005 	mblk_t			*dmp;
15006 	int			cnt = 0;
15007 	ip_stack_t		*ipst = ill->ill_ipst;
15008 
15009 	ASSERT(mp_chain != NULL);
15010 	ASSERT(ill != NULL);
15011 
15012 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15013 
15014 #define	rptr	((uchar_t *)ipha)
15015 
15016 	while (mp_chain != NULL) {
15017 		first_mp = mp = mp_chain;
15018 		mp_chain = mp_chain->b_next;
15019 		mp->b_next = NULL;
15020 		ll_multicast = 0;
15021 
15022 		/*
15023 		 * We do ire caching from one iteration to
15024 		 * another. In the event the packet chain contains
15025 		 * all packets from the same dst, this caching saves
15026 		 * an ire_cache_lookup for each of the succeeding
15027 		 * packets in a packet chain.
15028 		 */
15029 		prev_dst = dst;
15030 
15031 		/*
15032 		 * Check and align the IP header.
15033 		 */
15034 		if (DB_TYPE(mp) == M_DATA) {
15035 			dmp = mp;
15036 		} else if (DB_TYPE(mp) == M_PROTO &&
15037 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15038 			dmp = mp->b_cont;
15039 		} else {
15040 			dmp = NULL;
15041 		}
15042 		if (dmp != NULL) {
15043 			/*
15044 			 * IP header ptr not aligned?
15045 			 * OR IP header not complete in first mblk
15046 			 */
15047 			if (!OK_32PTR(dmp->b_rptr) ||
15048 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15049 				if (!ip_check_and_align_header(q, dmp, ipst))
15050 					continue;
15051 			}
15052 		}
15053 
15054 		/*
15055 		 * ip_input fast path
15056 		 */
15057 
15058 		/* mblk type is not M_DATA */
15059 		if (DB_TYPE(mp) != M_DATA) {
15060 			if (ip_rput_process_notdata(q, &first_mp, ill,
15061 			    &ll_multicast, &mp))
15062 				continue;
15063 		}
15064 
15065 		/* Make sure its an M_DATA and that its aligned */
15066 		ASSERT(DB_TYPE(mp) == M_DATA);
15067 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15068 
15069 		ipha = (ipha_t *)mp->b_rptr;
15070 		len = mp->b_wptr - rptr;
15071 		pkt_len = ntohs(ipha->ipha_length);
15072 
15073 		/*
15074 		 * We must count all incoming packets, even if they end
15075 		 * up being dropped later on.
15076 		 */
15077 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15078 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15079 
15080 		/* multiple mblk or too short */
15081 		len -= pkt_len;
15082 		if (len != 0) {
15083 			/*
15084 			 * Make sure we have data length consistent
15085 			 * with the IP header.
15086 			 */
15087 			if (mp->b_cont == NULL) {
15088 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15089 					BUMP_MIB(ill->ill_ip_mib,
15090 					    ipIfStatsInHdrErrors);
15091 					ip2dbg(("ip_input: drop pkt\n"));
15092 					freemsg(mp);
15093 					continue;
15094 				}
15095 				mp->b_wptr = rptr + pkt_len;
15096 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15097 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15098 					BUMP_MIB(ill->ill_ip_mib,
15099 					    ipIfStatsInHdrErrors);
15100 					ip2dbg(("ip_input: drop pkt\n"));
15101 					freemsg(mp);
15102 					continue;
15103 				}
15104 				(void) adjmsg(mp, -len);
15105 				IP_STAT(ipst, ip_multimblk3);
15106 			}
15107 		}
15108 
15109 		/* Obtain the dst of the current packet */
15110 		dst = ipha->ipha_dst;
15111 
15112 		if (IP_LOOPBACK_ADDR(dst) ||
15113 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15114 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15115 			cmn_err(CE_CONT, "dst %X src %X\n",
15116 			    dst, ipha->ipha_src);
15117 			freemsg(mp);
15118 			continue;
15119 		}
15120 
15121 		/*
15122 		 * The event for packets being received from a 'physical'
15123 		 * interface is placed after validation of the source and/or
15124 		 * destination address as being local so that packets can be
15125 		 * redirected to loopback addresses using ipnat.
15126 		 */
15127 		DTRACE_PROBE4(ip4__physical__in__start,
15128 		    ill_t *, ill, ill_t *, NULL,
15129 		    ipha_t *, ipha, mblk_t *, first_mp);
15130 
15131 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15132 		    ipst->ips_ipv4firewall_physical_in,
15133 		    ill, NULL, ipha, first_mp, mp, ipst);
15134 
15135 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15136 
15137 		if (first_mp == NULL) {
15138 			continue;
15139 		}
15140 		dst = ipha->ipha_dst;
15141 
15142 		/*
15143 		 * Attach any necessary label information to
15144 		 * this packet
15145 		 */
15146 		if (is_system_labeled() &&
15147 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15148 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15149 			freemsg(mp);
15150 			continue;
15151 		}
15152 
15153 		/*
15154 		 * Reuse the cached ire only if the ipha_dst of the previous
15155 		 * packet is the same as the current packet AND it is not
15156 		 * INADDR_ANY.
15157 		 */
15158 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15159 		    (ire != NULL)) {
15160 			ire_refrele(ire);
15161 			ire = NULL;
15162 		}
15163 		opt_len = ipha->ipha_version_and_hdr_length -
15164 		    IP_SIMPLE_HDR_VERSION;
15165 
15166 		/*
15167 		 * Check to see if we can take the fastpath.
15168 		 * That is possible if the following conditions are met
15169 		 *	o Tsol disabled
15170 		 *	o CGTP disabled
15171 		 *	o ipp_action_count is 0
15172 		 *	o Mobile IP not running
15173 		 *	o no options in the packet
15174 		 *	o not a RSVP packet
15175 		 * 	o not a multicast packet
15176 		 */
15177 		if (!is_system_labeled() &&
15178 		    !ip_cgtp_filter && ipp_action_count == 0 &&
15179 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
15180 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15181 		    !ll_multicast && !CLASSD(dst)) {
15182 			if (ire == NULL)
15183 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15184 				    ipst);
15185 
15186 			/* incoming packet is for forwarding */
15187 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15188 				ire = ip_fast_forward(ire, dst, ill, mp);
15189 				continue;
15190 			}
15191 			/* incoming packet is for local consumption */
15192 			if (ire->ire_type & IRE_LOCAL)
15193 				goto local;
15194 		}
15195 
15196 		/*
15197 		 * Disable ire caching for anything more complex
15198 		 * than the simple fast path case we checked for above.
15199 		 */
15200 		if (ire != NULL) {
15201 			ire_refrele(ire);
15202 			ire = NULL;
15203 		}
15204 
15205 		/* Full-blown slow path */
15206 		if (opt_len != 0) {
15207 			if (len != 0)
15208 				IP_STAT(ipst, ip_multimblk4);
15209 			else
15210 				IP_STAT(ipst, ip_ipoptions);
15211 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15212 			    &dst, ipst))
15213 				continue;
15214 		}
15215 
15216 		/*
15217 		 * Invoke the CGTP (multirouting) filtering module to process
15218 		 * the incoming packet. Packets identified as duplicates
15219 		 * must be discarded. Filtering is active only if the
15220 		 * the ip_cgtp_filter ndd variable is non-zero.
15221 		 *
15222 		 * Only applies to the shared stack since the filter_ops
15223 		 * do not carry an ip_stack_t or zoneid.
15224 		 */
15225 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15226 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
15227 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
15228 			cgtp_flt_pkt =
15229 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15230 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15231 				freemsg(first_mp);
15232 				continue;
15233 			}
15234 		}
15235 
15236 		/*
15237 		 * If rsvpd is running, let RSVP daemon handle its processing
15238 		 * and forwarding of RSVP multicast/unicast packets.
15239 		 * If rsvpd is not running but mrouted is running, RSVP
15240 		 * multicast packets are forwarded as multicast traffic
15241 		 * and RSVP unicast packets are forwarded by unicast router.
15242 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15243 		 * packets are not forwarded, but the unicast packets are
15244 		 * forwarded like unicast traffic.
15245 		 */
15246 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15247 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15248 		    NULL) {
15249 			/* RSVP packet and rsvpd running. Treat as ours */
15250 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15251 			/*
15252 			 * This assumes that we deliver to all streams for
15253 			 * multicast and broadcast packets.
15254 			 * We have to force ll_multicast to 1 to handle the
15255 			 * M_DATA messages passed in from ip_mroute_decap.
15256 			 */
15257 			dst = INADDR_BROADCAST;
15258 			ll_multicast = 1;
15259 		} else if (CLASSD(dst)) {
15260 			/* packet is multicast */
15261 			mp->b_next = NULL;
15262 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15263 			    &ll_multicast, &dst))
15264 				continue;
15265 		}
15266 
15267 
15268 		/*
15269 		 * Check if the packet is coming from the Mobile IP
15270 		 * forward tunnel interface
15271 		 */
15272 		if (ill->ill_srcif_refcnt > 0) {
15273 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15274 			    NULL, ill, MATCH_IRE_TYPE);
15275 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15276 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15277 
15278 				/* We need to resolve the link layer info */
15279 				ire_refrele(ire);
15280 				ire = NULL;
15281 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15282 				    ll_multicast, dst);
15283 				continue;
15284 			}
15285 		}
15286 
15287 		if (ire == NULL) {
15288 			ire = ire_cache_lookup(dst, ALL_ZONES,
15289 			    MBLK_GETLABEL(mp), ipst);
15290 		}
15291 
15292 		/*
15293 		 * If mipagent is running and reverse tunnel is created as per
15294 		 * mobile node request, then any packet coming through the
15295 		 * incoming interface from the mobile-node, should be reverse
15296 		 * tunneled to it's home agent except those that are destined
15297 		 * to foreign agent only.
15298 		 * This needs source address based ire lookup. The routing
15299 		 * entries for source address based lookup are only created by
15300 		 * mipagent program only when a reverse tunnel is created.
15301 		 * Reference : RFC2002, RFC2344
15302 		 */
15303 		if (ill->ill_mrtun_refcnt > 0) {
15304 			ipaddr_t	srcaddr;
15305 			ire_t		*tmp_ire;
15306 
15307 			tmp_ire = ire;	/* Save, we might need it later */
15308 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15309 			    ire->ire_type != IRE_BROADCAST)) {
15310 				srcaddr = ipha->ipha_src;
15311 				ire = ire_mrtun_lookup(srcaddr, ill);
15312 				if (ire != NULL) {
15313 					/*
15314 					 * Should not be getting iphada packet
15315 					 * here. we should only get those for
15316 					 * IRE_LOCAL traffic, excluded above.
15317 					 * Fail-safe (drop packet) in the event
15318 					 * hardware is misbehaving.
15319 					 */
15320 					if (first_mp != mp) {
15321 						/* IPsec KSTATS: beancount me */
15322 						freemsg(first_mp);
15323 					} else {
15324 						/*
15325 						 * This packet must be forwarded
15326 						 * to Reverse Tunnel
15327 						 */
15328 						ip_mrtun_forward(ire, ill, mp);
15329 					}
15330 					ire_refrele(ire);
15331 					ire = NULL;
15332 					if (tmp_ire != NULL) {
15333 						ire_refrele(tmp_ire);
15334 						tmp_ire = NULL;
15335 					}
15336 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15337 					    "ip_input_end: q %p (%S)",
15338 					    q, "uninit");
15339 					continue;
15340 				}
15341 			}
15342 			/*
15343 			 * If this packet is from a non-mobilenode  or a
15344 			 * mobile-node which does not request reverse
15345 			 * tunnel service
15346 			 */
15347 			ire = tmp_ire;
15348 		}
15349 
15350 
15351 		/*
15352 		 * If we reach here that means the incoming packet satisfies
15353 		 * one of the following conditions:
15354 		 *   - packet is from a mobile node which does not request
15355 		 *	reverse tunnel
15356 		 *   - packet is from a non-mobile node, which is the most
15357 		 *	common case
15358 		 *   - packet is from a reverse tunnel enabled mobile node
15359 		 *	and destined to foreign agent only
15360 		 */
15361 
15362 		if (ire == NULL) {
15363 			/*
15364 			 * No IRE for this destination, so it can't be for us.
15365 			 * Unless we are forwarding, drop the packet.
15366 			 * We have to let source routed packets through
15367 			 * since we don't yet know if they are 'ping -l'
15368 			 * packets i.e. if they will go out over the
15369 			 * same interface as they came in on.
15370 			 */
15371 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15372 			if (ire == NULL)
15373 				continue;
15374 		}
15375 
15376 		/*
15377 		 * Broadcast IRE may indicate either broadcast or
15378 		 * multicast packet
15379 		 */
15380 		if (ire->ire_type == IRE_BROADCAST) {
15381 			/*
15382 			 * Skip broadcast checks if packet is UDP multicast;
15383 			 * we'd rather not enter ip_rput_process_broadcast()
15384 			 * unless the packet is broadcast for real, since
15385 			 * that routine is a no-op for multicast.
15386 			 */
15387 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15388 			    !CLASSD(ipha->ipha_dst)) {
15389 				ire = ip_rput_process_broadcast(&q, mp,
15390 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15391 				    ll_multicast);
15392 				if (ire == NULL)
15393 					continue;
15394 			}
15395 		} else if (ire->ire_stq != NULL) {
15396 			/* fowarding? */
15397 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15398 			    ll_multicast);
15399 			/* ip_rput_process_forward consumed the packet */
15400 			continue;
15401 		}
15402 
15403 local:
15404 		/*
15405 		 * If the queue in the ire is different to the ingress queue
15406 		 * then we need to check to see if we can accept the packet.
15407 		 * Note that for multicast packets and broadcast packets sent
15408 		 * to a broadcast address which is shared between multiple
15409 		 * interfaces we should not do this since we just got a random
15410 		 * broadcast ire.
15411 		 */
15412 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15413 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15414 			    ill)) == NULL) {
15415 				/* Drop packet */
15416 				BUMP_MIB(ill->ill_ip_mib,
15417 				    ipIfStatsForwProhibits);
15418 				freemsg(mp);
15419 				continue;
15420 			}
15421 			if (ire->ire_rfq != NULL)
15422 				q = ire->ire_rfq;
15423 		}
15424 
15425 		switch (ipha->ipha_protocol) {
15426 		case IPPROTO_TCP:
15427 			ASSERT(first_mp == mp);
15428 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15429 			    mp, 0, q, ip_ring)) != NULL) {
15430 				if (curr_sqp == NULL) {
15431 					curr_sqp = GET_SQUEUE(mp);
15432 					ASSERT(cnt == 0);
15433 					cnt++;
15434 					head = tail = mp;
15435 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15436 					ASSERT(tail != NULL);
15437 					cnt++;
15438 					tail->b_next = mp;
15439 					tail = mp;
15440 				} else {
15441 					/*
15442 					 * A different squeue. Send the
15443 					 * chain for the previous squeue on
15444 					 * its way. This shouldn't happen
15445 					 * often unless interrupt binding
15446 					 * changes.
15447 					 */
15448 					IP_STAT(ipst, ip_input_multi_squeue);
15449 					squeue_enter_chain(curr_sqp, head,
15450 					    tail, cnt, SQTAG_IP_INPUT);
15451 					curr_sqp = GET_SQUEUE(mp);
15452 					head = mp;
15453 					tail = mp;
15454 					cnt = 1;
15455 				}
15456 			}
15457 			continue;
15458 		case IPPROTO_UDP:
15459 			ASSERT(first_mp == mp);
15460 			ip_udp_input(q, mp, ipha, ire, ill);
15461 			continue;
15462 		case IPPROTO_SCTP:
15463 			ASSERT(first_mp == mp);
15464 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15465 			    q, dst);
15466 			/* ire has been released by ip_sctp_input */
15467 			ire = NULL;
15468 			continue;
15469 		default:
15470 			ip_proto_input(q, first_mp, ipha, ire, ill);
15471 			continue;
15472 		}
15473 	}
15474 
15475 	if (ire != NULL)
15476 		ire_refrele(ire);
15477 
15478 	if (head != NULL)
15479 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15480 
15481 	/*
15482 	 * This code is there just to make netperf/ttcp look good.
15483 	 *
15484 	 * Its possible that after being in polling mode (and having cleared
15485 	 * the backlog), squeues have turned the interrupt frequency higher
15486 	 * to improve latency at the expense of more CPU utilization (less
15487 	 * packets per interrupts or more number of interrupts). Workloads
15488 	 * like ttcp/netperf do manage to tickle polling once in a while
15489 	 * but for the remaining time, stay in higher interrupt mode since
15490 	 * their packet arrival rate is pretty uniform and this shows up
15491 	 * as higher CPU utilization. Since people care about CPU utilization
15492 	 * while running netperf/ttcp, turn the interrupt frequency back to
15493 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15494 	 */
15495 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15496 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15497 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15498 			ip_ring->rr_blank(ip_ring->rr_handle,
15499 			    ip_ring->rr_normal_blank_time,
15500 			    ip_ring->rr_normal_pkt_cnt);
15501 		}
15502 		}
15503 
15504 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15505 	    "ip_input_end: q %p (%S)", q, "end");
15506 #undef  rptr
15507 }
15508 
15509 static void
15510 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15511     t_uscalar_t err)
15512 {
15513 	if (dl_err == DL_SYSERR) {
15514 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15515 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15516 		    ill->ill_name, dlpi_prim_str(prim), err);
15517 		return;
15518 	}
15519 
15520 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15521 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15522 	    dlpi_err_str(dl_err));
15523 }
15524 
15525 /*
15526  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15527  * than DL_UNITDATA_IND messages. If we need to process this message
15528  * exclusively, we call qwriter_ip, in which case we also need to call
15529  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15530  */
15531 void
15532 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15533 {
15534 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15535 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15536 	ill_t		*ill = (ill_t *)q->q_ptr;
15537 	boolean_t	pending;
15538 
15539 	ip1dbg(("ip_rput_dlpi"));
15540 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15541 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15542 		    "%s (0x%x), unix %u\n", ill->ill_name,
15543 		    dlpi_prim_str(dlea->dl_error_primitive),
15544 		    dlea->dl_error_primitive,
15545 		    dlpi_err_str(dlea->dl_errno),
15546 		    dlea->dl_errno,
15547 		    dlea->dl_unix_errno));
15548 	}
15549 
15550 	/*
15551 	 * If we received an ACK but didn't send a request for it, then it
15552 	 * can't be part of any pending operation; discard up-front.
15553 	 */
15554 	switch (dloa->dl_primitive) {
15555 	case DL_NOTIFY_IND:
15556 		pending = B_TRUE;
15557 		break;
15558 	case DL_ERROR_ACK:
15559 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15560 		break;
15561 	case DL_OK_ACK:
15562 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15563 		break;
15564 	case DL_INFO_ACK:
15565 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15566 		break;
15567 	case DL_BIND_ACK:
15568 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15569 		break;
15570 	case DL_PHYS_ADDR_ACK:
15571 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15572 		break;
15573 	case DL_NOTIFY_ACK:
15574 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15575 		break;
15576 	case DL_CONTROL_ACK:
15577 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15578 		break;
15579 	case DL_CAPABILITY_ACK:
15580 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15581 		break;
15582 	default:
15583 		/* Not a DLPI message we support or were expecting */
15584 		freemsg(mp);
15585 		return;
15586 	}
15587 
15588 	if (!pending) {
15589 		freemsg(mp);
15590 		return;
15591 	}
15592 
15593 	switch (dloa->dl_primitive) {
15594 	case DL_ERROR_ACK:
15595 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15596 			mutex_enter(&ill->ill_lock);
15597 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15598 			cv_signal(&ill->ill_cv);
15599 			mutex_exit(&ill->ill_lock);
15600 		}
15601 		break;
15602 
15603 	case DL_OK_ACK:
15604 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15605 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15606 		switch (dloa->dl_correct_primitive) {
15607 		case DL_UNBIND_REQ:
15608 			mutex_enter(&ill->ill_lock);
15609 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15610 			cv_signal(&ill->ill_cv);
15611 			mutex_exit(&ill->ill_lock);
15612 			break;
15613 
15614 		case DL_ENABMULTI_REQ:
15615 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15616 				ill->ill_dlpi_multicast_state = IDS_OK;
15617 			break;
15618 		}
15619 		break;
15620 	default:
15621 		break;
15622 	}
15623 
15624 	/*
15625 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15626 	 * and we need to become writer to continue to process it. If it's not
15627 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15628 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15629 	 * some work as part of the current exclusive operation that actually
15630 	 * is not part of it -- which is wrong, but better than the
15631 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15632 	 * should track which DLPI requests have ACKs that we wait on
15633 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15634 	 *
15635 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15636 	 * Since this is on the ill stream we unconditionally bump up the
15637 	 * refcount without doing ILL_CAN_LOOKUP().
15638 	 */
15639 	ill_refhold(ill);
15640 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15641 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15642 	else
15643 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15644 }
15645 
15646 /*
15647  * Handling of DLPI messages that require exclusive access to the ipsq.
15648  *
15649  * Need to do ill_pending_mp_release on ioctl completion, which could
15650  * happen here. (along with mi_copy_done)
15651  */
15652 /* ARGSUSED */
15653 static void
15654 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15655 {
15656 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15657 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15658 	int		err = 0;
15659 	ill_t		*ill;
15660 	ipif_t		*ipif = NULL;
15661 	mblk_t		*mp1 = NULL;
15662 	conn_t		*connp = NULL;
15663 	t_uscalar_t	paddrreq;
15664 	mblk_t		*mp_hw;
15665 	boolean_t	success;
15666 	boolean_t	ioctl_aborted = B_FALSE;
15667 	boolean_t	log = B_TRUE;
15668 	hook_nic_event_t	*info;
15669 	ip_stack_t		*ipst;
15670 
15671 	ip1dbg(("ip_rput_dlpi_writer .."));
15672 	ill = (ill_t *)q->q_ptr;
15673 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15674 
15675 	ASSERT(IAM_WRITER_ILL(ill));
15676 
15677 	ipst = ill->ill_ipst;
15678 
15679 	/*
15680 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15681 	 * both are null or non-null. However we can assert that only
15682 	 * after grabbing the ipsq_lock. So we don't make any assertion
15683 	 * here and in other places in the code.
15684 	 */
15685 	ipif = ipsq->ipsq_pending_ipif;
15686 	/*
15687 	 * The current ioctl could have been aborted by the user and a new
15688 	 * ioctl to bring up another ill could have started. We could still
15689 	 * get a response from the driver later.
15690 	 */
15691 	if (ipif != NULL && ipif->ipif_ill != ill)
15692 		ioctl_aborted = B_TRUE;
15693 
15694 	switch (dloa->dl_primitive) {
15695 	case DL_ERROR_ACK:
15696 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15697 		    dlpi_prim_str(dlea->dl_error_primitive)));
15698 
15699 		switch (dlea->dl_error_primitive) {
15700 		case DL_PROMISCON_REQ:
15701 		case DL_PROMISCOFF_REQ:
15702 		case DL_DISABMULTI_REQ:
15703 		case DL_UNBIND_REQ:
15704 		case DL_ATTACH_REQ:
15705 		case DL_INFO_REQ:
15706 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15707 			break;
15708 		case DL_NOTIFY_REQ:
15709 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15710 			log = B_FALSE;
15711 			break;
15712 		case DL_PHYS_ADDR_REQ:
15713 			/*
15714 			 * For IPv6 only, there are two additional
15715 			 * phys_addr_req's sent to the driver to get the
15716 			 * IPv6 token and lla. This allows IP to acquire
15717 			 * the hardware address format for a given interface
15718 			 * without having built in knowledge of the hardware
15719 			 * address. ill_phys_addr_pend keeps track of the last
15720 			 * DL_PAR sent so we know which response we are
15721 			 * dealing with. ill_dlpi_done will update
15722 			 * ill_phys_addr_pend when it sends the next req.
15723 			 * We don't complete the IOCTL until all three DL_PARs
15724 			 * have been attempted, so set *_len to 0 and break.
15725 			 */
15726 			paddrreq = ill->ill_phys_addr_pend;
15727 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15728 			if (paddrreq == DL_IPV6_TOKEN) {
15729 				ill->ill_token_length = 0;
15730 				log = B_FALSE;
15731 				break;
15732 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15733 				ill->ill_nd_lla_len = 0;
15734 				log = B_FALSE;
15735 				break;
15736 			}
15737 			/*
15738 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15739 			 * We presumably have an IOCTL hanging out waiting
15740 			 * for completion. Find it and complete the IOCTL
15741 			 * with the error noted.
15742 			 * However, ill_dl_phys was called on an ill queue
15743 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15744 			 * set. But the ioctl is known to be pending on ill_wq.
15745 			 */
15746 			if (!ill->ill_ifname_pending)
15747 				break;
15748 			ill->ill_ifname_pending = 0;
15749 			if (!ioctl_aborted)
15750 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15751 			if (mp1 != NULL) {
15752 				/*
15753 				 * This operation (SIOCSLIFNAME) must have
15754 				 * happened on the ill. Assert there is no conn
15755 				 */
15756 				ASSERT(connp == NULL);
15757 				q = ill->ill_wq;
15758 			}
15759 			break;
15760 		case DL_BIND_REQ:
15761 			ill_dlpi_done(ill, DL_BIND_REQ);
15762 			if (ill->ill_ifname_pending)
15763 				break;
15764 			/*
15765 			 * Something went wrong with the bind.  We presumably
15766 			 * have an IOCTL hanging out waiting for completion.
15767 			 * Find it, take down the interface that was coming
15768 			 * up, and complete the IOCTL with the error noted.
15769 			 */
15770 			if (!ioctl_aborted)
15771 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15772 			if (mp1 != NULL) {
15773 				/*
15774 				 * This operation (SIOCSLIFFLAGS) must have
15775 				 * happened from a conn.
15776 				 */
15777 				ASSERT(connp != NULL);
15778 				q = CONNP_TO_WQ(connp);
15779 				if (ill->ill_move_in_progress) {
15780 					ILL_CLEAR_MOVE(ill);
15781 				}
15782 				(void) ipif_down(ipif, NULL, NULL);
15783 				/* error is set below the switch */
15784 			}
15785 			break;
15786 		case DL_ENABMULTI_REQ:
15787 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15788 
15789 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15790 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15791 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15792 				ipif_t *ipif;
15793 
15794 				printf("ip: joining multicasts failed (%d)"
15795 				    " on %s - will use link layer "
15796 				    "broadcasts for multicast\n",
15797 				    dlea->dl_errno, ill->ill_name);
15798 
15799 				/*
15800 				 * Set up the multicast mapping alone.
15801 				 * writer, so ok to access ill->ill_ipif
15802 				 * without any lock.
15803 				 */
15804 				ipif = ill->ill_ipif;
15805 				mutex_enter(&ill->ill_phyint->phyint_lock);
15806 				ill->ill_phyint->phyint_flags |=
15807 				    PHYI_MULTI_BCAST;
15808 				mutex_exit(&ill->ill_phyint->phyint_lock);
15809 
15810 				if (!ill->ill_isv6) {
15811 					(void) ipif_arp_setup_multicast(ipif,
15812 					    NULL);
15813 				} else {
15814 					(void) ipif_ndp_setup_multicast(ipif,
15815 					    NULL);
15816 				}
15817 			}
15818 			freemsg(mp);	/* Don't want to pass this up */
15819 			return;
15820 
15821 		case DL_CAPABILITY_REQ:
15822 		case DL_CONTROL_REQ:
15823 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15824 			ill->ill_dlpi_capab_state = IDS_FAILED;
15825 			freemsg(mp);
15826 			return;
15827 		}
15828 		/*
15829 		 * Note the error for IOCTL completion (mp1 is set when
15830 		 * ready to complete ioctl). If ill_ifname_pending_err is
15831 		 * set, an error occured during plumbing (ill_ifname_pending),
15832 		 * so we want to report that error.
15833 		 *
15834 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15835 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15836 		 * expected to get errack'd if the driver doesn't support
15837 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15838 		 * if these error conditions are encountered.
15839 		 */
15840 		if (mp1 != NULL) {
15841 			if (ill->ill_ifname_pending_err != 0)  {
15842 				err = ill->ill_ifname_pending_err;
15843 				ill->ill_ifname_pending_err = 0;
15844 			} else {
15845 				err = dlea->dl_unix_errno ?
15846 				    dlea->dl_unix_errno : ENXIO;
15847 			}
15848 		/*
15849 		 * If we're plumbing an interface and an error hasn't already
15850 		 * been saved, set ill_ifname_pending_err to the error passed
15851 		 * up. Ignore the error if log is B_FALSE (see comment above).
15852 		 */
15853 		} else if (log && ill->ill_ifname_pending &&
15854 		    ill->ill_ifname_pending_err == 0) {
15855 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15856 			    dlea->dl_unix_errno : ENXIO;
15857 		}
15858 
15859 		if (log)
15860 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15861 			    dlea->dl_errno, dlea->dl_unix_errno);
15862 		break;
15863 	case DL_CAPABILITY_ACK: {
15864 		boolean_t reneg_flag = B_FALSE;
15865 		/* Call a routine to handle this one. */
15866 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15867 		/*
15868 		 * Check if the ACK is due to renegotiation case since we
15869 		 * will need to send a new CAPABILITY_REQ later.
15870 		 */
15871 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15872 			/* This is the ack for a renogiation case */
15873 			reneg_flag = B_TRUE;
15874 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15875 		}
15876 		ill_capability_ack(ill, mp);
15877 		if (reneg_flag)
15878 			ill_capability_probe(ill);
15879 		break;
15880 	}
15881 	case DL_CONTROL_ACK:
15882 		/* We treat all of these as "fire and forget" */
15883 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15884 		break;
15885 	case DL_INFO_ACK:
15886 		/* Call a routine to handle this one. */
15887 		ill_dlpi_done(ill, DL_INFO_REQ);
15888 		ip_ll_subnet_defaults(ill, mp);
15889 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15890 		return;
15891 	case DL_BIND_ACK:
15892 		/*
15893 		 * We should have an IOCTL waiting on this unless
15894 		 * sent by ill_dl_phys, in which case just return
15895 		 */
15896 		ill_dlpi_done(ill, DL_BIND_REQ);
15897 		if (ill->ill_ifname_pending)
15898 			break;
15899 
15900 		if (!ioctl_aborted)
15901 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15902 		if (mp1 == NULL)
15903 			break;
15904 		/*
15905 		 * Because mp1 was added by ill_dl_up(), and it always
15906 		 * passes a valid connp, connp must be valid here.
15907 		 */
15908 		ASSERT(connp != NULL);
15909 		q = CONNP_TO_WQ(connp);
15910 
15911 		/*
15912 		 * We are exclusive. So nothing can change even after
15913 		 * we get the pending mp. If need be we can put it back
15914 		 * and restart, as in calling ipif_arp_up()  below.
15915 		 */
15916 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15917 
15918 		mutex_enter(&ill->ill_lock);
15919 
15920 		ill->ill_dl_up = 1;
15921 
15922 		if ((info = ill->ill_nic_event_info) != NULL) {
15923 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15924 			    "attached for %s\n", info->hne_event,
15925 			    ill->ill_name));
15926 			if (info->hne_data != NULL)
15927 				kmem_free(info->hne_data, info->hne_datalen);
15928 			kmem_free(info, sizeof (hook_nic_event_t));
15929 		}
15930 
15931 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15932 		if (info != NULL) {
15933 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15934 			info->hne_lif = 0;
15935 			info->hne_event = NE_UP;
15936 			info->hne_data = NULL;
15937 			info->hne_datalen = 0;
15938 			info->hne_family = ill->ill_isv6 ?
15939 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15940 		} else
15941 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15942 			    "event information for %s (ENOMEM)\n",
15943 			    ill->ill_name));
15944 
15945 		ill->ill_nic_event_info = info;
15946 
15947 		mutex_exit(&ill->ill_lock);
15948 
15949 		/*
15950 		 * Now bring up the resolver; when that is complete, we'll
15951 		 * create IREs.  Note that we intentionally mirror what
15952 		 * ipif_up() would have done, because we got here by way of
15953 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15954 		 */
15955 		if (ill->ill_isv6) {
15956 			/*
15957 			 * v6 interfaces.
15958 			 * Unlike ARP which has to do another bind
15959 			 * and attach, once we get here we are
15960 			 * done with NDP. Except in the case of
15961 			 * ILLF_XRESOLV, in which case we send an
15962 			 * AR_INTERFACE_UP to the external resolver.
15963 			 * If all goes well, the ioctl will complete
15964 			 * in ip_rput(). If there's an error, we
15965 			 * complete it here.
15966 			 */
15967 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
15968 			if (err == 0) {
15969 				if (ill->ill_flags & ILLF_XRESOLV) {
15970 					mutex_enter(&connp->conn_lock);
15971 					mutex_enter(&ill->ill_lock);
15972 					success = ipsq_pending_mp_add(
15973 					    connp, ipif, q, mp1, 0);
15974 					mutex_exit(&ill->ill_lock);
15975 					mutex_exit(&connp->conn_lock);
15976 					if (success) {
15977 						err = ipif_resolver_up(ipif,
15978 						    Res_act_initial);
15979 						if (err == EINPROGRESS) {
15980 							freemsg(mp);
15981 							return;
15982 						}
15983 						ASSERT(err != 0);
15984 						mp1 = ipsq_pending_mp_get(ipsq,
15985 						    &connp);
15986 						ASSERT(mp1 != NULL);
15987 					} else {
15988 						/* conn has started closing */
15989 						err = EINTR;
15990 					}
15991 				} else { /* Non XRESOLV interface */
15992 					(void) ipif_resolver_up(ipif,
15993 					    Res_act_initial);
15994 					err = ipif_up_done_v6(ipif);
15995 				}
15996 			}
15997 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15998 			/*
15999 			 * ARP and other v4 external resolvers.
16000 			 * Leave the pending mblk intact so that
16001 			 * the ioctl completes in ip_rput().
16002 			 */
16003 			mutex_enter(&connp->conn_lock);
16004 			mutex_enter(&ill->ill_lock);
16005 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16006 			mutex_exit(&ill->ill_lock);
16007 			mutex_exit(&connp->conn_lock);
16008 			if (success) {
16009 				err = ipif_resolver_up(ipif, Res_act_initial);
16010 				if (err == EINPROGRESS) {
16011 					freemsg(mp);
16012 					return;
16013 				}
16014 				ASSERT(err != 0);
16015 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16016 			} else {
16017 				/* The conn has started closing */
16018 				err = EINTR;
16019 			}
16020 		} else {
16021 			/*
16022 			 * This one is complete. Reply to pending ioctl.
16023 			 */
16024 			(void) ipif_resolver_up(ipif, Res_act_initial);
16025 			err = ipif_up_done(ipif);
16026 		}
16027 
16028 		if ((err == 0) && (ill->ill_up_ipifs)) {
16029 			err = ill_up_ipifs(ill, q, mp1);
16030 			if (err == EINPROGRESS) {
16031 				freemsg(mp);
16032 				return;
16033 			}
16034 		}
16035 
16036 		if (ill->ill_up_ipifs) {
16037 			ill_group_cleanup(ill);
16038 		}
16039 
16040 		break;
16041 	case DL_NOTIFY_IND: {
16042 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16043 		ire_t *ire;
16044 		boolean_t need_ire_walk_v4 = B_FALSE;
16045 		boolean_t need_ire_walk_v6 = B_FALSE;
16046 
16047 		switch (notify->dl_notification) {
16048 		case DL_NOTE_PHYS_ADDR:
16049 			err = ill_set_phys_addr(ill, mp);
16050 			break;
16051 
16052 		case DL_NOTE_FASTPATH_FLUSH:
16053 			ill_fastpath_flush(ill);
16054 			break;
16055 
16056 		case DL_NOTE_SDU_SIZE:
16057 			/*
16058 			 * Change the MTU size of the interface, of all
16059 			 * attached ipif's, and of all relevant ire's.  The
16060 			 * new value's a uint32_t at notify->dl_data.
16061 			 * Mtu change Vs. new ire creation - protocol below.
16062 			 *
16063 			 * a Mark the ipif as IPIF_CHANGING.
16064 			 * b Set the new mtu in the ipif.
16065 			 * c Change the ire_max_frag on all affected ires
16066 			 * d Unmark the IPIF_CHANGING
16067 			 *
16068 			 * To see how the protocol works, assume an interface
16069 			 * route is also being added simultaneously by
16070 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16071 			 * the ire. If the ire is created before step a,
16072 			 * it will be cleaned up by step c. If the ire is
16073 			 * created after step d, it will see the new value of
16074 			 * ipif_mtu. Any attempt to create the ire between
16075 			 * steps a to d will fail because of the IPIF_CHANGING
16076 			 * flag. Note that ire_create() is passed a pointer to
16077 			 * the ipif_mtu, and not the value. During ire_add
16078 			 * under the bucket lock, the ire_max_frag of the
16079 			 * new ire being created is set from the ipif/ire from
16080 			 * which it is being derived.
16081 			 */
16082 			mutex_enter(&ill->ill_lock);
16083 			ill->ill_max_frag = (uint_t)notify->dl_data;
16084 
16085 			/*
16086 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16087 			 * leave it alone
16088 			 */
16089 			if (ill->ill_mtu_userspecified) {
16090 				mutex_exit(&ill->ill_lock);
16091 				break;
16092 			}
16093 			ill->ill_max_mtu = ill->ill_max_frag;
16094 			if (ill->ill_isv6) {
16095 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16096 					ill->ill_max_mtu = IPV6_MIN_MTU;
16097 			} else {
16098 				if (ill->ill_max_mtu < IP_MIN_MTU)
16099 					ill->ill_max_mtu = IP_MIN_MTU;
16100 			}
16101 			for (ipif = ill->ill_ipif; ipif != NULL;
16102 			    ipif = ipif->ipif_next) {
16103 				/*
16104 				 * Don't override the mtu if the user
16105 				 * has explicitly set it.
16106 				 */
16107 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16108 					continue;
16109 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16110 				if (ipif->ipif_isv6)
16111 					ire = ipif_to_ire_v6(ipif);
16112 				else
16113 					ire = ipif_to_ire(ipif);
16114 				if (ire != NULL) {
16115 					ire->ire_max_frag = ipif->ipif_mtu;
16116 					ire_refrele(ire);
16117 				}
16118 				if (ipif->ipif_flags & IPIF_UP) {
16119 					if (ill->ill_isv6)
16120 						need_ire_walk_v6 = B_TRUE;
16121 					else
16122 						need_ire_walk_v4 = B_TRUE;
16123 				}
16124 			}
16125 			mutex_exit(&ill->ill_lock);
16126 			if (need_ire_walk_v4)
16127 				ire_walk_v4(ill_mtu_change, (char *)ill,
16128 				    ALL_ZONES, ipst);
16129 			if (need_ire_walk_v6)
16130 				ire_walk_v6(ill_mtu_change, (char *)ill,
16131 				    ALL_ZONES, ipst);
16132 			break;
16133 		case DL_NOTE_LINK_UP:
16134 		case DL_NOTE_LINK_DOWN: {
16135 			/*
16136 			 * We are writer. ill / phyint / ipsq assocs stable.
16137 			 * The RUNNING flag reflects the state of the link.
16138 			 */
16139 			phyint_t *phyint = ill->ill_phyint;
16140 			uint64_t new_phyint_flags;
16141 			boolean_t changed = B_FALSE;
16142 			boolean_t went_up;
16143 
16144 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16145 			mutex_enter(&phyint->phyint_lock);
16146 			new_phyint_flags = went_up ?
16147 			    phyint->phyint_flags | PHYI_RUNNING :
16148 			    phyint->phyint_flags & ~PHYI_RUNNING;
16149 			if (new_phyint_flags != phyint->phyint_flags) {
16150 				phyint->phyint_flags = new_phyint_flags;
16151 				changed = B_TRUE;
16152 			}
16153 			mutex_exit(&phyint->phyint_lock);
16154 			/*
16155 			 * ill_restart_dad handles the DAD restart and routing
16156 			 * socket notification logic.
16157 			 */
16158 			if (changed) {
16159 				ill_restart_dad(phyint->phyint_illv4, went_up);
16160 				ill_restart_dad(phyint->phyint_illv6, went_up);
16161 			}
16162 			break;
16163 		}
16164 		case DL_NOTE_PROMISC_ON_PHYS:
16165 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16166 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16167 			mutex_enter(&ill->ill_lock);
16168 			ill->ill_promisc_on_phys = B_TRUE;
16169 			mutex_exit(&ill->ill_lock);
16170 			break;
16171 		case DL_NOTE_PROMISC_OFF_PHYS:
16172 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16173 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16174 			mutex_enter(&ill->ill_lock);
16175 			ill->ill_promisc_on_phys = B_FALSE;
16176 			mutex_exit(&ill->ill_lock);
16177 			break;
16178 		case DL_NOTE_CAPAB_RENEG:
16179 			/*
16180 			 * Something changed on the driver side.
16181 			 * It wants us to renegotiate the capabilities
16182 			 * on this ill. The most likely cause is the
16183 			 * aggregation interface under us where a
16184 			 * port got added or went away.
16185 			 *
16186 			 * We reset the capabilities and set the
16187 			 * state to IDS_RENG so that when the ack
16188 			 * comes back, we can start the
16189 			 * renegotiation process.
16190 			 */
16191 			ill_capability_reset(ill);
16192 			ill->ill_dlpi_capab_state = IDS_RENEG;
16193 			break;
16194 		default:
16195 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16196 			    "type 0x%x for DL_NOTIFY_IND\n",
16197 			    notify->dl_notification));
16198 			break;
16199 		}
16200 
16201 		/*
16202 		 * As this is an asynchronous operation, we
16203 		 * should not call ill_dlpi_done
16204 		 */
16205 		break;
16206 	}
16207 	case DL_NOTIFY_ACK: {
16208 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16209 
16210 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16211 			ill->ill_note_link = 1;
16212 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16213 		break;
16214 	}
16215 	case DL_PHYS_ADDR_ACK: {
16216 		/*
16217 		 * As part of plumbing the interface via SIOCSLIFNAME,
16218 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16219 		 * whose answers we receive here.  As each answer is received,
16220 		 * we call ill_dlpi_done() to dispatch the next request as
16221 		 * we're processing the current one.  Once all answers have
16222 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16223 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16224 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16225 		 * available, but we know the ioctl is pending on ill_wq.)
16226 		 */
16227 		uint_t paddrlen, paddroff;
16228 
16229 		paddrreq = ill->ill_phys_addr_pend;
16230 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16231 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16232 
16233 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16234 		if (paddrreq == DL_IPV6_TOKEN) {
16235 			/*
16236 			 * bcopy to low-order bits of ill_token
16237 			 *
16238 			 * XXX Temporary hack - currently, all known tokens
16239 			 * are 64 bits, so I'll cheat for the moment.
16240 			 */
16241 			bcopy(mp->b_rptr + paddroff,
16242 			    &ill->ill_token.s6_addr32[2], paddrlen);
16243 			ill->ill_token_length = paddrlen;
16244 			break;
16245 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16246 			ASSERT(ill->ill_nd_lla_mp == NULL);
16247 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16248 			mp = NULL;
16249 			break;
16250 		}
16251 
16252 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16253 		ASSERT(ill->ill_phys_addr_mp == NULL);
16254 		if (!ill->ill_ifname_pending)
16255 			break;
16256 		ill->ill_ifname_pending = 0;
16257 		if (!ioctl_aborted)
16258 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16259 		if (mp1 != NULL) {
16260 			ASSERT(connp == NULL);
16261 			q = ill->ill_wq;
16262 		}
16263 		/*
16264 		 * If any error acks received during the plumbing sequence,
16265 		 * ill_ifname_pending_err will be set. Break out and send up
16266 		 * the error to the pending ioctl.
16267 		 */
16268 		if (ill->ill_ifname_pending_err != 0) {
16269 			err = ill->ill_ifname_pending_err;
16270 			ill->ill_ifname_pending_err = 0;
16271 			break;
16272 		}
16273 
16274 		ill->ill_phys_addr_mp = mp;
16275 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16276 		mp = NULL;
16277 
16278 		/*
16279 		 * If paddrlen is zero, the DLPI provider doesn't support
16280 		 * physical addresses.  The other two tests were historical
16281 		 * workarounds for bugs in our former PPP implementation, but
16282 		 * now other things have grown dependencies on them -- e.g.,
16283 		 * the tun module specifies a dl_addr_length of zero in its
16284 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16285 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16286 		 * but only after careful testing ensures that all dependent
16287 		 * broken DLPI providers have been fixed.
16288 		 */
16289 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16290 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16291 			ill->ill_phys_addr = NULL;
16292 		} else if (paddrlen != ill->ill_phys_addr_length) {
16293 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16294 			    paddrlen, ill->ill_phys_addr_length));
16295 			err = EINVAL;
16296 			break;
16297 		}
16298 
16299 		if (ill->ill_nd_lla_mp == NULL) {
16300 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16301 				err = ENOMEM;
16302 				break;
16303 			}
16304 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16305 		}
16306 
16307 		/*
16308 		 * Set the interface token.  If the zeroth interface address
16309 		 * is unspecified, then set it to the link local address.
16310 		 */
16311 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16312 			(void) ill_setdefaulttoken(ill);
16313 
16314 		ASSERT(ill->ill_ipif->ipif_id == 0);
16315 		if (ipif != NULL &&
16316 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16317 			(void) ipif_setlinklocal(ipif);
16318 		}
16319 		break;
16320 	}
16321 	case DL_OK_ACK:
16322 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16323 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16324 		    dloa->dl_correct_primitive));
16325 		switch (dloa->dl_correct_primitive) {
16326 		case DL_PROMISCON_REQ:
16327 		case DL_PROMISCOFF_REQ:
16328 		case DL_ENABMULTI_REQ:
16329 		case DL_DISABMULTI_REQ:
16330 		case DL_UNBIND_REQ:
16331 		case DL_ATTACH_REQ:
16332 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16333 			break;
16334 		}
16335 		break;
16336 	default:
16337 		break;
16338 	}
16339 
16340 	freemsg(mp);
16341 	if (mp1 != NULL) {
16342 		/*
16343 		 * The operation must complete without EINPROGRESS
16344 		 * since ipsq_pending_mp_get() has removed the mblk
16345 		 * from ipsq_pending_mp.  Otherwise, the operation
16346 		 * will be stuck forever in the ipsq.
16347 		 */
16348 		ASSERT(err != EINPROGRESS);
16349 
16350 		switch (ipsq->ipsq_current_ioctl) {
16351 		case 0:
16352 			ipsq_current_finish(ipsq);
16353 			break;
16354 
16355 		case SIOCLIFADDIF:
16356 		case SIOCSLIFNAME:
16357 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16358 			break;
16359 
16360 		default:
16361 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16362 			break;
16363 		}
16364 	}
16365 }
16366 
16367 /*
16368  * ip_rput_other is called by ip_rput to handle messages modifying the global
16369  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16370  */
16371 /* ARGSUSED */
16372 void
16373 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16374 {
16375 	ill_t		*ill;
16376 	struct iocblk	*iocp;
16377 	mblk_t		*mp1;
16378 	conn_t		*connp = NULL;
16379 
16380 	ip1dbg(("ip_rput_other "));
16381 	ill = (ill_t *)q->q_ptr;
16382 	/*
16383 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16384 	 * in which case ipsq is NULL.
16385 	 */
16386 	if (ipsq != NULL) {
16387 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16388 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16389 	}
16390 
16391 	switch (mp->b_datap->db_type) {
16392 	case M_ERROR:
16393 	case M_HANGUP:
16394 		/*
16395 		 * The device has a problem.  We force the ILL down.  It can
16396 		 * be brought up again manually using SIOCSIFFLAGS (via
16397 		 * ifconfig or equivalent).
16398 		 */
16399 		ASSERT(ipsq != NULL);
16400 		if (mp->b_rptr < mp->b_wptr)
16401 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16402 		if (ill->ill_error == 0)
16403 			ill->ill_error = ENXIO;
16404 		if (!ill_down_start(q, mp))
16405 			return;
16406 		ipif_all_down_tail(ipsq, q, mp, NULL);
16407 		break;
16408 	case M_IOCACK:
16409 		iocp = (struct iocblk *)mp->b_rptr;
16410 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16411 		switch (iocp->ioc_cmd) {
16412 		case SIOCSTUNPARAM:
16413 		case OSIOCSTUNPARAM:
16414 			ASSERT(ipsq != NULL);
16415 			/*
16416 			 * Finish socket ioctl passed through to tun.
16417 			 * We should have an IOCTL waiting on this.
16418 			 */
16419 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16420 			if (ill->ill_isv6) {
16421 				struct iftun_req *ta;
16422 
16423 				/*
16424 				 * if a source or destination is
16425 				 * being set, try and set the link
16426 				 * local address for the tunnel
16427 				 */
16428 				ta = (struct iftun_req *)mp->b_cont->
16429 				    b_cont->b_rptr;
16430 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16431 					ipif_set_tun_llink(ill, ta);
16432 				}
16433 
16434 			}
16435 			if (mp1 != NULL) {
16436 				/*
16437 				 * Now copy back the b_next/b_prev used by
16438 				 * mi code for the mi_copy* functions.
16439 				 * See ip_sioctl_tunparam() for the reason.
16440 				 * Also protect against missing b_cont.
16441 				 */
16442 				if (mp->b_cont != NULL) {
16443 					mp->b_cont->b_next =
16444 					    mp1->b_cont->b_next;
16445 					mp->b_cont->b_prev =
16446 					    mp1->b_cont->b_prev;
16447 				}
16448 				inet_freemsg(mp1);
16449 				ASSERT(connp != NULL);
16450 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16451 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16452 			} else {
16453 				ASSERT(connp == NULL);
16454 				putnext(q, mp);
16455 			}
16456 			break;
16457 		case SIOCGTUNPARAM:
16458 		case OSIOCGTUNPARAM:
16459 			/*
16460 			 * This is really M_IOCDATA from the tunnel driver.
16461 			 * convert back and complete the ioctl.
16462 			 * We should have an IOCTL waiting on this.
16463 			 */
16464 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16465 			if (mp1) {
16466 				/*
16467 				 * Now copy back the b_next/b_prev used by
16468 				 * mi code for the mi_copy* functions.
16469 				 * See ip_sioctl_tunparam() for the reason.
16470 				 * Also protect against missing b_cont.
16471 				 */
16472 				if (mp->b_cont != NULL) {
16473 					mp->b_cont->b_next =
16474 					    mp1->b_cont->b_next;
16475 					mp->b_cont->b_prev =
16476 					    mp1->b_cont->b_prev;
16477 				}
16478 				inet_freemsg(mp1);
16479 				if (iocp->ioc_error == 0)
16480 					mp->b_datap->db_type = M_IOCDATA;
16481 				ASSERT(connp != NULL);
16482 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16483 				    iocp->ioc_error, COPYOUT, NULL);
16484 			} else {
16485 				ASSERT(connp == NULL);
16486 				putnext(q, mp);
16487 			}
16488 			break;
16489 		default:
16490 			break;
16491 		}
16492 		break;
16493 	case M_IOCNAK:
16494 		iocp = (struct iocblk *)mp->b_rptr;
16495 
16496 		switch (iocp->ioc_cmd) {
16497 		int mode;
16498 
16499 		case DL_IOC_HDR_INFO:
16500 			/*
16501 			 * If this was the first attempt turn of the
16502 			 * fastpath probing.
16503 			 */
16504 			mutex_enter(&ill->ill_lock);
16505 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16506 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16507 				mutex_exit(&ill->ill_lock);
16508 				ill_fastpath_nack(ill);
16509 				ip1dbg(("ip_rput: DLPI fastpath off on "
16510 				    "interface %s\n",
16511 				    ill->ill_name));
16512 			} else {
16513 				mutex_exit(&ill->ill_lock);
16514 			}
16515 			freemsg(mp);
16516 			break;
16517 		case SIOCSTUNPARAM:
16518 		case OSIOCSTUNPARAM:
16519 			ASSERT(ipsq != NULL);
16520 			/*
16521 			 * Finish socket ioctl passed through to tun
16522 			 * We should have an IOCTL waiting on this.
16523 			 */
16524 			/* FALLTHRU */
16525 		case SIOCGTUNPARAM:
16526 		case OSIOCGTUNPARAM:
16527 			/*
16528 			 * This is really M_IOCDATA from the tunnel driver.
16529 			 * convert back and complete the ioctl.
16530 			 * We should have an IOCTL waiting on this.
16531 			 */
16532 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16533 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16534 				mp1 = ill_pending_mp_get(ill, &connp,
16535 				    iocp->ioc_id);
16536 				mode = COPYOUT;
16537 				ipsq = NULL;
16538 			} else {
16539 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16540 				mode = NO_COPYOUT;
16541 			}
16542 			if (mp1 != NULL) {
16543 				/*
16544 				 * Now copy back the b_next/b_prev used by
16545 				 * mi code for the mi_copy* functions.
16546 				 * See ip_sioctl_tunparam() for the reason.
16547 				 * Also protect against missing b_cont.
16548 				 */
16549 				if (mp->b_cont != NULL) {
16550 					mp->b_cont->b_next =
16551 					    mp1->b_cont->b_next;
16552 					mp->b_cont->b_prev =
16553 					    mp1->b_cont->b_prev;
16554 				}
16555 				inet_freemsg(mp1);
16556 				if (iocp->ioc_error == 0)
16557 					iocp->ioc_error = EINVAL;
16558 				ASSERT(connp != NULL);
16559 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16560 				    iocp->ioc_error, mode, ipsq);
16561 			} else {
16562 				ASSERT(connp == NULL);
16563 				putnext(q, mp);
16564 			}
16565 			break;
16566 		default:
16567 			break;
16568 		}
16569 	default:
16570 		break;
16571 	}
16572 }
16573 
16574 /*
16575  * NOTE : This function does not ire_refrele the ire argument passed in.
16576  *
16577  * IPQoS notes
16578  * IP policy is invoked twice for a forwarded packet, once on the read side
16579  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16580  * enabled. An additional parameter, in_ill, has been added for this purpose.
16581  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16582  * because ip_mroute drops this information.
16583  *
16584  */
16585 void
16586 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16587 {
16588 	uint32_t	old_pkt_len;
16589 	uint32_t	pkt_len;
16590 	queue_t	*q;
16591 	uint32_t	sum;
16592 #define	rptr	((uchar_t *)ipha)
16593 	uint32_t	max_frag;
16594 	uint32_t	ill_index;
16595 	ill_t		*out_ill;
16596 	mib2_ipIfStatsEntry_t *mibptr;
16597 	ip_stack_t	*ipst = in_ill->ill_ipst;
16598 
16599 	/* Get the ill_index of the incoming ILL */
16600 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16601 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16602 
16603 	/* Initiate Read side IPPF processing */
16604 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16605 		ip_process(IPP_FWD_IN, &mp, ill_index);
16606 		if (mp == NULL) {
16607 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16608 			    "during IPPF processing\n"));
16609 			return;
16610 		}
16611 	}
16612 
16613 	/* Adjust the checksum to reflect the ttl decrement. */
16614 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16615 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16616 
16617 	if (ipha->ipha_ttl-- <= 1) {
16618 		if (ip_csum_hdr(ipha)) {
16619 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16620 			goto drop_pkt;
16621 		}
16622 		/*
16623 		 * Note: ire_stq this will be NULL for multicast
16624 		 * datagrams using the long path through arp (the IRE
16625 		 * is not an IRE_CACHE). This should not cause
16626 		 * problems since we don't generate ICMP errors for
16627 		 * multicast packets.
16628 		 */
16629 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16630 		q = ire->ire_stq;
16631 		if (q != NULL) {
16632 			/* Sent by forwarding path, and router is global zone */
16633 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16634 			    GLOBAL_ZONEID, ipst);
16635 		} else
16636 			freemsg(mp);
16637 		return;
16638 	}
16639 
16640 	/*
16641 	 * Don't forward if the interface is down
16642 	 */
16643 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16644 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16645 		ip2dbg(("ip_rput_forward:interface is down\n"));
16646 		goto drop_pkt;
16647 	}
16648 
16649 	/* Get the ill_index of the outgoing ILL */
16650 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16651 
16652 	out_ill = ire->ire_ipif->ipif_ill;
16653 
16654 	DTRACE_PROBE4(ip4__forwarding__start,
16655 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16656 
16657 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16658 	    ipst->ips_ipv4firewall_forwarding,
16659 	    in_ill, out_ill, ipha, mp, mp, ipst);
16660 
16661 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16662 
16663 	if (mp == NULL)
16664 		return;
16665 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16666 
16667 	if (is_system_labeled()) {
16668 		mblk_t *mp1;
16669 
16670 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16671 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16672 			goto drop_pkt;
16673 		}
16674 		/* Size may have changed */
16675 		mp = mp1;
16676 		ipha = (ipha_t *)mp->b_rptr;
16677 		pkt_len = ntohs(ipha->ipha_length);
16678 	}
16679 
16680 	/* Check if there are options to update */
16681 	if (!IS_SIMPLE_IPH(ipha)) {
16682 		if (ip_csum_hdr(ipha)) {
16683 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16684 			goto drop_pkt;
16685 		}
16686 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16687 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16688 			return;
16689 		}
16690 
16691 		ipha->ipha_hdr_checksum = 0;
16692 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16693 	}
16694 	max_frag = ire->ire_max_frag;
16695 	if (pkt_len > max_frag) {
16696 		/*
16697 		 * It needs fragging on its way out.  We haven't
16698 		 * verified the header checksum yet.  Since we
16699 		 * are going to put a surely good checksum in the
16700 		 * outgoing header, we have to make sure that it
16701 		 * was good coming in.
16702 		 */
16703 		if (ip_csum_hdr(ipha)) {
16704 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16705 			goto drop_pkt;
16706 		}
16707 		/* Initiate Write side IPPF processing */
16708 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16709 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16710 			if (mp == NULL) {
16711 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16712 				    " during IPPF processing\n"));
16713 				return;
16714 			}
16715 		}
16716 		/*
16717 		 * Handle labeled packet resizing.
16718 		 *
16719 		 * If we have added a label, inform ip_wput_frag() of its
16720 		 * effect on the MTU for ICMP messages.
16721 		 */
16722 		if (pkt_len > old_pkt_len) {
16723 			uint32_t secopt_size;
16724 
16725 			secopt_size = pkt_len - old_pkt_len;
16726 			if (secopt_size < max_frag)
16727 				max_frag -= secopt_size;
16728 		}
16729 
16730 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16731 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16732 		return;
16733 	}
16734 
16735 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16736 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16737 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16738 	    ipst->ips_ipv4firewall_physical_out,
16739 	    NULL, out_ill, ipha, mp, mp, ipst);
16740 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16741 	if (mp == NULL)
16742 		return;
16743 
16744 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16745 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16746 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16747 	/* ip_xmit_v4 always consumes the packet */
16748 	return;
16749 
16750 drop_pkt:;
16751 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16752 	freemsg(mp);
16753 #undef	rptr
16754 }
16755 
16756 void
16757 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16758 {
16759 	ire_t	*ire;
16760 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16761 
16762 	ASSERT(!ipif->ipif_isv6);
16763 	/*
16764 	 * Find an IRE which matches the destination and the outgoing
16765 	 * queue in the cache table. All we need is an IRE_CACHE which
16766 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16767 	 * then it is enough to have some IRE_CACHE in the group.
16768 	 */
16769 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16770 		dst = ipif->ipif_pp_dst_addr;
16771 
16772 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16773 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16774 	if (ire == NULL) {
16775 		/*
16776 		 * Mark this packet to make it be delivered to
16777 		 * ip_rput_forward after the new ire has been
16778 		 * created.
16779 		 */
16780 		mp->b_prev = NULL;
16781 		mp->b_next = mp;
16782 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16783 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16784 	} else {
16785 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16786 		IRE_REFRELE(ire);
16787 	}
16788 }
16789 
16790 /* Update any source route, record route or timestamp options */
16791 static int
16792 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16793 {
16794 	ipoptp_t	opts;
16795 	uchar_t		*opt;
16796 	uint8_t		optval;
16797 	uint8_t		optlen;
16798 	ipaddr_t	dst;
16799 	uint32_t	ts;
16800 	ire_t		*dst_ire = NULL;
16801 	ire_t		*tmp_ire = NULL;
16802 	timestruc_t	now;
16803 
16804 	ip2dbg(("ip_rput_forward_options\n"));
16805 	dst = ipha->ipha_dst;
16806 	for (optval = ipoptp_first(&opts, ipha);
16807 	    optval != IPOPT_EOL;
16808 	    optval = ipoptp_next(&opts)) {
16809 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16810 		opt = opts.ipoptp_cur;
16811 		optlen = opts.ipoptp_len;
16812 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16813 		    optval, opts.ipoptp_len));
16814 		switch (optval) {
16815 			uint32_t off;
16816 		case IPOPT_SSRR:
16817 		case IPOPT_LSRR:
16818 			/* Check if adminstratively disabled */
16819 			if (!ipst->ips_ip_forward_src_routed) {
16820 				if (ire->ire_stq != NULL) {
16821 					/*
16822 					 * Sent by forwarding path, and router
16823 					 * is global zone
16824 					 */
16825 					icmp_unreachable(ire->ire_stq, mp,
16826 					    ICMP_SOURCE_ROUTE_FAILED,
16827 					    GLOBAL_ZONEID, ipst);
16828 				} else {
16829 					ip0dbg(("ip_rput_forward_options: "
16830 					    "unable to send unreach\n"));
16831 					freemsg(mp);
16832 				}
16833 				return (-1);
16834 			}
16835 
16836 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16837 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16838 			if (dst_ire == NULL) {
16839 				/*
16840 				 * Must be partial since ip_rput_options
16841 				 * checked for strict.
16842 				 */
16843 				break;
16844 			}
16845 			off = opt[IPOPT_OFFSET];
16846 			off--;
16847 		redo_srr:
16848 			if (optlen < IP_ADDR_LEN ||
16849 			    off > optlen - IP_ADDR_LEN) {
16850 				/* End of source route */
16851 				ip1dbg((
16852 				    "ip_rput_forward_options: end of SR\n"));
16853 				ire_refrele(dst_ire);
16854 				break;
16855 			}
16856 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16857 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16858 			    IP_ADDR_LEN);
16859 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16860 			    ntohl(dst)));
16861 
16862 			/*
16863 			 * Check if our address is present more than
16864 			 * once as consecutive hops in source route.
16865 			 */
16866 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16867 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16868 			if (tmp_ire != NULL) {
16869 				ire_refrele(tmp_ire);
16870 				off += IP_ADDR_LEN;
16871 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16872 				goto redo_srr;
16873 			}
16874 			ipha->ipha_dst = dst;
16875 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16876 			ire_refrele(dst_ire);
16877 			break;
16878 		case IPOPT_RR:
16879 			off = opt[IPOPT_OFFSET];
16880 			off--;
16881 			if (optlen < IP_ADDR_LEN ||
16882 			    off > optlen - IP_ADDR_LEN) {
16883 				/* No more room - ignore */
16884 				ip1dbg((
16885 				    "ip_rput_forward_options: end of RR\n"));
16886 				break;
16887 			}
16888 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16889 			    IP_ADDR_LEN);
16890 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16891 			break;
16892 		case IPOPT_TS:
16893 			/* Insert timestamp if there is room */
16894 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16895 			case IPOPT_TS_TSONLY:
16896 				off = IPOPT_TS_TIMELEN;
16897 				break;
16898 			case IPOPT_TS_PRESPEC:
16899 			case IPOPT_TS_PRESPEC_RFC791:
16900 				/* Verify that the address matched */
16901 				off = opt[IPOPT_OFFSET] - 1;
16902 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16903 				dst_ire = ire_ctable_lookup(dst, 0,
16904 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16905 				    MATCH_IRE_TYPE, ipst);
16906 				if (dst_ire == NULL) {
16907 					/* Not for us */
16908 					break;
16909 				}
16910 				ire_refrele(dst_ire);
16911 				/* FALLTHRU */
16912 			case IPOPT_TS_TSANDADDR:
16913 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16914 				break;
16915 			default:
16916 				/*
16917 				 * ip_*put_options should have already
16918 				 * dropped this packet.
16919 				 */
16920 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16921 				    "unknown IT - bug in ip_rput_options?\n");
16922 				return (0);	/* Keep "lint" happy */
16923 			}
16924 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16925 				/* Increase overflow counter */
16926 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16927 				opt[IPOPT_POS_OV_FLG] =
16928 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16929 				    (off << 4));
16930 				break;
16931 			}
16932 			off = opt[IPOPT_OFFSET] - 1;
16933 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16934 			case IPOPT_TS_PRESPEC:
16935 			case IPOPT_TS_PRESPEC_RFC791:
16936 			case IPOPT_TS_TSANDADDR:
16937 				bcopy(&ire->ire_src_addr,
16938 				    (char *)opt + off, IP_ADDR_LEN);
16939 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16940 				/* FALLTHRU */
16941 			case IPOPT_TS_TSONLY:
16942 				off = opt[IPOPT_OFFSET] - 1;
16943 				/* Compute # of milliseconds since midnight */
16944 				gethrestime(&now);
16945 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16946 				    now.tv_nsec / (NANOSEC / MILLISEC);
16947 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16948 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16949 				break;
16950 			}
16951 			break;
16952 		}
16953 	}
16954 	return (0);
16955 }
16956 
16957 /*
16958  * This is called after processing at least one of AH/ESP headers.
16959  *
16960  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16961  * the actual, physical interface on which the packet was received,
16962  * but, when ip_strict_dst_multihoming is set to 1, could be the
16963  * interface which had the ipha_dst configured when the packet went
16964  * through ip_rput. The ill_index corresponding to the recv_ill
16965  * is saved in ipsec_in_rill_index
16966  *
16967  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16968  * cannot assume "ire" points to valid data for any IPv6 cases.
16969  */
16970 void
16971 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16972 {
16973 	mblk_t *mp;
16974 	ipaddr_t dst;
16975 	in6_addr_t *v6dstp;
16976 	ipha_t *ipha;
16977 	ip6_t *ip6h;
16978 	ipsec_in_t *ii;
16979 	boolean_t ill_need_rele = B_FALSE;
16980 	boolean_t rill_need_rele = B_FALSE;
16981 	boolean_t ire_need_rele = B_FALSE;
16982 	netstack_t	*ns;
16983 	ip_stack_t	*ipst;
16984 
16985 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16986 	ASSERT(ii->ipsec_in_ill_index != 0);
16987 	ns = ii->ipsec_in_ns;
16988 	ASSERT(ii->ipsec_in_ns != NULL);
16989 	ipst = ns->netstack_ip;
16990 
16991 	mp = ipsec_mp->b_cont;
16992 	ASSERT(mp != NULL);
16993 
16994 
16995 	if (ill == NULL) {
16996 		ASSERT(recv_ill == NULL);
16997 		/*
16998 		 * We need to get the original queue on which ip_rput_local
16999 		 * or ip_rput_data_v6 was called.
17000 		 */
17001 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17002 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17003 		ill_need_rele = B_TRUE;
17004 
17005 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17006 			recv_ill = ill_lookup_on_ifindex(
17007 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17008 			    NULL, NULL, NULL, NULL, ipst);
17009 			rill_need_rele = B_TRUE;
17010 		} else {
17011 			recv_ill = ill;
17012 		}
17013 
17014 		if ((ill == NULL) || (recv_ill == NULL)) {
17015 			ip0dbg(("ip_fanout_proto_again: interface "
17016 			    "disappeared\n"));
17017 			if (ill != NULL)
17018 				ill_refrele(ill);
17019 			if (recv_ill != NULL)
17020 				ill_refrele(recv_ill);
17021 			freemsg(ipsec_mp);
17022 			return;
17023 		}
17024 	}
17025 
17026 	ASSERT(ill != NULL && recv_ill != NULL);
17027 
17028 	if (mp->b_datap->db_type == M_CTL) {
17029 		/*
17030 		 * AH/ESP is returning the ICMP message after
17031 		 * removing their headers. Fanout again till
17032 		 * it gets to the right protocol.
17033 		 */
17034 		if (ii->ipsec_in_v4) {
17035 			icmph_t *icmph;
17036 			int iph_hdr_length;
17037 			int hdr_length;
17038 
17039 			ipha = (ipha_t *)mp->b_rptr;
17040 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17041 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17042 			ipha = (ipha_t *)&icmph[1];
17043 			hdr_length = IPH_HDR_LENGTH(ipha);
17044 			/*
17045 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17046 			 * Reset the type to M_DATA.
17047 			 */
17048 			mp->b_datap->db_type = M_DATA;
17049 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17050 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17051 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17052 		} else {
17053 			icmp6_t *icmp6;
17054 			int hdr_length;
17055 
17056 			ip6h = (ip6_t *)mp->b_rptr;
17057 			/* Don't call hdr_length_v6() unless you have to. */
17058 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17059 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17060 			else
17061 				hdr_length = IPV6_HDR_LEN;
17062 
17063 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17064 			/*
17065 			 * icmp_inbound_error_fanout_v6 may need to do
17066 			 * pullupmsg.  Reset the type to M_DATA.
17067 			 */
17068 			mp->b_datap->db_type = M_DATA;
17069 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17070 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17071 		}
17072 		if (ill_need_rele)
17073 			ill_refrele(ill);
17074 		if (rill_need_rele)
17075 			ill_refrele(recv_ill);
17076 		return;
17077 	}
17078 
17079 	if (ii->ipsec_in_v4) {
17080 		ipha = (ipha_t *)mp->b_rptr;
17081 		dst = ipha->ipha_dst;
17082 		if (CLASSD(dst)) {
17083 			/*
17084 			 * Multicast has to be delivered to all streams.
17085 			 */
17086 			dst = INADDR_BROADCAST;
17087 		}
17088 
17089 		if (ire == NULL) {
17090 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17091 			    MBLK_GETLABEL(mp), ipst);
17092 			if (ire == NULL) {
17093 				if (ill_need_rele)
17094 					ill_refrele(ill);
17095 				if (rill_need_rele)
17096 					ill_refrele(recv_ill);
17097 				ip1dbg(("ip_fanout_proto_again: "
17098 				    "IRE not found"));
17099 				freemsg(ipsec_mp);
17100 				return;
17101 			}
17102 			ire_need_rele = B_TRUE;
17103 		}
17104 
17105 		switch (ipha->ipha_protocol) {
17106 			case IPPROTO_UDP:
17107 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17108 				    recv_ill);
17109 				if (ire_need_rele)
17110 					ire_refrele(ire);
17111 				break;
17112 			case IPPROTO_TCP:
17113 				if (!ire_need_rele)
17114 					IRE_REFHOLD(ire);
17115 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17116 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17117 				IRE_REFRELE(ire);
17118 				if (mp != NULL)
17119 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17120 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17121 				break;
17122 			case IPPROTO_SCTP:
17123 				if (!ire_need_rele)
17124 					IRE_REFHOLD(ire);
17125 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17126 				    ipsec_mp, 0, ill->ill_rq, dst);
17127 				break;
17128 			default:
17129 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17130 				    recv_ill);
17131 				if (ire_need_rele)
17132 					ire_refrele(ire);
17133 				break;
17134 		}
17135 	} else {
17136 		uint32_t rput_flags = 0;
17137 
17138 		ip6h = (ip6_t *)mp->b_rptr;
17139 		v6dstp = &ip6h->ip6_dst;
17140 		/*
17141 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17142 		 * address.
17143 		 *
17144 		 * Currently, we don't store that state in the IPSEC_IN
17145 		 * message, and we may need to.
17146 		 */
17147 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17148 		    IP6_IN_LLMCAST : 0);
17149 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17150 		    NULL, NULL);
17151 	}
17152 	if (ill_need_rele)
17153 		ill_refrele(ill);
17154 	if (rill_need_rele)
17155 		ill_refrele(recv_ill);
17156 }
17157 
17158 /*
17159  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17160  * returns 'true' if there are still fragments left on the queue, in
17161  * which case we restart the timer.
17162  */
17163 void
17164 ill_frag_timer(void *arg)
17165 {
17166 	ill_t	*ill = (ill_t *)arg;
17167 	boolean_t frag_pending;
17168 	ip_stack_t	*ipst = ill->ill_ipst;
17169 
17170 	mutex_enter(&ill->ill_lock);
17171 	ASSERT(!ill->ill_fragtimer_executing);
17172 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17173 		ill->ill_frag_timer_id = 0;
17174 		mutex_exit(&ill->ill_lock);
17175 		return;
17176 	}
17177 	ill->ill_fragtimer_executing = 1;
17178 	mutex_exit(&ill->ill_lock);
17179 
17180 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17181 
17182 	/*
17183 	 * Restart the timer, if we have fragments pending or if someone
17184 	 * wanted us to be scheduled again.
17185 	 */
17186 	mutex_enter(&ill->ill_lock);
17187 	ill->ill_fragtimer_executing = 0;
17188 	ill->ill_frag_timer_id = 0;
17189 	if (frag_pending || ill->ill_fragtimer_needrestart)
17190 		ill_frag_timer_start(ill);
17191 	mutex_exit(&ill->ill_lock);
17192 }
17193 
17194 void
17195 ill_frag_timer_start(ill_t *ill)
17196 {
17197 	ip_stack_t	*ipst = ill->ill_ipst;
17198 
17199 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17200 
17201 	/* If the ill is closing or opening don't proceed */
17202 	if (ill->ill_state_flags & ILL_CONDEMNED)
17203 		return;
17204 
17205 	if (ill->ill_fragtimer_executing) {
17206 		/*
17207 		 * ill_frag_timer is currently executing. Just record the
17208 		 * the fact that we want the timer to be restarted.
17209 		 * ill_frag_timer will post a timeout before it returns,
17210 		 * ensuring it will be called again.
17211 		 */
17212 		ill->ill_fragtimer_needrestart = 1;
17213 		return;
17214 	}
17215 
17216 	if (ill->ill_frag_timer_id == 0) {
17217 		/*
17218 		 * The timer is neither running nor is the timeout handler
17219 		 * executing. Post a timeout so that ill_frag_timer will be
17220 		 * called
17221 		 */
17222 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17223 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17224 		ill->ill_fragtimer_needrestart = 0;
17225 	}
17226 }
17227 
17228 /*
17229  * This routine is needed for loopback when forwarding multicasts.
17230  *
17231  * IPQoS Notes:
17232  * IPPF processing is done in fanout routines.
17233  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17234  * processing for IPSec packets is done when it comes back in clear.
17235  * NOTE : The callers of this function need to do the ire_refrele for the
17236  *	  ire that is being passed in.
17237  */
17238 void
17239 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17240     ill_t *recv_ill)
17241 {
17242 	ill_t	*ill = (ill_t *)q->q_ptr;
17243 	uint32_t	sum;
17244 	uint32_t	u1;
17245 	uint32_t	u2;
17246 	int		hdr_length;
17247 	boolean_t	mctl_present;
17248 	mblk_t		*first_mp = mp;
17249 	mblk_t		*hada_mp = NULL;
17250 	ipha_t		*inner_ipha;
17251 	ip_stack_t	*ipst;
17252 
17253 	ASSERT(recv_ill != NULL);
17254 	ipst = recv_ill->ill_ipst;
17255 
17256 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17257 	    "ip_rput_locl_start: q %p", q);
17258 
17259 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17260 	ASSERT(ill != NULL);
17261 
17262 
17263 #define	rptr	((uchar_t *)ipha)
17264 #define	iphs	((uint16_t *)ipha)
17265 
17266 	/*
17267 	 * no UDP or TCP packet should come here anymore.
17268 	 */
17269 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17270 	    (ipha->ipha_protocol != IPPROTO_UDP));
17271 
17272 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17273 	if (mctl_present &&
17274 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17275 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17276 
17277 		/*
17278 		 * It's an IPsec accelerated packet.
17279 		 * Keep a pointer to the data attributes around until
17280 		 * we allocate the ipsec_info_t.
17281 		 */
17282 		IPSECHW_DEBUG(IPSECHW_PKT,
17283 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17284 		hada_mp = first_mp;
17285 		hada_mp->b_cont = NULL;
17286 		/*
17287 		 * Since it is accelerated, it comes directly from
17288 		 * the ill and the data attributes is followed by
17289 		 * the packet data.
17290 		 */
17291 		ASSERT(mp->b_datap->db_type != M_CTL);
17292 		first_mp = mp;
17293 		mctl_present = B_FALSE;
17294 	}
17295 
17296 	/*
17297 	 * IF M_CTL is not present, then ipsec_in_is_secure
17298 	 * should return B_TRUE. There is a case where loopback
17299 	 * packets has an M_CTL in the front with all the
17300 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17301 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17302 	 * packets never comes here, it is safe to ASSERT the
17303 	 * following.
17304 	 */
17305 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17306 
17307 
17308 	/* u1 is # words of IP options */
17309 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17310 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17311 
17312 	if (u1) {
17313 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17314 			if (hada_mp != NULL)
17315 				freemsg(hada_mp);
17316 			return;
17317 		}
17318 	} else {
17319 		/* Check the IP header checksum.  */
17320 #define	uph	((uint16_t *)ipha)
17321 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17322 		    uph[6] + uph[7] + uph[8] + uph[9];
17323 #undef  uph
17324 		/* finish doing IP checksum */
17325 		sum = (sum & 0xFFFF) + (sum >> 16);
17326 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17327 		/*
17328 		 * Don't verify header checksum if this packet is coming
17329 		 * back from AH/ESP as we already did it.
17330 		 */
17331 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17332 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17333 			goto drop_pkt;
17334 		}
17335 	}
17336 
17337 	/*
17338 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17339 	 * might be called more than once for secure packets, count only
17340 	 * the first time.
17341 	 */
17342 	if (!mctl_present) {
17343 		UPDATE_IB_PKT_COUNT(ire);
17344 		ire->ire_last_used_time = lbolt;
17345 	}
17346 
17347 	/* Check for fragmentation offset. */
17348 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17349 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17350 	if (u1) {
17351 		/*
17352 		 * We re-assemble fragments before we do the AH/ESP
17353 		 * processing. Thus, M_CTL should not be present
17354 		 * while we are re-assembling.
17355 		 */
17356 		ASSERT(!mctl_present);
17357 		ASSERT(first_mp == mp);
17358 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17359 			return;
17360 		}
17361 		/*
17362 		 * Make sure that first_mp points back to mp as
17363 		 * the mp we came in with could have changed in
17364 		 * ip_rput_fragment().
17365 		 */
17366 		ipha = (ipha_t *)mp->b_rptr;
17367 		first_mp = mp;
17368 	}
17369 
17370 	/*
17371 	 * Clear hardware checksumming flag as it is currently only
17372 	 * used by TCP and UDP.
17373 	 */
17374 	DB_CKSUMFLAGS(mp) = 0;
17375 
17376 	/* Now we have a complete datagram, destined for this machine. */
17377 	u1 = IPH_HDR_LENGTH(ipha);
17378 	switch (ipha->ipha_protocol) {
17379 	case IPPROTO_ICMP: {
17380 		ire_t		*ire_zone;
17381 		ilm_t		*ilm;
17382 		mblk_t		*mp1;
17383 		zoneid_t	last_zoneid;
17384 
17385 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17386 			ASSERT(ire->ire_type == IRE_BROADCAST);
17387 			/*
17388 			 * In the multicast case, applications may have joined
17389 			 * the group from different zones, so we need to deliver
17390 			 * the packet to each of them. Loop through the
17391 			 * multicast memberships structures (ilm) on the receive
17392 			 * ill and send a copy of the packet up each matching
17393 			 * one. However, we don't do this for multicasts sent on
17394 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17395 			 * they must stay in the sender's zone.
17396 			 *
17397 			 * ilm_add_v6() ensures that ilms in the same zone are
17398 			 * contiguous in the ill_ilm list. We use this property
17399 			 * to avoid sending duplicates needed when two
17400 			 * applications in the same zone join the same group on
17401 			 * different logical interfaces: we ignore the ilm if
17402 			 * its zoneid is the same as the last matching one.
17403 			 * In addition, the sending of the packet for
17404 			 * ire_zoneid is delayed until all of the other ilms
17405 			 * have been exhausted.
17406 			 */
17407 			last_zoneid = -1;
17408 			ILM_WALKER_HOLD(recv_ill);
17409 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17410 			    ilm = ilm->ilm_next) {
17411 				if ((ilm->ilm_flags & ILM_DELETED) ||
17412 				    ipha->ipha_dst != ilm->ilm_addr ||
17413 				    ilm->ilm_zoneid == last_zoneid ||
17414 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17415 				    ilm->ilm_zoneid == ALL_ZONES ||
17416 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17417 					continue;
17418 				mp1 = ip_copymsg(first_mp);
17419 				if (mp1 == NULL)
17420 					continue;
17421 				icmp_inbound(q, mp1, B_TRUE, ill,
17422 				    0, sum, mctl_present, B_TRUE,
17423 				    recv_ill, ilm->ilm_zoneid);
17424 				last_zoneid = ilm->ilm_zoneid;
17425 			}
17426 			ILM_WALKER_RELE(recv_ill);
17427 		} else if (ire->ire_type == IRE_BROADCAST) {
17428 			/*
17429 			 * In the broadcast case, there may be many zones
17430 			 * which need a copy of the packet delivered to them.
17431 			 * There is one IRE_BROADCAST per broadcast address
17432 			 * and per zone; we walk those using a helper function.
17433 			 * In addition, the sending of the packet for ire is
17434 			 * delayed until all of the other ires have been
17435 			 * processed.
17436 			 */
17437 			IRB_REFHOLD(ire->ire_bucket);
17438 			ire_zone = NULL;
17439 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17440 			    ire)) != NULL) {
17441 				mp1 = ip_copymsg(first_mp);
17442 				if (mp1 == NULL)
17443 					continue;
17444 
17445 				UPDATE_IB_PKT_COUNT(ire_zone);
17446 				ire_zone->ire_last_used_time = lbolt;
17447 				icmp_inbound(q, mp1, B_TRUE, ill,
17448 				    0, sum, mctl_present, B_TRUE,
17449 				    recv_ill, ire_zone->ire_zoneid);
17450 			}
17451 			IRB_REFRELE(ire->ire_bucket);
17452 		}
17453 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17454 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17455 		    ire->ire_zoneid);
17456 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17457 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17458 		return;
17459 	}
17460 	case IPPROTO_IGMP:
17461 		/*
17462 		 * If we are not willing to accept IGMP packets in clear,
17463 		 * then check with global policy.
17464 		 */
17465 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17466 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17467 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17468 			if (first_mp == NULL)
17469 				return;
17470 		}
17471 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17472 			freemsg(first_mp);
17473 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17474 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17475 			return;
17476 		}
17477 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17478 			/* Bad packet - discarded by igmp_input */
17479 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17480 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17481 			if (mctl_present)
17482 				freeb(first_mp);
17483 			return;
17484 		}
17485 		/*
17486 		 * igmp_input() may have returned the pulled up message.
17487 		 * So first_mp and ipha need to be reinitialized.
17488 		 */
17489 		ipha = (ipha_t *)mp->b_rptr;
17490 		if (mctl_present)
17491 			first_mp->b_cont = mp;
17492 		else
17493 			first_mp = mp;
17494 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17495 		    connf_head != NULL) {
17496 			/* No user-level listener for IGMP packets */
17497 			goto drop_pkt;
17498 		}
17499 		/* deliver to local raw users */
17500 		break;
17501 	case IPPROTO_PIM:
17502 		/*
17503 		 * If we are not willing to accept PIM packets in clear,
17504 		 * then check with global policy.
17505 		 */
17506 		if (ipst->ips_pim_accept_clear_messages == 0) {
17507 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17508 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17509 			if (first_mp == NULL)
17510 				return;
17511 		}
17512 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17513 			freemsg(first_mp);
17514 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17515 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17516 			return;
17517 		}
17518 		if (pim_input(q, mp, ill) != 0) {
17519 			/* Bad packet - discarded by pim_input */
17520 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17521 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17522 			if (mctl_present)
17523 				freeb(first_mp);
17524 			return;
17525 		}
17526 
17527 		/*
17528 		 * pim_input() may have pulled up the message so ipha needs to
17529 		 * be reinitialized.
17530 		 */
17531 		ipha = (ipha_t *)mp->b_rptr;
17532 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17533 		    connf_head != NULL) {
17534 			/* No user-level listener for PIM packets */
17535 			goto drop_pkt;
17536 		}
17537 		/* deliver to local raw users */
17538 		break;
17539 	case IPPROTO_ENCAP:
17540 		/*
17541 		 * Handle self-encapsulated packets (IP-in-IP where
17542 		 * the inner addresses == the outer addresses).
17543 		 */
17544 		hdr_length = IPH_HDR_LENGTH(ipha);
17545 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17546 		    mp->b_wptr) {
17547 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17548 			    sizeof (ipha_t) - mp->b_rptr)) {
17549 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17550 				freemsg(first_mp);
17551 				return;
17552 			}
17553 			ipha = (ipha_t *)mp->b_rptr;
17554 		}
17555 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17556 		/*
17557 		 * Check the sanity of the inner IP header.
17558 		 */
17559 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17560 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17561 			freemsg(first_mp);
17562 			return;
17563 		}
17564 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17565 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17566 			freemsg(first_mp);
17567 			return;
17568 		}
17569 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17570 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17571 			ipsec_in_t *ii;
17572 
17573 			/*
17574 			 * Self-encapsulated tunnel packet. Remove
17575 			 * the outer IP header and fanout again.
17576 			 * We also need to make sure that the inner
17577 			 * header is pulled up until options.
17578 			 */
17579 			mp->b_rptr = (uchar_t *)inner_ipha;
17580 			ipha = inner_ipha;
17581 			hdr_length = IPH_HDR_LENGTH(ipha);
17582 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17583 				if (!pullupmsg(mp, (uchar_t *)ipha +
17584 				    + hdr_length - mp->b_rptr)) {
17585 					freemsg(first_mp);
17586 					return;
17587 				}
17588 				ipha = (ipha_t *)mp->b_rptr;
17589 			}
17590 			if (!mctl_present) {
17591 				ASSERT(first_mp == mp);
17592 				/*
17593 				 * This means that somebody is sending
17594 				 * Self-encapsualted packets without AH/ESP.
17595 				 * If AH/ESP was present, we would have already
17596 				 * allocated the first_mp.
17597 				 */
17598 				first_mp = ipsec_in_alloc(B_TRUE,
17599 				    ipst->ips_netstack);
17600 				if (first_mp == NULL) {
17601 					ip1dbg(("ip_proto_input: IPSEC_IN "
17602 					    "allocation failure.\n"));
17603 					BUMP_MIB(ill->ill_ip_mib,
17604 					    ipIfStatsInDiscards);
17605 					freemsg(mp);
17606 					return;
17607 				}
17608 				first_mp->b_cont = mp;
17609 			}
17610 			/*
17611 			 * We generally store the ill_index if we need to
17612 			 * do IPSEC processing as we lose the ill queue when
17613 			 * we come back. But in this case, we never should
17614 			 * have to store the ill_index here as it should have
17615 			 * been stored previously when we processed the
17616 			 * AH/ESP header in this routine or for non-ipsec
17617 			 * cases, we still have the queue. But for some bad
17618 			 * packets from the wire, we can get to IPSEC after
17619 			 * this and we better store the index for that case.
17620 			 */
17621 			ill = (ill_t *)q->q_ptr;
17622 			ii = (ipsec_in_t *)first_mp->b_rptr;
17623 			ii->ipsec_in_ill_index =
17624 			    ill->ill_phyint->phyint_ifindex;
17625 			ii->ipsec_in_rill_index =
17626 			    recv_ill->ill_phyint->phyint_ifindex;
17627 			if (ii->ipsec_in_decaps) {
17628 				/*
17629 				 * This packet is self-encapsulated multiple
17630 				 * times. We don't want to recurse infinitely.
17631 				 * To keep it simple, drop the packet.
17632 				 */
17633 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17634 				freemsg(first_mp);
17635 				return;
17636 			}
17637 			ii->ipsec_in_decaps = B_TRUE;
17638 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17639 			    ire);
17640 			return;
17641 		}
17642 		break;
17643 	case IPPROTO_AH:
17644 	case IPPROTO_ESP: {
17645 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17646 
17647 		/*
17648 		 * Fast path for AH/ESP. If this is the first time
17649 		 * we are sending a datagram to AH/ESP, allocate
17650 		 * a IPSEC_IN message and prepend it. Otherwise,
17651 		 * just fanout.
17652 		 */
17653 
17654 		int ipsec_rc;
17655 		ipsec_in_t *ii;
17656 		netstack_t *ns = ipst->ips_netstack;
17657 
17658 		IP_STAT(ipst, ipsec_proto_ahesp);
17659 		if (!mctl_present) {
17660 			ASSERT(first_mp == mp);
17661 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17662 			if (first_mp == NULL) {
17663 				ip1dbg(("ip_proto_input: IPSEC_IN "
17664 				    "allocation failure.\n"));
17665 				freemsg(hada_mp); /* okay ifnull */
17666 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17667 				freemsg(mp);
17668 				return;
17669 			}
17670 			/*
17671 			 * Store the ill_index so that when we come back
17672 			 * from IPSEC we ride on the same queue.
17673 			 */
17674 			ill = (ill_t *)q->q_ptr;
17675 			ii = (ipsec_in_t *)first_mp->b_rptr;
17676 			ii->ipsec_in_ill_index =
17677 			    ill->ill_phyint->phyint_ifindex;
17678 			ii->ipsec_in_rill_index =
17679 			    recv_ill->ill_phyint->phyint_ifindex;
17680 			first_mp->b_cont = mp;
17681 			/*
17682 			 * Cache hardware acceleration info.
17683 			 */
17684 			if (hada_mp != NULL) {
17685 				IPSECHW_DEBUG(IPSECHW_PKT,
17686 				    ("ip_rput_local: caching data attr.\n"));
17687 				ii->ipsec_in_accelerated = B_TRUE;
17688 				ii->ipsec_in_da = hada_mp;
17689 				hada_mp = NULL;
17690 			}
17691 		} else {
17692 			ii = (ipsec_in_t *)first_mp->b_rptr;
17693 		}
17694 
17695 		if (!ipsec_loaded(ipss)) {
17696 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17697 			    ire->ire_zoneid, ipst);
17698 			return;
17699 		}
17700 
17701 		ns = ipst->ips_netstack;
17702 		/* select inbound SA and have IPsec process the pkt */
17703 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17704 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17705 			if (esph == NULL)
17706 				return;
17707 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17708 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17709 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17710 			    first_mp, esph);
17711 		} else {
17712 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17713 			if (ah == NULL)
17714 				return;
17715 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17716 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17717 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17718 			    first_mp, ah);
17719 		}
17720 
17721 		switch (ipsec_rc) {
17722 		case IPSEC_STATUS_SUCCESS:
17723 			break;
17724 		case IPSEC_STATUS_FAILED:
17725 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17726 			/* FALLTHRU */
17727 		case IPSEC_STATUS_PENDING:
17728 			return;
17729 		}
17730 		/* we're done with IPsec processing, send it up */
17731 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17732 		return;
17733 	}
17734 	default:
17735 		break;
17736 	}
17737 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17738 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17739 		    ire->ire_zoneid));
17740 		goto drop_pkt;
17741 	}
17742 	/*
17743 	 * Handle protocols with which IP is less intimate.  There
17744 	 * can be more than one stream bound to a particular
17745 	 * protocol.  When this is the case, each one gets a copy
17746 	 * of any incoming packets.
17747 	 */
17748 	ip_fanout_proto(q, first_mp, ill, ipha,
17749 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17750 	    B_TRUE, recv_ill, ire->ire_zoneid);
17751 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17752 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17753 	return;
17754 
17755 drop_pkt:
17756 	freemsg(first_mp);
17757 	if (hada_mp != NULL)
17758 		freeb(hada_mp);
17759 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17760 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17761 #undef	rptr
17762 #undef  iphs
17763 
17764 }
17765 
17766 /*
17767  * Update any source route, record route or timestamp options.
17768  * Check that we are at end of strict source route.
17769  * The options have already been checked for sanity in ip_rput_options().
17770  */
17771 static boolean_t
17772 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17773     ip_stack_t *ipst)
17774 {
17775 	ipoptp_t	opts;
17776 	uchar_t		*opt;
17777 	uint8_t		optval;
17778 	uint8_t		optlen;
17779 	ipaddr_t	dst;
17780 	uint32_t	ts;
17781 	ire_t		*dst_ire;
17782 	timestruc_t	now;
17783 	zoneid_t	zoneid;
17784 	ill_t		*ill;
17785 
17786 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17787 
17788 	ip2dbg(("ip_rput_local_options\n"));
17789 
17790 	for (optval = ipoptp_first(&opts, ipha);
17791 	    optval != IPOPT_EOL;
17792 	    optval = ipoptp_next(&opts)) {
17793 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17794 		opt = opts.ipoptp_cur;
17795 		optlen = opts.ipoptp_len;
17796 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17797 		    optval, optlen));
17798 		switch (optval) {
17799 			uint32_t off;
17800 		case IPOPT_SSRR:
17801 		case IPOPT_LSRR:
17802 			off = opt[IPOPT_OFFSET];
17803 			off--;
17804 			if (optlen < IP_ADDR_LEN ||
17805 			    off > optlen - IP_ADDR_LEN) {
17806 				/* End of source route */
17807 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17808 				break;
17809 			}
17810 			/*
17811 			 * This will only happen if two consecutive entries
17812 			 * in the source route contains our address or if
17813 			 * it is a packet with a loose source route which
17814 			 * reaches us before consuming the whole source route
17815 			 */
17816 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17817 			if (optval == IPOPT_SSRR) {
17818 				goto bad_src_route;
17819 			}
17820 			/*
17821 			 * Hack: instead of dropping the packet truncate the
17822 			 * source route to what has been used by filling the
17823 			 * rest with IPOPT_NOP.
17824 			 */
17825 			opt[IPOPT_OLEN] = (uint8_t)off;
17826 			while (off < optlen) {
17827 				opt[off++] = IPOPT_NOP;
17828 			}
17829 			break;
17830 		case IPOPT_RR:
17831 			off = opt[IPOPT_OFFSET];
17832 			off--;
17833 			if (optlen < IP_ADDR_LEN ||
17834 			    off > optlen - IP_ADDR_LEN) {
17835 				/* No more room - ignore */
17836 				ip1dbg((
17837 				    "ip_rput_local_options: end of RR\n"));
17838 				break;
17839 			}
17840 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17841 			    IP_ADDR_LEN);
17842 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17843 			break;
17844 		case IPOPT_TS:
17845 			/* Insert timestamp if there is romm */
17846 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17847 			case IPOPT_TS_TSONLY:
17848 				off = IPOPT_TS_TIMELEN;
17849 				break;
17850 			case IPOPT_TS_PRESPEC:
17851 			case IPOPT_TS_PRESPEC_RFC791:
17852 				/* Verify that the address matched */
17853 				off = opt[IPOPT_OFFSET] - 1;
17854 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17855 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17856 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17857 				    ipst);
17858 				if (dst_ire == NULL) {
17859 					/* Not for us */
17860 					break;
17861 				}
17862 				ire_refrele(dst_ire);
17863 				/* FALLTHRU */
17864 			case IPOPT_TS_TSANDADDR:
17865 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17866 				break;
17867 			default:
17868 				/*
17869 				 * ip_*put_options should have already
17870 				 * dropped this packet.
17871 				 */
17872 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17873 				    "unknown IT - bug in ip_rput_options?\n");
17874 				return (B_TRUE);	/* Keep "lint" happy */
17875 			}
17876 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17877 				/* Increase overflow counter */
17878 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17879 				opt[IPOPT_POS_OV_FLG] =
17880 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17881 				    (off << 4));
17882 				break;
17883 			}
17884 			off = opt[IPOPT_OFFSET] - 1;
17885 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17886 			case IPOPT_TS_PRESPEC:
17887 			case IPOPT_TS_PRESPEC_RFC791:
17888 			case IPOPT_TS_TSANDADDR:
17889 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17890 				    IP_ADDR_LEN);
17891 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17892 				/* FALLTHRU */
17893 			case IPOPT_TS_TSONLY:
17894 				off = opt[IPOPT_OFFSET] - 1;
17895 				/* Compute # of milliseconds since midnight */
17896 				gethrestime(&now);
17897 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17898 				    now.tv_nsec / (NANOSEC / MILLISEC);
17899 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17900 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17901 				break;
17902 			}
17903 			break;
17904 		}
17905 	}
17906 	return (B_TRUE);
17907 
17908 bad_src_route:
17909 	q = WR(q);
17910 	if (q->q_next != NULL)
17911 		ill = q->q_ptr;
17912 	else
17913 		ill = NULL;
17914 
17915 	/* make sure we clear any indication of a hardware checksum */
17916 	DB_CKSUMFLAGS(mp) = 0;
17917 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17918 	if (zoneid == ALL_ZONES)
17919 		freemsg(mp);
17920 	else
17921 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17922 	return (B_FALSE);
17923 
17924 }
17925 
17926 /*
17927  * Process IP options in an inbound packet.  If an option affects the
17928  * effective destination address, return the next hop address via dstp.
17929  * Returns -1 if something fails in which case an ICMP error has been sent
17930  * and mp freed.
17931  */
17932 static int
17933 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17934     ip_stack_t *ipst)
17935 {
17936 	ipoptp_t	opts;
17937 	uchar_t		*opt;
17938 	uint8_t		optval;
17939 	uint8_t		optlen;
17940 	ipaddr_t	dst;
17941 	intptr_t	code = 0;
17942 	ire_t		*ire = NULL;
17943 	zoneid_t	zoneid;
17944 	ill_t		*ill;
17945 
17946 	ip2dbg(("ip_rput_options\n"));
17947 	dst = ipha->ipha_dst;
17948 	for (optval = ipoptp_first(&opts, ipha);
17949 	    optval != IPOPT_EOL;
17950 	    optval = ipoptp_next(&opts)) {
17951 		opt = opts.ipoptp_cur;
17952 		optlen = opts.ipoptp_len;
17953 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17954 		    optval, optlen));
17955 		/*
17956 		 * Note: we need to verify the checksum before we
17957 		 * modify anything thus this routine only extracts the next
17958 		 * hop dst from any source route.
17959 		 */
17960 		switch (optval) {
17961 			uint32_t off;
17962 		case IPOPT_SSRR:
17963 		case IPOPT_LSRR:
17964 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17965 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17966 			if (ire == NULL) {
17967 				if (optval == IPOPT_SSRR) {
17968 					ip1dbg(("ip_rput_options: not next"
17969 					    " strict source route 0x%x\n",
17970 					    ntohl(dst)));
17971 					code = (char *)&ipha->ipha_dst -
17972 					    (char *)ipha;
17973 					goto param_prob; /* RouterReq's */
17974 				}
17975 				ip2dbg(("ip_rput_options: "
17976 				    "not next source route 0x%x\n",
17977 				    ntohl(dst)));
17978 				break;
17979 			}
17980 			ire_refrele(ire);
17981 
17982 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17983 				ip1dbg((
17984 				    "ip_rput_options: bad option offset\n"));
17985 				code = (char *)&opt[IPOPT_OLEN] -
17986 				    (char *)ipha;
17987 				goto param_prob;
17988 			}
17989 			off = opt[IPOPT_OFFSET];
17990 			off--;
17991 		redo_srr:
17992 			if (optlen < IP_ADDR_LEN ||
17993 			    off > optlen - IP_ADDR_LEN) {
17994 				/* End of source route */
17995 				ip1dbg(("ip_rput_options: end of SR\n"));
17996 				break;
17997 			}
17998 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17999 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18000 			    ntohl(dst)));
18001 
18002 			/*
18003 			 * Check if our address is present more than
18004 			 * once as consecutive hops in source route.
18005 			 * XXX verify per-interface ip_forwarding
18006 			 * for source route?
18007 			 */
18008 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18009 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18010 
18011 			if (ire != NULL) {
18012 				ire_refrele(ire);
18013 				off += IP_ADDR_LEN;
18014 				goto redo_srr;
18015 			}
18016 
18017 			if (dst == htonl(INADDR_LOOPBACK)) {
18018 				ip1dbg(("ip_rput_options: loopback addr in "
18019 				    "source route!\n"));
18020 				goto bad_src_route;
18021 			}
18022 			/*
18023 			 * For strict: verify that dst is directly
18024 			 * reachable.
18025 			 */
18026 			if (optval == IPOPT_SSRR) {
18027 				ire = ire_ftable_lookup(dst, 0, 0,
18028 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18029 				    MBLK_GETLABEL(mp),
18030 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18031 				if (ire == NULL) {
18032 					ip1dbg(("ip_rput_options: SSRR not "
18033 					    "directly reachable: 0x%x\n",
18034 					    ntohl(dst)));
18035 					goto bad_src_route;
18036 				}
18037 				ire_refrele(ire);
18038 			}
18039 			/*
18040 			 * Defer update of the offset and the record route
18041 			 * until the packet is forwarded.
18042 			 */
18043 			break;
18044 		case IPOPT_RR:
18045 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18046 				ip1dbg((
18047 				    "ip_rput_options: bad option offset\n"));
18048 				code = (char *)&opt[IPOPT_OLEN] -
18049 				    (char *)ipha;
18050 				goto param_prob;
18051 			}
18052 			break;
18053 		case IPOPT_TS:
18054 			/*
18055 			 * Verify that length >= 5 and that there is either
18056 			 * room for another timestamp or that the overflow
18057 			 * counter is not maxed out.
18058 			 */
18059 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18060 			if (optlen < IPOPT_MINLEN_IT) {
18061 				goto param_prob;
18062 			}
18063 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18064 				ip1dbg((
18065 				    "ip_rput_options: bad option offset\n"));
18066 				code = (char *)&opt[IPOPT_OFFSET] -
18067 				    (char *)ipha;
18068 				goto param_prob;
18069 			}
18070 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18071 			case IPOPT_TS_TSONLY:
18072 				off = IPOPT_TS_TIMELEN;
18073 				break;
18074 			case IPOPT_TS_TSANDADDR:
18075 			case IPOPT_TS_PRESPEC:
18076 			case IPOPT_TS_PRESPEC_RFC791:
18077 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18078 				break;
18079 			default:
18080 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18081 				    (char *)ipha;
18082 				goto param_prob;
18083 			}
18084 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18085 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18086 				/*
18087 				 * No room and the overflow counter is 15
18088 				 * already.
18089 				 */
18090 				goto param_prob;
18091 			}
18092 			break;
18093 		}
18094 	}
18095 
18096 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18097 		*dstp = dst;
18098 		return (0);
18099 	}
18100 
18101 	ip1dbg(("ip_rput_options: error processing IP options."));
18102 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18103 
18104 param_prob:
18105 	q = WR(q);
18106 	if (q->q_next != NULL)
18107 		ill = q->q_ptr;
18108 	else
18109 		ill = NULL;
18110 
18111 	/* make sure we clear any indication of a hardware checksum */
18112 	DB_CKSUMFLAGS(mp) = 0;
18113 	/* Don't know whether this is for non-global or global/forwarding */
18114 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18115 	if (zoneid == ALL_ZONES)
18116 		freemsg(mp);
18117 	else
18118 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18119 	return (-1);
18120 
18121 bad_src_route:
18122 	q = WR(q);
18123 	if (q->q_next != NULL)
18124 		ill = q->q_ptr;
18125 	else
18126 		ill = NULL;
18127 
18128 	/* make sure we clear any indication of a hardware checksum */
18129 	DB_CKSUMFLAGS(mp) = 0;
18130 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18131 	if (zoneid == ALL_ZONES)
18132 		freemsg(mp);
18133 	else
18134 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18135 	return (-1);
18136 }
18137 
18138 /*
18139  * IP & ICMP info in >=14 msg's ...
18140  *  - ip fixed part (mib2_ip_t)
18141  *  - icmp fixed part (mib2_icmp_t)
18142  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18143  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18144  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18145  *  - ipRouteAttributeTable (ip 102)	labeled routes
18146  *  - ip multicast membership (ip_member_t)
18147  *  - ip multicast source filtering (ip_grpsrc_t)
18148  *  - igmp fixed part (struct igmpstat)
18149  *  - multicast routing stats (struct mrtstat)
18150  *  - multicast routing vifs (array of struct vifctl)
18151  *  - multicast routing routes (array of struct mfcctl)
18152  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18153  *					One per ill plus one generic
18154  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18155  *					One per ill plus one generic
18156  *  - ipv6RouteEntry			all IPv6 IREs
18157  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18158  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18159  *  - ipv6AddrEntry			all IPv6 ipifs
18160  *  - ipv6 multicast membership (ipv6_member_t)
18161  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18162  *
18163  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18164  *
18165  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18166  * already filled in by the caller.
18167  * Return value of 0 indicates that no messages were sent and caller
18168  * should free mpctl.
18169  */
18170 int
18171 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18172 {
18173 	ip_stack_t *ipst;
18174 	sctp_stack_t *sctps;
18175 
18176 
18177 	if (q->q_next != NULL) {
18178 		ipst = ILLQ_TO_IPST(q);
18179 	} else {
18180 		ipst = CONNQ_TO_IPST(q);
18181 	}
18182 	ASSERT(ipst != NULL);
18183 	sctps = ipst->ips_netstack->netstack_sctp;
18184 
18185 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18186 		return (0);
18187 	}
18188 
18189 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18190 	    ipst)) == NULL) {
18191 		return (1);
18192 	}
18193 
18194 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18195 		return (1);
18196 	}
18197 
18198 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18199 		return (1);
18200 	}
18201 
18202 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18203 		return (1);
18204 	}
18205 
18206 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18207 		return (1);
18208 	}
18209 
18210 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18211 		return (1);
18212 	}
18213 
18214 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18215 		return (1);
18216 	}
18217 
18218 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18219 		return (1);
18220 	}
18221 
18222 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18223 		return (1);
18224 	}
18225 
18226 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18227 		return (1);
18228 	}
18229 
18230 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18231 		return (1);
18232 	}
18233 
18234 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18235 		return (1);
18236 	}
18237 
18238 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18239 		return (1);
18240 	}
18241 
18242 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18243 		return (1);
18244 	}
18245 
18246 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18247 		return (1);
18248 	}
18249 
18250 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18251 	if (mpctl == NULL) {
18252 		return (1);
18253 	}
18254 
18255 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18256 		return (1);
18257 	}
18258 	freemsg(mpctl);
18259 	return (1);
18260 }
18261 
18262 
18263 /* Get global (legacy) IPv4 statistics */
18264 static mblk_t *
18265 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18266     ip_stack_t *ipst)
18267 {
18268 	mib2_ip_t		old_ip_mib;
18269 	struct opthdr		*optp;
18270 	mblk_t			*mp2ctl;
18271 
18272 	/*
18273 	 * make a copy of the original message
18274 	 */
18275 	mp2ctl = copymsg(mpctl);
18276 
18277 	/* fixed length IP structure... */
18278 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18279 	optp->level = MIB2_IP;
18280 	optp->name = 0;
18281 	SET_MIB(old_ip_mib.ipForwarding,
18282 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18283 	SET_MIB(old_ip_mib.ipDefaultTTL,
18284 	    (uint32_t)ipst->ips_ip_def_ttl);
18285 	SET_MIB(old_ip_mib.ipReasmTimeout,
18286 	    ipst->ips_ip_g_frag_timeout);
18287 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18288 	    sizeof (mib2_ipAddrEntry_t));
18289 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18290 	    sizeof (mib2_ipRouteEntry_t));
18291 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18292 	    sizeof (mib2_ipNetToMediaEntry_t));
18293 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18294 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18295 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18296 	    sizeof (mib2_ipAttributeEntry_t));
18297 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18298 
18299 	/*
18300 	 * Grab the statistics from the new IP MIB
18301 	 */
18302 	SET_MIB(old_ip_mib.ipInReceives,
18303 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18304 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18305 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18306 	SET_MIB(old_ip_mib.ipForwDatagrams,
18307 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18308 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18309 	    ipmib->ipIfStatsInUnknownProtos);
18310 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18311 	SET_MIB(old_ip_mib.ipInDelivers,
18312 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18313 	SET_MIB(old_ip_mib.ipOutRequests,
18314 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18315 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18316 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18317 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18318 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18319 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18320 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18321 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18322 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18323 
18324 	/* ipRoutingDiscards is not being used */
18325 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18326 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18327 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18328 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18329 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18330 	    ipmib->ipIfStatsReasmDuplicates);
18331 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18332 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18333 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18334 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18335 	SET_MIB(old_ip_mib.rawipInOverflows,
18336 	    ipmib->rawipIfStatsInOverflows);
18337 
18338 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18339 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18340 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18341 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18342 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18343 	    ipmib->ipIfStatsOutSwitchIPVersion);
18344 
18345 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18346 	    (int)sizeof (old_ip_mib))) {
18347 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18348 		    (uint_t)sizeof (old_ip_mib)));
18349 	}
18350 
18351 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18352 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18353 	    (int)optp->level, (int)optp->name, (int)optp->len));
18354 	qreply(q, mpctl);
18355 	return (mp2ctl);
18356 }
18357 
18358 /* Per interface IPv4 statistics */
18359 static mblk_t *
18360 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18361 {
18362 	struct opthdr		*optp;
18363 	mblk_t			*mp2ctl;
18364 	ill_t			*ill;
18365 	ill_walk_context_t	ctx;
18366 	mblk_t			*mp_tail = NULL;
18367 	mib2_ipIfStatsEntry_t	global_ip_mib;
18368 
18369 	/*
18370 	 * Make a copy of the original message
18371 	 */
18372 	mp2ctl = copymsg(mpctl);
18373 
18374 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18375 	optp->level = MIB2_IP;
18376 	optp->name = MIB2_IP_TRAFFIC_STATS;
18377 	/* Include "unknown interface" ip_mib */
18378 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18379 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18380 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18381 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18382 	    (ipst->ips_ip_g_forward ? 1 : 2));
18383 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18384 	    (uint32_t)ipst->ips_ip_def_ttl);
18385 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18386 	    sizeof (mib2_ipIfStatsEntry_t));
18387 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18388 	    sizeof (mib2_ipAddrEntry_t));
18389 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18390 	    sizeof (mib2_ipRouteEntry_t));
18391 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18392 	    sizeof (mib2_ipNetToMediaEntry_t));
18393 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18394 	    sizeof (ip_member_t));
18395 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18396 	    sizeof (ip_grpsrc_t));
18397 
18398 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18399 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18400 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18401 		    "failed to allocate %u bytes\n",
18402 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18403 	}
18404 
18405 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18406 
18407 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18408 	ill = ILL_START_WALK_V4(&ctx, ipst);
18409 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18410 		ill->ill_ip_mib->ipIfStatsIfIndex =
18411 		    ill->ill_phyint->phyint_ifindex;
18412 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18413 		    (ipst->ips_ip_g_forward ? 1 : 2));
18414 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18415 		    (uint32_t)ipst->ips_ip_def_ttl);
18416 
18417 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18418 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18419 		    (char *)ill->ill_ip_mib,
18420 		    (int)sizeof (*ill->ill_ip_mib))) {
18421 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18422 			    "failed to allocate %u bytes\n",
18423 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18424 		}
18425 	}
18426 	rw_exit(&ipst->ips_ill_g_lock);
18427 
18428 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18429 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18430 	    "level %d, name %d, len %d\n",
18431 	    (int)optp->level, (int)optp->name, (int)optp->len));
18432 	qreply(q, mpctl);
18433 
18434 	if (mp2ctl == NULL)
18435 		return (NULL);
18436 
18437 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18438 }
18439 
18440 /* Global IPv4 ICMP statistics */
18441 static mblk_t *
18442 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18443 {
18444 	struct opthdr		*optp;
18445 	mblk_t			*mp2ctl;
18446 
18447 	/*
18448 	 * Make a copy of the original message
18449 	 */
18450 	mp2ctl = copymsg(mpctl);
18451 
18452 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18453 	optp->level = MIB2_ICMP;
18454 	optp->name = 0;
18455 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18456 	    (int)sizeof (ipst->ips_icmp_mib))) {
18457 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18458 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18459 	}
18460 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18461 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18462 	    (int)optp->level, (int)optp->name, (int)optp->len));
18463 	qreply(q, mpctl);
18464 	return (mp2ctl);
18465 }
18466 
18467 /* Global IPv4 IGMP statistics */
18468 static mblk_t *
18469 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18470 {
18471 	struct opthdr		*optp;
18472 	mblk_t			*mp2ctl;
18473 
18474 	/*
18475 	 * make a copy of the original message
18476 	 */
18477 	mp2ctl = copymsg(mpctl);
18478 
18479 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18480 	optp->level = EXPER_IGMP;
18481 	optp->name = 0;
18482 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18483 	    (int)sizeof (ipst->ips_igmpstat))) {
18484 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18485 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18486 	}
18487 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18488 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18489 	    (int)optp->level, (int)optp->name, (int)optp->len));
18490 	qreply(q, mpctl);
18491 	return (mp2ctl);
18492 }
18493 
18494 /* Global IPv4 Multicast Routing statistics */
18495 static mblk_t *
18496 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18497 {
18498 	struct opthdr		*optp;
18499 	mblk_t			*mp2ctl;
18500 
18501 	/*
18502 	 * make a copy of the original message
18503 	 */
18504 	mp2ctl = copymsg(mpctl);
18505 
18506 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18507 	optp->level = EXPER_DVMRP;
18508 	optp->name = 0;
18509 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18510 		ip0dbg(("ip_mroute_stats: failed\n"));
18511 	}
18512 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18513 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18514 	    (int)optp->level, (int)optp->name, (int)optp->len));
18515 	qreply(q, mpctl);
18516 	return (mp2ctl);
18517 }
18518 
18519 /* IPv4 address information */
18520 static mblk_t *
18521 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18522 {
18523 	struct opthdr		*optp;
18524 	mblk_t			*mp2ctl;
18525 	mblk_t			*mp_tail = NULL;
18526 	ill_t			*ill;
18527 	ipif_t			*ipif;
18528 	uint_t			bitval;
18529 	mib2_ipAddrEntry_t	mae;
18530 	zoneid_t		zoneid;
18531 	ill_walk_context_t ctx;
18532 
18533 	/*
18534 	 * make a copy of the original message
18535 	 */
18536 	mp2ctl = copymsg(mpctl);
18537 
18538 	/* ipAddrEntryTable */
18539 
18540 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18541 	optp->level = MIB2_IP;
18542 	optp->name = MIB2_IP_ADDR;
18543 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18544 
18545 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18546 	ill = ILL_START_WALK_V4(&ctx, ipst);
18547 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18548 		for (ipif = ill->ill_ipif; ipif != NULL;
18549 		    ipif = ipif->ipif_next) {
18550 			if (ipif->ipif_zoneid != zoneid &&
18551 			    ipif->ipif_zoneid != ALL_ZONES)
18552 				continue;
18553 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18554 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18555 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18556 
18557 			(void) ipif_get_name(ipif,
18558 			    mae.ipAdEntIfIndex.o_bytes,
18559 			    OCTET_LENGTH);
18560 			mae.ipAdEntIfIndex.o_length =
18561 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18562 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18563 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18564 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18565 			mae.ipAdEntInfo.ae_subnet_len =
18566 			    ip_mask_to_plen(ipif->ipif_net_mask);
18567 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18568 			for (bitval = 1;
18569 			    bitval &&
18570 			    !(bitval & ipif->ipif_brd_addr);
18571 			    bitval <<= 1)
18572 				noop;
18573 			mae.ipAdEntBcastAddr = bitval;
18574 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18575 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18576 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18577 			mae.ipAdEntInfo.ae_broadcast_addr =
18578 			    ipif->ipif_brd_addr;
18579 			mae.ipAdEntInfo.ae_pp_dst_addr =
18580 			    ipif->ipif_pp_dst_addr;
18581 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18582 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18583 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18584 
18585 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18586 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18587 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18588 				    "allocate %u bytes\n",
18589 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18590 			}
18591 		}
18592 	}
18593 	rw_exit(&ipst->ips_ill_g_lock);
18594 
18595 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18596 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18597 	    (int)optp->level, (int)optp->name, (int)optp->len));
18598 	qreply(q, mpctl);
18599 	return (mp2ctl);
18600 }
18601 
18602 /* IPv6 address information */
18603 static mblk_t *
18604 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18605 {
18606 	struct opthdr		*optp;
18607 	mblk_t			*mp2ctl;
18608 	mblk_t			*mp_tail = NULL;
18609 	ill_t			*ill;
18610 	ipif_t			*ipif;
18611 	mib2_ipv6AddrEntry_t	mae6;
18612 	zoneid_t		zoneid;
18613 	ill_walk_context_t	ctx;
18614 
18615 	/*
18616 	 * make a copy of the original message
18617 	 */
18618 	mp2ctl = copymsg(mpctl);
18619 
18620 	/* ipv6AddrEntryTable */
18621 
18622 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18623 	optp->level = MIB2_IP6;
18624 	optp->name = MIB2_IP6_ADDR;
18625 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18626 
18627 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18628 	ill = ILL_START_WALK_V6(&ctx, ipst);
18629 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18630 		for (ipif = ill->ill_ipif; ipif != NULL;
18631 		    ipif = ipif->ipif_next) {
18632 			if (ipif->ipif_zoneid != zoneid &&
18633 			    ipif->ipif_zoneid != ALL_ZONES)
18634 				continue;
18635 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18636 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18637 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18638 
18639 			(void) ipif_get_name(ipif,
18640 			    mae6.ipv6AddrIfIndex.o_bytes,
18641 			    OCTET_LENGTH);
18642 			mae6.ipv6AddrIfIndex.o_length =
18643 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18644 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18645 			mae6.ipv6AddrPfxLength =
18646 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18647 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18648 			mae6.ipv6AddrInfo.ae_subnet_len =
18649 			    mae6.ipv6AddrPfxLength;
18650 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18651 
18652 			/* Type: stateless(1), stateful(2), unknown(3) */
18653 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18654 				mae6.ipv6AddrType = 1;
18655 			else
18656 				mae6.ipv6AddrType = 2;
18657 			/* Anycast: true(1), false(2) */
18658 			if (ipif->ipif_flags & IPIF_ANYCAST)
18659 				mae6.ipv6AddrAnycastFlag = 1;
18660 			else
18661 				mae6.ipv6AddrAnycastFlag = 2;
18662 
18663 			/*
18664 			 * Address status: preferred(1), deprecated(2),
18665 			 * invalid(3), inaccessible(4), unknown(5)
18666 			 */
18667 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18668 				mae6.ipv6AddrStatus = 3;
18669 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18670 				mae6.ipv6AddrStatus = 2;
18671 			else
18672 				mae6.ipv6AddrStatus = 1;
18673 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18674 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18675 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18676 			    ipif->ipif_v6pp_dst_addr;
18677 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18678 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18679 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18680 			mae6.ipv6AddrIdentifier = ill->ill_token;
18681 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18682 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18683 			mae6.ipv6AddrRetransmitTime =
18684 			    ill->ill_reachable_retrans_time;
18685 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18686 			    (char *)&mae6,
18687 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18688 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18689 				    "allocate %u bytes\n",
18690 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18691 			}
18692 		}
18693 	}
18694 	rw_exit(&ipst->ips_ill_g_lock);
18695 
18696 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18697 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18698 	    (int)optp->level, (int)optp->name, (int)optp->len));
18699 	qreply(q, mpctl);
18700 	return (mp2ctl);
18701 }
18702 
18703 /* IPv4 multicast group membership. */
18704 static mblk_t *
18705 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18706 {
18707 	struct opthdr		*optp;
18708 	mblk_t			*mp2ctl;
18709 	ill_t			*ill;
18710 	ipif_t			*ipif;
18711 	ilm_t			*ilm;
18712 	ip_member_t		ipm;
18713 	mblk_t			*mp_tail = NULL;
18714 	ill_walk_context_t	ctx;
18715 	zoneid_t		zoneid;
18716 
18717 	/*
18718 	 * make a copy of the original message
18719 	 */
18720 	mp2ctl = copymsg(mpctl);
18721 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18722 
18723 	/* ipGroupMember table */
18724 	optp = (struct opthdr *)&mpctl->b_rptr[
18725 	    sizeof (struct T_optmgmt_ack)];
18726 	optp->level = MIB2_IP;
18727 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18728 
18729 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18730 	ill = ILL_START_WALK_V4(&ctx, ipst);
18731 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18732 		ILM_WALKER_HOLD(ill);
18733 		for (ipif = ill->ill_ipif; ipif != NULL;
18734 		    ipif = ipif->ipif_next) {
18735 			if (ipif->ipif_zoneid != zoneid &&
18736 			    ipif->ipif_zoneid != ALL_ZONES)
18737 				continue;	/* not this zone */
18738 			(void) ipif_get_name(ipif,
18739 			    ipm.ipGroupMemberIfIndex.o_bytes,
18740 			    OCTET_LENGTH);
18741 			ipm.ipGroupMemberIfIndex.o_length =
18742 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18743 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18744 				ASSERT(ilm->ilm_ipif != NULL);
18745 				ASSERT(ilm->ilm_ill == NULL);
18746 				if (ilm->ilm_ipif != ipif)
18747 					continue;
18748 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18749 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18750 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18751 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18752 				    (char *)&ipm, (int)sizeof (ipm))) {
18753 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18754 					    "failed to allocate %u bytes\n",
18755 					    (uint_t)sizeof (ipm)));
18756 				}
18757 			}
18758 		}
18759 		ILM_WALKER_RELE(ill);
18760 	}
18761 	rw_exit(&ipst->ips_ill_g_lock);
18762 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18763 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18764 	    (int)optp->level, (int)optp->name, (int)optp->len));
18765 	qreply(q, mpctl);
18766 	return (mp2ctl);
18767 }
18768 
18769 /* IPv6 multicast group membership. */
18770 static mblk_t *
18771 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18772 {
18773 	struct opthdr		*optp;
18774 	mblk_t			*mp2ctl;
18775 	ill_t			*ill;
18776 	ilm_t			*ilm;
18777 	ipv6_member_t		ipm6;
18778 	mblk_t			*mp_tail = NULL;
18779 	ill_walk_context_t	ctx;
18780 	zoneid_t		zoneid;
18781 
18782 	/*
18783 	 * make a copy of the original message
18784 	 */
18785 	mp2ctl = copymsg(mpctl);
18786 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18787 
18788 	/* ip6GroupMember table */
18789 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18790 	optp->level = MIB2_IP6;
18791 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18792 
18793 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18794 	ill = ILL_START_WALK_V6(&ctx, ipst);
18795 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18796 		ILM_WALKER_HOLD(ill);
18797 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18798 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18799 			ASSERT(ilm->ilm_ipif == NULL);
18800 			ASSERT(ilm->ilm_ill != NULL);
18801 			if (ilm->ilm_zoneid != zoneid)
18802 				continue;	/* not this zone */
18803 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18804 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18805 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18806 			if (!snmp_append_data2(mpctl->b_cont,
18807 			    &mp_tail,
18808 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18809 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18810 				    "failed to allocate %u bytes\n",
18811 				    (uint_t)sizeof (ipm6)));
18812 			}
18813 		}
18814 		ILM_WALKER_RELE(ill);
18815 	}
18816 	rw_exit(&ipst->ips_ill_g_lock);
18817 
18818 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18819 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18820 	    (int)optp->level, (int)optp->name, (int)optp->len));
18821 	qreply(q, mpctl);
18822 	return (mp2ctl);
18823 }
18824 
18825 /* IP multicast filtered sources */
18826 static mblk_t *
18827 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18828 {
18829 	struct opthdr		*optp;
18830 	mblk_t			*mp2ctl;
18831 	ill_t			*ill;
18832 	ipif_t			*ipif;
18833 	ilm_t			*ilm;
18834 	ip_grpsrc_t		ips;
18835 	mblk_t			*mp_tail = NULL;
18836 	ill_walk_context_t	ctx;
18837 	zoneid_t		zoneid;
18838 	int			i;
18839 	slist_t			*sl;
18840 
18841 	/*
18842 	 * make a copy of the original message
18843 	 */
18844 	mp2ctl = copymsg(mpctl);
18845 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18846 
18847 	/* ipGroupSource table */
18848 	optp = (struct opthdr *)&mpctl->b_rptr[
18849 	    sizeof (struct T_optmgmt_ack)];
18850 	optp->level = MIB2_IP;
18851 	optp->name = EXPER_IP_GROUP_SOURCES;
18852 
18853 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18854 	ill = ILL_START_WALK_V4(&ctx, ipst);
18855 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18856 		ILM_WALKER_HOLD(ill);
18857 		for (ipif = ill->ill_ipif; ipif != NULL;
18858 		    ipif = ipif->ipif_next) {
18859 			if (ipif->ipif_zoneid != zoneid)
18860 				continue;	/* not this zone */
18861 			(void) ipif_get_name(ipif,
18862 			    ips.ipGroupSourceIfIndex.o_bytes,
18863 			    OCTET_LENGTH);
18864 			ips.ipGroupSourceIfIndex.o_length =
18865 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18866 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18867 				ASSERT(ilm->ilm_ipif != NULL);
18868 				ASSERT(ilm->ilm_ill == NULL);
18869 				sl = ilm->ilm_filter;
18870 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18871 					continue;
18872 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18873 				for (i = 0; i < sl->sl_numsrc; i++) {
18874 					if (!IN6_IS_ADDR_V4MAPPED(
18875 					    &sl->sl_addr[i]))
18876 						continue;
18877 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18878 					    ips.ipGroupSourceAddress);
18879 					if (snmp_append_data2(mpctl->b_cont,
18880 					    &mp_tail, (char *)&ips,
18881 					    (int)sizeof (ips)) == 0) {
18882 						ip1dbg(("ip_snmp_get_mib2_"
18883 						    "ip_group_src: failed to "
18884 						    "allocate %u bytes\n",
18885 						    (uint_t)sizeof (ips)));
18886 					}
18887 				}
18888 			}
18889 		}
18890 		ILM_WALKER_RELE(ill);
18891 	}
18892 	rw_exit(&ipst->ips_ill_g_lock);
18893 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18894 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18895 	    (int)optp->level, (int)optp->name, (int)optp->len));
18896 	qreply(q, mpctl);
18897 	return (mp2ctl);
18898 }
18899 
18900 /* IPv6 multicast filtered sources. */
18901 static mblk_t *
18902 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18903 {
18904 	struct opthdr		*optp;
18905 	mblk_t			*mp2ctl;
18906 	ill_t			*ill;
18907 	ilm_t			*ilm;
18908 	ipv6_grpsrc_t		ips6;
18909 	mblk_t			*mp_tail = NULL;
18910 	ill_walk_context_t	ctx;
18911 	zoneid_t		zoneid;
18912 	int			i;
18913 	slist_t			*sl;
18914 
18915 	/*
18916 	 * make a copy of the original message
18917 	 */
18918 	mp2ctl = copymsg(mpctl);
18919 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18920 
18921 	/* ip6GroupMember table */
18922 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18923 	optp->level = MIB2_IP6;
18924 	optp->name = EXPER_IP6_GROUP_SOURCES;
18925 
18926 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18927 	ill = ILL_START_WALK_V6(&ctx, ipst);
18928 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18929 		ILM_WALKER_HOLD(ill);
18930 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18931 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18932 			ASSERT(ilm->ilm_ipif == NULL);
18933 			ASSERT(ilm->ilm_ill != NULL);
18934 			sl = ilm->ilm_filter;
18935 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18936 				continue;
18937 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18938 			for (i = 0; i < sl->sl_numsrc; i++) {
18939 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18940 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18941 				    (char *)&ips6, (int)sizeof (ips6))) {
18942 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18943 					    "group_src: failed to allocate "
18944 					    "%u bytes\n",
18945 					    (uint_t)sizeof (ips6)));
18946 				}
18947 			}
18948 		}
18949 		ILM_WALKER_RELE(ill);
18950 	}
18951 	rw_exit(&ipst->ips_ill_g_lock);
18952 
18953 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18954 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18955 	    (int)optp->level, (int)optp->name, (int)optp->len));
18956 	qreply(q, mpctl);
18957 	return (mp2ctl);
18958 }
18959 
18960 /* Multicast routing virtual interface table. */
18961 static mblk_t *
18962 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18963 {
18964 	struct opthdr		*optp;
18965 	mblk_t			*mp2ctl;
18966 
18967 	/*
18968 	 * make a copy of the original message
18969 	 */
18970 	mp2ctl = copymsg(mpctl);
18971 
18972 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18973 	optp->level = EXPER_DVMRP;
18974 	optp->name = EXPER_DVMRP_VIF;
18975 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18976 		ip0dbg(("ip_mroute_vif: failed\n"));
18977 	}
18978 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18979 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18980 	    (int)optp->level, (int)optp->name, (int)optp->len));
18981 	qreply(q, mpctl);
18982 	return (mp2ctl);
18983 }
18984 
18985 /* Multicast routing table. */
18986 static mblk_t *
18987 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18988 {
18989 	struct opthdr		*optp;
18990 	mblk_t			*mp2ctl;
18991 
18992 	/*
18993 	 * make a copy of the original message
18994 	 */
18995 	mp2ctl = copymsg(mpctl);
18996 
18997 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18998 	optp->level = EXPER_DVMRP;
18999 	optp->name = EXPER_DVMRP_MRT;
19000 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19001 		ip0dbg(("ip_mroute_mrt: failed\n"));
19002 	}
19003 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19004 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19005 	    (int)optp->level, (int)optp->name, (int)optp->len));
19006 	qreply(q, mpctl);
19007 	return (mp2ctl);
19008 }
19009 
19010 /*
19011  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19012  * in one IRE walk.
19013  */
19014 static mblk_t *
19015 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19016 {
19017 	struct opthdr	*optp;
19018 	mblk_t		*mp2ctl;	/* Returned */
19019 	mblk_t		*mp3ctl;	/* nettomedia */
19020 	mblk_t		*mp4ctl;	/* routeattrs */
19021 	iproutedata_t	ird;
19022 	zoneid_t	zoneid;
19023 
19024 	/*
19025 	 * make copies of the original message
19026 	 *	- mp2ctl is returned unchanged to the caller for his use
19027 	 *	- mpctl is sent upstream as ipRouteEntryTable
19028 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19029 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19030 	 */
19031 	mp2ctl = copymsg(mpctl);
19032 	mp3ctl = copymsg(mpctl);
19033 	mp4ctl = copymsg(mpctl);
19034 	if (mp3ctl == NULL || mp4ctl == NULL) {
19035 		freemsg(mp4ctl);
19036 		freemsg(mp3ctl);
19037 		freemsg(mp2ctl);
19038 		freemsg(mpctl);
19039 		return (NULL);
19040 	}
19041 
19042 	bzero(&ird, sizeof (ird));
19043 
19044 	ird.ird_route.lp_head = mpctl->b_cont;
19045 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19046 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19047 
19048 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19049 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19050 	if (zoneid == GLOBAL_ZONEID) {
19051 		/*
19052 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19053 		 * requires the sys_net_config or sys_ip_config privilege,
19054 		 * it can only run in the global zone or an exclusive-IP zone,
19055 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19056 		 */
19057 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19058 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19059 	}
19060 
19061 	/* ipRouteEntryTable in mpctl */
19062 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19063 	optp->level = MIB2_IP;
19064 	optp->name = MIB2_IP_ROUTE;
19065 	optp->len = msgdsize(ird.ird_route.lp_head);
19066 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19067 	    (int)optp->level, (int)optp->name, (int)optp->len));
19068 	qreply(q, mpctl);
19069 
19070 	/* ipNetToMediaEntryTable in mp3ctl */
19071 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19072 	optp->level = MIB2_IP;
19073 	optp->name = MIB2_IP_MEDIA;
19074 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19075 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19076 	    (int)optp->level, (int)optp->name, (int)optp->len));
19077 	qreply(q, mp3ctl);
19078 
19079 	/* ipRouteAttributeTable in mp4ctl */
19080 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19081 	optp->level = MIB2_IP;
19082 	optp->name = EXPER_IP_RTATTR;
19083 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19084 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19085 	    (int)optp->level, (int)optp->name, (int)optp->len));
19086 	if (optp->len == 0)
19087 		freemsg(mp4ctl);
19088 	else
19089 		qreply(q, mp4ctl);
19090 
19091 	return (mp2ctl);
19092 }
19093 
19094 /*
19095  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19096  * ipv6NetToMediaEntryTable in an NDP walk.
19097  */
19098 static mblk_t *
19099 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19100 {
19101 	struct opthdr	*optp;
19102 	mblk_t		*mp2ctl;	/* Returned */
19103 	mblk_t		*mp3ctl;	/* nettomedia */
19104 	mblk_t		*mp4ctl;	/* routeattrs */
19105 	iproutedata_t	ird;
19106 	zoneid_t	zoneid;
19107 
19108 	/*
19109 	 * make copies of the original message
19110 	 *	- mp2ctl is returned unchanged to the caller for his use
19111 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19112 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19113 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19114 	 */
19115 	mp2ctl = copymsg(mpctl);
19116 	mp3ctl = copymsg(mpctl);
19117 	mp4ctl = copymsg(mpctl);
19118 	if (mp3ctl == NULL || mp4ctl == NULL) {
19119 		freemsg(mp4ctl);
19120 		freemsg(mp3ctl);
19121 		freemsg(mp2ctl);
19122 		freemsg(mpctl);
19123 		return (NULL);
19124 	}
19125 
19126 	bzero(&ird, sizeof (ird));
19127 
19128 	ird.ird_route.lp_head = mpctl->b_cont;
19129 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19130 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19131 
19132 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19133 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19134 
19135 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19136 	optp->level = MIB2_IP6;
19137 	optp->name = MIB2_IP6_ROUTE;
19138 	optp->len = msgdsize(ird.ird_route.lp_head);
19139 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19140 	    (int)optp->level, (int)optp->name, (int)optp->len));
19141 	qreply(q, mpctl);
19142 
19143 	/* ipv6NetToMediaEntryTable in mp3ctl */
19144 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19145 
19146 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19147 	optp->level = MIB2_IP6;
19148 	optp->name = MIB2_IP6_MEDIA;
19149 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19150 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19151 	    (int)optp->level, (int)optp->name, (int)optp->len));
19152 	qreply(q, mp3ctl);
19153 
19154 	/* ipv6RouteAttributeTable in mp4ctl */
19155 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19156 	optp->level = MIB2_IP6;
19157 	optp->name = EXPER_IP_RTATTR;
19158 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19159 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19160 	    (int)optp->level, (int)optp->name, (int)optp->len));
19161 	if (optp->len == 0)
19162 		freemsg(mp4ctl);
19163 	else
19164 		qreply(q, mp4ctl);
19165 
19166 	return (mp2ctl);
19167 }
19168 
19169 /*
19170  * IPv6 mib: One per ill
19171  */
19172 static mblk_t *
19173 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19174 {
19175 	struct opthdr		*optp;
19176 	mblk_t			*mp2ctl;
19177 	ill_t			*ill;
19178 	ill_walk_context_t	ctx;
19179 	mblk_t			*mp_tail = NULL;
19180 
19181 	/*
19182 	 * Make a copy of the original message
19183 	 */
19184 	mp2ctl = copymsg(mpctl);
19185 
19186 	/* fixed length IPv6 structure ... */
19187 
19188 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19189 	optp->level = MIB2_IP6;
19190 	optp->name = 0;
19191 	/* Include "unknown interface" ip6_mib */
19192 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19193 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19194 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19195 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19196 	    ipst->ips_ipv6_forward ? 1 : 2);
19197 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19198 	    ipst->ips_ipv6_def_hops);
19199 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19200 	    sizeof (mib2_ipIfStatsEntry_t));
19201 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19202 	    sizeof (mib2_ipv6AddrEntry_t));
19203 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19204 	    sizeof (mib2_ipv6RouteEntry_t));
19205 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19206 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19207 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19208 	    sizeof (ipv6_member_t));
19209 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19210 	    sizeof (ipv6_grpsrc_t));
19211 
19212 	/*
19213 	 * Synchronize 64- and 32-bit counters
19214 	 */
19215 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19216 	    ipIfStatsHCInReceives);
19217 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19218 	    ipIfStatsHCInDelivers);
19219 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19220 	    ipIfStatsHCOutRequests);
19221 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19222 	    ipIfStatsHCOutForwDatagrams);
19223 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19224 	    ipIfStatsHCOutMcastPkts);
19225 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19226 	    ipIfStatsHCInMcastPkts);
19227 
19228 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19229 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19230 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19231 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19232 	}
19233 
19234 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19235 	ill = ILL_START_WALK_V6(&ctx, ipst);
19236 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19237 		ill->ill_ip_mib->ipIfStatsIfIndex =
19238 		    ill->ill_phyint->phyint_ifindex;
19239 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19240 		    ipst->ips_ipv6_forward ? 1 : 2);
19241 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19242 		    ill->ill_max_hops);
19243 
19244 		/*
19245 		 * Synchronize 64- and 32-bit counters
19246 		 */
19247 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19248 		    ipIfStatsHCInReceives);
19249 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19250 		    ipIfStatsHCInDelivers);
19251 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19252 		    ipIfStatsHCOutRequests);
19253 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19254 		    ipIfStatsHCOutForwDatagrams);
19255 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19256 		    ipIfStatsHCOutMcastPkts);
19257 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19258 		    ipIfStatsHCInMcastPkts);
19259 
19260 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19261 		    (char *)ill->ill_ip_mib,
19262 		    (int)sizeof (*ill->ill_ip_mib))) {
19263 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19264 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19265 		}
19266 	}
19267 	rw_exit(&ipst->ips_ill_g_lock);
19268 
19269 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19270 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19271 	    (int)optp->level, (int)optp->name, (int)optp->len));
19272 	qreply(q, mpctl);
19273 	return (mp2ctl);
19274 }
19275 
19276 /*
19277  * ICMPv6 mib: One per ill
19278  */
19279 static mblk_t *
19280 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19281 {
19282 	struct opthdr		*optp;
19283 	mblk_t			*mp2ctl;
19284 	ill_t			*ill;
19285 	ill_walk_context_t	ctx;
19286 	mblk_t			*mp_tail = NULL;
19287 	/*
19288 	 * Make a copy of the original message
19289 	 */
19290 	mp2ctl = copymsg(mpctl);
19291 
19292 	/* fixed length ICMPv6 structure ... */
19293 
19294 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19295 	optp->level = MIB2_ICMP6;
19296 	optp->name = 0;
19297 	/* Include "unknown interface" icmp6_mib */
19298 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19299 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19300 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19301 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19302 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19303 	    (char *)&ipst->ips_icmp6_mib,
19304 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19305 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19306 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19307 	}
19308 
19309 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19310 	ill = ILL_START_WALK_V6(&ctx, ipst);
19311 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19312 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19313 		    ill->ill_phyint->phyint_ifindex;
19314 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19315 		    (char *)ill->ill_icmp6_mib,
19316 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19317 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19318 			    "%u bytes\n",
19319 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19320 		}
19321 	}
19322 	rw_exit(&ipst->ips_ill_g_lock);
19323 
19324 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19325 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19326 	    (int)optp->level, (int)optp->name, (int)optp->len));
19327 	qreply(q, mpctl);
19328 	return (mp2ctl);
19329 }
19330 
19331 /*
19332  * ire_walk routine to create both ipRouteEntryTable and
19333  * ipRouteAttributeTable in one IRE walk
19334  */
19335 static void
19336 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19337 {
19338 	ill_t				*ill;
19339 	ipif_t				*ipif;
19340 	mib2_ipRouteEntry_t		*re;
19341 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19342 	ipaddr_t			gw_addr;
19343 	tsol_ire_gw_secattr_t		*attrp;
19344 	tsol_gc_t			*gc = NULL;
19345 	tsol_gcgrp_t			*gcgrp = NULL;
19346 	uint_t				sacnt = 0;
19347 	int				i;
19348 
19349 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19350 
19351 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19352 		return;
19353 
19354 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19355 		mutex_enter(&attrp->igsa_lock);
19356 		if ((gc = attrp->igsa_gc) != NULL) {
19357 			gcgrp = gc->gc_grp;
19358 			ASSERT(gcgrp != NULL);
19359 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19360 			sacnt = 1;
19361 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19362 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19363 			gc = gcgrp->gcgrp_head;
19364 			sacnt = gcgrp->gcgrp_count;
19365 		}
19366 		mutex_exit(&attrp->igsa_lock);
19367 
19368 		/* do nothing if there's no gc to report */
19369 		if (gc == NULL) {
19370 			ASSERT(sacnt == 0);
19371 			if (gcgrp != NULL) {
19372 				/* we might as well drop the lock now */
19373 				rw_exit(&gcgrp->gcgrp_rwlock);
19374 				gcgrp = NULL;
19375 			}
19376 			attrp = NULL;
19377 		}
19378 
19379 		ASSERT(gc == NULL || (gcgrp != NULL &&
19380 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19381 	}
19382 	ASSERT(sacnt == 0 || gc != NULL);
19383 
19384 	if (sacnt != 0 &&
19385 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19386 		kmem_free(re, sizeof (*re));
19387 		rw_exit(&gcgrp->gcgrp_rwlock);
19388 		return;
19389 	}
19390 
19391 	/*
19392 	 * Return all IRE types for route table... let caller pick and choose
19393 	 */
19394 	re->ipRouteDest = ire->ire_addr;
19395 	ipif = ire->ire_ipif;
19396 	re->ipRouteIfIndex.o_length = 0;
19397 	if (ire->ire_type == IRE_CACHE) {
19398 		ill = (ill_t *)ire->ire_stq->q_ptr;
19399 		re->ipRouteIfIndex.o_length =
19400 		    ill->ill_name_length == 0 ? 0 :
19401 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19402 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19403 		    re->ipRouteIfIndex.o_length);
19404 	} else if (ipif != NULL) {
19405 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19406 		    OCTET_LENGTH);
19407 		re->ipRouteIfIndex.o_length =
19408 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19409 	}
19410 	re->ipRouteMetric1 = -1;
19411 	re->ipRouteMetric2 = -1;
19412 	re->ipRouteMetric3 = -1;
19413 	re->ipRouteMetric4 = -1;
19414 
19415 	gw_addr = ire->ire_gateway_addr;
19416 
19417 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19418 		re->ipRouteNextHop = ire->ire_src_addr;
19419 	else
19420 		re->ipRouteNextHop = gw_addr;
19421 	/* indirect(4), direct(3), or invalid(2) */
19422 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19423 		re->ipRouteType = 2;
19424 	else
19425 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19426 	re->ipRouteProto = -1;
19427 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19428 	re->ipRouteMask = ire->ire_mask;
19429 	re->ipRouteMetric5 = -1;
19430 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19431 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19432 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19433 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19434 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19435 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19436 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19437 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19438 	re->ipRouteInfo.re_in_ill.o_length = 0;
19439 
19440 	if (ire->ire_flags & RTF_DYNAMIC) {
19441 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19442 	} else {
19443 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19444 	}
19445 
19446 	if (ire->ire_in_ill != NULL) {
19447 		re->ipRouteInfo.re_in_ill.o_length =
19448 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19449 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19450 		bcopy(ire->ire_in_ill->ill_name,
19451 		    re->ipRouteInfo.re_in_ill.o_bytes,
19452 		    re->ipRouteInfo.re_in_ill.o_length);
19453 	}
19454 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19455 
19456 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19457 	    (char *)re, (int)sizeof (*re))) {
19458 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19459 		    (uint_t)sizeof (*re)));
19460 	}
19461 
19462 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19463 		iaeptr->iae_routeidx = ird->ird_idx;
19464 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19465 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19466 	}
19467 
19468 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19469 	    (char *)iae, sacnt * sizeof (*iae))) {
19470 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19471 		    (unsigned)(sacnt * sizeof (*iae))));
19472 	}
19473 
19474 	/* bump route index for next pass */
19475 	ird->ird_idx++;
19476 
19477 	kmem_free(re, sizeof (*re));
19478 	if (sacnt != 0)
19479 		kmem_free(iae, sacnt * sizeof (*iae));
19480 
19481 	if (gcgrp != NULL)
19482 		rw_exit(&gcgrp->gcgrp_rwlock);
19483 }
19484 
19485 /*
19486  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19487  */
19488 static void
19489 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19490 {
19491 	ill_t				*ill;
19492 	ipif_t				*ipif;
19493 	mib2_ipv6RouteEntry_t		*re;
19494 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19495 	in6_addr_t			gw_addr_v6;
19496 	tsol_ire_gw_secattr_t		*attrp;
19497 	tsol_gc_t			*gc = NULL;
19498 	tsol_gcgrp_t			*gcgrp = NULL;
19499 	uint_t				sacnt = 0;
19500 	int				i;
19501 
19502 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19503 
19504 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19505 		return;
19506 
19507 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19508 		mutex_enter(&attrp->igsa_lock);
19509 		if ((gc = attrp->igsa_gc) != NULL) {
19510 			gcgrp = gc->gc_grp;
19511 			ASSERT(gcgrp != NULL);
19512 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19513 			sacnt = 1;
19514 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19515 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19516 			gc = gcgrp->gcgrp_head;
19517 			sacnt = gcgrp->gcgrp_count;
19518 		}
19519 		mutex_exit(&attrp->igsa_lock);
19520 
19521 		/* do nothing if there's no gc to report */
19522 		if (gc == NULL) {
19523 			ASSERT(sacnt == 0);
19524 			if (gcgrp != NULL) {
19525 				/* we might as well drop the lock now */
19526 				rw_exit(&gcgrp->gcgrp_rwlock);
19527 				gcgrp = NULL;
19528 			}
19529 			attrp = NULL;
19530 		}
19531 
19532 		ASSERT(gc == NULL || (gcgrp != NULL &&
19533 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19534 	}
19535 	ASSERT(sacnt == 0 || gc != NULL);
19536 
19537 	if (sacnt != 0 &&
19538 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19539 		kmem_free(re, sizeof (*re));
19540 		rw_exit(&gcgrp->gcgrp_rwlock);
19541 		return;
19542 	}
19543 
19544 	/*
19545 	 * Return all IRE types for route table... let caller pick and choose
19546 	 */
19547 	re->ipv6RouteDest = ire->ire_addr_v6;
19548 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19549 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19550 	re->ipv6RouteIfIndex.o_length = 0;
19551 	ipif = ire->ire_ipif;
19552 	if (ire->ire_type == IRE_CACHE) {
19553 		ill = (ill_t *)ire->ire_stq->q_ptr;
19554 		re->ipv6RouteIfIndex.o_length =
19555 		    ill->ill_name_length == 0 ? 0 :
19556 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19557 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19558 		    re->ipv6RouteIfIndex.o_length);
19559 	} else if (ipif != NULL) {
19560 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19561 		    OCTET_LENGTH);
19562 		re->ipv6RouteIfIndex.o_length =
19563 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19564 	}
19565 
19566 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19567 
19568 	mutex_enter(&ire->ire_lock);
19569 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19570 	mutex_exit(&ire->ire_lock);
19571 
19572 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19573 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19574 	else
19575 		re->ipv6RouteNextHop = gw_addr_v6;
19576 
19577 	/* remote(4), local(3), or discard(2) */
19578 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19579 		re->ipv6RouteType = 2;
19580 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19581 		re->ipv6RouteType = 3;
19582 	else
19583 		re->ipv6RouteType = 4;
19584 
19585 	re->ipv6RouteProtocol	= -1;
19586 	re->ipv6RoutePolicy	= 0;
19587 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19588 	re->ipv6RouteNextHopRDI	= 0;
19589 	re->ipv6RouteWeight	= 0;
19590 	re->ipv6RouteMetric	= 0;
19591 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19592 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19593 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19594 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19595 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19596 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19597 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19598 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19599 
19600 	if (ire->ire_flags & RTF_DYNAMIC) {
19601 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19602 	} else {
19603 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19604 	}
19605 
19606 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19607 	    (char *)re, (int)sizeof (*re))) {
19608 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19609 		    (uint_t)sizeof (*re)));
19610 	}
19611 
19612 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19613 		iaeptr->iae_routeidx = ird->ird_idx;
19614 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19615 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19616 	}
19617 
19618 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19619 	    (char *)iae, sacnt * sizeof (*iae))) {
19620 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19621 		    (unsigned)(sacnt * sizeof (*iae))));
19622 	}
19623 
19624 	/* bump route index for next pass */
19625 	ird->ird_idx++;
19626 
19627 	kmem_free(re, sizeof (*re));
19628 	if (sacnt != 0)
19629 		kmem_free(iae, sacnt * sizeof (*iae));
19630 
19631 	if (gcgrp != NULL)
19632 		rw_exit(&gcgrp->gcgrp_rwlock);
19633 }
19634 
19635 /*
19636  * ndp_walk routine to create ipv6NetToMediaEntryTable
19637  */
19638 static int
19639 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19640 {
19641 	ill_t				*ill;
19642 	mib2_ipv6NetToMediaEntry_t	ntme;
19643 	dl_unitdata_req_t		*dl;
19644 
19645 	ill = nce->nce_ill;
19646 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19647 		return (0);
19648 
19649 	/*
19650 	 * Neighbor cache entry attached to IRE with on-link
19651 	 * destination.
19652 	 */
19653 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19654 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19655 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19656 	    (nce->nce_res_mp != NULL)) {
19657 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19658 		ntme.ipv6NetToMediaPhysAddress.o_length =
19659 		    dl->dl_dest_addr_length;
19660 	} else {
19661 		ntme.ipv6NetToMediaPhysAddress.o_length =
19662 		    ill->ill_phys_addr_length;
19663 	}
19664 	if (nce->nce_res_mp != NULL) {
19665 		bcopy((char *)nce->nce_res_mp->b_rptr +
19666 		    NCE_LL_ADDR_OFFSET(ill),
19667 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19668 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19669 	} else {
19670 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19671 		    ill->ill_phys_addr_length);
19672 	}
19673 	/*
19674 	 * Note: Returns ND_* states. Should be:
19675 	 * reachable(1), stale(2), delay(3), probe(4),
19676 	 * invalid(5), unknown(6)
19677 	 */
19678 	ntme.ipv6NetToMediaState = nce->nce_state;
19679 	ntme.ipv6NetToMediaLastUpdated = 0;
19680 
19681 	/* other(1), dynamic(2), static(3), local(4) */
19682 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19683 		ntme.ipv6NetToMediaType = 4;
19684 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19685 		ntme.ipv6NetToMediaType = 1;
19686 	} else {
19687 		ntme.ipv6NetToMediaType = 2;
19688 	}
19689 
19690 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19691 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19692 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19693 		    (uint_t)sizeof (ntme)));
19694 	}
19695 	return (0);
19696 }
19697 
19698 /*
19699  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19700  */
19701 /* ARGSUSED */
19702 int
19703 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19704 {
19705 	switch (level) {
19706 	case MIB2_IP:
19707 	case MIB2_ICMP:
19708 		switch (name) {
19709 		default:
19710 			break;
19711 		}
19712 		return (1);
19713 	default:
19714 		return (1);
19715 	}
19716 }
19717 
19718 /*
19719  * When there exists both a 64- and 32-bit counter of a particular type
19720  * (i.e., InReceives), only the 64-bit counters are added.
19721  */
19722 void
19723 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19724 {
19725 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19726 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19727 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19728 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19729 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19730 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19731 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19732 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19733 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19734 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19735 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19736 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19737 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19738 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19739 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19740 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19741 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19742 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19743 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19744 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19745 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19746 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19747 	    o2->ipIfStatsInWrongIPVersion);
19748 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19749 	    o2->ipIfStatsInWrongIPVersion);
19750 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19751 	    o2->ipIfStatsOutSwitchIPVersion);
19752 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19753 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19754 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19755 	    o2->ipIfStatsHCInForwDatagrams);
19756 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19757 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19758 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19759 	    o2->ipIfStatsHCOutForwDatagrams);
19760 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19761 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19762 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19763 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19764 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19765 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19766 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19767 	    o2->ipIfStatsHCOutMcastOctets);
19768 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19769 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19770 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19771 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19772 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19773 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19774 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19775 }
19776 
19777 void
19778 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19779 {
19780 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19781 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19782 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19783 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19784 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19785 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19786 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19787 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19788 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19789 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19790 	    o2->ipv6IfIcmpInRouterSolicits);
19791 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19792 	    o2->ipv6IfIcmpInRouterAdvertisements);
19793 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19794 	    o2->ipv6IfIcmpInNeighborSolicits);
19795 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19796 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19797 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19798 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19799 	    o2->ipv6IfIcmpInGroupMembQueries);
19800 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19801 	    o2->ipv6IfIcmpInGroupMembResponses);
19802 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19803 	    o2->ipv6IfIcmpInGroupMembReductions);
19804 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19805 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19806 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19807 	    o2->ipv6IfIcmpOutDestUnreachs);
19808 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19809 	    o2->ipv6IfIcmpOutAdminProhibs);
19810 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19811 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19812 	    o2->ipv6IfIcmpOutParmProblems);
19813 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19814 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19815 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19816 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19817 	    o2->ipv6IfIcmpOutRouterSolicits);
19818 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19819 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19820 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19821 	    o2->ipv6IfIcmpOutNeighborSolicits);
19822 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19823 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19824 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19825 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19826 	    o2->ipv6IfIcmpOutGroupMembQueries);
19827 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19828 	    o2->ipv6IfIcmpOutGroupMembResponses);
19829 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19830 	    o2->ipv6IfIcmpOutGroupMembReductions);
19831 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19832 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19833 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19834 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19835 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19836 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19837 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19838 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19839 	    o2->ipv6IfIcmpInGroupMembTotal);
19840 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19841 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19842 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19843 	    o2->ipv6IfIcmpInGroupMembBadReports);
19844 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19845 	    o2->ipv6IfIcmpInGroupMembOurReports);
19846 }
19847 
19848 /*
19849  * Called before the options are updated to check if this packet will
19850  * be source routed from here.
19851  * This routine assumes that the options are well formed i.e. that they
19852  * have already been checked.
19853  */
19854 static boolean_t
19855 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19856 {
19857 	ipoptp_t	opts;
19858 	uchar_t		*opt;
19859 	uint8_t		optval;
19860 	uint8_t		optlen;
19861 	ipaddr_t	dst;
19862 	ire_t		*ire;
19863 
19864 	if (IS_SIMPLE_IPH(ipha)) {
19865 		ip2dbg(("not source routed\n"));
19866 		return (B_FALSE);
19867 	}
19868 	dst = ipha->ipha_dst;
19869 	for (optval = ipoptp_first(&opts, ipha);
19870 	    optval != IPOPT_EOL;
19871 	    optval = ipoptp_next(&opts)) {
19872 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19873 		opt = opts.ipoptp_cur;
19874 		optlen = opts.ipoptp_len;
19875 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19876 		    optval, optlen));
19877 		switch (optval) {
19878 			uint32_t off;
19879 		case IPOPT_SSRR:
19880 		case IPOPT_LSRR:
19881 			/*
19882 			 * If dst is one of our addresses and there are some
19883 			 * entries left in the source route return (true).
19884 			 */
19885 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19886 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19887 			if (ire == NULL) {
19888 				ip2dbg(("ip_source_routed: not next"
19889 				    " source route 0x%x\n",
19890 				    ntohl(dst)));
19891 				return (B_FALSE);
19892 			}
19893 			ire_refrele(ire);
19894 			off = opt[IPOPT_OFFSET];
19895 			off--;
19896 			if (optlen < IP_ADDR_LEN ||
19897 			    off > optlen - IP_ADDR_LEN) {
19898 				/* End of source route */
19899 				ip1dbg(("ip_source_routed: end of SR\n"));
19900 				return (B_FALSE);
19901 			}
19902 			return (B_TRUE);
19903 		}
19904 	}
19905 	ip2dbg(("not source routed\n"));
19906 	return (B_FALSE);
19907 }
19908 
19909 /*
19910  * Check if the packet contains any source route.
19911  */
19912 static boolean_t
19913 ip_source_route_included(ipha_t *ipha)
19914 {
19915 	ipoptp_t	opts;
19916 	uint8_t		optval;
19917 
19918 	if (IS_SIMPLE_IPH(ipha))
19919 		return (B_FALSE);
19920 	for (optval = ipoptp_first(&opts, ipha);
19921 	    optval != IPOPT_EOL;
19922 	    optval = ipoptp_next(&opts)) {
19923 		switch (optval) {
19924 		case IPOPT_SSRR:
19925 		case IPOPT_LSRR:
19926 			return (B_TRUE);
19927 		}
19928 	}
19929 	return (B_FALSE);
19930 }
19931 
19932 /*
19933  * Called when the IRE expiration timer fires.
19934  */
19935 void
19936 ip_trash_timer_expire(void *args)
19937 {
19938 	int			flush_flag = 0;
19939 	ire_expire_arg_t	iea;
19940 	ip_stack_t		*ipst = (ip_stack_t *)args;
19941 
19942 	iea.iea_ipst = ipst;	/* No netstack_hold */
19943 
19944 	/*
19945 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19946 	 * This lock makes sure that a new invocation of this function
19947 	 * that occurs due to an almost immediate timer firing will not
19948 	 * progress beyond this point until the current invocation is done
19949 	 */
19950 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19951 	ipst->ips_ip_ire_expire_id = 0;
19952 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19953 
19954 	/* Periodic timer */
19955 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19956 	    ipst->ips_ip_ire_arp_interval) {
19957 		/*
19958 		 * Remove all IRE_CACHE entries since they might
19959 		 * contain arp information.
19960 		 */
19961 		flush_flag |= FLUSH_ARP_TIME;
19962 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19963 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19964 	}
19965 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19966 	    ipst->ips_ip_ire_redir_interval) {
19967 		/* Remove all redirects */
19968 		flush_flag |= FLUSH_REDIRECT_TIME;
19969 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19970 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19971 	}
19972 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19973 	    ipst->ips_ip_ire_pathmtu_interval) {
19974 		/* Increase path mtu */
19975 		flush_flag |= FLUSH_MTU_TIME;
19976 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19977 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19978 	}
19979 
19980 	/*
19981 	 * Optimize for the case when there are no redirects in the
19982 	 * ftable, that is, no need to walk the ftable in that case.
19983 	 */
19984 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19985 		iea.iea_flush_flag = flush_flag;
19986 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19987 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19988 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19989 		    NULL, ALL_ZONES, ipst);
19990 	}
19991 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19992 	    ipst->ips_ip_redirect_cnt > 0) {
19993 		iea.iea_flush_flag = flush_flag;
19994 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19995 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19996 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19997 	}
19998 	if (flush_flag & FLUSH_MTU_TIME) {
19999 		/*
20000 		 * Walk all IPv6 IRE's and update them
20001 		 * Note that ARP and redirect timers are not
20002 		 * needed since NUD handles stale entries.
20003 		 */
20004 		flush_flag = FLUSH_MTU_TIME;
20005 		iea.iea_flush_flag = flush_flag;
20006 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20007 		    ALL_ZONES, ipst);
20008 	}
20009 
20010 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20011 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20012 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20013 
20014 	/*
20015 	 * Hold the lock to serialize timeout calls and prevent
20016 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20017 	 * for the timer to fire and a new invocation of this function
20018 	 * to start before the return value of timeout has been stored
20019 	 * in ip_ire_expire_id by the current invocation.
20020 	 */
20021 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20022 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20023 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20024 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20025 }
20026 
20027 /*
20028  * Called by the memory allocator subsystem directly, when the system
20029  * is running low on memory.
20030  */
20031 /* ARGSUSED */
20032 void
20033 ip_trash_ire_reclaim(void *args)
20034 {
20035 	netstack_handle_t nh;
20036 	netstack_t *ns;
20037 
20038 	netstack_next_init(&nh);
20039 	while ((ns = netstack_next(&nh)) != NULL) {
20040 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20041 		netstack_rele(ns);
20042 	}
20043 	netstack_next_fini(&nh);
20044 }
20045 
20046 static void
20047 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20048 {
20049 	ire_cache_count_t icc;
20050 	ire_cache_reclaim_t icr;
20051 	ncc_cache_count_t ncc;
20052 	nce_cache_reclaim_t ncr;
20053 	uint_t delete_cnt;
20054 	/*
20055 	 * Memory reclaim call back.
20056 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20057 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20058 	 * entries, determine what fraction to free for
20059 	 * each category of IRE_CACHE entries giving absolute priority
20060 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20061 	 * entry will be freed unless all offlink entries are freed).
20062 	 */
20063 	icc.icc_total = 0;
20064 	icc.icc_unused = 0;
20065 	icc.icc_offlink = 0;
20066 	icc.icc_pmtu = 0;
20067 	icc.icc_onlink = 0;
20068 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20069 
20070 	/*
20071 	 * Free NCEs for IPv6 like the onlink ires.
20072 	 */
20073 	ncc.ncc_total = 0;
20074 	ncc.ncc_host = 0;
20075 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20076 
20077 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20078 	    icc.icc_pmtu + icc.icc_onlink);
20079 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20080 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20081 	if (delete_cnt == 0)
20082 		return;
20083 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20084 	/* Always delete all unused offlink entries */
20085 	icr.icr_ipst = ipst;
20086 	icr.icr_unused = 1;
20087 	if (delete_cnt <= icc.icc_unused) {
20088 		/*
20089 		 * Only need to free unused entries.  In other words,
20090 		 * there are enough unused entries to free to meet our
20091 		 * target number of freed ire cache entries.
20092 		 */
20093 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20094 		ncr.ncr_host = 0;
20095 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20096 		/*
20097 		 * Only need to free unused entries, plus a fraction of offlink
20098 		 * entries.  It follows from the first if statement that
20099 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20100 		 */
20101 		delete_cnt -= icc.icc_unused;
20102 		/* Round up # deleted by truncating fraction */
20103 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20104 		icr.icr_pmtu = icr.icr_onlink = 0;
20105 		ncr.ncr_host = 0;
20106 	} else if (delete_cnt <=
20107 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20108 		/*
20109 		 * Free all unused and offlink entries, plus a fraction of
20110 		 * pmtu entries.  It follows from the previous if statement
20111 		 * that icc_pmtu is non-zero, and that
20112 		 * delete_cnt != icc_unused + icc_offlink.
20113 		 */
20114 		icr.icr_offlink = 1;
20115 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20116 		/* Round up # deleted by truncating fraction */
20117 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20118 		icr.icr_onlink = 0;
20119 		ncr.ncr_host = 0;
20120 	} else {
20121 		/*
20122 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20123 		 * of onlink entries.  If we're here, then we know that
20124 		 * icc_onlink is non-zero, and that
20125 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20126 		 */
20127 		icr.icr_offlink = icr.icr_pmtu = 1;
20128 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20129 		    icc.icc_pmtu;
20130 		/* Round up # deleted by truncating fraction */
20131 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20132 		/* Using the same delete fraction as for onlink IREs */
20133 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20134 	}
20135 #ifdef DEBUG
20136 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20137 	    "fractions %d/%d/%d/%d\n",
20138 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20139 	    icc.icc_unused, icc.icc_offlink,
20140 	    icc.icc_pmtu, icc.icc_onlink,
20141 	    icr.icr_unused, icr.icr_offlink,
20142 	    icr.icr_pmtu, icr.icr_onlink));
20143 #endif
20144 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20145 	if (ncr.ncr_host != 0)
20146 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20147 		    (uchar_t *)&ncr, ipst);
20148 #ifdef DEBUG
20149 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20150 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20151 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20152 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20153 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20154 	    icc.icc_pmtu, icc.icc_onlink));
20155 #endif
20156 }
20157 
20158 /*
20159  * ip_unbind is called when a copy of an unbind request is received from the
20160  * upper level protocol.  We remove this conn from any fanout hash list it is
20161  * on, and zero out the bind information.  No reply is expected up above.
20162  */
20163 mblk_t *
20164 ip_unbind(queue_t *q, mblk_t *mp)
20165 {
20166 	conn_t	*connp = Q_TO_CONN(q);
20167 
20168 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20169 
20170 	if (is_system_labeled() && connp->conn_anon_port) {
20171 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20172 		    connp->conn_mlp_type, connp->conn_ulp,
20173 		    ntohs(connp->conn_lport), B_FALSE);
20174 		connp->conn_anon_port = 0;
20175 	}
20176 	connp->conn_mlp_type = mlptSingle;
20177 
20178 	ipcl_hash_remove(connp);
20179 
20180 	ASSERT(mp->b_cont == NULL);
20181 	/*
20182 	 * Convert mp into a T_OK_ACK
20183 	 */
20184 	mp = mi_tpi_ok_ack_alloc(mp);
20185 
20186 	/*
20187 	 * should not happen in practice... T_OK_ACK is smaller than the
20188 	 * original message.
20189 	 */
20190 	if (mp == NULL)
20191 		return (NULL);
20192 
20193 	/*
20194 	 * Don't bzero the ports if its TCP since TCP still needs the
20195 	 * lport to remove it from its own bind hash. TCP will do the
20196 	 * cleanup.
20197 	 */
20198 	if (!IPCL_IS_TCP(connp))
20199 		bzero(&connp->u_port, sizeof (connp->u_port));
20200 
20201 	return (mp);
20202 }
20203 
20204 /*
20205  * Write side put procedure.  Outbound data, IOCTLs, responses from
20206  * resolvers, etc, come down through here.
20207  *
20208  * arg2 is always a queue_t *.
20209  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20210  * the zoneid.
20211  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20212  */
20213 void
20214 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20215 {
20216 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20217 }
20218 
20219 void
20220 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20221     ip_opt_info_t *infop)
20222 {
20223 	conn_t		*connp = NULL;
20224 	queue_t		*q = (queue_t *)arg2;
20225 	ipha_t		*ipha;
20226 #define	rptr	((uchar_t *)ipha)
20227 	ire_t		*ire = NULL;
20228 	ire_t		*sctp_ire = NULL;
20229 	uint32_t	v_hlen_tos_len;
20230 	ipaddr_t	dst;
20231 	mblk_t		*first_mp = NULL;
20232 	boolean_t	mctl_present;
20233 	ipsec_out_t	*io;
20234 	int		match_flags;
20235 	ill_t		*attach_ill = NULL;
20236 					/* Bind to IPIF_NOFAILOVER ill etc. */
20237 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20238 	ipif_t		*dst_ipif;
20239 	boolean_t	multirt_need_resolve = B_FALSE;
20240 	mblk_t		*copy_mp = NULL;
20241 	int		err;
20242 	zoneid_t	zoneid;
20243 	int	adjust;
20244 	uint16_t iplen;
20245 	boolean_t	need_decref = B_FALSE;
20246 	boolean_t	ignore_dontroute = B_FALSE;
20247 	boolean_t	ignore_nexthop = B_FALSE;
20248 	boolean_t	ip_nexthop = B_FALSE;
20249 	ipaddr_t	nexthop_addr;
20250 	ip_stack_t	*ipst;
20251 
20252 #ifdef	_BIG_ENDIAN
20253 #define	V_HLEN	(v_hlen_tos_len >> 24)
20254 #else
20255 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20256 #endif
20257 
20258 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20259 	    "ip_wput_start: q %p", q);
20260 
20261 	/*
20262 	 * ip_wput fast path
20263 	 */
20264 
20265 	/* is packet from ARP ? */
20266 	if (q->q_next != NULL) {
20267 		zoneid = (zoneid_t)(uintptr_t)arg;
20268 		goto qnext;
20269 	}
20270 
20271 	connp = (conn_t *)arg;
20272 	ASSERT(connp != NULL);
20273 	zoneid = connp->conn_zoneid;
20274 	ipst = connp->conn_netstack->netstack_ip;
20275 
20276 	/* is queue flow controlled? */
20277 	if ((q->q_first != NULL || connp->conn_draining) &&
20278 	    (caller == IP_WPUT)) {
20279 		ASSERT(!need_decref);
20280 		(void) putq(q, mp);
20281 		return;
20282 	}
20283 
20284 	/* Multidata transmit? */
20285 	if (DB_TYPE(mp) == M_MULTIDATA) {
20286 		/*
20287 		 * We should never get here, since all Multidata messages
20288 		 * originating from tcp should have been directed over to
20289 		 * tcp_multisend() in the first place.
20290 		 */
20291 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20292 		freemsg(mp);
20293 		return;
20294 	} else if (DB_TYPE(mp) != M_DATA)
20295 		goto notdata;
20296 
20297 	if (mp->b_flag & MSGHASREF) {
20298 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20299 		mp->b_flag &= ~MSGHASREF;
20300 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20301 		need_decref = B_TRUE;
20302 	}
20303 	ipha = (ipha_t *)mp->b_rptr;
20304 
20305 	/* is IP header non-aligned or mblk smaller than basic IP header */
20306 #ifndef SAFETY_BEFORE_SPEED
20307 	if (!OK_32PTR(rptr) ||
20308 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20309 		goto hdrtoosmall;
20310 #endif
20311 
20312 	ASSERT(OK_32PTR(ipha));
20313 
20314 	/*
20315 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20316 	 * wrong version, we'll catch it again in ip_output_v6.
20317 	 *
20318 	 * Note that this is *only* locally-generated output here, and never
20319 	 * forwarded data, and that we need to deal only with transports that
20320 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20321 	 * label.)
20322 	 */
20323 	if (is_system_labeled() &&
20324 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20325 	    !connp->conn_ulp_labeled) {
20326 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20327 		    connp->conn_mac_exempt, ipst);
20328 		ipha = (ipha_t *)mp->b_rptr;
20329 		if (err != 0) {
20330 			first_mp = mp;
20331 			if (err == EINVAL)
20332 				goto icmp_parameter_problem;
20333 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20334 			goto discard_pkt;
20335 		}
20336 		iplen = ntohs(ipha->ipha_length) + adjust;
20337 		ipha->ipha_length = htons(iplen);
20338 	}
20339 
20340 	ASSERT(infop != NULL);
20341 
20342 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20343 		/*
20344 		 * IP_PKTINFO ancillary option is present.
20345 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20346 		 * allows using address of any zone as the source address.
20347 		 */
20348 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20349 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20350 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20351 		if (ire == NULL)
20352 			goto drop_pkt;
20353 		ire_refrele(ire);
20354 		ire = NULL;
20355 	}
20356 
20357 	/*
20358 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20359 	 * ill index passed in IP_PKTINFO.
20360 	 */
20361 	if (infop->ip_opt_ill_index != 0 &&
20362 	    connp->conn_xmit_if_ill == NULL &&
20363 	    connp->conn_nofailover_ill == NULL) {
20364 
20365 		xmit_ill = ill_lookup_on_ifindex(
20366 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20367 		    ipst);
20368 
20369 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20370 			goto drop_pkt;
20371 		/*
20372 		 * check that there is an ipif belonging
20373 		 * to our zone. IPCL_ZONEID is not used because
20374 		 * IP_ALLZONES option is valid only when the ill is
20375 		 * accessible from all zones i.e has a valid ipif in
20376 		 * all zones.
20377 		 */
20378 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20379 			goto drop_pkt;
20380 		}
20381 	}
20382 
20383 	/*
20384 	 * If there is a policy, try to attach an ipsec_out in
20385 	 * the front. At the end, first_mp either points to a
20386 	 * M_DATA message or IPSEC_OUT message linked to a
20387 	 * M_DATA message. We have to do it now as we might
20388 	 * lose the "conn" if we go through ip_newroute.
20389 	 */
20390 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20391 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20392 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20393 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20394 			if (need_decref)
20395 				CONN_DEC_REF(connp);
20396 			return;
20397 		} else {
20398 			ASSERT(mp->b_datap->db_type == M_CTL);
20399 			first_mp = mp;
20400 			mp = mp->b_cont;
20401 			mctl_present = B_TRUE;
20402 		}
20403 	} else {
20404 		first_mp = mp;
20405 		mctl_present = B_FALSE;
20406 	}
20407 
20408 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20409 
20410 	/* is wrong version or IP options present */
20411 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20412 		goto version_hdrlen_check;
20413 	dst = ipha->ipha_dst;
20414 
20415 	if (connp->conn_nofailover_ill != NULL) {
20416 		attach_ill = conn_get_held_ill(connp,
20417 		    &connp->conn_nofailover_ill, &err);
20418 		if (err == ILL_LOOKUP_FAILED) {
20419 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20420 			if (need_decref)
20421 				CONN_DEC_REF(connp);
20422 			freemsg(first_mp);
20423 			return;
20424 		}
20425 	}
20426 
20427 
20428 	/* is packet multicast? */
20429 	if (CLASSD(dst))
20430 		goto multicast;
20431 
20432 	/*
20433 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20434 	 * takes precedence over conn_dontroute and conn_nexthop_set
20435 	 */
20436 	if (xmit_ill != NULL) {
20437 		goto send_from_ill;
20438 	}
20439 
20440 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20441 	    (connp->conn_nexthop_set)) {
20442 		/*
20443 		 * If the destination is a broadcast or a loopback
20444 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20445 		 * through the standard path. But in the case of local
20446 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20447 		 * the standard path not IP_XMIT_IF.
20448 		 */
20449 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20450 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20451 		    (ire->ire_type != IRE_LOOPBACK))) {
20452 			if ((connp->conn_dontroute ||
20453 			    connp->conn_nexthop_set) && (ire != NULL) &&
20454 			    (ire->ire_type == IRE_LOCAL))
20455 				goto standard_path;
20456 
20457 			if (ire != NULL) {
20458 				ire_refrele(ire);
20459 				/* No more access to ire */
20460 				ire = NULL;
20461 			}
20462 			/*
20463 			 * bypass routing checks and go directly to
20464 			 * interface.
20465 			 */
20466 			if (connp->conn_dontroute) {
20467 				goto dontroute;
20468 			} else if (connp->conn_nexthop_set) {
20469 				ip_nexthop = B_TRUE;
20470 				nexthop_addr = connp->conn_nexthop_v4;
20471 				goto send_from_ill;
20472 			}
20473 
20474 			/*
20475 			 * If IP_XMIT_IF socket option is set,
20476 			 * then we allow unicast and multicast
20477 			 * packets to go through the ill. It is
20478 			 * quite possible that the destination
20479 			 * is not in the ire cache table and we
20480 			 * do not want to go to ip_newroute()
20481 			 * instead we call ip_newroute_ipif.
20482 			 */
20483 			xmit_ill = conn_get_held_ill(connp,
20484 			    &connp->conn_xmit_if_ill, &err);
20485 			if (err == ILL_LOOKUP_FAILED) {
20486 				BUMP_MIB(&ipst->ips_ip_mib,
20487 				    ipIfStatsOutDiscards);
20488 				if (attach_ill != NULL)
20489 					ill_refrele(attach_ill);
20490 				if (need_decref)
20491 					CONN_DEC_REF(connp);
20492 				freemsg(first_mp);
20493 				return;
20494 			}
20495 			goto send_from_ill;
20496 		}
20497 standard_path:
20498 		/* Must be a broadcast, a loopback or a local ire */
20499 		if (ire != NULL) {
20500 			ire_refrele(ire);
20501 			/* No more access to ire */
20502 			ire = NULL;
20503 		}
20504 	}
20505 
20506 	if (attach_ill != NULL)
20507 		goto send_from_ill;
20508 
20509 	/*
20510 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20511 	 * this for the tcp global queue and listen end point
20512 	 * as it does not really have a real destination to
20513 	 * talk to.  This is also true for SCTP.
20514 	 */
20515 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20516 	    !connp->conn_fully_bound) {
20517 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20518 		if (ire == NULL)
20519 			goto noirefound;
20520 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20521 		    "ip_wput_end: q %p (%S)", q, "end");
20522 
20523 		/*
20524 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20525 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20526 		 */
20527 		if (ire->ire_flags & RTF_MULTIRT) {
20528 
20529 			/*
20530 			 * Force the TTL of multirouted packets if required.
20531 			 * The TTL of such packets is bounded by the
20532 			 * ip_multirt_ttl ndd variable.
20533 			 */
20534 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20535 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20536 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20537 				    "(was %d), dst 0x%08x\n",
20538 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20539 				    ntohl(ire->ire_addr)));
20540 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20541 			}
20542 			/*
20543 			 * We look at this point if there are pending
20544 			 * unresolved routes. ire_multirt_resolvable()
20545 			 * checks in O(n) that all IRE_OFFSUBNET ire
20546 			 * entries for the packet's destination and
20547 			 * flagged RTF_MULTIRT are currently resolved.
20548 			 * If some remain unresolved, we make a copy
20549 			 * of the current message. It will be used
20550 			 * to initiate additional route resolutions.
20551 			 */
20552 			multirt_need_resolve =
20553 			    ire_multirt_need_resolve(ire->ire_addr,
20554 			    MBLK_GETLABEL(first_mp), ipst);
20555 			ip2dbg(("ip_wput[TCP]: ire %p, "
20556 			    "multirt_need_resolve %d, first_mp %p\n",
20557 			    (void *)ire, multirt_need_resolve,
20558 			    (void *)first_mp));
20559 			if (multirt_need_resolve) {
20560 				copy_mp = copymsg(first_mp);
20561 				if (copy_mp != NULL) {
20562 					MULTIRT_DEBUG_TAG(copy_mp);
20563 				}
20564 			}
20565 		}
20566 
20567 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20568 
20569 		/*
20570 		 * Try to resolve another multiroute if
20571 		 * ire_multirt_need_resolve() deemed it necessary.
20572 		 */
20573 		if (copy_mp != NULL) {
20574 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20575 		}
20576 		if (need_decref)
20577 			CONN_DEC_REF(connp);
20578 		return;
20579 	}
20580 
20581 	/*
20582 	 * Access to conn_ire_cache. (protected by conn_lock)
20583 	 *
20584 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20585 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20586 	 * send a packet or two with the IRE_CACHE that is going away.
20587 	 * Access to the ire requires an ire refhold on the ire prior to
20588 	 * its use since an interface unplumb thread may delete the cached
20589 	 * ire and release the refhold at any time.
20590 	 *
20591 	 * Caching an ire in the conn_ire_cache
20592 	 *
20593 	 * o Caching an ire pointer in the conn requires a strict check for
20594 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20595 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20596 	 * in the conn is done after making sure under the bucket lock that the
20597 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20598 	 * caching an ire after the unplumb thread has cleaned up the conn.
20599 	 * If the conn does not send a packet subsequently the unplumb thread
20600 	 * will be hanging waiting for the ire count to drop to zero.
20601 	 *
20602 	 * o We also need to atomically test for a null conn_ire_cache and
20603 	 * set the conn_ire_cache under the the protection of the conn_lock
20604 	 * to avoid races among concurrent threads trying to simultaneously
20605 	 * cache an ire in the conn_ire_cache.
20606 	 */
20607 	mutex_enter(&connp->conn_lock);
20608 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20609 
20610 	if (ire != NULL && ire->ire_addr == dst &&
20611 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20612 
20613 		IRE_REFHOLD(ire);
20614 		mutex_exit(&connp->conn_lock);
20615 
20616 	} else {
20617 		boolean_t cached = B_FALSE;
20618 		connp->conn_ire_cache = NULL;
20619 		mutex_exit(&connp->conn_lock);
20620 		/* Release the old ire */
20621 		if (ire != NULL && sctp_ire == NULL)
20622 			IRE_REFRELE_NOTR(ire);
20623 
20624 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20625 		if (ire == NULL)
20626 			goto noirefound;
20627 		IRE_REFHOLD_NOTR(ire);
20628 
20629 		mutex_enter(&connp->conn_lock);
20630 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20631 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20632 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20633 				if (connp->conn_ulp == IPPROTO_TCP)
20634 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20635 				connp->conn_ire_cache = ire;
20636 				cached = B_TRUE;
20637 			}
20638 			rw_exit(&ire->ire_bucket->irb_lock);
20639 		}
20640 		mutex_exit(&connp->conn_lock);
20641 
20642 		/*
20643 		 * We can continue to use the ire but since it was
20644 		 * not cached, we should drop the extra reference.
20645 		 */
20646 		if (!cached)
20647 			IRE_REFRELE_NOTR(ire);
20648 	}
20649 
20650 
20651 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20652 	    "ip_wput_end: q %p (%S)", q, "end");
20653 
20654 	/*
20655 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20656 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20657 	 */
20658 	if (ire->ire_flags & RTF_MULTIRT) {
20659 
20660 		/*
20661 		 * Force the TTL of multirouted packets if required.
20662 		 * The TTL of such packets is bounded by the
20663 		 * ip_multirt_ttl ndd variable.
20664 		 */
20665 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20666 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20667 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20668 			    "(was %d), dst 0x%08x\n",
20669 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20670 			    ntohl(ire->ire_addr)));
20671 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20672 		}
20673 
20674 		/*
20675 		 * At this point, we check to see if there are any pending
20676 		 * unresolved routes. ire_multirt_resolvable()
20677 		 * checks in O(n) that all IRE_OFFSUBNET ire
20678 		 * entries for the packet's destination and
20679 		 * flagged RTF_MULTIRT are currently resolved.
20680 		 * If some remain unresolved, we make a copy
20681 		 * of the current message. It will be used
20682 		 * to initiate additional route resolutions.
20683 		 */
20684 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20685 		    MBLK_GETLABEL(first_mp), ipst);
20686 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20687 		    "multirt_need_resolve %d, first_mp %p\n",
20688 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20689 		if (multirt_need_resolve) {
20690 			copy_mp = copymsg(first_mp);
20691 			if (copy_mp != NULL) {
20692 				MULTIRT_DEBUG_TAG(copy_mp);
20693 			}
20694 		}
20695 	}
20696 
20697 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20698 
20699 	/*
20700 	 * Try to resolve another multiroute if
20701 	 * ire_multirt_resolvable() deemed it necessary
20702 	 */
20703 	if (copy_mp != NULL) {
20704 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20705 	}
20706 	if (need_decref)
20707 		CONN_DEC_REF(connp);
20708 	return;
20709 
20710 qnext:
20711 	/*
20712 	 * Upper Level Protocols pass down complete IP datagrams
20713 	 * as M_DATA messages.	Everything else is a sideshow.
20714 	 *
20715 	 * 1) We could be re-entering ip_wput because of ip_neworute
20716 	 *    in which case we could have a IPSEC_OUT message. We
20717 	 *    need to pass through ip_wput like other datagrams and
20718 	 *    hence cannot branch to ip_wput_nondata.
20719 	 *
20720 	 * 2) ARP, AH, ESP, and other clients who are on the module
20721 	 *    instance of IP stream, give us something to deal with.
20722 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20723 	 *
20724 	 * 3) ICMP replies also could come here.
20725 	 */
20726 	ipst = ILLQ_TO_IPST(q);
20727 
20728 	if (DB_TYPE(mp) != M_DATA) {
20729 notdata:
20730 		if (DB_TYPE(mp) == M_CTL) {
20731 			/*
20732 			 * M_CTL messages are used by ARP, AH and ESP to
20733 			 * communicate with IP. We deal with IPSEC_IN and
20734 			 * IPSEC_OUT here. ip_wput_nondata handles other
20735 			 * cases.
20736 			 */
20737 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20738 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20739 				first_mp = mp->b_cont;
20740 				first_mp->b_flag &= ~MSGHASREF;
20741 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20742 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20743 				CONN_DEC_REF(connp);
20744 				connp = NULL;
20745 			}
20746 			if (ii->ipsec_info_type == IPSEC_IN) {
20747 				/*
20748 				 * Either this message goes back to
20749 				 * IPSEC for further processing or to
20750 				 * ULP after policy checks.
20751 				 */
20752 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20753 				return;
20754 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20755 				io = (ipsec_out_t *)ii;
20756 				if (io->ipsec_out_proc_begin) {
20757 					/*
20758 					 * IPSEC processing has already started.
20759 					 * Complete it.
20760 					 * IPQoS notes: We don't care what is
20761 					 * in ipsec_out_ill_index since this
20762 					 * won't be processed for IPQoS policies
20763 					 * in ipsec_out_process.
20764 					 */
20765 					ipsec_out_process(q, mp, NULL,
20766 					    io->ipsec_out_ill_index);
20767 					return;
20768 				} else {
20769 					connp = (q->q_next != NULL) ?
20770 					    NULL : Q_TO_CONN(q);
20771 					first_mp = mp;
20772 					mp = mp->b_cont;
20773 					mctl_present = B_TRUE;
20774 				}
20775 				zoneid = io->ipsec_out_zoneid;
20776 				ASSERT(zoneid != ALL_ZONES);
20777 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20778 				/*
20779 				 * It's an IPsec control message requesting
20780 				 * an SADB update to be sent to the IPsec
20781 				 * hardware acceleration capable ills.
20782 				 */
20783 				ipsec_ctl_t *ipsec_ctl =
20784 				    (ipsec_ctl_t *)mp->b_rptr;
20785 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20786 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20787 				mblk_t *cmp = mp->b_cont;
20788 
20789 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20790 				ASSERT(cmp != NULL);
20791 
20792 				freeb(mp);
20793 				ill_ipsec_capab_send_all(satype, cmp, sa,
20794 				    ipst->ips_netstack);
20795 				return;
20796 			} else {
20797 				/*
20798 				 * This must be ARP or special TSOL signaling.
20799 				 */
20800 				ip_wput_nondata(NULL, q, mp, NULL);
20801 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20802 				    "ip_wput_end: q %p (%S)", q, "nondata");
20803 				return;
20804 			}
20805 		} else {
20806 			/*
20807 			 * This must be non-(ARP/AH/ESP) messages.
20808 			 */
20809 			ASSERT(!need_decref);
20810 			ip_wput_nondata(NULL, q, mp, NULL);
20811 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20812 			    "ip_wput_end: q %p (%S)", q, "nondata");
20813 			return;
20814 		}
20815 	} else {
20816 		first_mp = mp;
20817 		mctl_present = B_FALSE;
20818 	}
20819 
20820 	ASSERT(first_mp != NULL);
20821 	/*
20822 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20823 	 * to make sure that this packet goes out on the same interface it
20824 	 * came in. We handle that here.
20825 	 */
20826 	if (mctl_present) {
20827 		uint_t ifindex;
20828 
20829 		io = (ipsec_out_t *)first_mp->b_rptr;
20830 		if (io->ipsec_out_attach_if ||
20831 		    io->ipsec_out_xmit_if ||
20832 		    io->ipsec_out_ip_nexthop) {
20833 			ill_t	*ill;
20834 
20835 			/*
20836 			 * We may have lost the conn context if we are
20837 			 * coming here from ip_newroute(). Copy the
20838 			 * nexthop information.
20839 			 */
20840 			if (io->ipsec_out_ip_nexthop) {
20841 				ip_nexthop = B_TRUE;
20842 				nexthop_addr = io->ipsec_out_nexthop_addr;
20843 
20844 				ipha = (ipha_t *)mp->b_rptr;
20845 				dst = ipha->ipha_dst;
20846 				goto send_from_ill;
20847 			} else {
20848 				ASSERT(io->ipsec_out_ill_index != 0);
20849 				ifindex = io->ipsec_out_ill_index;
20850 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20851 				    NULL, NULL, NULL, NULL, ipst);
20852 				/*
20853 				 * ipsec_out_xmit_if bit is used to tell
20854 				 * ip_wput to use the ill to send outgoing data
20855 				 * as we have no conn when data comes from ICMP
20856 				 * error msg routines. Currently this feature is
20857 				 * only used by ip_mrtun_forward routine.
20858 				 */
20859 				if (io->ipsec_out_xmit_if) {
20860 					xmit_ill = ill;
20861 					if (xmit_ill == NULL) {
20862 						ip1dbg(("ip_output:bad ifindex "
20863 						    "for xmit_ill %d\n",
20864 						    ifindex));
20865 						freemsg(first_mp);
20866 						BUMP_MIB(&ipst->ips_ip_mib,
20867 						    ipIfStatsOutDiscards);
20868 						ASSERT(!need_decref);
20869 						return;
20870 					}
20871 					/* Free up the ipsec_out_t mblk */
20872 					ASSERT(first_mp->b_cont == mp);
20873 					first_mp->b_cont = NULL;
20874 					freeb(first_mp);
20875 					/* Just send the IP header+ICMP+data */
20876 					first_mp = mp;
20877 					ipha = (ipha_t *)mp->b_rptr;
20878 					dst = ipha->ipha_dst;
20879 					goto send_from_ill;
20880 				} else {
20881 					attach_ill = ill;
20882 				}
20883 
20884 				if (attach_ill == NULL) {
20885 					ASSERT(xmit_ill == NULL);
20886 					ip1dbg(("ip_output: bad ifindex for "
20887 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20888 					    ifindex));
20889 					freemsg(first_mp);
20890 					BUMP_MIB(&ipst->ips_ip_mib,
20891 					    ipIfStatsOutDiscards);
20892 					ASSERT(!need_decref);
20893 					return;
20894 				}
20895 			}
20896 		}
20897 	}
20898 
20899 	ASSERT(xmit_ill == NULL);
20900 
20901 	/* We have a complete IP datagram heading outbound. */
20902 	ipha = (ipha_t *)mp->b_rptr;
20903 
20904 #ifndef SPEED_BEFORE_SAFETY
20905 	/*
20906 	 * Make sure we have a full-word aligned message and that at least
20907 	 * a simple IP header is accessible in the first message.  If not,
20908 	 * try a pullup.
20909 	 */
20910 	if (!OK_32PTR(rptr) ||
20911 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20912 hdrtoosmall:
20913 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20914 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20915 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20916 			if (first_mp == NULL)
20917 				first_mp = mp;
20918 			goto discard_pkt;
20919 		}
20920 
20921 		/* This function assumes that mp points to an IPv4 packet. */
20922 		if (is_system_labeled() && q->q_next == NULL &&
20923 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20924 		    !connp->conn_ulp_labeled) {
20925 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20926 			    &adjust, connp->conn_mac_exempt, ipst);
20927 			ipha = (ipha_t *)mp->b_rptr;
20928 			if (first_mp != NULL)
20929 				first_mp->b_cont = mp;
20930 			if (err != 0) {
20931 				if (first_mp == NULL)
20932 					first_mp = mp;
20933 				if (err == EINVAL)
20934 					goto icmp_parameter_problem;
20935 				ip2dbg(("ip_wput: label check failed (%d)\n",
20936 				    err));
20937 				goto discard_pkt;
20938 			}
20939 			iplen = ntohs(ipha->ipha_length) + adjust;
20940 			ipha->ipha_length = htons(iplen);
20941 		}
20942 
20943 		ipha = (ipha_t *)mp->b_rptr;
20944 		if (first_mp == NULL) {
20945 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20946 			/*
20947 			 * If we got here because of "goto hdrtoosmall"
20948 			 * We need to attach a IPSEC_OUT.
20949 			 */
20950 			if (connp->conn_out_enforce_policy) {
20951 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20952 				    NULL, ipha->ipha_protocol,
20953 				    ipst->ips_netstack)) == NULL)) {
20954 					BUMP_MIB(&ipst->ips_ip_mib,
20955 					    ipIfStatsOutDiscards);
20956 					if (need_decref)
20957 						CONN_DEC_REF(connp);
20958 					return;
20959 				} else {
20960 					ASSERT(mp->b_datap->db_type == M_CTL);
20961 					first_mp = mp;
20962 					mp = mp->b_cont;
20963 					mctl_present = B_TRUE;
20964 				}
20965 			} else {
20966 				first_mp = mp;
20967 				mctl_present = B_FALSE;
20968 			}
20969 		}
20970 	}
20971 #endif
20972 
20973 	/* Most of the code below is written for speed, not readability */
20974 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20975 
20976 	/*
20977 	 * If ip_newroute() fails, we're going to need a full
20978 	 * header for the icmp wraparound.
20979 	 */
20980 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20981 		uint_t	v_hlen;
20982 version_hdrlen_check:
20983 		ASSERT(first_mp != NULL);
20984 		v_hlen = V_HLEN;
20985 		/*
20986 		 * siphon off IPv6 packets coming down from transport
20987 		 * layer modules here.
20988 		 * Note: high-order bit carries NUD reachability confirmation
20989 		 */
20990 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20991 			/*
20992 			 * XXX implement a IPv4 and IPv6 packet counter per
20993 			 * conn and switch when ratio exceeds e.g. 10:1
20994 			 */
20995 #ifdef notyet
20996 			if (q->q_next == NULL) /* Avoid ill queue */
20997 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
20998 #endif
20999 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21000 			ASSERT(xmit_ill == NULL);
21001 			if (attach_ill != NULL)
21002 				ill_refrele(attach_ill);
21003 			if (need_decref)
21004 				mp->b_flag |= MSGHASREF;
21005 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21006 			return;
21007 		}
21008 
21009 		if ((v_hlen >> 4) != IP_VERSION) {
21010 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21011 			    "ip_wput_end: q %p (%S)", q, "badvers");
21012 			goto discard_pkt;
21013 		}
21014 		/*
21015 		 * Is the header length at least 20 bytes?
21016 		 *
21017 		 * Are there enough bytes accessible in the header?  If
21018 		 * not, try a pullup.
21019 		 */
21020 		v_hlen &= 0xF;
21021 		v_hlen <<= 2;
21022 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21023 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21024 			    "ip_wput_end: q %p (%S)", q, "badlen");
21025 			goto discard_pkt;
21026 		}
21027 		if (v_hlen > (mp->b_wptr - rptr)) {
21028 			if (!pullupmsg(mp, v_hlen)) {
21029 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21030 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21031 				goto discard_pkt;
21032 			}
21033 			ipha = (ipha_t *)mp->b_rptr;
21034 		}
21035 		/*
21036 		 * Move first entry from any source route into ipha_dst and
21037 		 * verify the options
21038 		 */
21039 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21040 		    zoneid, ipst)) {
21041 			ASSERT(xmit_ill == NULL);
21042 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21043 			if (attach_ill != NULL)
21044 				ill_refrele(attach_ill);
21045 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21046 			    "ip_wput_end: q %p (%S)", q, "badopts");
21047 			if (need_decref)
21048 				CONN_DEC_REF(connp);
21049 			return;
21050 		}
21051 	}
21052 	dst = ipha->ipha_dst;
21053 
21054 	/*
21055 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21056 	 * we have to run the packet through ip_newroute which will take
21057 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21058 	 * a resolver, or assigning a default gateway, etc.
21059 	 */
21060 	if (CLASSD(dst)) {
21061 		ipif_t	*ipif;
21062 		uint32_t setsrc = 0;
21063 
21064 multicast:
21065 		ASSERT(first_mp != NULL);
21066 		ip2dbg(("ip_wput: CLASSD\n"));
21067 		if (connp == NULL) {
21068 			/*
21069 			 * Use the first good ipif on the ill.
21070 			 * XXX Should this ever happen? (Appears
21071 			 * to show up with just ppp and no ethernet due
21072 			 * to in.rdisc.)
21073 			 * However, ire_send should be able to
21074 			 * call ip_wput_ire directly.
21075 			 *
21076 			 * XXX Also, this can happen for ICMP and other packets
21077 			 * with multicast source addresses.  Perhaps we should
21078 			 * fix things so that we drop the packet in question,
21079 			 * but for now, just run with it.
21080 			 */
21081 			ill_t *ill = (ill_t *)q->q_ptr;
21082 
21083 			/*
21084 			 * Don't honor attach_if for this case. If ill
21085 			 * is part of the group, ipif could belong to
21086 			 * any ill and we cannot maintain attach_ill
21087 			 * and ipif_ill same anymore and the assert
21088 			 * below would fail.
21089 			 */
21090 			if (mctl_present && io->ipsec_out_attach_if) {
21091 				io->ipsec_out_ill_index = 0;
21092 				io->ipsec_out_attach_if = B_FALSE;
21093 				ASSERT(attach_ill != NULL);
21094 				ill_refrele(attach_ill);
21095 				attach_ill = NULL;
21096 			}
21097 
21098 			ASSERT(attach_ill == NULL);
21099 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21100 			if (ipif == NULL) {
21101 				if (need_decref)
21102 					CONN_DEC_REF(connp);
21103 				freemsg(first_mp);
21104 				return;
21105 			}
21106 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21107 			    ntohl(dst), ill->ill_name));
21108 		} else {
21109 			/*
21110 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21111 			 * and IP_MULTICAST_IF.
21112 			 * Block comment above this function explains the
21113 			 * locking mechanism used here
21114 			 */
21115 			if (xmit_ill == NULL) {
21116 				xmit_ill = conn_get_held_ill(connp,
21117 				    &connp->conn_xmit_if_ill, &err);
21118 				if (err == ILL_LOOKUP_FAILED) {
21119 					ip1dbg(("ip_wput: No ill for "
21120 					    "IP_XMIT_IF\n"));
21121 					BUMP_MIB(&ipst->ips_ip_mib,
21122 					    ipIfStatsOutNoRoutes);
21123 					goto drop_pkt;
21124 				}
21125 			}
21126 
21127 			if (xmit_ill == NULL) {
21128 				ipif = conn_get_held_ipif(connp,
21129 				    &connp->conn_multicast_ipif, &err);
21130 				if (err == IPIF_LOOKUP_FAILED) {
21131 					ip1dbg(("ip_wput: No ipif for "
21132 					    "multicast\n"));
21133 					BUMP_MIB(&ipst->ips_ip_mib,
21134 					    ipIfStatsOutNoRoutes);
21135 					goto drop_pkt;
21136 				}
21137 			}
21138 			if (xmit_ill != NULL) {
21139 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21140 				if (ipif == NULL) {
21141 					ip1dbg(("ip_wput: No ipif for "
21142 					    "IP_XMIT_IF\n"));
21143 					BUMP_MIB(&ipst->ips_ip_mib,
21144 					    ipIfStatsOutNoRoutes);
21145 					goto drop_pkt;
21146 				}
21147 			} else if (ipif == NULL || ipif->ipif_isv6) {
21148 				/*
21149 				 * We must do this ipif determination here
21150 				 * else we could pass through ip_newroute
21151 				 * and come back here without the conn context.
21152 				 *
21153 				 * Note: we do late binding i.e. we bind to
21154 				 * the interface when the first packet is sent.
21155 				 * For performance reasons we do not rebind on
21156 				 * each packet but keep the binding until the
21157 				 * next IP_MULTICAST_IF option.
21158 				 *
21159 				 * conn_multicast_{ipif,ill} are shared between
21160 				 * IPv4 and IPv6 and AF_INET6 sockets can
21161 				 * send both IPv4 and IPv6 packets. Hence
21162 				 * we have to check that "isv6" matches above.
21163 				 */
21164 				if (ipif != NULL)
21165 					ipif_refrele(ipif);
21166 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21167 				if (ipif == NULL) {
21168 					ip1dbg(("ip_wput: No ipif for "
21169 					    "multicast\n"));
21170 					BUMP_MIB(&ipst->ips_ip_mib,
21171 					    ipIfStatsOutNoRoutes);
21172 					goto drop_pkt;
21173 				}
21174 				err = conn_set_held_ipif(connp,
21175 				    &connp->conn_multicast_ipif, ipif);
21176 				if (err == IPIF_LOOKUP_FAILED) {
21177 					ipif_refrele(ipif);
21178 					ip1dbg(("ip_wput: No ipif for "
21179 					    "multicast\n"));
21180 					BUMP_MIB(&ipst->ips_ip_mib,
21181 					    ipIfStatsOutNoRoutes);
21182 					goto drop_pkt;
21183 				}
21184 			}
21185 		}
21186 		ASSERT(!ipif->ipif_isv6);
21187 		/*
21188 		 * As we may lose the conn by the time we reach ip_wput_ire,
21189 		 * we copy conn_multicast_loop and conn_dontroute on to an
21190 		 * ipsec_out. In case if this datagram goes out secure,
21191 		 * we need the ill_index also. Copy that also into the
21192 		 * ipsec_out.
21193 		 */
21194 		if (mctl_present) {
21195 			io = (ipsec_out_t *)first_mp->b_rptr;
21196 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21197 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21198 		} else {
21199 			ASSERT(mp == first_mp);
21200 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21201 			    BPRI_HI)) == NULL) {
21202 				ipif_refrele(ipif);
21203 				first_mp = mp;
21204 				goto discard_pkt;
21205 			}
21206 			first_mp->b_datap->db_type = M_CTL;
21207 			first_mp->b_wptr += sizeof (ipsec_info_t);
21208 			/* ipsec_out_secure is B_FALSE now */
21209 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21210 			io = (ipsec_out_t *)first_mp->b_rptr;
21211 			io->ipsec_out_type = IPSEC_OUT;
21212 			io->ipsec_out_len = sizeof (ipsec_out_t);
21213 			io->ipsec_out_use_global_policy = B_TRUE;
21214 			io->ipsec_out_ns = ipst->ips_netstack;
21215 			first_mp->b_cont = mp;
21216 			mctl_present = B_TRUE;
21217 		}
21218 		if (attach_ill != NULL) {
21219 			ASSERT(attach_ill == ipif->ipif_ill);
21220 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21221 
21222 			/*
21223 			 * Check if we need an ire that will not be
21224 			 * looked up by anybody else i.e. HIDDEN.
21225 			 */
21226 			if (ill_is_probeonly(attach_ill)) {
21227 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21228 			}
21229 			io->ipsec_out_ill_index =
21230 			    attach_ill->ill_phyint->phyint_ifindex;
21231 			io->ipsec_out_attach_if = B_TRUE;
21232 		} else {
21233 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21234 			io->ipsec_out_ill_index =
21235 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21236 		}
21237 		if (connp != NULL) {
21238 			io->ipsec_out_multicast_loop =
21239 			    connp->conn_multicast_loop;
21240 			io->ipsec_out_dontroute = connp->conn_dontroute;
21241 			io->ipsec_out_zoneid = connp->conn_zoneid;
21242 		}
21243 		/*
21244 		 * If the application uses IP_MULTICAST_IF with
21245 		 * different logical addresses of the same ILL, we
21246 		 * need to make sure that the soruce address of
21247 		 * the packet matches the logical IP address used
21248 		 * in the option. We do it by initializing ipha_src
21249 		 * here. This should keep IPSEC also happy as
21250 		 * when we return from IPSEC processing, we don't
21251 		 * have to worry about getting the right address on
21252 		 * the packet. Thus it is sufficient to look for
21253 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21254 		 * MATCH_IRE_IPIF.
21255 		 *
21256 		 * NOTE : We need to do it for non-secure case also as
21257 		 * this might go out secure if there is a global policy
21258 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21259 		 * address, the source should be initialized already and
21260 		 * hence we won't be initializing here.
21261 		 *
21262 		 * As we do not have the ire yet, it is possible that
21263 		 * we set the source address here and then later discover
21264 		 * that the ire implies the source address to be assigned
21265 		 * through the RTF_SETSRC flag.
21266 		 * In that case, the setsrc variable will remind us
21267 		 * that overwritting the source address by the one
21268 		 * of the RTF_SETSRC-flagged ire is allowed.
21269 		 */
21270 		if (ipha->ipha_src == INADDR_ANY &&
21271 		    (connp == NULL || !connp->conn_unspec_src)) {
21272 			ipha->ipha_src = ipif->ipif_src_addr;
21273 			setsrc = RTF_SETSRC;
21274 		}
21275 		/*
21276 		 * Find an IRE which matches the destination and the outgoing
21277 		 * queue (i.e. the outgoing interface.)
21278 		 * For loopback use a unicast IP address for
21279 		 * the ire lookup.
21280 		 */
21281 		if (IS_LOOPBACK(ipif->ipif_ill))
21282 			dst = ipif->ipif_lcl_addr;
21283 
21284 		/*
21285 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21286 		 * We don't need to lookup ire in ctable as the packet
21287 		 * needs to be sent to the destination through the specified
21288 		 * ill irrespective of ires in the cache table.
21289 		 */
21290 		ire = NULL;
21291 		if (xmit_ill == NULL) {
21292 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21293 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21294 		}
21295 
21296 		/*
21297 		 * refrele attach_ill as its not needed anymore.
21298 		 */
21299 		if (attach_ill != NULL) {
21300 			ill_refrele(attach_ill);
21301 			attach_ill = NULL;
21302 		}
21303 
21304 		if (ire == NULL) {
21305 			/*
21306 			 * Multicast loopback and multicast forwarding is
21307 			 * done in ip_wput_ire.
21308 			 *
21309 			 * Mark this packet to make it be delivered to
21310 			 * ip_wput_ire after the new ire has been
21311 			 * created.
21312 			 *
21313 			 * The call to ip_newroute_ipif takes into account
21314 			 * the setsrc reminder. In any case, we take care
21315 			 * of the RTF_MULTIRT flag.
21316 			 */
21317 			mp->b_prev = mp->b_next = NULL;
21318 			if (xmit_ill == NULL ||
21319 			    xmit_ill->ill_ipif_up_count > 0) {
21320 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21321 				    setsrc | RTF_MULTIRT, zoneid, infop);
21322 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21323 				    "ip_wput_end: q %p (%S)", q, "noire");
21324 			} else {
21325 				freemsg(first_mp);
21326 			}
21327 			ipif_refrele(ipif);
21328 			if (xmit_ill != NULL)
21329 				ill_refrele(xmit_ill);
21330 			if (need_decref)
21331 				CONN_DEC_REF(connp);
21332 			return;
21333 		}
21334 
21335 		ipif_refrele(ipif);
21336 		ipif = NULL;
21337 		ASSERT(xmit_ill == NULL);
21338 
21339 		/*
21340 		 * Honor the RTF_SETSRC flag for multicast packets,
21341 		 * if allowed by the setsrc reminder.
21342 		 */
21343 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21344 			ipha->ipha_src = ire->ire_src_addr;
21345 		}
21346 
21347 		/*
21348 		 * Unconditionally force the TTL to 1 for
21349 		 * multirouted multicast packets:
21350 		 * multirouted multicast should not cross
21351 		 * multicast routers.
21352 		 */
21353 		if (ire->ire_flags & RTF_MULTIRT) {
21354 			if (ipha->ipha_ttl > 1) {
21355 				ip2dbg(("ip_wput: forcing multicast "
21356 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21357 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21358 				ipha->ipha_ttl = 1;
21359 			}
21360 		}
21361 	} else {
21362 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21363 		if ((ire != NULL) && (ire->ire_type &
21364 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21365 			ignore_dontroute = B_TRUE;
21366 			ignore_nexthop = B_TRUE;
21367 		}
21368 		if (ire != NULL) {
21369 			ire_refrele(ire);
21370 			ire = NULL;
21371 		}
21372 		/*
21373 		 * Guard against coming in from arp in which case conn is NULL.
21374 		 * Also guard against non M_DATA with dontroute set but
21375 		 * destined to local, loopback or broadcast addresses.
21376 		 */
21377 		if (connp != NULL && connp->conn_dontroute &&
21378 		    !ignore_dontroute) {
21379 dontroute:
21380 			/*
21381 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21382 			 * routing protocols from seeing false direct
21383 			 * connectivity.
21384 			 */
21385 			ipha->ipha_ttl = 1;
21386 			/*
21387 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21388 			 * along with SO_DONTROUTE, higher precedence is
21389 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21390 			 */
21391 			if (connp->conn_xmit_if_ill == NULL) {
21392 				/* If suitable ipif not found, drop packet */
21393 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21394 				    ipst);
21395 				if (dst_ipif == NULL) {
21396 					ip1dbg(("ip_wput: no route for "
21397 					    "dst using SO_DONTROUTE\n"));
21398 					BUMP_MIB(&ipst->ips_ip_mib,
21399 					    ipIfStatsOutNoRoutes);
21400 					mp->b_prev = mp->b_next = NULL;
21401 					if (first_mp == NULL)
21402 						first_mp = mp;
21403 					goto drop_pkt;
21404 				} else {
21405 					/*
21406 					 * If suitable ipif has been found, set
21407 					 * xmit_ill to the corresponding
21408 					 * ipif_ill because we'll be following
21409 					 * the IP_XMIT_IF logic.
21410 					 */
21411 					ASSERT(xmit_ill == NULL);
21412 					xmit_ill = dst_ipif->ipif_ill;
21413 					mutex_enter(&xmit_ill->ill_lock);
21414 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21415 						mutex_exit(&xmit_ill->ill_lock);
21416 						xmit_ill = NULL;
21417 						ipif_refrele(dst_ipif);
21418 						ip1dbg(("ip_wput: no route for"
21419 						    " dst using"
21420 						    " SO_DONTROUTE\n"));
21421 						BUMP_MIB(&ipst->ips_ip_mib,
21422 						    ipIfStatsOutNoRoutes);
21423 						mp->b_prev = mp->b_next = NULL;
21424 						if (first_mp == NULL)
21425 							first_mp = mp;
21426 						goto drop_pkt;
21427 					}
21428 					ill_refhold_locked(xmit_ill);
21429 					mutex_exit(&xmit_ill->ill_lock);
21430 					ipif_refrele(dst_ipif);
21431 				}
21432 			}
21433 
21434 		}
21435 		/*
21436 		 * If we are bound to IPIF_NOFAILOVER address, look for
21437 		 * an IRE_CACHE matching the ill.
21438 		 */
21439 send_from_ill:
21440 		if (attach_ill != NULL) {
21441 			ipif_t	*attach_ipif;
21442 
21443 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21444 
21445 			/*
21446 			 * Check if we need an ire that will not be
21447 			 * looked up by anybody else i.e. HIDDEN.
21448 			 */
21449 			if (ill_is_probeonly(attach_ill)) {
21450 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21451 			}
21452 
21453 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21454 			if (attach_ipif == NULL) {
21455 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21456 				goto discard_pkt;
21457 			}
21458 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21459 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21460 			ipif_refrele(attach_ipif);
21461 		} else if (xmit_ill != NULL || (connp != NULL &&
21462 		    connp->conn_xmit_if_ill != NULL)) {
21463 			/*
21464 			 * Mark this packet as originated locally
21465 			 */
21466 			mp->b_prev = mp->b_next = NULL;
21467 			/*
21468 			 * xmit_ill could be NULL if SO_DONTROUTE
21469 			 * is also set.
21470 			 */
21471 			if (xmit_ill == NULL) {
21472 				xmit_ill = conn_get_held_ill(connp,
21473 				    &connp->conn_xmit_if_ill, &err);
21474 				if (err == ILL_LOOKUP_FAILED) {
21475 					BUMP_MIB(&ipst->ips_ip_mib,
21476 					    ipIfStatsOutDiscards);
21477 					if (need_decref)
21478 						CONN_DEC_REF(connp);
21479 					freemsg(first_mp);
21480 					return;
21481 				}
21482 				if (xmit_ill == NULL) {
21483 					if (connp->conn_dontroute)
21484 						goto dontroute;
21485 					goto send_from_ill;
21486 				}
21487 			}
21488 			/*
21489 			 * Could be SO_DONTROUTE case also.
21490 			 * check at least one interface is UP as
21491 			 * specified by this ILL
21492 			 */
21493 			if (xmit_ill->ill_ipif_up_count > 0) {
21494 				ipif_t *ipif;
21495 
21496 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21497 				if (ipif == NULL) {
21498 					ip1dbg(("ip_output: "
21499 					    "xmit_ill NULL ipif\n"));
21500 					goto drop_pkt;
21501 				}
21502 				/*
21503 				 * Look for a ire that is part of the group,
21504 				 * if found use it else call ip_newroute_ipif.
21505 				 * IPCL_ZONEID is not used for matching because
21506 				 * IP_ALLZONES option is valid only when the
21507 				 * ill is accessible from all zones i.e has a
21508 				 * valid ipif in all zones.
21509 				 */
21510 				match_flags = MATCH_IRE_ILL_GROUP |
21511 				    MATCH_IRE_SECATTR;
21512 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21513 				    MBLK_GETLABEL(mp), match_flags, ipst);
21514 				/*
21515 				 * If an ire exists use it or else create
21516 				 * an ire but don't add it to the cache.
21517 				 * Adding an ire may cause issues with
21518 				 * asymmetric routing.
21519 				 * In case of multiroute always act as if
21520 				 * ire does not exist.
21521 				 */
21522 				if (ire == NULL ||
21523 				    ire->ire_flags & RTF_MULTIRT) {
21524 					if (ire != NULL)
21525 						ire_refrele(ire);
21526 					ip_newroute_ipif(q, first_mp, ipif,
21527 					    dst, connp, 0, zoneid, infop);
21528 					ipif_refrele(ipif);
21529 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21530 					ill_refrele(xmit_ill);
21531 					if (need_decref)
21532 						CONN_DEC_REF(connp);
21533 					return;
21534 				}
21535 				ipif_refrele(ipif);
21536 			} else {
21537 				goto drop_pkt;
21538 			}
21539 		} else if (ip_nexthop || (connp != NULL &&
21540 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21541 			if (!ip_nexthop) {
21542 				ip_nexthop = B_TRUE;
21543 				nexthop_addr = connp->conn_nexthop_v4;
21544 			}
21545 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21546 			    MATCH_IRE_GW;
21547 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21548 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21549 		} else {
21550 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21551 			    ipst);
21552 		}
21553 		if (!ire) {
21554 			/*
21555 			 * Make sure we don't load spread if this
21556 			 * is IPIF_NOFAILOVER case.
21557 			 */
21558 			if ((attach_ill != NULL) ||
21559 			    (ip_nexthop && !ignore_nexthop)) {
21560 				if (mctl_present) {
21561 					io = (ipsec_out_t *)first_mp->b_rptr;
21562 					ASSERT(first_mp->b_datap->db_type ==
21563 					    M_CTL);
21564 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21565 				} else {
21566 					ASSERT(mp == first_mp);
21567 					first_mp = allocb(
21568 					    sizeof (ipsec_info_t), BPRI_HI);
21569 					if (first_mp == NULL) {
21570 						first_mp = mp;
21571 						goto discard_pkt;
21572 					}
21573 					first_mp->b_datap->db_type = M_CTL;
21574 					first_mp->b_wptr +=
21575 					    sizeof (ipsec_info_t);
21576 					/* ipsec_out_secure is B_FALSE now */
21577 					bzero(first_mp->b_rptr,
21578 					    sizeof (ipsec_info_t));
21579 					io = (ipsec_out_t *)first_mp->b_rptr;
21580 					io->ipsec_out_type = IPSEC_OUT;
21581 					io->ipsec_out_len =
21582 					    sizeof (ipsec_out_t);
21583 					io->ipsec_out_use_global_policy =
21584 					    B_TRUE;
21585 					io->ipsec_out_ns = ipst->ips_netstack;
21586 					first_mp->b_cont = mp;
21587 					mctl_present = B_TRUE;
21588 				}
21589 				if (attach_ill != NULL) {
21590 					io->ipsec_out_ill_index = attach_ill->
21591 					    ill_phyint->phyint_ifindex;
21592 					io->ipsec_out_attach_if = B_TRUE;
21593 				} else {
21594 					io->ipsec_out_ip_nexthop = ip_nexthop;
21595 					io->ipsec_out_nexthop_addr =
21596 					    nexthop_addr;
21597 				}
21598 			}
21599 noirefound:
21600 			/*
21601 			 * Mark this packet as having originated on
21602 			 * this machine.  This will be noted in
21603 			 * ire_add_then_send, which needs to know
21604 			 * whether to run it back through ip_wput or
21605 			 * ip_rput following successful resolution.
21606 			 */
21607 			mp->b_prev = NULL;
21608 			mp->b_next = NULL;
21609 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21610 			    ipst);
21611 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21612 			    "ip_wput_end: q %p (%S)", q, "newroute");
21613 			if (attach_ill != NULL)
21614 				ill_refrele(attach_ill);
21615 			if (xmit_ill != NULL)
21616 				ill_refrele(xmit_ill);
21617 			if (need_decref)
21618 				CONN_DEC_REF(connp);
21619 			return;
21620 		}
21621 	}
21622 
21623 	/* We now know where we are going with it. */
21624 
21625 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21626 	    "ip_wput_end: q %p (%S)", q, "end");
21627 
21628 	/*
21629 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21630 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21631 	 */
21632 	if (ire->ire_flags & RTF_MULTIRT) {
21633 		/*
21634 		 * Force the TTL of multirouted packets if required.
21635 		 * The TTL of such packets is bounded by the
21636 		 * ip_multirt_ttl ndd variable.
21637 		 */
21638 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21639 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21640 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21641 			    "(was %d), dst 0x%08x\n",
21642 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21643 			    ntohl(ire->ire_addr)));
21644 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21645 		}
21646 		/*
21647 		 * At this point, we check to see if there are any pending
21648 		 * unresolved routes. ire_multirt_resolvable()
21649 		 * checks in O(n) that all IRE_OFFSUBNET ire
21650 		 * entries for the packet's destination and
21651 		 * flagged RTF_MULTIRT are currently resolved.
21652 		 * If some remain unresolved, we make a copy
21653 		 * of the current message. It will be used
21654 		 * to initiate additional route resolutions.
21655 		 */
21656 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21657 		    MBLK_GETLABEL(first_mp), ipst);
21658 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21659 		    "multirt_need_resolve %d, first_mp %p\n",
21660 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21661 		if (multirt_need_resolve) {
21662 			copy_mp = copymsg(first_mp);
21663 			if (copy_mp != NULL) {
21664 				MULTIRT_DEBUG_TAG(copy_mp);
21665 			}
21666 		}
21667 	}
21668 
21669 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21670 	/*
21671 	 * Try to resolve another multiroute if
21672 	 * ire_multirt_resolvable() deemed it necessary.
21673 	 * At this point, we need to distinguish
21674 	 * multicasts from other packets. For multicasts,
21675 	 * we call ip_newroute_ipif() and request that both
21676 	 * multirouting and setsrc flags are checked.
21677 	 */
21678 	if (copy_mp != NULL) {
21679 		if (CLASSD(dst)) {
21680 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21681 			if (ipif) {
21682 				ASSERT(infop->ip_opt_ill_index == 0);
21683 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21684 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21685 				ipif_refrele(ipif);
21686 			} else {
21687 				MULTIRT_DEBUG_UNTAG(copy_mp);
21688 				freemsg(copy_mp);
21689 				copy_mp = NULL;
21690 			}
21691 		} else {
21692 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21693 		}
21694 	}
21695 	if (attach_ill != NULL)
21696 		ill_refrele(attach_ill);
21697 	if (xmit_ill != NULL)
21698 		ill_refrele(xmit_ill);
21699 	if (need_decref)
21700 		CONN_DEC_REF(connp);
21701 	return;
21702 
21703 icmp_parameter_problem:
21704 	/* could not have originated externally */
21705 	ASSERT(mp->b_prev == NULL);
21706 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21707 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21708 		/* it's the IP header length that's in trouble */
21709 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21710 		first_mp = NULL;
21711 	}
21712 
21713 discard_pkt:
21714 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21715 drop_pkt:
21716 	ip1dbg(("ip_wput: dropped packet\n"));
21717 	if (ire != NULL)
21718 		ire_refrele(ire);
21719 	if (need_decref)
21720 		CONN_DEC_REF(connp);
21721 	freemsg(first_mp);
21722 	if (attach_ill != NULL)
21723 		ill_refrele(attach_ill);
21724 	if (xmit_ill != NULL)
21725 		ill_refrele(xmit_ill);
21726 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21727 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21728 }
21729 
21730 /*
21731  * If this is a conn_t queue, then we pass in the conn. This includes the
21732  * zoneid.
21733  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21734  * in which case we use the global zoneid since those are all part of
21735  * the global zone.
21736  */
21737 void
21738 ip_wput(queue_t *q, mblk_t *mp)
21739 {
21740 	if (CONN_Q(q))
21741 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21742 	else
21743 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21744 }
21745 
21746 /*
21747  *
21748  * The following rules must be observed when accessing any ipif or ill
21749  * that has been cached in the conn. Typically conn_nofailover_ill,
21750  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21751  *
21752  * Access: The ipif or ill pointed to from the conn can be accessed under
21753  * the protection of the conn_lock or after it has been refheld under the
21754  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21755  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21756  * The reason for this is that a concurrent unplumb could actually be
21757  * cleaning up these cached pointers by walking the conns and might have
21758  * finished cleaning up the conn in question. The macros check that an
21759  * unplumb has not yet started on the ipif or ill.
21760  *
21761  * Caching: An ipif or ill pointer may be cached in the conn only after
21762  * making sure that an unplumb has not started. So the caching is done
21763  * while holding both the conn_lock and the ill_lock and after using the
21764  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21765  * flag before starting the cleanup of conns.
21766  *
21767  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21768  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21769  * or a reference to the ipif or a reference to an ire that references the
21770  * ipif. An ipif does not change its ill except for failover/failback. Since
21771  * failover/failback happens only after bringing down the ipif and making sure
21772  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21773  * the above holds.
21774  */
21775 ipif_t *
21776 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21777 {
21778 	ipif_t	*ipif;
21779 	ill_t	*ill;
21780 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21781 
21782 	*err = 0;
21783 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21784 	mutex_enter(&connp->conn_lock);
21785 	ipif = *ipifp;
21786 	if (ipif != NULL) {
21787 		ill = ipif->ipif_ill;
21788 		mutex_enter(&ill->ill_lock);
21789 		if (IPIF_CAN_LOOKUP(ipif)) {
21790 			ipif_refhold_locked(ipif);
21791 			mutex_exit(&ill->ill_lock);
21792 			mutex_exit(&connp->conn_lock);
21793 			rw_exit(&ipst->ips_ill_g_lock);
21794 			return (ipif);
21795 		} else {
21796 			*err = IPIF_LOOKUP_FAILED;
21797 		}
21798 		mutex_exit(&ill->ill_lock);
21799 	}
21800 	mutex_exit(&connp->conn_lock);
21801 	rw_exit(&ipst->ips_ill_g_lock);
21802 	return (NULL);
21803 }
21804 
21805 ill_t *
21806 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21807 {
21808 	ill_t	*ill;
21809 
21810 	*err = 0;
21811 	mutex_enter(&connp->conn_lock);
21812 	ill = *illp;
21813 	if (ill != NULL) {
21814 		mutex_enter(&ill->ill_lock);
21815 		if (ILL_CAN_LOOKUP(ill)) {
21816 			ill_refhold_locked(ill);
21817 			mutex_exit(&ill->ill_lock);
21818 			mutex_exit(&connp->conn_lock);
21819 			return (ill);
21820 		} else {
21821 			*err = ILL_LOOKUP_FAILED;
21822 		}
21823 		mutex_exit(&ill->ill_lock);
21824 	}
21825 	mutex_exit(&connp->conn_lock);
21826 	return (NULL);
21827 }
21828 
21829 static int
21830 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21831 {
21832 	ill_t	*ill;
21833 
21834 	ill = ipif->ipif_ill;
21835 	mutex_enter(&connp->conn_lock);
21836 	mutex_enter(&ill->ill_lock);
21837 	if (IPIF_CAN_LOOKUP(ipif)) {
21838 		*ipifp = ipif;
21839 		mutex_exit(&ill->ill_lock);
21840 		mutex_exit(&connp->conn_lock);
21841 		return (0);
21842 	}
21843 	mutex_exit(&ill->ill_lock);
21844 	mutex_exit(&connp->conn_lock);
21845 	return (IPIF_LOOKUP_FAILED);
21846 }
21847 
21848 /*
21849  * This is called if the outbound datagram needs fragmentation.
21850  *
21851  * NOTE : This function does not ire_refrele the ire argument passed in.
21852  */
21853 static void
21854 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21855     ip_stack_t *ipst)
21856 {
21857 	ipha_t		*ipha;
21858 	mblk_t		*mp;
21859 	uint32_t	v_hlen_tos_len;
21860 	uint32_t	max_frag;
21861 	uint32_t	frag_flag;
21862 	boolean_t	dont_use;
21863 
21864 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21865 		mp = ipsec_mp->b_cont;
21866 	} else {
21867 		mp = ipsec_mp;
21868 	}
21869 
21870 	ipha = (ipha_t *)mp->b_rptr;
21871 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21872 
21873 #ifdef	_BIG_ENDIAN
21874 #define	V_HLEN	(v_hlen_tos_len >> 24)
21875 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21876 #else
21877 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21878 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21879 #endif
21880 
21881 #ifndef SPEED_BEFORE_SAFETY
21882 	/*
21883 	 * Check that ipha_length is consistent with
21884 	 * the mblk length
21885 	 */
21886 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21887 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21888 		    LENGTH, msgdsize(mp)));
21889 		freemsg(ipsec_mp);
21890 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21891 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21892 		    "packet length mismatch");
21893 		return;
21894 	}
21895 #endif
21896 	/*
21897 	 * Don't use frag_flag if pre-built packet or source
21898 	 * routed or if multicast (since multicast packets do not solicit
21899 	 * ICMP "packet too big" messages). Get the values of
21900 	 * max_frag and frag_flag atomically by acquiring the
21901 	 * ire_lock.
21902 	 */
21903 	mutex_enter(&ire->ire_lock);
21904 	max_frag = ire->ire_max_frag;
21905 	frag_flag = ire->ire_frag_flag;
21906 	mutex_exit(&ire->ire_lock);
21907 
21908 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21909 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21910 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21911 
21912 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21913 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21914 }
21915 
21916 /*
21917  * Used for deciding the MSS size for the upper layer. Thus
21918  * we need to check the outbound policy values in the conn.
21919  */
21920 int
21921 conn_ipsec_length(conn_t *connp)
21922 {
21923 	ipsec_latch_t *ipl;
21924 
21925 	ipl = connp->conn_latch;
21926 	if (ipl == NULL)
21927 		return (0);
21928 
21929 	if (ipl->ipl_out_policy == NULL)
21930 		return (0);
21931 
21932 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21933 }
21934 
21935 /*
21936  * Returns an estimate of the IPSEC headers size. This is used if
21937  * we don't want to call into IPSEC to get the exact size.
21938  */
21939 int
21940 ipsec_out_extra_length(mblk_t *ipsec_mp)
21941 {
21942 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21943 	ipsec_action_t *a;
21944 
21945 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21946 	if (!io->ipsec_out_secure)
21947 		return (0);
21948 
21949 	a = io->ipsec_out_act;
21950 
21951 	if (a == NULL) {
21952 		ASSERT(io->ipsec_out_policy != NULL);
21953 		a = io->ipsec_out_policy->ipsp_act;
21954 	}
21955 	ASSERT(a != NULL);
21956 
21957 	return (a->ipa_ovhd);
21958 }
21959 
21960 /*
21961  * Returns an estimate of the IPSEC headers size. This is used if
21962  * we don't want to call into IPSEC to get the exact size.
21963  */
21964 int
21965 ipsec_in_extra_length(mblk_t *ipsec_mp)
21966 {
21967 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21968 	ipsec_action_t *a;
21969 
21970 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21971 
21972 	a = ii->ipsec_in_action;
21973 	return (a == NULL ? 0 : a->ipa_ovhd);
21974 }
21975 
21976 /*
21977  * If there are any source route options, return the true final
21978  * destination. Otherwise, return the destination.
21979  */
21980 ipaddr_t
21981 ip_get_dst(ipha_t *ipha)
21982 {
21983 	ipoptp_t	opts;
21984 	uchar_t		*opt;
21985 	uint8_t		optval;
21986 	uint8_t		optlen;
21987 	ipaddr_t	dst;
21988 	uint32_t off;
21989 
21990 	dst = ipha->ipha_dst;
21991 
21992 	if (IS_SIMPLE_IPH(ipha))
21993 		return (dst);
21994 
21995 	for (optval = ipoptp_first(&opts, ipha);
21996 	    optval != IPOPT_EOL;
21997 	    optval = ipoptp_next(&opts)) {
21998 		opt = opts.ipoptp_cur;
21999 		optlen = opts.ipoptp_len;
22000 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22001 		switch (optval) {
22002 		case IPOPT_SSRR:
22003 		case IPOPT_LSRR:
22004 			off = opt[IPOPT_OFFSET];
22005 			/*
22006 			 * If one of the conditions is true, it means
22007 			 * end of options and dst already has the right
22008 			 * value.
22009 			 */
22010 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22011 				off = optlen - IP_ADDR_LEN;
22012 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22013 			}
22014 			return (dst);
22015 		default:
22016 			break;
22017 		}
22018 	}
22019 
22020 	return (dst);
22021 }
22022 
22023 mblk_t *
22024 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22025     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22026 {
22027 	ipsec_out_t	*io;
22028 	mblk_t		*first_mp;
22029 	boolean_t policy_present;
22030 	ip_stack_t	*ipst;
22031 	ipsec_stack_t	*ipss;
22032 
22033 	ASSERT(ire != NULL);
22034 	ipst = ire->ire_ipst;
22035 	ipss = ipst->ips_netstack->netstack_ipsec;
22036 
22037 	first_mp = mp;
22038 	if (mp->b_datap->db_type == M_CTL) {
22039 		io = (ipsec_out_t *)first_mp->b_rptr;
22040 		/*
22041 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22042 		 *
22043 		 * 1) There is per-socket policy (including cached global
22044 		 *    policy) or a policy on the IP-in-IP tunnel.
22045 		 * 2) There is no per-socket policy, but it is
22046 		 *    a multicast packet that needs to go out
22047 		 *    on a specific interface. This is the case
22048 		 *    where (ip_wput and ip_wput_multicast) attaches
22049 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22050 		 *
22051 		 * In case (2) we check with global policy to
22052 		 * see if there is a match and set the ill_index
22053 		 * appropriately so that we can lookup the ire
22054 		 * properly in ip_wput_ipsec_out.
22055 		 */
22056 
22057 		/*
22058 		 * ipsec_out_use_global_policy is set to B_FALSE
22059 		 * in ipsec_in_to_out(). Refer to that function for
22060 		 * details.
22061 		 */
22062 		if ((io->ipsec_out_latch == NULL) &&
22063 		    (io->ipsec_out_use_global_policy)) {
22064 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22065 			    ire, connp, unspec_src, zoneid));
22066 		}
22067 		if (!io->ipsec_out_secure) {
22068 			/*
22069 			 * If this is not a secure packet, drop
22070 			 * the IPSEC_OUT mp and treat it as a clear
22071 			 * packet. This happens when we are sending
22072 			 * a ICMP reply back to a clear packet. See
22073 			 * ipsec_in_to_out() for details.
22074 			 */
22075 			mp = first_mp->b_cont;
22076 			freeb(first_mp);
22077 		}
22078 		return (mp);
22079 	}
22080 	/*
22081 	 * See whether we need to attach a global policy here. We
22082 	 * don't depend on the conn (as it could be null) for deciding
22083 	 * what policy this datagram should go through because it
22084 	 * should have happened in ip_wput if there was some
22085 	 * policy. This normally happens for connections which are not
22086 	 * fully bound preventing us from caching policies in
22087 	 * ip_bind. Packets coming from the TCP listener/global queue
22088 	 * - which are non-hard_bound - could also be affected by
22089 	 * applying policy here.
22090 	 *
22091 	 * If this packet is coming from tcp global queue or listener,
22092 	 * we will be applying policy here.  This may not be *right*
22093 	 * if these packets are coming from the detached connection as
22094 	 * it could have gone in clear before. This happens only if a
22095 	 * TCP connection started when there is no policy and somebody
22096 	 * added policy before it became detached. Thus packets of the
22097 	 * detached connection could go out secure and the other end
22098 	 * would drop it because it will be expecting in clear. The
22099 	 * converse is not true i.e if somebody starts a TCP
22100 	 * connection and deletes the policy, all the packets will
22101 	 * still go out with the policy that existed before deleting
22102 	 * because ip_unbind sends up policy information which is used
22103 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22104 	 * TCP to attach a dummy IPSEC_OUT and set
22105 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22106 	 * affect performance for normal cases, we are not doing it.
22107 	 * Thus, set policy before starting any TCP connections.
22108 	 *
22109 	 * NOTE - We might apply policy even for a hard bound connection
22110 	 * - for which we cached policy in ip_bind - if somebody added
22111 	 * global policy after we inherited the policy in ip_bind.
22112 	 * This means that the packets that were going out in clear
22113 	 * previously would start going secure and hence get dropped
22114 	 * on the other side. To fix this, TCP attaches a dummy
22115 	 * ipsec_out and make sure that we don't apply global policy.
22116 	 */
22117 	if (ipha != NULL)
22118 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22119 	else
22120 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22121 	if (!policy_present)
22122 		return (mp);
22123 
22124 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22125 	    zoneid));
22126 }
22127 
22128 ire_t *
22129 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22130 {
22131 	ipaddr_t addr;
22132 	ire_t *save_ire;
22133 	irb_t *irb;
22134 	ill_group_t *illgrp;
22135 	int	err;
22136 
22137 	save_ire = ire;
22138 	addr = ire->ire_addr;
22139 
22140 	ASSERT(ire->ire_type == IRE_BROADCAST);
22141 
22142 	illgrp = connp->conn_outgoing_ill->ill_group;
22143 	if (illgrp == NULL) {
22144 		*conn_outgoing_ill = conn_get_held_ill(connp,
22145 		    &connp->conn_outgoing_ill, &err);
22146 		if (err == ILL_LOOKUP_FAILED) {
22147 			ire_refrele(save_ire);
22148 			return (NULL);
22149 		}
22150 		return (save_ire);
22151 	}
22152 	/*
22153 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22154 	 * If it is part of the group, we need to send on the ire
22155 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22156 	 * to this group. This is okay as IP_BOUND_IF really means
22157 	 * any ill in the group. We depend on the fact that the
22158 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22159 	 * if such an ire exists. This is possible only if you have
22160 	 * at least one ill in the group that has not failed.
22161 	 *
22162 	 * First get to the ire that matches the address and group.
22163 	 *
22164 	 * We don't look for an ire with a matching zoneid because a given zone
22165 	 * won't always have broadcast ires on all ills in the group.
22166 	 */
22167 	irb = ire->ire_bucket;
22168 	rw_enter(&irb->irb_lock, RW_READER);
22169 	if (ire->ire_marks & IRE_MARK_NORECV) {
22170 		/*
22171 		 * If the current zone only has an ire broadcast for this
22172 		 * address marked NORECV, the ire we want is ahead in the
22173 		 * bucket, so we look it up deliberately ignoring the zoneid.
22174 		 */
22175 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22176 			if (ire->ire_addr != addr)
22177 				continue;
22178 			/* skip over deleted ires */
22179 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22180 				continue;
22181 		}
22182 	}
22183 	while (ire != NULL) {
22184 		/*
22185 		 * If a new interface is coming up, we could end up
22186 		 * seeing the loopback ire and the non-loopback ire
22187 		 * may not have been added yet. So check for ire_stq
22188 		 */
22189 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22190 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22191 			break;
22192 		}
22193 		ire = ire->ire_next;
22194 	}
22195 	if (ire != NULL && ire->ire_addr == addr &&
22196 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22197 		IRE_REFHOLD(ire);
22198 		rw_exit(&irb->irb_lock);
22199 		ire_refrele(save_ire);
22200 		*conn_outgoing_ill = ire_to_ill(ire);
22201 		/*
22202 		 * Refhold the ill to make the conn_outgoing_ill
22203 		 * independent of the ire. ip_wput_ire goes in a loop
22204 		 * and may refrele the ire. Since we have an ire at this
22205 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22206 		 */
22207 		ill_refhold(*conn_outgoing_ill);
22208 		return (ire);
22209 	}
22210 	rw_exit(&irb->irb_lock);
22211 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22212 	/*
22213 	 * If we can't find a suitable ire, return the original ire.
22214 	 */
22215 	return (save_ire);
22216 }
22217 
22218 /*
22219  * This function does the ire_refrele of the ire passed in as the
22220  * argument. As this function looks up more ires i.e broadcast ires,
22221  * it needs to REFRELE them. Currently, for simplicity we don't
22222  * differentiate the one passed in and looked up here. We always
22223  * REFRELE.
22224  * IPQoS Notes:
22225  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22226  * IPSec packets are done in ipsec_out_process.
22227  *
22228  */
22229 void
22230 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22231     zoneid_t zoneid)
22232 {
22233 	ipha_t		*ipha;
22234 #define	rptr	((uchar_t *)ipha)
22235 	queue_t		*stq;
22236 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22237 	uint32_t	v_hlen_tos_len;
22238 	uint32_t	ttl_protocol;
22239 	ipaddr_t	src;
22240 	ipaddr_t	dst;
22241 	uint32_t	cksum;
22242 	ipaddr_t	orig_src;
22243 	ire_t		*ire1;
22244 	mblk_t		*next_mp;
22245 	uint_t		hlen;
22246 	uint16_t	*up;
22247 	uint32_t	max_frag = ire->ire_max_frag;
22248 	ill_t		*ill = ire_to_ill(ire);
22249 	int		clusterwide;
22250 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22251 	int		ipsec_len;
22252 	mblk_t		*first_mp;
22253 	ipsec_out_t	*io;
22254 	boolean_t	conn_dontroute;		/* conn value for multicast */
22255 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22256 	boolean_t	multicast_forward;	/* Should we forward ? */
22257 	boolean_t	unspec_src;
22258 	ill_t		*conn_outgoing_ill = NULL;
22259 	ill_t		*ire_ill;
22260 	ill_t		*ire1_ill;
22261 	ill_t		*out_ill;
22262 	uint32_t 	ill_index = 0;
22263 	boolean_t	multirt_send = B_FALSE;
22264 	int		err;
22265 	ipxmit_state_t	pktxmit_state;
22266 	ip_stack_t	*ipst = ire->ire_ipst;
22267 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22268 
22269 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22270 	    "ip_wput_ire_start: q %p", q);
22271 
22272 	multicast_forward = B_FALSE;
22273 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22274 
22275 	if (ire->ire_flags & RTF_MULTIRT) {
22276 		/*
22277 		 * Multirouting case. The bucket where ire is stored
22278 		 * probably holds other RTF_MULTIRT flagged ire
22279 		 * to the destination. In this call to ip_wput_ire,
22280 		 * we attempt to send the packet through all
22281 		 * those ires. Thus, we first ensure that ire is the
22282 		 * first RTF_MULTIRT ire in the bucket,
22283 		 * before walking the ire list.
22284 		 */
22285 		ire_t *first_ire;
22286 		irb_t *irb = ire->ire_bucket;
22287 		ASSERT(irb != NULL);
22288 
22289 		/* Make sure we do not omit any multiroute ire. */
22290 		IRB_REFHOLD(irb);
22291 		for (first_ire = irb->irb_ire;
22292 		    first_ire != NULL;
22293 		    first_ire = first_ire->ire_next) {
22294 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22295 			    (first_ire->ire_addr == ire->ire_addr) &&
22296 			    !(first_ire->ire_marks &
22297 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22298 				break;
22299 			}
22300 		}
22301 
22302 		if ((first_ire != NULL) && (first_ire != ire)) {
22303 			IRE_REFHOLD(first_ire);
22304 			ire_refrele(ire);
22305 			ire = first_ire;
22306 			ill = ire_to_ill(ire);
22307 		}
22308 		IRB_REFRELE(irb);
22309 	}
22310 
22311 	/*
22312 	 * conn_outgoing_ill is used only in the broadcast loop.
22313 	 * for performance we don't grab the mutexs in the fastpath
22314 	 */
22315 	if ((connp != NULL) &&
22316 	    (connp->conn_xmit_if_ill == NULL) &&
22317 	    (ire->ire_type == IRE_BROADCAST) &&
22318 	    ((connp->conn_nofailover_ill != NULL) ||
22319 	    (connp->conn_outgoing_ill != NULL))) {
22320 		/*
22321 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22322 		 * option. So, see if this endpoint is bound to a
22323 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22324 		 * that if the interface is failed, we will still send
22325 		 * the packet on the same ill which is what we want.
22326 		 */
22327 		conn_outgoing_ill = conn_get_held_ill(connp,
22328 		    &connp->conn_nofailover_ill, &err);
22329 		if (err == ILL_LOOKUP_FAILED) {
22330 			ire_refrele(ire);
22331 			freemsg(mp);
22332 			return;
22333 		}
22334 		if (conn_outgoing_ill == NULL) {
22335 			/*
22336 			 * Choose a good ill in the group to send the
22337 			 * packets on.
22338 			 */
22339 			ire = conn_set_outgoing_ill(connp, ire,
22340 			    &conn_outgoing_ill);
22341 			if (ire == NULL) {
22342 				freemsg(mp);
22343 				return;
22344 			}
22345 		}
22346 	}
22347 
22348 	if (mp->b_datap->db_type != M_CTL) {
22349 		ipha = (ipha_t *)mp->b_rptr;
22350 	} else {
22351 		io = (ipsec_out_t *)mp->b_rptr;
22352 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22353 		ASSERT(zoneid == io->ipsec_out_zoneid);
22354 		ASSERT(zoneid != ALL_ZONES);
22355 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22356 		dst = ipha->ipha_dst;
22357 		/*
22358 		 * For the multicast case, ipsec_out carries conn_dontroute and
22359 		 * conn_multicast_loop as conn may not be available here. We
22360 		 * need this for multicast loopback and forwarding which is done
22361 		 * later in the code.
22362 		 */
22363 		if (CLASSD(dst)) {
22364 			conn_dontroute = io->ipsec_out_dontroute;
22365 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22366 			/*
22367 			 * If conn_dontroute is not set or conn_multicast_loop
22368 			 * is set, we need to do forwarding/loopback. For
22369 			 * datagrams from ip_wput_multicast, conn_dontroute is
22370 			 * set to B_TRUE and conn_multicast_loop is set to
22371 			 * B_FALSE so that we neither do forwarding nor
22372 			 * loopback.
22373 			 */
22374 			if (!conn_dontroute || conn_multicast_loop)
22375 				multicast_forward = B_TRUE;
22376 		}
22377 	}
22378 
22379 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22380 	    ire->ire_zoneid != ALL_ZONES) {
22381 		/*
22382 		 * When a zone sends a packet to another zone, we try to deliver
22383 		 * the packet under the same conditions as if the destination
22384 		 * was a real node on the network. To do so, we look for a
22385 		 * matching route in the forwarding table.
22386 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22387 		 * ip_newroute() does.
22388 		 * Note that IRE_LOCAL are special, since they are used
22389 		 * when the zoneid doesn't match in some cases. This means that
22390 		 * we need to handle ipha_src differently since ire_src_addr
22391 		 * belongs to the receiving zone instead of the sending zone.
22392 		 * When ip_restrict_interzone_loopback is set, then
22393 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22394 		 * for loopback between zones when the logical "Ethernet" would
22395 		 * have looped them back.
22396 		 */
22397 		ire_t *src_ire;
22398 
22399 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22400 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22401 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22402 		if (src_ire != NULL &&
22403 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22404 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22405 		    ire_local_same_ill_group(ire, src_ire))) {
22406 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22407 				ipha->ipha_src = src_ire->ire_src_addr;
22408 			ire_refrele(src_ire);
22409 		} else {
22410 			ire_refrele(ire);
22411 			if (conn_outgoing_ill != NULL)
22412 				ill_refrele(conn_outgoing_ill);
22413 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22414 			if (src_ire != NULL) {
22415 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22416 					ire_refrele(src_ire);
22417 					freemsg(mp);
22418 					return;
22419 				}
22420 				ire_refrele(src_ire);
22421 			}
22422 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22423 				/* Failed */
22424 				freemsg(mp);
22425 				return;
22426 			}
22427 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22428 			    ipst);
22429 			return;
22430 		}
22431 	}
22432 
22433 	if (mp->b_datap->db_type == M_CTL ||
22434 	    ipss->ipsec_outbound_v4_policy_present) {
22435 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22436 		    unspec_src, zoneid);
22437 		if (mp == NULL) {
22438 			ire_refrele(ire);
22439 			if (conn_outgoing_ill != NULL)
22440 				ill_refrele(conn_outgoing_ill);
22441 			return;
22442 		}
22443 	}
22444 
22445 	first_mp = mp;
22446 	ipsec_len = 0;
22447 
22448 	if (first_mp->b_datap->db_type == M_CTL) {
22449 		io = (ipsec_out_t *)first_mp->b_rptr;
22450 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22451 		mp = first_mp->b_cont;
22452 		ipsec_len = ipsec_out_extra_length(first_mp);
22453 		ASSERT(ipsec_len >= 0);
22454 		/* We already picked up the zoneid from the M_CTL above */
22455 		ASSERT(zoneid == io->ipsec_out_zoneid);
22456 		ASSERT(zoneid != ALL_ZONES);
22457 
22458 		/*
22459 		 * Drop M_CTL here if IPsec processing is not needed.
22460 		 * (Non-IPsec use of M_CTL extracted any information it
22461 		 * needed above).
22462 		 */
22463 		if (ipsec_len == 0) {
22464 			freeb(first_mp);
22465 			first_mp = mp;
22466 		}
22467 	}
22468 
22469 	/*
22470 	 * Fast path for ip_wput_ire
22471 	 */
22472 
22473 	ipha = (ipha_t *)mp->b_rptr;
22474 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22475 	dst = ipha->ipha_dst;
22476 
22477 	/*
22478 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22479 	 * if the socket is a SOCK_RAW type. The transport checksum should
22480 	 * be provided in the pre-built packet, so we don't need to compute it.
22481 	 * Also, other application set flags, like DF, should not be altered.
22482 	 * Other transport MUST pass down zero.
22483 	 */
22484 	ip_hdr_included = ipha->ipha_ident;
22485 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22486 
22487 	if (CLASSD(dst)) {
22488 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22489 		    ntohl(dst),
22490 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22491 		    ntohl(ire->ire_addr)));
22492 	}
22493 
22494 /* Macros to extract header fields from data already in registers */
22495 #ifdef	_BIG_ENDIAN
22496 #define	V_HLEN	(v_hlen_tos_len >> 24)
22497 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22498 #define	PROTO	(ttl_protocol & 0xFF)
22499 #else
22500 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22501 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22502 #define	PROTO	(ttl_protocol >> 8)
22503 #endif
22504 
22505 
22506 	orig_src = src = ipha->ipha_src;
22507 	/* (The loop back to "another" is explained down below.) */
22508 another:;
22509 	/*
22510 	 * Assign an ident value for this packet.  We assign idents on
22511 	 * a per destination basis out of the IRE.  There could be
22512 	 * other threads targeting the same destination, so we have to
22513 	 * arrange for a atomic increment.  Note that we use a 32-bit
22514 	 * atomic add because it has better performance than its
22515 	 * 16-bit sibling.
22516 	 *
22517 	 * If running in cluster mode and if the source address
22518 	 * belongs to a replicated service then vector through
22519 	 * cl_inet_ipident vector to allocate ip identifier
22520 	 * NOTE: This is a contract private interface with the
22521 	 * clustering group.
22522 	 */
22523 	clusterwide = 0;
22524 	if (cl_inet_ipident) {
22525 		ASSERT(cl_inet_isclusterwide);
22526 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22527 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22528 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22529 			    AF_INET, (uint8_t *)(uintptr_t)src,
22530 			    (uint8_t *)(uintptr_t)dst);
22531 			clusterwide = 1;
22532 		}
22533 	}
22534 	if (!clusterwide) {
22535 		ipha->ipha_ident =
22536 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22537 	}
22538 
22539 #ifndef _BIG_ENDIAN
22540 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22541 #endif
22542 
22543 	/*
22544 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22545 	 * This is needed to obey conn_unspec_src when packets go through
22546 	 * ip_newroute + arp.
22547 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22548 	 */
22549 	if (src == INADDR_ANY && !unspec_src) {
22550 		/*
22551 		 * Assign the appropriate source address from the IRE if none
22552 		 * was specified.
22553 		 */
22554 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22555 
22556 		/*
22557 		 * With IP multipathing, broadcast packets are sent on the ire
22558 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22559 		 * the group. However, this ire might not be in the same zone so
22560 		 * we can't always use its source address. We look for a
22561 		 * broadcast ire in the same group and in the right zone.
22562 		 */
22563 		if (ire->ire_type == IRE_BROADCAST &&
22564 		    ire->ire_zoneid != zoneid) {
22565 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22566 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22567 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22568 			if (src_ire != NULL) {
22569 				src = src_ire->ire_src_addr;
22570 				ire_refrele(src_ire);
22571 			} else {
22572 				ire_refrele(ire);
22573 				if (conn_outgoing_ill != NULL)
22574 					ill_refrele(conn_outgoing_ill);
22575 				freemsg(first_mp);
22576 				if (ill != NULL) {
22577 					BUMP_MIB(ill->ill_ip_mib,
22578 					    ipIfStatsOutDiscards);
22579 				} else {
22580 					BUMP_MIB(&ipst->ips_ip_mib,
22581 					    ipIfStatsOutDiscards);
22582 				}
22583 				return;
22584 			}
22585 		} else {
22586 			src = ire->ire_src_addr;
22587 		}
22588 
22589 		if (connp == NULL) {
22590 			ip1dbg(("ip_wput_ire: no connp and no src "
22591 			    "address for dst 0x%x, using src 0x%x\n",
22592 			    ntohl(dst),
22593 			    ntohl(src)));
22594 		}
22595 		ipha->ipha_src = src;
22596 	}
22597 	stq = ire->ire_stq;
22598 
22599 	/*
22600 	 * We only allow ire chains for broadcasts since there will
22601 	 * be multiple IRE_CACHE entries for the same multicast
22602 	 * address (one per ipif).
22603 	 */
22604 	next_mp = NULL;
22605 
22606 	/* broadcast packet */
22607 	if (ire->ire_type == IRE_BROADCAST)
22608 		goto broadcast;
22609 
22610 	/* loopback ? */
22611 	if (stq == NULL)
22612 		goto nullstq;
22613 
22614 	/* The ill_index for outbound ILL */
22615 	ill_index = Q_TO_INDEX(stq);
22616 
22617 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22618 	ttl_protocol = ((uint16_t *)ipha)[4];
22619 
22620 	/* pseudo checksum (do it in parts for IP header checksum) */
22621 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22622 
22623 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22624 		queue_t *dev_q = stq->q_next;
22625 
22626 		/* flow controlled */
22627 		if ((dev_q->q_next || dev_q->q_first) &&
22628 		    !canput(dev_q))
22629 			goto blocked;
22630 		if ((PROTO == IPPROTO_UDP) &&
22631 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22632 			hlen = (V_HLEN & 0xF) << 2;
22633 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22634 			if (*up != 0) {
22635 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22636 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22637 				/* Software checksum? */
22638 				if (DB_CKSUMFLAGS(mp) == 0) {
22639 					IP_STAT(ipst, ip_out_sw_cksum);
22640 					IP_STAT_UPDATE(ipst,
22641 					    ip_udp_out_sw_cksum_bytes,
22642 					    LENGTH - hlen);
22643 				}
22644 			}
22645 		}
22646 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22647 		hlen = (V_HLEN & 0xF) << 2;
22648 		if (PROTO == IPPROTO_TCP) {
22649 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22650 			/*
22651 			 * The packet header is processed once and for all, even
22652 			 * in the multirouting case. We disable hardware
22653 			 * checksum if the packet is multirouted, as it will be
22654 			 * replicated via several interfaces, and not all of
22655 			 * them may have this capability.
22656 			 */
22657 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22658 			    LENGTH, max_frag, ipsec_len, cksum);
22659 			/* Software checksum? */
22660 			if (DB_CKSUMFLAGS(mp) == 0) {
22661 				IP_STAT(ipst, ip_out_sw_cksum);
22662 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22663 				    LENGTH - hlen);
22664 			}
22665 		} else {
22666 			sctp_hdr_t	*sctph;
22667 
22668 			ASSERT(PROTO == IPPROTO_SCTP);
22669 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22670 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22671 			/*
22672 			 * Zero out the checksum field to ensure proper
22673 			 * checksum calculation.
22674 			 */
22675 			sctph->sh_chksum = 0;
22676 #ifdef	DEBUG
22677 			if (!skip_sctp_cksum)
22678 #endif
22679 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22680 		}
22681 	}
22682 
22683 	/*
22684 	 * If this is a multicast packet and originated from ip_wput
22685 	 * we need to do loopback and forwarding checks. If it comes
22686 	 * from ip_wput_multicast, we SHOULD not do this.
22687 	 */
22688 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22689 
22690 	/* checksum */
22691 	cksum += ttl_protocol;
22692 
22693 	/* fragment the packet */
22694 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22695 		goto fragmentit;
22696 	/*
22697 	 * Don't use frag_flag if packet is pre-built or source
22698 	 * routed or if multicast (since multicast packets do
22699 	 * not solicit ICMP "packet too big" messages).
22700 	 */
22701 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22702 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22703 	    !ip_source_route_included(ipha)) &&
22704 	    !CLASSD(ipha->ipha_dst))
22705 		ipha->ipha_fragment_offset_and_flags |=
22706 		    htons(ire->ire_frag_flag);
22707 
22708 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22709 		/* calculate IP header checksum */
22710 		cksum += ipha->ipha_ident;
22711 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22712 		cksum += ipha->ipha_fragment_offset_and_flags;
22713 
22714 		/* IP options present */
22715 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22716 		if (hlen)
22717 			goto checksumoptions;
22718 
22719 		/* calculate hdr checksum */
22720 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22721 		cksum = ~(cksum + (cksum >> 16));
22722 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22723 	}
22724 	if (ipsec_len != 0) {
22725 		/*
22726 		 * We will do the rest of the processing after
22727 		 * we come back from IPSEC in ip_wput_ipsec_out().
22728 		 */
22729 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22730 
22731 		io = (ipsec_out_t *)first_mp->b_rptr;
22732 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22733 		    ill_phyint->phyint_ifindex;
22734 
22735 		ipsec_out_process(q, first_mp, ire, ill_index);
22736 		ire_refrele(ire);
22737 		if (conn_outgoing_ill != NULL)
22738 			ill_refrele(conn_outgoing_ill);
22739 		return;
22740 	}
22741 
22742 	/*
22743 	 * In most cases, the emission loop below is entered only
22744 	 * once. Only in the case where the ire holds the
22745 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22746 	 * flagged ires in the bucket, and send the packet
22747 	 * through all crossed RTF_MULTIRT routes.
22748 	 */
22749 	if (ire->ire_flags & RTF_MULTIRT) {
22750 		multirt_send = B_TRUE;
22751 	}
22752 	do {
22753 		if (multirt_send) {
22754 			irb_t *irb;
22755 			/*
22756 			 * We are in a multiple send case, need to get
22757 			 * the next ire and make a duplicate of the packet.
22758 			 * ire1 holds here the next ire to process in the
22759 			 * bucket. If multirouting is expected,
22760 			 * any non-RTF_MULTIRT ire that has the
22761 			 * right destination address is ignored.
22762 			 */
22763 			irb = ire->ire_bucket;
22764 			ASSERT(irb != NULL);
22765 
22766 			IRB_REFHOLD(irb);
22767 			for (ire1 = ire->ire_next;
22768 			    ire1 != NULL;
22769 			    ire1 = ire1->ire_next) {
22770 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22771 					continue;
22772 				if (ire1->ire_addr != ire->ire_addr)
22773 					continue;
22774 				if (ire1->ire_marks &
22775 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22776 					continue;
22777 
22778 				/* Got one */
22779 				IRE_REFHOLD(ire1);
22780 				break;
22781 			}
22782 			IRB_REFRELE(irb);
22783 
22784 			if (ire1 != NULL) {
22785 				next_mp = copyb(mp);
22786 				if ((next_mp == NULL) ||
22787 				    ((mp->b_cont != NULL) &&
22788 				    ((next_mp->b_cont =
22789 				    dupmsg(mp->b_cont)) == NULL))) {
22790 					freemsg(next_mp);
22791 					next_mp = NULL;
22792 					ire_refrele(ire1);
22793 					ire1 = NULL;
22794 				}
22795 			}
22796 
22797 			/* Last multiroute ire; don't loop anymore. */
22798 			if (ire1 == NULL) {
22799 				multirt_send = B_FALSE;
22800 			}
22801 		}
22802 
22803 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22804 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22805 		    mblk_t *, mp);
22806 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22807 		    ipst->ips_ipv4firewall_physical_out,
22808 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22809 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22810 		if (mp == NULL)
22811 			goto release_ire_and_ill;
22812 
22813 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22814 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22815 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22816 		if ((pktxmit_state == SEND_FAILED) ||
22817 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22818 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22819 			    "- packet dropped\n"));
22820 release_ire_and_ill:
22821 			ire_refrele(ire);
22822 			if (next_mp != NULL) {
22823 				freemsg(next_mp);
22824 				ire_refrele(ire1);
22825 			}
22826 			if (conn_outgoing_ill != NULL)
22827 				ill_refrele(conn_outgoing_ill);
22828 			return;
22829 		}
22830 
22831 		if (CLASSD(dst)) {
22832 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22833 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22834 			    LENGTH);
22835 		}
22836 
22837 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22838 		    "ip_wput_ire_end: q %p (%S)",
22839 		    q, "last copy out");
22840 		IRE_REFRELE(ire);
22841 
22842 		if (multirt_send) {
22843 			ASSERT(ire1);
22844 			/*
22845 			 * Proceed with the next RTF_MULTIRT ire,
22846 			 * Also set up the send-to queue accordingly.
22847 			 */
22848 			ire = ire1;
22849 			ire1 = NULL;
22850 			stq = ire->ire_stq;
22851 			mp = next_mp;
22852 			next_mp = NULL;
22853 			ipha = (ipha_t *)mp->b_rptr;
22854 			ill_index = Q_TO_INDEX(stq);
22855 			ill = (ill_t *)stq->q_ptr;
22856 		}
22857 	} while (multirt_send);
22858 	if (conn_outgoing_ill != NULL)
22859 		ill_refrele(conn_outgoing_ill);
22860 	return;
22861 
22862 	/*
22863 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22864 	 */
22865 broadcast:
22866 	{
22867 		/*
22868 		 * Avoid broadcast storms by setting the ttl to 1
22869 		 * for broadcasts. This parameter can be set
22870 		 * via ndd, so make sure that for the SO_DONTROUTE
22871 		 * case that ipha_ttl is always set to 1.
22872 		 * In the event that we are replying to incoming
22873 		 * ICMP packets, conn could be NULL.
22874 		 */
22875 		if ((connp != NULL) && connp->conn_dontroute)
22876 			ipha->ipha_ttl = 1;
22877 		else
22878 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22879 
22880 		/*
22881 		 * Note that we are not doing a IRB_REFHOLD here.
22882 		 * Actually we don't care if the list changes i.e
22883 		 * if somebody deletes an IRE from the list while
22884 		 * we drop the lock, the next time we come around
22885 		 * ire_next will be NULL and hence we won't send
22886 		 * out multiple copies which is fine.
22887 		 */
22888 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22889 		ire1 = ire->ire_next;
22890 		if (conn_outgoing_ill != NULL) {
22891 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22892 				ASSERT(ire1 == ire->ire_next);
22893 				if (ire1 != NULL && ire1->ire_addr == dst) {
22894 					ire_refrele(ire);
22895 					ire = ire1;
22896 					IRE_REFHOLD(ire);
22897 					ire1 = ire->ire_next;
22898 					continue;
22899 				}
22900 				rw_exit(&ire->ire_bucket->irb_lock);
22901 				/* Did not find a matching ill */
22902 				ip1dbg(("ip_wput_ire: broadcast with no "
22903 				    "matching IP_BOUND_IF ill %s\n",
22904 				    conn_outgoing_ill->ill_name));
22905 				freemsg(first_mp);
22906 				if (ire != NULL)
22907 					ire_refrele(ire);
22908 				ill_refrele(conn_outgoing_ill);
22909 				return;
22910 			}
22911 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22912 			/*
22913 			 * If the next IRE has the same address and is not one
22914 			 * of the two copies that we need to send, try to see
22915 			 * whether this copy should be sent at all. This
22916 			 * assumes that we insert loopbacks first and then
22917 			 * non-loopbacks. This is acheived by inserting the
22918 			 * loopback always before non-loopback.
22919 			 * This is used to send a single copy of a broadcast
22920 			 * packet out all physical interfaces that have an
22921 			 * matching IRE_BROADCAST while also looping
22922 			 * back one copy (to ip_wput_local) for each
22923 			 * matching physical interface. However, we avoid
22924 			 * sending packets out different logical that match by
22925 			 * having ipif_up/ipif_down supress duplicate
22926 			 * IRE_BROADCASTS.
22927 			 *
22928 			 * This feature is currently used to get broadcasts
22929 			 * sent to multiple interfaces, when the broadcast
22930 			 * address being used applies to multiple interfaces.
22931 			 * For example, a whole net broadcast will be
22932 			 * replicated on every connected subnet of
22933 			 * the target net.
22934 			 *
22935 			 * Each zone has its own set of IRE_BROADCASTs, so that
22936 			 * we're able to distribute inbound packets to multiple
22937 			 * zones who share a broadcast address. We avoid looping
22938 			 * back outbound packets in different zones but on the
22939 			 * same ill, as the application would see duplicates.
22940 			 *
22941 			 * If the interfaces are part of the same group,
22942 			 * we would want to send only one copy out for
22943 			 * whole group.
22944 			 *
22945 			 * This logic assumes that ire_add_v4() groups the
22946 			 * IRE_BROADCAST entries so that those with the same
22947 			 * ire_addr and ill_group are kept together.
22948 			 */
22949 			ire_ill = ire->ire_ipif->ipif_ill;
22950 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22951 				if (ire_ill->ill_group != NULL &&
22952 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22953 					/*
22954 					 * If the current zone only has an ire
22955 					 * broadcast for this address marked
22956 					 * NORECV, the ire we want is ahead in
22957 					 * the bucket, so we look it up
22958 					 * deliberately ignoring the zoneid.
22959 					 */
22960 					for (ire1 = ire->ire_bucket->irb_ire;
22961 					    ire1 != NULL;
22962 					    ire1 = ire1->ire_next) {
22963 						ire1_ill =
22964 						    ire1->ire_ipif->ipif_ill;
22965 						if (ire1->ire_addr != dst)
22966 							continue;
22967 						/* skip over the current ire */
22968 						if (ire1 == ire)
22969 							continue;
22970 						/* skip over deleted ires */
22971 						if (ire1->ire_marks &
22972 						    IRE_MARK_CONDEMNED)
22973 							continue;
22974 						/*
22975 						 * non-loopback ire in our
22976 						 * group: use it for the next
22977 						 * pass in the loop
22978 						 */
22979 						if (ire1->ire_stq != NULL &&
22980 						    ire1_ill->ill_group ==
22981 						    ire_ill->ill_group)
22982 							break;
22983 					}
22984 				}
22985 			} else {
22986 				while (ire1 != NULL && ire1->ire_addr == dst) {
22987 					ire1_ill = ire1->ire_ipif->ipif_ill;
22988 					/*
22989 					 * We can have two broadcast ires on the
22990 					 * same ill in different zones; here
22991 					 * we'll send a copy of the packet on
22992 					 * each ill and the fanout code will
22993 					 * call conn_wantpacket() to check that
22994 					 * the zone has the broadcast address
22995 					 * configured on the ill. If the two
22996 					 * ires are in the same group we only
22997 					 * send one copy up.
22998 					 */
22999 					if (ire1_ill != ire_ill &&
23000 					    (ire1_ill->ill_group == NULL ||
23001 					    ire_ill->ill_group == NULL ||
23002 					    ire1_ill->ill_group !=
23003 					    ire_ill->ill_group)) {
23004 						break;
23005 					}
23006 					ire1 = ire1->ire_next;
23007 				}
23008 			}
23009 		}
23010 		ASSERT(multirt_send == B_FALSE);
23011 		if (ire1 != NULL && ire1->ire_addr == dst) {
23012 			if ((ire->ire_flags & RTF_MULTIRT) &&
23013 			    (ire1->ire_flags & RTF_MULTIRT)) {
23014 				/*
23015 				 * We are in the multirouting case.
23016 				 * The message must be sent at least
23017 				 * on both ires. These ires have been
23018 				 * inserted AFTER the standard ones
23019 				 * in ip_rt_add(). There are thus no
23020 				 * other ire entries for the destination
23021 				 * address in the rest of the bucket
23022 				 * that do not have the RTF_MULTIRT
23023 				 * flag. We don't process a copy
23024 				 * of the message here. This will be
23025 				 * done in the final sending loop.
23026 				 */
23027 				multirt_send = B_TRUE;
23028 			} else {
23029 				next_mp = ip_copymsg(first_mp);
23030 				if (next_mp != NULL)
23031 					IRE_REFHOLD(ire1);
23032 			}
23033 		}
23034 		rw_exit(&ire->ire_bucket->irb_lock);
23035 	}
23036 
23037 	if (stq) {
23038 		/*
23039 		 * A non-NULL send-to queue means this packet is going
23040 		 * out of this machine.
23041 		 */
23042 		out_ill = (ill_t *)stq->q_ptr;
23043 
23044 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23045 		ttl_protocol = ((uint16_t *)ipha)[4];
23046 		/*
23047 		 * We accumulate the pseudo header checksum in cksum.
23048 		 * This is pretty hairy code, so watch close.  One
23049 		 * thing to keep in mind is that UDP and TCP have
23050 		 * stored their respective datagram lengths in their
23051 		 * checksum fields.  This lines things up real nice.
23052 		 */
23053 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23054 		    (src >> 16) + (src & 0xFFFF);
23055 		/*
23056 		 * We assume the udp checksum field contains the
23057 		 * length, so to compute the pseudo header checksum,
23058 		 * all we need is the protocol number and src/dst.
23059 		 */
23060 		/* Provide the checksums for UDP and TCP. */
23061 		if ((PROTO == IPPROTO_TCP) &&
23062 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23063 			/* hlen gets the number of uchar_ts in the IP header */
23064 			hlen = (V_HLEN & 0xF) << 2;
23065 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23066 			IP_STAT(ipst, ip_out_sw_cksum);
23067 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23068 			    LENGTH - hlen);
23069 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23070 		} else if (PROTO == IPPROTO_SCTP &&
23071 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23072 			sctp_hdr_t	*sctph;
23073 
23074 			hlen = (V_HLEN & 0xF) << 2;
23075 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23076 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23077 			sctph->sh_chksum = 0;
23078 #ifdef	DEBUG
23079 			if (!skip_sctp_cksum)
23080 #endif
23081 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23082 		} else {
23083 			queue_t *dev_q = stq->q_next;
23084 
23085 			if ((dev_q->q_next || dev_q->q_first) &&
23086 			    !canput(dev_q)) {
23087 blocked:
23088 				ipha->ipha_ident = ip_hdr_included;
23089 				/*
23090 				 * If we don't have a conn to apply
23091 				 * backpressure, free the message.
23092 				 * In the ire_send path, we don't know
23093 				 * the position to requeue the packet. Rather
23094 				 * than reorder packets, we just drop this
23095 				 * packet.
23096 				 */
23097 				if (ipst->ips_ip_output_queue &&
23098 				    connp != NULL &&
23099 				    caller != IRE_SEND) {
23100 					if (caller == IP_WSRV) {
23101 						connp->conn_did_putbq = 1;
23102 						(void) putbq(connp->conn_wq,
23103 						    first_mp);
23104 						conn_drain_insert(connp);
23105 						/*
23106 						 * This is the service thread,
23107 						 * and the queue is already
23108 						 * noenabled. The check for
23109 						 * canput and the putbq is not
23110 						 * atomic. So we need to check
23111 						 * again.
23112 						 */
23113 						if (canput(stq->q_next))
23114 							connp->conn_did_putbq
23115 							    = 0;
23116 						IP_STAT(ipst, ip_conn_flputbq);
23117 					} else {
23118 						/*
23119 						 * We are not the service proc.
23120 						 * ip_wsrv will be scheduled or
23121 						 * is already running.
23122 						 */
23123 						(void) putq(connp->conn_wq,
23124 						    first_mp);
23125 					}
23126 				} else {
23127 					out_ill = (ill_t *)stq->q_ptr;
23128 					BUMP_MIB(out_ill->ill_ip_mib,
23129 					    ipIfStatsOutDiscards);
23130 					freemsg(first_mp);
23131 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23132 					    "ip_wput_ire_end: q %p (%S)",
23133 					    q, "discard");
23134 				}
23135 				ire_refrele(ire);
23136 				if (next_mp) {
23137 					ire_refrele(ire1);
23138 					freemsg(next_mp);
23139 				}
23140 				if (conn_outgoing_ill != NULL)
23141 					ill_refrele(conn_outgoing_ill);
23142 				return;
23143 			}
23144 			if ((PROTO == IPPROTO_UDP) &&
23145 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23146 				/*
23147 				 * hlen gets the number of uchar_ts in the
23148 				 * IP header
23149 				 */
23150 				hlen = (V_HLEN & 0xF) << 2;
23151 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23152 				max_frag = ire->ire_max_frag;
23153 				if (*up != 0) {
23154 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23155 					    up, PROTO, hlen, LENGTH, max_frag,
23156 					    ipsec_len, cksum);
23157 					/* Software checksum? */
23158 					if (DB_CKSUMFLAGS(mp) == 0) {
23159 						IP_STAT(ipst, ip_out_sw_cksum);
23160 						IP_STAT_UPDATE(ipst,
23161 						    ip_udp_out_sw_cksum_bytes,
23162 						    LENGTH - hlen);
23163 					}
23164 				}
23165 			}
23166 		}
23167 		/*
23168 		 * Need to do this even when fragmenting. The local
23169 		 * loopback can be done without computing checksums
23170 		 * but forwarding out other interface must be done
23171 		 * after the IP checksum (and ULP checksums) have been
23172 		 * computed.
23173 		 *
23174 		 * NOTE : multicast_forward is set only if this packet
23175 		 * originated from ip_wput. For packets originating from
23176 		 * ip_wput_multicast, it is not set.
23177 		 */
23178 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23179 multi_loopback:
23180 			ip2dbg(("ip_wput: multicast, loop %d\n",
23181 			    conn_multicast_loop));
23182 
23183 			/*  Forget header checksum offload */
23184 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23185 
23186 			/*
23187 			 * Local loopback of multicasts?  Check the
23188 			 * ill.
23189 			 *
23190 			 * Note that the loopback function will not come
23191 			 * in through ip_rput - it will only do the
23192 			 * client fanout thus we need to do an mforward
23193 			 * as well.  The is different from the BSD
23194 			 * logic.
23195 			 */
23196 			if (ill != NULL) {
23197 				ilm_t	*ilm;
23198 
23199 				ILM_WALKER_HOLD(ill);
23200 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23201 				    ALL_ZONES);
23202 				ILM_WALKER_RELE(ill);
23203 				if (ilm != NULL) {
23204 					/*
23205 					 * Pass along the virtual output q.
23206 					 * ip_wput_local() will distribute the
23207 					 * packet to all the matching zones,
23208 					 * except the sending zone when
23209 					 * IP_MULTICAST_LOOP is false.
23210 					 */
23211 					ip_multicast_loopback(q, ill, first_mp,
23212 					    conn_multicast_loop ? 0 :
23213 					    IP_FF_NO_MCAST_LOOP, zoneid);
23214 				}
23215 			}
23216 			if (ipha->ipha_ttl == 0) {
23217 				/*
23218 				 * 0 => only to this host i.e. we are
23219 				 * done. We are also done if this was the
23220 				 * loopback interface since it is sufficient
23221 				 * to loopback one copy of a multicast packet.
23222 				 */
23223 				freemsg(first_mp);
23224 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23225 				    "ip_wput_ire_end: q %p (%S)",
23226 				    q, "loopback");
23227 				ire_refrele(ire);
23228 				if (conn_outgoing_ill != NULL)
23229 					ill_refrele(conn_outgoing_ill);
23230 				return;
23231 			}
23232 			/*
23233 			 * ILLF_MULTICAST is checked in ip_newroute
23234 			 * i.e. we don't need to check it here since
23235 			 * all IRE_CACHEs come from ip_newroute.
23236 			 * For multicast traffic, SO_DONTROUTE is interpreted
23237 			 * to mean only send the packet out the interface
23238 			 * (optionally specified with IP_MULTICAST_IF)
23239 			 * and do not forward it out additional interfaces.
23240 			 * RSVP and the rsvp daemon is an example of a
23241 			 * protocol and user level process that
23242 			 * handles it's own routing. Hence, it uses the
23243 			 * SO_DONTROUTE option to accomplish this.
23244 			 */
23245 
23246 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23247 			    ill != NULL) {
23248 				/* Unconditionally redo the checksum */
23249 				ipha->ipha_hdr_checksum = 0;
23250 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23251 
23252 				/*
23253 				 * If this needs to go out secure, we need
23254 				 * to wait till we finish the IPSEC
23255 				 * processing.
23256 				 */
23257 				if (ipsec_len == 0 &&
23258 				    ip_mforward(ill, ipha, mp)) {
23259 					freemsg(first_mp);
23260 					ip1dbg(("ip_wput: mforward failed\n"));
23261 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23262 					    "ip_wput_ire_end: q %p (%S)",
23263 					    q, "mforward failed");
23264 					ire_refrele(ire);
23265 					if (conn_outgoing_ill != NULL)
23266 						ill_refrele(conn_outgoing_ill);
23267 					return;
23268 				}
23269 			}
23270 		}
23271 		max_frag = ire->ire_max_frag;
23272 		cksum += ttl_protocol;
23273 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23274 			/* No fragmentation required for this one. */
23275 			/*
23276 			 * Don't use frag_flag if packet is pre-built or source
23277 			 * routed or if multicast (since multicast packets do
23278 			 * not solicit ICMP "packet too big" messages).
23279 			 */
23280 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23281 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23282 			    !ip_source_route_included(ipha)) &&
23283 			    !CLASSD(ipha->ipha_dst))
23284 				ipha->ipha_fragment_offset_and_flags |=
23285 				    htons(ire->ire_frag_flag);
23286 
23287 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23288 				/* Complete the IP header checksum. */
23289 				cksum += ipha->ipha_ident;
23290 				cksum += (v_hlen_tos_len >> 16)+
23291 				    (v_hlen_tos_len & 0xFFFF);
23292 				cksum += ipha->ipha_fragment_offset_and_flags;
23293 				hlen = (V_HLEN & 0xF) -
23294 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23295 				if (hlen) {
23296 checksumoptions:
23297 					/*
23298 					 * Account for the IP Options in the IP
23299 					 * header checksum.
23300 					 */
23301 					up = (uint16_t *)(rptr+
23302 					    IP_SIMPLE_HDR_LENGTH);
23303 					do {
23304 						cksum += up[0];
23305 						cksum += up[1];
23306 						up += 2;
23307 					} while (--hlen);
23308 				}
23309 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23310 				cksum = ~(cksum + (cksum >> 16));
23311 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23312 			}
23313 			if (ipsec_len != 0) {
23314 				ipsec_out_process(q, first_mp, ire, ill_index);
23315 				if (!next_mp) {
23316 					ire_refrele(ire);
23317 					if (conn_outgoing_ill != NULL)
23318 						ill_refrele(conn_outgoing_ill);
23319 					return;
23320 				}
23321 				goto next;
23322 			}
23323 
23324 			/*
23325 			 * multirt_send has already been handled
23326 			 * for broadcast, but not yet for multicast
23327 			 * or IP options.
23328 			 */
23329 			if (next_mp == NULL) {
23330 				if (ire->ire_flags & RTF_MULTIRT) {
23331 					multirt_send = B_TRUE;
23332 				}
23333 			}
23334 
23335 			/*
23336 			 * In most cases, the emission loop below is
23337 			 * entered only once. Only in the case where
23338 			 * the ire holds the RTF_MULTIRT flag, do we loop
23339 			 * to process all RTF_MULTIRT ires in the bucket,
23340 			 * and send the packet through all crossed
23341 			 * RTF_MULTIRT routes.
23342 			 */
23343 			do {
23344 				if (multirt_send) {
23345 					irb_t *irb;
23346 
23347 					irb = ire->ire_bucket;
23348 					ASSERT(irb != NULL);
23349 					/*
23350 					 * We are in a multiple send case,
23351 					 * need to get the next IRE and make
23352 					 * a duplicate of the packet.
23353 					 */
23354 					IRB_REFHOLD(irb);
23355 					for (ire1 = ire->ire_next;
23356 					    ire1 != NULL;
23357 					    ire1 = ire1->ire_next) {
23358 						if (!(ire1->ire_flags &
23359 						    RTF_MULTIRT)) {
23360 							continue;
23361 						}
23362 						if (ire1->ire_addr !=
23363 						    ire->ire_addr) {
23364 							continue;
23365 						}
23366 						if (ire1->ire_marks &
23367 						    (IRE_MARK_CONDEMNED|
23368 						    IRE_MARK_HIDDEN)) {
23369 							continue;
23370 						}
23371 
23372 						/* Got one */
23373 						IRE_REFHOLD(ire1);
23374 						break;
23375 					}
23376 					IRB_REFRELE(irb);
23377 
23378 					if (ire1 != NULL) {
23379 						next_mp = copyb(mp);
23380 						if ((next_mp == NULL) ||
23381 						    ((mp->b_cont != NULL) &&
23382 						    ((next_mp->b_cont =
23383 						    dupmsg(mp->b_cont))
23384 						    == NULL))) {
23385 							freemsg(next_mp);
23386 							next_mp = NULL;
23387 							ire_refrele(ire1);
23388 							ire1 = NULL;
23389 						}
23390 					}
23391 
23392 					/*
23393 					 * Last multiroute ire; don't loop
23394 					 * anymore. The emission is over
23395 					 * and next_mp is NULL.
23396 					 */
23397 					if (ire1 == NULL) {
23398 						multirt_send = B_FALSE;
23399 					}
23400 				}
23401 
23402 				out_ill = ire->ire_ipif->ipif_ill;
23403 				DTRACE_PROBE4(ip4__physical__out__start,
23404 				    ill_t *, NULL,
23405 				    ill_t *, out_ill,
23406 				    ipha_t *, ipha, mblk_t *, mp);
23407 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23408 				    ipst->ips_ipv4firewall_physical_out,
23409 				    NULL, out_ill, ipha, mp, mp, ipst);
23410 				DTRACE_PROBE1(ip4__physical__out__end,
23411 				    mblk_t *, mp);
23412 				if (mp == NULL)
23413 					goto release_ire_and_ill_2;
23414 
23415 				ASSERT(ipsec_len == 0);
23416 				mp->b_prev =
23417 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23418 				DTRACE_PROBE2(ip__xmit__2,
23419 				    mblk_t *, mp, ire_t *, ire);
23420 				pktxmit_state = ip_xmit_v4(mp, ire,
23421 				    NULL, B_TRUE);
23422 				if ((pktxmit_state == SEND_FAILED) ||
23423 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23424 release_ire_and_ill_2:
23425 					if (next_mp) {
23426 						freemsg(next_mp);
23427 						ire_refrele(ire1);
23428 					}
23429 					ire_refrele(ire);
23430 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23431 					    "ip_wput_ire_end: q %p (%S)",
23432 					    q, "discard MDATA");
23433 					if (conn_outgoing_ill != NULL)
23434 						ill_refrele(conn_outgoing_ill);
23435 					return;
23436 				}
23437 
23438 				if (CLASSD(dst)) {
23439 					BUMP_MIB(out_ill->ill_ip_mib,
23440 					    ipIfStatsHCOutMcastPkts);
23441 					UPDATE_MIB(out_ill->ill_ip_mib,
23442 					    ipIfStatsHCOutMcastOctets,
23443 					    LENGTH);
23444 				} else if (ire->ire_type == IRE_BROADCAST) {
23445 					BUMP_MIB(out_ill->ill_ip_mib,
23446 					    ipIfStatsHCOutBcastPkts);
23447 				}
23448 
23449 				if (multirt_send) {
23450 					/*
23451 					 * We are in a multiple send case,
23452 					 * need to re-enter the sending loop
23453 					 * using the next ire.
23454 					 */
23455 					ire_refrele(ire);
23456 					ire = ire1;
23457 					stq = ire->ire_stq;
23458 					mp = next_mp;
23459 					next_mp = NULL;
23460 					ipha = (ipha_t *)mp->b_rptr;
23461 					ill_index = Q_TO_INDEX(stq);
23462 				}
23463 			} while (multirt_send);
23464 
23465 			if (!next_mp) {
23466 				/*
23467 				 * Last copy going out (the ultra-common
23468 				 * case).  Note that we intentionally replicate
23469 				 * the putnext rather than calling it before
23470 				 * the next_mp check in hopes of a little
23471 				 * tail-call action out of the compiler.
23472 				 */
23473 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23474 				    "ip_wput_ire_end: q %p (%S)",
23475 				    q, "last copy out(1)");
23476 				ire_refrele(ire);
23477 				if (conn_outgoing_ill != NULL)
23478 					ill_refrele(conn_outgoing_ill);
23479 				return;
23480 			}
23481 			/* More copies going out below. */
23482 		} else {
23483 			int offset;
23484 fragmentit:
23485 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23486 			/*
23487 			 * If this would generate a icmp_frag_needed message,
23488 			 * we need to handle it before we do the IPSEC
23489 			 * processing. Otherwise, we need to strip the IPSEC
23490 			 * headers before we send up the message to the ULPs
23491 			 * which becomes messy and difficult.
23492 			 */
23493 			if (ipsec_len != 0) {
23494 				if ((max_frag < (unsigned int)(LENGTH +
23495 				    ipsec_len)) && (offset & IPH_DF)) {
23496 					out_ill = (ill_t *)stq->q_ptr;
23497 					BUMP_MIB(out_ill->ill_ip_mib,
23498 					    ipIfStatsOutFragFails);
23499 					BUMP_MIB(out_ill->ill_ip_mib,
23500 					    ipIfStatsOutFragReqds);
23501 					ipha->ipha_hdr_checksum = 0;
23502 					ipha->ipha_hdr_checksum =
23503 					    (uint16_t)ip_csum_hdr(ipha);
23504 					icmp_frag_needed(ire->ire_stq, first_mp,
23505 					    max_frag, zoneid, ipst);
23506 					if (!next_mp) {
23507 						ire_refrele(ire);
23508 						if (conn_outgoing_ill != NULL) {
23509 							ill_refrele(
23510 							    conn_outgoing_ill);
23511 						}
23512 						return;
23513 					}
23514 				} else {
23515 					/*
23516 					 * This won't cause a icmp_frag_needed
23517 					 * message. to be generated. Send it on
23518 					 * the wire. Note that this could still
23519 					 * cause fragmentation and all we
23520 					 * do is the generation of the message
23521 					 * to the ULP if needed before IPSEC.
23522 					 */
23523 					if (!next_mp) {
23524 						ipsec_out_process(q, first_mp,
23525 						    ire, ill_index);
23526 						TRACE_2(TR_FAC_IP,
23527 						    TR_IP_WPUT_IRE_END,
23528 						    "ip_wput_ire_end: q %p "
23529 						    "(%S)", q,
23530 						    "last ipsec_out_process");
23531 						ire_refrele(ire);
23532 						if (conn_outgoing_ill != NULL) {
23533 							ill_refrele(
23534 							    conn_outgoing_ill);
23535 						}
23536 						return;
23537 					}
23538 					ipsec_out_process(q, first_mp,
23539 					    ire, ill_index);
23540 				}
23541 			} else {
23542 				/*
23543 				 * Initiate IPPF processing. For
23544 				 * fragmentable packets we finish
23545 				 * all QOS packet processing before
23546 				 * calling:
23547 				 * ip_wput_ire_fragmentit->ip_wput_frag
23548 				 */
23549 
23550 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23551 					ip_process(IPP_LOCAL_OUT, &mp,
23552 					    ill_index);
23553 					if (mp == NULL) {
23554 						out_ill = (ill_t *)stq->q_ptr;
23555 						BUMP_MIB(out_ill->ill_ip_mib,
23556 						    ipIfStatsOutDiscards);
23557 						if (next_mp != NULL) {
23558 							freemsg(next_mp);
23559 							ire_refrele(ire1);
23560 						}
23561 						ire_refrele(ire);
23562 						TRACE_2(TR_FAC_IP,
23563 						    TR_IP_WPUT_IRE_END,
23564 						    "ip_wput_ire: q %p (%S)",
23565 						    q, "discard MDATA");
23566 						if (conn_outgoing_ill != NULL) {
23567 							ill_refrele(
23568 							    conn_outgoing_ill);
23569 						}
23570 						return;
23571 					}
23572 				}
23573 				if (!next_mp) {
23574 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23575 					    "ip_wput_ire_end: q %p (%S)",
23576 					    q, "last fragmentation");
23577 					ip_wput_ire_fragmentit(mp, ire,
23578 					    zoneid, ipst);
23579 					ire_refrele(ire);
23580 					if (conn_outgoing_ill != NULL)
23581 						ill_refrele(conn_outgoing_ill);
23582 					return;
23583 				}
23584 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23585 			}
23586 		}
23587 	} else {
23588 nullstq:
23589 		/* A NULL stq means the destination address is local. */
23590 		UPDATE_OB_PKT_COUNT(ire);
23591 		ire->ire_last_used_time = lbolt;
23592 		ASSERT(ire->ire_ipif != NULL);
23593 		if (!next_mp) {
23594 			/*
23595 			 * Is there an "in" and "out" for traffic local
23596 			 * to a host (loopback)?  The code in Solaris doesn't
23597 			 * explicitly draw a line in its code for in vs out,
23598 			 * so we've had to draw a line in the sand: ip_wput_ire
23599 			 * is considered to be the "output" side and
23600 			 * ip_wput_local to be the "input" side.
23601 			 */
23602 			out_ill = ire->ire_ipif->ipif_ill;
23603 
23604 			DTRACE_PROBE4(ip4__loopback__out__start,
23605 			    ill_t *, NULL, ill_t *, out_ill,
23606 			    ipha_t *, ipha, mblk_t *, first_mp);
23607 
23608 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23609 			    ipst->ips_ipv4firewall_loopback_out,
23610 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23611 
23612 			DTRACE_PROBE1(ip4__loopback__out_end,
23613 			    mblk_t *, first_mp);
23614 
23615 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23616 			    "ip_wput_ire_end: q %p (%S)",
23617 			    q, "local address");
23618 
23619 			if (first_mp != NULL)
23620 				ip_wput_local(q, out_ill, ipha,
23621 				    first_mp, ire, 0, ire->ire_zoneid);
23622 			ire_refrele(ire);
23623 			if (conn_outgoing_ill != NULL)
23624 				ill_refrele(conn_outgoing_ill);
23625 			return;
23626 		}
23627 
23628 		out_ill = ire->ire_ipif->ipif_ill;
23629 
23630 		DTRACE_PROBE4(ip4__loopback__out__start,
23631 		    ill_t *, NULL, ill_t *, out_ill,
23632 		    ipha_t *, ipha, mblk_t *, first_mp);
23633 
23634 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23635 		    ipst->ips_ipv4firewall_loopback_out,
23636 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23637 
23638 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23639 
23640 		if (first_mp != NULL)
23641 			ip_wput_local(q, out_ill, ipha,
23642 			    first_mp, ire, 0, ire->ire_zoneid);
23643 	}
23644 next:
23645 	/*
23646 	 * More copies going out to additional interfaces.
23647 	 * ire1 has already been held. We don't need the
23648 	 * "ire" anymore.
23649 	 */
23650 	ire_refrele(ire);
23651 	ire = ire1;
23652 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23653 	mp = next_mp;
23654 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23655 	ill = ire_to_ill(ire);
23656 	first_mp = mp;
23657 	if (ipsec_len != 0) {
23658 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23659 		mp = mp->b_cont;
23660 	}
23661 	dst = ire->ire_addr;
23662 	ipha = (ipha_t *)mp->b_rptr;
23663 	/*
23664 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23665 	 * Restore ipha_ident "no checksum" flag.
23666 	 */
23667 	src = orig_src;
23668 	ipha->ipha_ident = ip_hdr_included;
23669 	goto another;
23670 
23671 #undef	rptr
23672 #undef	Q_TO_INDEX
23673 }
23674 
23675 /*
23676  * Routine to allocate a message that is used to notify the ULP about MDT.
23677  * The caller may provide a pointer to the link-layer MDT capabilities,
23678  * or NULL if MDT is to be disabled on the stream.
23679  */
23680 mblk_t *
23681 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23682 {
23683 	mblk_t *mp;
23684 	ip_mdt_info_t *mdti;
23685 	ill_mdt_capab_t *idst;
23686 
23687 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23688 		DB_TYPE(mp) = M_CTL;
23689 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23690 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23691 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23692 		idst = &(mdti->mdt_capab);
23693 
23694 		/*
23695 		 * If the caller provides us with the capability, copy
23696 		 * it over into our notification message; otherwise
23697 		 * we zero out the capability portion.
23698 		 */
23699 		if (isrc != NULL)
23700 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23701 		else
23702 			bzero((caddr_t)idst, sizeof (*idst));
23703 	}
23704 	return (mp);
23705 }
23706 
23707 /*
23708  * Routine which determines whether MDT can be enabled on the destination
23709  * IRE and IPC combination, and if so, allocates and returns the MDT
23710  * notification mblk that may be used by ULP.  We also check if we need to
23711  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23712  * MDT usage in the past have been lifted.  This gets called during IP
23713  * and ULP binding.
23714  */
23715 mblk_t *
23716 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23717     ill_mdt_capab_t *mdt_cap)
23718 {
23719 	mblk_t *mp;
23720 	boolean_t rc = B_FALSE;
23721 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23722 
23723 	ASSERT(dst_ire != NULL);
23724 	ASSERT(connp != NULL);
23725 	ASSERT(mdt_cap != NULL);
23726 
23727 	/*
23728 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23729 	 * Multidata, which is handled in tcp_multisend().  This
23730 	 * is the reason why we do all these checks here, to ensure
23731 	 * that we don't enable Multidata for the cases which we
23732 	 * can't handle at the moment.
23733 	 */
23734 	do {
23735 		/* Only do TCP at the moment */
23736 		if (connp->conn_ulp != IPPROTO_TCP)
23737 			break;
23738 
23739 		/*
23740 		 * IPSEC outbound policy present?  Note that we get here
23741 		 * after calling ipsec_conn_cache_policy() where the global
23742 		 * policy checking is performed.  conn_latch will be
23743 		 * non-NULL as long as there's a policy defined,
23744 		 * i.e. conn_out_enforce_policy may be NULL in such case
23745 		 * when the connection is non-secure, and hence we check
23746 		 * further if the latch refers to an outbound policy.
23747 		 */
23748 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23749 			break;
23750 
23751 		/* CGTP (multiroute) is enabled? */
23752 		if (dst_ire->ire_flags & RTF_MULTIRT)
23753 			break;
23754 
23755 		/* Outbound IPQoS enabled? */
23756 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23757 			/*
23758 			 * In this case, we disable MDT for this and all
23759 			 * future connections going over the interface.
23760 			 */
23761 			mdt_cap->ill_mdt_on = 0;
23762 			break;
23763 		}
23764 
23765 		/* socket option(s) present? */
23766 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23767 			break;
23768 
23769 		rc = B_TRUE;
23770 	/* CONSTCOND */
23771 	} while (0);
23772 
23773 	/* Remember the result */
23774 	connp->conn_mdt_ok = rc;
23775 
23776 	if (!rc)
23777 		return (NULL);
23778 	else if (!mdt_cap->ill_mdt_on) {
23779 		/*
23780 		 * If MDT has been previously turned off in the past, and we
23781 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23782 		 * then enable it for this interface.
23783 		 */
23784 		mdt_cap->ill_mdt_on = 1;
23785 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23786 		    "interface %s\n", ill_name));
23787 	}
23788 
23789 	/* Allocate the MDT info mblk */
23790 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23791 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23792 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23793 		return (NULL);
23794 	}
23795 	return (mp);
23796 }
23797 
23798 /*
23799  * Routine to allocate a message that is used to notify the ULP about LSO.
23800  * The caller may provide a pointer to the link-layer LSO capabilities,
23801  * or NULL if LSO is to be disabled on the stream.
23802  */
23803 mblk_t *
23804 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23805 {
23806 	mblk_t *mp;
23807 	ip_lso_info_t *lsoi;
23808 	ill_lso_capab_t *idst;
23809 
23810 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23811 		DB_TYPE(mp) = M_CTL;
23812 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23813 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23814 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23815 		idst = &(lsoi->lso_capab);
23816 
23817 		/*
23818 		 * If the caller provides us with the capability, copy
23819 		 * it over into our notification message; otherwise
23820 		 * we zero out the capability portion.
23821 		 */
23822 		if (isrc != NULL)
23823 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23824 		else
23825 			bzero((caddr_t)idst, sizeof (*idst));
23826 	}
23827 	return (mp);
23828 }
23829 
23830 /*
23831  * Routine which determines whether LSO can be enabled on the destination
23832  * IRE and IPC combination, and if so, allocates and returns the LSO
23833  * notification mblk that may be used by ULP.  We also check if we need to
23834  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23835  * LSO usage in the past have been lifted.  This gets called during IP
23836  * and ULP binding.
23837  */
23838 mblk_t *
23839 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23840     ill_lso_capab_t *lso_cap)
23841 {
23842 	mblk_t *mp;
23843 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23844 
23845 	ASSERT(dst_ire != NULL);
23846 	ASSERT(connp != NULL);
23847 	ASSERT(lso_cap != NULL);
23848 
23849 	connp->conn_lso_ok = B_TRUE;
23850 
23851 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23852 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23853 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23854 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23855 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23856 		connp->conn_lso_ok = B_FALSE;
23857 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23858 			/*
23859 			 * Disable LSO for this and all future connections going
23860 			 * over the interface.
23861 			 */
23862 			lso_cap->ill_lso_on = 0;
23863 		}
23864 	}
23865 
23866 	if (!connp->conn_lso_ok)
23867 		return (NULL);
23868 	else if (!lso_cap->ill_lso_on) {
23869 		/*
23870 		 * If LSO has been previously turned off in the past, and we
23871 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23872 		 * then enable it for this interface.
23873 		 */
23874 		lso_cap->ill_lso_on = 1;
23875 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23876 		    ill_name));
23877 	}
23878 
23879 	/* Allocate the LSO info mblk */
23880 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23881 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23882 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23883 
23884 	return (mp);
23885 }
23886 
23887 /*
23888  * Create destination address attribute, and fill it with the physical
23889  * destination address and SAP taken from the template DL_UNITDATA_REQ
23890  * message block.
23891  */
23892 boolean_t
23893 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23894 {
23895 	dl_unitdata_req_t *dlurp;
23896 	pattr_t *pa;
23897 	pattrinfo_t pa_info;
23898 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23899 	uint_t das_len, das_off;
23900 
23901 	ASSERT(dlmp != NULL);
23902 
23903 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23904 	das_len = dlurp->dl_dest_addr_length;
23905 	das_off = dlurp->dl_dest_addr_offset;
23906 
23907 	pa_info.type = PATTR_DSTADDRSAP;
23908 	pa_info.len = sizeof (**das) + das_len - 1;
23909 
23910 	/* create and associate the attribute */
23911 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23912 	if (pa != NULL) {
23913 		ASSERT(*das != NULL);
23914 		(*das)->addr_is_group = 0;
23915 		(*das)->addr_len = (uint8_t)das_len;
23916 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23917 	}
23918 
23919 	return (pa != NULL);
23920 }
23921 
23922 /*
23923  * Create hardware checksum attribute and fill it with the values passed.
23924  */
23925 boolean_t
23926 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23927     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23928 {
23929 	pattr_t *pa;
23930 	pattrinfo_t pa_info;
23931 
23932 	ASSERT(mmd != NULL);
23933 
23934 	pa_info.type = PATTR_HCKSUM;
23935 	pa_info.len = sizeof (pattr_hcksum_t);
23936 
23937 	/* create and associate the attribute */
23938 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23939 	if (pa != NULL) {
23940 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23941 
23942 		hck->hcksum_start_offset = start_offset;
23943 		hck->hcksum_stuff_offset = stuff_offset;
23944 		hck->hcksum_end_offset = end_offset;
23945 		hck->hcksum_flags = flags;
23946 	}
23947 	return (pa != NULL);
23948 }
23949 
23950 /*
23951  * Create zerocopy attribute and fill it with the specified flags
23952  */
23953 boolean_t
23954 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23955 {
23956 	pattr_t *pa;
23957 	pattrinfo_t pa_info;
23958 
23959 	ASSERT(mmd != NULL);
23960 	pa_info.type = PATTR_ZCOPY;
23961 	pa_info.len = sizeof (pattr_zcopy_t);
23962 
23963 	/* create and associate the attribute */
23964 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23965 	if (pa != NULL) {
23966 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23967 
23968 		zcopy->zcopy_flags = flags;
23969 	}
23970 	return (pa != NULL);
23971 }
23972 
23973 /*
23974  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23975  * block chain. We could rewrite to handle arbitrary message block chains but
23976  * that would make the code complicated and slow. Right now there three
23977  * restrictions:
23978  *
23979  *   1. The first message block must contain the complete IP header and
23980  *	at least 1 byte of payload data.
23981  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23982  *	so that we can use a single Multidata message.
23983  *   3. No frag must be distributed over two or more message blocks so
23984  *	that we don't need more than two packet descriptors per frag.
23985  *
23986  * The above restrictions allow us to support userland applications (which
23987  * will send down a single message block) and NFS over UDP (which will
23988  * send down a chain of at most three message blocks).
23989  *
23990  * We also don't use MDT for payloads with less than or equal to
23991  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23992  */
23993 boolean_t
23994 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23995 {
23996 	int	blocks;
23997 	ssize_t	total, missing, size;
23998 
23999 	ASSERT(mp != NULL);
24000 	ASSERT(hdr_len > 0);
24001 
24002 	size = MBLKL(mp) - hdr_len;
24003 	if (size <= 0)
24004 		return (B_FALSE);
24005 
24006 	/* The first mblk contains the header and some payload. */
24007 	blocks = 1;
24008 	total = size;
24009 	size %= len;
24010 	missing = (size == 0) ? 0 : (len - size);
24011 	mp = mp->b_cont;
24012 
24013 	while (mp != NULL) {
24014 		/*
24015 		 * Give up if we encounter a zero length message block.
24016 		 * In practice, this should rarely happen and therefore
24017 		 * not worth the trouble of freeing and re-linking the
24018 		 * mblk from the chain to handle such case.
24019 		 */
24020 		if ((size = MBLKL(mp)) == 0)
24021 			return (B_FALSE);
24022 
24023 		/* Too many payload buffers for a single Multidata message? */
24024 		if (++blocks > MULTIDATA_MAX_PBUFS)
24025 			return (B_FALSE);
24026 
24027 		total += size;
24028 		/* Is a frag distributed over two or more message blocks? */
24029 		if (missing > size)
24030 			return (B_FALSE);
24031 		size -= missing;
24032 
24033 		size %= len;
24034 		missing = (size == 0) ? 0 : (len - size);
24035 
24036 		mp = mp->b_cont;
24037 	}
24038 
24039 	return (total > ip_wput_frag_mdt_min);
24040 }
24041 
24042 /*
24043  * Outbound IPv4 fragmentation routine using MDT.
24044  */
24045 static void
24046 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24047     uint32_t frag_flag, int offset)
24048 {
24049 	ipha_t		*ipha_orig;
24050 	int		i1, ip_data_end;
24051 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24052 	mblk_t		*hdr_mp, *md_mp = NULL;
24053 	unsigned char	*hdr_ptr, *pld_ptr;
24054 	multidata_t	*mmd;
24055 	ip_pdescinfo_t	pdi;
24056 	ill_t		*ill;
24057 	ip_stack_t	*ipst = ire->ire_ipst;
24058 
24059 	ASSERT(DB_TYPE(mp) == M_DATA);
24060 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24061 
24062 	ill = ire_to_ill(ire);
24063 	ASSERT(ill != NULL);
24064 
24065 	ipha_orig = (ipha_t *)mp->b_rptr;
24066 	mp->b_rptr += sizeof (ipha_t);
24067 
24068 	/* Calculate how many packets we will send out */
24069 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24070 	pkts = (i1 + len - 1) / len;
24071 	ASSERT(pkts > 1);
24072 
24073 	/* Allocate a message block which will hold all the IP Headers. */
24074 	wroff = ipst->ips_ip_wroff_extra;
24075 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24076 
24077 	i1 = pkts * hdr_chunk_len;
24078 	/*
24079 	 * Create the header buffer, Multidata and destination address
24080 	 * and SAP attribute that should be associated with it.
24081 	 */
24082 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24083 	    ((hdr_mp->b_wptr += i1),
24084 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24085 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24086 		freemsg(mp);
24087 		if (md_mp == NULL) {
24088 			freemsg(hdr_mp);
24089 		} else {
24090 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24091 			freemsg(md_mp);
24092 		}
24093 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24094 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24095 		return;
24096 	}
24097 	IP_STAT(ipst, ip_frag_mdt_allocd);
24098 
24099 	/*
24100 	 * Add a payload buffer to the Multidata; this operation must not
24101 	 * fail, or otherwise our logic in this routine is broken.  There
24102 	 * is no memory allocation done by the routine, so any returned
24103 	 * failure simply tells us that we've done something wrong.
24104 	 *
24105 	 * A failure tells us that either we're adding the same payload
24106 	 * buffer more than once, or we're trying to add more buffers than
24107 	 * allowed.  None of the above cases should happen, and we panic
24108 	 * because either there's horrible heap corruption, and/or
24109 	 * programming mistake.
24110 	 */
24111 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24112 		goto pbuf_panic;
24113 
24114 	hdr_ptr = hdr_mp->b_rptr;
24115 	pld_ptr = mp->b_rptr;
24116 
24117 	/* Establish the ending byte offset, based on the starting offset. */
24118 	offset <<= 3;
24119 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24120 	    IP_SIMPLE_HDR_LENGTH;
24121 
24122 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24123 
24124 	while (pld_ptr < mp->b_wptr) {
24125 		ipha_t		*ipha;
24126 		uint16_t	offset_and_flags;
24127 		uint16_t	ip_len;
24128 		int		error;
24129 
24130 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24131 		ipha = (ipha_t *)(hdr_ptr + wroff);
24132 		ASSERT(OK_32PTR(ipha));
24133 		*ipha = *ipha_orig;
24134 
24135 		if (ip_data_end - offset > len) {
24136 			offset_and_flags = IPH_MF;
24137 		} else {
24138 			/*
24139 			 * Last frag. Set len to the length of this last piece.
24140 			 */
24141 			len = ip_data_end - offset;
24142 			/* A frag of a frag might have IPH_MF non-zero */
24143 			offset_and_flags =
24144 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24145 			    IPH_MF;
24146 		}
24147 		offset_and_flags |= (uint16_t)(offset >> 3);
24148 		offset_and_flags |= (uint16_t)frag_flag;
24149 		/* Store the offset and flags in the IP header. */
24150 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24151 
24152 		/* Store the length in the IP header. */
24153 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24154 		ipha->ipha_length = htons(ip_len);
24155 
24156 		/*
24157 		 * Set the IP header checksum.  Note that mp is just
24158 		 * the header, so this is easy to pass to ip_csum.
24159 		 */
24160 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24161 
24162 		/*
24163 		 * Record offset and size of header and data of the next packet
24164 		 * in the multidata message.
24165 		 */
24166 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24167 		PDESC_PLD_INIT(&pdi);
24168 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24169 		ASSERT(i1 > 0);
24170 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24171 		if (i1 == len) {
24172 			pld_ptr += len;
24173 		} else {
24174 			i1 = len - i1;
24175 			mp = mp->b_cont;
24176 			ASSERT(mp != NULL);
24177 			ASSERT(MBLKL(mp) >= i1);
24178 			/*
24179 			 * Attach the next payload message block to the
24180 			 * multidata message.
24181 			 */
24182 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24183 				goto pbuf_panic;
24184 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24185 			pld_ptr = mp->b_rptr + i1;
24186 		}
24187 
24188 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24189 		    KM_NOSLEEP)) == NULL) {
24190 			/*
24191 			 * Any failure other than ENOMEM indicates that we
24192 			 * have passed in invalid pdesc info or parameters
24193 			 * to mmd_addpdesc, which must not happen.
24194 			 *
24195 			 * EINVAL is a result of failure on boundary checks
24196 			 * against the pdesc info contents.  It should not
24197 			 * happen, and we panic because either there's
24198 			 * horrible heap corruption, and/or programming
24199 			 * mistake.
24200 			 */
24201 			if (error != ENOMEM) {
24202 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24203 				    "pdesc logic error detected for "
24204 				    "mmd %p pinfo %p (%d)\n",
24205 				    (void *)mmd, (void *)&pdi, error);
24206 				/* NOTREACHED */
24207 			}
24208 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24209 			/* Free unattached payload message blocks as well */
24210 			md_mp->b_cont = mp->b_cont;
24211 			goto free_mmd;
24212 		}
24213 
24214 		/* Advance fragment offset. */
24215 		offset += len;
24216 
24217 		/* Advance to location for next header in the buffer. */
24218 		hdr_ptr += hdr_chunk_len;
24219 
24220 		/* Did we reach the next payload message block? */
24221 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24222 			mp = mp->b_cont;
24223 			/*
24224 			 * Attach the next message block with payload
24225 			 * data to the multidata message.
24226 			 */
24227 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24228 				goto pbuf_panic;
24229 			pld_ptr = mp->b_rptr;
24230 		}
24231 	}
24232 
24233 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24234 	ASSERT(mp->b_wptr == pld_ptr);
24235 
24236 	/* Update IP statistics */
24237 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24238 
24239 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24240 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24241 
24242 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24243 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24244 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24245 
24246 	if (pkt_type == OB_PKT) {
24247 		ire->ire_ob_pkt_count += pkts;
24248 		if (ire->ire_ipif != NULL)
24249 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24250 	} else {
24251 		/*
24252 		 * The type is IB_PKT in the forwarding path and in
24253 		 * the mobile IP case when the packet is being reverse-
24254 		 * tunneled to the home agent.
24255 		 */
24256 		ire->ire_ib_pkt_count += pkts;
24257 		ASSERT(!IRE_IS_LOCAL(ire));
24258 		if (ire->ire_type & IRE_BROADCAST) {
24259 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24260 		} else {
24261 			UPDATE_MIB(ill->ill_ip_mib,
24262 			    ipIfStatsHCOutForwDatagrams, pkts);
24263 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24264 		}
24265 	}
24266 	ire->ire_last_used_time = lbolt;
24267 	/* Send it down */
24268 	putnext(ire->ire_stq, md_mp);
24269 	return;
24270 
24271 pbuf_panic:
24272 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24273 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24274 	    pbuf_idx);
24275 	/* NOTREACHED */
24276 }
24277 
24278 /*
24279  * Outbound IP fragmentation routine.
24280  *
24281  * NOTE : This routine does not ire_refrele the ire that is passed in
24282  * as the argument.
24283  */
24284 static void
24285 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24286     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24287 {
24288 	int		i1;
24289 	mblk_t		*ll_hdr_mp;
24290 	int 		ll_hdr_len;
24291 	int		hdr_len;
24292 	mblk_t		*hdr_mp;
24293 	ipha_t		*ipha;
24294 	int		ip_data_end;
24295 	int		len;
24296 	mblk_t		*mp = mp_orig, *mp1;
24297 	int		offset;
24298 	queue_t		*q;
24299 	uint32_t	v_hlen_tos_len;
24300 	mblk_t		*first_mp;
24301 	boolean_t	mctl_present;
24302 	ill_t		*ill;
24303 	ill_t		*out_ill;
24304 	mblk_t		*xmit_mp;
24305 	mblk_t		*carve_mp;
24306 	ire_t		*ire1 = NULL;
24307 	ire_t		*save_ire = NULL;
24308 	mblk_t  	*next_mp = NULL;
24309 	boolean_t	last_frag = B_FALSE;
24310 	boolean_t	multirt_send = B_FALSE;
24311 	ire_t		*first_ire = NULL;
24312 	irb_t		*irb = NULL;
24313 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24314 
24315 	ill = ire_to_ill(ire);
24316 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24317 
24318 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24319 
24320 	if (max_frag == 0) {
24321 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24322 		    " -  dropping packet\n"));
24323 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24324 		freemsg(mp);
24325 		return;
24326 	}
24327 
24328 	/*
24329 	 * IPSEC does not allow hw accelerated packets to be fragmented
24330 	 * This check is made in ip_wput_ipsec_out prior to coming here
24331 	 * via ip_wput_ire_fragmentit.
24332 	 *
24333 	 * If at this point we have an ire whose ARP request has not
24334 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24335 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24336 	 * This packet and all fragmentable packets for this ire will
24337 	 * continue to get dropped while ire_nce->nce_state remains in
24338 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24339 	 * ND_REACHABLE, all subsquent large packets for this ire will
24340 	 * get fragemented and sent out by this function.
24341 	 */
24342 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24343 		/* If nce_state is ND_INITIAL, trigger ARP query */
24344 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24345 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24346 		    " -  dropping packet\n"));
24347 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24348 		freemsg(mp);
24349 		return;
24350 	}
24351 
24352 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24353 	    "ip_wput_frag_start:");
24354 
24355 	if (mp->b_datap->db_type == M_CTL) {
24356 		first_mp = mp;
24357 		mp_orig = mp = mp->b_cont;
24358 		mctl_present = B_TRUE;
24359 	} else {
24360 		first_mp = mp;
24361 		mctl_present = B_FALSE;
24362 	}
24363 
24364 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24365 	ipha = (ipha_t *)mp->b_rptr;
24366 
24367 	/*
24368 	 * If the Don't Fragment flag is on, generate an ICMP destination
24369 	 * unreachable, fragmentation needed.
24370 	 */
24371 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24372 	if (offset & IPH_DF) {
24373 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24374 		if (is_system_labeled()) {
24375 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24376 			    ire->ire_max_frag - max_frag, AF_INET);
24377 		}
24378 		/*
24379 		 * Need to compute hdr checksum if called from ip_wput_ire.
24380 		 * Note that ip_rput_forward verifies the checksum before
24381 		 * calling this routine so in that case this is a noop.
24382 		 */
24383 		ipha->ipha_hdr_checksum = 0;
24384 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24385 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24386 		    ipst);
24387 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24388 		    "ip_wput_frag_end:(%S)",
24389 		    "don't fragment");
24390 		return;
24391 	}
24392 	/*
24393 	 * Labeled systems adjust max_frag if they add a label
24394 	 * to send the correct path mtu.  We need the real mtu since we
24395 	 * are fragmenting the packet after label adjustment.
24396 	 */
24397 	if (is_system_labeled())
24398 		max_frag = ire->ire_max_frag;
24399 	if (mctl_present)
24400 		freeb(first_mp);
24401 	/*
24402 	 * Establish the starting offset.  May not be zero if we are fragging
24403 	 * a fragment that is being forwarded.
24404 	 */
24405 	offset = offset & IPH_OFFSET;
24406 
24407 	/* TODO why is this test needed? */
24408 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24409 	if (((max_frag - LENGTH) & ~7) < 8) {
24410 		/* TODO: notify ulp somehow */
24411 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24412 		freemsg(mp);
24413 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24414 		    "ip_wput_frag_end:(%S)",
24415 		    "len < 8");
24416 		return;
24417 	}
24418 
24419 	hdr_len = (V_HLEN & 0xF) << 2;
24420 
24421 	ipha->ipha_hdr_checksum = 0;
24422 
24423 	/*
24424 	 * Establish the number of bytes maximum per frag, after putting
24425 	 * in the header.
24426 	 */
24427 	len = (max_frag - hdr_len) & ~7;
24428 
24429 	/* Check if we can use MDT to send out the frags. */
24430 	ASSERT(!IRE_IS_LOCAL(ire));
24431 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24432 	    ipst->ips_ip_multidata_outbound &&
24433 	    !(ire->ire_flags & RTF_MULTIRT) &&
24434 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24435 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24436 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24437 		ASSERT(ill->ill_mdt_capab != NULL);
24438 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24439 			/*
24440 			 * If MDT has been previously turned off in the past,
24441 			 * and we currently can do MDT (due to IPQoS policy
24442 			 * removal, etc.) then enable it for this interface.
24443 			 */
24444 			ill->ill_mdt_capab->ill_mdt_on = 1;
24445 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24446 			    ill->ill_name));
24447 		}
24448 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24449 		    offset);
24450 		return;
24451 	}
24452 
24453 	/* Get a copy of the header for the trailing frags */
24454 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24455 	if (!hdr_mp) {
24456 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24457 		freemsg(mp);
24458 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24459 		    "ip_wput_frag_end:(%S)",
24460 		    "couldn't copy hdr");
24461 		return;
24462 	}
24463 	if (DB_CRED(mp) != NULL)
24464 		mblk_setcred(hdr_mp, DB_CRED(mp));
24465 
24466 	/* Store the starting offset, with the MoreFrags flag. */
24467 	i1 = offset | IPH_MF | frag_flag;
24468 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24469 
24470 	/* Establish the ending byte offset, based on the starting offset. */
24471 	offset <<= 3;
24472 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24473 
24474 	/* Store the length of the first fragment in the IP header. */
24475 	i1 = len + hdr_len;
24476 	ASSERT(i1 <= IP_MAXPACKET);
24477 	ipha->ipha_length = htons((uint16_t)i1);
24478 
24479 	/*
24480 	 * Compute the IP header checksum for the first frag.  We have to
24481 	 * watch out that we stop at the end of the header.
24482 	 */
24483 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24484 
24485 	/*
24486 	 * Now carve off the first frag.  Note that this will include the
24487 	 * original IP header.
24488 	 */
24489 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24490 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24491 		freeb(hdr_mp);
24492 		freemsg(mp_orig);
24493 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24494 		    "ip_wput_frag_end:(%S)",
24495 		    "couldn't carve first");
24496 		return;
24497 	}
24498 
24499 	/*
24500 	 * Multirouting case. Each fragment is replicated
24501 	 * via all non-condemned RTF_MULTIRT routes
24502 	 * currently resolved.
24503 	 * We ensure that first_ire is the first RTF_MULTIRT
24504 	 * ire in the bucket.
24505 	 */
24506 	if (ire->ire_flags & RTF_MULTIRT) {
24507 		irb = ire->ire_bucket;
24508 		ASSERT(irb != NULL);
24509 
24510 		multirt_send = B_TRUE;
24511 
24512 		/* Make sure we do not omit any multiroute ire. */
24513 		IRB_REFHOLD(irb);
24514 		for (first_ire = irb->irb_ire;
24515 		    first_ire != NULL;
24516 		    first_ire = first_ire->ire_next) {
24517 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24518 			    (first_ire->ire_addr == ire->ire_addr) &&
24519 			    !(first_ire->ire_marks &
24520 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24521 				break;
24522 			}
24523 		}
24524 
24525 		if (first_ire != NULL) {
24526 			if (first_ire != ire) {
24527 				IRE_REFHOLD(first_ire);
24528 				/*
24529 				 * Do not release the ire passed in
24530 				 * as the argument.
24531 				 */
24532 				ire = first_ire;
24533 			} else {
24534 				first_ire = NULL;
24535 			}
24536 		}
24537 		IRB_REFRELE(irb);
24538 
24539 		/*
24540 		 * Save the first ire; we will need to restore it
24541 		 * for the trailing frags.
24542 		 * We REFHOLD save_ire, as each iterated ire will be
24543 		 * REFRELEd.
24544 		 */
24545 		save_ire = ire;
24546 		IRE_REFHOLD(save_ire);
24547 	}
24548 
24549 	/*
24550 	 * First fragment emission loop.
24551 	 * In most cases, the emission loop below is entered only
24552 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24553 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24554 	 * bucket, and send the fragment through all crossed
24555 	 * RTF_MULTIRT routes.
24556 	 */
24557 	do {
24558 		if (ire->ire_flags & RTF_MULTIRT) {
24559 			/*
24560 			 * We are in a multiple send case, need to get
24561 			 * the next ire and make a copy of the packet.
24562 			 * ire1 holds here the next ire to process in the
24563 			 * bucket. If multirouting is expected,
24564 			 * any non-RTF_MULTIRT ire that has the
24565 			 * right destination address is ignored.
24566 			 *
24567 			 * We have to take into account the MTU of
24568 			 * each walked ire. max_frag is set by the
24569 			 * the caller and generally refers to
24570 			 * the primary ire entry. Here we ensure that
24571 			 * no route with a lower MTU will be used, as
24572 			 * fragments are carved once for all ires,
24573 			 * then replicated.
24574 			 */
24575 			ASSERT(irb != NULL);
24576 			IRB_REFHOLD(irb);
24577 			for (ire1 = ire->ire_next;
24578 			    ire1 != NULL;
24579 			    ire1 = ire1->ire_next) {
24580 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24581 					continue;
24582 				if (ire1->ire_addr != ire->ire_addr)
24583 					continue;
24584 				if (ire1->ire_marks &
24585 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24586 					continue;
24587 				/*
24588 				 * Ensure we do not exceed the MTU
24589 				 * of the next route.
24590 				 */
24591 				if (ire1->ire_max_frag < max_frag) {
24592 					ip_multirt_bad_mtu(ire1, max_frag);
24593 					continue;
24594 				}
24595 
24596 				/* Got one. */
24597 				IRE_REFHOLD(ire1);
24598 				break;
24599 			}
24600 			IRB_REFRELE(irb);
24601 
24602 			if (ire1 != NULL) {
24603 				next_mp = copyb(mp);
24604 				if ((next_mp == NULL) ||
24605 				    ((mp->b_cont != NULL) &&
24606 				    ((next_mp->b_cont =
24607 				    dupmsg(mp->b_cont)) == NULL))) {
24608 					freemsg(next_mp);
24609 					next_mp = NULL;
24610 					ire_refrele(ire1);
24611 					ire1 = NULL;
24612 				}
24613 			}
24614 
24615 			/* Last multiroute ire; don't loop anymore. */
24616 			if (ire1 == NULL) {
24617 				multirt_send = B_FALSE;
24618 			}
24619 		}
24620 
24621 		ll_hdr_len = 0;
24622 		LOCK_IRE_FP_MP(ire);
24623 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24624 		if (ll_hdr_mp != NULL) {
24625 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24626 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24627 		} else {
24628 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24629 		}
24630 
24631 		/* If there is a transmit header, get a copy for this frag. */
24632 		/*
24633 		 * TODO: should check db_ref before calling ip_carve_mp since
24634 		 * it might give us a dup.
24635 		 */
24636 		if (!ll_hdr_mp) {
24637 			/* No xmit header. */
24638 			xmit_mp = mp;
24639 
24640 		/* We have a link-layer header that can fit in our mblk. */
24641 		} else if (mp->b_datap->db_ref == 1 &&
24642 		    ll_hdr_len != 0 &&
24643 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24644 			/* M_DATA fastpath */
24645 			mp->b_rptr -= ll_hdr_len;
24646 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24647 			xmit_mp = mp;
24648 
24649 		/* Corner case if copyb has failed */
24650 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24651 			UNLOCK_IRE_FP_MP(ire);
24652 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24653 			freeb(hdr_mp);
24654 			freemsg(mp);
24655 			freemsg(mp_orig);
24656 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24657 			    "ip_wput_frag_end:(%S)",
24658 			    "discard");
24659 
24660 			if (multirt_send) {
24661 				ASSERT(ire1);
24662 				ASSERT(next_mp);
24663 
24664 				freemsg(next_mp);
24665 				ire_refrele(ire1);
24666 			}
24667 			if (save_ire != NULL)
24668 				IRE_REFRELE(save_ire);
24669 
24670 			if (first_ire != NULL)
24671 				ire_refrele(first_ire);
24672 			return;
24673 
24674 		/*
24675 		 * Case of res_mp OR the fastpath mp can't fit
24676 		 * in the mblk
24677 		 */
24678 		} else {
24679 			xmit_mp->b_cont = mp;
24680 			if (DB_CRED(mp) != NULL)
24681 				mblk_setcred(xmit_mp, DB_CRED(mp));
24682 			/*
24683 			 * Get priority marking, if any.
24684 			 * We propagate the CoS marking from the
24685 			 * original packet that went to QoS processing
24686 			 * in ip_wput_ire to the newly carved mp.
24687 			 */
24688 			if (DB_TYPE(xmit_mp) == M_DATA)
24689 				xmit_mp->b_band = mp->b_band;
24690 		}
24691 		UNLOCK_IRE_FP_MP(ire);
24692 
24693 		q = ire->ire_stq;
24694 		out_ill = (ill_t *)q->q_ptr;
24695 
24696 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24697 
24698 		DTRACE_PROBE4(ip4__physical__out__start,
24699 		    ill_t *, NULL, ill_t *, out_ill,
24700 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24701 
24702 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24703 		    ipst->ips_ipv4firewall_physical_out,
24704 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24705 
24706 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24707 
24708 		if (xmit_mp != NULL) {
24709 			putnext(q, xmit_mp);
24710 
24711 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24712 			UPDATE_MIB(out_ill->ill_ip_mib,
24713 			    ipIfStatsHCOutOctets, i1);
24714 
24715 			if (pkt_type != OB_PKT) {
24716 				/*
24717 				 * Update the packet count and MIB stats
24718 				 * of trailing RTF_MULTIRT ires.
24719 				 */
24720 				UPDATE_OB_PKT_COUNT(ire);
24721 				BUMP_MIB(out_ill->ill_ip_mib,
24722 				    ipIfStatsOutFragReqds);
24723 			}
24724 		}
24725 
24726 		if (multirt_send) {
24727 			/*
24728 			 * We are in a multiple send case; look for
24729 			 * the next ire and re-enter the loop.
24730 			 */
24731 			ASSERT(ire1);
24732 			ASSERT(next_mp);
24733 			/* REFRELE the current ire before looping */
24734 			ire_refrele(ire);
24735 			ire = ire1;
24736 			ire1 = NULL;
24737 			mp = next_mp;
24738 			next_mp = NULL;
24739 		}
24740 	} while (multirt_send);
24741 
24742 	ASSERT(ire1 == NULL);
24743 
24744 	/* Restore the original ire; we need it for the trailing frags */
24745 	if (save_ire != NULL) {
24746 		/* REFRELE the last iterated ire */
24747 		ire_refrele(ire);
24748 		/* save_ire has been REFHOLDed */
24749 		ire = save_ire;
24750 		save_ire = NULL;
24751 		q = ire->ire_stq;
24752 	}
24753 
24754 	if (pkt_type == OB_PKT) {
24755 		UPDATE_OB_PKT_COUNT(ire);
24756 	} else {
24757 		out_ill = (ill_t *)q->q_ptr;
24758 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24759 		UPDATE_IB_PKT_COUNT(ire);
24760 	}
24761 
24762 	/* Advance the offset to the second frag starting point. */
24763 	offset += len;
24764 	/*
24765 	 * Update hdr_len from the copied header - there might be less options
24766 	 * in the later fragments.
24767 	 */
24768 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24769 	/* Loop until done. */
24770 	for (;;) {
24771 		uint16_t	offset_and_flags;
24772 		uint16_t	ip_len;
24773 
24774 		if (ip_data_end - offset > len) {
24775 			/*
24776 			 * Carve off the appropriate amount from the original
24777 			 * datagram.
24778 			 */
24779 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24780 				mp = NULL;
24781 				break;
24782 			}
24783 			/*
24784 			 * More frags after this one.  Get another copy
24785 			 * of the header.
24786 			 */
24787 			if (carve_mp->b_datap->db_ref == 1 &&
24788 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24789 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24790 				/* Inline IP header */
24791 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24792 				    hdr_mp->b_rptr;
24793 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24794 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24795 				mp = carve_mp;
24796 			} else {
24797 				if (!(mp = copyb(hdr_mp))) {
24798 					freemsg(carve_mp);
24799 					break;
24800 				}
24801 				/* Get priority marking, if any. */
24802 				mp->b_band = carve_mp->b_band;
24803 				mp->b_cont = carve_mp;
24804 			}
24805 			ipha = (ipha_t *)mp->b_rptr;
24806 			offset_and_flags = IPH_MF;
24807 		} else {
24808 			/*
24809 			 * Last frag.  Consume the header. Set len to
24810 			 * the length of this last piece.
24811 			 */
24812 			len = ip_data_end - offset;
24813 
24814 			/*
24815 			 * Carve off the appropriate amount from the original
24816 			 * datagram.
24817 			 */
24818 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24819 				mp = NULL;
24820 				break;
24821 			}
24822 			if (carve_mp->b_datap->db_ref == 1 &&
24823 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24824 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24825 				/* Inline IP header */
24826 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24827 				    hdr_mp->b_rptr;
24828 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24829 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24830 				mp = carve_mp;
24831 				freeb(hdr_mp);
24832 				hdr_mp = mp;
24833 			} else {
24834 				mp = hdr_mp;
24835 				/* Get priority marking, if any. */
24836 				mp->b_band = carve_mp->b_band;
24837 				mp->b_cont = carve_mp;
24838 			}
24839 			ipha = (ipha_t *)mp->b_rptr;
24840 			/* A frag of a frag might have IPH_MF non-zero */
24841 			offset_and_flags =
24842 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24843 			    IPH_MF;
24844 		}
24845 		offset_and_flags |= (uint16_t)(offset >> 3);
24846 		offset_and_flags |= (uint16_t)frag_flag;
24847 		/* Store the offset and flags in the IP header. */
24848 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24849 
24850 		/* Store the length in the IP header. */
24851 		ip_len = (uint16_t)(len + hdr_len);
24852 		ipha->ipha_length = htons(ip_len);
24853 
24854 		/*
24855 		 * Set the IP header checksum.	Note that mp is just
24856 		 * the header, so this is easy to pass to ip_csum.
24857 		 */
24858 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24859 
24860 		/* Attach a transmit header, if any, and ship it. */
24861 		if (pkt_type == OB_PKT) {
24862 			UPDATE_OB_PKT_COUNT(ire);
24863 		} else {
24864 			out_ill = (ill_t *)q->q_ptr;
24865 			BUMP_MIB(out_ill->ill_ip_mib,
24866 			    ipIfStatsHCOutForwDatagrams);
24867 			UPDATE_IB_PKT_COUNT(ire);
24868 		}
24869 
24870 		if (ire->ire_flags & RTF_MULTIRT) {
24871 			irb = ire->ire_bucket;
24872 			ASSERT(irb != NULL);
24873 
24874 			multirt_send = B_TRUE;
24875 
24876 			/*
24877 			 * Save the original ire; we will need to restore it
24878 			 * for the tailing frags.
24879 			 */
24880 			save_ire = ire;
24881 			IRE_REFHOLD(save_ire);
24882 		}
24883 		/*
24884 		 * Emission loop for this fragment, similar
24885 		 * to what is done for the first fragment.
24886 		 */
24887 		do {
24888 			if (multirt_send) {
24889 				/*
24890 				 * We are in a multiple send case, need to get
24891 				 * the next ire and make a copy of the packet.
24892 				 */
24893 				ASSERT(irb != NULL);
24894 				IRB_REFHOLD(irb);
24895 				for (ire1 = ire->ire_next;
24896 				    ire1 != NULL;
24897 				    ire1 = ire1->ire_next) {
24898 					if (!(ire1->ire_flags & RTF_MULTIRT))
24899 						continue;
24900 					if (ire1->ire_addr != ire->ire_addr)
24901 						continue;
24902 					if (ire1->ire_marks &
24903 					    (IRE_MARK_CONDEMNED|
24904 					    IRE_MARK_HIDDEN)) {
24905 						continue;
24906 					}
24907 					/*
24908 					 * Ensure we do not exceed the MTU
24909 					 * of the next route.
24910 					 */
24911 					if (ire1->ire_max_frag < max_frag) {
24912 						ip_multirt_bad_mtu(ire1,
24913 						    max_frag);
24914 						continue;
24915 					}
24916 
24917 					/* Got one. */
24918 					IRE_REFHOLD(ire1);
24919 					break;
24920 				}
24921 				IRB_REFRELE(irb);
24922 
24923 				if (ire1 != NULL) {
24924 					next_mp = copyb(mp);
24925 					if ((next_mp == NULL) ||
24926 					    ((mp->b_cont != NULL) &&
24927 					    ((next_mp->b_cont =
24928 					    dupmsg(mp->b_cont)) == NULL))) {
24929 						freemsg(next_mp);
24930 						next_mp = NULL;
24931 						ire_refrele(ire1);
24932 						ire1 = NULL;
24933 					}
24934 				}
24935 
24936 				/* Last multiroute ire; don't loop anymore. */
24937 				if (ire1 == NULL) {
24938 					multirt_send = B_FALSE;
24939 				}
24940 			}
24941 
24942 			/* Update transmit header */
24943 			ll_hdr_len = 0;
24944 			LOCK_IRE_FP_MP(ire);
24945 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24946 			if (ll_hdr_mp != NULL) {
24947 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24948 				ll_hdr_len = MBLKL(ll_hdr_mp);
24949 			} else {
24950 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24951 			}
24952 
24953 			if (!ll_hdr_mp) {
24954 				xmit_mp = mp;
24955 
24956 			/*
24957 			 * We have link-layer header that can fit in
24958 			 * our mblk.
24959 			 */
24960 			} else if (mp->b_datap->db_ref == 1 &&
24961 			    ll_hdr_len != 0 &&
24962 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24963 				/* M_DATA fastpath */
24964 				mp->b_rptr -= ll_hdr_len;
24965 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24966 				    ll_hdr_len);
24967 				xmit_mp = mp;
24968 
24969 			/*
24970 			 * Case of res_mp OR the fastpath mp can't fit
24971 			 * in the mblk
24972 			 */
24973 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24974 				xmit_mp->b_cont = mp;
24975 				if (DB_CRED(mp) != NULL)
24976 					mblk_setcred(xmit_mp, DB_CRED(mp));
24977 				/* Get priority marking, if any. */
24978 				if (DB_TYPE(xmit_mp) == M_DATA)
24979 					xmit_mp->b_band = mp->b_band;
24980 
24981 			/* Corner case if copyb failed */
24982 			} else {
24983 				/*
24984 				 * Exit both the replication and
24985 				 * fragmentation loops.
24986 				 */
24987 				UNLOCK_IRE_FP_MP(ire);
24988 				goto drop_pkt;
24989 			}
24990 			UNLOCK_IRE_FP_MP(ire);
24991 
24992 			mp1 = mp;
24993 			out_ill = (ill_t *)q->q_ptr;
24994 
24995 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24996 
24997 			DTRACE_PROBE4(ip4__physical__out__start,
24998 			    ill_t *, NULL, ill_t *, out_ill,
24999 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25000 
25001 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25002 			    ipst->ips_ipv4firewall_physical_out,
25003 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25004 
25005 			DTRACE_PROBE1(ip4__physical__out__end,
25006 			    mblk_t *, xmit_mp);
25007 
25008 			if (mp != mp1 && hdr_mp == mp1)
25009 				hdr_mp = mp;
25010 			if (mp != mp1 && mp_orig == mp1)
25011 				mp_orig = mp;
25012 
25013 			if (xmit_mp != NULL) {
25014 				putnext(q, xmit_mp);
25015 
25016 				BUMP_MIB(out_ill->ill_ip_mib,
25017 				    ipIfStatsHCOutTransmits);
25018 				UPDATE_MIB(out_ill->ill_ip_mib,
25019 				    ipIfStatsHCOutOctets, ip_len);
25020 
25021 				if (pkt_type != OB_PKT) {
25022 					/*
25023 					 * Update the packet count of trailing
25024 					 * RTF_MULTIRT ires.
25025 					 */
25026 					UPDATE_OB_PKT_COUNT(ire);
25027 				}
25028 			}
25029 
25030 			/* All done if we just consumed the hdr_mp. */
25031 			if (mp == hdr_mp) {
25032 				last_frag = B_TRUE;
25033 				BUMP_MIB(out_ill->ill_ip_mib,
25034 				    ipIfStatsOutFragOKs);
25035 			}
25036 
25037 			if (multirt_send) {
25038 				/*
25039 				 * We are in a multiple send case; look for
25040 				 * the next ire and re-enter the loop.
25041 				 */
25042 				ASSERT(ire1);
25043 				ASSERT(next_mp);
25044 				/* REFRELE the current ire before looping */
25045 				ire_refrele(ire);
25046 				ire = ire1;
25047 				ire1 = NULL;
25048 				q = ire->ire_stq;
25049 				mp = next_mp;
25050 				next_mp = NULL;
25051 			}
25052 		} while (multirt_send);
25053 		/*
25054 		 * Restore the original ire; we need it for the
25055 		 * trailing frags
25056 		 */
25057 		if (save_ire != NULL) {
25058 			ASSERT(ire1 == NULL);
25059 			/* REFRELE the last iterated ire */
25060 			ire_refrele(ire);
25061 			/* save_ire has been REFHOLDed */
25062 			ire = save_ire;
25063 			q = ire->ire_stq;
25064 			save_ire = NULL;
25065 		}
25066 
25067 		if (last_frag) {
25068 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25069 			    "ip_wput_frag_end:(%S)",
25070 			    "consumed hdr_mp");
25071 
25072 			if (first_ire != NULL)
25073 				ire_refrele(first_ire);
25074 			return;
25075 		}
25076 		/* Otherwise, advance and loop. */
25077 		offset += len;
25078 	}
25079 
25080 drop_pkt:
25081 	/* Clean up following allocation failure. */
25082 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25083 	freemsg(mp);
25084 	if (mp != hdr_mp)
25085 		freeb(hdr_mp);
25086 	if (mp != mp_orig)
25087 		freemsg(mp_orig);
25088 
25089 	if (save_ire != NULL)
25090 		IRE_REFRELE(save_ire);
25091 	if (first_ire != NULL)
25092 		ire_refrele(first_ire);
25093 
25094 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25095 	    "ip_wput_frag_end:(%S)",
25096 	    "end--alloc failure");
25097 }
25098 
25099 /*
25100  * Copy the header plus those options which have the copy bit set
25101  */
25102 static mblk_t *
25103 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25104 {
25105 	mblk_t	*mp;
25106 	uchar_t	*up;
25107 
25108 	/*
25109 	 * Quick check if we need to look for options without the copy bit
25110 	 * set
25111 	 */
25112 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25113 	if (!mp)
25114 		return (mp);
25115 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25116 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25117 		bcopy(rptr, mp->b_rptr, hdr_len);
25118 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25119 		return (mp);
25120 	}
25121 	up  = mp->b_rptr;
25122 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25123 	up += IP_SIMPLE_HDR_LENGTH;
25124 	rptr += IP_SIMPLE_HDR_LENGTH;
25125 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25126 	while (hdr_len > 0) {
25127 		uint32_t optval;
25128 		uint32_t optlen;
25129 
25130 		optval = *rptr;
25131 		if (optval == IPOPT_EOL)
25132 			break;
25133 		if (optval == IPOPT_NOP)
25134 			optlen = 1;
25135 		else
25136 			optlen = rptr[1];
25137 		if (optval & IPOPT_COPY) {
25138 			bcopy(rptr, up, optlen);
25139 			up += optlen;
25140 		}
25141 		rptr += optlen;
25142 		hdr_len -= optlen;
25143 	}
25144 	/*
25145 	 * Make sure that we drop an even number of words by filling
25146 	 * with EOL to the next word boundary.
25147 	 */
25148 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25149 	    hdr_len & 0x3; hdr_len++)
25150 		*up++ = IPOPT_EOL;
25151 	mp->b_wptr = up;
25152 	/* Update header length */
25153 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25154 	return (mp);
25155 }
25156 
25157 /*
25158  * Delivery to local recipients including fanout to multiple recipients.
25159  * Does not do checksumming of UDP/TCP.
25160  * Note: q should be the read side queue for either the ill or conn.
25161  * Note: rq should be the read side q for the lower (ill) stream.
25162  * We don't send packets to IPPF processing, thus the last argument
25163  * to all the fanout calls are B_FALSE.
25164  */
25165 void
25166 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25167     int fanout_flags, zoneid_t zoneid)
25168 {
25169 	uint32_t	protocol;
25170 	mblk_t		*first_mp;
25171 	boolean_t	mctl_present;
25172 	int		ire_type;
25173 #define	rptr	((uchar_t *)ipha)
25174 	ip_stack_t	*ipst = ill->ill_ipst;
25175 
25176 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25177 	    "ip_wput_local_start: q %p", q);
25178 
25179 	if (ire != NULL) {
25180 		ire_type = ire->ire_type;
25181 	} else {
25182 		/*
25183 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25184 		 * packet is not multicast, we can't tell the ire type.
25185 		 */
25186 		ASSERT(CLASSD(ipha->ipha_dst));
25187 		ire_type = IRE_BROADCAST;
25188 	}
25189 
25190 	first_mp = mp;
25191 	if (first_mp->b_datap->db_type == M_CTL) {
25192 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25193 		if (!io->ipsec_out_secure) {
25194 			/*
25195 			 * This ipsec_out_t was allocated in ip_wput
25196 			 * for multicast packets to store the ill_index.
25197 			 * As this is being delivered locally, we don't
25198 			 * need this anymore.
25199 			 */
25200 			mp = first_mp->b_cont;
25201 			freeb(first_mp);
25202 			first_mp = mp;
25203 			mctl_present = B_FALSE;
25204 		} else {
25205 			/*
25206 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25207 			 * security properties for the looped-back packet.
25208 			 */
25209 			mctl_present = B_TRUE;
25210 			mp = first_mp->b_cont;
25211 			ASSERT(mp != NULL);
25212 			ipsec_out_to_in(first_mp);
25213 		}
25214 	} else {
25215 		mctl_present = B_FALSE;
25216 	}
25217 
25218 	DTRACE_PROBE4(ip4__loopback__in__start,
25219 	    ill_t *, ill, ill_t *, NULL,
25220 	    ipha_t *, ipha, mblk_t *, first_mp);
25221 
25222 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25223 	    ipst->ips_ipv4firewall_loopback_in,
25224 	    ill, NULL, ipha, first_mp, mp, ipst);
25225 
25226 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25227 
25228 	if (first_mp == NULL)
25229 		return;
25230 
25231 	ipst->ips_loopback_packets++;
25232 
25233 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25234 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25235 	if (!IS_SIMPLE_IPH(ipha)) {
25236 		ip_wput_local_options(ipha, ipst);
25237 	}
25238 
25239 	protocol = ipha->ipha_protocol;
25240 	switch (protocol) {
25241 	case IPPROTO_ICMP: {
25242 		ire_t		*ire_zone;
25243 		ilm_t		*ilm;
25244 		mblk_t		*mp1;
25245 		zoneid_t	last_zoneid;
25246 
25247 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25248 			ASSERT(ire_type == IRE_BROADCAST);
25249 			/*
25250 			 * In the multicast case, applications may have joined
25251 			 * the group from different zones, so we need to deliver
25252 			 * the packet to each of them. Loop through the
25253 			 * multicast memberships structures (ilm) on the receive
25254 			 * ill and send a copy of the packet up each matching
25255 			 * one. However, we don't do this for multicasts sent on
25256 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25257 			 * they must stay in the sender's zone.
25258 			 *
25259 			 * ilm_add_v6() ensures that ilms in the same zone are
25260 			 * contiguous in the ill_ilm list. We use this property
25261 			 * to avoid sending duplicates needed when two
25262 			 * applications in the same zone join the same group on
25263 			 * different logical interfaces: we ignore the ilm if
25264 			 * it's zoneid is the same as the last matching one.
25265 			 * In addition, the sending of the packet for
25266 			 * ire_zoneid is delayed until all of the other ilms
25267 			 * have been exhausted.
25268 			 */
25269 			last_zoneid = -1;
25270 			ILM_WALKER_HOLD(ill);
25271 			for (ilm = ill->ill_ilm; ilm != NULL;
25272 			    ilm = ilm->ilm_next) {
25273 				if ((ilm->ilm_flags & ILM_DELETED) ||
25274 				    ipha->ipha_dst != ilm->ilm_addr ||
25275 				    ilm->ilm_zoneid == last_zoneid ||
25276 				    ilm->ilm_zoneid == zoneid ||
25277 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25278 					continue;
25279 				mp1 = ip_copymsg(first_mp);
25280 				if (mp1 == NULL)
25281 					continue;
25282 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25283 				    mctl_present, B_FALSE, ill,
25284 				    ilm->ilm_zoneid);
25285 				last_zoneid = ilm->ilm_zoneid;
25286 			}
25287 			ILM_WALKER_RELE(ill);
25288 			/*
25289 			 * Loopback case: the sending endpoint has
25290 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25291 			 * dispatch the multicast packet to the sending zone.
25292 			 */
25293 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25294 				freemsg(first_mp);
25295 				return;
25296 			}
25297 		} else if (ire_type == IRE_BROADCAST) {
25298 			/*
25299 			 * In the broadcast case, there may be many zones
25300 			 * which need a copy of the packet delivered to them.
25301 			 * There is one IRE_BROADCAST per broadcast address
25302 			 * and per zone; we walk those using a helper function.
25303 			 * In addition, the sending of the packet for zoneid is
25304 			 * delayed until all of the other ires have been
25305 			 * processed.
25306 			 */
25307 			IRB_REFHOLD(ire->ire_bucket);
25308 			ire_zone = NULL;
25309 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25310 			    ire)) != NULL) {
25311 				mp1 = ip_copymsg(first_mp);
25312 				if (mp1 == NULL)
25313 					continue;
25314 
25315 				UPDATE_IB_PKT_COUNT(ire_zone);
25316 				ire_zone->ire_last_used_time = lbolt;
25317 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25318 				    mctl_present, B_FALSE, ill,
25319 				    ire_zone->ire_zoneid);
25320 			}
25321 			IRB_REFRELE(ire->ire_bucket);
25322 		}
25323 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25324 		    0, mctl_present, B_FALSE, ill, zoneid);
25325 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25326 		    "ip_wput_local_end: q %p (%S)",
25327 		    q, "icmp");
25328 		return;
25329 	}
25330 	case IPPROTO_IGMP:
25331 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25332 			/* Bad packet - discarded by igmp_input */
25333 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25334 			    "ip_wput_local_end: q %p (%S)",
25335 			    q, "igmp_input--bad packet");
25336 			if (mctl_present)
25337 				freeb(first_mp);
25338 			return;
25339 		}
25340 		/*
25341 		 * igmp_input() may have returned the pulled up message.
25342 		 * So first_mp and ipha need to be reinitialized.
25343 		 */
25344 		ipha = (ipha_t *)mp->b_rptr;
25345 		if (mctl_present)
25346 			first_mp->b_cont = mp;
25347 		else
25348 			first_mp = mp;
25349 		/* deliver to local raw users */
25350 		break;
25351 	case IPPROTO_ENCAP:
25352 		/*
25353 		 * This case is covered by either ip_fanout_proto, or by
25354 		 * the above security processing for self-tunneled packets.
25355 		 */
25356 		break;
25357 	case IPPROTO_UDP: {
25358 		uint16_t	*up;
25359 		uint32_t	ports;
25360 
25361 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25362 		    UDP_PORTS_OFFSET);
25363 		/* Force a 'valid' checksum. */
25364 		up[3] = 0;
25365 
25366 		ports = *(uint32_t *)up;
25367 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25368 		    (ire_type == IRE_BROADCAST),
25369 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25370 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25371 		    ill, zoneid);
25372 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25373 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25374 		return;
25375 	}
25376 	case IPPROTO_TCP: {
25377 
25378 		/*
25379 		 * For TCP, discard broadcast packets.
25380 		 */
25381 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25382 			freemsg(first_mp);
25383 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25384 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25385 			return;
25386 		}
25387 
25388 		if (mp->b_datap->db_type == M_DATA) {
25389 			/*
25390 			 * M_DATA mblk, so init mblk (chain) for no struio().
25391 			 */
25392 			mblk_t	*mp1 = mp;
25393 
25394 			do {
25395 				mp1->b_datap->db_struioflag = 0;
25396 			} while ((mp1 = mp1->b_cont) != NULL);
25397 		}
25398 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25399 		    <= mp->b_wptr);
25400 		ip_fanout_tcp(q, first_mp, ill, ipha,
25401 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25402 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25403 		    mctl_present, B_FALSE, zoneid);
25404 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25405 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25406 		return;
25407 	}
25408 	case IPPROTO_SCTP:
25409 	{
25410 		uint32_t	ports;
25411 
25412 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25413 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25414 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25415 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25416 		return;
25417 	}
25418 
25419 	default:
25420 		break;
25421 	}
25422 	/*
25423 	 * Find a client for some other protocol.  We give
25424 	 * copies to multiple clients, if more than one is
25425 	 * bound.
25426 	 */
25427 	ip_fanout_proto(q, first_mp, ill, ipha,
25428 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25429 	    mctl_present, B_FALSE, ill, zoneid);
25430 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25431 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25432 #undef	rptr
25433 }
25434 
25435 /*
25436  * Update any source route, record route, or timestamp options.
25437  * Check that we are at end of strict source route.
25438  * The options have been sanity checked by ip_wput_options().
25439  */
25440 static void
25441 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25442 {
25443 	ipoptp_t	opts;
25444 	uchar_t		*opt;
25445 	uint8_t		optval;
25446 	uint8_t		optlen;
25447 	ipaddr_t	dst;
25448 	uint32_t	ts;
25449 	ire_t		*ire;
25450 	timestruc_t	now;
25451 
25452 	ip2dbg(("ip_wput_local_options\n"));
25453 	for (optval = ipoptp_first(&opts, ipha);
25454 	    optval != IPOPT_EOL;
25455 	    optval = ipoptp_next(&opts)) {
25456 		opt = opts.ipoptp_cur;
25457 		optlen = opts.ipoptp_len;
25458 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25459 		switch (optval) {
25460 			uint32_t off;
25461 		case IPOPT_SSRR:
25462 		case IPOPT_LSRR:
25463 			off = opt[IPOPT_OFFSET];
25464 			off--;
25465 			if (optlen < IP_ADDR_LEN ||
25466 			    off > optlen - IP_ADDR_LEN) {
25467 				/* End of source route */
25468 				break;
25469 			}
25470 			/*
25471 			 * This will only happen if two consecutive entries
25472 			 * in the source route contains our address or if
25473 			 * it is a packet with a loose source route which
25474 			 * reaches us before consuming the whole source route
25475 			 */
25476 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25477 			if (optval == IPOPT_SSRR) {
25478 				return;
25479 			}
25480 			/*
25481 			 * Hack: instead of dropping the packet truncate the
25482 			 * source route to what has been used by filling the
25483 			 * rest with IPOPT_NOP.
25484 			 */
25485 			opt[IPOPT_OLEN] = (uint8_t)off;
25486 			while (off < optlen) {
25487 				opt[off++] = IPOPT_NOP;
25488 			}
25489 			break;
25490 		case IPOPT_RR:
25491 			off = opt[IPOPT_OFFSET];
25492 			off--;
25493 			if (optlen < IP_ADDR_LEN ||
25494 			    off > optlen - IP_ADDR_LEN) {
25495 				/* No more room - ignore */
25496 				ip1dbg((
25497 				    "ip_wput_forward_options: end of RR\n"));
25498 				break;
25499 			}
25500 			dst = htonl(INADDR_LOOPBACK);
25501 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25502 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25503 			break;
25504 		case IPOPT_TS:
25505 			/* Insert timestamp if there is romm */
25506 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25507 			case IPOPT_TS_TSONLY:
25508 				off = IPOPT_TS_TIMELEN;
25509 				break;
25510 			case IPOPT_TS_PRESPEC:
25511 			case IPOPT_TS_PRESPEC_RFC791:
25512 				/* Verify that the address matched */
25513 				off = opt[IPOPT_OFFSET] - 1;
25514 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25515 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25516 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25517 				    ipst);
25518 				if (ire == NULL) {
25519 					/* Not for us */
25520 					break;
25521 				}
25522 				ire_refrele(ire);
25523 				/* FALLTHRU */
25524 			case IPOPT_TS_TSANDADDR:
25525 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25526 				break;
25527 			default:
25528 				/*
25529 				 * ip_*put_options should have already
25530 				 * dropped this packet.
25531 				 */
25532 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25533 				    "unknown IT - bug in ip_wput_options?\n");
25534 				return;	/* Keep "lint" happy */
25535 			}
25536 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25537 				/* Increase overflow counter */
25538 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25539 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25540 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25541 				    (off << 4);
25542 				break;
25543 			}
25544 			off = opt[IPOPT_OFFSET] - 1;
25545 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25546 			case IPOPT_TS_PRESPEC:
25547 			case IPOPT_TS_PRESPEC_RFC791:
25548 			case IPOPT_TS_TSANDADDR:
25549 				dst = htonl(INADDR_LOOPBACK);
25550 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25551 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25552 				/* FALLTHRU */
25553 			case IPOPT_TS_TSONLY:
25554 				off = opt[IPOPT_OFFSET] - 1;
25555 				/* Compute # of milliseconds since midnight */
25556 				gethrestime(&now);
25557 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25558 				    now.tv_nsec / (NANOSEC / MILLISEC);
25559 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25560 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25561 				break;
25562 			}
25563 			break;
25564 		}
25565 	}
25566 }
25567 
25568 /*
25569  * Send out a multicast packet on interface ipif.
25570  * The sender does not have an conn.
25571  * Caller verifies that this isn't a PHYI_LOOPBACK.
25572  */
25573 void
25574 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25575 {
25576 	ipha_t	*ipha;
25577 	ire_t	*ire;
25578 	ipaddr_t	dst;
25579 	mblk_t		*first_mp;
25580 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25581 
25582 	/* igmp_sendpkt always allocates a ipsec_out_t */
25583 	ASSERT(mp->b_datap->db_type == M_CTL);
25584 	ASSERT(!ipif->ipif_isv6);
25585 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25586 
25587 	first_mp = mp;
25588 	mp = first_mp->b_cont;
25589 	ASSERT(mp->b_datap->db_type == M_DATA);
25590 	ipha = (ipha_t *)mp->b_rptr;
25591 
25592 	/*
25593 	 * Find an IRE which matches the destination and the outgoing
25594 	 * queue (i.e. the outgoing interface.)
25595 	 */
25596 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25597 		dst = ipif->ipif_pp_dst_addr;
25598 	else
25599 		dst = ipha->ipha_dst;
25600 	/*
25601 	 * The source address has already been initialized by the
25602 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25603 	 * be sufficient rather than MATCH_IRE_IPIF.
25604 	 *
25605 	 * This function is used for sending IGMP packets. We need
25606 	 * to make sure that we send the packet out of the interface
25607 	 * (ipif->ipif_ill) where we joined the group. This is to
25608 	 * prevent from switches doing IGMP snooping to send us multicast
25609 	 * packets for a given group on the interface we have joined.
25610 	 * If we can't find an ire, igmp_sendpkt has already initialized
25611 	 * ipsec_out_attach_if so that this will not be load spread in
25612 	 * ip_newroute_ipif.
25613 	 */
25614 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25615 	    MATCH_IRE_ILL, ipst);
25616 	if (!ire) {
25617 		/*
25618 		 * Mark this packet to make it be delivered to
25619 		 * ip_wput_ire after the new ire has been
25620 		 * created.
25621 		 */
25622 		mp->b_prev = NULL;
25623 		mp->b_next = NULL;
25624 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25625 		    zoneid, &zero_info);
25626 		return;
25627 	}
25628 
25629 	/*
25630 	 * Honor the RTF_SETSRC flag; this is the only case
25631 	 * where we force this addr whatever the current src addr is,
25632 	 * because this address is set by igmp_sendpkt(), and
25633 	 * cannot be specified by any user.
25634 	 */
25635 	if (ire->ire_flags & RTF_SETSRC) {
25636 		ipha->ipha_src = ire->ire_src_addr;
25637 	}
25638 
25639 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25640 }
25641 
25642 /*
25643  * NOTE : This function does not ire_refrele the ire argument passed in.
25644  *
25645  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25646  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25647  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25648  * the ire_lock to access the nce_fp_mp in this case.
25649  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25650  * prepending a fastpath message IPQoS processing must precede it, we also set
25651  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25652  * (IPQoS might have set the b_band for CoS marking).
25653  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25654  * must follow it so that IPQoS can mark the dl_priority field for CoS
25655  * marking, if needed.
25656  */
25657 static mblk_t *
25658 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25659 {
25660 	uint_t	hlen;
25661 	ipha_t *ipha;
25662 	mblk_t *mp1;
25663 	boolean_t qos_done = B_FALSE;
25664 	uchar_t	*ll_hdr;
25665 	ip_stack_t	*ipst = ire->ire_ipst;
25666 
25667 #define	rptr	((uchar_t *)ipha)
25668 
25669 	ipha = (ipha_t *)mp->b_rptr;
25670 	hlen = 0;
25671 	LOCK_IRE_FP_MP(ire);
25672 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25673 		ASSERT(DB_TYPE(mp1) == M_DATA);
25674 		/* Initiate IPPF processing */
25675 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25676 			UNLOCK_IRE_FP_MP(ire);
25677 			ip_process(proc, &mp, ill_index);
25678 			if (mp == NULL)
25679 				return (NULL);
25680 
25681 			ipha = (ipha_t *)mp->b_rptr;
25682 			LOCK_IRE_FP_MP(ire);
25683 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25684 				qos_done = B_TRUE;
25685 				goto no_fp_mp;
25686 			}
25687 			ASSERT(DB_TYPE(mp1) == M_DATA);
25688 		}
25689 		hlen = MBLKL(mp1);
25690 		/*
25691 		 * Check if we have enough room to prepend fastpath
25692 		 * header
25693 		 */
25694 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25695 			ll_hdr = rptr - hlen;
25696 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25697 			/*
25698 			 * Set the b_rptr to the start of the link layer
25699 			 * header
25700 			 */
25701 			mp->b_rptr = ll_hdr;
25702 			mp1 = mp;
25703 		} else {
25704 			mp1 = copyb(mp1);
25705 			if (mp1 == NULL)
25706 				goto unlock_err;
25707 			mp1->b_band = mp->b_band;
25708 			mp1->b_cont = mp;
25709 			/*
25710 			 * certain system generated traffic may not
25711 			 * have cred/label in ip header block. This
25712 			 * is true even for a labeled system. But for
25713 			 * labeled traffic, inherit the label in the
25714 			 * new header.
25715 			 */
25716 			if (DB_CRED(mp) != NULL)
25717 				mblk_setcred(mp1, DB_CRED(mp));
25718 			/*
25719 			 * XXX disable ICK_VALID and compute checksum
25720 			 * here; can happen if nce_fp_mp changes and
25721 			 * it can't be copied now due to insufficient
25722 			 * space. (unlikely, fp mp can change, but it
25723 			 * does not increase in length)
25724 			 */
25725 		}
25726 		UNLOCK_IRE_FP_MP(ire);
25727 	} else {
25728 no_fp_mp:
25729 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25730 		if (mp1 == NULL) {
25731 unlock_err:
25732 			UNLOCK_IRE_FP_MP(ire);
25733 			freemsg(mp);
25734 			return (NULL);
25735 		}
25736 		UNLOCK_IRE_FP_MP(ire);
25737 		mp1->b_cont = mp;
25738 		/*
25739 		 * certain system generated traffic may not
25740 		 * have cred/label in ip header block. This
25741 		 * is true even for a labeled system. But for
25742 		 * labeled traffic, inherit the label in the
25743 		 * new header.
25744 		 */
25745 		if (DB_CRED(mp) != NULL)
25746 			mblk_setcred(mp1, DB_CRED(mp));
25747 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25748 			ip_process(proc, &mp1, ill_index);
25749 			if (mp1 == NULL)
25750 				return (NULL);
25751 		}
25752 	}
25753 	return (mp1);
25754 #undef rptr
25755 }
25756 
25757 /*
25758  * Finish the outbound IPsec processing for an IPv6 packet. This function
25759  * is called from ipsec_out_process() if the IPsec packet was processed
25760  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25761  * asynchronously.
25762  */
25763 void
25764 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25765     ire_t *ire_arg)
25766 {
25767 	in6_addr_t *v6dstp;
25768 	ire_t *ire;
25769 	mblk_t *mp;
25770 	ip6_t *ip6h1;
25771 	uint_t	ill_index;
25772 	ipsec_out_t *io;
25773 	boolean_t attach_if, hwaccel;
25774 	uint32_t flags = IP6_NO_IPPOLICY;
25775 	int match_flags;
25776 	zoneid_t zoneid;
25777 	boolean_t ill_need_rele = B_FALSE;
25778 	boolean_t ire_need_rele = B_FALSE;
25779 	ip_stack_t	*ipst;
25780 
25781 	mp = ipsec_mp->b_cont;
25782 	ip6h1 = (ip6_t *)mp->b_rptr;
25783 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25784 	ASSERT(io->ipsec_out_ns != NULL);
25785 	ipst = io->ipsec_out_ns->netstack_ip;
25786 	ill_index = io->ipsec_out_ill_index;
25787 	if (io->ipsec_out_reachable) {
25788 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25789 	}
25790 	attach_if = io->ipsec_out_attach_if;
25791 	hwaccel = io->ipsec_out_accelerated;
25792 	zoneid = io->ipsec_out_zoneid;
25793 	ASSERT(zoneid != ALL_ZONES);
25794 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25795 	/* Multicast addresses should have non-zero ill_index. */
25796 	v6dstp = &ip6h->ip6_dst;
25797 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25798 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25799 	ASSERT(!attach_if || ill_index != 0);
25800 	if (ill_index != 0) {
25801 		if (ill == NULL) {
25802 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25803 			    B_TRUE, ipst);
25804 
25805 			/* Failure case frees things for us. */
25806 			if (ill == NULL)
25807 				return;
25808 
25809 			ill_need_rele = B_TRUE;
25810 		}
25811 		/*
25812 		 * If this packet needs to go out on a particular interface
25813 		 * honor it.
25814 		 */
25815 		if (attach_if) {
25816 			match_flags = MATCH_IRE_ILL;
25817 
25818 			/*
25819 			 * Check if we need an ire that will not be
25820 			 * looked up by anybody else i.e. HIDDEN.
25821 			 */
25822 			if (ill_is_probeonly(ill)) {
25823 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25824 			}
25825 		}
25826 	}
25827 	ASSERT(mp != NULL);
25828 
25829 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25830 		boolean_t unspec_src;
25831 		ipif_t	*ipif;
25832 
25833 		/*
25834 		 * Use the ill_index to get the right ill.
25835 		 */
25836 		unspec_src = io->ipsec_out_unspec_src;
25837 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25838 		if (ipif == NULL) {
25839 			if (ill_need_rele)
25840 				ill_refrele(ill);
25841 			freemsg(ipsec_mp);
25842 			return;
25843 		}
25844 
25845 		if (ire_arg != NULL) {
25846 			ire = ire_arg;
25847 		} else {
25848 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25849 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25850 			ire_need_rele = B_TRUE;
25851 		}
25852 		if (ire != NULL) {
25853 			ipif_refrele(ipif);
25854 			/*
25855 			 * XXX Do the multicast forwarding now, as the IPSEC
25856 			 * processing has been done.
25857 			 */
25858 			goto send;
25859 		}
25860 
25861 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25862 		mp->b_prev = NULL;
25863 		mp->b_next = NULL;
25864 
25865 		/*
25866 		 * If the IPsec packet was processed asynchronously,
25867 		 * drop it now.
25868 		 */
25869 		if (q == NULL) {
25870 			if (ill_need_rele)
25871 				ill_refrele(ill);
25872 			freemsg(ipsec_mp);
25873 			return;
25874 		}
25875 
25876 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25877 		    unspec_src, zoneid);
25878 		ipif_refrele(ipif);
25879 	} else {
25880 		if (attach_if) {
25881 			ipif_t	*ipif;
25882 
25883 			ipif = ipif_get_next_ipif(NULL, ill);
25884 			if (ipif == NULL) {
25885 				if (ill_need_rele)
25886 					ill_refrele(ill);
25887 				freemsg(ipsec_mp);
25888 				return;
25889 			}
25890 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25891 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25892 			ire_need_rele = B_TRUE;
25893 			ipif_refrele(ipif);
25894 		} else {
25895 			if (ire_arg != NULL) {
25896 				ire = ire_arg;
25897 			} else {
25898 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25899 				    ipst);
25900 				ire_need_rele = B_TRUE;
25901 			}
25902 		}
25903 		if (ire != NULL)
25904 			goto send;
25905 		/*
25906 		 * ire disappeared underneath.
25907 		 *
25908 		 * What we need to do here is the ip_newroute
25909 		 * logic to get the ire without doing the IPSEC
25910 		 * processing. Follow the same old path. But this
25911 		 * time, ip_wput or ire_add_then_send will call us
25912 		 * directly as all the IPSEC operations are done.
25913 		 */
25914 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25915 		mp->b_prev = NULL;
25916 		mp->b_next = NULL;
25917 
25918 		/*
25919 		 * If the IPsec packet was processed asynchronously,
25920 		 * drop it now.
25921 		 */
25922 		if (q == NULL) {
25923 			if (ill_need_rele)
25924 				ill_refrele(ill);
25925 			freemsg(ipsec_mp);
25926 			return;
25927 		}
25928 
25929 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25930 		    zoneid, ipst);
25931 	}
25932 	if (ill != NULL && ill_need_rele)
25933 		ill_refrele(ill);
25934 	return;
25935 send:
25936 	if (ill != NULL && ill_need_rele)
25937 		ill_refrele(ill);
25938 
25939 	/* Local delivery */
25940 	if (ire->ire_stq == NULL) {
25941 		ill_t	*out_ill;
25942 		ASSERT(q != NULL);
25943 
25944 		/* PFHooks: LOOPBACK_OUT */
25945 		out_ill = ire->ire_ipif->ipif_ill;
25946 
25947 		DTRACE_PROBE4(ip6__loopback__out__start,
25948 		    ill_t *, NULL, ill_t *, out_ill,
25949 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25950 
25951 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25952 		    ipst->ips_ipv6firewall_loopback_out,
25953 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25954 
25955 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25956 
25957 		if (ipsec_mp != NULL)
25958 			ip_wput_local_v6(RD(q), out_ill,
25959 			    ip6h, ipsec_mp, ire, 0);
25960 		if (ire_need_rele)
25961 			ire_refrele(ire);
25962 		return;
25963 	}
25964 	/*
25965 	 * Everything is done. Send it out on the wire.
25966 	 * We force the insertion of a fragment header using the
25967 	 * IPH_FRAG_HDR flag in two cases:
25968 	 * - after reception of an ICMPv6 "packet too big" message
25969 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25970 	 * - for multirouted IPv6 packets, so that the receiver can
25971 	 *   discard duplicates according to their fragment identifier
25972 	 */
25973 	/* XXX fix flow control problems. */
25974 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25975 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25976 		if (hwaccel) {
25977 			/*
25978 			 * hardware acceleration does not handle these
25979 			 * "slow path" cases.
25980 			 */
25981 			/* IPsec KSTATS: should bump bean counter here. */
25982 			if (ire_need_rele)
25983 				ire_refrele(ire);
25984 			freemsg(ipsec_mp);
25985 			return;
25986 		}
25987 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25988 		    (mp->b_cont ? msgdsize(mp) :
25989 		    mp->b_wptr - (uchar_t *)ip6h)) {
25990 			/* IPsec KSTATS: should bump bean counter here. */
25991 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25992 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25993 			    msgdsize(mp)));
25994 			if (ire_need_rele)
25995 				ire_refrele(ire);
25996 			freemsg(ipsec_mp);
25997 			return;
25998 		}
25999 		ASSERT(mp->b_prev == NULL);
26000 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26001 		    ntohs(ip6h->ip6_plen) +
26002 		    IPV6_HDR_LEN, ire->ire_max_frag));
26003 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26004 		    ire->ire_max_frag);
26005 	} else {
26006 		UPDATE_OB_PKT_COUNT(ire);
26007 		ire->ire_last_used_time = lbolt;
26008 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26009 	}
26010 	if (ire_need_rele)
26011 		ire_refrele(ire);
26012 	freeb(ipsec_mp);
26013 }
26014 
26015 void
26016 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26017 {
26018 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26019 	da_ipsec_t *hada;	/* data attributes */
26020 	ill_t *ill = (ill_t *)q->q_ptr;
26021 
26022 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26023 
26024 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26025 		/* IPsec KSTATS: Bump lose counter here! */
26026 		freemsg(mp);
26027 		return;
26028 	}
26029 
26030 	/*
26031 	 * It's an IPsec packet that must be
26032 	 * accelerated by the Provider, and the
26033 	 * outbound ill is IPsec acceleration capable.
26034 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26035 	 * to the ill.
26036 	 * IPsec KSTATS: should bump packet counter here.
26037 	 */
26038 
26039 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26040 	if (hada_mp == NULL) {
26041 		/* IPsec KSTATS: should bump packet counter here. */
26042 		freemsg(mp);
26043 		return;
26044 	}
26045 
26046 	hada_mp->b_datap->db_type = M_CTL;
26047 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26048 	hada_mp->b_cont = mp;
26049 
26050 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26051 	bzero(hada, sizeof (da_ipsec_t));
26052 	hada->da_type = IPHADA_M_CTL;
26053 
26054 	putnext(q, hada_mp);
26055 }
26056 
26057 /*
26058  * Finish the outbound IPsec processing. This function is called from
26059  * ipsec_out_process() if the IPsec packet was processed
26060  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26061  * asynchronously.
26062  */
26063 void
26064 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26065     ire_t *ire_arg)
26066 {
26067 	uint32_t v_hlen_tos_len;
26068 	ipaddr_t	dst;
26069 	ipif_t	*ipif = NULL;
26070 	ire_t *ire;
26071 	ire_t *ire1 = NULL;
26072 	mblk_t *next_mp = NULL;
26073 	uint32_t max_frag;
26074 	boolean_t multirt_send = B_FALSE;
26075 	mblk_t *mp;
26076 	mblk_t *mp1;
26077 	ipha_t *ipha1;
26078 	uint_t	ill_index;
26079 	ipsec_out_t *io;
26080 	boolean_t attach_if;
26081 	int match_flags, offset;
26082 	irb_t *irb = NULL;
26083 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26084 	zoneid_t zoneid;
26085 	uint32_t cksum;
26086 	uint16_t *up;
26087 	ipxmit_state_t	pktxmit_state;
26088 	ip_stack_t	*ipst;
26089 
26090 #ifdef	_BIG_ENDIAN
26091 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26092 #else
26093 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26094 #endif
26095 
26096 	mp = ipsec_mp->b_cont;
26097 	ipha1 = (ipha_t *)mp->b_rptr;
26098 	ASSERT(mp != NULL);
26099 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26100 	dst = ipha->ipha_dst;
26101 
26102 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26103 	ill_index = io->ipsec_out_ill_index;
26104 	attach_if = io->ipsec_out_attach_if;
26105 	zoneid = io->ipsec_out_zoneid;
26106 	ASSERT(zoneid != ALL_ZONES);
26107 	ipst = io->ipsec_out_ns->netstack_ip;
26108 	ASSERT(io->ipsec_out_ns != NULL);
26109 
26110 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26111 	if (ill_index != 0) {
26112 		if (ill == NULL) {
26113 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26114 			    ill_index, B_FALSE, ipst);
26115 
26116 			/* Failure case frees things for us. */
26117 			if (ill == NULL)
26118 				return;
26119 
26120 			ill_need_rele = B_TRUE;
26121 		}
26122 		/*
26123 		 * If this packet needs to go out on a particular interface
26124 		 * honor it.
26125 		 */
26126 		if (attach_if) {
26127 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26128 
26129 			/*
26130 			 * Check if we need an ire that will not be
26131 			 * looked up by anybody else i.e. HIDDEN.
26132 			 */
26133 			if (ill_is_probeonly(ill)) {
26134 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26135 			}
26136 		}
26137 	}
26138 
26139 	if (CLASSD(dst)) {
26140 		boolean_t conn_dontroute;
26141 		/*
26142 		 * Use the ill_index to get the right ipif.
26143 		 */
26144 		conn_dontroute = io->ipsec_out_dontroute;
26145 		if (ill_index == 0)
26146 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26147 		else
26148 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26149 		if (ipif == NULL) {
26150 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26151 			    " multicast\n"));
26152 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26153 			freemsg(ipsec_mp);
26154 			goto done;
26155 		}
26156 		/*
26157 		 * ipha_src has already been intialized with the
26158 		 * value of the ipif in ip_wput. All we need now is
26159 		 * an ire to send this downstream.
26160 		 */
26161 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26162 		    MBLK_GETLABEL(mp), match_flags, ipst);
26163 		if (ire != NULL) {
26164 			ill_t *ill1;
26165 			/*
26166 			 * Do the multicast forwarding now, as the IPSEC
26167 			 * processing has been done.
26168 			 */
26169 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26170 			    (ill1 = ire_to_ill(ire))) {
26171 				if (ip_mforward(ill1, ipha, mp)) {
26172 					freemsg(ipsec_mp);
26173 					ip1dbg(("ip_wput_ipsec_out: mforward "
26174 					    "failed\n"));
26175 					ire_refrele(ire);
26176 					goto done;
26177 				}
26178 			}
26179 			goto send;
26180 		}
26181 
26182 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26183 		mp->b_prev = NULL;
26184 		mp->b_next = NULL;
26185 
26186 		/*
26187 		 * If the IPsec packet was processed asynchronously,
26188 		 * drop it now.
26189 		 */
26190 		if (q == NULL) {
26191 			freemsg(ipsec_mp);
26192 			goto done;
26193 		}
26194 
26195 		/*
26196 		 * We may be using a wrong ipif to create the ire.
26197 		 * But it is okay as the source address is assigned
26198 		 * for the packet already. Next outbound packet would
26199 		 * create the IRE with the right IPIF in ip_wput.
26200 		 *
26201 		 * Also handle RTF_MULTIRT routes.
26202 		 */
26203 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26204 		    zoneid, &zero_info);
26205 	} else {
26206 		if (attach_if) {
26207 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26208 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26209 		} else {
26210 			if (ire_arg != NULL) {
26211 				ire = ire_arg;
26212 				ire_need_rele = B_FALSE;
26213 			} else {
26214 				ire = ire_cache_lookup(dst, zoneid,
26215 				    MBLK_GETLABEL(mp), ipst);
26216 			}
26217 		}
26218 		if (ire != NULL) {
26219 			goto send;
26220 		}
26221 
26222 		/*
26223 		 * ire disappeared underneath.
26224 		 *
26225 		 * What we need to do here is the ip_newroute
26226 		 * logic to get the ire without doing the IPSEC
26227 		 * processing. Follow the same old path. But this
26228 		 * time, ip_wput or ire_add_then_put will call us
26229 		 * directly as all the IPSEC operations are done.
26230 		 */
26231 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26232 		mp->b_prev = NULL;
26233 		mp->b_next = NULL;
26234 
26235 		/*
26236 		 * If the IPsec packet was processed asynchronously,
26237 		 * drop it now.
26238 		 */
26239 		if (q == NULL) {
26240 			freemsg(ipsec_mp);
26241 			goto done;
26242 		}
26243 
26244 		/*
26245 		 * Since we're going through ip_newroute() again, we
26246 		 * need to make sure we don't:
26247 		 *
26248 		 *	1.) Trigger the ASSERT() with the ipha_ident
26249 		 *	    overloading.
26250 		 *	2.) Redo transport-layer checksumming, since we've
26251 		 *	    already done all that to get this far.
26252 		 *
26253 		 * The easiest way not do either of the above is to set
26254 		 * the ipha_ident field to IP_HDR_INCLUDED.
26255 		 */
26256 		ipha->ipha_ident = IP_HDR_INCLUDED;
26257 		ip_newroute(q, ipsec_mp, dst, NULL,
26258 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26259 	}
26260 	goto done;
26261 send:
26262 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26263 	    udp_compute_checksum(ipst->ips_netstack)) {
26264 		/*
26265 		 * ESP NAT-Traversal packet.
26266 		 *
26267 		 * Just do software checksum for now.
26268 		 */
26269 
26270 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26271 		IP_STAT(ipst, ip_out_sw_cksum);
26272 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26273 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26274 #define	iphs	((uint16_t *)ipha)
26275 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26276 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26277 		    IP_SIMPLE_HDR_LENGTH);
26278 #undef iphs
26279 		cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum);
26280 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26281 			if (mp1->b_wptr - mp1->b_rptr >=
26282 			    offset + sizeof (uint16_t)) {
26283 				up = (uint16_t *)(mp1->b_rptr + offset);
26284 				*up = cksum;
26285 				break;	/* out of for loop */
26286 			} else {
26287 				offset -= (mp->b_wptr - mp->b_rptr);
26288 			}
26289 	} /* Otherwise, just keep the all-zero checksum. */
26290 
26291 	if (ire->ire_stq == NULL) {
26292 		ill_t	*out_ill;
26293 		/*
26294 		 * Loopbacks go through ip_wput_local except for one case.
26295 		 * We come here if we generate a icmp_frag_needed message
26296 		 * after IPSEC processing is over. When this function calls
26297 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26298 		 * icmp_frag_needed. The message generated comes back here
26299 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26300 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26301 		 * source address as it is usually set in ip_wput_ire. As
26302 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26303 		 * and we end up here. We can't enter ip_wput_ire once the
26304 		 * IPSEC processing is over and hence we need to do it here.
26305 		 */
26306 		ASSERT(q != NULL);
26307 		UPDATE_OB_PKT_COUNT(ire);
26308 		ire->ire_last_used_time = lbolt;
26309 		if (ipha->ipha_src == 0)
26310 			ipha->ipha_src = ire->ire_src_addr;
26311 
26312 		/* PFHooks: LOOPBACK_OUT */
26313 		out_ill = ire->ire_ipif->ipif_ill;
26314 
26315 		DTRACE_PROBE4(ip4__loopback__out__start,
26316 		    ill_t *, NULL, ill_t *, out_ill,
26317 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26318 
26319 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26320 		    ipst->ips_ipv4firewall_loopback_out,
26321 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26322 
26323 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26324 
26325 		if (ipsec_mp != NULL)
26326 			ip_wput_local(RD(q), out_ill,
26327 			    ipha, ipsec_mp, ire, 0, zoneid);
26328 		if (ire_need_rele)
26329 			ire_refrele(ire);
26330 		goto done;
26331 	}
26332 
26333 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26334 		/*
26335 		 * We are through with IPSEC processing.
26336 		 * Fragment this and send it on the wire.
26337 		 */
26338 		if (io->ipsec_out_accelerated) {
26339 			/*
26340 			 * The packet has been accelerated but must
26341 			 * be fragmented. This should not happen
26342 			 * since AH and ESP must not accelerate
26343 			 * packets that need fragmentation, however
26344 			 * the configuration could have changed
26345 			 * since the AH or ESP processing.
26346 			 * Drop packet.
26347 			 * IPsec KSTATS: bump bean counter here.
26348 			 */
26349 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26350 			    "fragmented accelerated packet!\n"));
26351 			freemsg(ipsec_mp);
26352 		} else {
26353 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26354 		}
26355 		if (ire_need_rele)
26356 			ire_refrele(ire);
26357 		goto done;
26358 	}
26359 
26360 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26361 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26362 	    (void *)ire->ire_ipif, (void *)ipif));
26363 
26364 	/*
26365 	 * Multiroute the secured packet, unless IPsec really
26366 	 * requires the packet to go out only through a particular
26367 	 * interface.
26368 	 */
26369 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26370 		ire_t *first_ire;
26371 		irb = ire->ire_bucket;
26372 		ASSERT(irb != NULL);
26373 		/*
26374 		 * This ire has been looked up as the one that
26375 		 * goes through the given ipif;
26376 		 * make sure we do not omit any other multiroute ire
26377 		 * that may be present in the bucket before this one.
26378 		 */
26379 		IRB_REFHOLD(irb);
26380 		for (first_ire = irb->irb_ire;
26381 		    first_ire != NULL;
26382 		    first_ire = first_ire->ire_next) {
26383 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26384 			    (first_ire->ire_addr == ire->ire_addr) &&
26385 			    !(first_ire->ire_marks &
26386 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26387 				break;
26388 			}
26389 		}
26390 
26391 		if ((first_ire != NULL) && (first_ire != ire)) {
26392 			/*
26393 			 * Don't change the ire if the packet must
26394 			 * be fragmented if sent via this new one.
26395 			 */
26396 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26397 				IRE_REFHOLD(first_ire);
26398 				if (ire_need_rele)
26399 					ire_refrele(ire);
26400 				else
26401 					ire_need_rele = B_TRUE;
26402 				ire = first_ire;
26403 			}
26404 		}
26405 		IRB_REFRELE(irb);
26406 
26407 		multirt_send = B_TRUE;
26408 		max_frag = ire->ire_max_frag;
26409 	} else {
26410 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26411 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26412 			    "flag, attach_if %d\n", attach_if));
26413 		}
26414 	}
26415 
26416 	/*
26417 	 * In most cases, the emission loop below is entered only once.
26418 	 * Only in the case where the ire holds the RTF_MULTIRT
26419 	 * flag, we loop to process all RTF_MULTIRT ires in the
26420 	 * bucket, and send the packet through all crossed
26421 	 * RTF_MULTIRT routes.
26422 	 */
26423 	do {
26424 		if (multirt_send) {
26425 			/*
26426 			 * ire1 holds here the next ire to process in the
26427 			 * bucket. If multirouting is expected,
26428 			 * any non-RTF_MULTIRT ire that has the
26429 			 * right destination address is ignored.
26430 			 */
26431 			ASSERT(irb != NULL);
26432 			IRB_REFHOLD(irb);
26433 			for (ire1 = ire->ire_next;
26434 			    ire1 != NULL;
26435 			    ire1 = ire1->ire_next) {
26436 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26437 					continue;
26438 				if (ire1->ire_addr != ire->ire_addr)
26439 					continue;
26440 				if (ire1->ire_marks &
26441 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26442 					continue;
26443 				/* No loopback here */
26444 				if (ire1->ire_stq == NULL)
26445 					continue;
26446 				/*
26447 				 * Ensure we do not exceed the MTU
26448 				 * of the next route.
26449 				 */
26450 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26451 					ip_multirt_bad_mtu(ire1, max_frag);
26452 					continue;
26453 				}
26454 
26455 				IRE_REFHOLD(ire1);
26456 				break;
26457 			}
26458 			IRB_REFRELE(irb);
26459 			if (ire1 != NULL) {
26460 				/*
26461 				 * We are in a multiple send case, need to
26462 				 * make a copy of the packet.
26463 				 */
26464 				next_mp = copymsg(ipsec_mp);
26465 				if (next_mp == NULL) {
26466 					ire_refrele(ire1);
26467 					ire1 = NULL;
26468 				}
26469 			}
26470 		}
26471 		/*
26472 		 * Everything is done. Send it out on the wire
26473 		 *
26474 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26475 		 * either send it on the wire or, in the case of
26476 		 * HW acceleration, call ipsec_hw_putnext.
26477 		 */
26478 		if (ire->ire_nce &&
26479 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26480 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26481 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26482 			/*
26483 			 * If ire's link-layer is unresolved (this
26484 			 * would only happen if the incomplete ire
26485 			 * was added to cachetable via forwarding path)
26486 			 * don't bother going to ip_xmit_v4. Just drop the
26487 			 * packet.
26488 			 * There is a slight risk here, in that, if we
26489 			 * have the forwarding path create an incomplete
26490 			 * IRE, then until the IRE is completed, any
26491 			 * transmitted IPSEC packets will be dropped
26492 			 * instead of being queued waiting for resolution.
26493 			 *
26494 			 * But the likelihood of a forwarding packet and a wput
26495 			 * packet sending to the same dst at the same time
26496 			 * and there not yet be an ARP entry for it is small.
26497 			 * Furthermore, if this actually happens, it might
26498 			 * be likely that wput would generate multiple
26499 			 * packets (and forwarding would also have a train
26500 			 * of packets) for that destination. If this is
26501 			 * the case, some of them would have been dropped
26502 			 * anyway, since ARP only queues a few packets while
26503 			 * waiting for resolution
26504 			 *
26505 			 * NOTE: We should really call ip_xmit_v4,
26506 			 * and let it queue the packet and send the
26507 			 * ARP query and have ARP come back thus:
26508 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26509 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26510 			 * hw accel work. But it's too complex to get
26511 			 * the IPsec hw  acceleration approach to fit
26512 			 * well with ip_xmit_v4 doing ARP without
26513 			 * doing IPSEC simplification. For now, we just
26514 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26515 			 * that we can continue with the send on the next
26516 			 * attempt.
26517 			 *
26518 			 * XXX THis should be revisited, when
26519 			 * the IPsec/IP interaction is cleaned up
26520 			 */
26521 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26522 			    " - dropping packet\n"));
26523 			freemsg(ipsec_mp);
26524 			/*
26525 			 * Call ip_xmit_v4() to trigger ARP query
26526 			 * in case the nce_state is ND_INITIAL
26527 			 */
26528 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26529 			goto drop_pkt;
26530 		}
26531 
26532 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26533 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26534 		    mblk_t *, ipsec_mp);
26535 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26536 		    ipst->ips_ipv4firewall_physical_out,
26537 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26538 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26539 		if (ipsec_mp == NULL)
26540 			goto drop_pkt;
26541 
26542 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26543 		pktxmit_state = ip_xmit_v4(mp, ire,
26544 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26545 
26546 		if ((pktxmit_state ==  SEND_FAILED) ||
26547 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26548 
26549 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26550 drop_pkt:
26551 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26552 			    ipIfStatsOutDiscards);
26553 			if (ire_need_rele)
26554 				ire_refrele(ire);
26555 			if (ire1 != NULL) {
26556 				ire_refrele(ire1);
26557 				freemsg(next_mp);
26558 			}
26559 			goto done;
26560 		}
26561 
26562 		freeb(ipsec_mp);
26563 		if (ire_need_rele)
26564 			ire_refrele(ire);
26565 
26566 		if (ire1 != NULL) {
26567 			ire = ire1;
26568 			ire_need_rele = B_TRUE;
26569 			ASSERT(next_mp);
26570 			ipsec_mp = next_mp;
26571 			mp = ipsec_mp->b_cont;
26572 			ire1 = NULL;
26573 			next_mp = NULL;
26574 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26575 		} else {
26576 			multirt_send = B_FALSE;
26577 		}
26578 	} while (multirt_send);
26579 done:
26580 	if (ill != NULL && ill_need_rele)
26581 		ill_refrele(ill);
26582 	if (ipif != NULL)
26583 		ipif_refrele(ipif);
26584 }
26585 
26586 /*
26587  * Get the ill corresponding to the specified ire, and compare its
26588  * capabilities with the protocol and algorithms specified by the
26589  * the SA obtained from ipsec_out. If they match, annotate the
26590  * ipsec_out structure to indicate that the packet needs acceleration.
26591  *
26592  *
26593  * A packet is eligible for outbound hardware acceleration if the
26594  * following conditions are satisfied:
26595  *
26596  * 1. the packet will not be fragmented
26597  * 2. the provider supports the algorithm
26598  * 3. there is no pending control message being exchanged
26599  * 4. snoop is not attached
26600  * 5. the destination address is not a broadcast or multicast address.
26601  *
26602  * Rationale:
26603  *	- Hardware drivers do not support fragmentation with
26604  *	  the current interface.
26605  *	- snoop, multicast, and broadcast may result in exposure of
26606  *	  a cleartext datagram.
26607  * We check all five of these conditions here.
26608  *
26609  * XXX would like to nuke "ire_t *" parameter here; problem is that
26610  * IRE is only way to figure out if a v4 address is a broadcast and
26611  * thus ineligible for acceleration...
26612  */
26613 static void
26614 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26615 {
26616 	ipsec_out_t *io;
26617 	mblk_t *data_mp;
26618 	uint_t plen, overhead;
26619 	ip_stack_t	*ipst;
26620 
26621 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26622 		return;
26623 
26624 	if (ill == NULL)
26625 		return;
26626 	ipst = ill->ill_ipst;
26627 	/*
26628 	 * Destination address is a broadcast or multicast.  Punt.
26629 	 */
26630 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26631 	    IRE_LOCAL)))
26632 		return;
26633 
26634 	data_mp = ipsec_mp->b_cont;
26635 
26636 	if (ill->ill_isv6) {
26637 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26638 
26639 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26640 			return;
26641 
26642 		plen = ip6h->ip6_plen;
26643 	} else {
26644 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26645 
26646 		if (CLASSD(ipha->ipha_dst))
26647 			return;
26648 
26649 		plen = ipha->ipha_length;
26650 	}
26651 	/*
26652 	 * Is there a pending DLPI control message being exchanged
26653 	 * between IP/IPsec and the DLS Provider? If there is, it
26654 	 * could be a SADB update, and the state of the DLS Provider
26655 	 * SADB might not be in sync with the SADB maintained by
26656 	 * IPsec. To avoid dropping packets or using the wrong keying
26657 	 * material, we do not accelerate this packet.
26658 	 */
26659 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26660 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26661 		    "ill_dlpi_pending! don't accelerate packet\n"));
26662 		return;
26663 	}
26664 
26665 	/*
26666 	 * Is the Provider in promiscous mode? If it does, we don't
26667 	 * accelerate the packet since it will bounce back up to the
26668 	 * listeners in the clear.
26669 	 */
26670 	if (ill->ill_promisc_on_phys) {
26671 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26672 		    "ill in promiscous mode, don't accelerate packet\n"));
26673 		return;
26674 	}
26675 
26676 	/*
26677 	 * Will the packet require fragmentation?
26678 	 */
26679 
26680 	/*
26681 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26682 	 * as is used elsewhere.
26683 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26684 	 *	+ 2-byte trailer
26685 	 */
26686 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26687 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26688 
26689 	if ((plen + overhead) > ill->ill_max_mtu)
26690 		return;
26691 
26692 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26693 
26694 	/*
26695 	 * Can the ill accelerate this IPsec protocol and algorithm
26696 	 * specified by the SA?
26697 	 */
26698 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26699 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26700 		return;
26701 	}
26702 
26703 	/*
26704 	 * Tell AH or ESP that the outbound ill is capable of
26705 	 * accelerating this packet.
26706 	 */
26707 	io->ipsec_out_is_capab_ill = B_TRUE;
26708 }
26709 
26710 /*
26711  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26712  *
26713  * If this function returns B_TRUE, the requested SA's have been filled
26714  * into the ipsec_out_*_sa pointers.
26715  *
26716  * If the function returns B_FALSE, the packet has been "consumed", most
26717  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26718  *
26719  * The SA references created by the protocol-specific "select"
26720  * function will be released when the ipsec_mp is freed, thanks to the
26721  * ipsec_out_free destructor -- see spd.c.
26722  */
26723 static boolean_t
26724 ipsec_out_select_sa(mblk_t *ipsec_mp)
26725 {
26726 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26727 	ipsec_out_t *io;
26728 	ipsec_policy_t *pp;
26729 	ipsec_action_t *ap;
26730 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26731 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26732 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26733 
26734 	if (!io->ipsec_out_secure) {
26735 		/*
26736 		 * We came here by mistake.
26737 		 * Don't bother with ipsec processing
26738 		 * We should "discourage" this path in the future.
26739 		 */
26740 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26741 		return (B_FALSE);
26742 	}
26743 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26744 	ASSERT((io->ipsec_out_policy != NULL) ||
26745 	    (io->ipsec_out_act != NULL));
26746 
26747 	ASSERT(io->ipsec_out_failed == B_FALSE);
26748 
26749 	/*
26750 	 * IPSEC processing has started.
26751 	 */
26752 	io->ipsec_out_proc_begin = B_TRUE;
26753 	ap = io->ipsec_out_act;
26754 	if (ap == NULL) {
26755 		pp = io->ipsec_out_policy;
26756 		ASSERT(pp != NULL);
26757 		ap = pp->ipsp_act;
26758 		ASSERT(ap != NULL);
26759 	}
26760 
26761 	/*
26762 	 * We have an action.  now, let's select SA's.
26763 	 * (In the future, we can cache this in the conn_t..)
26764 	 */
26765 	if (ap->ipa_want_esp) {
26766 		if (io->ipsec_out_esp_sa == NULL) {
26767 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26768 			    IPPROTO_ESP);
26769 		}
26770 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26771 	}
26772 
26773 	if (ap->ipa_want_ah) {
26774 		if (io->ipsec_out_ah_sa == NULL) {
26775 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26776 			    IPPROTO_AH);
26777 		}
26778 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26779 		/*
26780 		 * The ESP and AH processing order needs to be preserved
26781 		 * when both protocols are required (ESP should be applied
26782 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26783 		 * when both ESP and AH are required, and an AH ACQUIRE
26784 		 * is needed.
26785 		 */
26786 		if (ap->ipa_want_esp && need_ah_acquire)
26787 			need_esp_acquire = B_TRUE;
26788 	}
26789 
26790 	/*
26791 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26792 	 * Release SAs that got referenced, but will not be used until we
26793 	 * acquire _all_ of the SAs we need.
26794 	 */
26795 	if (need_ah_acquire || need_esp_acquire) {
26796 		if (io->ipsec_out_ah_sa != NULL) {
26797 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26798 			io->ipsec_out_ah_sa = NULL;
26799 		}
26800 		if (io->ipsec_out_esp_sa != NULL) {
26801 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26802 			io->ipsec_out_esp_sa = NULL;
26803 		}
26804 
26805 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26806 		return (B_FALSE);
26807 	}
26808 
26809 	return (B_TRUE);
26810 }
26811 
26812 /*
26813  * Process an IPSEC_OUT message and see what you can
26814  * do with it.
26815  * IPQoS Notes:
26816  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26817  * IPSec.
26818  * XXX would like to nuke ire_t.
26819  * XXX ill_index better be "real"
26820  */
26821 void
26822 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26823 {
26824 	ipsec_out_t *io;
26825 	ipsec_policy_t *pp;
26826 	ipsec_action_t *ap;
26827 	ipha_t *ipha;
26828 	ip6_t *ip6h;
26829 	mblk_t *mp;
26830 	ill_t *ill;
26831 	zoneid_t zoneid;
26832 	ipsec_status_t ipsec_rc;
26833 	boolean_t ill_need_rele = B_FALSE;
26834 	ip_stack_t	*ipst;
26835 	ipsec_stack_t	*ipss;
26836 
26837 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26838 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26839 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26840 	ipst = io->ipsec_out_ns->netstack_ip;
26841 	mp = ipsec_mp->b_cont;
26842 
26843 	/*
26844 	 * Initiate IPPF processing. We do it here to account for packets
26845 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26846 	 * We can check for ipsec_out_proc_begin even for such packets, as
26847 	 * they will always be false (asserted below).
26848 	 */
26849 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26850 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26851 		    io->ipsec_out_ill_index : ill_index);
26852 		if (mp == NULL) {
26853 			ip2dbg(("ipsec_out_process: packet dropped "\
26854 			    "during IPPF processing\n"));
26855 			freeb(ipsec_mp);
26856 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26857 			return;
26858 		}
26859 	}
26860 
26861 	if (!io->ipsec_out_secure) {
26862 		/*
26863 		 * We came here by mistake.
26864 		 * Don't bother with ipsec processing
26865 		 * Should "discourage" this path in the future.
26866 		 */
26867 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26868 		goto done;
26869 	}
26870 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26871 	ASSERT((io->ipsec_out_policy != NULL) ||
26872 	    (io->ipsec_out_act != NULL));
26873 	ASSERT(io->ipsec_out_failed == B_FALSE);
26874 
26875 	ipss = ipst->ips_netstack->netstack_ipsec;
26876 	if (!ipsec_loaded(ipss)) {
26877 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26878 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26879 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26880 		} else {
26881 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26882 		}
26883 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26884 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26885 		    &ipss->ipsec_dropper);
26886 		return;
26887 	}
26888 
26889 	/*
26890 	 * IPSEC processing has started.
26891 	 */
26892 	io->ipsec_out_proc_begin = B_TRUE;
26893 	ap = io->ipsec_out_act;
26894 	if (ap == NULL) {
26895 		pp = io->ipsec_out_policy;
26896 		ASSERT(pp != NULL);
26897 		ap = pp->ipsp_act;
26898 		ASSERT(ap != NULL);
26899 	}
26900 
26901 	/*
26902 	 * Save the outbound ill index. When the packet comes back
26903 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26904 	 * before sending it the accelerated packet.
26905 	 */
26906 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26907 		int ifindex;
26908 		ill = ire_to_ill(ire);
26909 		ifindex = ill->ill_phyint->phyint_ifindex;
26910 		io->ipsec_out_capab_ill_index = ifindex;
26911 	}
26912 
26913 	/*
26914 	 * The order of processing is first insert a IP header if needed.
26915 	 * Then insert the ESP header and then the AH header.
26916 	 */
26917 	if ((io->ipsec_out_se_done == B_FALSE) &&
26918 	    (ap->ipa_want_se)) {
26919 		/*
26920 		 * First get the outer IP header before sending
26921 		 * it to ESP.
26922 		 */
26923 		ipha_t *oipha, *iipha;
26924 		mblk_t *outer_mp, *inner_mp;
26925 
26926 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26927 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26928 			    "ipsec_out_process: "
26929 			    "Self-Encapsulation failed: Out of memory\n");
26930 			freemsg(ipsec_mp);
26931 			if (ill != NULL) {
26932 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26933 			} else {
26934 				BUMP_MIB(&ipst->ips_ip_mib,
26935 				    ipIfStatsOutDiscards);
26936 			}
26937 			return;
26938 		}
26939 		inner_mp = ipsec_mp->b_cont;
26940 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26941 		oipha = (ipha_t *)outer_mp->b_rptr;
26942 		iipha = (ipha_t *)inner_mp->b_rptr;
26943 		*oipha = *iipha;
26944 		outer_mp->b_wptr += sizeof (ipha_t);
26945 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26946 		    sizeof (ipha_t));
26947 		oipha->ipha_protocol = IPPROTO_ENCAP;
26948 		oipha->ipha_version_and_hdr_length =
26949 		    IP_SIMPLE_HDR_VERSION;
26950 		oipha->ipha_hdr_checksum = 0;
26951 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26952 		outer_mp->b_cont = inner_mp;
26953 		ipsec_mp->b_cont = outer_mp;
26954 
26955 		io->ipsec_out_se_done = B_TRUE;
26956 		io->ipsec_out_tunnel = B_TRUE;
26957 	}
26958 
26959 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26960 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26961 	    !ipsec_out_select_sa(ipsec_mp))
26962 		return;
26963 
26964 	/*
26965 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26966 	 * to do the heavy lifting.
26967 	 */
26968 	zoneid = io->ipsec_out_zoneid;
26969 	ASSERT(zoneid != ALL_ZONES);
26970 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26971 		ASSERT(io->ipsec_out_esp_sa != NULL);
26972 		io->ipsec_out_esp_done = B_TRUE;
26973 		/*
26974 		 * Note that since hw accel can only apply one transform,
26975 		 * not two, we skip hw accel for ESP if we also have AH
26976 		 * This is an design limitation of the interface
26977 		 * which should be revisited.
26978 		 */
26979 		ASSERT(ire != NULL);
26980 		if (io->ipsec_out_ah_sa == NULL) {
26981 			ill = (ill_t *)ire->ire_stq->q_ptr;
26982 			ipsec_out_is_accelerated(ipsec_mp,
26983 			    io->ipsec_out_esp_sa, ill, ire);
26984 		}
26985 
26986 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26987 		switch (ipsec_rc) {
26988 		case IPSEC_STATUS_SUCCESS:
26989 			break;
26990 		case IPSEC_STATUS_FAILED:
26991 			if (ill != NULL) {
26992 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26993 			} else {
26994 				BUMP_MIB(&ipst->ips_ip_mib,
26995 				    ipIfStatsOutDiscards);
26996 			}
26997 			/* FALLTHRU */
26998 		case IPSEC_STATUS_PENDING:
26999 			return;
27000 		}
27001 	}
27002 
27003 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27004 		ASSERT(io->ipsec_out_ah_sa != NULL);
27005 		io->ipsec_out_ah_done = B_TRUE;
27006 		if (ire == NULL) {
27007 			int idx = io->ipsec_out_capab_ill_index;
27008 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27009 			    NULL, NULL, NULL, NULL, ipst);
27010 			ill_need_rele = B_TRUE;
27011 		} else {
27012 			ill = (ill_t *)ire->ire_stq->q_ptr;
27013 		}
27014 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27015 		    ire);
27016 
27017 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27018 		switch (ipsec_rc) {
27019 		case IPSEC_STATUS_SUCCESS:
27020 			break;
27021 		case IPSEC_STATUS_FAILED:
27022 			if (ill != NULL) {
27023 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27024 			} else {
27025 				BUMP_MIB(&ipst->ips_ip_mib,
27026 				    ipIfStatsOutDiscards);
27027 			}
27028 			/* FALLTHRU */
27029 		case IPSEC_STATUS_PENDING:
27030 			if (ill != NULL && ill_need_rele)
27031 				ill_refrele(ill);
27032 			return;
27033 		}
27034 	}
27035 	/*
27036 	 * We are done with IPSEC processing. Send it over
27037 	 * the wire.
27038 	 */
27039 done:
27040 	mp = ipsec_mp->b_cont;
27041 	ipha = (ipha_t *)mp->b_rptr;
27042 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27043 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27044 	} else {
27045 		ip6h = (ip6_t *)ipha;
27046 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27047 	}
27048 	if (ill != NULL && ill_need_rele)
27049 		ill_refrele(ill);
27050 }
27051 
27052 /* ARGSUSED */
27053 void
27054 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27055 {
27056 	opt_restart_t	*or;
27057 	int	err;
27058 	conn_t	*connp;
27059 
27060 	ASSERT(CONN_Q(q));
27061 	connp = Q_TO_CONN(q);
27062 
27063 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27064 	or = (opt_restart_t *)first_mp->b_rptr;
27065 	/*
27066 	 * We don't need to pass any credentials here since this is just
27067 	 * a restart. The credentials are passed in when svr4_optcom_req
27068 	 * is called the first time (from ip_wput_nondata).
27069 	 */
27070 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27071 		err = svr4_optcom_req(q, first_mp, NULL,
27072 		    &ip_opt_obj);
27073 	} else {
27074 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27075 		err = tpi_optcom_req(q, first_mp, NULL,
27076 		    &ip_opt_obj);
27077 	}
27078 	if (err != EINPROGRESS) {
27079 		/* operation is done */
27080 		CONN_OPER_PENDING_DONE(connp);
27081 	}
27082 }
27083 
27084 /*
27085  * ioctls that go through a down/up sequence may need to wait for the down
27086  * to complete. This involves waiting for the ire and ipif refcnts to go down
27087  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27088  */
27089 /* ARGSUSED */
27090 void
27091 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27092 {
27093 	struct iocblk *iocp;
27094 	mblk_t *mp1;
27095 	ip_ioctl_cmd_t *ipip;
27096 	int err;
27097 	sin_t	*sin;
27098 	struct lifreq *lifr;
27099 	struct ifreq *ifr;
27100 
27101 	iocp = (struct iocblk *)mp->b_rptr;
27102 	ASSERT(ipsq != NULL);
27103 	/* Existence of mp1 verified in ip_wput_nondata */
27104 	mp1 = mp->b_cont->b_cont;
27105 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27106 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27107 		/*
27108 		 * Special case where ipsq_current_ipif is not set:
27109 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27110 		 * ill could also have become part of a ipmp group in the
27111 		 * process, we are here as were not able to complete the
27112 		 * operation in ipif_set_values because we could not become
27113 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27114 		 * will not be set so we need to set it.
27115 		 */
27116 		ill_t *ill = q->q_ptr;
27117 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27118 	}
27119 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27120 
27121 	if (ipip->ipi_cmd_type == IF_CMD) {
27122 		/* This a old style SIOC[GS]IF* command */
27123 		ifr = (struct ifreq *)mp1->b_rptr;
27124 		sin = (sin_t *)&ifr->ifr_addr;
27125 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27126 		/* This a new style SIOC[GS]LIF* command */
27127 		lifr = (struct lifreq *)mp1->b_rptr;
27128 		sin = (sin_t *)&lifr->lifr_addr;
27129 	} else {
27130 		sin = NULL;
27131 	}
27132 
27133 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27134 	    ipip, mp1->b_rptr);
27135 
27136 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27137 }
27138 
27139 /*
27140  * ioctl processing
27141  *
27142  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27143  * the ioctl command in the ioctl tables and determines the copyin data size
27144  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27145  * size.
27146  *
27147  * ioctl processing then continues when the M_IOCDATA makes its way down.
27148  * Now the ioctl is looked up again in the ioctl table, and its properties are
27149  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27150  * and the general ioctl processing function ip_process_ioctl is called.
27151  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27152  * so goes thru the serialization primitive ipsq_try_enter. Then the
27153  * appropriate function to handle the ioctl is called based on the entry in
27154  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27155  * which also refreleases the 'conn' that was refheld at the start of the
27156  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27157  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27158  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27159  *
27160  * Many exclusive ioctls go thru an internal down up sequence as part of
27161  * the operation. For example an attempt to change the IP address of an
27162  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27163  * does all the cleanup such as deleting all ires that use this address.
27164  * Then we need to wait till all references to the interface go away.
27165  */
27166 void
27167 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27168 {
27169 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27170 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27171 	cmd_info_t ci;
27172 	int err;
27173 	boolean_t entered_ipsq = B_FALSE;
27174 
27175 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27176 
27177 	if (ipip == NULL)
27178 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27179 
27180 	/*
27181 	 * SIOCLIFADDIF needs to go thru a special path since the
27182 	 * ill may not exist yet. This happens in the case of lo0
27183 	 * which is created using this ioctl.
27184 	 */
27185 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27186 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27187 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27188 		return;
27189 	}
27190 
27191 	ci.ci_ipif = NULL;
27192 	switch (ipip->ipi_cmd_type) {
27193 	case IF_CMD:
27194 	case LIF_CMD:
27195 		/*
27196 		 * ioctls that pass in a [l]ifreq appear here.
27197 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27198 		 * ci.ci_ipif
27199 		 */
27200 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27201 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27202 		if (err != 0) {
27203 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27204 			return;
27205 		}
27206 		ASSERT(ci.ci_ipif != NULL);
27207 		break;
27208 
27209 	case TUN_CMD:
27210 		/*
27211 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27212 		 * a refheld ipif in ci.ci_ipif
27213 		 */
27214 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27215 		if (err != 0) {
27216 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27217 			return;
27218 		}
27219 		ASSERT(ci.ci_ipif != NULL);
27220 		break;
27221 
27222 	case MISC_CMD:
27223 		/*
27224 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27225 		 * For eg. SIOCGLIFCONF will appear here.
27226 		 */
27227 		switch (ipip->ipi_cmd) {
27228 		case IF_UNITSEL:
27229 			/* ioctl comes down the ill */
27230 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27231 			ipif_refhold(ci.ci_ipif);
27232 			break;
27233 		case SIOCGMSFILTER:
27234 		case SIOCSMSFILTER:
27235 		case SIOCGIPMSFILTER:
27236 		case SIOCSIPMSFILTER:
27237 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27238 			    ip_process_ioctl);
27239 			if (err != 0) {
27240 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27241 				    NULL);
27242 			}
27243 			break;
27244 		}
27245 		err = 0;
27246 		ci.ci_sin = NULL;
27247 		ci.ci_sin6 = NULL;
27248 		ci.ci_lifr = NULL;
27249 		break;
27250 	}
27251 
27252 	/*
27253 	 * If ipsq is non-null, we are already being called exclusively
27254 	 */
27255 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27256 	if (!(ipip->ipi_flags & IPI_WR)) {
27257 		/*
27258 		 * A return value of EINPROGRESS means the ioctl is
27259 		 * either queued and waiting for some reason or has
27260 		 * already completed.
27261 		 */
27262 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27263 		    ci.ci_lifr);
27264 		if (ci.ci_ipif != NULL)
27265 			ipif_refrele(ci.ci_ipif);
27266 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27267 		return;
27268 	}
27269 
27270 	ASSERT(ci.ci_ipif != NULL);
27271 
27272 	if (ipsq == NULL) {
27273 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27274 		    ip_process_ioctl, NEW_OP, B_TRUE);
27275 		entered_ipsq = B_TRUE;
27276 	}
27277 	/*
27278 	 * Release the ipif so that ipif_down and friends that wait for
27279 	 * references to go away are not misled about the current ipif_refcnt
27280 	 * values. We are writer so we can access the ipif even after releasing
27281 	 * the ipif.
27282 	 */
27283 	ipif_refrele(ci.ci_ipif);
27284 	if (ipsq == NULL)
27285 		return;
27286 
27287 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27288 
27289 	/*
27290 	 * For most set ioctls that come here, this serves as a single point
27291 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27292 	 * be any new references to the ipif. This helps functions that go
27293 	 * through this path and end up trying to wait for the refcnts
27294 	 * associated with the ipif to go down to zero. Some exceptions are
27295 	 * Failover, Failback, and Groupname commands that operate on more than
27296 	 * just the ci.ci_ipif. These commands internally determine the
27297 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27298 	 * flags on that set. Another exception is the Removeif command that
27299 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27300 	 * ipif to operate on.
27301 	 */
27302 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27303 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27304 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27305 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27306 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27307 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27308 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27309 
27310 	/*
27311 	 * A return value of EINPROGRESS means the ioctl is
27312 	 * either queued and waiting for some reason or has
27313 	 * already completed.
27314 	 */
27315 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27316 
27317 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27318 
27319 	if (entered_ipsq)
27320 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27321 }
27322 
27323 /*
27324  * Complete the ioctl. Typically ioctls use the mi package and need to
27325  * do mi_copyout/mi_copy_done.
27326  */
27327 void
27328 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27329 {
27330 	conn_t	*connp = NULL;
27331 
27332 	if (err == EINPROGRESS)
27333 		return;
27334 
27335 	if (CONN_Q(q)) {
27336 		connp = Q_TO_CONN(q);
27337 		ASSERT(connp->conn_ref >= 2);
27338 	}
27339 
27340 	switch (mode) {
27341 	case COPYOUT:
27342 		if (err == 0)
27343 			mi_copyout(q, mp);
27344 		else
27345 			mi_copy_done(q, mp, err);
27346 		break;
27347 
27348 	case NO_COPYOUT:
27349 		mi_copy_done(q, mp, err);
27350 		break;
27351 
27352 	default:
27353 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27354 		break;
27355 	}
27356 
27357 	/*
27358 	 * The refhold placed at the start of the ioctl is released here.
27359 	 */
27360 	if (connp != NULL)
27361 		CONN_OPER_PENDING_DONE(connp);
27362 
27363 	if (ipsq != NULL)
27364 		ipsq_current_finish(ipsq);
27365 }
27366 
27367 /*
27368  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27369  */
27370 /* ARGSUSED */
27371 void
27372 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27373 {
27374 	conn_t *connp = arg;
27375 	tcp_t	*tcp;
27376 
27377 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27378 	tcp = connp->conn_tcp;
27379 
27380 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27381 		freemsg(mp);
27382 	else
27383 		tcp_rput_other(tcp, mp);
27384 	CONN_OPER_PENDING_DONE(connp);
27385 }
27386 
27387 /* Called from ip_wput for all non data messages */
27388 /* ARGSUSED */
27389 void
27390 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27391 {
27392 	mblk_t		*mp1;
27393 	ire_t		*ire, *fake_ire;
27394 	ill_t		*ill;
27395 	struct iocblk	*iocp;
27396 	ip_ioctl_cmd_t	*ipip;
27397 	cred_t		*cr;
27398 	conn_t		*connp;
27399 	int		cmd, err;
27400 	nce_t		*nce;
27401 	ipif_t		*ipif;
27402 	ip_stack_t	*ipst;
27403 	char		*proto_str;
27404 
27405 	if (CONN_Q(q)) {
27406 		connp = Q_TO_CONN(q);
27407 		ipst = connp->conn_netstack->netstack_ip;
27408 	} else {
27409 		connp = NULL;
27410 		ipst = ILLQ_TO_IPST(q);
27411 	}
27412 
27413 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27414 
27415 	/* Check if it is a queue to /dev/sctp. */
27416 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27417 	    connp->conn_rq == NULL) {
27418 		sctp_wput(q, mp);
27419 		return;
27420 	}
27421 
27422 	switch (DB_TYPE(mp)) {
27423 	case M_IOCTL:
27424 		/*
27425 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27426 		 * will arrange to copy in associated control structures.
27427 		 */
27428 		ip_sioctl_copyin_setup(q, mp);
27429 		return;
27430 	case M_IOCDATA:
27431 		/*
27432 		 * Ensure that this is associated with one of our trans-
27433 		 * parent ioctls.  If it's not ours, discard it if we're
27434 		 * running as a driver, or pass it on if we're a module.
27435 		 */
27436 		iocp = (struct iocblk *)mp->b_rptr;
27437 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27438 		if (ipip == NULL) {
27439 			if (q->q_next == NULL) {
27440 				goto nak;
27441 			} else {
27442 				putnext(q, mp);
27443 			}
27444 			return;
27445 		} else if ((q->q_next != NULL) &&
27446 		    !(ipip->ipi_flags & IPI_MODOK)) {
27447 			/*
27448 			 * the ioctl is one we recognise, but is not
27449 			 * consumed by IP as a module, pass M_IOCDATA
27450 			 * for processing downstream, but only for
27451 			 * common Streams ioctls.
27452 			 */
27453 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27454 				putnext(q, mp);
27455 				return;
27456 			} else {
27457 				goto nak;
27458 			}
27459 		}
27460 
27461 		/* IOCTL continuation following copyin or copyout. */
27462 		if (mi_copy_state(q, mp, NULL) == -1) {
27463 			/*
27464 			 * The copy operation failed.  mi_copy_state already
27465 			 * cleaned up, so we're out of here.
27466 			 */
27467 			return;
27468 		}
27469 		/*
27470 		 * If we just completed a copy in, we become writer and
27471 		 * continue processing in ip_sioctl_copyin_done.  If it
27472 		 * was a copy out, we call mi_copyout again.  If there is
27473 		 * nothing more to copy out, it will complete the IOCTL.
27474 		 */
27475 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27476 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27477 				mi_copy_done(q, mp, EPROTO);
27478 				return;
27479 			}
27480 			/*
27481 			 * Check for cases that need more copying.  A return
27482 			 * value of 0 means a second copyin has been started,
27483 			 * so we return; a return value of 1 means no more
27484 			 * copying is needed, so we continue.
27485 			 */
27486 			cmd = iocp->ioc_cmd;
27487 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27488 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27489 			    MI_COPY_COUNT(mp) == 1) {
27490 				if (ip_copyin_msfilter(q, mp) == 0)
27491 					return;
27492 			}
27493 			/*
27494 			 * Refhold the conn, till the ioctl completes. This is
27495 			 * needed in case the ioctl ends up in the pending mp
27496 			 * list. Every mp in the ill_pending_mp list and
27497 			 * the ipsq_pending_mp must have a refhold on the conn
27498 			 * to resume processing. The refhold is released when
27499 			 * the ioctl completes. (normally or abnormally)
27500 			 * In all cases ip_ioctl_finish is called to finish
27501 			 * the ioctl.
27502 			 */
27503 			if (connp != NULL) {
27504 				/* This is not a reentry */
27505 				ASSERT(ipsq == NULL);
27506 				CONN_INC_REF(connp);
27507 			} else {
27508 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27509 					mi_copy_done(q, mp, EINVAL);
27510 					return;
27511 				}
27512 			}
27513 
27514 			ip_process_ioctl(ipsq, q, mp, ipip);
27515 
27516 		} else {
27517 			mi_copyout(q, mp);
27518 		}
27519 		return;
27520 nak:
27521 		iocp->ioc_error = EINVAL;
27522 		mp->b_datap->db_type = M_IOCNAK;
27523 		iocp->ioc_count = 0;
27524 		qreply(q, mp);
27525 		return;
27526 
27527 	case M_IOCNAK:
27528 		/*
27529 		 * The only way we could get here is if a resolver didn't like
27530 		 * an IOCTL we sent it.	 This shouldn't happen.
27531 		 */
27532 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27533 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27534 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27535 		freemsg(mp);
27536 		return;
27537 	case M_IOCACK:
27538 		/* /dev/ip shouldn't see this */
27539 		if (CONN_Q(q))
27540 			goto nak;
27541 
27542 		/* Finish socket ioctls passed through to ARP. */
27543 		ip_sioctl_iocack(q, mp);
27544 		return;
27545 	case M_FLUSH:
27546 		if (*mp->b_rptr & FLUSHW)
27547 			flushq(q, FLUSHALL);
27548 		if (q->q_next) {
27549 			putnext(q, mp);
27550 			return;
27551 		}
27552 		if (*mp->b_rptr & FLUSHR) {
27553 			*mp->b_rptr &= ~FLUSHW;
27554 			qreply(q, mp);
27555 			return;
27556 		}
27557 		freemsg(mp);
27558 		return;
27559 	case IRE_DB_REQ_TYPE:
27560 		if (connp == NULL) {
27561 			proto_str = "IRE_DB_REQ_TYPE";
27562 			goto protonak;
27563 		}
27564 		/* An Upper Level Protocol wants a copy of an IRE. */
27565 		ip_ire_req(q, mp);
27566 		return;
27567 	case M_CTL:
27568 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27569 			break;
27570 
27571 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27572 		    TUN_HELLO) {
27573 			ASSERT(connp != NULL);
27574 			connp->conn_flags |= IPCL_IPTUN;
27575 			freeb(mp);
27576 			return;
27577 		}
27578 
27579 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27580 		    IP_ULP_OUT_LABELED) {
27581 			out_labeled_t *olp;
27582 
27583 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27584 				break;
27585 			olp = (out_labeled_t *)mp->b_rptr;
27586 			connp->conn_ulp_labeled = olp->out_qnext == q;
27587 			freemsg(mp);
27588 			return;
27589 		}
27590 
27591 		/* M_CTL messages are used by ARP to tell us things. */
27592 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27593 			break;
27594 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27595 		case AR_ENTRY_SQUERY:
27596 			ip_wput_ctl(q, mp);
27597 			return;
27598 		case AR_CLIENT_NOTIFY:
27599 			ip_arp_news(q, mp);
27600 			return;
27601 		case AR_DLPIOP_DONE:
27602 			ASSERT(q->q_next != NULL);
27603 			ill = (ill_t *)q->q_ptr;
27604 			/* qwriter_ip releases the refhold */
27605 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27606 			ill_refhold(ill);
27607 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27608 			return;
27609 		case AR_ARP_CLOSING:
27610 			/*
27611 			 * ARP (above us) is closing. If no ARP bringup is
27612 			 * currently pending, ack the message so that ARP
27613 			 * can complete its close. Also mark ill_arp_closing
27614 			 * so that new ARP bringups will fail. If any
27615 			 * ARP bringup is currently in progress, we will
27616 			 * ack this when the current ARP bringup completes.
27617 			 */
27618 			ASSERT(q->q_next != NULL);
27619 			ill = (ill_t *)q->q_ptr;
27620 			mutex_enter(&ill->ill_lock);
27621 			ill->ill_arp_closing = 1;
27622 			if (!ill->ill_arp_bringup_pending) {
27623 				mutex_exit(&ill->ill_lock);
27624 				qreply(q, mp);
27625 			} else {
27626 				mutex_exit(&ill->ill_lock);
27627 				freemsg(mp);
27628 			}
27629 			return;
27630 		case AR_ARP_EXTEND:
27631 			/*
27632 			 * The ARP module above us is capable of duplicate
27633 			 * address detection.  Old ATM drivers will not send
27634 			 * this message.
27635 			 */
27636 			ASSERT(q->q_next != NULL);
27637 			ill = (ill_t *)q->q_ptr;
27638 			ill->ill_arp_extend = B_TRUE;
27639 			freemsg(mp);
27640 			return;
27641 		default:
27642 			break;
27643 		}
27644 		break;
27645 	case M_PROTO:
27646 	case M_PCPROTO:
27647 		/*
27648 		 * The only PROTO messages we expect are ULP binds and
27649 		 * copies of option negotiation acknowledgements.
27650 		 */
27651 		switch (((union T_primitives *)mp->b_rptr)->type) {
27652 		case O_T_BIND_REQ:
27653 		case T_BIND_REQ: {
27654 			/* Request can get queued in bind */
27655 			if (connp == NULL) {
27656 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27657 				goto protonak;
27658 			}
27659 			/*
27660 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27661 			 * instead of going through this path.  We only get
27662 			 * here in the following cases:
27663 			 *
27664 			 * a. Bind retries, where ipsq is non-NULL.
27665 			 * b. T_BIND_REQ is issued from non TCP/UDP
27666 			 *    transport, e.g. icmp for raw socket,
27667 			 *    in which case ipsq will be NULL.
27668 			 */
27669 			ASSERT(ipsq != NULL ||
27670 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27671 
27672 			/* Don't increment refcnt if this is a re-entry */
27673 			if (ipsq == NULL)
27674 				CONN_INC_REF(connp);
27675 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27676 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27677 			if (mp == NULL)
27678 				return;
27679 			if (IPCL_IS_TCP(connp)) {
27680 				/*
27681 				 * In the case of TCP endpoint we
27682 				 * come here only for bind retries
27683 				 */
27684 				ASSERT(ipsq != NULL);
27685 				CONN_INC_REF(connp);
27686 				squeue_fill(connp->conn_sqp, mp,
27687 				    ip_resume_tcp_bind, connp,
27688 				    SQTAG_BIND_RETRY);
27689 				return;
27690 			} else if (IPCL_IS_UDP(connp)) {
27691 				/*
27692 				 * In the case of UDP endpoint we
27693 				 * come here only for bind retries
27694 				 */
27695 				ASSERT(ipsq != NULL);
27696 				udp_resume_bind(connp, mp);
27697 				return;
27698 			}
27699 			qreply(q, mp);
27700 			CONN_OPER_PENDING_DONE(connp);
27701 			return;
27702 		}
27703 		case T_SVR4_OPTMGMT_REQ:
27704 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27705 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27706 
27707 			if (connp == NULL) {
27708 				proto_str = "T_SVR4_OPTMGMT_REQ";
27709 				goto protonak;
27710 			}
27711 
27712 			if (!snmpcom_req(q, mp, ip_snmp_set,
27713 			    ip_snmp_get, cr)) {
27714 				/*
27715 				 * Call svr4_optcom_req so that it can
27716 				 * generate the ack. We don't come here
27717 				 * if this operation is being restarted.
27718 				 * ip_restart_optmgmt will drop the conn ref.
27719 				 * In the case of ipsec option after the ipsec
27720 				 * load is complete conn_restart_ipsec_waiter
27721 				 * drops the conn ref.
27722 				 */
27723 				ASSERT(ipsq == NULL);
27724 				CONN_INC_REF(connp);
27725 				if (ip_check_for_ipsec_opt(q, mp))
27726 					return;
27727 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27728 				if (err != EINPROGRESS) {
27729 					/* Operation is done */
27730 					CONN_OPER_PENDING_DONE(connp);
27731 				}
27732 			}
27733 			return;
27734 		case T_OPTMGMT_REQ:
27735 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27736 			/*
27737 			 * Note: No snmpcom_req support through new
27738 			 * T_OPTMGMT_REQ.
27739 			 * Call tpi_optcom_req so that it can
27740 			 * generate the ack.
27741 			 */
27742 			if (connp == NULL) {
27743 				proto_str = "T_OPTMGMT_REQ";
27744 				goto protonak;
27745 			}
27746 
27747 			ASSERT(ipsq == NULL);
27748 			/*
27749 			 * We don't come here for restart. ip_restart_optmgmt
27750 			 * will drop the conn ref. In the case of ipsec option
27751 			 * after the ipsec load is complete
27752 			 * conn_restart_ipsec_waiter drops the conn ref.
27753 			 */
27754 			CONN_INC_REF(connp);
27755 			if (ip_check_for_ipsec_opt(q, mp))
27756 				return;
27757 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27758 			if (err != EINPROGRESS) {
27759 				/* Operation is done */
27760 				CONN_OPER_PENDING_DONE(connp);
27761 			}
27762 			return;
27763 		case T_UNBIND_REQ:
27764 			if (connp == NULL) {
27765 				proto_str = "T_UNBIND_REQ";
27766 				goto protonak;
27767 			}
27768 			mp = ip_unbind(q, mp);
27769 			qreply(q, mp);
27770 			return;
27771 		default:
27772 			/*
27773 			 * Have to drop any DLPI messages coming down from
27774 			 * arp (such as an info_req which would cause ip
27775 			 * to receive an extra info_ack if it was passed
27776 			 * through.
27777 			 */
27778 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27779 			    (int)*(uint_t *)mp->b_rptr));
27780 			freemsg(mp);
27781 			return;
27782 		}
27783 		/* NOTREACHED */
27784 	case IRE_DB_TYPE: {
27785 		nce_t		*nce;
27786 		ill_t		*ill;
27787 		in6_addr_t	gw_addr_v6;
27788 
27789 
27790 		/*
27791 		 * This is a response back from a resolver.  It
27792 		 * consists of a message chain containing:
27793 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27794 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27795 		 * The LL_HDR_MBLK is the DLPI header to use to get
27796 		 * the attached packet, and subsequent ones for the
27797 		 * same destination, transmitted.
27798 		 */
27799 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27800 			break;
27801 		/*
27802 		 * First, check to make sure the resolution succeeded.
27803 		 * If it failed, the second mblk will be empty.
27804 		 * If it is, free the chain, dropping the packet.
27805 		 * (We must ire_delete the ire; that frees the ire mblk)
27806 		 * We're doing this now to support PVCs for ATM; it's
27807 		 * a partial xresolv implementation. When we fully implement
27808 		 * xresolv interfaces, instead of freeing everything here
27809 		 * we'll initiate neighbor discovery.
27810 		 *
27811 		 * For v4 (ARP and other external resolvers) the resolver
27812 		 * frees the message, so no check is needed. This check
27813 		 * is required, though, for a full xresolve implementation.
27814 		 * Including this code here now both shows how external
27815 		 * resolvers can NACK a resolution request using an
27816 		 * existing design that has no specific provisions for NACKs,
27817 		 * and also takes into account that the current non-ARP
27818 		 * external resolver has been coded to use this method of
27819 		 * NACKing for all IPv6 (xresolv) cases,
27820 		 * whether our xresolv implementation is complete or not.
27821 		 *
27822 		 */
27823 		ire = (ire_t *)mp->b_rptr;
27824 		ill = ire_to_ill(ire);
27825 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27826 		if (mp1->b_rptr == mp1->b_wptr) {
27827 			if (ire->ire_ipversion == IPV6_VERSION) {
27828 				/*
27829 				 * XRESOLV interface.
27830 				 */
27831 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27832 				mutex_enter(&ire->ire_lock);
27833 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27834 				mutex_exit(&ire->ire_lock);
27835 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27836 					nce = ndp_lookup_v6(ill,
27837 					    &ire->ire_addr_v6, B_FALSE);
27838 				} else {
27839 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27840 					    B_FALSE);
27841 				}
27842 				if (nce != NULL) {
27843 					nce_resolv_failed(nce);
27844 					ndp_delete(nce);
27845 					NCE_REFRELE(nce);
27846 				}
27847 			}
27848 			mp->b_cont = NULL;
27849 			freemsg(mp1);		/* frees the pkt as well */
27850 			ASSERT(ire->ire_nce == NULL);
27851 			ire_delete((ire_t *)mp->b_rptr);
27852 			return;
27853 		}
27854 
27855 		/*
27856 		 * Split them into IRE_MBLK and pkt and feed it into
27857 		 * ire_add_then_send. Then in ire_add_then_send
27858 		 * the IRE will be added, and then the packet will be
27859 		 * run back through ip_wput. This time it will make
27860 		 * it to the wire.
27861 		 */
27862 		mp->b_cont = NULL;
27863 		mp = mp1->b_cont;		/* now, mp points to pkt */
27864 		mp1->b_cont = NULL;
27865 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27866 		if (ire->ire_ipversion == IPV6_VERSION) {
27867 			/*
27868 			 * XRESOLV interface. Find the nce and put a copy
27869 			 * of the dl_unitdata_req in nce_res_mp
27870 			 */
27871 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27872 			mutex_enter(&ire->ire_lock);
27873 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27874 			mutex_exit(&ire->ire_lock);
27875 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27876 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27877 				    B_FALSE);
27878 			} else {
27879 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27880 			}
27881 			if (nce != NULL) {
27882 				/*
27883 				 * We have to protect nce_res_mp here
27884 				 * from being accessed by other threads
27885 				 * while we change the mblk pointer.
27886 				 * Other functions will also lock the nce when
27887 				 * accessing nce_res_mp.
27888 				 *
27889 				 * The reason we change the mblk pointer
27890 				 * here rather than copying the resolved address
27891 				 * into the template is that, unlike with
27892 				 * ethernet, we have no guarantee that the
27893 				 * resolved address length will be
27894 				 * smaller than or equal to the lla length
27895 				 * with which the template was allocated,
27896 				 * (for ethernet, they're equal)
27897 				 * so we have to use the actual resolved
27898 				 * address mblk - which holds the real
27899 				 * dl_unitdata_req with the resolved address.
27900 				 *
27901 				 * Doing this is the same behavior as was
27902 				 * previously used in the v4 ARP case.
27903 				 */
27904 				mutex_enter(&nce->nce_lock);
27905 				if (nce->nce_res_mp != NULL)
27906 					freemsg(nce->nce_res_mp);
27907 				nce->nce_res_mp = mp1;
27908 				mutex_exit(&nce->nce_lock);
27909 				/*
27910 				 * We do a fastpath probe here because
27911 				 * we have resolved the address without
27912 				 * using Neighbor Discovery.
27913 				 * In the non-XRESOLV v6 case, the fastpath
27914 				 * probe is done right after neighbor
27915 				 * discovery completes.
27916 				 */
27917 				if (nce->nce_res_mp != NULL) {
27918 					int res;
27919 					nce_fastpath_list_add(nce);
27920 					res = ill_fastpath_probe(ill,
27921 					    nce->nce_res_mp);
27922 					if (res != 0 && res != EAGAIN)
27923 						nce_fastpath_list_delete(nce);
27924 				}
27925 
27926 				ire_add_then_send(q, ire, mp);
27927 				/*
27928 				 * Now we have to clean out any packets
27929 				 * that may have been queued on the nce
27930 				 * while it was waiting for address resolution
27931 				 * to complete.
27932 				 */
27933 				mutex_enter(&nce->nce_lock);
27934 				mp1 = nce->nce_qd_mp;
27935 				nce->nce_qd_mp = NULL;
27936 				mutex_exit(&nce->nce_lock);
27937 				while (mp1 != NULL) {
27938 					mblk_t *nxt_mp;
27939 					queue_t *fwdq = NULL;
27940 					ill_t   *inbound_ill;
27941 					uint_t ifindex;
27942 
27943 					nxt_mp = mp1->b_next;
27944 					mp1->b_next = NULL;
27945 					/*
27946 					 * Retrieve ifindex stored in
27947 					 * ip_rput_data_v6()
27948 					 */
27949 					ifindex =
27950 					    (uint_t)(uintptr_t)mp1->b_prev;
27951 					inbound_ill =
27952 					    ill_lookup_on_ifindex(ifindex,
27953 					    B_TRUE, NULL, NULL, NULL,
27954 					    NULL, ipst);
27955 					mp1->b_prev = NULL;
27956 					if (inbound_ill != NULL)
27957 						fwdq = inbound_ill->ill_rq;
27958 
27959 					if (fwdq != NULL) {
27960 						put(fwdq, mp1);
27961 						ill_refrele(inbound_ill);
27962 					} else
27963 						put(WR(ill->ill_rq), mp1);
27964 					mp1 = nxt_mp;
27965 				}
27966 				NCE_REFRELE(nce);
27967 			} else {	/* nce is NULL; clean up */
27968 				ire_delete(ire);
27969 				freemsg(mp);
27970 				freemsg(mp1);
27971 				return;
27972 			}
27973 		} else {
27974 			nce_t *arpce;
27975 			/*
27976 			 * Link layer resolution succeeded. Recompute the
27977 			 * ire_nce.
27978 			 */
27979 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27980 			if ((arpce = ndp_lookup_v4(ill,
27981 			    (ire->ire_gateway_addr != INADDR_ANY ?
27982 			    &ire->ire_gateway_addr : &ire->ire_addr),
27983 			    B_FALSE)) == NULL) {
27984 				freeb(ire->ire_mp);
27985 				freeb(mp1);
27986 				freemsg(mp);
27987 				return;
27988 			}
27989 			mutex_enter(&arpce->nce_lock);
27990 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27991 			if (arpce->nce_state == ND_REACHABLE) {
27992 				/*
27993 				 * Someone resolved this before us;
27994 				 * cleanup the res_mp. Since ire has
27995 				 * not been added yet, the call to ire_add_v4
27996 				 * from ire_add_then_send (when a dup is
27997 				 * detected) will clean up the ire.
27998 				 */
27999 				freeb(mp1);
28000 			} else {
28001 				ASSERT(arpce->nce_res_mp == NULL);
28002 				arpce->nce_res_mp = mp1;
28003 				arpce->nce_state = ND_REACHABLE;
28004 			}
28005 			mutex_exit(&arpce->nce_lock);
28006 			if (ire->ire_marks & IRE_MARK_NOADD) {
28007 				/*
28008 				 * this ire will not be added to the ire
28009 				 * cache table, so we can set the ire_nce
28010 				 * here, as there are no atomicity constraints.
28011 				 */
28012 				ire->ire_nce = arpce;
28013 				/*
28014 				 * We are associating this nce with the ire
28015 				 * so change the nce ref taken in
28016 				 * ndp_lookup_v4() from
28017 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28018 				 */
28019 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28020 			} else {
28021 				NCE_REFRELE(arpce);
28022 			}
28023 			ire_add_then_send(q, ire, mp);
28024 		}
28025 		return;	/* All is well, the packet has been sent. */
28026 	}
28027 	case IRE_ARPRESOLVE_TYPE: {
28028 
28029 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28030 			break;
28031 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28032 		mp->b_cont = NULL;
28033 		/*
28034 		 * First, check to make sure the resolution succeeded.
28035 		 * If it failed, the second mblk will be empty.
28036 		 */
28037 		if (mp1->b_rptr == mp1->b_wptr) {
28038 			/* cleanup  the incomplete ire, free queued packets */
28039 			freemsg(mp); /* fake ire */
28040 			freeb(mp1);  /* dl_unitdata response */
28041 			return;
28042 		}
28043 
28044 		/*
28045 		 * update any incomplete nce_t found. we lookup the ctable
28046 		 * and find the nce from the ire->ire_nce because we need
28047 		 * to pass the ire to ip_xmit_v4 later, and can find both
28048 		 * ire and nce in one lookup from the ctable.
28049 		 */
28050 		fake_ire = (ire_t *)mp->b_rptr;
28051 		/*
28052 		 * By the time we come back here from ARP
28053 		 * the logical outgoing interface  of the incomplete ire
28054 		 * we added in ire_forward could have disappeared,
28055 		 * causing the incomplete ire to also have
28056 		 * dissapeared. So we need to retreive the
28057 		 * proper ipif for the ire  before looking
28058 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28059 		 */
28060 		ill = q->q_ptr;
28061 
28062 		/* Get the outgoing ipif */
28063 		mutex_enter(&ill->ill_lock);
28064 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28065 			mutex_exit(&ill->ill_lock);
28066 			freemsg(mp); /* fake ire */
28067 			freeb(mp1);  /* dl_unitdata response */
28068 			return;
28069 		}
28070 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28071 
28072 		if (ipif == NULL) {
28073 			mutex_exit(&ill->ill_lock);
28074 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28075 			freemsg(mp);
28076 			freeb(mp1);
28077 			return;
28078 		}
28079 		ipif_refhold_locked(ipif);
28080 		mutex_exit(&ill->ill_lock);
28081 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28082 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28083 		    ipif, fake_ire->ire_zoneid, NULL,
28084 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28085 		ipif_refrele(ipif);
28086 		if (ire == NULL) {
28087 			/*
28088 			 * no ire was found; check if there is an nce
28089 			 * for this lookup; if it has no ire's pointing at it
28090 			 * cleanup.
28091 			 */
28092 			if ((nce = ndp_lookup_v4(ill,
28093 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28094 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28095 			    B_FALSE)) != NULL) {
28096 				/*
28097 				 * cleanup:
28098 				 * We check for refcnt 2 (one for the nce
28099 				 * hash list + 1 for the ref taken by
28100 				 * ndp_lookup_v4) to check that there are
28101 				 * no ire's pointing at the nce.
28102 				 */
28103 				if (nce->nce_refcnt == 2)
28104 					ndp_delete(nce);
28105 				NCE_REFRELE(nce);
28106 			}
28107 			freeb(mp1);  /* dl_unitdata response */
28108 			freemsg(mp); /* fake ire */
28109 			return;
28110 		}
28111 		nce = ire->ire_nce;
28112 		DTRACE_PROBE2(ire__arpresolve__type,
28113 		    ire_t *, ire, nce_t *, nce);
28114 		ASSERT(nce->nce_state != ND_INITIAL);
28115 		mutex_enter(&nce->nce_lock);
28116 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28117 		if (nce->nce_state == ND_REACHABLE) {
28118 			/*
28119 			 * Someone resolved this before us;
28120 			 * our response is not needed any more.
28121 			 */
28122 			mutex_exit(&nce->nce_lock);
28123 			freeb(mp1);  /* dl_unitdata response */
28124 		} else {
28125 			ASSERT(nce->nce_res_mp == NULL);
28126 			nce->nce_res_mp = mp1;
28127 			nce->nce_state = ND_REACHABLE;
28128 			mutex_exit(&nce->nce_lock);
28129 			nce_fastpath(nce);
28130 		}
28131 		/*
28132 		 * The cached nce_t has been updated to be reachable;
28133 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
28134 		 */
28135 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28136 		freemsg(mp);
28137 		/*
28138 		 * send out queued packets.
28139 		 */
28140 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28141 
28142 		IRE_REFRELE(ire);
28143 		return;
28144 	}
28145 	default:
28146 		break;
28147 	}
28148 	if (q->q_next) {
28149 		putnext(q, mp);
28150 	} else
28151 		freemsg(mp);
28152 	return;
28153 
28154 protonak:
28155 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28156 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28157 		qreply(q, mp);
28158 }
28159 
28160 /*
28161  * Process IP options in an outbound packet.  Modify the destination if there
28162  * is a source route option.
28163  * Returns non-zero if something fails in which case an ICMP error has been
28164  * sent and mp freed.
28165  */
28166 static int
28167 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28168     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28169 {
28170 	ipoptp_t	opts;
28171 	uchar_t		*opt;
28172 	uint8_t		optval;
28173 	uint8_t		optlen;
28174 	ipaddr_t	dst;
28175 	intptr_t	code = 0;
28176 	mblk_t		*mp;
28177 	ire_t		*ire = NULL;
28178 
28179 	ip2dbg(("ip_wput_options\n"));
28180 	mp = ipsec_mp;
28181 	if (mctl_present) {
28182 		mp = ipsec_mp->b_cont;
28183 	}
28184 
28185 	dst = ipha->ipha_dst;
28186 	for (optval = ipoptp_first(&opts, ipha);
28187 	    optval != IPOPT_EOL;
28188 	    optval = ipoptp_next(&opts)) {
28189 		opt = opts.ipoptp_cur;
28190 		optlen = opts.ipoptp_len;
28191 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28192 		    optval, optlen));
28193 		switch (optval) {
28194 			uint32_t off;
28195 		case IPOPT_SSRR:
28196 		case IPOPT_LSRR:
28197 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28198 				ip1dbg((
28199 				    "ip_wput_options: bad option offset\n"));
28200 				code = (char *)&opt[IPOPT_OLEN] -
28201 				    (char *)ipha;
28202 				goto param_prob;
28203 			}
28204 			off = opt[IPOPT_OFFSET];
28205 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28206 			    ntohl(dst)));
28207 			/*
28208 			 * For strict: verify that dst is directly
28209 			 * reachable.
28210 			 */
28211 			if (optval == IPOPT_SSRR) {
28212 				ire = ire_ftable_lookup(dst, 0, 0,
28213 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28214 				    MBLK_GETLABEL(mp),
28215 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28216 				if (ire == NULL) {
28217 					ip1dbg(("ip_wput_options: SSRR not"
28218 					    " directly reachable: 0x%x\n",
28219 					    ntohl(dst)));
28220 					goto bad_src_route;
28221 				}
28222 				ire_refrele(ire);
28223 			}
28224 			break;
28225 		case IPOPT_RR:
28226 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28227 				ip1dbg((
28228 				    "ip_wput_options: bad option offset\n"));
28229 				code = (char *)&opt[IPOPT_OLEN] -
28230 				    (char *)ipha;
28231 				goto param_prob;
28232 			}
28233 			break;
28234 		case IPOPT_TS:
28235 			/*
28236 			 * Verify that length >=5 and that there is either
28237 			 * room for another timestamp or that the overflow
28238 			 * counter is not maxed out.
28239 			 */
28240 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28241 			if (optlen < IPOPT_MINLEN_IT) {
28242 				goto param_prob;
28243 			}
28244 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28245 				ip1dbg((
28246 				    "ip_wput_options: bad option offset\n"));
28247 				code = (char *)&opt[IPOPT_OFFSET] -
28248 				    (char *)ipha;
28249 				goto param_prob;
28250 			}
28251 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28252 			case IPOPT_TS_TSONLY:
28253 				off = IPOPT_TS_TIMELEN;
28254 				break;
28255 			case IPOPT_TS_TSANDADDR:
28256 			case IPOPT_TS_PRESPEC:
28257 			case IPOPT_TS_PRESPEC_RFC791:
28258 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28259 				break;
28260 			default:
28261 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28262 				    (char *)ipha;
28263 				goto param_prob;
28264 			}
28265 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28266 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28267 				/*
28268 				 * No room and the overflow counter is 15
28269 				 * already.
28270 				 */
28271 				goto param_prob;
28272 			}
28273 			break;
28274 		}
28275 	}
28276 
28277 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28278 		return (0);
28279 
28280 	ip1dbg(("ip_wput_options: error processing IP options."));
28281 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28282 
28283 param_prob:
28284 	/*
28285 	 * Since ip_wput() isn't close to finished, we fill
28286 	 * in enough of the header for credible error reporting.
28287 	 */
28288 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28289 		/* Failed */
28290 		freemsg(ipsec_mp);
28291 		return (-1);
28292 	}
28293 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28294 	return (-1);
28295 
28296 bad_src_route:
28297 	/*
28298 	 * Since ip_wput() isn't close to finished, we fill
28299 	 * in enough of the header for credible error reporting.
28300 	 */
28301 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28302 		/* Failed */
28303 		freemsg(ipsec_mp);
28304 		return (-1);
28305 	}
28306 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28307 	return (-1);
28308 }
28309 
28310 /*
28311  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28312  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28313  * thru /etc/system.
28314  */
28315 #define	CONN_MAXDRAINCNT	64
28316 
28317 static void
28318 conn_drain_init(ip_stack_t *ipst)
28319 {
28320 	int i;
28321 
28322 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28323 
28324 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28325 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28326 		/*
28327 		 * Default value of the number of drainers is the
28328 		 * number of cpus, subject to maximum of 8 drainers.
28329 		 */
28330 		if (boot_max_ncpus != -1)
28331 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28332 		else
28333 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28334 	}
28335 
28336 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28337 	    sizeof (idl_t), KM_SLEEP);
28338 
28339 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28340 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28341 		    MUTEX_DEFAULT, NULL);
28342 	}
28343 }
28344 
28345 static void
28346 conn_drain_fini(ip_stack_t *ipst)
28347 {
28348 	int i;
28349 
28350 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28351 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28352 	kmem_free(ipst->ips_conn_drain_list,
28353 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28354 	ipst->ips_conn_drain_list = NULL;
28355 }
28356 
28357 /*
28358  * Note: For an overview of how flowcontrol is handled in IP please see the
28359  * IP Flowcontrol notes at the top of this file.
28360  *
28361  * Flow control has blocked us from proceeding. Insert the given conn in one
28362  * of the conn drain lists. These conn wq's will be qenabled later on when
28363  * STREAMS flow control does a backenable. conn_walk_drain will enable
28364  * the first conn in each of these drain lists. Each of these qenabled conns
28365  * in turn enables the next in the list, after it runs, or when it closes,
28366  * thus sustaining the drain process.
28367  *
28368  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28369  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28370  * running at any time, on a given conn, since there can be only 1 service proc
28371  * running on a queue at any time.
28372  */
28373 void
28374 conn_drain_insert(conn_t *connp)
28375 {
28376 	idl_t	*idl;
28377 	uint_t	index;
28378 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28379 
28380 	mutex_enter(&connp->conn_lock);
28381 	if (connp->conn_state_flags & CONN_CLOSING) {
28382 		/*
28383 		 * The conn is closing as a result of which CONN_CLOSING
28384 		 * is set. Return.
28385 		 */
28386 		mutex_exit(&connp->conn_lock);
28387 		return;
28388 	} else if (connp->conn_idl == NULL) {
28389 		/*
28390 		 * Assign the next drain list round robin. We dont' use
28391 		 * a lock, and thus it may not be strictly round robin.
28392 		 * Atomicity of load/stores is enough to make sure that
28393 		 * conn_drain_list_index is always within bounds.
28394 		 */
28395 		index = ipst->ips_conn_drain_list_index;
28396 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28397 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28398 		index++;
28399 		if (index == ipst->ips_conn_drain_list_cnt)
28400 			index = 0;
28401 		ipst->ips_conn_drain_list_index = index;
28402 	}
28403 	mutex_exit(&connp->conn_lock);
28404 
28405 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28406 	if ((connp->conn_drain_prev != NULL) ||
28407 	    (connp->conn_state_flags & CONN_CLOSING)) {
28408 		/*
28409 		 * The conn is already in the drain list, OR
28410 		 * the conn is closing. We need to check again for
28411 		 * the closing case again since close can happen
28412 		 * after we drop the conn_lock, and before we
28413 		 * acquire the CONN_DRAIN_LIST_LOCK.
28414 		 */
28415 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28416 		return;
28417 	} else {
28418 		idl = connp->conn_idl;
28419 	}
28420 
28421 	/*
28422 	 * The conn is not in the drain list. Insert it at the
28423 	 * tail of the drain list. The drain list is circular
28424 	 * and doubly linked. idl_conn points to the 1st element
28425 	 * in the list.
28426 	 */
28427 	if (idl->idl_conn == NULL) {
28428 		idl->idl_conn = connp;
28429 		connp->conn_drain_next = connp;
28430 		connp->conn_drain_prev = connp;
28431 	} else {
28432 		conn_t *head = idl->idl_conn;
28433 
28434 		connp->conn_drain_next = head;
28435 		connp->conn_drain_prev = head->conn_drain_prev;
28436 		head->conn_drain_prev->conn_drain_next = connp;
28437 		head->conn_drain_prev = connp;
28438 	}
28439 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28440 }
28441 
28442 /*
28443  * This conn is closing, and we are called from ip_close. OR
28444  * This conn has been serviced by ip_wsrv, and we need to do the tail
28445  * processing.
28446  * If this conn is part of the drain list, we may need to sustain the drain
28447  * process by qenabling the next conn in the drain list. We may also need to
28448  * remove this conn from the list, if it is done.
28449  */
28450 static void
28451 conn_drain_tail(conn_t *connp, boolean_t closing)
28452 {
28453 	idl_t *idl;
28454 
28455 	/*
28456 	 * connp->conn_idl is stable at this point, and no lock is needed
28457 	 * to check it. If we are called from ip_close, close has already
28458 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28459 	 * called us only because conn_idl is non-null. If we are called thru
28460 	 * service, conn_idl could be null, but it cannot change because
28461 	 * service is single-threaded per queue, and there cannot be another
28462 	 * instance of service trying to call conn_drain_insert on this conn
28463 	 * now.
28464 	 */
28465 	ASSERT(!closing || (connp->conn_idl != NULL));
28466 
28467 	/*
28468 	 * If connp->conn_idl is null, the conn has not been inserted into any
28469 	 * drain list even once since creation of the conn. Just return.
28470 	 */
28471 	if (connp->conn_idl == NULL)
28472 		return;
28473 
28474 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28475 
28476 	if (connp->conn_drain_prev == NULL) {
28477 		/* This conn is currently not in the drain list.  */
28478 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28479 		return;
28480 	}
28481 	idl = connp->conn_idl;
28482 	if (idl->idl_conn_draining == connp) {
28483 		/*
28484 		 * This conn is the current drainer. If this is the last conn
28485 		 * in the drain list, we need to do more checks, in the 'if'
28486 		 * below. Otherwwise we need to just qenable the next conn,
28487 		 * to sustain the draining, and is handled in the 'else'
28488 		 * below.
28489 		 */
28490 		if (connp->conn_drain_next == idl->idl_conn) {
28491 			/*
28492 			 * This conn is the last in this list. This round
28493 			 * of draining is complete. If idl_repeat is set,
28494 			 * it means another flow enabling has happened from
28495 			 * the driver/streams and we need to another round
28496 			 * of draining.
28497 			 * If there are more than 2 conns in the drain list,
28498 			 * do a left rotate by 1, so that all conns except the
28499 			 * conn at the head move towards the head by 1, and the
28500 			 * the conn at the head goes to the tail. This attempts
28501 			 * a more even share for all queues that are being
28502 			 * drained.
28503 			 */
28504 			if ((connp->conn_drain_next != connp) &&
28505 			    (idl->idl_conn->conn_drain_next != connp)) {
28506 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28507 			}
28508 			if (idl->idl_repeat) {
28509 				qenable(idl->idl_conn->conn_wq);
28510 				idl->idl_conn_draining = idl->idl_conn;
28511 				idl->idl_repeat = 0;
28512 			} else {
28513 				idl->idl_conn_draining = NULL;
28514 			}
28515 		} else {
28516 			/*
28517 			 * If the next queue that we are now qenable'ing,
28518 			 * is closing, it will remove itself from this list
28519 			 * and qenable the subsequent queue in ip_close().
28520 			 * Serialization is acheived thru idl_lock.
28521 			 */
28522 			qenable(connp->conn_drain_next->conn_wq);
28523 			idl->idl_conn_draining = connp->conn_drain_next;
28524 		}
28525 	}
28526 	if (!connp->conn_did_putbq || closing) {
28527 		/*
28528 		 * Remove ourself from the drain list, if we did not do
28529 		 * a putbq, or if the conn is closing.
28530 		 * Note: It is possible that q->q_first is non-null. It means
28531 		 * that these messages landed after we did a enableok() in
28532 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28533 		 * service them.
28534 		 */
28535 		if (connp->conn_drain_next == connp) {
28536 			/* Singleton in the list */
28537 			ASSERT(connp->conn_drain_prev == connp);
28538 			idl->idl_conn = NULL;
28539 			idl->idl_conn_draining = NULL;
28540 		} else {
28541 			connp->conn_drain_prev->conn_drain_next =
28542 			    connp->conn_drain_next;
28543 			connp->conn_drain_next->conn_drain_prev =
28544 			    connp->conn_drain_prev;
28545 			if (idl->idl_conn == connp)
28546 				idl->idl_conn = connp->conn_drain_next;
28547 			ASSERT(idl->idl_conn_draining != connp);
28548 
28549 		}
28550 		connp->conn_drain_next = NULL;
28551 		connp->conn_drain_prev = NULL;
28552 	}
28553 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28554 }
28555 
28556 /*
28557  * Write service routine. Shared perimeter entry point.
28558  * ip_wsrv can be called in any of the following ways.
28559  * 1. The device queue's messages has fallen below the low water mark
28560  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28561  *    the drain lists and backenable the first conn in each list.
28562  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28563  *    qenabled non-tcp upper layers. We start dequeing messages and call
28564  *    ip_wput for each message.
28565  */
28566 
28567 void
28568 ip_wsrv(queue_t *q)
28569 {
28570 	conn_t	*connp;
28571 	ill_t	*ill;
28572 	mblk_t	*mp;
28573 
28574 	if (q->q_next) {
28575 		ill = (ill_t *)q->q_ptr;
28576 		if (ill->ill_state_flags == 0) {
28577 			/*
28578 			 * The device flow control has opened up.
28579 			 * Walk through conn drain lists and qenable the
28580 			 * first conn in each list. This makes sense only
28581 			 * if the stream is fully plumbed and setup.
28582 			 * Hence the if check above.
28583 			 */
28584 			ip1dbg(("ip_wsrv: walking\n"));
28585 			conn_walk_drain(ill->ill_ipst);
28586 		}
28587 		return;
28588 	}
28589 
28590 	connp = Q_TO_CONN(q);
28591 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28592 
28593 	/*
28594 	 * 1. Set conn_draining flag to signal that service is active.
28595 	 *
28596 	 * 2. ip_output determines whether it has been called from service,
28597 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28598 	 *    has been called from service.
28599 	 *
28600 	 * 3. Message ordering is preserved by the following logic.
28601 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28602 	 *    the message at the tail, if conn_draining is set (i.e. service
28603 	 *    is running) or if q->q_first is non-null.
28604 	 *
28605 	 *    ii. If ip_output is called from service, and if ip_output cannot
28606 	 *    putnext due to flow control, it does a putbq.
28607 	 *
28608 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28609 	 *    (causing an infinite loop).
28610 	 */
28611 	ASSERT(!connp->conn_did_putbq);
28612 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28613 		connp->conn_draining = 1;
28614 		noenable(q);
28615 		while ((mp = getq(q)) != NULL) {
28616 			ASSERT(CONN_Q(q));
28617 
28618 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28619 			if (connp->conn_did_putbq) {
28620 				/* ip_wput did a putbq */
28621 				break;
28622 			}
28623 		}
28624 		/*
28625 		 * At this point, a thread coming down from top, calling
28626 		 * ip_wput, may end up queueing the message. We have not yet
28627 		 * enabled the queue, so ip_wsrv won't be called again.
28628 		 * To avoid this race, check q->q_first again (in the loop)
28629 		 * If the other thread queued the message before we call
28630 		 * enableok(), we will catch it in the q->q_first check.
28631 		 * If the other thread queues the message after we call
28632 		 * enableok(), ip_wsrv will be called again by STREAMS.
28633 		 */
28634 		connp->conn_draining = 0;
28635 		enableok(q);
28636 	}
28637 
28638 	/* Enable the next conn for draining */
28639 	conn_drain_tail(connp, B_FALSE);
28640 
28641 	connp->conn_did_putbq = 0;
28642 }
28643 
28644 /*
28645  * Walk the list of all conn's calling the function provided with the
28646  * specified argument for each.	 Note that this only walks conn's that
28647  * have been bound.
28648  * Applies to both IPv4 and IPv6.
28649  */
28650 static void
28651 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28652 {
28653 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28654 	    ipst->ips_ipcl_udp_fanout_size,
28655 	    func, arg, zoneid);
28656 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28657 	    ipst->ips_ipcl_conn_fanout_size,
28658 	    func, arg, zoneid);
28659 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28660 	    ipst->ips_ipcl_bind_fanout_size,
28661 	    func, arg, zoneid);
28662 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28663 	    IPPROTO_MAX, func, arg, zoneid);
28664 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28665 	    IPPROTO_MAX, func, arg, zoneid);
28666 }
28667 
28668 /*
28669  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28670  * of conns that need to be drained, check if drain is already in progress.
28671  * If so set the idl_repeat bit, indicating that the last conn in the list
28672  * needs to reinitiate the drain once again, for the list. If drain is not
28673  * in progress for the list, initiate the draining, by qenabling the 1st
28674  * conn in the list. The drain is self-sustaining, each qenabled conn will
28675  * in turn qenable the next conn, when it is done/blocked/closing.
28676  */
28677 static void
28678 conn_walk_drain(ip_stack_t *ipst)
28679 {
28680 	int i;
28681 	idl_t *idl;
28682 
28683 	IP_STAT(ipst, ip_conn_walk_drain);
28684 
28685 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28686 		idl = &ipst->ips_conn_drain_list[i];
28687 		mutex_enter(&idl->idl_lock);
28688 		if (idl->idl_conn == NULL) {
28689 			mutex_exit(&idl->idl_lock);
28690 			continue;
28691 		}
28692 		/*
28693 		 * If this list is not being drained currently by
28694 		 * an ip_wsrv thread, start the process.
28695 		 */
28696 		if (idl->idl_conn_draining == NULL) {
28697 			ASSERT(idl->idl_repeat == 0);
28698 			qenable(idl->idl_conn->conn_wq);
28699 			idl->idl_conn_draining = idl->idl_conn;
28700 		} else {
28701 			idl->idl_repeat = 1;
28702 		}
28703 		mutex_exit(&idl->idl_lock);
28704 	}
28705 }
28706 
28707 /*
28708  * Walk an conn hash table of `count' buckets, calling func for each entry.
28709  */
28710 static void
28711 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28712     zoneid_t zoneid)
28713 {
28714 	conn_t	*connp;
28715 
28716 	while (count-- > 0) {
28717 		mutex_enter(&connfp->connf_lock);
28718 		for (connp = connfp->connf_head; connp != NULL;
28719 		    connp = connp->conn_next) {
28720 			if (zoneid == GLOBAL_ZONEID ||
28721 			    zoneid == connp->conn_zoneid) {
28722 				CONN_INC_REF(connp);
28723 				mutex_exit(&connfp->connf_lock);
28724 				(*func)(connp, arg);
28725 				mutex_enter(&connfp->connf_lock);
28726 				CONN_DEC_REF(connp);
28727 			}
28728 		}
28729 		mutex_exit(&connfp->connf_lock);
28730 		connfp++;
28731 	}
28732 }
28733 
28734 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28735 static void
28736 conn_report1(conn_t *connp, void *mp)
28737 {
28738 	char	buf1[INET6_ADDRSTRLEN];
28739 	char	buf2[INET6_ADDRSTRLEN];
28740 	uint_t	print_len, buf_len;
28741 
28742 	ASSERT(connp != NULL);
28743 
28744 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28745 	if (buf_len <= 0)
28746 		return;
28747 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28748 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28749 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28750 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28751 	    "%5d %s/%05d %s/%05d\n",
28752 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28753 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28754 	    buf1, connp->conn_lport,
28755 	    buf2, connp->conn_fport);
28756 	if (print_len < buf_len) {
28757 		((mblk_t *)mp)->b_wptr += print_len;
28758 	} else {
28759 		((mblk_t *)mp)->b_wptr += buf_len;
28760 	}
28761 }
28762 
28763 /*
28764  * Named Dispatch routine to produce a formatted report on all conns
28765  * that are listed in one of the fanout tables.
28766  * This report is accessed by using the ndd utility to "get" ND variable
28767  * "ip_conn_status".
28768  */
28769 /* ARGSUSED */
28770 static int
28771 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28772 {
28773 	conn_t *connp = Q_TO_CONN(q);
28774 
28775 	(void) mi_mpprintf(mp,
28776 	    "CONN      " MI_COL_HDRPAD_STR
28777 	    "rfq      " MI_COL_HDRPAD_STR
28778 	    "stq      " MI_COL_HDRPAD_STR
28779 	    " zone local                 remote");
28780 
28781 	/*
28782 	 * Because of the ndd constraint, at most we can have 64K buffer
28783 	 * to put in all conn info.  So to be more efficient, just
28784 	 * allocate a 64K buffer here, assuming we need that large buffer.
28785 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28786 	 */
28787 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28788 		/* The following may work even if we cannot get a large buf. */
28789 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28790 		return (0);
28791 	}
28792 
28793 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28794 	    connp->conn_netstack->netstack_ip);
28795 	return (0);
28796 }
28797 
28798 /*
28799  * Determine if the ill and multicast aspects of that packets
28800  * "matches" the conn.
28801  */
28802 boolean_t
28803 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28804     zoneid_t zoneid)
28805 {
28806 	ill_t *in_ill;
28807 	boolean_t found;
28808 	ipif_t *ipif;
28809 	ire_t *ire;
28810 	ipaddr_t dst, src;
28811 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28812 
28813 	dst = ipha->ipha_dst;
28814 	src = ipha->ipha_src;
28815 
28816 	/*
28817 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28818 	 * unicast, broadcast and multicast reception to
28819 	 * conn_incoming_ill. conn_wantpacket itself is called
28820 	 * only for BROADCAST and multicast.
28821 	 *
28822 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28823 	 *    is part of a group. Hence, we should be receiving
28824 	 *    just one copy of broadcast for the whole group.
28825 	 *    Thus, if it is part of the group the packet could
28826 	 *    come on any ill of the group and hence we need a
28827 	 *    match on the group. Otherwise, match on ill should
28828 	 *    be sufficient.
28829 	 *
28830 	 * 2) ip_rput does not suppress duplicate multicast packets.
28831 	 *    If there are two interfaces in a ill group and we have
28832 	 *    2 applications (conns) joined a multicast group G on
28833 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28834 	 *    will give us two packets because we join G on both the
28835 	 *    interfaces rather than nominating just one interface
28836 	 *    for receiving multicast like broadcast above. So,
28837 	 *    we have to call ilg_lookup_ill to filter out duplicate
28838 	 *    copies, if ill is part of a group.
28839 	 */
28840 	in_ill = connp->conn_incoming_ill;
28841 	if (in_ill != NULL) {
28842 		if (in_ill->ill_group == NULL) {
28843 			if (in_ill != ill)
28844 				return (B_FALSE);
28845 		} else if (in_ill->ill_group != ill->ill_group) {
28846 			return (B_FALSE);
28847 		}
28848 	}
28849 
28850 	if (!CLASSD(dst)) {
28851 		if (IPCL_ZONE_MATCH(connp, zoneid))
28852 			return (B_TRUE);
28853 		/*
28854 		 * The conn is in a different zone; we need to check that this
28855 		 * broadcast address is configured in the application's zone and
28856 		 * on one ill in the group.
28857 		 */
28858 		ipif = ipif_get_next_ipif(NULL, ill);
28859 		if (ipif == NULL)
28860 			return (B_FALSE);
28861 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28862 		    connp->conn_zoneid, NULL,
28863 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28864 		ipif_refrele(ipif);
28865 		if (ire != NULL) {
28866 			ire_refrele(ire);
28867 			return (B_TRUE);
28868 		} else {
28869 			return (B_FALSE);
28870 		}
28871 	}
28872 
28873 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28874 	    connp->conn_zoneid == zoneid) {
28875 		/*
28876 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28877 		 * disabled, therefore we don't dispatch the multicast packet to
28878 		 * the sending zone.
28879 		 */
28880 		return (B_FALSE);
28881 	}
28882 
28883 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28884 		/*
28885 		 * Multicast packet on the loopback interface: we only match
28886 		 * conns who joined the group in the specified zone.
28887 		 */
28888 		return (B_FALSE);
28889 	}
28890 
28891 	if (connp->conn_multi_router) {
28892 		/* multicast packet and multicast router socket: send up */
28893 		return (B_TRUE);
28894 	}
28895 
28896 	mutex_enter(&connp->conn_lock);
28897 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28898 	mutex_exit(&connp->conn_lock);
28899 	return (found);
28900 }
28901 
28902 /*
28903  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28904  */
28905 /* ARGSUSED */
28906 static void
28907 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28908 {
28909 	ill_t *ill = (ill_t *)q->q_ptr;
28910 	mblk_t	*mp1, *mp2;
28911 	ipif_t  *ipif;
28912 	int err = 0;
28913 	conn_t *connp = NULL;
28914 	ipsq_t	*ipsq;
28915 	arc_t	*arc;
28916 
28917 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28918 
28919 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28920 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28921 
28922 	ASSERT(IAM_WRITER_ILL(ill));
28923 	mp2 = mp->b_cont;
28924 	mp->b_cont = NULL;
28925 
28926 	/*
28927 	 * We have now received the arp bringup completion message
28928 	 * from ARP. Mark the arp bringup as done. Also if the arp
28929 	 * stream has already started closing, send up the AR_ARP_CLOSING
28930 	 * ack now since ARP is waiting in close for this ack.
28931 	 */
28932 	mutex_enter(&ill->ill_lock);
28933 	ill->ill_arp_bringup_pending = 0;
28934 	if (ill->ill_arp_closing) {
28935 		mutex_exit(&ill->ill_lock);
28936 		/* Let's reuse the mp for sending the ack */
28937 		arc = (arc_t *)mp->b_rptr;
28938 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28939 		arc->arc_cmd = AR_ARP_CLOSING;
28940 		qreply(q, mp);
28941 	} else {
28942 		mutex_exit(&ill->ill_lock);
28943 		freeb(mp);
28944 	}
28945 
28946 	ipsq = ill->ill_phyint->phyint_ipsq;
28947 	ipif = ipsq->ipsq_pending_ipif;
28948 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28949 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28950 	if (mp1 == NULL) {
28951 		/* bringup was aborted by the user */
28952 		freemsg(mp2);
28953 		return;
28954 	}
28955 
28956 	/*
28957 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28958 	 * must have an associated conn_t.  Otherwise, we're bringing this
28959 	 * interface back up as part of handling an asynchronous event (e.g.,
28960 	 * physical address change).
28961 	 */
28962 	if (ipsq->ipsq_current_ioctl != 0) {
28963 		ASSERT(connp != NULL);
28964 		q = CONNP_TO_WQ(connp);
28965 	} else {
28966 		ASSERT(connp == NULL);
28967 		q = ill->ill_rq;
28968 	}
28969 
28970 	/*
28971 	 * If the DL_BIND_REQ fails, it is noted
28972 	 * in arc_name_offset.
28973 	 */
28974 	err = *((int *)mp2->b_rptr);
28975 	if (err == 0) {
28976 		if (ipif->ipif_isv6) {
28977 			if ((err = ipif_up_done_v6(ipif)) != 0)
28978 				ip0dbg(("ip_arp_done: init failed\n"));
28979 		} else {
28980 			if ((err = ipif_up_done(ipif)) != 0)
28981 				ip0dbg(("ip_arp_done: init failed\n"));
28982 		}
28983 	} else {
28984 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28985 	}
28986 
28987 	freemsg(mp2);
28988 
28989 	if ((err == 0) && (ill->ill_up_ipifs)) {
28990 		err = ill_up_ipifs(ill, q, mp1);
28991 		if (err == EINPROGRESS)
28992 			return;
28993 	}
28994 
28995 	if (ill->ill_up_ipifs)
28996 		ill_group_cleanup(ill);
28997 
28998 	/*
28999 	 * The operation must complete without EINPROGRESS since
29000 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29001 	 * Otherwise, the operation will be stuck forever in the ipsq.
29002 	 */
29003 	ASSERT(err != EINPROGRESS);
29004 	if (ipsq->ipsq_current_ioctl != 0)
29005 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29006 	else
29007 		ipsq_current_finish(ipsq);
29008 }
29009 
29010 /* Allocate the private structure */
29011 static int
29012 ip_priv_alloc(void **bufp)
29013 {
29014 	void	*buf;
29015 
29016 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29017 		return (ENOMEM);
29018 
29019 	*bufp = buf;
29020 	return (0);
29021 }
29022 
29023 /* Function to delete the private structure */
29024 void
29025 ip_priv_free(void *buf)
29026 {
29027 	ASSERT(buf != NULL);
29028 	kmem_free(buf, sizeof (ip_priv_t));
29029 }
29030 
29031 /*
29032  * The entry point for IPPF processing.
29033  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29034  * routine just returns.
29035  *
29036  * When called, ip_process generates an ipp_packet_t structure
29037  * which holds the state information for this packet and invokes the
29038  * the classifier (via ipp_packet_process). The classification, depending on
29039  * configured filters, results in a list of actions for this packet. Invoking
29040  * an action may cause the packet to be dropped, in which case the resulting
29041  * mblk (*mpp) is NULL. proc indicates the callout position for
29042  * this packet and ill_index is the interface this packet on or will leave
29043  * on (inbound and outbound resp.).
29044  */
29045 void
29046 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29047 {
29048 	mblk_t		*mp;
29049 	ip_priv_t	*priv;
29050 	ipp_action_id_t	aid;
29051 	int		rc = 0;
29052 	ipp_packet_t	*pp;
29053 #define	IP_CLASS	"ip"
29054 
29055 	/* If the classifier is not loaded, return  */
29056 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29057 		return;
29058 	}
29059 
29060 	mp = *mpp;
29061 	ASSERT(mp != NULL);
29062 
29063 	/* Allocate the packet structure */
29064 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29065 	if (rc != 0) {
29066 		*mpp = NULL;
29067 		freemsg(mp);
29068 		return;
29069 	}
29070 
29071 	/* Allocate the private structure */
29072 	rc = ip_priv_alloc((void **)&priv);
29073 	if (rc != 0) {
29074 		*mpp = NULL;
29075 		freemsg(mp);
29076 		ipp_packet_free(pp);
29077 		return;
29078 	}
29079 	priv->proc = proc;
29080 	priv->ill_index = ill_index;
29081 	ipp_packet_set_private(pp, priv, ip_priv_free);
29082 	ipp_packet_set_data(pp, mp);
29083 
29084 	/* Invoke the classifier */
29085 	rc = ipp_packet_process(&pp);
29086 	if (pp != NULL) {
29087 		mp = ipp_packet_get_data(pp);
29088 		ipp_packet_free(pp);
29089 		if (rc != 0) {
29090 			freemsg(mp);
29091 			*mpp = NULL;
29092 		}
29093 	} else {
29094 		*mpp = NULL;
29095 	}
29096 #undef	IP_CLASS
29097 }
29098 
29099 /*
29100  * Propagate a multicast group membership operation (add/drop) on
29101  * all the interfaces crossed by the related multirt routes.
29102  * The call is considered successful if the operation succeeds
29103  * on at least one interface.
29104  */
29105 static int
29106 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29107     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29108     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29109     mblk_t *first_mp)
29110 {
29111 	ire_t		*ire_gw;
29112 	irb_t		*irb;
29113 	int		error = 0;
29114 	opt_restart_t	*or;
29115 	ip_stack_t	*ipst = ire->ire_ipst;
29116 
29117 	irb = ire->ire_bucket;
29118 	ASSERT(irb != NULL);
29119 
29120 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29121 
29122 	or = (opt_restart_t *)first_mp->b_rptr;
29123 	IRB_REFHOLD(irb);
29124 	for (; ire != NULL; ire = ire->ire_next) {
29125 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29126 			continue;
29127 		if (ire->ire_addr != group)
29128 			continue;
29129 
29130 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29131 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29132 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29133 		/* No resolver exists for the gateway; skip this ire. */
29134 		if (ire_gw == NULL)
29135 			continue;
29136 
29137 		/*
29138 		 * This function can return EINPROGRESS. If so the operation
29139 		 * will be restarted from ip_restart_optmgmt which will
29140 		 * call ip_opt_set and option processing will restart for
29141 		 * this option. So we may end up calling 'fn' more than once.
29142 		 * This requires that 'fn' is idempotent except for the
29143 		 * return value. The operation is considered a success if
29144 		 * it succeeds at least once on any one interface.
29145 		 */
29146 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29147 		    NULL, fmode, src, first_mp);
29148 		if (error == 0)
29149 			or->or_private = CGTP_MCAST_SUCCESS;
29150 
29151 		if (ip_debug > 0) {
29152 			ulong_t	off;
29153 			char	*ksym;
29154 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29155 			ip2dbg(("ip_multirt_apply_membership: "
29156 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29157 			    "error %d [success %u]\n",
29158 			    ksym ? ksym : "?",
29159 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29160 			    error, or->or_private));
29161 		}
29162 
29163 		ire_refrele(ire_gw);
29164 		if (error == EINPROGRESS) {
29165 			IRB_REFRELE(irb);
29166 			return (error);
29167 		}
29168 	}
29169 	IRB_REFRELE(irb);
29170 	/*
29171 	 * Consider the call as successful if we succeeded on at least
29172 	 * one interface. Otherwise, return the last encountered error.
29173 	 */
29174 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29175 }
29176 
29177 
29178 /*
29179  * Issue a warning regarding a route crossing an interface with an
29180  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29181  * amount of time is logged.
29182  */
29183 static void
29184 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29185 {
29186 	hrtime_t	current = gethrtime();
29187 	char		buf[INET_ADDRSTRLEN];
29188 	ip_stack_t	*ipst = ire->ire_ipst;
29189 
29190 	/* Convert interval in ms to hrtime in ns */
29191 	if (ipst->ips_multirt_bad_mtu_last_time +
29192 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29193 	    current) {
29194 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29195 		    "to %s, incorrect MTU %u (expected %u)\n",
29196 		    ip_dot_addr(ire->ire_addr, buf),
29197 		    ire->ire_max_frag, max_frag);
29198 
29199 		ipst->ips_multirt_bad_mtu_last_time = current;
29200 	}
29201 }
29202 
29203 
29204 /*
29205  * Get the CGTP (multirouting) filtering status.
29206  * If 0, the CGTP hooks are transparent.
29207  */
29208 /* ARGSUSED */
29209 static int
29210 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29211 {
29212 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29213 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29214 
29215 	/*
29216 	 * Only applies to the shared stack since the filter_ops
29217 	 * do not carry an ip_stack_t or zoneid.
29218 	 */
29219 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29220 		return (ENOTSUP);
29221 
29222 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29223 	return (0);
29224 }
29225 
29226 
29227 /*
29228  * Set the CGTP (multirouting) filtering status.
29229  * If the status is changed from active to transparent
29230  * or from transparent to active, forward the new status
29231  * to the filtering module (if loaded).
29232  */
29233 /* ARGSUSED */
29234 static int
29235 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29236     cred_t *ioc_cr)
29237 {
29238 	long		new_value;
29239 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29240 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29241 
29242 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
29243 		return (EPERM);
29244 
29245 	/*
29246 	 * Only applies to the shared stack since the filter_ops
29247 	 * do not carry an ip_stack_t or zoneid.
29248 	 */
29249 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29250 		return (ENOTSUP);
29251 
29252 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29253 	    new_value < 0 || new_value > 1) {
29254 		return (EINVAL);
29255 	}
29256 
29257 	/*
29258 	 * Do not enable CGTP filtering - thus preventing the hooks
29259 	 * from being invoked - if the version number of the
29260 	 * filtering module hooks does not match.
29261 	 */
29262 	if ((ip_cgtp_filter_ops != NULL) &&
29263 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29264 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29265 		    "(module hooks version %d, expecting %d)\n",
29266 		    ip_cgtp_filter_ops->cfo_filter_rev,
29267 		    CGTP_FILTER_REV);
29268 		return (ENOTSUP);
29269 	}
29270 
29271 	if ((!*ip_cgtp_filter_value) && new_value) {
29272 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29273 		    ip_cgtp_filter_ops == NULL ?
29274 		    " (module not loaded)" : "");
29275 	}
29276 	if (*ip_cgtp_filter_value && (!new_value)) {
29277 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29278 		    ip_cgtp_filter_ops == NULL ?
29279 		    " (module not loaded)" : "");
29280 	}
29281 
29282 	if (ip_cgtp_filter_ops != NULL) {
29283 		int	res;
29284 
29285 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
29286 		if (res)
29287 			return (res);
29288 	}
29289 
29290 	*ip_cgtp_filter_value = (boolean_t)new_value;
29291 
29292 	return (0);
29293 }
29294 
29295 
29296 /*
29297  * Return the expected CGTP hooks version number.
29298  */
29299 int
29300 ip_cgtp_filter_supported(void)
29301 {
29302 	ip_stack_t *ipst;
29303 	int ret;
29304 
29305 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29306 	if (ipst == NULL)
29307 		return (-1);
29308 	ret = ip_cgtp_filter_rev;
29309 	netstack_rele(ipst->ips_netstack);
29310 	return (ret);
29311 }
29312 
29313 
29314 /*
29315  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29316  * or by invoking this function. In the first case, the version number
29317  * of the registered structure is checked at hooks activation time
29318  * in ip_cgtp_filter_set().
29319  *
29320  * Only applies to the shared stack since the filter_ops
29321  * do not carry an ip_stack_t or zoneid.
29322  */
29323 int
29324 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29325 {
29326 	ip_stack_t *ipst;
29327 
29328 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29329 		return (ENOTSUP);
29330 
29331 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29332 	if (ipst == NULL)
29333 		return (EINVAL);
29334 
29335 	ip_cgtp_filter_ops = ops;
29336 	netstack_rele(ipst->ips_netstack);
29337 	return (0);
29338 }
29339 
29340 static squeue_func_t
29341 ip_squeue_switch(int val)
29342 {
29343 	squeue_func_t rval = squeue_fill;
29344 
29345 	switch (val) {
29346 	case IP_SQUEUE_ENTER_NODRAIN:
29347 		rval = squeue_enter_nodrain;
29348 		break;
29349 	case IP_SQUEUE_ENTER:
29350 		rval = squeue_enter;
29351 		break;
29352 	default:
29353 		break;
29354 	}
29355 	return (rval);
29356 }
29357 
29358 /* ARGSUSED */
29359 static int
29360 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29361     caddr_t addr, cred_t *cr)
29362 {
29363 	int *v = (int *)addr;
29364 	long new_value;
29365 
29366 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29367 		return (EPERM);
29368 
29369 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29370 		return (EINVAL);
29371 
29372 	ip_input_proc = ip_squeue_switch(new_value);
29373 	*v = new_value;
29374 	return (0);
29375 }
29376 
29377 /* ARGSUSED */
29378 static int
29379 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29380     caddr_t addr, cred_t *cr)
29381 {
29382 	int *v = (int *)addr;
29383 	long new_value;
29384 
29385 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29386 		return (EPERM);
29387 
29388 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29389 		return (EINVAL);
29390 
29391 	*v = new_value;
29392 	return (0);
29393 }
29394 
29395 /*
29396  * Handle changes to ipmp_hook_emulation ndd variable.
29397  * Need to update phyint_hook_ifindex.
29398  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29399  */
29400 static void
29401 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29402 {
29403 	phyint_t *phyi;
29404 	phyint_t *phyi_tmp;
29405 	char *groupname;
29406 	int namelen;
29407 	ill_t	*ill;
29408 	boolean_t new_group;
29409 
29410 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29411 	/*
29412 	 * Group indicies are stored in the phyint - a common structure
29413 	 * to both IPv4 and IPv6.
29414 	 */
29415 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29416 	for (; phyi != NULL;
29417 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29418 	    phyi, AVL_AFTER)) {
29419 		/* Ignore the ones that do not have a group */
29420 		if (phyi->phyint_groupname_len == 0)
29421 			continue;
29422 
29423 		/*
29424 		 * Look for other phyint in group.
29425 		 * Clear name/namelen so the lookup doesn't find ourselves.
29426 		 */
29427 		namelen = phyi->phyint_groupname_len;
29428 		groupname = phyi->phyint_groupname;
29429 		phyi->phyint_groupname_len = 0;
29430 		phyi->phyint_groupname = NULL;
29431 
29432 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29433 		/* Restore */
29434 		phyi->phyint_groupname_len = namelen;
29435 		phyi->phyint_groupname = groupname;
29436 
29437 		new_group = B_FALSE;
29438 		if (ipst->ips_ipmp_hook_emulation) {
29439 			/*
29440 			 * If the group already exists and has already
29441 			 * been assigned a group ifindex, we use the existing
29442 			 * group_ifindex, otherwise we pick a new group_ifindex
29443 			 * here.
29444 			 */
29445 			if (phyi_tmp != NULL &&
29446 			    phyi_tmp->phyint_group_ifindex != 0) {
29447 				phyi->phyint_group_ifindex =
29448 				    phyi_tmp->phyint_group_ifindex;
29449 			} else {
29450 				/* XXX We need a recovery strategy here. */
29451 				if (!ip_assign_ifindex(
29452 				    &phyi->phyint_group_ifindex, ipst))
29453 					cmn_err(CE_PANIC,
29454 					    "ip_assign_ifindex() failed");
29455 				new_group = B_TRUE;
29456 			}
29457 		} else {
29458 			phyi->phyint_group_ifindex = 0;
29459 		}
29460 		if (ipst->ips_ipmp_hook_emulation)
29461 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29462 		else
29463 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29464 
29465 		/*
29466 		 * For IP Filter to find out the relationship between
29467 		 * names and interface indicies, we need to generate
29468 		 * a NE_PLUMB event when a new group can appear.
29469 		 * We always generate events when a new interface appears
29470 		 * (even when ipmp_hook_emulation is set) so there
29471 		 * is no need to generate NE_PLUMB events when
29472 		 * ipmp_hook_emulation is turned off.
29473 		 * And since it isn't critical for IP Filter to get
29474 		 * the NE_UNPLUMB events we skip those here.
29475 		 */
29476 		if (new_group) {
29477 			/*
29478 			 * First phyint in group - generate group PLUMB event.
29479 			 * Since we are not running inside the ipsq we do
29480 			 * the dispatch immediately.
29481 			 */
29482 			if (phyi->phyint_illv4 != NULL)
29483 				ill = phyi->phyint_illv4;
29484 			else
29485 				ill = phyi->phyint_illv6;
29486 
29487 			if (ill != NULL) {
29488 				mutex_enter(&ill->ill_lock);
29489 				ill_nic_info_plumb(ill, B_TRUE);
29490 				ill_nic_info_dispatch(ill);
29491 				mutex_exit(&ill->ill_lock);
29492 			}
29493 		}
29494 	}
29495 	rw_exit(&ipst->ips_ill_g_lock);
29496 }
29497 
29498 /* ARGSUSED */
29499 static int
29500 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29501     caddr_t addr, cred_t *cr)
29502 {
29503 	int *v = (int *)addr;
29504 	long new_value;
29505 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29506 
29507 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29508 		return (EINVAL);
29509 
29510 	if (*v != new_value) {
29511 		*v = new_value;
29512 		ipmp_hook_emulation_changed(ipst);
29513 	}
29514 	return (0);
29515 }
29516 
29517 static void *
29518 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29519 {
29520 	kstat_t *ksp;
29521 
29522 	ip_stat_t template = {
29523 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29524 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29525 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29526 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29527 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29528 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29529 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29530 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29531 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29532 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29533 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29534 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29535 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29536 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29537 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29538 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29539 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29540 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29541 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29542 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29543 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29544 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29545 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29546 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29547 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29548 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29549 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29550 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29551 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29552 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29553 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29554 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29555 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29556 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29557 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29558 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29559 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29560 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29561 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29562 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29563 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29564 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29565 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29566 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29567 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29568 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29569 	};
29570 
29571 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29572 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29573 	    KSTAT_FLAG_VIRTUAL, stackid);
29574 
29575 	if (ksp == NULL)
29576 		return (NULL);
29577 
29578 	bcopy(&template, ip_statisticsp, sizeof (template));
29579 	ksp->ks_data = (void *)ip_statisticsp;
29580 	ksp->ks_private = (void *)(uintptr_t)stackid;
29581 
29582 	kstat_install(ksp);
29583 	return (ksp);
29584 }
29585 
29586 static void
29587 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29588 {
29589 	if (ksp != NULL) {
29590 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29591 		kstat_delete_netstack(ksp, stackid);
29592 	}
29593 }
29594 
29595 static void *
29596 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29597 {
29598 	kstat_t	*ksp;
29599 
29600 	ip_named_kstat_t template = {
29601 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29602 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29603 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29604 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29605 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29606 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29607 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29608 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29609 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29610 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29611 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29612 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29613 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29614 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29615 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29616 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29617 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29618 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29619 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29620 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29621 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29622 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29623 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29624 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29625 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29626 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29627 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29628 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29629 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29630 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29631 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29632 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29633 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29634 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29635 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29636 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29637 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29638 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29639 	};
29640 
29641 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29642 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29643 	if (ksp == NULL || ksp->ks_data == NULL)
29644 		return (NULL);
29645 
29646 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29647 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29648 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29649 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29650 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29651 
29652 	template.netToMediaEntrySize.value.i32 =
29653 	    sizeof (mib2_ipNetToMediaEntry_t);
29654 
29655 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29656 
29657 	bcopy(&template, ksp->ks_data, sizeof (template));
29658 	ksp->ks_update = ip_kstat_update;
29659 	ksp->ks_private = (void *)(uintptr_t)stackid;
29660 
29661 	kstat_install(ksp);
29662 	return (ksp);
29663 }
29664 
29665 static void
29666 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29667 {
29668 	if (ksp != NULL) {
29669 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29670 		kstat_delete_netstack(ksp, stackid);
29671 	}
29672 }
29673 
29674 static int
29675 ip_kstat_update(kstat_t *kp, int rw)
29676 {
29677 	ip_named_kstat_t *ipkp;
29678 	mib2_ipIfStatsEntry_t ipmib;
29679 	ill_walk_context_t ctx;
29680 	ill_t *ill;
29681 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29682 	netstack_t	*ns;
29683 	ip_stack_t	*ipst;
29684 
29685 	if (kp == NULL || kp->ks_data == NULL)
29686 		return (EIO);
29687 
29688 	if (rw == KSTAT_WRITE)
29689 		return (EACCES);
29690 
29691 	ns = netstack_find_by_stackid(stackid);
29692 	if (ns == NULL)
29693 		return (-1);
29694 	ipst = ns->netstack_ip;
29695 	if (ipst == NULL) {
29696 		netstack_rele(ns);
29697 		return (-1);
29698 	}
29699 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29700 
29701 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29702 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29703 	ill = ILL_START_WALK_V4(&ctx, ipst);
29704 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29705 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29706 	rw_exit(&ipst->ips_ill_g_lock);
29707 
29708 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29709 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29710 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29711 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29712 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29713 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29714 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29715 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29716 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29717 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29718 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29719 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29720 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29721 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29722 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29723 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29724 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29725 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29726 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29727 
29728 	ipkp->routingDiscards.value.ui32 =	0;
29729 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29730 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29731 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29732 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29733 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29734 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29735 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29736 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29737 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29738 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29739 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29740 
29741 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29742 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29743 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29744 
29745 	netstack_rele(ns);
29746 
29747 	return (0);
29748 }
29749 
29750 static void *
29751 icmp_kstat_init(netstackid_t stackid)
29752 {
29753 	kstat_t	*ksp;
29754 
29755 	icmp_named_kstat_t template = {
29756 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29757 		{ "inErrors",		KSTAT_DATA_UINT32 },
29758 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29759 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29760 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29761 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29762 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29763 		{ "inEchos",		KSTAT_DATA_UINT32 },
29764 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29765 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29766 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29767 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29768 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29769 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29770 		{ "outErrors",		KSTAT_DATA_UINT32 },
29771 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29772 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29773 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29774 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29775 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29776 		{ "outEchos",		KSTAT_DATA_UINT32 },
29777 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29778 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29779 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29780 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29781 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29782 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29783 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29784 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29785 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29786 		{ "outDrops",		KSTAT_DATA_UINT32 },
29787 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29788 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29789 	};
29790 
29791 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29792 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29793 	if (ksp == NULL || ksp->ks_data == NULL)
29794 		return (NULL);
29795 
29796 	bcopy(&template, ksp->ks_data, sizeof (template));
29797 
29798 	ksp->ks_update = icmp_kstat_update;
29799 	ksp->ks_private = (void *)(uintptr_t)stackid;
29800 
29801 	kstat_install(ksp);
29802 	return (ksp);
29803 }
29804 
29805 static void
29806 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29807 {
29808 	if (ksp != NULL) {
29809 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29810 		kstat_delete_netstack(ksp, stackid);
29811 	}
29812 }
29813 
29814 static int
29815 icmp_kstat_update(kstat_t *kp, int rw)
29816 {
29817 	icmp_named_kstat_t *icmpkp;
29818 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29819 	netstack_t	*ns;
29820 	ip_stack_t	*ipst;
29821 
29822 	if ((kp == NULL) || (kp->ks_data == NULL))
29823 		return (EIO);
29824 
29825 	if (rw == KSTAT_WRITE)
29826 		return (EACCES);
29827 
29828 	ns = netstack_find_by_stackid(stackid);
29829 	if (ns == NULL)
29830 		return (-1);
29831 	ipst = ns->netstack_ip;
29832 	if (ipst == NULL) {
29833 		netstack_rele(ns);
29834 		return (-1);
29835 	}
29836 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29837 
29838 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29839 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29840 	icmpkp->inDestUnreachs.value.ui32 =
29841 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29842 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29843 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29844 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29845 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29846 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29847 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29848 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29849 	icmpkp->inTimestampReps.value.ui32 =
29850 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29851 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29852 	icmpkp->inAddrMaskReps.value.ui32 =
29853 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29854 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29855 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29856 	icmpkp->outDestUnreachs.value.ui32 =
29857 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29858 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29859 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29860 	icmpkp->outSrcQuenchs.value.ui32 =
29861 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29862 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29863 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29864 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29865 	icmpkp->outTimestamps.value.ui32 =
29866 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29867 	icmpkp->outTimestampReps.value.ui32 =
29868 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29869 	icmpkp->outAddrMasks.value.ui32 =
29870 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29871 	icmpkp->outAddrMaskReps.value.ui32 =
29872 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29873 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29874 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29875 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29876 	icmpkp->outFragNeeded.value.ui32 =
29877 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29878 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29879 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29880 	icmpkp->inBadRedirects.value.ui32 =
29881 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29882 
29883 	netstack_rele(ns);
29884 	return (0);
29885 }
29886 
29887 /*
29888  * This is the fanout function for raw socket opened for SCTP.  Note
29889  * that it is called after SCTP checks that there is no socket which
29890  * wants a packet.  Then before SCTP handles this out of the blue packet,
29891  * this function is called to see if there is any raw socket for SCTP.
29892  * If there is and it is bound to the correct address, the packet will
29893  * be sent to that socket.  Note that only one raw socket can be bound to
29894  * a port.  This is assured in ipcl_sctp_hash_insert();
29895  */
29896 void
29897 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29898     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29899     zoneid_t zoneid)
29900 {
29901 	conn_t		*connp;
29902 	queue_t		*rq;
29903 	mblk_t		*first_mp;
29904 	boolean_t	secure;
29905 	ip6_t		*ip6h;
29906 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29907 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29908 
29909 	first_mp = mp;
29910 	if (mctl_present) {
29911 		mp = first_mp->b_cont;
29912 		secure = ipsec_in_is_secure(first_mp);
29913 		ASSERT(mp != NULL);
29914 	} else {
29915 		secure = B_FALSE;
29916 	}
29917 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29918 
29919 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29920 	if (connp == NULL) {
29921 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29922 		return;
29923 	}
29924 	rq = connp->conn_rq;
29925 	if (!canputnext(rq)) {
29926 		CONN_DEC_REF(connp);
29927 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29928 		freemsg(first_mp);
29929 		return;
29930 	}
29931 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29932 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29933 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29934 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29935 		if (first_mp == NULL) {
29936 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29937 			CONN_DEC_REF(connp);
29938 			return;
29939 		}
29940 	}
29941 	/*
29942 	 * We probably should not send M_CTL message up to
29943 	 * raw socket.
29944 	 */
29945 	if (mctl_present)
29946 		freeb(first_mp);
29947 
29948 	/* Initiate IPPF processing here if needed. */
29949 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29950 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29951 		ip_process(IPP_LOCAL_IN, &mp,
29952 		    recv_ill->ill_phyint->phyint_ifindex);
29953 		if (mp == NULL) {
29954 			CONN_DEC_REF(connp);
29955 			return;
29956 		}
29957 	}
29958 
29959 	if (connp->conn_recvif || connp->conn_recvslla ||
29960 	    ((connp->conn_ip_recvpktinfo ||
29961 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29962 	    (flags & IP_FF_IPINFO))) {
29963 		int in_flags = 0;
29964 
29965 		/*
29966 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29967 		 * IPF_RECVIF.
29968 		 */
29969 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29970 			in_flags = IPF_RECVIF;
29971 		}
29972 		if (connp->conn_recvslla) {
29973 			in_flags |= IPF_RECVSLLA;
29974 		}
29975 		if (isv4) {
29976 			mp = ip_add_info(mp, recv_ill, in_flags,
29977 			    IPCL_ZONEID(connp), ipst);
29978 		} else {
29979 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29980 			if (mp == NULL) {
29981 				BUMP_MIB(recv_ill->ill_ip_mib,
29982 				    ipIfStatsInDiscards);
29983 				CONN_DEC_REF(connp);
29984 				return;
29985 			}
29986 		}
29987 	}
29988 
29989 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29990 	/*
29991 	 * We are sending the IPSEC_IN message also up. Refer
29992 	 * to comments above this function.
29993 	 */
29994 	putnext(rq, mp);
29995 	CONN_DEC_REF(connp);
29996 }
29997 
29998 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29999 {									\
30000 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30001 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30002 }
30003 /*
30004  * This function should be called only if all packet processing
30005  * including fragmentation is complete. Callers of this function
30006  * must set mp->b_prev to one of these values:
30007  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30008  * prior to handing over the mp as first argument to this function.
30009  *
30010  * If the ire passed by caller is incomplete, this function
30011  * queues the packet and if necessary, sends ARP request and bails.
30012  * If the ire passed is fully resolved, we simply prepend
30013  * the link-layer header to the packet, do ipsec hw acceleration
30014  * work if necessary, and send the packet out on the wire.
30015  *
30016  * NOTE: IPSEC will only call this function with fully resolved
30017  * ires if hw acceleration is involved.
30018  * TODO list :
30019  * 	a Handle M_MULTIDATA so that
30020  *	  tcp_multisend->tcp_multisend_data can
30021  *	  call ip_xmit_v4 directly
30022  *	b Handle post-ARP work for fragments so that
30023  *	  ip_wput_frag can call this function.
30024  */
30025 ipxmit_state_t
30026 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
30027 {
30028 	nce_t		*arpce;
30029 	queue_t		*q;
30030 	int		ill_index;
30031 	mblk_t		*nxt_mp, *first_mp;
30032 	boolean_t	xmit_drop = B_FALSE;
30033 	ip_proc_t	proc;
30034 	ill_t		*out_ill;
30035 	int		pkt_len;
30036 
30037 	arpce = ire->ire_nce;
30038 	ASSERT(arpce != NULL);
30039 
30040 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30041 
30042 	mutex_enter(&arpce->nce_lock);
30043 	switch (arpce->nce_state) {
30044 	case ND_REACHABLE:
30045 		/* If there are other queued packets, queue this packet */
30046 		if (arpce->nce_qd_mp != NULL) {
30047 			if (mp != NULL)
30048 				nce_queue_mp_common(arpce, mp, B_FALSE);
30049 			mp = arpce->nce_qd_mp;
30050 		}
30051 		arpce->nce_qd_mp = NULL;
30052 		mutex_exit(&arpce->nce_lock);
30053 
30054 		/*
30055 		 * Flush the queue.  In the common case, where the
30056 		 * ARP is already resolved,  it will go through the
30057 		 * while loop only once.
30058 		 */
30059 		while (mp != NULL) {
30060 
30061 			nxt_mp = mp->b_next;
30062 			mp->b_next = NULL;
30063 			ASSERT(mp->b_datap->db_type != M_CTL);
30064 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30065 			/*
30066 			 * This info is needed for IPQOS to do COS marking
30067 			 * in ip_wput_attach_llhdr->ip_process.
30068 			 */
30069 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30070 			mp->b_prev = NULL;
30071 
30072 			/* set up ill index for outbound qos processing */
30073 			out_ill = ire->ire_ipif->ipif_ill;
30074 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30075 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30076 			    ill_index);
30077 			if (first_mp == NULL) {
30078 				xmit_drop = B_TRUE;
30079 				BUMP_MIB(out_ill->ill_ip_mib,
30080 				    ipIfStatsOutDiscards);
30081 				goto next_mp;
30082 			}
30083 			/* non-ipsec hw accel case */
30084 			if (io == NULL || !io->ipsec_out_accelerated) {
30085 				/* send it */
30086 				q = ire->ire_stq;
30087 				if (proc == IPP_FWD_OUT) {
30088 					UPDATE_IB_PKT_COUNT(ire);
30089 				} else {
30090 					UPDATE_OB_PKT_COUNT(ire);
30091 				}
30092 				ire->ire_last_used_time = lbolt;
30093 
30094 				if (flow_ctl_enabled || canputnext(q)) {
30095 					if (proc == IPP_FWD_OUT) {
30096 
30097 					BUMP_MIB(out_ill->ill_ip_mib,
30098 					    ipIfStatsHCOutForwDatagrams);
30099 
30100 					}
30101 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30102 					    pkt_len);
30103 
30104 					putnext(q, first_mp);
30105 				} else {
30106 					BUMP_MIB(out_ill->ill_ip_mib,
30107 					    ipIfStatsOutDiscards);
30108 					xmit_drop = B_TRUE;
30109 					freemsg(first_mp);
30110 				}
30111 			} else {
30112 				/*
30113 				 * Safety Pup says: make sure this
30114 				 *  is going to the right interface!
30115 				 */
30116 				ill_t *ill1 =
30117 				    (ill_t *)ire->ire_stq->q_ptr;
30118 				int ifindex =
30119 				    ill1->ill_phyint->phyint_ifindex;
30120 				if (ifindex !=
30121 				    io->ipsec_out_capab_ill_index) {
30122 					xmit_drop = B_TRUE;
30123 					freemsg(mp);
30124 				} else {
30125 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30126 					    pkt_len);
30127 					ipsec_hw_putnext(ire->ire_stq, mp);
30128 				}
30129 			}
30130 next_mp:
30131 			mp = nxt_mp;
30132 		} /* while (mp != NULL) */
30133 		if (xmit_drop)
30134 			return (SEND_FAILED);
30135 		else
30136 			return (SEND_PASSED);
30137 
30138 	case ND_INITIAL:
30139 	case ND_INCOMPLETE:
30140 
30141 		/*
30142 		 * While we do send off packets to dests that
30143 		 * use fully-resolved CGTP routes, we do not
30144 		 * handle unresolved CGTP routes.
30145 		 */
30146 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30147 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30148 
30149 		if (mp != NULL) {
30150 			/* queue the packet */
30151 			nce_queue_mp_common(arpce, mp, B_FALSE);
30152 		}
30153 
30154 		if (arpce->nce_state == ND_INCOMPLETE) {
30155 			mutex_exit(&arpce->nce_lock);
30156 			DTRACE_PROBE3(ip__xmit__incomplete,
30157 			    (ire_t *), ire, (mblk_t *), mp,
30158 			    (ipsec_out_t *), io);
30159 			return (LOOKUP_IN_PROGRESS);
30160 		}
30161 
30162 		arpce->nce_state = ND_INCOMPLETE;
30163 		mutex_exit(&arpce->nce_lock);
30164 		/*
30165 		 * Note that ire_add() (called from ire_forward())
30166 		 * holds a ref on the ire until ARP is completed.
30167 		 */
30168 
30169 		ire_arpresolve(ire, ire_to_ill(ire));
30170 		return (LOOKUP_IN_PROGRESS);
30171 	default:
30172 		ASSERT(0);
30173 		mutex_exit(&arpce->nce_lock);
30174 		return (LLHDR_RESLV_FAILED);
30175 	}
30176 }
30177 
30178 #undef	UPDATE_IP_MIB_OB_COUNTERS
30179 
30180 /*
30181  * Return B_TRUE if the buffers differ in length or content.
30182  * This is used for comparing extension header buffers.
30183  * Note that an extension header would be declared different
30184  * even if all that changed was the next header value in that header i.e.
30185  * what really changed is the next extension header.
30186  */
30187 boolean_t
30188 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30189     uint_t blen)
30190 {
30191 	if (!b_valid)
30192 		blen = 0;
30193 
30194 	if (alen != blen)
30195 		return (B_TRUE);
30196 	if (alen == 0)
30197 		return (B_FALSE);	/* Both zero length */
30198 	return (bcmp(abuf, bbuf, alen));
30199 }
30200 
30201 /*
30202  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30203  * Return B_FALSE if memory allocation fails - don't change any state!
30204  */
30205 boolean_t
30206 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30207     const void *src, uint_t srclen)
30208 {
30209 	void *dst;
30210 
30211 	if (!src_valid)
30212 		srclen = 0;
30213 
30214 	ASSERT(*dstlenp == 0);
30215 	if (src != NULL && srclen != 0) {
30216 		dst = mi_alloc(srclen, BPRI_MED);
30217 		if (dst == NULL)
30218 			return (B_FALSE);
30219 	} else {
30220 		dst = NULL;
30221 	}
30222 	if (*dstp != NULL)
30223 		mi_free(*dstp);
30224 	*dstp = dst;
30225 	*dstlenp = dst == NULL ? 0 : srclen;
30226 	return (B_TRUE);
30227 }
30228 
30229 /*
30230  * Replace what is in *dst, *dstlen with the source.
30231  * Assumes ip_allocbuf has already been called.
30232  */
30233 void
30234 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30235     const void *src, uint_t srclen)
30236 {
30237 	if (!src_valid)
30238 		srclen = 0;
30239 
30240 	ASSERT(*dstlenp == srclen);
30241 	if (src != NULL && srclen != 0)
30242 		bcopy(src, *dstp, srclen);
30243 }
30244 
30245 /*
30246  * Free the storage pointed to by the members of an ip6_pkt_t.
30247  */
30248 void
30249 ip6_pkt_free(ip6_pkt_t *ipp)
30250 {
30251 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30252 
30253 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30254 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30255 		ipp->ipp_hopopts = NULL;
30256 		ipp->ipp_hopoptslen = 0;
30257 	}
30258 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30259 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30260 		ipp->ipp_rtdstopts = NULL;
30261 		ipp->ipp_rtdstoptslen = 0;
30262 	}
30263 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30264 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30265 		ipp->ipp_dstopts = NULL;
30266 		ipp->ipp_dstoptslen = 0;
30267 	}
30268 	if (ipp->ipp_fields & IPPF_RTHDR) {
30269 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30270 		ipp->ipp_rthdr = NULL;
30271 		ipp->ipp_rthdrlen = 0;
30272 	}
30273 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30274 	    IPPF_RTHDR);
30275 }
30276