xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 46736d35df047bb400483364f76bfcb08cdcbb25)
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 squeue_func_t ip_squeue_switch(int);
755 
756 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
757 static void	ip_kstat_fini(netstackid_t, kstat_t *);
758 static int	ip_kstat_update(kstat_t *kp, int rw);
759 static void	*icmp_kstat_init(netstackid_t);
760 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
761 static int	icmp_kstat_update(kstat_t *kp, int rw);
762 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
763 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
764 
765 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
766 
767 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
768     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
769 
770 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
771     ipha_t *, ill_t *, boolean_t);
772 
773 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
774     ipha_t *, ill_t *, boolean_t);
775 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
776 
777 /* How long, in seconds, we allow frags to hang around. */
778 #define	IP_FRAG_TIMEOUT	60
779 
780 /*
781  * Threshold which determines whether MDT should be used when
782  * generating IP fragments; payload size must be greater than
783  * this threshold for MDT to take place.
784  */
785 #define	IP_WPUT_FRAG_MDT_MIN	32768
786 
787 /* Setable in /etc/system only */
788 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
789 
790 static long ip_rput_pullups;
791 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
792 
793 vmem_t *ip_minor_arena;
794 
795 int	ip_debug;
796 
797 #ifdef DEBUG
798 uint32_t ipsechw_debug = 0;
799 #endif
800 
801 /*
802  * Multirouting/CGTP stuff
803  */
804 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
805 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
806 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
807 
808 /*
809  * XXX following really should only be in a header. Would need more
810  * header and .c clean up first.
811  */
812 extern optdb_obj_t	ip_opt_obj;
813 
814 ulong_t ip_squeue_enter_unbound = 0;
815 
816 /*
817  * Named Dispatch Parameter Table.
818  * All of these are alterable, within the min/max values given, at run time.
819  */
820 static ipparam_t	lcl_param_arr[] = {
821 	/* min	max	value	name */
822 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
823 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
824 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
825 	{  0,	1,	0,	"ip_respond_to_timestamp"},
826 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
827 	{  0,	1,	1,	"ip_send_redirects"},
828 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
829 	{  0,	10,	0,	"ip_debug"},
830 	{  0,	10,	0,	"ip_mrtdebug"},
831 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
832 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
833 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
834 	{  1,	255,	255,	"ip_def_ttl" },
835 	{  0,	1,	0,	"ip_forward_src_routed"},
836 	{  0,	256,	32,	"ip_wroff_extra" },
837 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
838 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
839 	{  0,	1,	1,	"ip_path_mtu_discovery" },
840 	{  0,	240,	30,	"ip_ignore_delete_time" },
841 	{  0,	1,	0,	"ip_ignore_redirect" },
842 	{  0,	1,	1,	"ip_output_queue" },
843 	{  1,	254,	1,	"ip_broadcast_ttl" },
844 	{  0,	99999,	100,	"ip_icmp_err_interval" },
845 	{  1,	99999,	10,	"ip_icmp_err_burst" },
846 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
847 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
848 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
849 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
850 	{  0,	1,	1,	"icmp_accept_clear_messages" },
851 	{  0,	1,	1,	"igmp_accept_clear_messages" },
852 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
853 				"ip_ndp_delay_first_probe_time"},
854 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
855 				"ip_ndp_max_unicast_solicit"},
856 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
857 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
858 	{  0,	1,	0,	"ip6_forward_src_routed"},
859 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
860 	{  0,	1,	1,	"ip6_send_redirects"},
861 	{  0,	1,	0,	"ip6_ignore_redirect" },
862 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
863 
864 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
865 
866 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
867 
868 	{  0,	1,	1,	"pim_accept_clear_messages" },
869 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
870 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
871 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
872 	{  0,	15,	0,	"ip_policy_mask" },
873 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
874 	{  0,	255,	1,	"ip_multirt_ttl" },
875 	{  0,	1,	1,	"ip_multidata_outbound" },
876 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
877 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
878 	{  0,	1000,	1,	"ip_max_temp_defend" },
879 	{  0,	1000,	3,	"ip_max_defend" },
880 	{  0,	999999,	30,	"ip_defend_interval" },
881 	{  0,	3600000, 300000, "ip_dup_recovery" },
882 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
883 	{  0,	1,	1,	"ip_lso_outbound" },
884 #ifdef DEBUG
885 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
886 #else
887 	{  0,	0,	0,	"" },
888 #endif
889 };
890 
891 /*
892  * Extended NDP table
893  * The addresses for the first two are filled in to be ips_ip_g_forward
894  * and ips_ipv6_forward at init time.
895  */
896 static ipndp_t	lcl_ndp_arr[] = {
897 	/* getf			setf		data			name */
898 #define	IPNDP_IP_FORWARDING_OFFSET	0
899 	{  ip_param_generic_get,	ip_forward_set,	NULL,
900 	    "ip_forwarding" },
901 #define	IPNDP_IP6_FORWARDING_OFFSET	1
902 	{  ip_param_generic_get,	ip_forward_set,	NULL,
903 	    "ip6_forwarding" },
904 	{  ip_ill_report,	NULL,		NULL,
905 	    "ip_ill_status" },
906 	{  ip_ipif_report,	NULL,		NULL,
907 	    "ip_ipif_status" },
908 	{  ip_ire_report,	NULL,		NULL,
909 	    "ipv4_ire_status" },
910 	{  ip_ire_report_mrtun,	NULL,		NULL,
911 	    "ipv4_mrtun_ire_status" },
912 	{  ip_ire_report_srcif,	NULL,		NULL,
913 	    "ipv4_srcif_ire_status" },
914 	{  ip_ire_report_v6,	NULL,		NULL,
915 	    "ipv6_ire_status" },
916 	{  ip_conn_report,	NULL,		NULL,
917 	    "ip_conn_status" },
918 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
919 	    "ip_rput_pullups" },
920 	{  ndp_report,		NULL,		NULL,
921 	    "ip_ndp_cache_report" },
922 	{  ip_srcid_report,	NULL,		NULL,
923 	    "ip_srcid_status" },
924 	{ ip_param_generic_get, ip_squeue_profile_set,
925 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
926 	{ ip_param_generic_get, ip_squeue_bind_set,
927 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
928 	{ ip_param_generic_get, ip_input_proc_set,
929 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
930 	{ ip_param_generic_get, ip_int_set,
931 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
932 #define	IPNDP_CGTP_FILTER_OFFSET	16
933 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
934 	    "ip_cgtp_filter" },
935 	{ ip_param_generic_get, ip_int_set,
936 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
937 };
938 
939 /*
940  * Table of IP ioctls encoding the various properties of the ioctl and
941  * indexed based on the last byte of the ioctl command. Occasionally there
942  * is a clash, and there is more than 1 ioctl with the same last byte.
943  * In such a case 1 ioctl is encoded in the ndx table and the remaining
944  * ioctls are encoded in the misc table. An entry in the ndx table is
945  * retrieved by indexing on the last byte of the ioctl command and comparing
946  * the ioctl command with the value in the ndx table. In the event of a
947  * mismatch the misc table is then searched sequentially for the desired
948  * ioctl command.
949  *
950  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
951  */
952 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
953 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
961 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
962 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
963 
964 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
965 			MISC_CMD, ip_siocaddrt, NULL },
966 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
967 			MISC_CMD, ip_siocdelrt, NULL },
968 
969 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
970 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
971 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
972 			IF_CMD, ip_sioctl_get_addr, NULL },
973 
974 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
975 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
976 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
977 			IPI_GET_CMD | IPI_REPL,
978 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
979 
980 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
981 			IPI_PRIV | IPI_WR | IPI_REPL,
982 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
983 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
984 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
985 			IF_CMD, ip_sioctl_get_flags, NULL },
986 
987 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
988 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
989 
990 	/* copyin size cannot be coded for SIOCGIFCONF */
991 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
992 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
993 
994 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
995 			IF_CMD, ip_sioctl_mtu, NULL },
996 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
997 			IF_CMD, ip_sioctl_get_mtu, NULL },
998 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
999 			IPI_GET_CMD | IPI_REPL,
1000 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1001 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1002 			IF_CMD, ip_sioctl_brdaddr, NULL },
1003 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1004 			IPI_GET_CMD | IPI_REPL,
1005 			IF_CMD, ip_sioctl_get_netmask, NULL },
1006 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1007 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1008 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1009 			IPI_GET_CMD | IPI_REPL,
1010 			IF_CMD, ip_sioctl_get_metric, NULL },
1011 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1012 			IF_CMD, ip_sioctl_metric, NULL },
1013 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1014 
1015 	/* See 166-168 below for extended SIOC*XARP ioctls */
1016 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1017 			MISC_CMD, ip_sioctl_arp, NULL },
1018 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1019 			MISC_CMD, ip_sioctl_arp, NULL },
1020 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1021 			MISC_CMD, ip_sioctl_arp, NULL },
1022 
1023 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 
1045 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1046 			MISC_CMD, if_unitsel, if_unitsel_restart },
1047 
1048 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 
1067 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1068 			IPI_PRIV | IPI_WR | IPI_MODOK,
1069 			IF_CMD, ip_sioctl_sifname, NULL },
1070 
1071 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 
1085 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1086 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1087 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1088 			IF_CMD, ip_sioctl_get_muxid, NULL },
1089 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1090 			IPI_PRIV | IPI_WR | IPI_REPL,
1091 			IF_CMD, ip_sioctl_muxid, NULL },
1092 
1093 	/* Both if and lif variants share same func */
1094 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1095 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1096 	/* Both if and lif variants share same func */
1097 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1098 			IPI_PRIV | IPI_WR | IPI_REPL,
1099 			IF_CMD, ip_sioctl_slifindex, NULL },
1100 
1101 	/* copyin size cannot be coded for SIOCGIFCONF */
1102 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1103 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1104 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 
1122 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1123 			IPI_PRIV | IPI_WR | IPI_REPL,
1124 			LIF_CMD, ip_sioctl_removeif,
1125 			ip_sioctl_removeif_restart },
1126 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1127 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1128 			LIF_CMD, ip_sioctl_addif, NULL },
1129 #define	SIOCLIFADDR_NDX 112
1130 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1131 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1132 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1133 			IPI_GET_CMD | IPI_REPL,
1134 			LIF_CMD, ip_sioctl_get_addr, NULL },
1135 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1136 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1137 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1138 			IPI_GET_CMD | IPI_REPL,
1139 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1140 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1141 			IPI_PRIV | IPI_WR | IPI_REPL,
1142 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1143 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1144 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1145 			LIF_CMD, ip_sioctl_get_flags, NULL },
1146 
1147 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 
1150 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1151 			ip_sioctl_get_lifconf, NULL },
1152 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1153 			LIF_CMD, ip_sioctl_mtu, NULL },
1154 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1155 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1156 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1157 			IPI_GET_CMD | IPI_REPL,
1158 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1159 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1160 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1161 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1162 			IPI_GET_CMD | IPI_REPL,
1163 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1164 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1165 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1166 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1167 			IPI_GET_CMD | IPI_REPL,
1168 			LIF_CMD, ip_sioctl_get_metric, NULL },
1169 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1170 			LIF_CMD, ip_sioctl_metric, NULL },
1171 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1172 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1173 			LIF_CMD, ip_sioctl_slifname,
1174 			ip_sioctl_slifname_restart },
1175 
1176 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1177 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1178 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1179 			IPI_GET_CMD | IPI_REPL,
1180 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1181 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1182 			IPI_PRIV | IPI_WR | IPI_REPL,
1183 			LIF_CMD, ip_sioctl_muxid, NULL },
1184 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1185 			IPI_GET_CMD | IPI_REPL,
1186 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1187 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1188 			IPI_PRIV | IPI_WR | IPI_REPL,
1189 			LIF_CMD, ip_sioctl_slifindex, 0 },
1190 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1191 			LIF_CMD, ip_sioctl_token, NULL },
1192 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1193 			IPI_GET_CMD | IPI_REPL,
1194 			LIF_CMD, ip_sioctl_get_token, NULL },
1195 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1197 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1198 			IPI_GET_CMD | IPI_REPL,
1199 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1200 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1201 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1202 
1203 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1204 			IPI_GET_CMD | IPI_REPL,
1205 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1206 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1207 			LIF_CMD, ip_siocdelndp_v6, NULL },
1208 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1209 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1210 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1211 			LIF_CMD, ip_siocsetndp_v6, NULL },
1212 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1213 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1214 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1215 			MISC_CMD, ip_sioctl_tonlink, NULL },
1216 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1217 			MISC_CMD, ip_sioctl_tmysite, NULL },
1218 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1219 			TUN_CMD, ip_sioctl_tunparam, NULL },
1220 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1221 			IPI_PRIV | IPI_WR,
1222 			TUN_CMD, ip_sioctl_tunparam, NULL },
1223 
1224 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1225 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1226 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1227 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1228 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1229 
1230 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1231 			IPI_PRIV | IPI_WR | IPI_REPL,
1232 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1233 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1234 			IPI_PRIV | IPI_WR | IPI_REPL,
1235 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1236 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1237 			IPI_PRIV | IPI_WR,
1238 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1239 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1240 			IPI_GET_CMD | IPI_REPL,
1241 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1242 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1243 			IPI_GET_CMD | IPI_REPL,
1244 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1245 
1246 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1247 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1248 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1249 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1250 
1251 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1252 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1253 
1254 	/* These are handled in ip_sioctl_copyin_setup itself */
1255 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1256 			MISC_CMD, NULL, NULL },
1257 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1258 			MISC_CMD, NULL, NULL },
1259 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1260 
1261 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1262 			ip_sioctl_get_lifconf, NULL },
1263 
1264 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1265 			MISC_CMD, ip_sioctl_xarp, NULL },
1266 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1267 			MISC_CMD, ip_sioctl_xarp, NULL },
1268 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1269 			MISC_CMD, ip_sioctl_xarp, NULL },
1270 
1271 	/* SIOCPOPSOCKFS is not handled by IP */
1272 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1273 
1274 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1275 			IPI_GET_CMD | IPI_REPL,
1276 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1277 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1278 			IPI_PRIV | IPI_WR | IPI_REPL,
1279 			LIF_CMD, ip_sioctl_slifzone,
1280 			ip_sioctl_slifzone_restart },
1281 	/* 172-174 are SCTP ioctls and not handled by IP */
1282 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1283 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1284 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1285 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1286 			IPI_GET_CMD, LIF_CMD,
1287 			ip_sioctl_get_lifusesrc, 0 },
1288 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1289 			IPI_PRIV | IPI_WR,
1290 			LIF_CMD, ip_sioctl_slifusesrc,
1291 			NULL },
1292 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1293 			ip_sioctl_get_lifsrcof, NULL },
1294 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1295 			MISC_CMD, ip_sioctl_msfilter, NULL },
1296 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1297 			MISC_CMD, ip_sioctl_msfilter, NULL },
1298 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1299 			MISC_CMD, ip_sioctl_msfilter, NULL },
1300 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1301 			MISC_CMD, ip_sioctl_msfilter, NULL },
1302 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1303 			ip_sioctl_set_ipmpfailback, NULL }
1304 };
1305 
1306 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1307 
1308 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1309 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1310 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1311 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1312 		TUN_CMD, ip_sioctl_tunparam, NULL },
1313 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1314 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1315 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1317 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1318 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1319 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1320 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1321 		MISC_CMD, mrt_ioctl},
1322 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1323 		MISC_CMD, mrt_ioctl},
1324 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1325 		MISC_CMD, mrt_ioctl}
1326 };
1327 
1328 int ip_misc_ioctl_count =
1329     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1330 
1331 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1332 					/* Settable in /etc/system */
1333 /* Defined in ip_ire.c */
1334 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1335 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1336 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1337 
1338 static nv_t	ire_nv_arr[] = {
1339 	{ IRE_BROADCAST, "BROADCAST" },
1340 	{ IRE_LOCAL, "LOCAL" },
1341 	{ IRE_LOOPBACK, "LOOPBACK" },
1342 	{ IRE_CACHE, "CACHE" },
1343 	{ IRE_DEFAULT, "DEFAULT" },
1344 	{ IRE_PREFIX, "PREFIX" },
1345 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1346 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1347 	{ IRE_HOST, "HOST" },
1348 	{ 0 }
1349 };
1350 
1351 nv_t	*ire_nv_tbl = ire_nv_arr;
1352 
1353 /* Defined in ip_netinfo.c */
1354 extern ddi_taskq_t	*eventq_queue_nic;
1355 
1356 /* Simple ICMP IP Header Template */
1357 static ipha_t icmp_ipha = {
1358 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1359 };
1360 
1361 struct module_info ip_mod_info = {
1362 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1363 };
1364 
1365 /*
1366  * Duplicate static symbols within a module confuses mdb; so we avoid the
1367  * problem by making the symbols here distinct from those in udp.c.
1368  */
1369 
1370 static struct qinit iprinit = {
1371 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1372 	&ip_mod_info
1373 };
1374 
1375 static struct qinit ipwinit = {
1376 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1377 	&ip_mod_info
1378 };
1379 
1380 static struct qinit iplrinit = {
1381 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1382 	&ip_mod_info
1383 };
1384 
1385 static struct qinit iplwinit = {
1386 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1387 	&ip_mod_info
1388 };
1389 
1390 struct streamtab ipinfo = {
1391 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1392 };
1393 
1394 #ifdef	DEBUG
1395 static boolean_t skip_sctp_cksum = B_FALSE;
1396 #endif
1397 
1398 /*
1399  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1400  * ip_rput_v6(), ip_output(), etc.  If the message
1401  * block already has a M_CTL at the front of it, then simply set the zoneid
1402  * appropriately.
1403  */
1404 mblk_t *
1405 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1406 {
1407 	mblk_t		*first_mp;
1408 	ipsec_out_t	*io;
1409 
1410 	ASSERT(zoneid != ALL_ZONES);
1411 	if (mp->b_datap->db_type == M_CTL) {
1412 		io = (ipsec_out_t *)mp->b_rptr;
1413 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1414 		io->ipsec_out_zoneid = zoneid;
1415 		return (mp);
1416 	}
1417 
1418 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1419 	if (first_mp == NULL)
1420 		return (NULL);
1421 	io = (ipsec_out_t *)first_mp->b_rptr;
1422 	/* This is not a secure packet */
1423 	io->ipsec_out_secure = B_FALSE;
1424 	io->ipsec_out_zoneid = zoneid;
1425 	first_mp->b_cont = mp;
1426 	return (first_mp);
1427 }
1428 
1429 /*
1430  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1431  */
1432 mblk_t *
1433 ip_copymsg(mblk_t *mp)
1434 {
1435 	mblk_t *nmp;
1436 	ipsec_info_t *in;
1437 
1438 	if (mp->b_datap->db_type != M_CTL)
1439 		return (copymsg(mp));
1440 
1441 	in = (ipsec_info_t *)mp->b_rptr;
1442 
1443 	/*
1444 	 * Note that M_CTL is also used for delivering ICMP error messages
1445 	 * upstream to transport layers.
1446 	 */
1447 	if (in->ipsec_info_type != IPSEC_OUT &&
1448 	    in->ipsec_info_type != IPSEC_IN)
1449 		return (copymsg(mp));
1450 
1451 	nmp = copymsg(mp->b_cont);
1452 
1453 	if (in->ipsec_info_type == IPSEC_OUT) {
1454 		return (ipsec_out_tag(mp, nmp,
1455 			    ((ipsec_out_t *)in)->ipsec_out_ns));
1456 	} else {
1457 		return (ipsec_in_tag(mp, nmp,
1458 			    ((ipsec_in_t *)in)->ipsec_in_ns));
1459 	}
1460 }
1461 
1462 /* Generate an ICMP fragmentation needed message. */
1463 static void
1464 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1465     ip_stack_t *ipst)
1466 {
1467 	icmph_t	icmph;
1468 	mblk_t *first_mp;
1469 	boolean_t mctl_present;
1470 
1471 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1472 
1473 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1474 		if (mctl_present)
1475 			freeb(first_mp);
1476 		return;
1477 	}
1478 
1479 	bzero(&icmph, sizeof (icmph_t));
1480 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1481 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1482 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1483 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1484 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1485 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1486 	    ipst);
1487 }
1488 
1489 /*
1490  * icmp_inbound deals with ICMP messages in the following ways.
1491  *
1492  * 1) It needs to send a reply back and possibly delivering it
1493  *    to the "interested" upper clients.
1494  * 2) It needs to send it to the upper clients only.
1495  * 3) It needs to change some values in IP only.
1496  * 4) It needs to change some values in IP and upper layers e.g TCP.
1497  *
1498  * We need to accomodate icmp messages coming in clear until we get
1499  * everything secure from the wire. If icmp_accept_clear_messages
1500  * is zero we check with the global policy and act accordingly. If
1501  * it is non-zero, we accept the message without any checks. But
1502  * *this does not mean* that this will be delivered to the upper
1503  * clients. By accepting we might send replies back, change our MTU
1504  * value etc. but delivery to the ULP/clients depends on their policy
1505  * dispositions.
1506  *
1507  * We handle the above 4 cases in the context of IPSEC in the
1508  * following way :
1509  *
1510  * 1) Send the reply back in the same way as the request came in.
1511  *    If it came in encrypted, it goes out encrypted. If it came in
1512  *    clear, it goes out in clear. Thus, this will prevent chosen
1513  *    plain text attack.
1514  * 2) The client may or may not expect things to come in secure.
1515  *    If it comes in secure, the policy constraints are checked
1516  *    before delivering it to the upper layers. If it comes in
1517  *    clear, ipsec_inbound_accept_clear will decide whether to
1518  *    accept this in clear or not. In both the cases, if the returned
1519  *    message (IP header + 8 bytes) that caused the icmp message has
1520  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1521  *    sending up. If there are only 8 bytes of returned message, then
1522  *    upper client will not be notified.
1523  * 3) Check with global policy to see whether it matches the constaints.
1524  *    But this will be done only if icmp_accept_messages_in_clear is
1525  *    zero.
1526  * 4) If we need to change both in IP and ULP, then the decision taken
1527  *    while affecting the values in IP and while delivering up to TCP
1528  *    should be the same.
1529  *
1530  * 	There are two cases.
1531  *
1532  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1533  *	   failed), we will not deliver it to the ULP, even though they
1534  *	   are *willing* to accept in *clear*. This is fine as our global
1535  *	   disposition to icmp messages asks us reject the datagram.
1536  *
1537  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1538  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1539  *	   to deliver it to ULP (policy failed), it can lead to
1540  *	   consistency problems. The cases known at this time are
1541  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1542  *	   values :
1543  *
1544  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1545  *	     and Upper layer rejects. Then the communication will
1546  *	     come to a stop. This is solved by making similar decisions
1547  *	     at both levels. Currently, when we are unable to deliver
1548  *	     to the Upper Layer (due to policy failures) while IP has
1549  *	     adjusted ire_max_frag, the next outbound datagram would
1550  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1551  *	     will be with the right level of protection. Thus the right
1552  *	     value will be communicated even if we are not able to
1553  *	     communicate when we get from the wire initially. But this
1554  *	     assumes there would be at least one outbound datagram after
1555  *	     IP has adjusted its ire_max_frag value. To make things
1556  *	     simpler, we accept in clear after the validation of
1557  *	     AH/ESP headers.
1558  *
1559  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1560  *	     upper layer depending on the level of protection the upper
1561  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1562  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1563  *	     should be accepted in clear when the Upper layer expects secure.
1564  *	     Thus the communication may get aborted by some bad ICMP
1565  *	     packets.
1566  *
1567  * IPQoS Notes:
1568  * The only instance when a packet is sent for processing is when there
1569  * isn't an ICMP client and if we are interested in it.
1570  * If there is a client, IPPF processing will take place in the
1571  * ip_fanout_proto routine.
1572  *
1573  * Zones notes:
1574  * The packet is only processed in the context of the specified zone: typically
1575  * only this zone will reply to an echo request, and only interested clients in
1576  * this zone will receive a copy of the packet. This means that the caller must
1577  * call icmp_inbound() for each relevant zone.
1578  */
1579 static void
1580 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1581     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1582     ill_t *recv_ill, zoneid_t zoneid)
1583 {
1584 	icmph_t	*icmph;
1585 	ipha_t	*ipha;
1586 	int	iph_hdr_length;
1587 	int	hdr_length;
1588 	boolean_t	interested;
1589 	uint32_t	ts;
1590 	uchar_t	*wptr;
1591 	ipif_t	*ipif;
1592 	mblk_t *first_mp;
1593 	ipsec_in_t *ii;
1594 	ire_t *src_ire;
1595 	boolean_t onlink;
1596 	timestruc_t now;
1597 	uint32_t ill_index;
1598 	ip_stack_t *ipst;
1599 
1600 	ASSERT(ill != NULL);
1601 	ipst = ill->ill_ipst;
1602 
1603 	first_mp = mp;
1604 	if (mctl_present) {
1605 		mp = first_mp->b_cont;
1606 		ASSERT(mp != NULL);
1607 	}
1608 
1609 	ipha = (ipha_t *)mp->b_rptr;
1610 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1611 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1612 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1613 		if (first_mp == NULL)
1614 			return;
1615 	}
1616 
1617 	/*
1618 	 * On a labeled system, we have to check whether the zone itself is
1619 	 * permitted to receive raw traffic.
1620 	 */
1621 	if (is_system_labeled()) {
1622 		if (zoneid == ALL_ZONES)
1623 			zoneid = tsol_packet_to_zoneid(mp);
1624 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1625 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1626 			    zoneid));
1627 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1628 			freemsg(first_mp);
1629 			return;
1630 		}
1631 	}
1632 
1633 	/*
1634 	 * We have accepted the ICMP message. It means that we will
1635 	 * respond to the packet if needed. It may not be delivered
1636 	 * to the upper client depending on the policy constraints
1637 	 * and the disposition in ipsec_inbound_accept_clear.
1638 	 */
1639 
1640 	ASSERT(ill != NULL);
1641 
1642 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1643 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1644 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1645 		/* Last chance to get real. */
1646 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1647 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1648 			freemsg(first_mp);
1649 			return;
1650 		}
1651 		/* Refresh iph following the pullup. */
1652 		ipha = (ipha_t *)mp->b_rptr;
1653 	}
1654 	/* ICMP header checksum, including checksum field, should be zero. */
1655 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1656 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1657 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1658 		freemsg(first_mp);
1659 		return;
1660 	}
1661 	/* The IP header will always be a multiple of four bytes */
1662 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1663 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1664 	    icmph->icmph_code));
1665 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1666 	/* We will set "interested" to "true" if we want a copy */
1667 	interested = B_FALSE;
1668 	switch (icmph->icmph_type) {
1669 	case ICMP_ECHO_REPLY:
1670 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1671 		break;
1672 	case ICMP_DEST_UNREACHABLE:
1673 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1674 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1675 		interested = B_TRUE;	/* Pass up to transport */
1676 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1677 		break;
1678 	case ICMP_SOURCE_QUENCH:
1679 		interested = B_TRUE;	/* Pass up to transport */
1680 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1681 		break;
1682 	case ICMP_REDIRECT:
1683 		if (!ipst->ips_ip_ignore_redirect)
1684 			interested = B_TRUE;
1685 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1686 		break;
1687 	case ICMP_ECHO_REQUEST:
1688 		/*
1689 		 * Whether to respond to echo requests that come in as IP
1690 		 * broadcasts or as IP multicast is subject to debate
1691 		 * (what isn't?).  We aim to please, you pick it.
1692 		 * Default is do it.
1693 		 */
1694 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1695 			/* unicast: always respond */
1696 			interested = B_TRUE;
1697 		} else if (CLASSD(ipha->ipha_dst)) {
1698 			/* multicast: respond based on tunable */
1699 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1700 		} else if (broadcast) {
1701 			/* broadcast: respond based on tunable */
1702 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1703 		}
1704 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1705 		break;
1706 	case ICMP_ROUTER_ADVERTISEMENT:
1707 	case ICMP_ROUTER_SOLICITATION:
1708 		break;
1709 	case ICMP_TIME_EXCEEDED:
1710 		interested = B_TRUE;	/* Pass up to transport */
1711 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1712 		break;
1713 	case ICMP_PARAM_PROBLEM:
1714 		interested = B_TRUE;	/* Pass up to transport */
1715 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1716 		break;
1717 	case ICMP_TIME_STAMP_REQUEST:
1718 		/* Response to Time Stamp Requests is local policy. */
1719 		if (ipst->ips_ip_g_resp_to_timestamp &&
1720 		    /* So is whether to respond if it was an IP broadcast. */
1721 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1722 			int tstamp_len = 3 * sizeof (uint32_t);
1723 
1724 			if (wptr +  tstamp_len > mp->b_wptr) {
1725 				if (!pullupmsg(mp, wptr + tstamp_len -
1726 				    mp->b_rptr)) {
1727 					BUMP_MIB(ill->ill_ip_mib,
1728 					    ipIfStatsInDiscards);
1729 					freemsg(first_mp);
1730 					return;
1731 				}
1732 				/* Refresh ipha following the pullup. */
1733 				ipha = (ipha_t *)mp->b_rptr;
1734 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1735 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1736 			}
1737 			interested = B_TRUE;
1738 		}
1739 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1740 		break;
1741 	case ICMP_TIME_STAMP_REPLY:
1742 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1743 		break;
1744 	case ICMP_INFO_REQUEST:
1745 		/* Per RFC 1122 3.2.2.7, ignore this. */
1746 	case ICMP_INFO_REPLY:
1747 		break;
1748 	case ICMP_ADDRESS_MASK_REQUEST:
1749 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1750 			!broadcast) &&
1751 		    /* TODO m_pullup of complete header? */
1752 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1753 			interested = B_TRUE;
1754 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1755 		break;
1756 	case ICMP_ADDRESS_MASK_REPLY:
1757 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1758 		break;
1759 	default:
1760 		interested = B_TRUE;	/* Pass up to transport */
1761 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1762 		break;
1763 	}
1764 	/* See if there is an ICMP client. */
1765 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1766 		/* If there is an ICMP client and we want one too, copy it. */
1767 		mblk_t *first_mp1;
1768 
1769 		if (!interested) {
1770 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1771 			    ip_policy, recv_ill, zoneid);
1772 			return;
1773 		}
1774 		first_mp1 = ip_copymsg(first_mp);
1775 		if (first_mp1 != NULL) {
1776 			ip_fanout_proto(q, first_mp1, ill, ipha,
1777 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1778 		}
1779 	} else if (!interested) {
1780 		freemsg(first_mp);
1781 		return;
1782 	} else {
1783 		/*
1784 		 * Initiate policy processing for this packet if ip_policy
1785 		 * is true.
1786 		 */
1787 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1788 			ill_index = ill->ill_phyint->phyint_ifindex;
1789 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1790 			if (mp == NULL) {
1791 				if (mctl_present) {
1792 					freeb(first_mp);
1793 				}
1794 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1795 				return;
1796 			}
1797 		}
1798 	}
1799 	/* We want to do something with it. */
1800 	/* Check db_ref to make sure we can modify the packet. */
1801 	if (mp->b_datap->db_ref > 1) {
1802 		mblk_t	*first_mp1;
1803 
1804 		first_mp1 = ip_copymsg(first_mp);
1805 		freemsg(first_mp);
1806 		if (!first_mp1) {
1807 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1808 			return;
1809 		}
1810 		first_mp = first_mp1;
1811 		if (mctl_present) {
1812 			mp = first_mp->b_cont;
1813 			ASSERT(mp != NULL);
1814 		} else {
1815 			mp = first_mp;
1816 		}
1817 		ipha = (ipha_t *)mp->b_rptr;
1818 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1819 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1820 	}
1821 	switch (icmph->icmph_type) {
1822 	case ICMP_ADDRESS_MASK_REQUEST:
1823 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1824 		if (ipif == NULL) {
1825 			freemsg(first_mp);
1826 			return;
1827 		}
1828 		/*
1829 		 * outging interface must be IPv4
1830 		 */
1831 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1832 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1833 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1834 		ipif_refrele(ipif);
1835 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1836 		break;
1837 	case ICMP_ECHO_REQUEST:
1838 		icmph->icmph_type = ICMP_ECHO_REPLY;
1839 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1840 		break;
1841 	case ICMP_TIME_STAMP_REQUEST: {
1842 		uint32_t *tsp;
1843 
1844 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1845 		tsp = (uint32_t *)wptr;
1846 		tsp++;		/* Skip past 'originate time' */
1847 		/* Compute # of milliseconds since midnight */
1848 		gethrestime(&now);
1849 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1850 		    now.tv_nsec / (NANOSEC / MILLISEC);
1851 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1852 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1853 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1854 		break;
1855 	}
1856 	default:
1857 		ipha = (ipha_t *)&icmph[1];
1858 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1859 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1860 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1861 				freemsg(first_mp);
1862 				return;
1863 			}
1864 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1865 			ipha = (ipha_t *)&icmph[1];
1866 		}
1867 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1868 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1869 			freemsg(first_mp);
1870 			return;
1871 		}
1872 		hdr_length = IPH_HDR_LENGTH(ipha);
1873 		if (hdr_length < sizeof (ipha_t)) {
1874 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1875 			freemsg(first_mp);
1876 			return;
1877 		}
1878 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1879 			if (!pullupmsg(mp,
1880 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1881 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1882 				freemsg(first_mp);
1883 				return;
1884 			}
1885 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1886 			ipha = (ipha_t *)&icmph[1];
1887 		}
1888 		switch (icmph->icmph_type) {
1889 		case ICMP_REDIRECT:
1890 			/*
1891 			 * As there is no upper client to deliver, we don't
1892 			 * need the first_mp any more.
1893 			 */
1894 			if (mctl_present) {
1895 				freeb(first_mp);
1896 			}
1897 			icmp_redirect(ill, mp);
1898 			return;
1899 		case ICMP_DEST_UNREACHABLE:
1900 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1901 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1902 				    zoneid, mp, iph_hdr_length, ipst)) {
1903 					freemsg(first_mp);
1904 					return;
1905 				}
1906 				/*
1907 				 * icmp_inbound_too_big() may alter mp.
1908 				 * Resynch ipha and icmph accordingly.
1909 				 */
1910 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1911 				ipha = (ipha_t *)&icmph[1];
1912 			}
1913 			/* FALLTHRU */
1914 		default :
1915 			/*
1916 			 * IPQoS notes: Since we have already done IPQoS
1917 			 * processing we don't want to do it again in
1918 			 * the fanout routines called by
1919 			 * icmp_inbound_error_fanout, hence the last
1920 			 * argument, ip_policy, is B_FALSE.
1921 			 */
1922 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1923 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1924 			    B_FALSE, recv_ill, zoneid);
1925 		}
1926 		return;
1927 	}
1928 	/* Send out an ICMP packet */
1929 	icmph->icmph_checksum = 0;
1930 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1931 	if (icmph->icmph_checksum == 0)
1932 		icmph->icmph_checksum = 0xFFFF;
1933 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1934 		ipif_t	*ipif_chosen;
1935 		/*
1936 		 * Make it look like it was directed to us, so we don't look
1937 		 * like a fool with a broadcast or multicast source address.
1938 		 */
1939 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1940 		/*
1941 		 * Make sure that we haven't grabbed an interface that's DOWN.
1942 		 */
1943 		if (ipif != NULL) {
1944 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1945 			    ipha->ipha_src, zoneid);
1946 			if (ipif_chosen != NULL) {
1947 				ipif_refrele(ipif);
1948 				ipif = ipif_chosen;
1949 			}
1950 		}
1951 		if (ipif == NULL) {
1952 			ip0dbg(("icmp_inbound: "
1953 			    "No source for broadcast/multicast:\n"
1954 			    "\tsrc 0x%x dst 0x%x ill %p "
1955 			    "ipif_lcl_addr 0x%x\n",
1956 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1957 			    (void *)ill,
1958 			    ill->ill_ipif->ipif_lcl_addr));
1959 			freemsg(first_mp);
1960 			return;
1961 		}
1962 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1963 		ipha->ipha_dst = ipif->ipif_src_addr;
1964 		ipif_refrele(ipif);
1965 	}
1966 	/* Reset time to live. */
1967 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1968 	{
1969 		/* Swap source and destination addresses */
1970 		ipaddr_t tmp;
1971 
1972 		tmp = ipha->ipha_src;
1973 		ipha->ipha_src = ipha->ipha_dst;
1974 		ipha->ipha_dst = tmp;
1975 	}
1976 	ipha->ipha_ident = 0;
1977 	if (!IS_SIMPLE_IPH(ipha))
1978 		icmp_options_update(ipha);
1979 
1980 	/*
1981 	 * ICMP echo replies should go out on the same interface
1982 	 * the request came on as probes used by in.mpathd for detecting
1983 	 * NIC failures are ECHO packets. We turn-off load spreading
1984 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1985 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1986 	 * function. This is in turn handled by ip_wput and ip_newroute
1987 	 * to make sure that the packet goes out on the interface it came
1988 	 * in on. If we don't turnoff load spreading, the packets might get
1989 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1990 	 * to go out and in.mpathd would wrongly detect a failure or
1991 	 * mis-detect a NIC failure for link failure. As load spreading
1992 	 * can happen only if ill_group is not NULL, we do only for
1993 	 * that case and this does not affect the normal case.
1994 	 *
1995 	 * We turn off load spreading only on echo packets that came from
1996 	 * on-link hosts. If the interface route has been deleted, this will
1997 	 * not be enforced as we can't do much. For off-link hosts, as the
1998 	 * default routes in IPv4 does not typically have an ire_ipif
1999 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2000 	 * Moreover, expecting a default route through this interface may
2001 	 * not be correct. We use ipha_dst because of the swap above.
2002 	 */
2003 	onlink = B_FALSE;
2004 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2005 		/*
2006 		 * First, we need to make sure that it is not one of our
2007 		 * local addresses. If we set onlink when it is one of
2008 		 * our local addresses, we will end up creating IRE_CACHES
2009 		 * for one of our local addresses. Then, we will never
2010 		 * accept packets for them afterwards.
2011 		 */
2012 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2013 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2014 		if (src_ire == NULL) {
2015 			ipif = ipif_get_next_ipif(NULL, ill);
2016 			if (ipif == NULL) {
2017 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2018 				freemsg(mp);
2019 				return;
2020 			}
2021 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2022 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2023 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2024 			ipif_refrele(ipif);
2025 			if (src_ire != NULL) {
2026 				onlink = B_TRUE;
2027 				ire_refrele(src_ire);
2028 			}
2029 		} else {
2030 			ire_refrele(src_ire);
2031 		}
2032 	}
2033 	if (!mctl_present) {
2034 		/*
2035 		 * This packet should go out the same way as it
2036 		 * came in i.e in clear. To make sure that global
2037 		 * policy will not be applied to this in ip_wput_ire,
2038 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2039 		 */
2040 		ASSERT(first_mp == mp);
2041 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2042 		if (first_mp == NULL) {
2043 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2044 			freemsg(mp);
2045 			return;
2046 		}
2047 		ii = (ipsec_in_t *)first_mp->b_rptr;
2048 
2049 		/* This is not a secure packet */
2050 		ii->ipsec_in_secure = B_FALSE;
2051 		if (onlink) {
2052 			ii->ipsec_in_attach_if = B_TRUE;
2053 			ii->ipsec_in_ill_index =
2054 			    ill->ill_phyint->phyint_ifindex;
2055 			ii->ipsec_in_rill_index =
2056 			    recv_ill->ill_phyint->phyint_ifindex;
2057 		}
2058 		first_mp->b_cont = mp;
2059 	} else if (onlink) {
2060 		ii = (ipsec_in_t *)first_mp->b_rptr;
2061 		ii->ipsec_in_attach_if = B_TRUE;
2062 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2063 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2064 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2065 	} else {
2066 		ii = (ipsec_in_t *)first_mp->b_rptr;
2067 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2068 	}
2069 	ii->ipsec_in_zoneid = zoneid;
2070 	ASSERT(zoneid != ALL_ZONES);
2071 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2072 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2073 		return;
2074 	}
2075 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2076 	put(WR(q), first_mp);
2077 }
2078 
2079 static ipaddr_t
2080 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2081 {
2082 	conn_t *connp;
2083 	connf_t *connfp;
2084 	ipaddr_t nexthop_addr = INADDR_ANY;
2085 	int hdr_length = IPH_HDR_LENGTH(ipha);
2086 	uint16_t *up;
2087 	uint32_t ports;
2088 	ip_stack_t *ipst = ill->ill_ipst;
2089 
2090 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2091 	switch (ipha->ipha_protocol) {
2092 		case IPPROTO_TCP:
2093 		{
2094 			tcph_t *tcph;
2095 
2096 			/* do a reverse lookup */
2097 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2098 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2099 			    TCPS_LISTEN, ipst);
2100 			break;
2101 		}
2102 		case IPPROTO_UDP:
2103 		{
2104 			uint32_t dstport, srcport;
2105 
2106 			((uint16_t *)&ports)[0] = up[1];
2107 			((uint16_t *)&ports)[1] = up[0];
2108 
2109 			/* Extract ports in net byte order */
2110 			dstport = htons(ntohl(ports) & 0xFFFF);
2111 			srcport = htons(ntohl(ports) >> 16);
2112 
2113 			connfp = &ipst->ips_ipcl_udp_fanout[
2114 			    IPCL_UDP_HASH(dstport, ipst)];
2115 			mutex_enter(&connfp->connf_lock);
2116 			connp = connfp->connf_head;
2117 
2118 			/* do a reverse lookup */
2119 			while ((connp != NULL) &&
2120 			    (!IPCL_UDP_MATCH(connp, dstport,
2121 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2122 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2123 				connp = connp->conn_next;
2124 			}
2125 			if (connp != NULL)
2126 				CONN_INC_REF(connp);
2127 			mutex_exit(&connfp->connf_lock);
2128 			break;
2129 		}
2130 		case IPPROTO_SCTP:
2131 		{
2132 			in6_addr_t map_src, map_dst;
2133 
2134 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2135 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2136 			((uint16_t *)&ports)[0] = up[1];
2137 			((uint16_t *)&ports)[1] = up[0];
2138 
2139 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2140 			    zoneid, ipst->ips_netstack->netstack_sctp);
2141 			if (connp == NULL) {
2142 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2143 				    zoneid, ports, ipha, ipst);
2144 			} else {
2145 				CONN_INC_REF(connp);
2146 				SCTP_REFRELE(CONN2SCTP(connp));
2147 			}
2148 			break;
2149 		}
2150 		default:
2151 		{
2152 			ipha_t ripha;
2153 
2154 			ripha.ipha_src = ipha->ipha_dst;
2155 			ripha.ipha_dst = ipha->ipha_src;
2156 			ripha.ipha_protocol = ipha->ipha_protocol;
2157 
2158 			connfp = &ipst->ips_ipcl_proto_fanout[
2159 			    ipha->ipha_protocol];
2160 			mutex_enter(&connfp->connf_lock);
2161 			connp = connfp->connf_head;
2162 			for (connp = connfp->connf_head; connp != NULL;
2163 			    connp = connp->conn_next) {
2164 				if (IPCL_PROTO_MATCH(connp,
2165 				    ipha->ipha_protocol, &ripha, ill,
2166 				    0, zoneid)) {
2167 					CONN_INC_REF(connp);
2168 					break;
2169 				}
2170 			}
2171 			mutex_exit(&connfp->connf_lock);
2172 		}
2173 	}
2174 	if (connp != NULL) {
2175 		if (connp->conn_nexthop_set)
2176 			nexthop_addr = connp->conn_nexthop_v4;
2177 		CONN_DEC_REF(connp);
2178 	}
2179 	return (nexthop_addr);
2180 }
2181 
2182 /* Table from RFC 1191 */
2183 static int icmp_frag_size_table[] =
2184 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2185 
2186 /*
2187  * Process received ICMP Packet too big.
2188  * After updating any IRE it does the fanout to any matching transport streams.
2189  * Assumes the message has been pulled up till the IP header that caused
2190  * the error.
2191  *
2192  * Returns B_FALSE on failure and B_TRUE on success.
2193  */
2194 static boolean_t
2195 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2196     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2197     ip_stack_t *ipst)
2198 {
2199 	ire_t	*ire, *first_ire;
2200 	int	mtu;
2201 	int	hdr_length;
2202 	ipaddr_t nexthop_addr;
2203 
2204 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2205 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2206 	ASSERT(ill != NULL);
2207 
2208 	hdr_length = IPH_HDR_LENGTH(ipha);
2209 
2210 	/* Drop if the original packet contained a source route */
2211 	if (ip_source_route_included(ipha)) {
2212 		return (B_FALSE);
2213 	}
2214 	/*
2215 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2216 	 * header.
2217 	 */
2218 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2219 	    mp->b_wptr) {
2220 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2221 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2222 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2223 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2224 			return (B_FALSE);
2225 		}
2226 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2227 		ipha = (ipha_t *)&icmph[1];
2228 	}
2229 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2230 	if (nexthop_addr != INADDR_ANY) {
2231 		/* nexthop set */
2232 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2233 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2234 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2235 	} else {
2236 		/* nexthop not set */
2237 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2238 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2239 	}
2240 
2241 	if (!first_ire) {
2242 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2243 		    ntohl(ipha->ipha_dst)));
2244 		return (B_FALSE);
2245 	}
2246 	/* Check for MTU discovery advice as described in RFC 1191 */
2247 	mtu = ntohs(icmph->icmph_du_mtu);
2248 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2249 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2250 	    ire = ire->ire_next) {
2251 		/*
2252 		 * Look for the connection to which this ICMP message is
2253 		 * directed. If it has the IP_NEXTHOP option set, then the
2254 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2255 		 * option. Else the search is limited to regular IREs.
2256 		 */
2257 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2258 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2259 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2260 		    (nexthop_addr != INADDR_ANY)))
2261 			continue;
2262 
2263 		mutex_enter(&ire->ire_lock);
2264 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2265 			/* Reduce the IRE max frag value as advised. */
2266 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2267 			    mtu, ire->ire_max_frag));
2268 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2269 		} else {
2270 			uint32_t length;
2271 			int	i;
2272 
2273 			/*
2274 			 * Use the table from RFC 1191 to figure out
2275 			 * the next "plateau" based on the length in
2276 			 * the original IP packet.
2277 			 */
2278 			length = ntohs(ipha->ipha_length);
2279 			if (ire->ire_max_frag <= length &&
2280 			    ire->ire_max_frag >= length - hdr_length) {
2281 				/*
2282 				 * Handle broken BSD 4.2 systems that
2283 				 * return the wrong iph_length in ICMP
2284 				 * errors.
2285 				 */
2286 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2287 				    length, ire->ire_max_frag));
2288 				length -= hdr_length;
2289 			}
2290 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2291 				if (length > icmp_frag_size_table[i])
2292 					break;
2293 			}
2294 			if (i == A_CNT(icmp_frag_size_table)) {
2295 				/* Smaller than 68! */
2296 				ip1dbg(("Too big for packet size %d\n",
2297 				    length));
2298 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2299 				ire->ire_frag_flag = 0;
2300 			} else {
2301 				mtu = icmp_frag_size_table[i];
2302 				ip1dbg(("Calculated mtu %d, packet size %d, "
2303 				    "before %d", mtu, length,
2304 				    ire->ire_max_frag));
2305 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2306 				ip1dbg((", after %d\n", ire->ire_max_frag));
2307 			}
2308 			/* Record the new max frag size for the ULP. */
2309 			icmph->icmph_du_zero = 0;
2310 			icmph->icmph_du_mtu =
2311 			    htons((uint16_t)ire->ire_max_frag);
2312 		}
2313 		mutex_exit(&ire->ire_lock);
2314 	}
2315 	rw_exit(&first_ire->ire_bucket->irb_lock);
2316 	ire_refrele(first_ire);
2317 	return (B_TRUE);
2318 }
2319 
2320 /*
2321  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2322  * calls this function.
2323  */
2324 static mblk_t *
2325 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2326 {
2327 	ipha_t *ipha;
2328 	icmph_t *icmph;
2329 	ipha_t *in_ipha;
2330 	int length;
2331 
2332 	ASSERT(mp->b_datap->db_type == M_DATA);
2333 
2334 	/*
2335 	 * For Self-encapsulated packets, we added an extra IP header
2336 	 * without the options. Inner IP header is the one from which
2337 	 * the outer IP header was formed. Thus, we need to remove the
2338 	 * outer IP header. To do this, we pullup the whole message
2339 	 * and overlay whatever follows the outer IP header over the
2340 	 * outer IP header.
2341 	 */
2342 
2343 	if (!pullupmsg(mp, -1))
2344 		return (NULL);
2345 
2346 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2347 	ipha = (ipha_t *)&icmph[1];
2348 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2349 
2350 	/*
2351 	 * The length that we want to overlay is following the inner
2352 	 * IP header. Subtracting the IP header + icmp header + outer
2353 	 * IP header's length should give us the length that we want to
2354 	 * overlay.
2355 	 */
2356 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2357 	    hdr_length;
2358 	/*
2359 	 * Overlay whatever follows the inner header over the
2360 	 * outer header.
2361 	 */
2362 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2363 
2364 	/* Set the wptr to account for the outer header */
2365 	mp->b_wptr -= hdr_length;
2366 	return (mp);
2367 }
2368 
2369 /*
2370  * Try to pass the ICMP message upstream in case the ULP cares.
2371  *
2372  * If the packet that caused the ICMP error is secure, we send
2373  * it to AH/ESP to make sure that the attached packet has a
2374  * valid association. ipha in the code below points to the
2375  * IP header of the packet that caused the error.
2376  *
2377  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2378  * in the context of IPSEC. Normally we tell the upper layer
2379  * whenever we send the ire (including ip_bind), the IPSEC header
2380  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2381  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2382  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2383  * same thing. As TCP has the IPSEC options size that needs to be
2384  * adjusted, we just pass the MTU unchanged.
2385  *
2386  * IFN could have been generated locally or by some router.
2387  *
2388  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2389  *	    This happens because IP adjusted its value of MTU on an
2390  *	    earlier IFN message and could not tell the upper layer,
2391  *	    the new adjusted value of MTU e.g. Packet was encrypted
2392  *	    or there was not enough information to fanout to upper
2393  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2394  *	    generates the IFN, where IPSEC processing has *not* been
2395  *	    done.
2396  *
2397  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2398  *	    could have generated this. This happens because ire_max_frag
2399  *	    value in IP was set to a new value, while the IPSEC processing
2400  *	    was being done and after we made the fragmentation check in
2401  *	    ip_wput_ire. Thus on return from IPSEC processing,
2402  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2403  *	    and generates the IFN. As IPSEC processing is over, we fanout
2404  *	    to AH/ESP to remove the header.
2405  *
2406  *	    In both these cases, ipsec_in_loopback will be set indicating
2407  *	    that IFN was generated locally.
2408  *
2409  * ROUTER : IFN could be secure or non-secure.
2410  *
2411  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2412  *	      packet in error has AH/ESP headers to validate the AH/ESP
2413  *	      headers. AH/ESP will verify whether there is a valid SA or
2414  *	      not and send it back. We will fanout again if we have more
2415  *	      data in the packet.
2416  *
2417  *	      If the packet in error does not have AH/ESP, we handle it
2418  *	      like any other case.
2419  *
2420  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2421  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2422  *	      for validation. AH/ESP will verify whether there is a
2423  *	      valid SA or not and send it back. We will fanout again if
2424  *	      we have more data in the packet.
2425  *
2426  *	      If the packet in error does not have AH/ESP, we handle it
2427  *	      like any other case.
2428  */
2429 static void
2430 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2431     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2432     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2433     zoneid_t zoneid)
2434 {
2435 	uint16_t *up;	/* Pointer to ports in ULP header */
2436 	uint32_t ports;	/* reversed ports for fanout */
2437 	ipha_t ripha;	/* With reversed addresses */
2438 	mblk_t *first_mp;
2439 	ipsec_in_t *ii;
2440 	tcph_t	*tcph;
2441 	conn_t	*connp;
2442 	ip_stack_t *ipst;
2443 
2444 	ASSERT(ill != NULL);
2445 
2446 	ASSERT(recv_ill != NULL);
2447 	ipst = recv_ill->ill_ipst;
2448 
2449 	first_mp = mp;
2450 	if (mctl_present) {
2451 		mp = first_mp->b_cont;
2452 		ASSERT(mp != NULL);
2453 
2454 		ii = (ipsec_in_t *)first_mp->b_rptr;
2455 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2456 	} else {
2457 		ii = NULL;
2458 	}
2459 
2460 	switch (ipha->ipha_protocol) {
2461 	case IPPROTO_UDP:
2462 		/*
2463 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2464 		 * transport header.
2465 		 */
2466 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2467 		    mp->b_wptr) {
2468 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2469 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2470 				goto discard_pkt;
2471 			}
2472 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2473 			ipha = (ipha_t *)&icmph[1];
2474 		}
2475 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2476 
2477 		/*
2478 		 * Attempt to find a client stream based on port.
2479 		 * Note that we do a reverse lookup since the header is
2480 		 * in the form we sent it out.
2481 		 * The ripha header is only used for the IP_UDP_MATCH and we
2482 		 * only set the src and dst addresses and protocol.
2483 		 */
2484 		ripha.ipha_src = ipha->ipha_dst;
2485 		ripha.ipha_dst = ipha->ipha_src;
2486 		ripha.ipha_protocol = ipha->ipha_protocol;
2487 		((uint16_t *)&ports)[0] = up[1];
2488 		((uint16_t *)&ports)[1] = up[0];
2489 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2490 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2491 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2492 		    icmph->icmph_type, icmph->icmph_code));
2493 
2494 		/* Have to change db_type after any pullupmsg */
2495 		DB_TYPE(mp) = M_CTL;
2496 
2497 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2498 		    mctl_present, ip_policy, recv_ill, zoneid);
2499 		return;
2500 
2501 	case IPPROTO_TCP:
2502 		/*
2503 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2504 		 * transport header.
2505 		 */
2506 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2507 		    mp->b_wptr) {
2508 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2509 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2510 				goto discard_pkt;
2511 			}
2512 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2513 			ipha = (ipha_t *)&icmph[1];
2514 		}
2515 		/*
2516 		 * Find a TCP client stream for this packet.
2517 		 * Note that we do a reverse lookup since the header is
2518 		 * in the form we sent it out.
2519 		 */
2520 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2521 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2522 		    ipst);
2523 		if (connp == NULL)
2524 			goto discard_pkt;
2525 
2526 		/* Have to change db_type after any pullupmsg */
2527 		DB_TYPE(mp) = M_CTL;
2528 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2529 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2530 		return;
2531 
2532 	case IPPROTO_SCTP:
2533 		/*
2534 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2535 		 * transport header.
2536 		 */
2537 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2538 		    mp->b_wptr) {
2539 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2540 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2541 				goto discard_pkt;
2542 			}
2543 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2544 			ipha = (ipha_t *)&icmph[1];
2545 		}
2546 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2547 		/*
2548 		 * Find a SCTP client stream for this packet.
2549 		 * Note that we do a reverse lookup since the header is
2550 		 * in the form we sent it out.
2551 		 * The ripha header is only used for the matching and we
2552 		 * only set the src and dst addresses, protocol, and version.
2553 		 */
2554 		ripha.ipha_src = ipha->ipha_dst;
2555 		ripha.ipha_dst = ipha->ipha_src;
2556 		ripha.ipha_protocol = ipha->ipha_protocol;
2557 		ripha.ipha_version_and_hdr_length =
2558 		    ipha->ipha_version_and_hdr_length;
2559 		((uint16_t *)&ports)[0] = up[1];
2560 		((uint16_t *)&ports)[1] = up[0];
2561 
2562 		/* Have to change db_type after any pullupmsg */
2563 		DB_TYPE(mp) = M_CTL;
2564 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2565 		    mctl_present, ip_policy, zoneid);
2566 		return;
2567 
2568 	case IPPROTO_ESP:
2569 	case IPPROTO_AH: {
2570 		int ipsec_rc;
2571 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2572 
2573 		/*
2574 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2575 		 * We will re-use the IPSEC_IN if it is already present as
2576 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2577 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2578 		 * one and attach it in the front.
2579 		 */
2580 		if (ii != NULL) {
2581 			/*
2582 			 * ip_fanout_proto_again converts the ICMP errors
2583 			 * that come back from AH/ESP to M_DATA so that
2584 			 * if it is non-AH/ESP and we do a pullupmsg in
2585 			 * this function, it would work. Convert it back
2586 			 * to M_CTL before we send up as this is a ICMP
2587 			 * error. This could have been generated locally or
2588 			 * by some router. Validate the inner IPSEC
2589 			 * headers.
2590 			 *
2591 			 * NOTE : ill_index is used by ip_fanout_proto_again
2592 			 * to locate the ill.
2593 			 */
2594 			ASSERT(ill != NULL);
2595 			ii->ipsec_in_ill_index =
2596 			    ill->ill_phyint->phyint_ifindex;
2597 			ii->ipsec_in_rill_index =
2598 			    recv_ill->ill_phyint->phyint_ifindex;
2599 			DB_TYPE(first_mp->b_cont) = M_CTL;
2600 		} else {
2601 			/*
2602 			 * IPSEC_IN is not present. We attach a ipsec_in
2603 			 * message and send up to IPSEC for validating
2604 			 * and removing the IPSEC headers. Clear
2605 			 * ipsec_in_secure so that when we return
2606 			 * from IPSEC, we don't mistakenly think that this
2607 			 * is a secure packet came from the network.
2608 			 *
2609 			 * NOTE : ill_index is used by ip_fanout_proto_again
2610 			 * to locate the ill.
2611 			 */
2612 			ASSERT(first_mp == mp);
2613 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2614 			if (first_mp == NULL) {
2615 				freemsg(mp);
2616 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2617 				return;
2618 			}
2619 			ii = (ipsec_in_t *)first_mp->b_rptr;
2620 
2621 			/* This is not a secure packet */
2622 			ii->ipsec_in_secure = B_FALSE;
2623 			first_mp->b_cont = mp;
2624 			DB_TYPE(mp) = M_CTL;
2625 			ASSERT(ill != NULL);
2626 			ii->ipsec_in_ill_index =
2627 			    ill->ill_phyint->phyint_ifindex;
2628 			ii->ipsec_in_rill_index =
2629 			    recv_ill->ill_phyint->phyint_ifindex;
2630 		}
2631 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2632 
2633 		if (!ipsec_loaded(ipss)) {
2634 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2635 			return;
2636 		}
2637 
2638 		if (ipha->ipha_protocol == IPPROTO_ESP)
2639 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2640 		else
2641 			ipsec_rc = ipsecah_icmp_error(first_mp);
2642 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2643 			return;
2644 
2645 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2646 		return;
2647 	}
2648 	default:
2649 		/*
2650 		 * The ripha header is only used for the lookup and we
2651 		 * only set the src and dst addresses and protocol.
2652 		 */
2653 		ripha.ipha_src = ipha->ipha_dst;
2654 		ripha.ipha_dst = ipha->ipha_src;
2655 		ripha.ipha_protocol = ipha->ipha_protocol;
2656 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2657 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2658 		    ntohl(ipha->ipha_dst),
2659 		    icmph->icmph_type, icmph->icmph_code));
2660 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2661 			ipha_t *in_ipha;
2662 
2663 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2664 			    mp->b_wptr) {
2665 				if (!pullupmsg(mp, (uchar_t *)ipha +
2666 				    hdr_length + sizeof (ipha_t) -
2667 				    mp->b_rptr)) {
2668 					goto discard_pkt;
2669 				}
2670 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2671 				ipha = (ipha_t *)&icmph[1];
2672 			}
2673 			/*
2674 			 * Caller has verified that length has to be
2675 			 * at least the size of IP header.
2676 			 */
2677 			ASSERT(hdr_length >= sizeof (ipha_t));
2678 			/*
2679 			 * Check the sanity of the inner IP header like
2680 			 * we did for the outer header.
2681 			 */
2682 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2683 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2684 				goto discard_pkt;
2685 			}
2686 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2687 				goto discard_pkt;
2688 			}
2689 			/* Check for Self-encapsulated tunnels */
2690 			if (in_ipha->ipha_src == ipha->ipha_src &&
2691 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2692 
2693 				mp = icmp_inbound_self_encap_error(mp,
2694 				    iph_hdr_length, hdr_length);
2695 				if (mp == NULL)
2696 					goto discard_pkt;
2697 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2698 				ipha = (ipha_t *)&icmph[1];
2699 				hdr_length = IPH_HDR_LENGTH(ipha);
2700 				/*
2701 				 * The packet in error is self-encapsualted.
2702 				 * And we are finding it further encapsulated
2703 				 * which we could not have possibly generated.
2704 				 */
2705 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2706 					goto discard_pkt;
2707 				}
2708 				icmp_inbound_error_fanout(q, ill, first_mp,
2709 				    icmph, ipha, iph_hdr_length, hdr_length,
2710 				    mctl_present, ip_policy, recv_ill, zoneid);
2711 				return;
2712 			}
2713 		}
2714 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2715 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2716 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2717 		    ii != NULL &&
2718 		    ii->ipsec_in_loopback &&
2719 		    ii->ipsec_in_secure) {
2720 			/*
2721 			 * For IP tunnels that get a looped-back
2722 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2723 			 * reported new MTU to take into account the IPsec
2724 			 * headers protecting this configured tunnel.
2725 			 *
2726 			 * This allows the tunnel module (tun.c) to blindly
2727 			 * accept the MTU reported in an ICMP "too big"
2728 			 * message.
2729 			 *
2730 			 * Non-looped back ICMP messages will just be
2731 			 * handled by the security protocols (if needed),
2732 			 * and the first subsequent packet will hit this
2733 			 * path.
2734 			 */
2735 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2736 			    ipsec_in_extra_length(first_mp));
2737 		}
2738 		/* Have to change db_type after any pullupmsg */
2739 		DB_TYPE(mp) = M_CTL;
2740 
2741 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2742 		    ip_policy, recv_ill, zoneid);
2743 		return;
2744 	}
2745 	/* NOTREACHED */
2746 discard_pkt:
2747 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2748 drop_pkt:;
2749 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2750 	freemsg(first_mp);
2751 }
2752 
2753 /*
2754  * Common IP options parser.
2755  *
2756  * Setup routine: fill in *optp with options-parsing state, then
2757  * tail-call ipoptp_next to return the first option.
2758  */
2759 uint8_t
2760 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2761 {
2762 	uint32_t totallen; /* total length of all options */
2763 
2764 	totallen = ipha->ipha_version_and_hdr_length -
2765 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2766 	totallen <<= 2;
2767 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2768 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2769 	optp->ipoptp_flags = 0;
2770 	return (ipoptp_next(optp));
2771 }
2772 
2773 /*
2774  * Common IP options parser: extract next option.
2775  */
2776 uint8_t
2777 ipoptp_next(ipoptp_t *optp)
2778 {
2779 	uint8_t *end = optp->ipoptp_end;
2780 	uint8_t *cur = optp->ipoptp_next;
2781 	uint8_t opt, len, pointer;
2782 
2783 	/*
2784 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2785 	 * has been corrupted.
2786 	 */
2787 	ASSERT(cur <= end);
2788 
2789 	if (cur == end)
2790 		return (IPOPT_EOL);
2791 
2792 	opt = cur[IPOPT_OPTVAL];
2793 
2794 	/*
2795 	 * Skip any NOP options.
2796 	 */
2797 	while (opt == IPOPT_NOP) {
2798 		cur++;
2799 		if (cur == end)
2800 			return (IPOPT_EOL);
2801 		opt = cur[IPOPT_OPTVAL];
2802 	}
2803 
2804 	if (opt == IPOPT_EOL)
2805 		return (IPOPT_EOL);
2806 
2807 	/*
2808 	 * Option requiring a length.
2809 	 */
2810 	if ((cur + 1) >= end) {
2811 		optp->ipoptp_flags |= IPOPTP_ERROR;
2812 		return (IPOPT_EOL);
2813 	}
2814 	len = cur[IPOPT_OLEN];
2815 	if (len < 2) {
2816 		optp->ipoptp_flags |= IPOPTP_ERROR;
2817 		return (IPOPT_EOL);
2818 	}
2819 	optp->ipoptp_cur = cur;
2820 	optp->ipoptp_len = len;
2821 	optp->ipoptp_next = cur + len;
2822 	if (cur + len > end) {
2823 		optp->ipoptp_flags |= IPOPTP_ERROR;
2824 		return (IPOPT_EOL);
2825 	}
2826 
2827 	/*
2828 	 * For the options which require a pointer field, make sure
2829 	 * its there, and make sure it points to either something
2830 	 * inside this option, or the end of the option.
2831 	 */
2832 	switch (opt) {
2833 	case IPOPT_RR:
2834 	case IPOPT_TS:
2835 	case IPOPT_LSRR:
2836 	case IPOPT_SSRR:
2837 		if (len <= IPOPT_OFFSET) {
2838 			optp->ipoptp_flags |= IPOPTP_ERROR;
2839 			return (opt);
2840 		}
2841 		pointer = cur[IPOPT_OFFSET];
2842 		if (pointer - 1 > len) {
2843 			optp->ipoptp_flags |= IPOPTP_ERROR;
2844 			return (opt);
2845 		}
2846 		break;
2847 	}
2848 
2849 	/*
2850 	 * Sanity check the pointer field based on the type of the
2851 	 * option.
2852 	 */
2853 	switch (opt) {
2854 	case IPOPT_RR:
2855 	case IPOPT_SSRR:
2856 	case IPOPT_LSRR:
2857 		if (pointer < IPOPT_MINOFF_SR)
2858 			optp->ipoptp_flags |= IPOPTP_ERROR;
2859 		break;
2860 	case IPOPT_TS:
2861 		if (pointer < IPOPT_MINOFF_IT)
2862 			optp->ipoptp_flags |= IPOPTP_ERROR;
2863 		/*
2864 		 * Note that the Internet Timestamp option also
2865 		 * contains two four bit fields (the Overflow field,
2866 		 * and the Flag field), which follow the pointer
2867 		 * field.  We don't need to check that these fields
2868 		 * fall within the length of the option because this
2869 		 * was implicitely done above.  We've checked that the
2870 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2871 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2872 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2873 		 */
2874 		ASSERT(len > IPOPT_POS_OV_FLG);
2875 		break;
2876 	}
2877 
2878 	return (opt);
2879 }
2880 
2881 /*
2882  * Use the outgoing IP header to create an IP_OPTIONS option the way
2883  * it was passed down from the application.
2884  */
2885 int
2886 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2887 {
2888 	ipoptp_t	opts;
2889 	const uchar_t	*opt;
2890 	uint8_t		optval;
2891 	uint8_t		optlen;
2892 	uint32_t	len = 0;
2893 	uchar_t	*buf1 = buf;
2894 
2895 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2896 	len += IP_ADDR_LEN;
2897 	bzero(buf1, IP_ADDR_LEN);
2898 
2899 	/*
2900 	 * OK to cast away const here, as we don't store through the returned
2901 	 * opts.ipoptp_cur pointer.
2902 	 */
2903 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2904 	    optval != IPOPT_EOL;
2905 	    optval = ipoptp_next(&opts)) {
2906 		int	off;
2907 
2908 		opt = opts.ipoptp_cur;
2909 		optlen = opts.ipoptp_len;
2910 		switch (optval) {
2911 		case IPOPT_SSRR:
2912 		case IPOPT_LSRR:
2913 
2914 			/*
2915 			 * Insert ipha_dst as the first entry in the source
2916 			 * route and move down the entries on step.
2917 			 * The last entry gets placed at buf1.
2918 			 */
2919 			buf[IPOPT_OPTVAL] = optval;
2920 			buf[IPOPT_OLEN] = optlen;
2921 			buf[IPOPT_OFFSET] = optlen;
2922 
2923 			off = optlen - IP_ADDR_LEN;
2924 			if (off < 0) {
2925 				/* No entries in source route */
2926 				break;
2927 			}
2928 			/* Last entry in source route */
2929 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2930 			off -= IP_ADDR_LEN;
2931 
2932 			while (off > 0) {
2933 				bcopy(opt + off,
2934 				    buf + off + IP_ADDR_LEN,
2935 				    IP_ADDR_LEN);
2936 				off -= IP_ADDR_LEN;
2937 			}
2938 			/* ipha_dst into first slot */
2939 			bcopy(&ipha->ipha_dst,
2940 			    buf + off + IP_ADDR_LEN,
2941 			    IP_ADDR_LEN);
2942 			buf += optlen;
2943 			len += optlen;
2944 			break;
2945 
2946 		case IPOPT_COMSEC:
2947 		case IPOPT_SECURITY:
2948 			/* if passing up a label is not ok, then remove */
2949 			if (is_system_labeled())
2950 				break;
2951 			/* FALLTHROUGH */
2952 		default:
2953 			bcopy(opt, buf, optlen);
2954 			buf += optlen;
2955 			len += optlen;
2956 			break;
2957 		}
2958 	}
2959 done:
2960 	/* Pad the resulting options */
2961 	while (len & 0x3) {
2962 		*buf++ = IPOPT_EOL;
2963 		len++;
2964 	}
2965 	return (len);
2966 }
2967 
2968 /*
2969  * Update any record route or timestamp options to include this host.
2970  * Reverse any source route option.
2971  * This routine assumes that the options are well formed i.e. that they
2972  * have already been checked.
2973  */
2974 static void
2975 icmp_options_update(ipha_t *ipha)
2976 {
2977 	ipoptp_t	opts;
2978 	uchar_t		*opt;
2979 	uint8_t		optval;
2980 	ipaddr_t	src;		/* Our local address */
2981 	ipaddr_t	dst;
2982 
2983 	ip2dbg(("icmp_options_update\n"));
2984 	src = ipha->ipha_src;
2985 	dst = ipha->ipha_dst;
2986 
2987 	for (optval = ipoptp_first(&opts, ipha);
2988 	    optval != IPOPT_EOL;
2989 	    optval = ipoptp_next(&opts)) {
2990 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2991 		opt = opts.ipoptp_cur;
2992 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2993 		    optval, opts.ipoptp_len));
2994 		switch (optval) {
2995 			int off1, off2;
2996 		case IPOPT_SSRR:
2997 		case IPOPT_LSRR:
2998 			/*
2999 			 * Reverse the source route.  The first entry
3000 			 * should be the next to last one in the current
3001 			 * source route (the last entry is our address).
3002 			 * The last entry should be the final destination.
3003 			 */
3004 			off1 = IPOPT_MINOFF_SR - 1;
3005 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3006 			if (off2 < 0) {
3007 				/* No entries in source route */
3008 				ip1dbg((
3009 				    "icmp_options_update: bad src route\n"));
3010 				break;
3011 			}
3012 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3013 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3014 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3015 			off2 -= IP_ADDR_LEN;
3016 
3017 			while (off1 < off2) {
3018 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3019 				bcopy((char *)opt + off2, (char *)opt + off1,
3020 				    IP_ADDR_LEN);
3021 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3022 				off1 += IP_ADDR_LEN;
3023 				off2 -= IP_ADDR_LEN;
3024 			}
3025 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3026 			break;
3027 		}
3028 	}
3029 }
3030 
3031 /*
3032  * Process received ICMP Redirect messages.
3033  */
3034 static void
3035 icmp_redirect(ill_t *ill, mblk_t *mp)
3036 {
3037 	ipha_t	*ipha;
3038 	int	iph_hdr_length;
3039 	icmph_t	*icmph;
3040 	ipha_t	*ipha_err;
3041 	ire_t	*ire;
3042 	ire_t	*prev_ire;
3043 	ire_t	*save_ire;
3044 	ipaddr_t  src, dst, gateway;
3045 	iulp_t	ulp_info = { 0 };
3046 	int	error;
3047 	ip_stack_t *ipst;
3048 
3049 	ASSERT(ill != NULL);
3050 	ipst = ill->ill_ipst;
3051 
3052 	ipha = (ipha_t *)mp->b_rptr;
3053 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3054 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3055 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3056 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3057 		freemsg(mp);
3058 		return;
3059 	}
3060 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3061 	ipha_err = (ipha_t *)&icmph[1];
3062 	src = ipha->ipha_src;
3063 	dst = ipha_err->ipha_dst;
3064 	gateway = icmph->icmph_rd_gateway;
3065 	/* Make sure the new gateway is reachable somehow. */
3066 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3067 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3068 	/*
3069 	 * Make sure we had a route for the dest in question and that
3070 	 * that route was pointing to the old gateway (the source of the
3071 	 * redirect packet.)
3072 	 */
3073 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3074 	    NULL, MATCH_IRE_GW, ipst);
3075 	/*
3076 	 * Check that
3077 	 *	the redirect was not from ourselves
3078 	 *	the new gateway and the old gateway are directly reachable
3079 	 */
3080 	if (!prev_ire ||
3081 	    !ire ||
3082 	    ire->ire_type == IRE_LOCAL) {
3083 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3084 		freemsg(mp);
3085 		if (ire != NULL)
3086 			ire_refrele(ire);
3087 		if (prev_ire != NULL)
3088 			ire_refrele(prev_ire);
3089 		return;
3090 	}
3091 
3092 	/*
3093 	 * Should we use the old ULP info to create the new gateway?  From
3094 	 * a user's perspective, we should inherit the info so that it
3095 	 * is a "smooth" transition.  If we do not do that, then new
3096 	 * connections going thru the new gateway will have no route metrics,
3097 	 * which is counter-intuitive to user.  From a network point of
3098 	 * view, this may or may not make sense even though the new gateway
3099 	 * is still directly connected to us so the route metrics should not
3100 	 * change much.
3101 	 *
3102 	 * But if the old ire_uinfo is not initialized, we do another
3103 	 * recursive lookup on the dest using the new gateway.  There may
3104 	 * be a route to that.  If so, use it to initialize the redirect
3105 	 * route.
3106 	 */
3107 	if (prev_ire->ire_uinfo.iulp_set) {
3108 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3109 	} else {
3110 		ire_t *tmp_ire;
3111 		ire_t *sire;
3112 
3113 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3114 		    ALL_ZONES, 0, NULL,
3115 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3116 		    ipst);
3117 		if (sire != NULL) {
3118 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3119 			/*
3120 			 * If sire != NULL, ire_ftable_lookup() should not
3121 			 * return a NULL value.
3122 			 */
3123 			ASSERT(tmp_ire != NULL);
3124 			ire_refrele(tmp_ire);
3125 			ire_refrele(sire);
3126 		} else if (tmp_ire != NULL) {
3127 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3128 			    sizeof (iulp_t));
3129 			ire_refrele(tmp_ire);
3130 		}
3131 	}
3132 	if (prev_ire->ire_type == IRE_CACHE)
3133 		ire_delete(prev_ire);
3134 	ire_refrele(prev_ire);
3135 	/*
3136 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3137 	 * require TOS routing
3138 	 */
3139 	switch (icmph->icmph_code) {
3140 	case 0:
3141 	case 1:
3142 		/* TODO: TOS specificity for cases 2 and 3 */
3143 	case 2:
3144 	case 3:
3145 		break;
3146 	default:
3147 		freemsg(mp);
3148 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3149 		ire_refrele(ire);
3150 		return;
3151 	}
3152 	/*
3153 	 * Create a Route Association.  This will allow us to remember that
3154 	 * someone we believe told us to use the particular gateway.
3155 	 */
3156 	save_ire = ire;
3157 	ire = ire_create(
3158 		(uchar_t *)&dst,			/* dest addr */
3159 		(uchar_t *)&ip_g_all_ones,		/* mask */
3160 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3161 		(uchar_t *)&gateway,			/* gateway addr */
3162 		NULL,					/* no in_srcaddr */
3163 		&save_ire->ire_max_frag,		/* max frag */
3164 		NULL,					/* Fast Path header */
3165 		NULL,					/* no rfq */
3166 		NULL,					/* no stq */
3167 		IRE_HOST,
3168 		NULL,
3169 		NULL,
3170 		NULL,
3171 		0,
3172 		0,
3173 		0,
3174 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3175 		&ulp_info,
3176 		NULL,
3177 		NULL,
3178 		ipst);
3179 
3180 	if (ire == NULL) {
3181 		freemsg(mp);
3182 		ire_refrele(save_ire);
3183 		return;
3184 	}
3185 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3186 	ire_refrele(save_ire);
3187 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3188 
3189 	if (error == 0) {
3190 		ire_refrele(ire);		/* Held in ire_add_v4 */
3191 		/* tell routing sockets that we received a redirect */
3192 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3193 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3194 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3195 	}
3196 
3197 	/*
3198 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3199 	 * This together with the added IRE has the effect of
3200 	 * modifying an existing redirect.
3201 	 */
3202 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3203 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3204 	if (prev_ire != NULL) {
3205 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3206 			ire_delete(prev_ire);
3207 		ire_refrele(prev_ire);
3208 	}
3209 
3210 	freemsg(mp);
3211 }
3212 
3213 /*
3214  * Generate an ICMP parameter problem message.
3215  */
3216 static void
3217 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3218 	ip_stack_t *ipst)
3219 {
3220 	icmph_t	icmph;
3221 	boolean_t mctl_present;
3222 	mblk_t *first_mp;
3223 
3224 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3225 
3226 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3227 		if (mctl_present)
3228 			freeb(first_mp);
3229 		return;
3230 	}
3231 
3232 	bzero(&icmph, sizeof (icmph_t));
3233 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3234 	icmph.icmph_pp_ptr = ptr;
3235 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3236 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3237 	    ipst);
3238 }
3239 
3240 /*
3241  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3242  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3243  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3244  * an icmp error packet can be sent.
3245  * Assigns an appropriate source address to the packet. If ipha_dst is
3246  * one of our addresses use it for source. Otherwise pick a source based
3247  * on a route lookup back to ipha_src.
3248  * Note that ipha_src must be set here since the
3249  * packet is likely to arrive on an ill queue in ip_wput() which will
3250  * not set a source address.
3251  */
3252 static void
3253 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3254     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3255 {
3256 	ipaddr_t dst;
3257 	icmph_t	*icmph;
3258 	ipha_t	*ipha;
3259 	uint_t	len_needed;
3260 	size_t	msg_len;
3261 	mblk_t	*mp1;
3262 	ipaddr_t src;
3263 	ire_t	*ire;
3264 	mblk_t *ipsec_mp;
3265 	ipsec_out_t	*io = NULL;
3266 	boolean_t xmit_if_on = B_FALSE;
3267 
3268 	if (mctl_present) {
3269 		/*
3270 		 * If it is :
3271 		 *
3272 		 * 1) a IPSEC_OUT, then this is caused by outbound
3273 		 *    datagram originating on this host. IPSEC processing
3274 		 *    may or may not have been done. Refer to comments above
3275 		 *    icmp_inbound_error_fanout for details.
3276 		 *
3277 		 * 2) a IPSEC_IN if we are generating a icmp_message
3278 		 *    for an incoming datagram destined for us i.e called
3279 		 *    from ip_fanout_send_icmp.
3280 		 */
3281 		ipsec_info_t *in;
3282 		ipsec_mp = mp;
3283 		mp = ipsec_mp->b_cont;
3284 
3285 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3286 		ipha = (ipha_t *)mp->b_rptr;
3287 
3288 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3289 		    in->ipsec_info_type == IPSEC_IN);
3290 
3291 		if (in->ipsec_info_type == IPSEC_IN) {
3292 			/*
3293 			 * Convert the IPSEC_IN to IPSEC_OUT.
3294 			 */
3295 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3296 				BUMP_MIB(&ipst->ips_ip_mib,
3297 				    ipIfStatsOutDiscards);
3298 				return;
3299 			}
3300 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3301 		} else {
3302 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3303 			io = (ipsec_out_t *)in;
3304 			if (io->ipsec_out_xmit_if)
3305 				xmit_if_on = B_TRUE;
3306 			/*
3307 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3308 			 * ire lookup.
3309 			 */
3310 			io->ipsec_out_proc_begin = B_FALSE;
3311 		}
3312 		ASSERT(zoneid == io->ipsec_out_zoneid);
3313 		ASSERT(zoneid != ALL_ZONES);
3314 	} else {
3315 		/*
3316 		 * This is in clear. The icmp message we are building
3317 		 * here should go out in clear.
3318 		 *
3319 		 * Pardon the convolution of it all, but it's easier to
3320 		 * allocate a "use cleartext" IPSEC_IN message and convert
3321 		 * it than it is to allocate a new one.
3322 		 */
3323 		ipsec_in_t *ii;
3324 		ASSERT(DB_TYPE(mp) == M_DATA);
3325 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3326 		if (ipsec_mp == NULL) {
3327 			freemsg(mp);
3328 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3329 			return;
3330 		}
3331 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3332 
3333 		/* This is not a secure packet */
3334 		ii->ipsec_in_secure = B_FALSE;
3335 		/*
3336 		 * For trusted extensions using a shared IP address we can
3337 		 * send using any zoneid.
3338 		 */
3339 		if (zoneid == ALL_ZONES)
3340 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3341 		else
3342 			ii->ipsec_in_zoneid = zoneid;
3343 		ipsec_mp->b_cont = mp;
3344 		ipha = (ipha_t *)mp->b_rptr;
3345 		/*
3346 		 * Convert the IPSEC_IN to IPSEC_OUT.
3347 		 */
3348 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3349 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3350 			return;
3351 		}
3352 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3353 	}
3354 
3355 	/* Remember our eventual destination */
3356 	dst = ipha->ipha_src;
3357 
3358 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3359 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3360 	if (ire != NULL &&
3361 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3362 		src = ipha->ipha_dst;
3363 	} else if (!xmit_if_on) {
3364 		if (ire != NULL)
3365 			ire_refrele(ire);
3366 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3367 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3368 		    ipst);
3369 		if (ire == NULL) {
3370 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3371 			freemsg(ipsec_mp);
3372 			return;
3373 		}
3374 		src = ire->ire_src_addr;
3375 	} else {
3376 		ipif_t	*ipif = NULL;
3377 		ill_t	*ill;
3378 		/*
3379 		 * This must be an ICMP error coming from
3380 		 * ip_mrtun_forward(). The src addr should
3381 		 * be equal to the IP-addr of the outgoing
3382 		 * interface.
3383 		 */
3384 		if (io == NULL) {
3385 			/* This is not a IPSEC_OUT type control msg */
3386 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3387 			freemsg(ipsec_mp);
3388 			return;
3389 		}
3390 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3391 		    NULL, NULL, NULL, NULL, ipst);
3392 		if (ill != NULL) {
3393 			ipif = ipif_get_next_ipif(NULL, ill);
3394 			ill_refrele(ill);
3395 		}
3396 		if (ipif == NULL) {
3397 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3398 			freemsg(ipsec_mp);
3399 			return;
3400 		}
3401 		src = ipif->ipif_src_addr;
3402 		ipif_refrele(ipif);
3403 	}
3404 
3405 	if (ire != NULL)
3406 		ire_refrele(ire);
3407 
3408 	/*
3409 	 * Check if we can send back more then 8 bytes in addition
3410 	 * to the IP header. We will include as much as 64 bytes.
3411 	 */
3412 	len_needed = IPH_HDR_LENGTH(ipha);
3413 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3414 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3415 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3416 	}
3417 	len_needed += ipst->ips_ip_icmp_return;
3418 	msg_len = msgdsize(mp);
3419 	if (msg_len > len_needed) {
3420 		(void) adjmsg(mp, len_needed - msg_len);
3421 		msg_len = len_needed;
3422 	}
3423 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3424 	if (mp1 == NULL) {
3425 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3426 		freemsg(ipsec_mp);
3427 		return;
3428 	}
3429 	/*
3430 	 * On an unlabeled system, dblks don't necessarily have creds.
3431 	 */
3432 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3433 	if (DB_CRED(mp) != NULL)
3434 		mblk_setcred(mp1, DB_CRED(mp));
3435 	mp1->b_cont = mp;
3436 	mp = mp1;
3437 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3438 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3439 	    io->ipsec_out_type == IPSEC_OUT);
3440 	ipsec_mp->b_cont = mp;
3441 
3442 	/*
3443 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3444 	 * node generates be accepted in peace by all on-host destinations.
3445 	 * If we do NOT assume that all on-host destinations trust
3446 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3447 	 * (Look for ipsec_out_icmp_loopback).
3448 	 */
3449 	io->ipsec_out_icmp_loopback = B_TRUE;
3450 
3451 	ipha = (ipha_t *)mp->b_rptr;
3452 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3453 	*ipha = icmp_ipha;
3454 	ipha->ipha_src = src;
3455 	ipha->ipha_dst = dst;
3456 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3457 	msg_len += sizeof (icmp_ipha) + len;
3458 	if (msg_len > IP_MAXPACKET) {
3459 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3460 		msg_len = IP_MAXPACKET;
3461 	}
3462 	ipha->ipha_length = htons((uint16_t)msg_len);
3463 	icmph = (icmph_t *)&ipha[1];
3464 	bcopy(stuff, icmph, len);
3465 	icmph->icmph_checksum = 0;
3466 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3467 	if (icmph->icmph_checksum == 0)
3468 		icmph->icmph_checksum = 0xFFFF;
3469 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3470 	put(q, ipsec_mp);
3471 }
3472 
3473 /*
3474  * Determine if an ICMP error packet can be sent given the rate limit.
3475  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3476  * in milliseconds) and a burst size. Burst size number of packets can
3477  * be sent arbitrarely closely spaced.
3478  * The state is tracked using two variables to implement an approximate
3479  * token bucket filter:
3480  *	icmp_pkt_err_last - lbolt value when the last burst started
3481  *	icmp_pkt_err_sent - number of packets sent in current burst
3482  */
3483 boolean_t
3484 icmp_err_rate_limit(ip_stack_t *ipst)
3485 {
3486 	clock_t now = TICK_TO_MSEC(lbolt);
3487 	uint_t refilled; /* Number of packets refilled in tbf since last */
3488 	/* Guard against changes by loading into local variable */
3489 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3490 
3491 	if (err_interval == 0)
3492 		return (B_FALSE);
3493 
3494 	if (ipst->ips_icmp_pkt_err_last > now) {
3495 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3496 		ipst->ips_icmp_pkt_err_last = 0;
3497 		ipst->ips_icmp_pkt_err_sent = 0;
3498 	}
3499 	/*
3500 	 * If we are in a burst update the token bucket filter.
3501 	 * Update the "last" time to be close to "now" but make sure
3502 	 * we don't loose precision.
3503 	 */
3504 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3505 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3506 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3507 			ipst->ips_icmp_pkt_err_sent = 0;
3508 		} else {
3509 			ipst->ips_icmp_pkt_err_sent -= refilled;
3510 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3511 		}
3512 	}
3513 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3514 		/* Start of new burst */
3515 		ipst->ips_icmp_pkt_err_last = now;
3516 	}
3517 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3518 		ipst->ips_icmp_pkt_err_sent++;
3519 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3520 			    ipst->ips_icmp_pkt_err_sent));
3521 		return (B_FALSE);
3522 	}
3523 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3524 	return (B_TRUE);
3525 }
3526 
3527 /*
3528  * Check if it is ok to send an IPv4 ICMP error packet in
3529  * response to the IPv4 packet in mp.
3530  * Free the message and return null if no
3531  * ICMP error packet should be sent.
3532  */
3533 static mblk_t *
3534 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3535 {
3536 	icmph_t	*icmph;
3537 	ipha_t	*ipha;
3538 	uint_t	len_needed;
3539 	ire_t	*src_ire;
3540 	ire_t	*dst_ire;
3541 
3542 	if (!mp)
3543 		return (NULL);
3544 	ipha = (ipha_t *)mp->b_rptr;
3545 	if (ip_csum_hdr(ipha)) {
3546 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3547 		freemsg(mp);
3548 		return (NULL);
3549 	}
3550 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3551 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3552 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3553 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3554 	if (src_ire != NULL || dst_ire != NULL ||
3555 	    CLASSD(ipha->ipha_dst) ||
3556 	    CLASSD(ipha->ipha_src) ||
3557 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3558 		/* Note: only errors to the fragment with offset 0 */
3559 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3560 		freemsg(mp);
3561 		if (src_ire != NULL)
3562 			ire_refrele(src_ire);
3563 		if (dst_ire != NULL)
3564 			ire_refrele(dst_ire);
3565 		return (NULL);
3566 	}
3567 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3568 		/*
3569 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3570 		 * errors in response to any ICMP errors.
3571 		 */
3572 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3573 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3574 			if (!pullupmsg(mp, len_needed)) {
3575 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3576 				freemsg(mp);
3577 				return (NULL);
3578 			}
3579 			ipha = (ipha_t *)mp->b_rptr;
3580 		}
3581 		icmph = (icmph_t *)
3582 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3583 		switch (icmph->icmph_type) {
3584 		case ICMP_DEST_UNREACHABLE:
3585 		case ICMP_SOURCE_QUENCH:
3586 		case ICMP_TIME_EXCEEDED:
3587 		case ICMP_PARAM_PROBLEM:
3588 		case ICMP_REDIRECT:
3589 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3590 			freemsg(mp);
3591 			return (NULL);
3592 		default:
3593 			break;
3594 		}
3595 	}
3596 	/*
3597 	 * If this is a labeled system, then check to see if we're allowed to
3598 	 * send a response to this particular sender.  If not, then just drop.
3599 	 */
3600 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3601 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3602 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3603 		freemsg(mp);
3604 		return (NULL);
3605 	}
3606 	if (icmp_err_rate_limit(ipst)) {
3607 		/*
3608 		 * Only send ICMP error packets every so often.
3609 		 * This should be done on a per port/source basis,
3610 		 * but for now this will suffice.
3611 		 */
3612 		freemsg(mp);
3613 		return (NULL);
3614 	}
3615 	return (mp);
3616 }
3617 
3618 /*
3619  * Generate an ICMP redirect message.
3620  */
3621 static void
3622 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3623 {
3624 	icmph_t	icmph;
3625 
3626 	/*
3627 	 * We are called from ip_rput where we could
3628 	 * not have attached an IPSEC_IN.
3629 	 */
3630 	ASSERT(mp->b_datap->db_type == M_DATA);
3631 
3632 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3633 		return;
3634 	}
3635 
3636 	bzero(&icmph, sizeof (icmph_t));
3637 	icmph.icmph_type = ICMP_REDIRECT;
3638 	icmph.icmph_code = 1;
3639 	icmph.icmph_rd_gateway = gateway;
3640 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3641 	/* Redirects sent by router, and router is global zone */
3642 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3643 }
3644 
3645 /*
3646  * Generate an ICMP time exceeded message.
3647  */
3648 void
3649 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3650     ip_stack_t *ipst)
3651 {
3652 	icmph_t	icmph;
3653 	boolean_t mctl_present;
3654 	mblk_t *first_mp;
3655 
3656 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3657 
3658 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3659 		if (mctl_present)
3660 			freeb(first_mp);
3661 		return;
3662 	}
3663 
3664 	bzero(&icmph, sizeof (icmph_t));
3665 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3666 	icmph.icmph_code = code;
3667 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3668 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3669 	    ipst);
3670 }
3671 
3672 /*
3673  * Generate an ICMP unreachable message.
3674  */
3675 void
3676 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3677     ip_stack_t *ipst)
3678 {
3679 	icmph_t	icmph;
3680 	mblk_t *first_mp;
3681 	boolean_t mctl_present;
3682 
3683 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3684 
3685 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3686 		if (mctl_present)
3687 			freeb(first_mp);
3688 		return;
3689 	}
3690 
3691 	bzero(&icmph, sizeof (icmph_t));
3692 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3693 	icmph.icmph_code = code;
3694 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3695 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3696 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3697 	    zoneid, ipst);
3698 }
3699 
3700 /*
3701  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3702  * duplicate.  As long as someone else holds the address, the interface will
3703  * stay down.  When that conflict goes away, the interface is brought back up.
3704  * This is done so that accidental shutdowns of addresses aren't made
3705  * permanent.  Your server will recover from a failure.
3706  *
3707  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3708  * user space process (dhcpagent).
3709  *
3710  * Recovery completes if ARP reports that the address is now ours (via
3711  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3712  *
3713  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3714  */
3715 static void
3716 ipif_dup_recovery(void *arg)
3717 {
3718 	ipif_t *ipif = arg;
3719 	ill_t *ill = ipif->ipif_ill;
3720 	mblk_t *arp_add_mp;
3721 	mblk_t *arp_del_mp;
3722 	area_t *area;
3723 	ip_stack_t *ipst = ill->ill_ipst;
3724 
3725 	ipif->ipif_recovery_id = 0;
3726 
3727 	/*
3728 	 * No lock needed for moving or condemned check, as this is just an
3729 	 * optimization.
3730 	 */
3731 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3732 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3733 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3734 		/* No reason to try to bring this address back. */
3735 		return;
3736 	}
3737 
3738 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3739 		goto alloc_fail;
3740 
3741 	if (ipif->ipif_arp_del_mp == NULL) {
3742 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3743 			goto alloc_fail;
3744 		ipif->ipif_arp_del_mp = arp_del_mp;
3745 	}
3746 
3747 	/* Setting the 'unverified' flag restarts DAD */
3748 	area = (area_t *)arp_add_mp->b_rptr;
3749 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3750 	    ACE_F_UNVERIFIED;
3751 	putnext(ill->ill_rq, arp_add_mp);
3752 	return;
3753 
3754 alloc_fail:
3755 	/*
3756 	 * On allocation failure, just restart the timer.  Note that the ipif
3757 	 * is down here, so no other thread could be trying to start a recovery
3758 	 * timer.  The ill_lock protects the condemned flag and the recovery
3759 	 * timer ID.
3760 	 */
3761 	freemsg(arp_add_mp);
3762 	mutex_enter(&ill->ill_lock);
3763 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3764 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3765 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3766 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3767 	}
3768 	mutex_exit(&ill->ill_lock);
3769 }
3770 
3771 /*
3772  * This is for exclusive changes due to ARP.  Either tear down an interface due
3773  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3774  */
3775 /* ARGSUSED */
3776 static void
3777 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3778 {
3779 	ill_t	*ill = rq->q_ptr;
3780 	arh_t *arh;
3781 	ipaddr_t src;
3782 	ipif_t	*ipif;
3783 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3784 	char hbuf[MAC_STR_LEN];
3785 	char sbuf[INET_ADDRSTRLEN];
3786 	const char *failtype;
3787 	boolean_t bring_up;
3788 	ip_stack_t *ipst = ill->ill_ipst;
3789 
3790 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3791 	case AR_CN_READY:
3792 		failtype = NULL;
3793 		bring_up = B_TRUE;
3794 		break;
3795 	case AR_CN_FAILED:
3796 		failtype = "in use";
3797 		bring_up = B_FALSE;
3798 		break;
3799 	default:
3800 		failtype = "claimed";
3801 		bring_up = B_FALSE;
3802 		break;
3803 	}
3804 
3805 	arh = (arh_t *)mp->b_cont->b_rptr;
3806 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3807 
3808 	/* Handle failures due to probes */
3809 	if (src == 0) {
3810 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3811 		    IP_ADDR_LEN);
3812 	}
3813 
3814 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3815 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3816 	    sizeof (hbuf));
3817 	(void) ip_dot_addr(src, sbuf);
3818 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3819 
3820 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3821 		    ipif->ipif_lcl_addr != src) {
3822 			continue;
3823 		}
3824 
3825 		/*
3826 		 * If we failed on a recovery probe, then restart the timer to
3827 		 * try again later.
3828 		 */
3829 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3830 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3831 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3832 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3833 		    ipst->ips_ip_dup_recovery > 0 &&
3834 		    ipif->ipif_recovery_id == 0) {
3835 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3836 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3837 			continue;
3838 		}
3839 
3840 		/*
3841 		 * If what we're trying to do has already been done, then do
3842 		 * nothing.
3843 		 */
3844 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3845 			continue;
3846 
3847 		if (ipif->ipif_id != 0) {
3848 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3849 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3850 			    ipif->ipif_id);
3851 		}
3852 		if (failtype == NULL) {
3853 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3854 			    ibuf);
3855 		} else {
3856 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3857 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3858 		}
3859 
3860 		if (bring_up) {
3861 			ASSERT(ill->ill_dl_up);
3862 			/*
3863 			 * Free up the ARP delete message so we can allocate
3864 			 * a fresh one through the normal path.
3865 			 */
3866 			freemsg(ipif->ipif_arp_del_mp);
3867 			ipif->ipif_arp_del_mp = NULL;
3868 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3869 			    EINPROGRESS) {
3870 				ipif->ipif_addr_ready = 1;
3871 				(void) ipif_up_done(ipif);
3872 			}
3873 			continue;
3874 		}
3875 
3876 		mutex_enter(&ill->ill_lock);
3877 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3878 		ipif->ipif_flags |= IPIF_DUPLICATE;
3879 		ill->ill_ipif_dup_count++;
3880 		mutex_exit(&ill->ill_lock);
3881 		/*
3882 		 * Already exclusive on the ill; no need to handle deferred
3883 		 * processing here.
3884 		 */
3885 		(void) ipif_down(ipif, NULL, NULL);
3886 		ipif_down_tail(ipif);
3887 		mutex_enter(&ill->ill_lock);
3888 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3889 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3890 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3891 		    ipst->ips_ip_dup_recovery > 0) {
3892 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3893 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3894 		}
3895 		mutex_exit(&ill->ill_lock);
3896 	}
3897 	freemsg(mp);
3898 }
3899 
3900 /* ARGSUSED */
3901 static void
3902 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3903 {
3904 	ill_t	*ill = rq->q_ptr;
3905 	arh_t *arh;
3906 	ipaddr_t src;
3907 	ipif_t	*ipif;
3908 
3909 	arh = (arh_t *)mp->b_cont->b_rptr;
3910 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3911 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3912 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3913 			(void) ipif_resolver_up(ipif, Res_act_defend);
3914 	}
3915 	freemsg(mp);
3916 }
3917 
3918 /*
3919  * News from ARP.  ARP sends notification of interesting events down
3920  * to its clients using M_CTL messages with the interesting ARP packet
3921  * attached via b_cont.
3922  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3923  * queue as opposed to ARP sending the message to all the clients, i.e. all
3924  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3925  * table if a cache IRE is found to delete all the entries for the address in
3926  * the packet.
3927  */
3928 static void
3929 ip_arp_news(queue_t *q, mblk_t *mp)
3930 {
3931 	arcn_t		*arcn;
3932 	arh_t		*arh;
3933 	ire_t		*ire = NULL;
3934 	char		hbuf[MAC_STR_LEN];
3935 	char		sbuf[INET_ADDRSTRLEN];
3936 	ipaddr_t	src;
3937 	in6_addr_t	v6src;
3938 	boolean_t	isv6 = B_FALSE;
3939 	ipif_t		*ipif;
3940 	ill_t		*ill;
3941 	ip_stack_t	*ipst;
3942 
3943 	if (CONN_Q(q)) {
3944 		conn_t *connp = Q_TO_CONN(q);
3945 
3946 		ipst = connp->conn_netstack->netstack_ip;
3947 	} else {
3948 		ill_t *ill = (ill_t *)q->q_ptr;
3949 
3950 		ipst = ill->ill_ipst;
3951 	}
3952 
3953 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3954 		if (q->q_next) {
3955 			putnext(q, mp);
3956 		} else
3957 			freemsg(mp);
3958 		return;
3959 	}
3960 	arh = (arh_t *)mp->b_cont->b_rptr;
3961 	/* Is it one we are interested in? */
3962 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3963 		isv6 = B_TRUE;
3964 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3965 		    IPV6_ADDR_LEN);
3966 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3967 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3968 		    IP_ADDR_LEN);
3969 	} else {
3970 		freemsg(mp);
3971 		return;
3972 	}
3973 
3974 	ill = q->q_ptr;
3975 
3976 	arcn = (arcn_t *)mp->b_rptr;
3977 	switch (arcn->arcn_code) {
3978 	case AR_CN_BOGON:
3979 		/*
3980 		 * Someone is sending ARP packets with a source protocol
3981 		 * address that we have published and for which we believe our
3982 		 * entry is authoritative and (when ill_arp_extend is set)
3983 		 * verified to be unique on the network.
3984 		 *
3985 		 * The ARP module internally handles the cases where the sender
3986 		 * is just probing (for DAD) and where the hardware address of
3987 		 * a non-authoritative entry has changed.  Thus, these are the
3988 		 * real conflicts, and we have to do resolution.
3989 		 *
3990 		 * We back away quickly from the address if it's from DHCP or
3991 		 * otherwise temporary and hasn't been used recently (or at
3992 		 * all).  We'd like to include "deprecated" addresses here as
3993 		 * well (as there's no real reason to defend something we're
3994 		 * discarding), but IPMP "reuses" this flag to mean something
3995 		 * other than the standard meaning.
3996 		 *
3997 		 * If the ARP module above is not extended (meaning that it
3998 		 * doesn't know how to defend the address), then we just log
3999 		 * the problem as we always did and continue on.  It's not
4000 		 * right, but there's little else we can do, and those old ATM
4001 		 * users are going away anyway.
4002 		 */
4003 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4004 		    hbuf, sizeof (hbuf));
4005 		(void) ip_dot_addr(src, sbuf);
4006 		if (isv6) {
4007 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4008 			    ipst);
4009 		} else {
4010 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4011 		}
4012 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4013 			uint32_t now;
4014 			uint32_t maxage;
4015 			clock_t lused;
4016 			uint_t maxdefense;
4017 			uint_t defs;
4018 
4019 			/*
4020 			 * First, figure out if this address hasn't been used
4021 			 * in a while.  If it hasn't, then it's a better
4022 			 * candidate for abandoning.
4023 			 */
4024 			ipif = ire->ire_ipif;
4025 			ASSERT(ipif != NULL);
4026 			now = gethrestime_sec();
4027 			maxage = now - ire->ire_create_time;
4028 			if (maxage > ipst->ips_ip_max_temp_idle)
4029 				maxage = ipst->ips_ip_max_temp_idle;
4030 			lused = drv_hztousec(ddi_get_lbolt() -
4031 			    ire->ire_last_used_time) / MICROSEC + 1;
4032 			if (lused >= maxage && (ipif->ipif_flags &
4033 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4034 				maxdefense = ipst->ips_ip_max_temp_defend;
4035 			else
4036 				maxdefense = ipst->ips_ip_max_defend;
4037 
4038 			/*
4039 			 * Now figure out how many times we've defended
4040 			 * ourselves.  Ignore defenses that happened long in
4041 			 * the past.
4042 			 */
4043 			mutex_enter(&ire->ire_lock);
4044 			if ((defs = ire->ire_defense_count) > 0 &&
4045 			    now - ire->ire_defense_time >
4046 			    ipst->ips_ip_defend_interval) {
4047 				ire->ire_defense_count = defs = 0;
4048 			}
4049 			ire->ire_defense_count++;
4050 			ire->ire_defense_time = now;
4051 			mutex_exit(&ire->ire_lock);
4052 			ill_refhold(ill);
4053 			ire_refrele(ire);
4054 
4055 			/*
4056 			 * If we've defended ourselves too many times already,
4057 			 * then give up and tear down the interface(s) using
4058 			 * this address.  Otherwise, defend by sending out a
4059 			 * gratuitous ARP.
4060 			 */
4061 			if (defs >= maxdefense && ill->ill_arp_extend) {
4062 				(void) qwriter_ip(NULL, ill, q, mp,
4063 				    ip_arp_excl, CUR_OP, B_FALSE);
4064 			} else {
4065 				cmn_err(CE_WARN,
4066 				    "node %s is using our IP address %s on %s",
4067 				    hbuf, sbuf, ill->ill_name);
4068 				/*
4069 				 * If this is an old (ATM) ARP module, then
4070 				 * don't try to defend the address.  Remain
4071 				 * compatible with the old behavior.  Defend
4072 				 * only with new ARP.
4073 				 */
4074 				if (ill->ill_arp_extend) {
4075 					(void) qwriter_ip(NULL, ill, q, mp,
4076 					    ip_arp_defend, CUR_OP, B_FALSE);
4077 				} else {
4078 					ill_refrele(ill);
4079 				}
4080 			}
4081 			return;
4082 		}
4083 		cmn_err(CE_WARN,
4084 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4085 		    hbuf, sbuf, ill->ill_name);
4086 		if (ire != NULL)
4087 			ire_refrele(ire);
4088 		break;
4089 	case AR_CN_ANNOUNCE:
4090 		if (isv6) {
4091 			/*
4092 			 * For XRESOLV interfaces.
4093 			 * Delete the IRE cache entry and NCE for this
4094 			 * v6 address
4095 			 */
4096 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4097 			/*
4098 			 * If v6src is a non-zero, it's a router address
4099 			 * as below. Do the same sort of thing to clean
4100 			 * out off-net IRE_CACHE entries that go through
4101 			 * the router.
4102 			 */
4103 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4104 				ire_walk_v6(ire_delete_cache_gw_v6,
4105 				    (char *)&v6src, ALL_ZONES, ipst);
4106 			}
4107 		} else {
4108 			nce_hw_map_t hwm;
4109 
4110 			/*
4111 			 * ARP gives us a copy of any packet where it thinks
4112 			 * the address has changed, so that we can update our
4113 			 * caches.  We're responsible for caching known answers
4114 			 * in the current design.  We check whether the
4115 			 * hardware address really has changed in all of our
4116 			 * entries that have cached this mapping, and if so, we
4117 			 * blow them away.  This way we will immediately pick
4118 			 * up the rare case of a host changing hardware
4119 			 * address.
4120 			 */
4121 			if (src == 0)
4122 				break;
4123 			hwm.hwm_addr = src;
4124 			hwm.hwm_hwlen = arh->arh_hlen;
4125 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4126 			ndp_walk_common(ipst->ips_ndp4, NULL,
4127 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4128 		}
4129 		break;
4130 	case AR_CN_READY:
4131 		/* No external v6 resolver has a contract to use this */
4132 		if (isv6)
4133 			break;
4134 		/* If the link is down, we'll retry this later */
4135 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4136 			break;
4137 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4138 		    NULL, NULL, ipst);
4139 		if (ipif != NULL) {
4140 			/*
4141 			 * If this is a duplicate recovery, then we now need to
4142 			 * go exclusive to bring this thing back up.
4143 			 */
4144 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4145 			    IPIF_DUPLICATE) {
4146 				ipif_refrele(ipif);
4147 				ill_refhold(ill);
4148 				(void) qwriter_ip(NULL, ill, q, mp,
4149 				    ip_arp_excl, CUR_OP, B_FALSE);
4150 				return;
4151 			}
4152 			/*
4153 			 * If this is the first notice that this address is
4154 			 * ready, then let the user know now.
4155 			 */
4156 			if ((ipif->ipif_flags & IPIF_UP) &&
4157 			    !ipif->ipif_addr_ready) {
4158 				ipif_mask_reply(ipif);
4159 				ip_rts_ifmsg(ipif);
4160 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4161 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4162 			}
4163 			ipif->ipif_addr_ready = 1;
4164 			ipif_refrele(ipif);
4165 		}
4166 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4167 		if (ire != NULL) {
4168 			ire->ire_defense_count = 0;
4169 			ire_refrele(ire);
4170 		}
4171 		break;
4172 	case AR_CN_FAILED:
4173 		/* No external v6 resolver has a contract to use this */
4174 		if (isv6)
4175 			break;
4176 		ill_refhold(ill);
4177 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4178 		    B_FALSE);
4179 		return;
4180 	}
4181 	freemsg(mp);
4182 }
4183 
4184 /*
4185  * Create a mblk suitable for carrying the interface index and/or source link
4186  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4187  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4188  * application.
4189  */
4190 mblk_t *
4191 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4192     ip_stack_t *ipst)
4193 {
4194 	mblk_t		*mp;
4195 	ip_pktinfo_t	*pinfo;
4196 	ipha_t *ipha;
4197 	struct ether_header *pether;
4198 
4199 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4200 	if (mp == NULL) {
4201 		ip1dbg(("ip_add_info: allocation failure.\n"));
4202 		return (data_mp);
4203 	}
4204 
4205 	ipha	= (ipha_t *)data_mp->b_rptr;
4206 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4207 	bzero(pinfo, sizeof (ip_pktinfo_t));
4208 	pinfo->ip_pkt_flags = (uchar_t)flags;
4209 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4210 
4211 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4212 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4213 	if (flags & IPF_RECVADDR) {
4214 		ipif_t	*ipif;
4215 		ire_t	*ire;
4216 
4217 		/*
4218 		 * Only valid for V4
4219 		 */
4220 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4221 		    (IPV4_VERSION << 4));
4222 
4223 		ipif = ipif_get_next_ipif(NULL, ill);
4224 		if (ipif != NULL) {
4225 			/*
4226 			 * Since a decision has already been made to deliver the
4227 			 * packet, there is no need to test for SECATTR and
4228 			 * ZONEONLY.
4229 			 */
4230 			ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0, ipif,
4231 			    zoneid, NULL, MATCH_IRE_ILL_GROUP, ipst);
4232 			if (ire == NULL) {
4233 				/*
4234 				 * packet must have come on a different
4235 				 * interface.
4236 				 * Since a decision has already been made to
4237 				 * deliver the packet, there is no need to test
4238 				 * for SECATTR and ZONEONLY.
4239 				 */
4240 				ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0,
4241 				    ipif, zoneid, NULL, NULL, ipst);
4242 			}
4243 
4244 			if (ire == NULL) {
4245 				/*
4246 				 * This is either a multicast packet or
4247 				 * the address has been removed since
4248 				 * the packet was received.
4249 				 * Return INADDR_ANY so that normal source
4250 				 * selection occurs for the response.
4251 				 */
4252 
4253 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4254 			} else {
4255 				ASSERT(ire->ire_type != IRE_CACHE);
4256 				pinfo->ip_pkt_match_addr.s_addr =
4257 				    ire->ire_src_addr;
4258 				ire_refrele(ire);
4259 			}
4260 			ipif_refrele(ipif);
4261 		} else {
4262 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4263 		}
4264 	}
4265 
4266 	pether = (struct ether_header *)((char *)ipha
4267 	    - sizeof (struct ether_header));
4268 	/*
4269 	 * Make sure the interface is an ethernet type, since this option
4270 	 * is currently supported only on this type of interface. Also make
4271 	 * sure we are pointing correctly above db_base.
4272 	 */
4273 
4274 	if ((flags & IPF_RECVSLLA) &&
4275 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4276 	    (ill->ill_type == IFT_ETHER) &&
4277 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4278 
4279 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4280 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4281 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4282 	} else {
4283 		/*
4284 		 * Clear the bit. Indicate to upper layer that IP is not
4285 		 * sending this ancillary info.
4286 		 */
4287 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4288 	}
4289 
4290 	mp->b_datap->db_type = M_CTL;
4291 	mp->b_wptr += sizeof (ip_pktinfo_t);
4292 	mp->b_cont = data_mp;
4293 
4294 	return (mp);
4295 }
4296 
4297 /*
4298  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4299  * part of the bind request.
4300  */
4301 
4302 boolean_t
4303 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4304 {
4305 	ipsec_in_t *ii;
4306 
4307 	ASSERT(policy_mp != NULL);
4308 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4309 
4310 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4311 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4312 
4313 	connp->conn_policy = ii->ipsec_in_policy;
4314 	ii->ipsec_in_policy = NULL;
4315 
4316 	if (ii->ipsec_in_action != NULL) {
4317 		if (connp->conn_latch == NULL) {
4318 			connp->conn_latch = iplatch_create();
4319 			if (connp->conn_latch == NULL)
4320 				return (B_FALSE);
4321 		}
4322 		ipsec_latch_inbound(connp->conn_latch, ii);
4323 	}
4324 	return (B_TRUE);
4325 }
4326 
4327 /*
4328  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4329  * and to arrange for power-fanout assist.  The ULP is identified by
4330  * adding a single byte at the end of the original bind message.
4331  * A ULP other than UDP or TCP that wishes to be recognized passes
4332  * down a bind with a zero length address.
4333  *
4334  * The binding works as follows:
4335  * - A zero byte address means just bind to the protocol.
4336  * - A four byte address is treated as a request to validate
4337  *   that the address is a valid local address, appropriate for
4338  *   an application to bind to. This does not affect any fanout
4339  *   information in IP.
4340  * - A sizeof sin_t byte address is used to bind to only the local address
4341  *   and port.
4342  * - A sizeof ipa_conn_t byte address contains complete fanout information
4343  *   consisting of local and remote addresses and ports.  In
4344  *   this case, the addresses are both validated as appropriate
4345  *   for this operation, and, if so, the information is retained
4346  *   for use in the inbound fanout.
4347  *
4348  * The ULP (except in the zero-length bind) can append an
4349  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4350  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4351  * a copy of the source or destination IRE (source for local bind;
4352  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4353  * policy information contained should be copied on to the conn.
4354  *
4355  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4356  */
4357 mblk_t *
4358 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4359 {
4360 	ssize_t		len;
4361 	struct T_bind_req	*tbr;
4362 	sin_t		*sin;
4363 	ipa_conn_t	*ac;
4364 	uchar_t		*ucp;
4365 	mblk_t		*mp1;
4366 	boolean_t	ire_requested;
4367 	boolean_t	ipsec_policy_set = B_FALSE;
4368 	int		error = 0;
4369 	int		protocol;
4370 	ipa_conn_x_t	*acx;
4371 
4372 	ASSERT(!connp->conn_af_isv6);
4373 	connp->conn_pkt_isv6 = B_FALSE;
4374 
4375 	len = MBLKL(mp);
4376 	if (len < (sizeof (*tbr) + 1)) {
4377 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4378 		    "ip_bind: bogus msg, len %ld", len);
4379 		/* XXX: Need to return something better */
4380 		goto bad_addr;
4381 	}
4382 	/* Back up and extract the protocol identifier. */
4383 	mp->b_wptr--;
4384 	protocol = *mp->b_wptr & 0xFF;
4385 	tbr = (struct T_bind_req *)mp->b_rptr;
4386 	/* Reset the message type in preparation for shipping it back. */
4387 	DB_TYPE(mp) = M_PCPROTO;
4388 
4389 	connp->conn_ulp = (uint8_t)protocol;
4390 
4391 	/*
4392 	 * Check for a zero length address.  This is from a protocol that
4393 	 * wants to register to receive all packets of its type.
4394 	 */
4395 	if (tbr->ADDR_length == 0) {
4396 		/*
4397 		 * These protocols are now intercepted in ip_bind_v6().
4398 		 * Reject protocol-level binds here for now.
4399 		 *
4400 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4401 		 * so that the protocol type cannot be SCTP.
4402 		 */
4403 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4404 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4405 			goto bad_addr;
4406 		}
4407 
4408 		/*
4409 		 *
4410 		 * The udp module never sends down a zero-length address,
4411 		 * and allowing this on a labeled system will break MLP
4412 		 * functionality.
4413 		 */
4414 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4415 			goto bad_addr;
4416 
4417 		if (connp->conn_mac_exempt)
4418 			goto bad_addr;
4419 
4420 		/* No hash here really.  The table is big enough. */
4421 		connp->conn_srcv6 = ipv6_all_zeros;
4422 
4423 		ipcl_proto_insert(connp, protocol);
4424 
4425 		tbr->PRIM_type = T_BIND_ACK;
4426 		return (mp);
4427 	}
4428 
4429 	/* Extract the address pointer from the message. */
4430 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4431 	    tbr->ADDR_length);
4432 	if (ucp == NULL) {
4433 		ip1dbg(("ip_bind: no address\n"));
4434 		goto bad_addr;
4435 	}
4436 	if (!OK_32PTR(ucp)) {
4437 		ip1dbg(("ip_bind: unaligned address\n"));
4438 		goto bad_addr;
4439 	}
4440 	/*
4441 	 * Check for trailing mps.
4442 	 */
4443 
4444 	mp1 = mp->b_cont;
4445 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4446 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4447 
4448 	switch (tbr->ADDR_length) {
4449 	default:
4450 		ip1dbg(("ip_bind: bad address length %d\n",
4451 		    (int)tbr->ADDR_length));
4452 		goto bad_addr;
4453 
4454 	case IP_ADDR_LEN:
4455 		/* Verification of local address only */
4456 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4457 		    ire_requested, ipsec_policy_set, B_FALSE);
4458 		break;
4459 
4460 	case sizeof (sin_t):
4461 		sin = (sin_t *)ucp;
4462 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4463 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4464 		break;
4465 
4466 	case sizeof (ipa_conn_t):
4467 		ac = (ipa_conn_t *)ucp;
4468 		/* For raw socket, the local port is not set. */
4469 		if (ac->ac_lport == 0)
4470 			ac->ac_lport = connp->conn_lport;
4471 		/* Always verify destination reachability. */
4472 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4473 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4474 		    ipsec_policy_set, B_TRUE, B_TRUE);
4475 		break;
4476 
4477 	case sizeof (ipa_conn_x_t):
4478 		acx = (ipa_conn_x_t *)ucp;
4479 		/*
4480 		 * Whether or not to verify destination reachability depends
4481 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4482 		 */
4483 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4484 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4485 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4486 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4487 		break;
4488 	}
4489 	if (error == EINPROGRESS)
4490 		return (NULL);
4491 	else if (error != 0)
4492 		goto bad_addr;
4493 	/*
4494 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4495 	 * We can't do this in ip_bind_insert_ire because the policy
4496 	 * may not have been inherited at that point in time and hence
4497 	 * conn_out_enforce_policy may not be set.
4498 	 */
4499 	mp1 = mp->b_cont;
4500 	if (ire_requested && connp->conn_out_enforce_policy &&
4501 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4502 		ire_t *ire = (ire_t *)mp1->b_rptr;
4503 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4504 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4505 	}
4506 
4507 	/* Send it home. */
4508 	mp->b_datap->db_type = M_PCPROTO;
4509 	tbr->PRIM_type = T_BIND_ACK;
4510 	return (mp);
4511 
4512 bad_addr:
4513 	/*
4514 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4515 	 * a unix errno.
4516 	 */
4517 	if (error > 0)
4518 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4519 	else
4520 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4521 	return (mp);
4522 }
4523 
4524 /*
4525  * Here address is verified to be a valid local address.
4526  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4527  * address is also considered a valid local address.
4528  * In the case of a broadcast/multicast address, however, the
4529  * upper protocol is expected to reset the src address
4530  * to 0 if it sees a IRE_BROADCAST type returned so that
4531  * no packets are emitted with broadcast/multicast address as
4532  * source address (that violates hosts requirements RFC1122)
4533  * The addresses valid for bind are:
4534  *	(1) - INADDR_ANY (0)
4535  *	(2) - IP address of an UP interface
4536  *	(3) - IP address of a DOWN interface
4537  *	(4) - valid local IP broadcast addresses. In this case
4538  *	the conn will only receive packets destined to
4539  *	the specified broadcast address.
4540  *	(5) - a multicast address. In this case
4541  *	the conn will only receive packets destined to
4542  *	the specified multicast address. Note: the
4543  *	application still has to issue an
4544  *	IP_ADD_MEMBERSHIP socket option.
4545  *
4546  * On error, return -1 for TBADADDR otherwise pass the
4547  * errno with TSYSERR reply.
4548  *
4549  * In all the above cases, the bound address must be valid in the current zone.
4550  * When the address is loopback, multicast or broadcast, there might be many
4551  * matching IREs so bind has to look up based on the zone.
4552  *
4553  * Note: lport is in network byte order.
4554  */
4555 int
4556 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4557     boolean_t ire_requested, boolean_t ipsec_policy_set,
4558     boolean_t fanout_insert)
4559 {
4560 	int		error = 0;
4561 	ire_t		*src_ire;
4562 	mblk_t		*policy_mp;
4563 	ipif_t		*ipif;
4564 	zoneid_t	zoneid;
4565 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4566 
4567 	if (ipsec_policy_set) {
4568 		policy_mp = mp->b_cont;
4569 	}
4570 
4571 	/*
4572 	 * If it was previously connected, conn_fully_bound would have
4573 	 * been set.
4574 	 */
4575 	connp->conn_fully_bound = B_FALSE;
4576 
4577 	src_ire = NULL;
4578 	ipif = NULL;
4579 
4580 	zoneid = IPCL_ZONEID(connp);
4581 
4582 	if (src_addr) {
4583 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4584 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4585 		/*
4586 		 * If an address other than 0.0.0.0 is requested,
4587 		 * we verify that it is a valid address for bind
4588 		 * Note: Following code is in if-else-if form for
4589 		 * readability compared to a condition check.
4590 		 */
4591 		/* LINTED - statement has no consequent */
4592 		if (IRE_IS_LOCAL(src_ire)) {
4593 			/*
4594 			 * (2) Bind to address of local UP interface
4595 			 */
4596 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4597 			/*
4598 			 * (4) Bind to broadcast address
4599 			 * Note: permitted only from transports that
4600 			 * request IRE
4601 			 */
4602 			if (!ire_requested)
4603 				error = EADDRNOTAVAIL;
4604 		} else {
4605 			/*
4606 			 * (3) Bind to address of local DOWN interface
4607 			 * (ipif_lookup_addr() looks up all interfaces
4608 			 * but we do not get here for UP interfaces
4609 			 * - case (2) above)
4610 			 * We put the protocol byte back into the mblk
4611 			 * since we may come back via ip_wput_nondata()
4612 			 * later with this mblk if ipif_lookup_addr chooses
4613 			 * to defer processing.
4614 			 */
4615 			*mp->b_wptr++ = (char)connp->conn_ulp;
4616 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4617 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4618 			    &error, ipst)) != NULL) {
4619 				ipif_refrele(ipif);
4620 			} else if (error == EINPROGRESS) {
4621 				if (src_ire != NULL)
4622 					ire_refrele(src_ire);
4623 				return (EINPROGRESS);
4624 			} else if (CLASSD(src_addr)) {
4625 				error = 0;
4626 				if (src_ire != NULL)
4627 					ire_refrele(src_ire);
4628 				/*
4629 				 * (5) bind to multicast address.
4630 				 * Fake out the IRE returned to upper
4631 				 * layer to be a broadcast IRE.
4632 				 */
4633 				src_ire = ire_ctable_lookup(
4634 				    INADDR_BROADCAST, INADDR_ANY,
4635 				    IRE_BROADCAST, NULL, zoneid, NULL,
4636 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4637 				    ipst);
4638 				if (src_ire == NULL || !ire_requested)
4639 					error = EADDRNOTAVAIL;
4640 			} else {
4641 				/*
4642 				 * Not a valid address for bind
4643 				 */
4644 				error = EADDRNOTAVAIL;
4645 			}
4646 			/*
4647 			 * Just to keep it consistent with the processing in
4648 			 * ip_bind_v4()
4649 			 */
4650 			mp->b_wptr--;
4651 		}
4652 		if (error) {
4653 			/* Red Alert!  Attempting to be a bogon! */
4654 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4655 			    ntohl(src_addr)));
4656 			goto bad_addr;
4657 		}
4658 	}
4659 
4660 	/*
4661 	 * Allow setting new policies. For example, disconnects come
4662 	 * down as ipa_t bind. As we would have set conn_policy_cached
4663 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4664 	 * can change after the disconnect.
4665 	 */
4666 	connp->conn_policy_cached = B_FALSE;
4667 
4668 	/*
4669 	 * If not fanout_insert this was just an address verification
4670 	 */
4671 	if (fanout_insert) {
4672 		/*
4673 		 * The addresses have been verified. Time to insert in
4674 		 * the correct fanout list.
4675 		 */
4676 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4677 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4678 		connp->conn_lport = lport;
4679 		connp->conn_fport = 0;
4680 		/*
4681 		 * Do we need to add a check to reject Multicast packets
4682 		 *
4683 		 * We need to make sure that the conn_recv is set to a non-null
4684 		 * value before we insert the conn into the classifier table.
4685 		 * This is to avoid a race with an incoming packet which does an
4686 		 * ipcl_classify().
4687 		 */
4688 		if (*mp->b_wptr == IPPROTO_TCP)
4689 			connp->conn_recv = tcp_conn_request;
4690 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4691 	}
4692 
4693 	if (error == 0) {
4694 		if (ire_requested) {
4695 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4696 				error = -1;
4697 				/* Falls through to bad_addr */
4698 			}
4699 		} else if (ipsec_policy_set) {
4700 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4701 				error = -1;
4702 				/* Falls through to bad_addr */
4703 			}
4704 		}
4705 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4706 		connp->conn_recv = tcp_input;
4707 	}
4708 bad_addr:
4709 	if (error != 0) {
4710 		if (connp->conn_anon_port) {
4711 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4712 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4713 			    B_FALSE);
4714 		}
4715 		connp->conn_mlp_type = mlptSingle;
4716 	}
4717 	if (src_ire != NULL)
4718 		IRE_REFRELE(src_ire);
4719 	if (ipsec_policy_set) {
4720 		ASSERT(policy_mp == mp->b_cont);
4721 		ASSERT(policy_mp != NULL);
4722 		freeb(policy_mp);
4723 		/*
4724 		 * As of now assume that nothing else accompanies
4725 		 * IPSEC_POLICY_SET.
4726 		 */
4727 		mp->b_cont = NULL;
4728 	}
4729 	return (error);
4730 }
4731 
4732 /*
4733  * Verify that both the source and destination addresses
4734  * are valid.  If verify_dst is false, then the destination address may be
4735  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4736  * destination reachability, while tunnels do not.
4737  * Note that we allow connect to broadcast and multicast
4738  * addresses when ire_requested is set. Thus the ULP
4739  * has to check for IRE_BROADCAST and multicast.
4740  *
4741  * Returns zero if ok.
4742  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4743  * (for use with TSYSERR reply).
4744  *
4745  * Note: lport and fport are in network byte order.
4746  */
4747 int
4748 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4749     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4750     boolean_t ire_requested, boolean_t ipsec_policy_set,
4751     boolean_t fanout_insert, boolean_t verify_dst)
4752 {
4753 	ire_t		*src_ire;
4754 	ire_t		*dst_ire;
4755 	int		error = 0;
4756 	int 		protocol;
4757 	mblk_t		*policy_mp;
4758 	ire_t		*sire = NULL;
4759 	ire_t		*md_dst_ire = NULL;
4760 	ire_t		*lso_dst_ire = NULL;
4761 	ill_t		*ill = NULL;
4762 	zoneid_t	zoneid;
4763 	ipaddr_t	src_addr = *src_addrp;
4764 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4765 
4766 	src_ire = dst_ire = NULL;
4767 	protocol = *mp->b_wptr & 0xFF;
4768 
4769 	/*
4770 	 * If we never got a disconnect before, clear it now.
4771 	 */
4772 	connp->conn_fully_bound = B_FALSE;
4773 
4774 	if (ipsec_policy_set) {
4775 		policy_mp = mp->b_cont;
4776 	}
4777 
4778 	zoneid = IPCL_ZONEID(connp);
4779 
4780 	if (CLASSD(dst_addr)) {
4781 		/* Pick up an IRE_BROADCAST */
4782 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4783 		    NULL, zoneid, MBLK_GETLABEL(mp),
4784 		    (MATCH_IRE_RECURSIVE |
4785 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4786 		    MATCH_IRE_SECATTR), ipst);
4787 	} else {
4788 		/*
4789 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4790 		 * and onlink ipif is not found set ENETUNREACH error.
4791 		 */
4792 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4793 			ipif_t *ipif;
4794 
4795 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4796 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4797 			if (ipif == NULL) {
4798 				error = ENETUNREACH;
4799 				goto bad_addr;
4800 			}
4801 			ipif_refrele(ipif);
4802 		}
4803 
4804 		if (connp->conn_nexthop_set) {
4805 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4806 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4807 			    MATCH_IRE_SECATTR, ipst);
4808 		} else {
4809 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4810 			    &sire, zoneid, MBLK_GETLABEL(mp),
4811 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4812 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4813 			    MATCH_IRE_SECATTR), ipst);
4814 		}
4815 	}
4816 	/*
4817 	 * dst_ire can't be a broadcast when not ire_requested.
4818 	 * We also prevent ire's with src address INADDR_ANY to
4819 	 * be used, which are created temporarily for
4820 	 * sending out packets from endpoints that have
4821 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4822 	 * reachable.  If verify_dst is false, the destination needn't be
4823 	 * reachable.
4824 	 *
4825 	 * If we match on a reject or black hole, then we've got a
4826 	 * local failure.  May as well fail out the connect() attempt,
4827 	 * since it's never going to succeed.
4828 	 */
4829 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4830 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4831 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4832 		/*
4833 		 * If we're verifying destination reachability, we always want
4834 		 * to complain here.
4835 		 *
4836 		 * If we're not verifying destination reachability but the
4837 		 * destination has a route, we still want to fail on the
4838 		 * temporary address and broadcast address tests.
4839 		 */
4840 		if (verify_dst || (dst_ire != NULL)) {
4841 			if (ip_debug > 2) {
4842 				pr_addr_dbg("ip_bind_connected: bad connected "
4843 				    "dst %s\n", AF_INET, &dst_addr);
4844 			}
4845 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4846 				error = ENETUNREACH;
4847 			else
4848 				error = EHOSTUNREACH;
4849 			goto bad_addr;
4850 		}
4851 	}
4852 
4853 	/*
4854 	 * We now know that routing will allow us to reach the destination.
4855 	 * Check whether Trusted Solaris policy allows communication with this
4856 	 * host, and pretend that the destination is unreachable if not.
4857 	 *
4858 	 * This is never a problem for TCP, since that transport is known to
4859 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4860 	 * handling.  If the remote is unreachable, it will be detected at that
4861 	 * point, so there's no reason to check it here.
4862 	 *
4863 	 * Note that for sendto (and other datagram-oriented friends), this
4864 	 * check is done as part of the data path label computation instead.
4865 	 * The check here is just to make non-TCP connect() report the right
4866 	 * error.
4867 	 */
4868 	if (dst_ire != NULL && is_system_labeled() &&
4869 	    !IPCL_IS_TCP(connp) &&
4870 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4871 	    connp->conn_mac_exempt, ipst) != 0) {
4872 		error = EHOSTUNREACH;
4873 		if (ip_debug > 2) {
4874 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4875 			    AF_INET, &dst_addr);
4876 		}
4877 		goto bad_addr;
4878 	}
4879 
4880 	/*
4881 	 * If the app does a connect(), it means that it will most likely
4882 	 * send more than 1 packet to the destination.  It makes sense
4883 	 * to clear the temporary flag.
4884 	 */
4885 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4886 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4887 		irb_t *irb = dst_ire->ire_bucket;
4888 
4889 		rw_enter(&irb->irb_lock, RW_WRITER);
4890 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4891 		irb->irb_tmp_ire_cnt--;
4892 		rw_exit(&irb->irb_lock);
4893 	}
4894 
4895 	/*
4896 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4897 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4898 	 * eligibility tests for passive connects are handled separately
4899 	 * through tcp_adapt_ire().  We do this before the source address
4900 	 * selection, because dst_ire may change after a call to
4901 	 * ipif_select_source().  This is a best-effort check, as the
4902 	 * packet for this connection may not actually go through
4903 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4904 	 * calling ip_newroute().  This is why we further check on the
4905 	 * IRE during LSO/Multidata packet transmission in
4906 	 * tcp_lsosend()/tcp_multisend().
4907 	 */
4908 	if (!ipsec_policy_set && dst_ire != NULL &&
4909 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4910 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4911 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4912 			lso_dst_ire = dst_ire;
4913 			IRE_REFHOLD(lso_dst_ire);
4914 		} else if (ipst->ips_ip_multidata_outbound &&
4915 		    ILL_MDT_CAPABLE(ill)) {
4916 			md_dst_ire = dst_ire;
4917 			IRE_REFHOLD(md_dst_ire);
4918 		}
4919 	}
4920 
4921 	if (dst_ire != NULL &&
4922 	    dst_ire->ire_type == IRE_LOCAL &&
4923 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4924 		/*
4925 		 * If the IRE belongs to a different zone, look for a matching
4926 		 * route in the forwarding table and use the source address from
4927 		 * that route.
4928 		 */
4929 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4930 		    zoneid, 0, NULL,
4931 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4932 		    MATCH_IRE_RJ_BHOLE, ipst);
4933 		if (src_ire == NULL) {
4934 			error = EHOSTUNREACH;
4935 			goto bad_addr;
4936 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4937 			if (!(src_ire->ire_type & IRE_HOST))
4938 				error = ENETUNREACH;
4939 			else
4940 				error = EHOSTUNREACH;
4941 			goto bad_addr;
4942 		}
4943 		if (src_addr == INADDR_ANY)
4944 			src_addr = src_ire->ire_src_addr;
4945 		ire_refrele(src_ire);
4946 		src_ire = NULL;
4947 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4948 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4949 			src_addr = sire->ire_src_addr;
4950 			ire_refrele(dst_ire);
4951 			dst_ire = sire;
4952 			sire = NULL;
4953 		} else {
4954 			/*
4955 			 * Pick a source address so that a proper inbound
4956 			 * load spreading would happen.
4957 			 */
4958 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4959 			ipif_t *src_ipif = NULL;
4960 			ire_t *ipif_ire;
4961 
4962 			/*
4963 			 * Supply a local source address such that inbound
4964 			 * load spreading happens.
4965 			 *
4966 			 * Determine the best source address on this ill for
4967 			 * the destination.
4968 			 *
4969 			 * 1) For broadcast, we should return a broadcast ire
4970 			 *    found above so that upper layers know that the
4971 			 *    destination address is a broadcast address.
4972 			 *
4973 			 * 2) If this is part of a group, select a better
4974 			 *    source address so that better inbound load
4975 			 *    balancing happens. Do the same if the ipif
4976 			 *    is DEPRECATED.
4977 			 *
4978 			 * 3) If the outgoing interface is part of a usesrc
4979 			 *    group, then try selecting a source address from
4980 			 *    the usesrc ILL.
4981 			 */
4982 			if ((dst_ire->ire_zoneid != zoneid &&
4983 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4984 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4985 			    ((dst_ill->ill_group != NULL) ||
4986 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4987 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4988 				/*
4989 				 * If the destination is reachable via a
4990 				 * given gateway, the selected source address
4991 				 * should be in the same subnet as the gateway.
4992 				 * Otherwise, the destination is not reachable.
4993 				 *
4994 				 * If there are no interfaces on the same subnet
4995 				 * as the destination, ipif_select_source gives
4996 				 * first non-deprecated interface which might be
4997 				 * on a different subnet than the gateway.
4998 				 * This is not desirable. Hence pass the dst_ire
4999 				 * source address to ipif_select_source.
5000 				 * It is sure that the destination is reachable
5001 				 * with the dst_ire source address subnet.
5002 				 * So passing dst_ire source address to
5003 				 * ipif_select_source will make sure that the
5004 				 * selected source will be on the same subnet
5005 				 * as dst_ire source address.
5006 				 */
5007 				ipaddr_t saddr =
5008 				    dst_ire->ire_ipif->ipif_src_addr;
5009 				src_ipif = ipif_select_source(dst_ill,
5010 				    saddr, zoneid);
5011 				if (src_ipif != NULL) {
5012 					if (IS_VNI(src_ipif->ipif_ill)) {
5013 						/*
5014 						 * For VNI there is no
5015 						 * interface route
5016 						 */
5017 						src_addr =
5018 						    src_ipif->ipif_src_addr;
5019 					} else {
5020 						ipif_ire =
5021 						    ipif_to_ire(src_ipif);
5022 						if (ipif_ire != NULL) {
5023 							IRE_REFRELE(dst_ire);
5024 							dst_ire = ipif_ire;
5025 						}
5026 						src_addr =
5027 						    dst_ire->ire_src_addr;
5028 					}
5029 					ipif_refrele(src_ipif);
5030 				} else {
5031 					src_addr = dst_ire->ire_src_addr;
5032 				}
5033 			} else {
5034 				src_addr = dst_ire->ire_src_addr;
5035 			}
5036 		}
5037 	}
5038 
5039 	/*
5040 	 * We do ire_route_lookup() here (and not
5041 	 * interface lookup as we assert that
5042 	 * src_addr should only come from an
5043 	 * UP interface for hard binding.
5044 	 */
5045 	ASSERT(src_ire == NULL);
5046 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5047 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5048 	/* src_ire must be a local|loopback */
5049 	if (!IRE_IS_LOCAL(src_ire)) {
5050 		if (ip_debug > 2) {
5051 			pr_addr_dbg("ip_bind_connected: bad connected "
5052 			    "src %s\n", AF_INET, &src_addr);
5053 		}
5054 		error = EADDRNOTAVAIL;
5055 		goto bad_addr;
5056 	}
5057 
5058 	/*
5059 	 * If the source address is a loopback address, the
5060 	 * destination had best be local or multicast.
5061 	 * The transports that can't handle multicast will reject
5062 	 * those addresses.
5063 	 */
5064 	if (src_ire->ire_type == IRE_LOOPBACK &&
5065 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5066 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5067 		error = -1;
5068 		goto bad_addr;
5069 	}
5070 
5071 	/*
5072 	 * Allow setting new policies. For example, disconnects come
5073 	 * down as ipa_t bind. As we would have set conn_policy_cached
5074 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5075 	 * can change after the disconnect.
5076 	 */
5077 	connp->conn_policy_cached = B_FALSE;
5078 
5079 	/*
5080 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5081 	 * can handle their passed-in conn's.
5082 	 */
5083 
5084 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5085 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5086 	connp->conn_lport = lport;
5087 	connp->conn_fport = fport;
5088 	*src_addrp = src_addr;
5089 
5090 	ASSERT(!(ipsec_policy_set && ire_requested));
5091 	if (ire_requested) {
5092 		iulp_t *ulp_info = NULL;
5093 
5094 		/*
5095 		 * Note that sire will not be NULL if this is an off-link
5096 		 * connection and there is not cache for that dest yet.
5097 		 *
5098 		 * XXX Because of an existing bug, if there are multiple
5099 		 * default routes, the IRE returned now may not be the actual
5100 		 * default route used (default routes are chosen in a
5101 		 * round robin fashion).  So if the metrics for different
5102 		 * default routes are different, we may return the wrong
5103 		 * metrics.  This will not be a problem if the existing
5104 		 * bug is fixed.
5105 		 */
5106 		if (sire != NULL) {
5107 			ulp_info = &(sire->ire_uinfo);
5108 		}
5109 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5110 			error = -1;
5111 			goto bad_addr;
5112 		}
5113 	} else if (ipsec_policy_set) {
5114 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5115 			error = -1;
5116 			goto bad_addr;
5117 		}
5118 	}
5119 
5120 	/*
5121 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5122 	 * we'll cache that.  If we don't, we'll inherit global policy.
5123 	 *
5124 	 * We can't insert until the conn reflects the policy. Note that
5125 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5126 	 * connections where we don't have a policy. This is to prevent
5127 	 * global policy lookups in the inbound path.
5128 	 *
5129 	 * If we insert before we set conn_policy_cached,
5130 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5131 	 * because global policy cound be non-empty. We normally call
5132 	 * ipsec_check_policy() for conn_policy_cached connections only if
5133 	 * ipc_in_enforce_policy is set. But in this case,
5134 	 * conn_policy_cached can get set anytime since we made the
5135 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5136 	 * called, which will make the above assumption false.  Thus, we
5137 	 * need to insert after we set conn_policy_cached.
5138 	 */
5139 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5140 		goto bad_addr;
5141 
5142 	if (fanout_insert) {
5143 		/*
5144 		 * The addresses have been verified. Time to insert in
5145 		 * the correct fanout list.
5146 		 * We need to make sure that the conn_recv is set to a non-null
5147 		 * value before we insert into the classifier table to avoid a
5148 		 * race with an incoming packet which does an ipcl_classify().
5149 		 */
5150 		if (protocol == IPPROTO_TCP)
5151 			connp->conn_recv = tcp_input;
5152 		error = ipcl_conn_insert(connp, protocol, src_addr,
5153 		    dst_addr, connp->conn_ports);
5154 	}
5155 
5156 	if (error == 0) {
5157 		connp->conn_fully_bound = B_TRUE;
5158 		/*
5159 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5160 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5161 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5162 		 * ip_xxinfo_return(), which performs further checks
5163 		 * against them and upon success, returns the LSO/MDT info
5164 		 * mblk which we will attach to the bind acknowledgment.
5165 		 */
5166 		if (lso_dst_ire != NULL) {
5167 			mblk_t *lsoinfo_mp;
5168 
5169 			ASSERT(ill->ill_lso_capab != NULL);
5170 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5171 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5172 				linkb(mp, lsoinfo_mp);
5173 		} else if (md_dst_ire != NULL) {
5174 			mblk_t *mdinfo_mp;
5175 
5176 			ASSERT(ill->ill_mdt_capab != NULL);
5177 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5178 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5179 				linkb(mp, mdinfo_mp);
5180 		}
5181 	}
5182 bad_addr:
5183 	if (ipsec_policy_set) {
5184 		ASSERT(policy_mp == mp->b_cont);
5185 		ASSERT(policy_mp != NULL);
5186 		freeb(policy_mp);
5187 		/*
5188 		 * As of now assume that nothing else accompanies
5189 		 * IPSEC_POLICY_SET.
5190 		 */
5191 		mp->b_cont = NULL;
5192 	}
5193 	if (src_ire != NULL)
5194 		IRE_REFRELE(src_ire);
5195 	if (dst_ire != NULL)
5196 		IRE_REFRELE(dst_ire);
5197 	if (sire != NULL)
5198 		IRE_REFRELE(sire);
5199 	if (md_dst_ire != NULL)
5200 		IRE_REFRELE(md_dst_ire);
5201 	if (lso_dst_ire != NULL)
5202 		IRE_REFRELE(lso_dst_ire);
5203 	return (error);
5204 }
5205 
5206 /*
5207  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5208  * Prefers dst_ire over src_ire.
5209  */
5210 static boolean_t
5211 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5212 {
5213 	mblk_t	*mp1;
5214 	ire_t *ret_ire = NULL;
5215 
5216 	mp1 = mp->b_cont;
5217 	ASSERT(mp1 != NULL);
5218 
5219 	if (ire != NULL) {
5220 		/*
5221 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5222 		 * appended mblk. Its <upper protocol>'s
5223 		 * job to make sure there is room.
5224 		 */
5225 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5226 			return (0);
5227 
5228 		mp1->b_datap->db_type = IRE_DB_TYPE;
5229 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5230 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5231 		ret_ire = (ire_t *)mp1->b_rptr;
5232 		/*
5233 		 * Pass the latest setting of the ip_path_mtu_discovery and
5234 		 * copy the ulp info if any.
5235 		 */
5236 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5237 		    IPH_DF : 0;
5238 		if (ulp_info != NULL) {
5239 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5240 			    sizeof (iulp_t));
5241 		}
5242 		ret_ire->ire_mp = mp1;
5243 	} else {
5244 		/*
5245 		 * No IRE was found. Remove IRE mblk.
5246 		 */
5247 		mp->b_cont = mp1->b_cont;
5248 		freeb(mp1);
5249 	}
5250 
5251 	return (1);
5252 }
5253 
5254 /*
5255  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5256  * the final piece where we don't.  Return a pointer to the first mblk in the
5257  * result, and update the pointer to the next mblk to chew on.  If anything
5258  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5259  * NULL pointer.
5260  */
5261 mblk_t *
5262 ip_carve_mp(mblk_t **mpp, ssize_t len)
5263 {
5264 	mblk_t	*mp0;
5265 	mblk_t	*mp1;
5266 	mblk_t	*mp2;
5267 
5268 	if (!len || !mpp || !(mp0 = *mpp))
5269 		return (NULL);
5270 	/* If we aren't going to consume the first mblk, we need a dup. */
5271 	if (mp0->b_wptr - mp0->b_rptr > len) {
5272 		mp1 = dupb(mp0);
5273 		if (mp1) {
5274 			/* Partition the data between the two mblks. */
5275 			mp1->b_wptr = mp1->b_rptr + len;
5276 			mp0->b_rptr = mp1->b_wptr;
5277 			/*
5278 			 * after adjustments if mblk not consumed is now
5279 			 * unaligned, try to align it. If this fails free
5280 			 * all messages and let upper layer recover.
5281 			 */
5282 			if (!OK_32PTR(mp0->b_rptr)) {
5283 				if (!pullupmsg(mp0, -1)) {
5284 					freemsg(mp0);
5285 					freemsg(mp1);
5286 					*mpp = NULL;
5287 					return (NULL);
5288 				}
5289 			}
5290 		}
5291 		return (mp1);
5292 	}
5293 	/* Eat through as many mblks as we need to get len bytes. */
5294 	len -= mp0->b_wptr - mp0->b_rptr;
5295 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5296 		if (mp2->b_wptr - mp2->b_rptr > len) {
5297 			/*
5298 			 * We won't consume the entire last mblk.  Like
5299 			 * above, dup and partition it.
5300 			 */
5301 			mp1->b_cont = dupb(mp2);
5302 			mp1 = mp1->b_cont;
5303 			if (!mp1) {
5304 				/*
5305 				 * Trouble.  Rather than go to a lot of
5306 				 * trouble to clean up, we free the messages.
5307 				 * This won't be any worse than losing it on
5308 				 * the wire.
5309 				 */
5310 				freemsg(mp0);
5311 				freemsg(mp2);
5312 				*mpp = NULL;
5313 				return (NULL);
5314 			}
5315 			mp1->b_wptr = mp1->b_rptr + len;
5316 			mp2->b_rptr = mp1->b_wptr;
5317 			/*
5318 			 * after adjustments if mblk not consumed is now
5319 			 * unaligned, try to align it. If this fails free
5320 			 * all messages and let upper layer recover.
5321 			 */
5322 			if (!OK_32PTR(mp2->b_rptr)) {
5323 				if (!pullupmsg(mp2, -1)) {
5324 					freemsg(mp0);
5325 					freemsg(mp2);
5326 					*mpp = NULL;
5327 					return (NULL);
5328 				}
5329 			}
5330 			*mpp = mp2;
5331 			return (mp0);
5332 		}
5333 		/* Decrement len by the amount we just got. */
5334 		len -= mp2->b_wptr - mp2->b_rptr;
5335 	}
5336 	/*
5337 	 * len should be reduced to zero now.  If not our caller has
5338 	 * screwed up.
5339 	 */
5340 	if (len) {
5341 		/* Shouldn't happen! */
5342 		freemsg(mp0);
5343 		*mpp = NULL;
5344 		return (NULL);
5345 	}
5346 	/*
5347 	 * We consumed up to exactly the end of an mblk.  Detach the part
5348 	 * we are returning from the rest of the chain.
5349 	 */
5350 	mp1->b_cont = NULL;
5351 	*mpp = mp2;
5352 	return (mp0);
5353 }
5354 
5355 /* The ill stream is being unplumbed. Called from ip_close */
5356 int
5357 ip_modclose(ill_t *ill)
5358 {
5359 
5360 	boolean_t success;
5361 	ipsq_t	*ipsq;
5362 	ipif_t	*ipif;
5363 	queue_t	*q = ill->ill_rq;
5364 	hook_nic_event_t *info;
5365 	ip_stack_t	*ipst = ill->ill_ipst;
5366 	clock_t timeout;
5367 
5368 	/*
5369 	 * Wait for the ACKs of all deferred control messages to be processed.
5370 	 * In particular, we wait for a potential capability reset initiated
5371 	 * in ip_sioctl_plink() to complete before proceeding.
5372 	 *
5373 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5374 	 * in case the driver never replies.
5375 	 */
5376 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5377 	mutex_enter(&ill->ill_lock);
5378 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5379 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5380 			/* Timeout */
5381 			break;
5382 		}
5383 	}
5384 	mutex_exit(&ill->ill_lock);
5385 
5386 	/*
5387 	 * Forcibly enter the ipsq after some delay. This is to take
5388 	 * care of the case when some ioctl does not complete because
5389 	 * we sent a control message to the driver and it did not
5390 	 * send us a reply. We want to be able to at least unplumb
5391 	 * and replumb rather than force the user to reboot the system.
5392 	 */
5393 	success = ipsq_enter(ill, B_FALSE);
5394 
5395 	/*
5396 	 * Open/close/push/pop is guaranteed to be single threaded
5397 	 * per stream by STREAMS. FS guarantees that all references
5398 	 * from top are gone before close is called. So there can't
5399 	 * be another close thread that has set CONDEMNED on this ill.
5400 	 * and cause ipsq_enter to return failure.
5401 	 */
5402 	ASSERT(success);
5403 	ipsq = ill->ill_phyint->phyint_ipsq;
5404 
5405 	/*
5406 	 * Mark it condemned. No new reference will be made to this ill.
5407 	 * Lookup functions will return an error. Threads that try to
5408 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5409 	 * that the refcnt will drop down to zero.
5410 	 */
5411 	mutex_enter(&ill->ill_lock);
5412 	ill->ill_state_flags |= ILL_CONDEMNED;
5413 	for (ipif = ill->ill_ipif; ipif != NULL;
5414 	    ipif = ipif->ipif_next) {
5415 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5416 	}
5417 	/*
5418 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5419 	 * returns  error if ILL_CONDEMNED is set
5420 	 */
5421 	cv_broadcast(&ill->ill_cv);
5422 	mutex_exit(&ill->ill_lock);
5423 
5424 	/*
5425 	 * Send all the deferred control messages downstream which came in
5426 	 * during the small window right before ipsq_enter(). We do this
5427 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5428 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5429 	 */
5430 	ill_send_all_deferred_mp(ill);
5431 
5432 	/*
5433 	 * Shut down fragmentation reassembly.
5434 	 * ill_frag_timer won't start a timer again.
5435 	 * Now cancel any existing timer
5436 	 */
5437 	(void) untimeout(ill->ill_frag_timer_id);
5438 	(void) ill_frag_timeout(ill, 0);
5439 
5440 	/*
5441 	 * If MOVE was in progress, clear the
5442 	 * move_in_progress fields also.
5443 	 */
5444 	if (ill->ill_move_in_progress) {
5445 		ILL_CLEAR_MOVE(ill);
5446 	}
5447 
5448 	/*
5449 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5450 	 * this ill. Then wait for the refcnts to drop to zero.
5451 	 * ill_is_quiescent checks whether the ill is really quiescent.
5452 	 * Then make sure that threads that are waiting to enter the
5453 	 * ipsq have seen the error returned by ipsq_enter and have
5454 	 * gone away. Then we call ill_delete_tail which does the
5455 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5456 	 */
5457 	ill_delete(ill);
5458 	mutex_enter(&ill->ill_lock);
5459 	while (!ill_is_quiescent(ill))
5460 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5461 	while (ill->ill_waiters)
5462 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5463 
5464 	mutex_exit(&ill->ill_lock);
5465 
5466 	/*
5467 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5468 	 * it held until the end of the function since the cleanup
5469 	 * below needs to be able to use the ip_stack_t.
5470 	 */
5471 	netstack_hold(ipst->ips_netstack);
5472 
5473 	/* qprocsoff is called in ill_delete_tail */
5474 	ill_delete_tail(ill);
5475 	ASSERT(ill->ill_ipst == NULL);
5476 
5477 	/*
5478 	 * Walk through all upper (conn) streams and qenable
5479 	 * those that have queued data.
5480 	 * close synchronization needs this to
5481 	 * be done to ensure that all upper layers blocked
5482 	 * due to flow control to the closing device
5483 	 * get unblocked.
5484 	 */
5485 	ip1dbg(("ip_wsrv: walking\n"));
5486 	conn_walk_drain(ipst);
5487 
5488 	mutex_enter(&ipst->ips_ip_mi_lock);
5489 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5490 	mutex_exit(&ipst->ips_ip_mi_lock);
5491 
5492 	/*
5493 	 * credp could be null if the open didn't succeed and ip_modopen
5494 	 * itself calls ip_close.
5495 	 */
5496 	if (ill->ill_credp != NULL)
5497 		crfree(ill->ill_credp);
5498 
5499 	/*
5500 	 * Unhook the nic event message from the ill and enqueue it into the nic
5501 	 * event taskq.
5502 	 */
5503 	if ((info = ill->ill_nic_event_info) != NULL) {
5504 		if (ddi_taskq_dispatch(eventq_queue_nic,
5505 		    ip_ne_queue_func,
5506 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5507 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5508 			if (info->hne_data != NULL)
5509 				kmem_free(info->hne_data, info->hne_datalen);
5510 			kmem_free(info, sizeof (hook_nic_event_t));
5511 		}
5512 		ill->ill_nic_event_info = NULL;
5513 	}
5514 
5515 	/*
5516 	 * Now we are done with the module close pieces that
5517 	 * need the netstack_t.
5518 	 */
5519 	netstack_rele(ipst->ips_netstack);
5520 
5521 	mi_close_free((IDP)ill);
5522 	q->q_ptr = WR(q)->q_ptr = NULL;
5523 
5524 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5525 
5526 	return (0);
5527 }
5528 
5529 /*
5530  * This is called as part of close() for both IP and UDP
5531  * in order to quiesce the conn.
5532  */
5533 void
5534 ip_quiesce_conn(conn_t *connp)
5535 {
5536 	boolean_t	drain_cleanup_reqd = B_FALSE;
5537 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5538 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5539 	ip_stack_t	*ipst;
5540 
5541 	ASSERT(!IPCL_IS_TCP(connp));
5542 	ipst = connp->conn_netstack->netstack_ip;
5543 
5544 	/*
5545 	 * Mark the conn as closing, and this conn must not be
5546 	 * inserted in future into any list. Eg. conn_drain_insert(),
5547 	 * won't insert this conn into the conn_drain_list.
5548 	 * Similarly ill_pending_mp_add() will not add any mp to
5549 	 * the pending mp list, after this conn has started closing.
5550 	 *
5551 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5552 	 * cannot get set henceforth.
5553 	 */
5554 	mutex_enter(&connp->conn_lock);
5555 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5556 	connp->conn_state_flags |= CONN_CLOSING;
5557 	if (connp->conn_idl != NULL)
5558 		drain_cleanup_reqd = B_TRUE;
5559 	if (connp->conn_oper_pending_ill != NULL)
5560 		conn_ioctl_cleanup_reqd = B_TRUE;
5561 	if (connp->conn_ilg_inuse != 0)
5562 		ilg_cleanup_reqd = B_TRUE;
5563 	mutex_exit(&connp->conn_lock);
5564 
5565 	if (IPCL_IS_UDP(connp))
5566 		udp_quiesce_conn(connp);
5567 
5568 	if (conn_ioctl_cleanup_reqd)
5569 		conn_ioctl_cleanup(connp);
5570 
5571 	if (is_system_labeled() && connp->conn_anon_port) {
5572 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5573 		    connp->conn_mlp_type, connp->conn_ulp,
5574 		    ntohs(connp->conn_lport), B_FALSE);
5575 		connp->conn_anon_port = 0;
5576 	}
5577 	connp->conn_mlp_type = mlptSingle;
5578 
5579 	/*
5580 	 * Remove this conn from any fanout list it is on.
5581 	 * and then wait for any threads currently operating
5582 	 * on this endpoint to finish
5583 	 */
5584 	ipcl_hash_remove(connp);
5585 
5586 	/*
5587 	 * Remove this conn from the drain list, and do
5588 	 * any other cleanup that may be required.
5589 	 * (Only non-tcp streams may have a non-null conn_idl.
5590 	 * TCP streams are never flow controlled, and
5591 	 * conn_idl will be null)
5592 	 */
5593 	if (drain_cleanup_reqd)
5594 		conn_drain_tail(connp, B_TRUE);
5595 
5596 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5597 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5598 		(void) ip_mrouter_done(NULL, ipst);
5599 
5600 	if (ilg_cleanup_reqd)
5601 		ilg_delete_all(connp);
5602 
5603 	conn_delete_ire(connp, NULL);
5604 
5605 	/*
5606 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5607 	 * callers from write side can't be there now because close
5608 	 * is in progress. The only other caller is ipcl_walk
5609 	 * which checks for the condemned flag.
5610 	 */
5611 	mutex_enter(&connp->conn_lock);
5612 	connp->conn_state_flags |= CONN_CONDEMNED;
5613 	while (connp->conn_ref != 1)
5614 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5615 	connp->conn_state_flags |= CONN_QUIESCED;
5616 	mutex_exit(&connp->conn_lock);
5617 }
5618 
5619 /* ARGSUSED */
5620 int
5621 ip_close(queue_t *q, int flags)
5622 {
5623 	conn_t		*connp;
5624 
5625 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5626 
5627 	/*
5628 	 * Call the appropriate delete routine depending on whether this is
5629 	 * a module or device.
5630 	 */
5631 	if (WR(q)->q_next != NULL) {
5632 		/* This is a module close */
5633 		return (ip_modclose((ill_t *)q->q_ptr));
5634 	}
5635 
5636 	connp = q->q_ptr;
5637 	ip_quiesce_conn(connp);
5638 
5639 	qprocsoff(q);
5640 
5641 	/*
5642 	 * Now we are truly single threaded on this stream, and can
5643 	 * delete the things hanging off the connp, and finally the connp.
5644 	 * We removed this connp from the fanout list, it cannot be
5645 	 * accessed thru the fanouts, and we already waited for the
5646 	 * conn_ref to drop to 0. We are already in close, so
5647 	 * there cannot be any other thread from the top. qprocsoff
5648 	 * has completed, and service has completed or won't run in
5649 	 * future.
5650 	 */
5651 	ASSERT(connp->conn_ref == 1);
5652 
5653 	/*
5654 	 * A conn which was previously marked as IPCL_UDP cannot
5655 	 * retain the flag because it would have been cleared by
5656 	 * udp_close().
5657 	 */
5658 	ASSERT(!IPCL_IS_UDP(connp));
5659 
5660 	if (connp->conn_latch != NULL) {
5661 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5662 		connp->conn_latch = NULL;
5663 	}
5664 	if (connp->conn_policy != NULL) {
5665 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5666 		connp->conn_policy = NULL;
5667 	}
5668 	if (connp->conn_ipsec_opt_mp != NULL) {
5669 		freemsg(connp->conn_ipsec_opt_mp);
5670 		connp->conn_ipsec_opt_mp = NULL;
5671 	}
5672 
5673 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5674 
5675 	connp->conn_ref--;
5676 	ipcl_conn_destroy(connp);
5677 
5678 	q->q_ptr = WR(q)->q_ptr = NULL;
5679 	return (0);
5680 }
5681 
5682 int
5683 ip_snmpmod_close(queue_t *q)
5684 {
5685 	conn_t *connp = Q_TO_CONN(q);
5686 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5687 
5688 	qprocsoff(q);
5689 
5690 	if (connp->conn_flags & IPCL_UDPMOD)
5691 		udp_close_free(connp);
5692 
5693 	if (connp->conn_cred != NULL) {
5694 		crfree(connp->conn_cred);
5695 		connp->conn_cred = NULL;
5696 	}
5697 	CONN_DEC_REF(connp);
5698 	q->q_ptr = WR(q)->q_ptr = NULL;
5699 	return (0);
5700 }
5701 
5702 /*
5703  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5704  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5705  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5706  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5707  * queues as we never enqueue messages there and we don't handle any ioctls.
5708  * Everything else is freed.
5709  */
5710 void
5711 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5712 {
5713 	conn_t	*connp = q->q_ptr;
5714 	pfi_t	setfn;
5715 	pfi_t	getfn;
5716 
5717 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5718 
5719 	switch (DB_TYPE(mp)) {
5720 	case M_PROTO:
5721 	case M_PCPROTO:
5722 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5723 		    ((((union T_primitives *)mp->b_rptr)->type ==
5724 			T_SVR4_OPTMGMT_REQ) ||
5725 		    (((union T_primitives *)mp->b_rptr)->type ==
5726 			T_OPTMGMT_REQ))) {
5727 			/*
5728 			 * This is the only TPI primitive supported. Its
5729 			 * handling does not require tcp_t, but it does require
5730 			 * conn_t to check permissions.
5731 			 */
5732 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5733 
5734 			if (connp->conn_flags & IPCL_TCPMOD) {
5735 				setfn = tcp_snmp_set;
5736 				getfn = tcp_snmp_get;
5737 			} else {
5738 				setfn = udp_snmp_set;
5739 				getfn = udp_snmp_get;
5740 			}
5741 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5742 				freemsg(mp);
5743 				return;
5744 			}
5745 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5746 		    != NULL)
5747 			qreply(q, mp);
5748 		break;
5749 	case M_FLUSH:
5750 	case M_IOCTL:
5751 		putnext(q, mp);
5752 		break;
5753 	default:
5754 		freemsg(mp);
5755 		break;
5756 	}
5757 }
5758 
5759 /* Return the IP checksum for the IP header at "iph". */
5760 uint16_t
5761 ip_csum_hdr(ipha_t *ipha)
5762 {
5763 	uint16_t	*uph;
5764 	uint32_t	sum;
5765 	int		opt_len;
5766 
5767 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5768 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5769 	uph = (uint16_t *)ipha;
5770 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5771 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5772 	if (opt_len > 0) {
5773 		do {
5774 			sum += uph[10];
5775 			sum += uph[11];
5776 			uph += 2;
5777 		} while (--opt_len);
5778 	}
5779 	sum = (sum & 0xFFFF) + (sum >> 16);
5780 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5781 	if (sum == 0xffff)
5782 		sum = 0;
5783 	return ((uint16_t)sum);
5784 }
5785 
5786 /*
5787  * Called when the module is about to be unloaded
5788  */
5789 void
5790 ip_ddi_destroy(void)
5791 {
5792 	tnet_fini();
5793 
5794 	sctp_ddi_g_destroy();
5795 	tcp_ddi_g_destroy();
5796 	ipsec_policy_g_destroy();
5797 	ipcl_g_destroy();
5798 	ip_net_g_destroy();
5799 	ip_ire_g_fini();
5800 	inet_minor_destroy(ip_minor_arena);
5801 
5802 	netstack_unregister(NS_IP);
5803 }
5804 
5805 /*
5806  * First step in cleanup.
5807  */
5808 /* ARGSUSED */
5809 static void
5810 ip_stack_shutdown(netstackid_t stackid, void *arg)
5811 {
5812 	ip_stack_t *ipst = (ip_stack_t *)arg;
5813 
5814 #ifdef NS_DEBUG
5815 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5816 #endif
5817 
5818 	/* Get rid of loopback interfaces and their IREs */
5819 	ip_loopback_cleanup(ipst);
5820 }
5821 
5822 /*
5823  * Free the IP stack instance.
5824  */
5825 static void
5826 ip_stack_fini(netstackid_t stackid, void *arg)
5827 {
5828 	ip_stack_t *ipst = (ip_stack_t *)arg;
5829 	int ret;
5830 
5831 #ifdef NS_DEBUG
5832 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5833 #endif
5834 	ipv4_hook_destroy(ipst);
5835 	ipv6_hook_destroy(ipst);
5836 	ip_net_destroy(ipst);
5837 
5838 	rw_destroy(&ipst->ips_srcid_lock);
5839 
5840 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5841 	ipst->ips_ip_mibkp = NULL;
5842 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5843 	ipst->ips_icmp_mibkp = NULL;
5844 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5845 	ipst->ips_ip_kstat = NULL;
5846 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5847 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5848 	ipst->ips_ip6_kstat = NULL;
5849 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5850 
5851 	nd_free(&ipst->ips_ip_g_nd);
5852 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5853 	ipst->ips_param_arr = NULL;
5854 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5855 	ipst->ips_ndp_arr = NULL;
5856 
5857 	ip_mrouter_stack_destroy(ipst);
5858 
5859 	mutex_destroy(&ipst->ips_ip_mi_lock);
5860 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5861 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5862 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5863 
5864 	ret = untimeout(ipst->ips_igmp_timeout_id);
5865 	if (ret == -1) {
5866 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5867 	} else {
5868 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5869 		ipst->ips_igmp_timeout_id = 0;
5870 	}
5871 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5872 	if (ret == -1) {
5873 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5874 	} else {
5875 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5876 		ipst->ips_igmp_slowtimeout_id = 0;
5877 	}
5878 	ret = untimeout(ipst->ips_mld_timeout_id);
5879 	if (ret == -1) {
5880 		ASSERT(ipst->ips_mld_timeout_id == 0);
5881 	} else {
5882 		ASSERT(ipst->ips_mld_timeout_id != 0);
5883 		ipst->ips_mld_timeout_id = 0;
5884 	}
5885 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5886 	if (ret == -1) {
5887 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5888 	} else {
5889 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5890 		ipst->ips_mld_slowtimeout_id = 0;
5891 	}
5892 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5893 	if (ret == -1) {
5894 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5895 	} else {
5896 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5897 		ipst->ips_ip_ire_expire_id = 0;
5898 	}
5899 
5900 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5901 	mutex_destroy(&ipst->ips_mld_timer_lock);
5902 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5903 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5904 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5905 	rw_destroy(&ipst->ips_ill_g_lock);
5906 
5907 	ip_ire_fini(ipst);
5908 	ip6_asp_free(ipst);
5909 	conn_drain_fini(ipst);
5910 	ipcl_destroy(ipst);
5911 
5912 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5913 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5914 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5915 	ipst->ips_ndp4 = NULL;
5916 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5917 	ipst->ips_ndp6 = NULL;
5918 
5919 	if (ipst->ips_loopback_ksp != NULL) {
5920 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5921 		ipst->ips_loopback_ksp = NULL;
5922 	}
5923 
5924 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5925 	ipst->ips_phyint_g_list = NULL;
5926 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5927 	ipst->ips_ill_g_heads = NULL;
5928 
5929 	kmem_free(ipst, sizeof (*ipst));
5930 }
5931 
5932 /*
5933  * Called when the IP kernel module is loaded into the kernel
5934  */
5935 void
5936 ip_ddi_init(void)
5937 {
5938 	TCP6_MAJ = ddi_name_to_major(TCP6);
5939 	TCP_MAJ	= ddi_name_to_major(TCP);
5940 	SCTP_MAJ = ddi_name_to_major(SCTP);
5941 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5942 
5943 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5944 
5945 	/*
5946 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5947 	 * initial devices: ip, ip6, tcp, tcp6.
5948 	 */
5949 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5950 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5951 		cmn_err(CE_PANIC,
5952 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5953 	}
5954 
5955 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5956 
5957 	ipcl_g_init();
5958 	ip_ire_g_init();
5959 	ip_net_g_init();
5960 
5961 	/*
5962 	 * We want to be informed each time a stack is created or
5963 	 * destroyed in the kernel, so we can maintain the
5964 	 * set of udp_stack_t's.
5965 	 */
5966 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5967 	    ip_stack_fini);
5968 
5969 	ipsec_policy_g_init();
5970 	tcp_ddi_g_init();
5971 	sctp_ddi_g_init();
5972 
5973 	tnet_init();
5974 }
5975 
5976 /*
5977  * Initialize the IP stack instance.
5978  */
5979 static void *
5980 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5981 {
5982 	ip_stack_t	*ipst;
5983 	ipparam_t	*pa;
5984 	ipndp_t		*na;
5985 
5986 #ifdef NS_DEBUG
5987 	printf("ip_stack_init(stack %d)\n", stackid);
5988 #endif
5989 
5990 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5991 	ipst->ips_netstack = ns;
5992 
5993 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5994 	    KM_SLEEP);
5995 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5996 	    KM_SLEEP);
5997 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5998 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5999 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6000 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6001 
6002 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6003 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6004 	ipst->ips_igmp_deferred_next = INFINITY;
6005 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6006 	ipst->ips_mld_deferred_next = INFINITY;
6007 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6008 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6009 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6010 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6011 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6012 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6013 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6014 
6015 	ipcl_init(ipst);
6016 	ip_ire_init(ipst);
6017 	ip6_asp_init(ipst);
6018 	ipif_init(ipst);
6019 	conn_drain_init(ipst);
6020 	ip_mrouter_stack_init(ipst);
6021 
6022 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6023 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6024 
6025 	ipst->ips_ip_multirt_log_interval = 1000;
6026 
6027 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6028 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6029 	ipst->ips_ill_index = 1;
6030 
6031 	ipst->ips_saved_ip_g_forward = -1;
6032 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6033 
6034 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6035 	ipst->ips_param_arr = pa;
6036 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6037 
6038 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6039 	ipst->ips_ndp_arr = na;
6040 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6041 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6042 	    (caddr_t)&ipst->ips_ip_g_forward;
6043 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6044 	    (caddr_t)&ipst->ips_ipv6_forward;
6045 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6046 		"ip_cgtp_filter") == 0);
6047 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6048 	    (caddr_t)&ip_cgtp_filter;
6049 
6050 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6051 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6052 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6053 
6054 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6055 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6056 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6057 	ipst->ips_ip6_kstat =
6058 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6059 
6060 	ipst->ips_ipmp_enable_failback = B_TRUE;
6061 
6062 	ipst->ips_ip_src_id = 1;
6063 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6064 
6065 	ip_net_init(ipst, ns);
6066 	ipv4_hook_init(ipst);
6067 	ipv6_hook_init(ipst);
6068 
6069 	return (ipst);
6070 }
6071 
6072 /*
6073  * Allocate and initialize a DLPI template of the specified length.  (May be
6074  * called as writer.)
6075  */
6076 mblk_t *
6077 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6078 {
6079 	mblk_t	*mp;
6080 
6081 	mp = allocb(len, BPRI_MED);
6082 	if (!mp)
6083 		return (NULL);
6084 
6085 	/*
6086 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6087 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6088 	 * that other DLPI are M_PROTO.
6089 	 */
6090 	if (prim == DL_INFO_REQ) {
6091 		mp->b_datap->db_type = M_PCPROTO;
6092 	} else {
6093 		mp->b_datap->db_type = M_PROTO;
6094 	}
6095 
6096 	mp->b_wptr = mp->b_rptr + len;
6097 	bzero(mp->b_rptr, len);
6098 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6099 	return (mp);
6100 }
6101 
6102 const char *
6103 dlpi_prim_str(int prim)
6104 {
6105 	switch (prim) {
6106 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6107 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6108 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6109 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6110 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6111 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6112 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6113 	case DL_OK_ACK:		return ("DL_OK_ACK");
6114 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6115 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6116 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6117 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6118 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6119 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6120 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6121 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6122 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6123 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6124 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6125 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6126 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6127 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6128 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6129 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6130 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6131 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6132 	default:		return ("<unknown primitive>");
6133 	}
6134 }
6135 
6136 const char *
6137 dlpi_err_str(int err)
6138 {
6139 	switch (err) {
6140 	case DL_ACCESS:		return ("DL_ACCESS");
6141 	case DL_BADADDR:	return ("DL_BADADDR");
6142 	case DL_BADCORR:	return ("DL_BADCORR");
6143 	case DL_BADDATA:	return ("DL_BADDATA");
6144 	case DL_BADPPA:		return ("DL_BADPPA");
6145 	case DL_BADPRIM:	return ("DL_BADPRIM");
6146 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6147 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6148 	case DL_BADSAP:		return ("DL_BADSAP");
6149 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6150 	case DL_BOUND:		return ("DL_BOUND");
6151 	case DL_INITFAILED:	return ("DL_INITFAILED");
6152 	case DL_NOADDR:		return ("DL_NOADDR");
6153 	case DL_NOTINIT:	return ("DL_NOTINIT");
6154 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6155 	case DL_SYSERR:		return ("DL_SYSERR");
6156 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6157 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6158 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6159 	case DL_TOOMANY:	return ("DL_TOOMANY");
6160 	case DL_NOTENAB:	return ("DL_NOTENAB");
6161 	case DL_BUSY:		return ("DL_BUSY");
6162 	case DL_NOAUTO:		return ("DL_NOAUTO");
6163 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6164 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6165 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6166 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6167 	case DL_PENDING:	return ("DL_PENDING");
6168 	default:		return ("<unknown error>");
6169 	}
6170 }
6171 
6172 /*
6173  * Debug formatting routine.  Returns a character string representation of the
6174  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6175  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6176  *
6177  * Once the ndd table-printing interfaces are removed, this can be changed to
6178  * standard dotted-decimal form.
6179  */
6180 char *
6181 ip_dot_addr(ipaddr_t addr, char *buf)
6182 {
6183 	uint8_t *ap = (uint8_t *)&addr;
6184 
6185 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6186 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6187 	return (buf);
6188 }
6189 
6190 /*
6191  * Write the given MAC address as a printable string in the usual colon-
6192  * separated format.
6193  */
6194 const char *
6195 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6196 {
6197 	char *bp;
6198 
6199 	if (alen == 0 || buflen < 4)
6200 		return ("?");
6201 	bp = buf;
6202 	for (;;) {
6203 		/*
6204 		 * If there are more MAC address bytes available, but we won't
6205 		 * have any room to print them, then add "..." to the string
6206 		 * instead.  See below for the 'magic number' explanation.
6207 		 */
6208 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6209 			(void) strcpy(bp, "...");
6210 			break;
6211 		}
6212 		(void) sprintf(bp, "%02x", *addr++);
6213 		bp += 2;
6214 		if (--alen == 0)
6215 			break;
6216 		*bp++ = ':';
6217 		buflen -= 3;
6218 		/*
6219 		 * At this point, based on the first 'if' statement above,
6220 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6221 		 * buflen >= 4.  The first case leaves room for the final "xx"
6222 		 * number and trailing NUL byte.  The second leaves room for at
6223 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6224 		 * that statement.
6225 		 */
6226 	}
6227 	return (buf);
6228 }
6229 
6230 /*
6231  * Send an ICMP error after patching up the packet appropriately.  Returns
6232  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6233  */
6234 static boolean_t
6235 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6236     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6237     zoneid_t zoneid, ip_stack_t *ipst)
6238 {
6239 	ipha_t *ipha;
6240 	mblk_t *first_mp;
6241 	boolean_t secure;
6242 	unsigned char db_type;
6243 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6244 
6245 	first_mp = mp;
6246 	if (mctl_present) {
6247 		mp = mp->b_cont;
6248 		secure = ipsec_in_is_secure(first_mp);
6249 		ASSERT(mp != NULL);
6250 	} else {
6251 		/*
6252 		 * If this is an ICMP error being reported - which goes
6253 		 * up as M_CTLs, we need to convert them to M_DATA till
6254 		 * we finish checking with global policy because
6255 		 * ipsec_check_global_policy() assumes M_DATA as clear
6256 		 * and M_CTL as secure.
6257 		 */
6258 		db_type = DB_TYPE(mp);
6259 		DB_TYPE(mp) = M_DATA;
6260 		secure = B_FALSE;
6261 	}
6262 	/*
6263 	 * We are generating an icmp error for some inbound packet.
6264 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6265 	 * Before we generate an error, check with global policy
6266 	 * to see whether this is allowed to enter the system. As
6267 	 * there is no "conn", we are checking with global policy.
6268 	 */
6269 	ipha = (ipha_t *)mp->b_rptr;
6270 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6271 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6272 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6273 		if (first_mp == NULL)
6274 			return (B_FALSE);
6275 	}
6276 
6277 	if (!mctl_present)
6278 		DB_TYPE(mp) = db_type;
6279 
6280 	if (flags & IP_FF_SEND_ICMP) {
6281 		if (flags & IP_FF_HDR_COMPLETE) {
6282 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6283 				freemsg(first_mp);
6284 				return (B_TRUE);
6285 			}
6286 		}
6287 		if (flags & IP_FF_CKSUM) {
6288 			/*
6289 			 * Have to correct checksum since
6290 			 * the packet might have been
6291 			 * fragmented and the reassembly code in ip_rput
6292 			 * does not restore the IP checksum.
6293 			 */
6294 			ipha->ipha_hdr_checksum = 0;
6295 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6296 		}
6297 		switch (icmp_type) {
6298 		case ICMP_DEST_UNREACHABLE:
6299 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6300 			    ipst);
6301 			break;
6302 		default:
6303 			freemsg(first_mp);
6304 			break;
6305 		}
6306 	} else {
6307 		freemsg(first_mp);
6308 		return (B_FALSE);
6309 	}
6310 
6311 	return (B_TRUE);
6312 }
6313 
6314 /*
6315  * Used to send an ICMP error message when a packet is received for
6316  * a protocol that is not supported. The mblk passed as argument
6317  * is consumed by this function.
6318  */
6319 void
6320 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6321     ip_stack_t *ipst)
6322 {
6323 	mblk_t *mp;
6324 	ipha_t *ipha;
6325 	ill_t *ill;
6326 	ipsec_in_t *ii;
6327 
6328 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6329 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6330 
6331 	mp = ipsec_mp->b_cont;
6332 	ipsec_mp->b_cont = NULL;
6333 	ipha = (ipha_t *)mp->b_rptr;
6334 	/* Get ill from index in ipsec_in_t. */
6335 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6336 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6337 	    ipst);
6338 	if (ill != NULL) {
6339 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6340 			if (ip_fanout_send_icmp(q, mp, flags,
6341 			    ICMP_DEST_UNREACHABLE,
6342 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6343 				BUMP_MIB(ill->ill_ip_mib,
6344 				    ipIfStatsInUnknownProtos);
6345 			}
6346 		} else {
6347 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6348 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6349 			    0, B_FALSE, zoneid, ipst)) {
6350 				BUMP_MIB(ill->ill_ip_mib,
6351 				    ipIfStatsInUnknownProtos);
6352 			}
6353 		}
6354 		ill_refrele(ill);
6355 	} else { /* re-link for the freemsg() below. */
6356 		ipsec_mp->b_cont = mp;
6357 	}
6358 
6359 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6360 	freemsg(ipsec_mp);
6361 }
6362 
6363 /*
6364  * See if the inbound datagram has had IPsec processing applied to it.
6365  */
6366 boolean_t
6367 ipsec_in_is_secure(mblk_t *ipsec_mp)
6368 {
6369 	ipsec_in_t *ii;
6370 
6371 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6372 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6373 
6374 	if (ii->ipsec_in_loopback) {
6375 		return (ii->ipsec_in_secure);
6376 	} else {
6377 		return (ii->ipsec_in_ah_sa != NULL ||
6378 		    ii->ipsec_in_esp_sa != NULL ||
6379 		    ii->ipsec_in_decaps);
6380 	}
6381 }
6382 
6383 /*
6384  * Handle protocols with which IP is less intimate.  There
6385  * can be more than one stream bound to a particular
6386  * protocol.  When this is the case, normally each one gets a copy
6387  * of any incoming packets.
6388  *
6389  * IPSEC NOTE :
6390  *
6391  * Don't allow a secure packet going up a non-secure connection.
6392  * We don't allow this because
6393  *
6394  * 1) Reply might go out in clear which will be dropped at
6395  *    the sending side.
6396  * 2) If the reply goes out in clear it will give the
6397  *    adversary enough information for getting the key in
6398  *    most of the cases.
6399  *
6400  * Moreover getting a secure packet when we expect clear
6401  * implies that SA's were added without checking for
6402  * policy on both ends. This should not happen once ISAKMP
6403  * is used to negotiate SAs as SAs will be added only after
6404  * verifying the policy.
6405  *
6406  * NOTE : If the packet was tunneled and not multicast we only send
6407  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6408  * back to delivering packets to AF_INET6 raw sockets.
6409  *
6410  * IPQoS Notes:
6411  * Once we have determined the client, invoke IPPF processing.
6412  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6413  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6414  * ip_policy will be false.
6415  *
6416  * Zones notes:
6417  * Currently only applications in the global zone can create raw sockets for
6418  * protocols other than ICMP. So unlike the broadcast / multicast case of
6419  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6420  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6421  */
6422 static void
6423 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6424     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6425     zoneid_t zoneid)
6426 {
6427 	queue_t	*rq;
6428 	mblk_t	*mp1, *first_mp1;
6429 	uint_t	protocol = ipha->ipha_protocol;
6430 	ipaddr_t dst;
6431 	boolean_t one_only;
6432 	mblk_t *first_mp = mp;
6433 	boolean_t secure;
6434 	uint32_t ill_index;
6435 	conn_t	*connp, *first_connp, *next_connp;
6436 	connf_t	*connfp;
6437 	boolean_t shared_addr;
6438 	mib2_ipIfStatsEntry_t *mibptr;
6439 	ip_stack_t *ipst = recv_ill->ill_ipst;
6440 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6441 
6442 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6443 	if (mctl_present) {
6444 		mp = first_mp->b_cont;
6445 		secure = ipsec_in_is_secure(first_mp);
6446 		ASSERT(mp != NULL);
6447 	} else {
6448 		secure = B_FALSE;
6449 	}
6450 	dst = ipha->ipha_dst;
6451 	/*
6452 	 * If the packet was tunneled and not multicast we only send to it
6453 	 * the first match.
6454 	 */
6455 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6456 	    !CLASSD(dst));
6457 
6458 	shared_addr = (zoneid == ALL_ZONES);
6459 	if (shared_addr) {
6460 		/*
6461 		 * We don't allow multilevel ports for raw IP, so no need to
6462 		 * check for that here.
6463 		 */
6464 		zoneid = tsol_packet_to_zoneid(mp);
6465 	}
6466 
6467 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6468 	mutex_enter(&connfp->connf_lock);
6469 	connp = connfp->connf_head;
6470 	for (connp = connfp->connf_head; connp != NULL;
6471 		connp = connp->conn_next) {
6472 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6473 		    zoneid) &&
6474 		    (!is_system_labeled() ||
6475 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6476 		    connp)))
6477 			break;
6478 	}
6479 
6480 	if (connp == NULL || connp->conn_upq == NULL) {
6481 		/*
6482 		 * No one bound to these addresses.  Is
6483 		 * there a client that wants all
6484 		 * unclaimed datagrams?
6485 		 */
6486 		mutex_exit(&connfp->connf_lock);
6487 		/*
6488 		 * Check for IPPROTO_ENCAP...
6489 		 */
6490 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6491 			/*
6492 			 * If an IPsec mblk is here on a multicast
6493 			 * tunnel (using ip_mroute stuff), check policy here,
6494 			 * THEN ship off to ip_mroute_decap().
6495 			 *
6496 			 * BTW,  If I match a configured IP-in-IP
6497 			 * tunnel, this path will not be reached, and
6498 			 * ip_mroute_decap will never be called.
6499 			 */
6500 			first_mp = ipsec_check_global_policy(first_mp, connp,
6501 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6502 			if (first_mp != NULL) {
6503 				if (mctl_present)
6504 					freeb(first_mp);
6505 				ip_mroute_decap(q, mp, ill);
6506 			} /* Else we already freed everything! */
6507 		} else {
6508 			/*
6509 			 * Otherwise send an ICMP protocol unreachable.
6510 			 */
6511 			if (ip_fanout_send_icmp(q, first_mp, flags,
6512 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6513 			    mctl_present, zoneid, ipst)) {
6514 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6515 			}
6516 		}
6517 		return;
6518 	}
6519 	CONN_INC_REF(connp);
6520 	first_connp = connp;
6521 
6522 	/*
6523 	 * Only send message to one tunnel driver by immediately
6524 	 * terminating the loop.
6525 	 */
6526 	connp = one_only ? NULL : connp->conn_next;
6527 
6528 	for (;;) {
6529 		while (connp != NULL) {
6530 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6531 			    flags, zoneid) &&
6532 			    (!is_system_labeled() ||
6533 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6534 			    shared_addr, connp)))
6535 				break;
6536 			connp = connp->conn_next;
6537 		}
6538 
6539 		/*
6540 		 * Copy the packet.
6541 		 */
6542 		if (connp == NULL || connp->conn_upq == NULL ||
6543 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6544 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6545 			/*
6546 			 * No more interested clients or memory
6547 			 * allocation failed
6548 			 */
6549 			connp = first_connp;
6550 			break;
6551 		}
6552 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6553 		CONN_INC_REF(connp);
6554 		mutex_exit(&connfp->connf_lock);
6555 		rq = connp->conn_rq;
6556 		if (!canputnext(rq)) {
6557 			if (flags & IP_FF_RAWIP) {
6558 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6559 			} else {
6560 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6561 			}
6562 
6563 			freemsg(first_mp1);
6564 		} else {
6565 			/*
6566 			 * Don't enforce here if we're an actual tunnel -
6567 			 * let "tun" do it instead.
6568 			 */
6569 			if (!IPCL_IS_IPTUN(connp) &&
6570 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6571 			    secure)) {
6572 				first_mp1 = ipsec_check_inbound_policy
6573 				    (first_mp1, connp, ipha, NULL,
6574 				    mctl_present);
6575 			}
6576 			if (first_mp1 != NULL) {
6577 				int in_flags = 0;
6578 				/*
6579 				 * ip_fanout_proto also gets called from
6580 				 * icmp_inbound_error_fanout, in which case
6581 				 * the msg type is M_CTL.  Don't add info
6582 				 * in this case for the time being. In future
6583 				 * when there is a need for knowing the
6584 				 * inbound iface index for ICMP error msgs,
6585 				 * then this can be changed.
6586 				 */
6587 				if (connp->conn_recvif)
6588 					in_flags = IPF_RECVIF;
6589 				/*
6590 				 * The ULP may support IP_RECVPKTINFO for both
6591 				 * IP v4 and v6 so pass the appropriate argument
6592 				 * based on conn IP version.
6593 				 */
6594 				if (connp->conn_ip_recvpktinfo) {
6595 					if (connp->conn_af_isv6) {
6596 						/*
6597 						 * V6 only needs index
6598 						 */
6599 						in_flags |= IPF_RECVIF;
6600 					} else {
6601 						/*
6602 						 * V4 needs index +
6603 						 * matching address.
6604 						 */
6605 						in_flags |= IPF_RECVADDR;
6606 					}
6607 				}
6608 				if ((in_flags != 0) &&
6609 				    (mp->b_datap->db_type != M_CTL)) {
6610 					/*
6611 					 * the actual data will be
6612 					 * contained in b_cont upon
6613 					 * successful return of the
6614 					 * following call else
6615 					 * original mblk is returned
6616 					 */
6617 					ASSERT(recv_ill != NULL);
6618 					mp1 = ip_add_info(mp1, recv_ill,
6619 					    in_flags, IPCL_ZONEID(connp), ipst);
6620 				}
6621 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6622 				if (mctl_present)
6623 					freeb(first_mp1);
6624 				putnext(rq, mp1);
6625 			}
6626 		}
6627 		mutex_enter(&connfp->connf_lock);
6628 		/* Follow the next pointer before releasing the conn. */
6629 		next_connp = connp->conn_next;
6630 		CONN_DEC_REF(connp);
6631 		connp = next_connp;
6632 	}
6633 
6634 	/* Last one.  Send it upstream. */
6635 	mutex_exit(&connfp->connf_lock);
6636 
6637 	/*
6638 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6639 	 * will be set to false.
6640 	 */
6641 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6642 		ill_index = ill->ill_phyint->phyint_ifindex;
6643 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6644 		if (mp == NULL) {
6645 			CONN_DEC_REF(connp);
6646 			if (mctl_present) {
6647 				freeb(first_mp);
6648 			}
6649 			return;
6650 		}
6651 	}
6652 
6653 	rq = connp->conn_rq;
6654 	if (!canputnext(rq)) {
6655 		if (flags & IP_FF_RAWIP) {
6656 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6657 		} else {
6658 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6659 		}
6660 
6661 		freemsg(first_mp);
6662 	} else {
6663 		if (IPCL_IS_IPTUN(connp)) {
6664 			/*
6665 			 * Tunneled packet.  We enforce policy in the tunnel
6666 			 * module itself.
6667 			 *
6668 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6669 			 * a policy check.
6670 			 */
6671 			putnext(rq, first_mp);
6672 			CONN_DEC_REF(connp);
6673 			return;
6674 		}
6675 
6676 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6677 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6678 			    ipha, NULL, mctl_present);
6679 		}
6680 
6681 		if (first_mp != NULL) {
6682 			int in_flags = 0;
6683 
6684 			/*
6685 			 * ip_fanout_proto also gets called
6686 			 * from icmp_inbound_error_fanout, in
6687 			 * which case the msg type is M_CTL.
6688 			 * Don't add info in this case for time
6689 			 * being. In future when there is a
6690 			 * need for knowing the inbound iface
6691 			 * index for ICMP error msgs, then this
6692 			 * can be changed
6693 			 */
6694 			if (connp->conn_recvif)
6695 				in_flags = IPF_RECVIF;
6696 			if (connp->conn_ip_recvpktinfo) {
6697 				if (connp->conn_af_isv6) {
6698 					/*
6699 					 * V6 only needs index
6700 					 */
6701 					in_flags |= IPF_RECVIF;
6702 				} else {
6703 					/*
6704 					 * V4 needs index +
6705 					 * matching address.
6706 					 */
6707 					in_flags |= IPF_RECVADDR;
6708 				}
6709 			}
6710 			if ((in_flags != 0) &&
6711 			    (mp->b_datap->db_type != M_CTL)) {
6712 
6713 				/*
6714 				 * the actual data will be contained in
6715 				 * b_cont upon successful return
6716 				 * of the following call else original
6717 				 * mblk is returned
6718 				 */
6719 				ASSERT(recv_ill != NULL);
6720 				mp = ip_add_info(mp, recv_ill,
6721 				    in_flags, IPCL_ZONEID(connp), ipst);
6722 			}
6723 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6724 			putnext(rq, mp);
6725 			if (mctl_present)
6726 				freeb(first_mp);
6727 		}
6728 	}
6729 	CONN_DEC_REF(connp);
6730 }
6731 
6732 /*
6733  * Fanout for TCP packets
6734  * The caller puts <fport, lport> in the ports parameter.
6735  *
6736  * IPQoS Notes
6737  * Before sending it to the client, invoke IPPF processing.
6738  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6739  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6740  * ip_policy is false.
6741  */
6742 static void
6743 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6744     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6745 {
6746 	mblk_t  *first_mp;
6747 	boolean_t secure;
6748 	uint32_t ill_index;
6749 	int	ip_hdr_len;
6750 	tcph_t	*tcph;
6751 	boolean_t syn_present = B_FALSE;
6752 	conn_t	*connp;
6753 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6754 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6755 
6756 	ASSERT(recv_ill != NULL);
6757 
6758 	first_mp = mp;
6759 	if (mctl_present) {
6760 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6761 		mp = first_mp->b_cont;
6762 		secure = ipsec_in_is_secure(first_mp);
6763 		ASSERT(mp != NULL);
6764 	} else {
6765 		secure = B_FALSE;
6766 	}
6767 
6768 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6769 
6770 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6771 		    zoneid, ipst)) == NULL) {
6772 		/*
6773 		 * No connected connection or listener. Send a
6774 		 * TH_RST via tcp_xmit_listeners_reset.
6775 		 */
6776 
6777 		/* Initiate IPPf processing, if needed. */
6778 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6779 			uint32_t ill_index;
6780 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6781 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6782 			if (first_mp == NULL)
6783 				return;
6784 		}
6785 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6786 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6787 		    zoneid));
6788 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6789 		    ipst->ips_netstack->netstack_tcp);
6790 		return;
6791 	}
6792 
6793 	/*
6794 	 * Allocate the SYN for the TCP connection here itself
6795 	 */
6796 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6797 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6798 		if (IPCL_IS_TCP(connp)) {
6799 			squeue_t *sqp;
6800 
6801 			/*
6802 			 * For fused tcp loopback, assign the eager's
6803 			 * squeue to be that of the active connect's.
6804 			 * Note that we don't check for IP_FF_LOOPBACK
6805 			 * here since this routine gets called only
6806 			 * for loopback (unlike the IPv6 counterpart).
6807 			 */
6808 			ASSERT(Q_TO_CONN(q) != NULL);
6809 			if (do_tcp_fusion &&
6810 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6811 			    !secure &&
6812 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6813 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6814 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6815 				sqp = Q_TO_CONN(q)->conn_sqp;
6816 			} else {
6817 				sqp = IP_SQUEUE_GET(lbolt);
6818 			}
6819 
6820 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6821 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6822 			syn_present = B_TRUE;
6823 		}
6824 	}
6825 
6826 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6827 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6828 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6829 		if ((flags & TH_RST) || (flags & TH_URG)) {
6830 			CONN_DEC_REF(connp);
6831 			freemsg(first_mp);
6832 			return;
6833 		}
6834 		if (flags & TH_ACK) {
6835 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6836 			    ipst->ips_netstack->netstack_tcp);
6837 			CONN_DEC_REF(connp);
6838 			return;
6839 		}
6840 
6841 		CONN_DEC_REF(connp);
6842 		freemsg(first_mp);
6843 		return;
6844 	}
6845 
6846 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6847 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6848 		    NULL, mctl_present);
6849 		if (first_mp == NULL) {
6850 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6851 			CONN_DEC_REF(connp);
6852 			return;
6853 		}
6854 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6855 			ASSERT(syn_present);
6856 			if (mctl_present) {
6857 				ASSERT(first_mp != mp);
6858 				first_mp->b_datap->db_struioflag |=
6859 				    STRUIO_POLICY;
6860 			} else {
6861 				ASSERT(first_mp == mp);
6862 				mp->b_datap->db_struioflag &=
6863 				    ~STRUIO_EAGER;
6864 				mp->b_datap->db_struioflag |=
6865 				    STRUIO_POLICY;
6866 			}
6867 		} else {
6868 			/*
6869 			 * Discard first_mp early since we're dealing with a
6870 			 * fully-connected conn_t and tcp doesn't do policy in
6871 			 * this case.
6872 			 */
6873 			if (mctl_present) {
6874 				freeb(first_mp);
6875 				mctl_present = B_FALSE;
6876 			}
6877 			first_mp = mp;
6878 		}
6879 	}
6880 
6881 	/*
6882 	 * Initiate policy processing here if needed. If we get here from
6883 	 * icmp_inbound_error_fanout, ip_policy is false.
6884 	 */
6885 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6886 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6887 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6888 		if (mp == NULL) {
6889 			CONN_DEC_REF(connp);
6890 			if (mctl_present)
6891 				freeb(first_mp);
6892 			return;
6893 		} else if (mctl_present) {
6894 			ASSERT(first_mp != mp);
6895 			first_mp->b_cont = mp;
6896 		} else {
6897 			first_mp = mp;
6898 		}
6899 	}
6900 
6901 
6902 
6903 	/* Handle socket options. */
6904 	if (!syn_present &&
6905 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6906 		/* Add header */
6907 		ASSERT(recv_ill != NULL);
6908 		/*
6909 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6910 		 * IPF_RECVIF.
6911 		 */
6912 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6913 		    ipst);
6914 		if (mp == NULL) {
6915 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6916 			CONN_DEC_REF(connp);
6917 			if (mctl_present)
6918 				freeb(first_mp);
6919 			return;
6920 		} else if (mctl_present) {
6921 			/*
6922 			 * ip_add_info might return a new mp.
6923 			 */
6924 			ASSERT(first_mp != mp);
6925 			first_mp->b_cont = mp;
6926 		} else {
6927 			first_mp = mp;
6928 		}
6929 	}
6930 
6931 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6932 	if (IPCL_IS_TCP(connp)) {
6933 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6934 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6935 	} else {
6936 		putnext(connp->conn_rq, first_mp);
6937 		CONN_DEC_REF(connp);
6938 	}
6939 }
6940 
6941 /*
6942  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6943  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6944  * Caller is responsible for dropping references to the conn, and freeing
6945  * first_mp.
6946  *
6947  * IPQoS Notes
6948  * Before sending it to the client, invoke IPPF processing. Policy processing
6949  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6950  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6951  * ip_wput_local, ip_policy is false.
6952  */
6953 static void
6954 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6955     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6956     boolean_t ip_policy)
6957 {
6958 	boolean_t	mctl_present = (first_mp != NULL);
6959 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6960 	uint32_t	ill_index;
6961 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6962 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6963 
6964 	ASSERT(ill != NULL);
6965 
6966 	if (mctl_present)
6967 		first_mp->b_cont = mp;
6968 	else
6969 		first_mp = mp;
6970 
6971 	if (CONN_UDP_FLOWCTLD(connp)) {
6972 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6973 		freemsg(first_mp);
6974 		return;
6975 	}
6976 
6977 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6978 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6979 		    NULL, mctl_present);
6980 		if (first_mp == NULL) {
6981 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6982 			return;	/* Freed by ipsec_check_inbound_policy(). */
6983 		}
6984 	}
6985 	if (mctl_present)
6986 		freeb(first_mp);
6987 
6988 	/* Handle options. */
6989 	if (connp->conn_recvif)
6990 		in_flags = IPF_RECVIF;
6991 	/*
6992 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6993 	 * passed to ip_add_info is based on IP version of connp.
6994 	 */
6995 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6996 		if (connp->conn_af_isv6) {
6997 			/*
6998 			 * V6 only needs index
6999 			 */
7000 			in_flags |= IPF_RECVIF;
7001 		} else {
7002 			/*
7003 			 * V4 needs index + matching address.
7004 			 */
7005 			in_flags |= IPF_RECVADDR;
7006 		}
7007 	}
7008 
7009 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7010 		in_flags |= IPF_RECVSLLA;
7011 
7012 	/*
7013 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7014 	 * freed if the packet is dropped. The caller will do so.
7015 	 */
7016 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7017 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7018 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7019 		if (mp == NULL) {
7020 			return;
7021 		}
7022 	}
7023 	if ((in_flags != 0) &&
7024 	    (mp->b_datap->db_type != M_CTL)) {
7025 		/*
7026 		 * The actual data will be contained in b_cont
7027 		 * upon successful return of the following call
7028 		 * else original mblk is returned
7029 		 */
7030 		ASSERT(recv_ill != NULL);
7031 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7032 		    ipst);
7033 	}
7034 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7035 	/* Send it upstream */
7036 	CONN_UDP_RECV(connp, mp);
7037 }
7038 
7039 /*
7040  * Fanout for UDP packets.
7041  * The caller puts <fport, lport> in the ports parameter.
7042  *
7043  * If SO_REUSEADDR is set all multicast and broadcast packets
7044  * will be delivered to all streams bound to the same port.
7045  *
7046  * Zones notes:
7047  * Multicast and broadcast packets will be distributed to streams in all zones.
7048  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7049  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7050  * packets. To maintain this behavior with multiple zones, the conns are grouped
7051  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7052  * each zone. If unset, all the following conns in the same zone are skipped.
7053  */
7054 static void
7055 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7056     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7057     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7058 {
7059 	uint32_t	dstport, srcport;
7060 	ipaddr_t	dst;
7061 	mblk_t		*first_mp;
7062 	boolean_t	secure;
7063 	in6_addr_t	v6src;
7064 	conn_t		*connp;
7065 	connf_t		*connfp;
7066 	conn_t		*first_connp;
7067 	conn_t		*next_connp;
7068 	mblk_t		*mp1, *first_mp1;
7069 	ipaddr_t	src;
7070 	zoneid_t	last_zoneid;
7071 	boolean_t	reuseaddr;
7072 	boolean_t	shared_addr;
7073 	ip_stack_t	*ipst;
7074 
7075 	ASSERT(recv_ill != NULL);
7076 	ipst = recv_ill->ill_ipst;
7077 
7078 	first_mp = mp;
7079 	if (mctl_present) {
7080 		mp = first_mp->b_cont;
7081 		first_mp->b_cont = NULL;
7082 		secure = ipsec_in_is_secure(first_mp);
7083 		ASSERT(mp != NULL);
7084 	} else {
7085 		first_mp = NULL;
7086 		secure = B_FALSE;
7087 	}
7088 
7089 	/* Extract ports in net byte order */
7090 	dstport = htons(ntohl(ports) & 0xFFFF);
7091 	srcport = htons(ntohl(ports) >> 16);
7092 	dst = ipha->ipha_dst;
7093 	src = ipha->ipha_src;
7094 
7095 	shared_addr = (zoneid == ALL_ZONES);
7096 	if (shared_addr) {
7097 		/*
7098 		 * No need to handle exclusive-stack zones since ALL_ZONES
7099 		 * only applies to the shared stack.
7100 		 */
7101 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7102 		if (zoneid == ALL_ZONES)
7103 			zoneid = tsol_packet_to_zoneid(mp);
7104 	}
7105 
7106 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7107 	mutex_enter(&connfp->connf_lock);
7108 	connp = connfp->connf_head;
7109 	if (!broadcast && !CLASSD(dst)) {
7110 		/*
7111 		 * Not broadcast or multicast. Send to the one (first)
7112 		 * client we find. No need to check conn_wantpacket()
7113 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7114 		 * IPv4 unicast packets.
7115 		 */
7116 		while ((connp != NULL) &&
7117 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7118 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7119 			connp = connp->conn_next;
7120 		}
7121 
7122 		if (connp == NULL || connp->conn_upq == NULL)
7123 			goto notfound;
7124 
7125 		if (is_system_labeled() &&
7126 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7127 		    connp))
7128 			goto notfound;
7129 
7130 		CONN_INC_REF(connp);
7131 		mutex_exit(&connfp->connf_lock);
7132 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7133 		    flags, recv_ill, ip_policy);
7134 		IP_STAT(ipst, ip_udp_fannorm);
7135 		CONN_DEC_REF(connp);
7136 		return;
7137 	}
7138 
7139 	/*
7140 	 * Broadcast and multicast case
7141 	 *
7142 	 * Need to check conn_wantpacket().
7143 	 * If SO_REUSEADDR has been set on the first we send the
7144 	 * packet to all clients that have joined the group and
7145 	 * match the port.
7146 	 */
7147 
7148 	while (connp != NULL) {
7149 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7150 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7151 		    (!is_system_labeled() ||
7152 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7153 		    connp)))
7154 			break;
7155 		connp = connp->conn_next;
7156 	}
7157 
7158 	if (connp == NULL || connp->conn_upq == NULL)
7159 		goto notfound;
7160 
7161 	first_connp = connp;
7162 	/*
7163 	 * When SO_REUSEADDR is not set, send the packet only to the first
7164 	 * matching connection in its zone by keeping track of the zoneid.
7165 	 */
7166 	reuseaddr = first_connp->conn_reuseaddr;
7167 	last_zoneid = first_connp->conn_zoneid;
7168 
7169 	CONN_INC_REF(connp);
7170 	connp = connp->conn_next;
7171 	for (;;) {
7172 		while (connp != NULL) {
7173 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7174 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7175 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7176 			    (!is_system_labeled() ||
7177 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7178 			    shared_addr, connp)))
7179 				break;
7180 			connp = connp->conn_next;
7181 		}
7182 		/*
7183 		 * Just copy the data part alone. The mctl part is
7184 		 * needed just for verifying policy and it is never
7185 		 * sent up.
7186 		 */
7187 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7188 		    ((mp1 = copymsg(mp)) == NULL))) {
7189 			/*
7190 			 * No more interested clients or memory
7191 			 * allocation failed
7192 			 */
7193 			connp = first_connp;
7194 			break;
7195 		}
7196 		if (connp->conn_zoneid != last_zoneid) {
7197 			/*
7198 			 * Update the zoneid so that the packet isn't sent to
7199 			 * any more conns in the same zone unless SO_REUSEADDR
7200 			 * is set.
7201 			 */
7202 			reuseaddr = connp->conn_reuseaddr;
7203 			last_zoneid = connp->conn_zoneid;
7204 		}
7205 		if (first_mp != NULL) {
7206 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7207 			    ipsec_info_type == IPSEC_IN);
7208 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7209 			    ipst->ips_netstack);
7210 			if (first_mp1 == NULL) {
7211 				freemsg(mp1);
7212 				connp = first_connp;
7213 				break;
7214 			}
7215 		} else {
7216 			first_mp1 = NULL;
7217 		}
7218 		CONN_INC_REF(connp);
7219 		mutex_exit(&connfp->connf_lock);
7220 		/*
7221 		 * IPQoS notes: We don't send the packet for policy
7222 		 * processing here, will do it for the last one (below).
7223 		 * i.e. we do it per-packet now, but if we do policy
7224 		 * processing per-conn, then we would need to do it
7225 		 * here too.
7226 		 */
7227 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7228 		    ipha, flags, recv_ill, B_FALSE);
7229 		mutex_enter(&connfp->connf_lock);
7230 		/* Follow the next pointer before releasing the conn. */
7231 		next_connp = connp->conn_next;
7232 		IP_STAT(ipst, ip_udp_fanmb);
7233 		CONN_DEC_REF(connp);
7234 		connp = next_connp;
7235 	}
7236 
7237 	/* Last one.  Send it upstream. */
7238 	mutex_exit(&connfp->connf_lock);
7239 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7240 	    recv_ill, ip_policy);
7241 	IP_STAT(ipst, ip_udp_fanmb);
7242 	CONN_DEC_REF(connp);
7243 	return;
7244 
7245 notfound:
7246 
7247 	mutex_exit(&connfp->connf_lock);
7248 	IP_STAT(ipst, ip_udp_fanothers);
7249 	/*
7250 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7251 	 * have already been matched above, since they live in the IPv4
7252 	 * fanout tables. This implies we only need to
7253 	 * check for IPv6 in6addr_any endpoints here.
7254 	 * Thus we compare using ipv6_all_zeros instead of the destination
7255 	 * address, except for the multicast group membership lookup which
7256 	 * uses the IPv4 destination.
7257 	 */
7258 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7259 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7260 	mutex_enter(&connfp->connf_lock);
7261 	connp = connfp->connf_head;
7262 	if (!broadcast && !CLASSD(dst)) {
7263 		while (connp != NULL) {
7264 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7265 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7266 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7267 			    !connp->conn_ipv6_v6only)
7268 				break;
7269 			connp = connp->conn_next;
7270 		}
7271 
7272 		if (connp != NULL && is_system_labeled() &&
7273 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7274 		    connp))
7275 			connp = NULL;
7276 
7277 		if (connp == NULL || connp->conn_upq == NULL) {
7278 			/*
7279 			 * No one bound to this port.  Is
7280 			 * there a client that wants all
7281 			 * unclaimed datagrams?
7282 			 */
7283 			mutex_exit(&connfp->connf_lock);
7284 
7285 			if (mctl_present)
7286 				first_mp->b_cont = mp;
7287 			else
7288 				first_mp = mp;
7289 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7290 			    connf_head != NULL) {
7291 				ip_fanout_proto(q, first_mp, ill, ipha,
7292 				    flags | IP_FF_RAWIP, mctl_present,
7293 				    ip_policy, recv_ill, zoneid);
7294 			} else {
7295 				if (ip_fanout_send_icmp(q, first_mp, flags,
7296 				    ICMP_DEST_UNREACHABLE,
7297 				    ICMP_PORT_UNREACHABLE,
7298 				    mctl_present, zoneid, ipst)) {
7299 					BUMP_MIB(ill->ill_ip_mib,
7300 					    udpIfStatsNoPorts);
7301 				}
7302 			}
7303 			return;
7304 		}
7305 
7306 		CONN_INC_REF(connp);
7307 		mutex_exit(&connfp->connf_lock);
7308 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7309 		    flags, recv_ill, ip_policy);
7310 		CONN_DEC_REF(connp);
7311 		return;
7312 	}
7313 	/*
7314 	 * IPv4 multicast packet being delivered to an AF_INET6
7315 	 * in6addr_any endpoint.
7316 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7317 	 * and not conn_wantpacket_v6() since any multicast membership is
7318 	 * for an IPv4-mapped multicast address.
7319 	 * The packet is sent to all clients in all zones that have joined the
7320 	 * group and match the port.
7321 	 */
7322 	while (connp != NULL) {
7323 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7324 		    srcport, v6src) &&
7325 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7326 		    (!is_system_labeled() ||
7327 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7328 		    connp)))
7329 			break;
7330 		connp = connp->conn_next;
7331 	}
7332 
7333 	if (connp == NULL || connp->conn_upq == NULL) {
7334 		/*
7335 		 * No one bound to this port.  Is
7336 		 * there a client that wants all
7337 		 * unclaimed datagrams?
7338 		 */
7339 		mutex_exit(&connfp->connf_lock);
7340 
7341 		if (mctl_present)
7342 			first_mp->b_cont = mp;
7343 		else
7344 			first_mp = mp;
7345 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7346 		    NULL) {
7347 			ip_fanout_proto(q, first_mp, ill, ipha,
7348 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7349 			    recv_ill, zoneid);
7350 		} else {
7351 			/*
7352 			 * We used to attempt to send an icmp error here, but
7353 			 * since this is known to be a multicast packet
7354 			 * and we don't send icmp errors in response to
7355 			 * multicast, just drop the packet and give up sooner.
7356 			 */
7357 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7358 			freemsg(first_mp);
7359 		}
7360 		return;
7361 	}
7362 
7363 	first_connp = connp;
7364 
7365 	CONN_INC_REF(connp);
7366 	connp = connp->conn_next;
7367 	for (;;) {
7368 		while (connp != NULL) {
7369 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7370 			    ipv6_all_zeros, srcport, v6src) &&
7371 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7372 			    (!is_system_labeled() ||
7373 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7374 			    shared_addr, connp)))
7375 				break;
7376 			connp = connp->conn_next;
7377 		}
7378 		/*
7379 		 * Just copy the data part alone. The mctl part is
7380 		 * needed just for verifying policy and it is never
7381 		 * sent up.
7382 		 */
7383 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7384 		    ((mp1 = copymsg(mp)) == NULL))) {
7385 			/*
7386 			 * No more intested clients or memory
7387 			 * allocation failed
7388 			 */
7389 			connp = first_connp;
7390 			break;
7391 		}
7392 		if (first_mp != NULL) {
7393 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7394 			    ipsec_info_type == IPSEC_IN);
7395 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7396 			    ipst->ips_netstack);
7397 			if (first_mp1 == NULL) {
7398 				freemsg(mp1);
7399 				connp = first_connp;
7400 				break;
7401 			}
7402 		} else {
7403 			first_mp1 = NULL;
7404 		}
7405 		CONN_INC_REF(connp);
7406 		mutex_exit(&connfp->connf_lock);
7407 		/*
7408 		 * IPQoS notes: We don't send the packet for policy
7409 		 * processing here, will do it for the last one (below).
7410 		 * i.e. we do it per-packet now, but if we do policy
7411 		 * processing per-conn, then we would need to do it
7412 		 * here too.
7413 		 */
7414 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7415 		    ipha, flags, recv_ill, B_FALSE);
7416 		mutex_enter(&connfp->connf_lock);
7417 		/* Follow the next pointer before releasing the conn. */
7418 		next_connp = connp->conn_next;
7419 		CONN_DEC_REF(connp);
7420 		connp = next_connp;
7421 	}
7422 
7423 	/* Last one.  Send it upstream. */
7424 	mutex_exit(&connfp->connf_lock);
7425 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7426 	    recv_ill, ip_policy);
7427 	CONN_DEC_REF(connp);
7428 }
7429 
7430 /*
7431  * Complete the ip_wput header so that it
7432  * is possible to generate ICMP
7433  * errors.
7434  */
7435 int
7436 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7437 {
7438 	ire_t *ire;
7439 
7440 	if (ipha->ipha_src == INADDR_ANY) {
7441 		ire = ire_lookup_local(zoneid, ipst);
7442 		if (ire == NULL) {
7443 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7444 			return (1);
7445 		}
7446 		ipha->ipha_src = ire->ire_addr;
7447 		ire_refrele(ire);
7448 	}
7449 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7450 	ipha->ipha_hdr_checksum = 0;
7451 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7452 	return (0);
7453 }
7454 
7455 /*
7456  * Nobody should be sending
7457  * packets up this stream
7458  */
7459 static void
7460 ip_lrput(queue_t *q, mblk_t *mp)
7461 {
7462 	mblk_t *mp1;
7463 
7464 	switch (mp->b_datap->db_type) {
7465 	case M_FLUSH:
7466 		/* Turn around */
7467 		if (*mp->b_rptr & FLUSHW) {
7468 			*mp->b_rptr &= ~FLUSHR;
7469 			qreply(q, mp);
7470 			return;
7471 		}
7472 		break;
7473 	}
7474 	/* Could receive messages that passed through ar_rput */
7475 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7476 		mp1->b_prev = mp1->b_next = NULL;
7477 	freemsg(mp);
7478 }
7479 
7480 /* Nobody should be sending packets down this stream */
7481 /* ARGSUSED */
7482 void
7483 ip_lwput(queue_t *q, mblk_t *mp)
7484 {
7485 	freemsg(mp);
7486 }
7487 
7488 /*
7489  * Move the first hop in any source route to ipha_dst and remove that part of
7490  * the source route.  Called by other protocols.  Errors in option formatting
7491  * are ignored - will be handled by ip_wput_options Return the final
7492  * destination (either ipha_dst or the last entry in a source route.)
7493  */
7494 ipaddr_t
7495 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7496 {
7497 	ipoptp_t	opts;
7498 	uchar_t		*opt;
7499 	uint8_t		optval;
7500 	uint8_t		optlen;
7501 	ipaddr_t	dst;
7502 	int		i;
7503 	ire_t		*ire;
7504 	ip_stack_t	*ipst = ns->netstack_ip;
7505 
7506 	ip2dbg(("ip_massage_options\n"));
7507 	dst = ipha->ipha_dst;
7508 	for (optval = ipoptp_first(&opts, ipha);
7509 	    optval != IPOPT_EOL;
7510 	    optval = ipoptp_next(&opts)) {
7511 		opt = opts.ipoptp_cur;
7512 		switch (optval) {
7513 			uint8_t off;
7514 		case IPOPT_SSRR:
7515 		case IPOPT_LSRR:
7516 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7517 				ip1dbg(("ip_massage_options: bad src route\n"));
7518 				break;
7519 			}
7520 			optlen = opts.ipoptp_len;
7521 			off = opt[IPOPT_OFFSET];
7522 			off--;
7523 		redo_srr:
7524 			if (optlen < IP_ADDR_LEN ||
7525 			    off > optlen - IP_ADDR_LEN) {
7526 				/* End of source route */
7527 				ip1dbg(("ip_massage_options: end of SR\n"));
7528 				break;
7529 			}
7530 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7531 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7532 			    ntohl(dst)));
7533 			/*
7534 			 * Check if our address is present more than
7535 			 * once as consecutive hops in source route.
7536 			 * XXX verify per-interface ip_forwarding
7537 			 * for source route?
7538 			 */
7539 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7540 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7541 			if (ire != NULL) {
7542 				ire_refrele(ire);
7543 				off += IP_ADDR_LEN;
7544 				goto redo_srr;
7545 			}
7546 			if (dst == htonl(INADDR_LOOPBACK)) {
7547 				ip1dbg(("ip_massage_options: loopback addr in "
7548 				    "source route!\n"));
7549 				break;
7550 			}
7551 			/*
7552 			 * Update ipha_dst to be the first hop and remove the
7553 			 * first hop from the source route (by overwriting
7554 			 * part of the option with NOP options).
7555 			 */
7556 			ipha->ipha_dst = dst;
7557 			/* Put the last entry in dst */
7558 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7559 			    3;
7560 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7561 
7562 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7563 			    ntohl(dst)));
7564 			/* Move down and overwrite */
7565 			opt[IP_ADDR_LEN] = opt[0];
7566 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7567 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7568 			for (i = 0; i < IP_ADDR_LEN; i++)
7569 				opt[i] = IPOPT_NOP;
7570 			break;
7571 		}
7572 	}
7573 	return (dst);
7574 }
7575 
7576 /*
7577  * This function's job is to forward data to the reverse tunnel (FA->HA)
7578  * after doing a few checks. It is assumed that the incoming interface
7579  * of the packet is always different than the outgoing interface and the
7580  * ire_type of the found ire has to be a non-resolver type.
7581  *
7582  * IPQoS notes
7583  * IP policy is invoked twice for a forwarded packet, once on the read side
7584  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7585  * enabled.
7586  */
7587 static void
7588 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7589 {
7590 	ipha_t		*ipha;
7591 	queue_t		*q;
7592 	uint32_t 	pkt_len;
7593 #define	rptr    ((uchar_t *)ipha)
7594 	uint32_t 	sum;
7595 	uint32_t 	max_frag;
7596 	mblk_t		*first_mp;
7597 	uint32_t	ill_index;
7598 	ipxmit_state_t	pktxmit_state;
7599 	ill_t		*out_ill;
7600 	ip_stack_t	*ipst = in_ill->ill_ipst;
7601 
7602 	ASSERT(ire != NULL);
7603 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7604 	ASSERT(ire->ire_stq != NULL);
7605 
7606 	/* Initiate read side IPPF processing */
7607 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
7608 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7609 		ip_process(IPP_FWD_IN, &mp, ill_index);
7610 		if (mp == NULL) {
7611 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7612 			    "dropped during IPPF processing\n"));
7613 			return;
7614 		}
7615 	}
7616 
7617 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7618 		ILLF_ROUTER) == 0) ||
7619 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7620 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7621 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7622 		    "forwarding is not turned on\n"));
7623 		goto drop_pkt;
7624 	}
7625 
7626 	/*
7627 	 * Don't forward if the interface is down
7628 	 */
7629 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7630 		goto discard_pkt;
7631 	}
7632 
7633 	ipha = (ipha_t *)mp->b_rptr;
7634 	pkt_len = ntohs(ipha->ipha_length);
7635 	/* Adjust the checksum to reflect the ttl decrement. */
7636 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7637 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7638 	if (ipha->ipha_ttl-- <= 1) {
7639 		if (ip_csum_hdr(ipha)) {
7640 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7641 			goto drop_pkt;
7642 		}
7643 		q = ire->ire_stq;
7644 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7645 		    BPRI_HI)) == NULL) {
7646 			goto discard_pkt;
7647 		}
7648 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7649 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7650 		/* Sent by forwarding path, and router is global zone */
7651 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7652 		    GLOBAL_ZONEID, ipst);
7653 		return;
7654 	}
7655 
7656 	/* Get the ill_index of the ILL */
7657 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7658 
7659 	/*
7660 	 * This location is chosen for the placement of the forwarding hook
7661 	 * because at this point we know that we have a path out for the
7662 	 * packet but haven't yet applied any logic (such as fragmenting)
7663 	 * that happen as part of transmitting the packet out.
7664 	 */
7665 	out_ill = ire->ire_ipif->ipif_ill;
7666 
7667 	DTRACE_PROBE4(ip4__forwarding__start,
7668 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7669 
7670 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
7671 	    ipst->ips_ipv4firewall_forwarding,
7672 	    in_ill, out_ill, ipha, mp, mp, ipst);
7673 
7674 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7675 
7676 	if (mp == NULL)
7677 		return;
7678 	pkt_len = ntohs(ipha->ipha_length);
7679 
7680 	/*
7681 	 * ip_mrtun_forward is only used by foreign agent to reverse
7682 	 * tunnel the incoming packet. So it does not do any option
7683 	 * processing for source routing.
7684 	 */
7685 	max_frag = ire->ire_max_frag;
7686 	if (pkt_len > max_frag) {
7687 		/*
7688 		 * It needs fragging on its way out.  We haven't
7689 		 * verified the header checksum yet.  Since we
7690 		 * are going to put a surely good checksum in the
7691 		 * outgoing header, we have to make sure that it
7692 		 * was good coming in.
7693 		 */
7694 		if (ip_csum_hdr(ipha)) {
7695 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7696 			goto drop_pkt;
7697 		}
7698 
7699 		/* Initiate write side IPPF processing */
7700 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
7701 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7702 			if (mp == NULL) {
7703 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7704 				    "dropped/deferred during ip policy "\
7705 				    "processing\n"));
7706 				return;
7707 			}
7708 		}
7709 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7710 		    BPRI_HI)) == NULL) {
7711 			goto discard_pkt;
7712 		}
7713 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7714 		mp = first_mp;
7715 
7716 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
7717 		return;
7718 	}
7719 
7720 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7721 
7722 	ASSERT(ire->ire_ipif != NULL);
7723 
7724 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7725 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7726 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
7727 	    ipst->ips_ipv4firewall_physical_out,
7728 	    NULL, out_ill, ipha, mp, mp, ipst);
7729 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7730 	if (mp == NULL)
7731 		return;
7732 
7733 	/* Now send the packet to the tunnel interface */
7734 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7735 	q = ire->ire_stq;
7736 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7737 	if ((pktxmit_state == SEND_FAILED) ||
7738 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7739 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7740 		    q->q_ptr));
7741 	}
7742 
7743 	return;
7744 discard_pkt:
7745 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7746 drop_pkt:;
7747 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7748 	freemsg(mp);
7749 #undef	rptr
7750 }
7751 
7752 /*
7753  * Fills the ipsec_out_t data structure with appropriate fields and
7754  * prepends it to mp which contains the IP hdr + data that was meant
7755  * to be forwarded. Please note that ipsec_out_info data structure
7756  * is used here to communicate the outgoing ill path at ip_wput()
7757  * for the ICMP error packet. This has nothing to do with ipsec IP
7758  * security. ipsec_out_t is really used to pass the info to the module
7759  * IP where this information cannot be extracted from conn.
7760  * This functions is called by ip_mrtun_forward().
7761  */
7762 void
7763 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7764 {
7765 	ipsec_out_t	*io;
7766 
7767 	ASSERT(xmit_ill != NULL);
7768 	first_mp->b_datap->db_type = M_CTL;
7769 	first_mp->b_wptr += sizeof (ipsec_info_t);
7770 	/*
7771 	 * This is to pass info to ip_wput in absence of conn.
7772 	 * ipsec_out_secure will be B_FALSE because of this.
7773 	 * Thus ipsec_out_secure being B_FALSE indicates that
7774 	 * this is not IPSEC security related information.
7775 	 */
7776 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7777 	io = (ipsec_out_t *)first_mp->b_rptr;
7778 	io->ipsec_out_type = IPSEC_OUT;
7779 	io->ipsec_out_len = sizeof (ipsec_out_t);
7780 	first_mp->b_cont = mp;
7781 	io->ipsec_out_ill_index =
7782 	    xmit_ill->ill_phyint->phyint_ifindex;
7783 	io->ipsec_out_xmit_if = B_TRUE;
7784 	io->ipsec_out_ns = xmit_ill->ill_ipst->ips_netstack;
7785 }
7786 
7787 /*
7788  * Return the network mask
7789  * associated with the specified address.
7790  */
7791 ipaddr_t
7792 ip_net_mask(ipaddr_t addr)
7793 {
7794 	uchar_t	*up = (uchar_t *)&addr;
7795 	ipaddr_t mask = 0;
7796 	uchar_t	*maskp = (uchar_t *)&mask;
7797 
7798 #if defined(__i386) || defined(__amd64)
7799 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7800 #endif
7801 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7802 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7803 #endif
7804 	if (CLASSD(addr)) {
7805 		maskp[0] = 0xF0;
7806 		return (mask);
7807 	}
7808 	if (addr == 0)
7809 		return (0);
7810 	maskp[0] = 0xFF;
7811 	if ((up[0] & 0x80) == 0)
7812 		return (mask);
7813 
7814 	maskp[1] = 0xFF;
7815 	if ((up[0] & 0xC0) == 0x80)
7816 		return (mask);
7817 
7818 	maskp[2] = 0xFF;
7819 	if ((up[0] & 0xE0) == 0xC0)
7820 		return (mask);
7821 
7822 	/* Must be experimental or multicast, indicate as much */
7823 	return ((ipaddr_t)0);
7824 }
7825 
7826 /*
7827  * Select an ill for the packet by considering load spreading across
7828  * a different ill in the group if dst_ill is part of some group.
7829  */
7830 ill_t *
7831 ip_newroute_get_dst_ill(ill_t *dst_ill)
7832 {
7833 	ill_t *ill;
7834 
7835 	/*
7836 	 * We schedule irrespective of whether the source address is
7837 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7838 	 */
7839 	ill = illgrp_scheduler(dst_ill);
7840 	if (ill == NULL)
7841 		return (NULL);
7842 
7843 	/*
7844 	 * For groups with names ip_sioctl_groupname ensures that all
7845 	 * ills are of same type. For groups without names, ifgrp_insert
7846 	 * ensures this.
7847 	 */
7848 	ASSERT(dst_ill->ill_type == ill->ill_type);
7849 
7850 	return (ill);
7851 }
7852 
7853 /*
7854  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7855  */
7856 ill_t *
7857 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7858     ip_stack_t *ipst)
7859 {
7860 	ill_t *ret_ill;
7861 
7862 	ASSERT(ifindex != 0);
7863 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7864 	    ipst);
7865 	if (ret_ill == NULL ||
7866 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7867 		if (isv6) {
7868 			if (ill != NULL) {
7869 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7870 			} else {
7871 				BUMP_MIB(&ipst->ips_ip6_mib,
7872 				    ipIfStatsOutDiscards);
7873 			}
7874 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7875 			    "bad ifindex %d.\n", ifindex));
7876 		} else {
7877 			if (ill != NULL) {
7878 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7879 			} else {
7880 				BUMP_MIB(&ipst->ips_ip_mib,
7881 				    ipIfStatsOutDiscards);
7882 			}
7883 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7884 			    "bad ifindex %d.\n", ifindex));
7885 		}
7886 		if (ret_ill != NULL)
7887 			ill_refrele(ret_ill);
7888 		freemsg(first_mp);
7889 		return (NULL);
7890 	}
7891 
7892 	return (ret_ill);
7893 }
7894 
7895 /*
7896  * IPv4 -
7897  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7898  * out a packet to a destination address for which we do not have specific
7899  * (or sufficient) routing information.
7900  *
7901  * NOTE : These are the scopes of some of the variables that point at IRE,
7902  *	  which needs to be followed while making any future modifications
7903  *	  to avoid memory leaks.
7904  *
7905  *	- ire and sire are the entries looked up initially by
7906  *	  ire_ftable_lookup.
7907  *	- ipif_ire is used to hold the interface ire associated with
7908  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7909  *	  it before branching out to error paths.
7910  *	- save_ire is initialized before ire_create, so that ire returned
7911  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7912  *	  before breaking out of the switch.
7913  *
7914  *	Thus on failures, we have to REFRELE only ire and sire, if they
7915  *	are not NULL.
7916  */
7917 void
7918 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7919     zoneid_t zoneid, ip_stack_t *ipst)
7920 {
7921 	areq_t	*areq;
7922 	ipaddr_t gw = 0;
7923 	ire_t	*ire = NULL;
7924 	mblk_t	*res_mp;
7925 	ipaddr_t *addrp;
7926 	ipaddr_t nexthop_addr;
7927 	ipif_t  *src_ipif = NULL;
7928 	ill_t	*dst_ill = NULL;
7929 	ipha_t  *ipha;
7930 	ire_t	*sire = NULL;
7931 	mblk_t	*first_mp;
7932 	ire_t	*save_ire;
7933 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7934 	ushort_t ire_marks = 0;
7935 	boolean_t mctl_present;
7936 	ipsec_out_t *io;
7937 	mblk_t	*saved_mp;
7938 	ire_t	*first_sire = NULL;
7939 	mblk_t	*copy_mp = NULL;
7940 	mblk_t	*xmit_mp = NULL;
7941 	ipaddr_t save_dst;
7942 	uint32_t multirt_flags =
7943 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7944 	boolean_t multirt_is_resolvable;
7945 	boolean_t multirt_resolve_next;
7946 	boolean_t do_attach_ill = B_FALSE;
7947 	boolean_t ip_nexthop = B_FALSE;
7948 	tsol_ire_gw_secattr_t *attrp = NULL;
7949 	tsol_gcgrp_t *gcgrp = NULL;
7950 	tsol_gcgrp_addr_t ga;
7951 
7952 	if (ip_debug > 2) {
7953 		/* ip1dbg */
7954 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7955 	}
7956 
7957 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7958 	if (mctl_present) {
7959 		io = (ipsec_out_t *)first_mp->b_rptr;
7960 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7961 		ASSERT(zoneid == io->ipsec_out_zoneid);
7962 		ASSERT(zoneid != ALL_ZONES);
7963 	}
7964 
7965 	ipha = (ipha_t *)mp->b_rptr;
7966 
7967 	/* All multicast lookups come through ip_newroute_ipif() */
7968 	if (CLASSD(dst)) {
7969 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7970 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7971 		freemsg(first_mp);
7972 		return;
7973 	}
7974 
7975 	if (mctl_present && io->ipsec_out_attach_if) {
7976 		/* ip_grab_attach_ill returns a held ill */
7977 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7978 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7979 
7980 		/* Failure case frees things for us. */
7981 		if (attach_ill == NULL)
7982 			return;
7983 
7984 		/*
7985 		 * Check if we need an ire that will not be
7986 		 * looked up by anybody else i.e. HIDDEN.
7987 		 */
7988 		if (ill_is_probeonly(attach_ill))
7989 			ire_marks = IRE_MARK_HIDDEN;
7990 	}
7991 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7992 		ip_nexthop = B_TRUE;
7993 		nexthop_addr = io->ipsec_out_nexthop_addr;
7994 	}
7995 	/*
7996 	 * If this IRE is created for forwarding or it is not for
7997 	 * traffic for congestion controlled protocols, mark it as temporary.
7998 	 */
7999 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
8000 		ire_marks |= IRE_MARK_TEMPORARY;
8001 
8002 	/*
8003 	 * Get what we can from ire_ftable_lookup which will follow an IRE
8004 	 * chain until it gets the most specific information available.
8005 	 * For example, we know that there is no IRE_CACHE for this dest,
8006 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
8007 	 * ire_ftable_lookup will look up the gateway, etc.
8008 	 * Check if in_ill != NULL. If it is true, the packet must be
8009 	 * from an incoming interface where RTA_SRCIFP is set.
8010 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
8011 	 * to the destination, of equal netmask length in the forward table,
8012 	 * will be recursively explored. If no information is available
8013 	 * for the final gateway of that route, we force the returned ire
8014 	 * to be equal to sire using MATCH_IRE_PARENT.
8015 	 * At least, in this case we have a starting point (in the buckets)
8016 	 * to look for other routes to the destination in the forward table.
8017 	 * This is actually used only for multirouting, where a list
8018 	 * of routes has to be processed in sequence.
8019 	 *
8020 	 * In the process of coming up with the most specific information,
8021 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8022 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8023 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8024 	 * Two caveats when handling incomplete ire's in ip_newroute:
8025 	 * - we should be careful when accessing its ire_nce (specifically
8026 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8027 	 * - not all legacy code path callers are prepared to handle
8028 	 *   incomplete ire's, so we should not create/add incomplete
8029 	 *   ire_cache entries here. (See discussion about temporary solution
8030 	 *   further below).
8031 	 *
8032 	 * In order to minimize packet dropping, and to preserve existing
8033 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8034 	 * gateway, and instead use the IF_RESOLVER ire to send out
8035 	 * another request to ARP (this is achieved by passing the
8036 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8037 	 * arp response comes back in ip_wput_nondata, we will create
8038 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8039 	 *
8040 	 * Note that this is a temporary solution; the correct solution is
8041 	 * to create an incomplete  per-dst ire_cache entry, and send the
8042 	 * packet out when the gw's nce is resolved. In order to achieve this,
8043 	 * all packet processing must have been completed prior to calling
8044 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8045 	 * to be modified to accomodate this solution.
8046 	 */
8047 	if (in_ill != NULL) {
8048 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
8049 		    in_ill, MATCH_IRE_TYPE);
8050 	} else if (ip_nexthop) {
8051 		/*
8052 		 * The first time we come here, we look for an IRE_INTERFACE
8053 		 * entry for the specified nexthop, set the dst to be the
8054 		 * nexthop address and create an IRE_CACHE entry for the
8055 		 * nexthop. The next time around, we are able to find an
8056 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8057 		 * nexthop address and create an IRE_CACHE entry for the
8058 		 * destination address via the specified nexthop.
8059 		 */
8060 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8061 		    MBLK_GETLABEL(mp), ipst);
8062 		if (ire != NULL) {
8063 			gw = nexthop_addr;
8064 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8065 		} else {
8066 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8067 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8068 			    MBLK_GETLABEL(mp),
8069 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8070 			    ipst);
8071 			if (ire != NULL) {
8072 				dst = nexthop_addr;
8073 			}
8074 		}
8075 	} else if (attach_ill == NULL) {
8076 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8077 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8078 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8079 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8080 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8081 		    ipst);
8082 	} else {
8083 		/*
8084 		 * attach_ill is set only for communicating with
8085 		 * on-link hosts. So, don't look for DEFAULT.
8086 		 */
8087 		ipif_t	*attach_ipif;
8088 
8089 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8090 		if (attach_ipif == NULL) {
8091 			ill_refrele(attach_ill);
8092 			goto icmp_err_ret;
8093 		}
8094 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8095 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8096 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8097 		    MATCH_IRE_SECATTR, ipst);
8098 		ipif_refrele(attach_ipif);
8099 	}
8100 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8101 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8102 
8103 	/*
8104 	 * This loop is run only once in most cases.
8105 	 * We loop to resolve further routes only when the destination
8106 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8107 	 */
8108 	do {
8109 		/* Clear the previous iteration's values */
8110 		if (src_ipif != NULL) {
8111 			ipif_refrele(src_ipif);
8112 			src_ipif = NULL;
8113 		}
8114 		if (dst_ill != NULL) {
8115 			ill_refrele(dst_ill);
8116 			dst_ill = NULL;
8117 		}
8118 
8119 		multirt_resolve_next = B_FALSE;
8120 		/*
8121 		 * We check if packets have to be multirouted.
8122 		 * In this case, given the current <ire, sire> couple,
8123 		 * we look for the next suitable <ire, sire>.
8124 		 * This check is done in ire_multirt_lookup(),
8125 		 * which applies various criteria to find the next route
8126 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8127 		 * unchanged if it detects it has not been tried yet.
8128 		 */
8129 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8130 			ip3dbg(("ip_newroute: starting next_resolution "
8131 			    "with first_mp %p, tag %d\n",
8132 			    (void *)first_mp,
8133 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8134 
8135 			ASSERT(sire != NULL);
8136 			multirt_is_resolvable =
8137 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8138 				MBLK_GETLABEL(mp), ipst);
8139 
8140 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8141 			    "ire %p, sire %p\n",
8142 			    multirt_is_resolvable,
8143 			    (void *)ire, (void *)sire));
8144 
8145 			if (!multirt_is_resolvable) {
8146 				/*
8147 				 * No more multirt route to resolve; give up
8148 				 * (all routes resolved or no more
8149 				 * resolvable routes).
8150 				 */
8151 				if (ire != NULL) {
8152 					ire_refrele(ire);
8153 					ire = NULL;
8154 				}
8155 			} else {
8156 				ASSERT(sire != NULL);
8157 				ASSERT(ire != NULL);
8158 				/*
8159 				 * We simply use first_sire as a flag that
8160 				 * indicates if a resolvable multirt route
8161 				 * has already been found.
8162 				 * If it is not the case, we may have to send
8163 				 * an ICMP error to report that the
8164 				 * destination is unreachable.
8165 				 * We do not IRE_REFHOLD first_sire.
8166 				 */
8167 				if (first_sire == NULL) {
8168 					first_sire = sire;
8169 				}
8170 			}
8171 		}
8172 		if (ire == NULL) {
8173 			if (ip_debug > 3) {
8174 				/* ip2dbg */
8175 				pr_addr_dbg("ip_newroute: "
8176 				    "can't resolve %s\n", AF_INET, &dst);
8177 			}
8178 			ip3dbg(("ip_newroute: "
8179 			    "ire %p, sire %p, first_sire %p\n",
8180 			    (void *)ire, (void *)sire, (void *)first_sire));
8181 
8182 			if (sire != NULL) {
8183 				ire_refrele(sire);
8184 				sire = NULL;
8185 			}
8186 
8187 			if (first_sire != NULL) {
8188 				/*
8189 				 * At least one multirt route has been found
8190 				 * in the same call to ip_newroute();
8191 				 * there is no need to report an ICMP error.
8192 				 * first_sire was not IRE_REFHOLDed.
8193 				 */
8194 				MULTIRT_DEBUG_UNTAG(first_mp);
8195 				freemsg(first_mp);
8196 				return;
8197 			}
8198 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8199 			    RTA_DST, ipst);
8200 			if (attach_ill != NULL)
8201 				ill_refrele(attach_ill);
8202 			goto icmp_err_ret;
8203 		}
8204 
8205 		/*
8206 		 * When RTA_SRCIFP is used to add a route, then an interface
8207 		 * route is added in the source interface's routing table.
8208 		 * If the outgoing interface of this route is of type
8209 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8210 		 * ire_nce->nce_res_mp is set to NULL.
8211 		 * Later, when this route is first used for forwarding
8212 		 * a packet, ip_newroute() is called
8213 		 * to resolve the hardware address of the outgoing ipif.
8214 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8215 		 * source interface based table. We only come here if the
8216 		 * outgoing interface is a resolver interface and we don't
8217 		 * have the ire_nce->nce_res_mp information yet.
8218 		 * If in_ill is not null that means it is called from
8219 		 * ip_rput.
8220 		 */
8221 
8222 		ASSERT(ire->ire_in_ill == NULL ||
8223 		    (ire->ire_type == IRE_IF_RESOLVER &&
8224 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8225 
8226 		/*
8227 		 * Verify that the returned IRE does not have either
8228 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8229 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8230 		 */
8231 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8232 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8233 			if (attach_ill != NULL)
8234 				ill_refrele(attach_ill);
8235 			goto icmp_err_ret;
8236 		}
8237 		/*
8238 		 * Increment the ire_ob_pkt_count field for ire if it is an
8239 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8240 		 * increment the same for the parent IRE, sire, if it is some
8241 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
8242 		 * and HOST_REDIRECT).
8243 		 */
8244 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8245 			UPDATE_OB_PKT_COUNT(ire);
8246 			ire->ire_last_used_time = lbolt;
8247 		}
8248 
8249 		if (sire != NULL) {
8250 			gw = sire->ire_gateway_addr;
8251 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8252 			    IRE_INTERFACE)) == 0);
8253 			UPDATE_OB_PKT_COUNT(sire);
8254 			sire->ire_last_used_time = lbolt;
8255 		}
8256 		/*
8257 		 * We have a route to reach the destination.
8258 		 *
8259 		 * 1) If the interface is part of ill group, try to get a new
8260 		 *    ill taking load spreading into account.
8261 		 *
8262 		 * 2) After selecting the ill, get a source address that
8263 		 *    might create good inbound load spreading.
8264 		 *    ipif_select_source does this for us.
8265 		 *
8266 		 * If the application specified the ill (ifindex), we still
8267 		 * load spread. Only if the packets needs to go out
8268 		 * specifically on a given ill e.g. binding to
8269 		 * IPIF_NOFAILOVER address, then we don't try to use a
8270 		 * different ill for load spreading.
8271 		 */
8272 		if (attach_ill == NULL) {
8273 			/*
8274 			 * Don't perform outbound load spreading in the
8275 			 * case of an RTF_MULTIRT route, as we actually
8276 			 * typically want to replicate outgoing packets
8277 			 * through particular interfaces.
8278 			 */
8279 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8280 				dst_ill = ire->ire_ipif->ipif_ill;
8281 				/* for uniformity */
8282 				ill_refhold(dst_ill);
8283 			} else {
8284 				/*
8285 				 * If we are here trying to create an IRE_CACHE
8286 				 * for an offlink destination and have the
8287 				 * IRE_CACHE for the next hop and the latter is
8288 				 * using virtual IP source address selection i.e
8289 				 * it's ire->ire_ipif is pointing to a virtual
8290 				 * network interface (vni) then
8291 				 * ip_newroute_get_dst_ll() will return the vni
8292 				 * interface as the dst_ill. Since the vni is
8293 				 * virtual i.e not associated with any physical
8294 				 * interface, it cannot be the dst_ill, hence
8295 				 * in such a case call ip_newroute_get_dst_ll()
8296 				 * with the stq_ill instead of the ire_ipif ILL.
8297 				 * The function returns a refheld ill.
8298 				 */
8299 				if ((ire->ire_type == IRE_CACHE) &&
8300 				    IS_VNI(ire->ire_ipif->ipif_ill))
8301 					dst_ill = ip_newroute_get_dst_ill(
8302 						ire->ire_stq->q_ptr);
8303 				else
8304 					dst_ill = ip_newroute_get_dst_ill(
8305 						ire->ire_ipif->ipif_ill);
8306 			}
8307 			if (dst_ill == NULL) {
8308 				if (ip_debug > 2) {
8309 					pr_addr_dbg("ip_newroute: "
8310 					    "no dst ill for dst"
8311 					    " %s\n", AF_INET, &dst);
8312 				}
8313 				goto icmp_err_ret;
8314 			}
8315 		} else {
8316 			dst_ill = ire->ire_ipif->ipif_ill;
8317 			/* for uniformity */
8318 			ill_refhold(dst_ill);
8319 			/*
8320 			 * We should have found a route matching ill as we
8321 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8322 			 * Rather than asserting, when there is a mismatch,
8323 			 * we just drop the packet.
8324 			 */
8325 			if (dst_ill != attach_ill) {
8326 				ip0dbg(("ip_newroute: Packet dropped as "
8327 				    "IPIF_NOFAILOVER ill is %s, "
8328 				    "ire->ire_ipif->ipif_ill is %s\n",
8329 				    attach_ill->ill_name,
8330 				    dst_ill->ill_name));
8331 				ill_refrele(attach_ill);
8332 				goto icmp_err_ret;
8333 			}
8334 		}
8335 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8336 		if (attach_ill != NULL) {
8337 			ill_refrele(attach_ill);
8338 			attach_ill = NULL;
8339 			do_attach_ill = B_TRUE;
8340 		}
8341 		ASSERT(dst_ill != NULL);
8342 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8343 
8344 		/*
8345 		 * Pick the best source address from dst_ill.
8346 		 *
8347 		 * 1) If it is part of a multipathing group, we would
8348 		 *    like to spread the inbound packets across different
8349 		 *    interfaces. ipif_select_source picks a random source
8350 		 *    across the different ills in the group.
8351 		 *
8352 		 * 2) If it is not part of a multipathing group, we try
8353 		 *    to pick the source address from the destination
8354 		 *    route. Clustering assumes that when we have multiple
8355 		 *    prefixes hosted on an interface, the prefix of the
8356 		 *    source address matches the prefix of the destination
8357 		 *    route. We do this only if the address is not
8358 		 *    DEPRECATED.
8359 		 *
8360 		 * 3) If the conn is in a different zone than the ire, we
8361 		 *    need to pick a source address from the right zone.
8362 		 *
8363 		 * NOTE : If we hit case (1) above, the prefix of the source
8364 		 *	  address picked may not match the prefix of the
8365 		 *	  destination routes prefix as ipif_select_source
8366 		 *	  does not look at "dst" while picking a source
8367 		 *	  address.
8368 		 *	  If we want the same behavior as (2), we will need
8369 		 *	  to change the behavior of ipif_select_source.
8370 		 */
8371 		ASSERT(src_ipif == NULL);
8372 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8373 			/*
8374 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8375 			 * Check that the ipif matching the requested source
8376 			 * address still exists.
8377 			 */
8378 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8379 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8380 		}
8381 		if (src_ipif == NULL) {
8382 			ire_marks |= IRE_MARK_USESRC_CHECK;
8383 			if ((dst_ill->ill_group != NULL) ||
8384 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8385 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8386 			    ire->ire_zoneid != ALL_ZONES) ||
8387 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8388 				/*
8389 				 * If the destination is reachable via a
8390 				 * given gateway, the selected source address
8391 				 * should be in the same subnet as the gateway.
8392 				 * Otherwise, the destination is not reachable.
8393 				 *
8394 				 * If there are no interfaces on the same subnet
8395 				 * as the destination, ipif_select_source gives
8396 				 * first non-deprecated interface which might be
8397 				 * on a different subnet than the gateway.
8398 				 * This is not desirable. Hence pass the dst_ire
8399 				 * source address to ipif_select_source.
8400 				 * It is sure that the destination is reachable
8401 				 * with the dst_ire source address subnet.
8402 				 * So passing dst_ire source address to
8403 				 * ipif_select_source will make sure that the
8404 				 * selected source will be on the same subnet
8405 				 * as dst_ire source address.
8406 				 */
8407 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8408 				src_ipif = ipif_select_source(dst_ill, saddr,
8409 				    zoneid);
8410 				if (src_ipif == NULL) {
8411 					if (ip_debug > 2) {
8412 						pr_addr_dbg("ip_newroute: "
8413 						    "no src for dst %s ",
8414 						    AF_INET, &dst);
8415 						printf("through interface %s\n",
8416 						    dst_ill->ill_name);
8417 					}
8418 					goto icmp_err_ret;
8419 				}
8420 			} else {
8421 				src_ipif = ire->ire_ipif;
8422 				ASSERT(src_ipif != NULL);
8423 				/* hold src_ipif for uniformity */
8424 				ipif_refhold(src_ipif);
8425 			}
8426 		}
8427 
8428 		/*
8429 		 * Assign a source address while we have the conn.
8430 		 * We can't have ip_wput_ire pick a source address when the
8431 		 * packet returns from arp since we need to look at
8432 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8433 		 * going through arp.
8434 		 *
8435 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8436 		 *	  it uses ip6i to store this information.
8437 		 */
8438 		if (ipha->ipha_src == INADDR_ANY &&
8439 		    (connp == NULL || !connp->conn_unspec_src)) {
8440 			ipha->ipha_src = src_ipif->ipif_src_addr;
8441 		}
8442 		if (ip_debug > 3) {
8443 			/* ip2dbg */
8444 			pr_addr_dbg("ip_newroute: first hop %s\n",
8445 			    AF_INET, &gw);
8446 		}
8447 		ip2dbg(("\tire type %s (%d)\n",
8448 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8449 
8450 		/*
8451 		 * The TTL of multirouted packets is bounded by the
8452 		 * ip_multirt_ttl ndd variable.
8453 		 */
8454 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8455 			/* Force TTL of multirouted packets */
8456 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8457 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8458 				ip2dbg(("ip_newroute: forcing multirt TTL "
8459 				    "to %d (was %d), dst 0x%08x\n",
8460 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8461 				    ntohl(sire->ire_addr)));
8462 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8463 			}
8464 		}
8465 		/*
8466 		 * At this point in ip_newroute(), ire is either the
8467 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8468 		 * destination or an IRE_INTERFACE type that should be used
8469 		 * to resolve an on-subnet destination or an on-subnet
8470 		 * next-hop gateway.
8471 		 *
8472 		 * In the IRE_CACHE case, we have the following :
8473 		 *
8474 		 * 1) src_ipif - used for getting a source address.
8475 		 *
8476 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8477 		 *    means packets using this IRE_CACHE will go out on
8478 		 *    dst_ill.
8479 		 *
8480 		 * 3) The IRE sire will point to the prefix that is the
8481 		 *    longest  matching route for the destination. These
8482 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8483 		 *
8484 		 *    The newly created IRE_CACHE entry for the off-subnet
8485 		 *    destination is tied to both the prefix route and the
8486 		 *    interface route used to resolve the next-hop gateway
8487 		 *    via the ire_phandle and ire_ihandle fields,
8488 		 *    respectively.
8489 		 *
8490 		 * In the IRE_INTERFACE case, we have the following :
8491 		 *
8492 		 * 1) src_ipif - used for getting a source address.
8493 		 *
8494 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8495 		 *    means packets using the IRE_CACHE that we will build
8496 		 *    here will go out on dst_ill.
8497 		 *
8498 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8499 		 *    to be created will only be tied to the IRE_INTERFACE
8500 		 *    that was derived from the ire_ihandle field.
8501 		 *
8502 		 *    If sire is non-NULL, it means the destination is
8503 		 *    off-link and we will first create the IRE_CACHE for the
8504 		 *    gateway. Next time through ip_newroute, we will create
8505 		 *    the IRE_CACHE for the final destination as described
8506 		 *    above.
8507 		 *
8508 		 * In both cases, after the current resolution has been
8509 		 * completed (or possibly initialised, in the IRE_INTERFACE
8510 		 * case), the loop may be re-entered to attempt the resolution
8511 		 * of another RTF_MULTIRT route.
8512 		 *
8513 		 * When an IRE_CACHE entry for the off-subnet destination is
8514 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8515 		 * for further processing in emission loops.
8516 		 */
8517 		save_ire = ire;
8518 		switch (ire->ire_type) {
8519 		case IRE_CACHE: {
8520 			ire_t	*ipif_ire;
8521 			mblk_t	*ire_fp_mp;
8522 
8523 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8524 			if (gw == 0)
8525 				gw = ire->ire_gateway_addr;
8526 			/*
8527 			 * We need 3 ire's to create a new cache ire for an
8528 			 * off-link destination from the cache ire of the
8529 			 * gateway.
8530 			 *
8531 			 *	1. The prefix ire 'sire' (Note that this does
8532 			 *	   not apply to the conn_nexthop_set case)
8533 			 *	2. The cache ire of the gateway 'ire'
8534 			 *	3. The interface ire 'ipif_ire'
8535 			 *
8536 			 * We have (1) and (2). We lookup (3) below.
8537 			 *
8538 			 * If there is no interface route to the gateway,
8539 			 * it is a race condition, where we found the cache
8540 			 * but the interface route has been deleted.
8541 			 */
8542 			if (ip_nexthop) {
8543 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8544 			} else {
8545 				ipif_ire =
8546 				    ire_ihandle_lookup_offlink(ire, sire);
8547 			}
8548 			if (ipif_ire == NULL) {
8549 				ip1dbg(("ip_newroute: "
8550 				    "ire_ihandle_lookup_offlink failed\n"));
8551 				goto icmp_err_ret;
8552 			}
8553 			/*
8554 			 * XXX We are using the same res_mp
8555 			 * (DL_UNITDATA_REQ) though the save_ire is not
8556 			 * pointing at the same ill.
8557 			 * This is incorrect. We need to send it up to the
8558 			 * resolver to get the right res_mp. For ethernets
8559 			 * this may be okay (ill_type == DL_ETHER).
8560 			 */
8561 			res_mp = save_ire->ire_nce->nce_res_mp;
8562 			ire_fp_mp = NULL;
8563 			/*
8564 			 * save_ire's nce_fp_mp can't change since it is
8565 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8566 			 * LOCK_IRE_FP_MP does not do any useful work in
8567 			 * the case of IRE_CACHE. So we don't use it below.
8568 			 */
8569 			if (save_ire->ire_stq == dst_ill->ill_wq)
8570 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8571 
8572 			/*
8573 			 * Check cached gateway IRE for any security
8574 			 * attributes; if found, associate the gateway
8575 			 * credentials group to the destination IRE.
8576 			 */
8577 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8578 				mutex_enter(&attrp->igsa_lock);
8579 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8580 					GCGRP_REFHOLD(gcgrp);
8581 				mutex_exit(&attrp->igsa_lock);
8582 			}
8583 
8584 			ire = ire_create(
8585 			    (uchar_t *)&dst,		/* dest address */
8586 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8587 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8588 			    (uchar_t *)&gw,		/* gateway address */
8589 			    NULL,
8590 			    &save_ire->ire_max_frag,
8591 			    ire_fp_mp,			/* Fast Path header */
8592 			    dst_ill->ill_rq,		/* recv-from queue */
8593 			    dst_ill->ill_wq,		/* send-to queue */
8594 			    IRE_CACHE,			/* IRE type */
8595 			    res_mp,
8596 			    src_ipif,
8597 			    in_ill,			/* incoming ill */
8598 			    (sire != NULL) ?
8599 				sire->ire_mask : 0, 	/* Parent mask */
8600 			    (sire != NULL) ?
8601 				sire->ire_phandle : 0,  /* Parent handle */
8602 			    ipif_ire->ire_ihandle,	/* Interface handle */
8603 			    (sire != NULL) ? (sire->ire_flags &
8604 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8605 			    (sire != NULL) ?
8606 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8607 			    NULL,
8608 			    gcgrp,
8609 			    ipst);
8610 
8611 			if (ire == NULL) {
8612 				if (gcgrp != NULL) {
8613 					GCGRP_REFRELE(gcgrp);
8614 					gcgrp = NULL;
8615 				}
8616 				ire_refrele(ipif_ire);
8617 				ire_refrele(save_ire);
8618 				break;
8619 			}
8620 
8621 			/* reference now held by IRE */
8622 			gcgrp = NULL;
8623 
8624 			ire->ire_marks |= ire_marks;
8625 
8626 			/*
8627 			 * Prevent sire and ipif_ire from getting deleted.
8628 			 * The newly created ire is tied to both of them via
8629 			 * the phandle and ihandle respectively.
8630 			 */
8631 			if (sire != NULL) {
8632 				IRB_REFHOLD(sire->ire_bucket);
8633 				/* Has it been removed already ? */
8634 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8635 					IRB_REFRELE(sire->ire_bucket);
8636 					ire_refrele(ipif_ire);
8637 					ire_refrele(save_ire);
8638 					break;
8639 				}
8640 			}
8641 
8642 			IRB_REFHOLD(ipif_ire->ire_bucket);
8643 			/* Has it been removed already ? */
8644 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8645 				IRB_REFRELE(ipif_ire->ire_bucket);
8646 				if (sire != NULL)
8647 					IRB_REFRELE(sire->ire_bucket);
8648 				ire_refrele(ipif_ire);
8649 				ire_refrele(save_ire);
8650 				break;
8651 			}
8652 
8653 			xmit_mp = first_mp;
8654 			/*
8655 			 * In the case of multirouting, a copy
8656 			 * of the packet is done before its sending.
8657 			 * The copy is used to attempt another
8658 			 * route resolution, in a next loop.
8659 			 */
8660 			if (ire->ire_flags & RTF_MULTIRT) {
8661 				copy_mp = copymsg(first_mp);
8662 				if (copy_mp != NULL) {
8663 					xmit_mp = copy_mp;
8664 					MULTIRT_DEBUG_TAG(first_mp);
8665 				}
8666 			}
8667 			ire_add_then_send(q, ire, xmit_mp);
8668 			ire_refrele(save_ire);
8669 
8670 			/* Assert that sire is not deleted yet. */
8671 			if (sire != NULL) {
8672 				ASSERT(sire->ire_ptpn != NULL);
8673 				IRB_REFRELE(sire->ire_bucket);
8674 			}
8675 
8676 			/* Assert that ipif_ire is not deleted yet. */
8677 			ASSERT(ipif_ire->ire_ptpn != NULL);
8678 			IRB_REFRELE(ipif_ire->ire_bucket);
8679 			ire_refrele(ipif_ire);
8680 
8681 			/*
8682 			 * If copy_mp is not NULL, multirouting was
8683 			 * requested. We loop to initiate a next
8684 			 * route resolution attempt, starting from sire.
8685 			 */
8686 			if (copy_mp != NULL) {
8687 				/*
8688 				 * Search for the next unresolved
8689 				 * multirt route.
8690 				 */
8691 				copy_mp = NULL;
8692 				ipif_ire = NULL;
8693 				ire = NULL;
8694 				multirt_resolve_next = B_TRUE;
8695 				continue;
8696 			}
8697 			if (sire != NULL)
8698 				ire_refrele(sire);
8699 			ipif_refrele(src_ipif);
8700 			ill_refrele(dst_ill);
8701 			return;
8702 		}
8703 		case IRE_IF_NORESOLVER: {
8704 			/*
8705 			 * We have what we need to build an IRE_CACHE.
8706 			 *
8707 			 * Create a new res_mp with the IP gateway address
8708 			 * in destination address in the DLPI hdr if the
8709 			 * physical length is exactly 4 bytes.
8710 			 */
8711 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8712 				uchar_t *addr;
8713 
8714 				if (gw)
8715 					addr = (uchar_t *)&gw;
8716 				else
8717 					addr = (uchar_t *)&dst;
8718 
8719 				res_mp = ill_dlur_gen(addr,
8720 				    dst_ill->ill_phys_addr_length,
8721 				    dst_ill->ill_sap,
8722 				    dst_ill->ill_sap_length);
8723 
8724 				if (res_mp == NULL) {
8725 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8726 					break;
8727 				}
8728 			} else if (dst_ill->ill_resolver_mp == NULL) {
8729 				ip1dbg(("ip_newroute: dst_ill %p "
8730 				    "for IF_NORESOLV ire %p has "
8731 				    "no ill_resolver_mp\n",
8732 				    (void *)dst_ill, (void *)ire));
8733 				break;
8734 			} else {
8735 				res_mp = NULL;
8736 			}
8737 
8738 			/*
8739 			 * TSol note: We are creating the ire cache for the
8740 			 * destination 'dst'. If 'dst' is offlink, going
8741 			 * through the first hop 'gw', the security attributes
8742 			 * of 'dst' must be set to point to the gateway
8743 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8744 			 * is possible that 'dst' is a potential gateway that is
8745 			 * referenced by some route that has some security
8746 			 * attributes. Thus in the former case, we need to do a
8747 			 * gcgrp_lookup of 'gw' while in the latter case we
8748 			 * need to do gcgrp_lookup of 'dst' itself.
8749 			 */
8750 			ga.ga_af = AF_INET;
8751 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8752 			    &ga.ga_addr);
8753 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8754 
8755 			ire = ire_create(
8756 			    (uchar_t *)&dst,		/* dest address */
8757 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8758 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8759 			    (uchar_t *)&gw,		/* gateway address */
8760 			    NULL,
8761 			    &save_ire->ire_max_frag,
8762 			    NULL,			/* Fast Path header */
8763 			    dst_ill->ill_rq,		/* recv-from queue */
8764 			    dst_ill->ill_wq,		/* send-to queue */
8765 			    IRE_CACHE,
8766 			    res_mp,
8767 			    src_ipif,
8768 			    in_ill,			/* Incoming ill */
8769 			    save_ire->ire_mask,		/* Parent mask */
8770 			    (sire != NULL) ?		/* Parent handle */
8771 				sire->ire_phandle : 0,
8772 			    save_ire->ire_ihandle,	/* Interface handle */
8773 			    (sire != NULL) ? sire->ire_flags &
8774 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8775 			    &(save_ire->ire_uinfo),
8776 			    NULL,
8777 			    gcgrp,
8778 			    ipst);
8779 
8780 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8781 				freeb(res_mp);
8782 
8783 			if (ire == NULL) {
8784 				if (gcgrp != NULL) {
8785 					GCGRP_REFRELE(gcgrp);
8786 					gcgrp = NULL;
8787 				}
8788 				ire_refrele(save_ire);
8789 				break;
8790 			}
8791 
8792 			/* reference now held by IRE */
8793 			gcgrp = NULL;
8794 
8795 			ire->ire_marks |= ire_marks;
8796 
8797 			/* Prevent save_ire from getting deleted */
8798 			IRB_REFHOLD(save_ire->ire_bucket);
8799 			/* Has it been removed already ? */
8800 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8801 				IRB_REFRELE(save_ire->ire_bucket);
8802 				ire_refrele(save_ire);
8803 				break;
8804 			}
8805 
8806 			/*
8807 			 * In the case of multirouting, a copy
8808 			 * of the packet is made before it is sent.
8809 			 * The copy is used in the next
8810 			 * loop to attempt another resolution.
8811 			 */
8812 			xmit_mp = first_mp;
8813 			if ((sire != NULL) &&
8814 			    (sire->ire_flags & RTF_MULTIRT)) {
8815 				copy_mp = copymsg(first_mp);
8816 				if (copy_mp != NULL) {
8817 					xmit_mp = copy_mp;
8818 					MULTIRT_DEBUG_TAG(first_mp);
8819 				}
8820 			}
8821 			ire_add_then_send(q, ire, xmit_mp);
8822 
8823 			/* Assert that it is not deleted yet. */
8824 			ASSERT(save_ire->ire_ptpn != NULL);
8825 			IRB_REFRELE(save_ire->ire_bucket);
8826 			ire_refrele(save_ire);
8827 
8828 			if (copy_mp != NULL) {
8829 				/*
8830 				 * If we found a (no)resolver, we ignore any
8831 				 * trailing top priority IRE_CACHE in further
8832 				 * loops. This ensures that we do not omit any
8833 				 * (no)resolver.
8834 				 * This IRE_CACHE, if any, will be processed
8835 				 * by another thread entering ip_newroute().
8836 				 * IRE_CACHE entries, if any, will be processed
8837 				 * by another thread entering ip_newroute(),
8838 				 * (upon resolver response, for instance).
8839 				 * This aims to force parallel multirt
8840 				 * resolutions as soon as a packet must be sent.
8841 				 * In the best case, after the tx of only one
8842 				 * packet, all reachable routes are resolved.
8843 				 * Otherwise, the resolution of all RTF_MULTIRT
8844 				 * routes would require several emissions.
8845 				 */
8846 				multirt_flags &= ~MULTIRT_CACHEGW;
8847 
8848 				/*
8849 				 * Search for the next unresolved multirt
8850 				 * route.
8851 				 */
8852 				copy_mp = NULL;
8853 				save_ire = NULL;
8854 				ire = NULL;
8855 				multirt_resolve_next = B_TRUE;
8856 				continue;
8857 			}
8858 
8859 			/*
8860 			 * Don't need sire anymore
8861 			 */
8862 			if (sire != NULL)
8863 				ire_refrele(sire);
8864 
8865 			ipif_refrele(src_ipif);
8866 			ill_refrele(dst_ill);
8867 			return;
8868 		}
8869 		case IRE_IF_RESOLVER:
8870 			/*
8871 			 * We can't build an IRE_CACHE yet, but at least we
8872 			 * found a resolver that can help.
8873 			 */
8874 			res_mp = dst_ill->ill_resolver_mp;
8875 			if (!OK_RESOLVER_MP(res_mp))
8876 				break;
8877 
8878 			/*
8879 			 * To be at this point in the code with a non-zero gw
8880 			 * means that dst is reachable through a gateway that
8881 			 * we have never resolved.  By changing dst to the gw
8882 			 * addr we resolve the gateway first.
8883 			 * When ire_add_then_send() tries to put the IP dg
8884 			 * to dst, it will reenter ip_newroute() at which
8885 			 * time we will find the IRE_CACHE for the gw and
8886 			 * create another IRE_CACHE in case IRE_CACHE above.
8887 			 */
8888 			if (gw != INADDR_ANY) {
8889 				/*
8890 				 * The source ipif that was determined above was
8891 				 * relative to the destination address, not the
8892 				 * gateway's. If src_ipif was not taken out of
8893 				 * the IRE_IF_RESOLVER entry, we'll need to call
8894 				 * ipif_select_source() again.
8895 				 */
8896 				if (src_ipif != ire->ire_ipif) {
8897 					ipif_refrele(src_ipif);
8898 					src_ipif = ipif_select_source(dst_ill,
8899 					    gw, zoneid);
8900 					if (src_ipif == NULL) {
8901 						if (ip_debug > 2) {
8902 							pr_addr_dbg(
8903 							    "ip_newroute: no "
8904 							    "src for gw %s ",
8905 							    AF_INET, &gw);
8906 							printf("through "
8907 							    "interface %s\n",
8908 							    dst_ill->ill_name);
8909 						}
8910 						goto icmp_err_ret;
8911 					}
8912 				}
8913 				save_dst = dst;
8914 				dst = gw;
8915 				gw = INADDR_ANY;
8916 			}
8917 
8918 			/*
8919 			 * We obtain a partial IRE_CACHE which we will pass
8920 			 * along with the resolver query.  When the response
8921 			 * comes back it will be there ready for us to add.
8922 			 * The ire_max_frag is atomically set under the
8923 			 * irebucket lock in ire_add_v[46].
8924 			 */
8925 
8926 			ire = ire_create_mp(
8927 			    (uchar_t *)&dst,		/* dest address */
8928 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8929 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8930 			    (uchar_t *)&gw,		/* gateway address */
8931 			    NULL,			/* no in_src_addr */
8932 			    NULL,			/* ire_max_frag */
8933 			    NULL,			/* Fast Path header */
8934 			    dst_ill->ill_rq,		/* recv-from queue */
8935 			    dst_ill->ill_wq,		/* send-to queue */
8936 			    IRE_CACHE,
8937 			    NULL,
8938 			    src_ipif,			/* Interface ipif */
8939 			    in_ill,			/* Incoming ILL */
8940 			    save_ire->ire_mask,		/* Parent mask */
8941 			    0,
8942 			    save_ire->ire_ihandle,	/* Interface handle */
8943 			    0,				/* flags if any */
8944 			    &(save_ire->ire_uinfo),
8945 			    NULL,
8946 			    NULL,
8947 			    ipst);
8948 
8949 			if (ire == NULL) {
8950 				ire_refrele(save_ire);
8951 				break;
8952 			}
8953 
8954 			if ((sire != NULL) &&
8955 			    (sire->ire_flags & RTF_MULTIRT)) {
8956 				copy_mp = copymsg(first_mp);
8957 				if (copy_mp != NULL)
8958 					MULTIRT_DEBUG_TAG(copy_mp);
8959 			}
8960 
8961 			ire->ire_marks |= ire_marks;
8962 
8963 			/*
8964 			 * Construct message chain for the resolver
8965 			 * of the form:
8966 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8967 			 * Packet could contain a IPSEC_OUT mp.
8968 			 *
8969 			 * NOTE : ire will be added later when the response
8970 			 * comes back from ARP. If the response does not
8971 			 * come back, ARP frees the packet. For this reason,
8972 			 * we can't REFHOLD the bucket of save_ire to prevent
8973 			 * deletions. We may not be able to REFRELE the bucket
8974 			 * if the response never comes back. Thus, before
8975 			 * adding the ire, ire_add_v4 will make sure that the
8976 			 * interface route does not get deleted. This is the
8977 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8978 			 * where we can always prevent deletions because of
8979 			 * the synchronous nature of adding IRES i.e
8980 			 * ire_add_then_send is called after creating the IRE.
8981 			 */
8982 			ASSERT(ire->ire_mp != NULL);
8983 			ire->ire_mp->b_cont = first_mp;
8984 			/* Have saved_mp handy, for cleanup if canput fails */
8985 			saved_mp = mp;
8986 			mp = copyb(res_mp);
8987 			if (mp == NULL) {
8988 				/* Prepare for cleanup */
8989 				mp = saved_mp; /* pkt */
8990 				ire_delete(ire); /* ire_mp */
8991 				ire = NULL;
8992 				ire_refrele(save_ire);
8993 				if (copy_mp != NULL) {
8994 					MULTIRT_DEBUG_UNTAG(copy_mp);
8995 					freemsg(copy_mp);
8996 					copy_mp = NULL;
8997 				}
8998 				break;
8999 			}
9000 			linkb(mp, ire->ire_mp);
9001 
9002 			/*
9003 			 * Fill in the source and dest addrs for the resolver.
9004 			 * NOTE: this depends on memory layouts imposed by
9005 			 * ill_init().
9006 			 */
9007 			areq = (areq_t *)mp->b_rptr;
9008 			addrp = (ipaddr_t *)((char *)areq +
9009 			    areq->areq_sender_addr_offset);
9010 			if (do_attach_ill) {
9011 				/*
9012 				 * This is bind to no failover case.
9013 				 * arp packet also must go out on attach_ill.
9014 				 */
9015 				ASSERT(ipha->ipha_src != NULL);
9016 				*addrp = ipha->ipha_src;
9017 			} else {
9018 				*addrp = save_ire->ire_src_addr;
9019 			}
9020 
9021 			ire_refrele(save_ire);
9022 			addrp = (ipaddr_t *)((char *)areq +
9023 			    areq->areq_target_addr_offset);
9024 			*addrp = dst;
9025 			/* Up to the resolver. */
9026 			if (canputnext(dst_ill->ill_rq) &&
9027 			    !(dst_ill->ill_arp_closing)) {
9028 				putnext(dst_ill->ill_rq, mp);
9029 				ire = NULL;
9030 				if (copy_mp != NULL) {
9031 					/*
9032 					 * If we found a resolver, we ignore
9033 					 * any trailing top priority IRE_CACHE
9034 					 * in the further loops. This ensures
9035 					 * that we do not omit any resolver.
9036 					 * IRE_CACHE entries, if any, will be
9037 					 * processed next time we enter
9038 					 * ip_newroute().
9039 					 */
9040 					multirt_flags &= ~MULTIRT_CACHEGW;
9041 					/*
9042 					 * Search for the next unresolved
9043 					 * multirt route.
9044 					 */
9045 					first_mp = copy_mp;
9046 					copy_mp = NULL;
9047 					/* Prepare the next resolution loop. */
9048 					mp = first_mp;
9049 					EXTRACT_PKT_MP(mp, first_mp,
9050 					    mctl_present);
9051 					if (mctl_present)
9052 						io = (ipsec_out_t *)
9053 						    first_mp->b_rptr;
9054 					ipha = (ipha_t *)mp->b_rptr;
9055 
9056 					ASSERT(sire != NULL);
9057 
9058 					dst = save_dst;
9059 					multirt_resolve_next = B_TRUE;
9060 					continue;
9061 				}
9062 
9063 				if (sire != NULL)
9064 					ire_refrele(sire);
9065 
9066 				/*
9067 				 * The response will come back in ip_wput
9068 				 * with db_type IRE_DB_TYPE.
9069 				 */
9070 				ipif_refrele(src_ipif);
9071 				ill_refrele(dst_ill);
9072 				return;
9073 			} else {
9074 				/* Prepare for cleanup */
9075 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
9076 				    mp);
9077 				mp->b_cont = NULL;
9078 				freeb(mp); /* areq */
9079 				/*
9080 				 * this is an ire that is not added to the
9081 				 * cache. ire_freemblk will handle the release
9082 				 * of any resources associated with the ire.
9083 				 */
9084 				ire_delete(ire); /* ire_mp */
9085 				mp = saved_mp; /* pkt */
9086 				ire = NULL;
9087 				if (copy_mp != NULL) {
9088 					MULTIRT_DEBUG_UNTAG(copy_mp);
9089 					freemsg(copy_mp);
9090 					copy_mp = NULL;
9091 				}
9092 				break;
9093 			}
9094 		default:
9095 			break;
9096 		}
9097 	} while (multirt_resolve_next);
9098 
9099 	ip1dbg(("ip_newroute: dropped\n"));
9100 	/* Did this packet originate externally? */
9101 	if (mp->b_prev) {
9102 		mp->b_next = NULL;
9103 		mp->b_prev = NULL;
9104 		if (in_ill != NULL) {
9105 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
9106 		} else {
9107 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9108 		}
9109 	} else {
9110 		if (dst_ill != NULL) {
9111 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
9112 		} else {
9113 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
9114 		}
9115 	}
9116 	ASSERT(copy_mp == NULL);
9117 	MULTIRT_DEBUG_UNTAG(first_mp);
9118 	freemsg(first_mp);
9119 	if (ire != NULL)
9120 		ire_refrele(ire);
9121 	if (sire != NULL)
9122 		ire_refrele(sire);
9123 	if (src_ipif != NULL)
9124 		ipif_refrele(src_ipif);
9125 	if (dst_ill != NULL)
9126 		ill_refrele(dst_ill);
9127 	return;
9128 
9129 icmp_err_ret:
9130 	ip1dbg(("ip_newroute: no route\n"));
9131 	if (src_ipif != NULL)
9132 		ipif_refrele(src_ipif);
9133 	if (dst_ill != NULL)
9134 		ill_refrele(dst_ill);
9135 	if (sire != NULL)
9136 		ire_refrele(sire);
9137 	/* Did this packet originate externally? */
9138 	if (mp->b_prev) {
9139 		mp->b_next = NULL;
9140 		mp->b_prev = NULL;
9141 		if (in_ill != NULL) {
9142 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
9143 		} else {
9144 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9145 		}
9146 		q = WR(q);
9147 	} else {
9148 		/*
9149 		 * There is no outgoing ill, so just increment the
9150 		 * system MIB.
9151 		 */
9152 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9153 		/*
9154 		 * Since ip_wput() isn't close to finished, we fill
9155 		 * in enough of the header for credible error reporting.
9156 		 */
9157 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9158 			/* Failed */
9159 			MULTIRT_DEBUG_UNTAG(first_mp);
9160 			freemsg(first_mp);
9161 			if (ire != NULL)
9162 				ire_refrele(ire);
9163 			return;
9164 		}
9165 	}
9166 
9167 	/*
9168 	 * At this point we will have ire only if RTF_BLACKHOLE
9169 	 * or RTF_REJECT flags are set on the IRE. It will not
9170 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9171 	 */
9172 	if (ire != NULL) {
9173 		if (ire->ire_flags & RTF_BLACKHOLE) {
9174 			ire_refrele(ire);
9175 			MULTIRT_DEBUG_UNTAG(first_mp);
9176 			freemsg(first_mp);
9177 			return;
9178 		}
9179 		ire_refrele(ire);
9180 	}
9181 	if (ip_source_routed(ipha, ipst)) {
9182 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9183 		    zoneid, ipst);
9184 		return;
9185 	}
9186 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9187 }
9188 
9189 ip_opt_info_t zero_info;
9190 
9191 /*
9192  * IPv4 -
9193  * ip_newroute_ipif is called by ip_wput_multicast and
9194  * ip_rput_forward_multicast whenever we need to send
9195  * out a packet to a destination address for which we do not have specific
9196  * routing information. It is used when the packet will be sent out
9197  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9198  * socket option is set or icmp error message wants to go out on a particular
9199  * interface for a unicast packet.
9200  *
9201  * In most cases, the destination address is resolved thanks to the ipif
9202  * intrinsic resolver. However, there are some cases where the call to
9203  * ip_newroute_ipif must take into account the potential presence of
9204  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9205  * that uses the interface. This is specified through flags,
9206  * which can be a combination of:
9207  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9208  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9209  *   and flags. Additionally, the packet source address has to be set to
9210  *   the specified address. The caller is thus expected to set this flag
9211  *   if the packet has no specific source address yet.
9212  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9213  *   flag, the resulting ire will inherit the flag. All unresolved routes
9214  *   to the destination must be explored in the same call to
9215  *   ip_newroute_ipif().
9216  */
9217 static void
9218 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9219     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9220 {
9221 	areq_t	*areq;
9222 	ire_t	*ire = NULL;
9223 	mblk_t	*res_mp;
9224 	ipaddr_t *addrp;
9225 	mblk_t *first_mp;
9226 	ire_t	*save_ire = NULL;
9227 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9228 	ipif_t	*src_ipif = NULL;
9229 	ushort_t ire_marks = 0;
9230 	ill_t	*dst_ill = NULL;
9231 	boolean_t mctl_present;
9232 	ipsec_out_t *io;
9233 	ipha_t *ipha;
9234 	int	ihandle = 0;
9235 	mblk_t	*saved_mp;
9236 	ire_t   *fire = NULL;
9237 	mblk_t  *copy_mp = NULL;
9238 	boolean_t multirt_resolve_next;
9239 	ipaddr_t ipha_dst;
9240 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9241 
9242 	/*
9243 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9244 	 * here for uniformity
9245 	 */
9246 	ipif_refhold(ipif);
9247 
9248 	/*
9249 	 * This loop is run only once in most cases.
9250 	 * We loop to resolve further routes only when the destination
9251 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9252 	 */
9253 	do {
9254 		if (dst_ill != NULL) {
9255 			ill_refrele(dst_ill);
9256 			dst_ill = NULL;
9257 		}
9258 		if (src_ipif != NULL) {
9259 			ipif_refrele(src_ipif);
9260 			src_ipif = NULL;
9261 		}
9262 		multirt_resolve_next = B_FALSE;
9263 
9264 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9265 		    ipif->ipif_ill->ill_name));
9266 
9267 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9268 		if (mctl_present)
9269 			io = (ipsec_out_t *)first_mp->b_rptr;
9270 
9271 		ipha = (ipha_t *)mp->b_rptr;
9272 
9273 		/*
9274 		 * Save the packet destination address, we may need it after
9275 		 * the packet has been consumed.
9276 		 */
9277 		ipha_dst = ipha->ipha_dst;
9278 
9279 		/*
9280 		 * If the interface is a pt-pt interface we look for an
9281 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9282 		 * local_address and the pt-pt destination address. Otherwise
9283 		 * we just match the local address.
9284 		 * NOTE: dst could be different than ipha->ipha_dst in case
9285 		 * of sending igmp multicast packets over a point-to-point
9286 		 * connection.
9287 		 * Thus we must be careful enough to check ipha_dst to be a
9288 		 * multicast address, otherwise it will take xmit_if path for
9289 		 * multicast packets resulting into kernel stack overflow by
9290 		 * repeated calls to ip_newroute_ipif from ire_send().
9291 		 */
9292 		if (CLASSD(ipha_dst) &&
9293 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9294 			goto err_ret;
9295 		}
9296 
9297 		/*
9298 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9299 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9300 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9301 		 * propagate its flags to the new ire.
9302 		 */
9303 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9304 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9305 			ip2dbg(("ip_newroute_ipif: "
9306 			    "ipif_lookup_multi_ire("
9307 			    "ipif %p, dst %08x) = fire %p\n",
9308 			    (void *)ipif, ntohl(dst), (void *)fire));
9309 		}
9310 
9311 		if (mctl_present && io->ipsec_out_attach_if) {
9312 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9313 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9314 
9315 			/* Failure case frees things for us. */
9316 			if (attach_ill == NULL) {
9317 				ipif_refrele(ipif);
9318 				if (fire != NULL)
9319 					ire_refrele(fire);
9320 				return;
9321 			}
9322 
9323 			/*
9324 			 * Check if we need an ire that will not be
9325 			 * looked up by anybody else i.e. HIDDEN.
9326 			 */
9327 			if (ill_is_probeonly(attach_ill)) {
9328 				ire_marks = IRE_MARK_HIDDEN;
9329 			}
9330 			/*
9331 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9332 			 * case.
9333 			 */
9334 			dst_ill = ipif->ipif_ill;
9335 			/* attach_ill has been refheld by ip_grab_attach_ill */
9336 			ASSERT(dst_ill == attach_ill);
9337 		} else {
9338 			/*
9339 			 * If this is set by IP_XMIT_IF, then make sure that
9340 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9341 			 * specified ill.
9342 			 */
9343 			ASSERT((connp == NULL) ||
9344 			    (connp->conn_xmit_if_ill == NULL) ||
9345 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9346 			/*
9347 			 * If the interface belongs to an interface group,
9348 			 * make sure the next possible interface in the group
9349 			 * is used.  This encourages load spreading among
9350 			 * peers in an interface group.
9351 			 * Note: load spreading is disabled for RTF_MULTIRT
9352 			 * routes.
9353 			 */
9354 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9355 			    (fire->ire_flags & RTF_MULTIRT)) {
9356 				/*
9357 				 * Don't perform outbound load spreading
9358 				 * in the case of an RTF_MULTIRT issued route,
9359 				 * we actually typically want to replicate
9360 				 * outgoing packets through particular
9361 				 * interfaces.
9362 				 */
9363 				dst_ill = ipif->ipif_ill;
9364 				ill_refhold(dst_ill);
9365 			} else {
9366 				dst_ill = ip_newroute_get_dst_ill(
9367 				    ipif->ipif_ill);
9368 			}
9369 			if (dst_ill == NULL) {
9370 				if (ip_debug > 2) {
9371 					pr_addr_dbg("ip_newroute_ipif: "
9372 					    "no dst ill for dst %s\n",
9373 					    AF_INET, &dst);
9374 				}
9375 				goto err_ret;
9376 			}
9377 		}
9378 
9379 		/*
9380 		 * Pick a source address preferring non-deprecated ones.
9381 		 * Unlike ip_newroute, we don't do any source address
9382 		 * selection here since for multicast it really does not help
9383 		 * in inbound load spreading as in the unicast case.
9384 		 */
9385 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9386 		    (fire->ire_flags & RTF_SETSRC)) {
9387 			/*
9388 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9389 			 * on that interface. This ire has RTF_SETSRC flag, so
9390 			 * the source address of the packet must be changed.
9391 			 * Check that the ipif matching the requested source
9392 			 * address still exists.
9393 			 */
9394 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9395 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9396 		}
9397 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9398 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9399 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9400 		    (src_ipif == NULL)) {
9401 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9402 			if (src_ipif == NULL) {
9403 				if (ip_debug > 2) {
9404 					/* ip1dbg */
9405 					pr_addr_dbg("ip_newroute_ipif: "
9406 					    "no src for dst %s",
9407 					    AF_INET, &dst);
9408 				}
9409 				ip1dbg((" through interface %s\n",
9410 				    dst_ill->ill_name));
9411 				goto err_ret;
9412 			}
9413 			ipif_refrele(ipif);
9414 			ipif = src_ipif;
9415 			ipif_refhold(ipif);
9416 		}
9417 		if (src_ipif == NULL) {
9418 			src_ipif = ipif;
9419 			ipif_refhold(src_ipif);
9420 		}
9421 
9422 		/*
9423 		 * Assign a source address while we have the conn.
9424 		 * We can't have ip_wput_ire pick a source address when the
9425 		 * packet returns from arp since conn_unspec_src might be set
9426 		 * and we loose the conn when going through arp.
9427 		 */
9428 		if (ipha->ipha_src == INADDR_ANY &&
9429 		    (connp == NULL || !connp->conn_unspec_src)) {
9430 			ipha->ipha_src = src_ipif->ipif_src_addr;
9431 		}
9432 
9433 		/*
9434 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9435 		 * interface does not have an interface ire.
9436 		 * Example: Thousands of mobileip PPP interfaces to mobile
9437 		 * nodes. We don't want to create interface ires because
9438 		 * packets from other mobile nodes must not take the route
9439 		 * via interface ires to the visiting mobile node without
9440 		 * going through the home agent, in absence of mobileip
9441 		 * route optimization.
9442 		 */
9443 		if (CLASSD(ipha_dst) && (connp == NULL ||
9444 		    connp->conn_xmit_if_ill == NULL) &&
9445 		    infop->ip_opt_ill_index == 0) {
9446 			/* ipif_to_ire returns an held ire */
9447 			ire = ipif_to_ire(ipif);
9448 			if (ire == NULL)
9449 				goto err_ret;
9450 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9451 				goto err_ret;
9452 			/*
9453 			 * ihandle is needed when the ire is added to
9454 			 * cache table.
9455 			 */
9456 			save_ire = ire;
9457 			ihandle = save_ire->ire_ihandle;
9458 
9459 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9460 			    "flags %04x\n",
9461 			    (void *)ire, (void *)ipif, flags));
9462 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9463 			    (fire->ire_flags & RTF_MULTIRT)) {
9464 				/*
9465 				 * As requested by flags, an IRE_OFFSUBNET was
9466 				 * looked up on that interface. This ire has
9467 				 * RTF_MULTIRT flag, so the resolution loop will
9468 				 * be re-entered to resolve additional routes on
9469 				 * other interfaces. For that purpose, a copy of
9470 				 * the packet is performed at this point.
9471 				 */
9472 				fire->ire_last_used_time = lbolt;
9473 				copy_mp = copymsg(first_mp);
9474 				if (copy_mp) {
9475 					MULTIRT_DEBUG_TAG(copy_mp);
9476 				}
9477 			}
9478 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9479 			    (fire->ire_flags & RTF_SETSRC)) {
9480 				/*
9481 				 * As requested by flags, an IRE_OFFSUBET was
9482 				 * looked up on that interface. This ire has
9483 				 * RTF_SETSRC flag, so the source address of the
9484 				 * packet must be changed.
9485 				 */
9486 				ipha->ipha_src = fire->ire_src_addr;
9487 			}
9488 		} else {
9489 			ASSERT((connp == NULL) ||
9490 			    (connp->conn_xmit_if_ill != NULL) ||
9491 			    (connp->conn_dontroute) ||
9492 			    infop->ip_opt_ill_index != 0);
9493 			/*
9494 			 * The only ways we can come here are:
9495 			 * 1) IP_XMIT_IF socket option is set
9496 			 * 2) ICMP error message generated from
9497 			 *    ip_mrtun_forward() routine and it needs
9498 			 *    to go through the specified ill.
9499 			 * 3) SO_DONTROUTE socket option is set
9500 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9501 			 * In all cases, the new ire will not be added
9502 			 * into cache table.
9503 			 */
9504 			ire_marks |= IRE_MARK_NOADD;
9505 		}
9506 
9507 		switch (ipif->ipif_net_type) {
9508 		case IRE_IF_NORESOLVER: {
9509 			/* We have what we need to build an IRE_CACHE. */
9510 			mblk_t	*res_mp;
9511 
9512 			/*
9513 			 * Create a new res_mp with the
9514 			 * IP gateway address as destination address in the
9515 			 * DLPI hdr if the physical length is exactly 4 bytes.
9516 			 */
9517 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9518 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9519 				    dst_ill->ill_phys_addr_length,
9520 				    dst_ill->ill_sap,
9521 				    dst_ill->ill_sap_length);
9522 			} else if (dst_ill->ill_resolver_mp == NULL) {
9523 				ip1dbg(("ip_newroute: dst_ill %p "
9524 				    "for IF_NORESOLV ire %p has "
9525 				    "no ill_resolver_mp\n",
9526 				    (void *)dst_ill, (void *)ire));
9527 				break;
9528 			} else {
9529 				/* use the value set in ip_ll_subnet_defaults */
9530 				res_mp = ill_dlur_gen(NULL,
9531 				    dst_ill->ill_phys_addr_length,
9532 				    dst_ill->ill_sap,
9533 				    dst_ill->ill_sap_length);
9534 			}
9535 
9536 			if (res_mp == NULL)
9537 				break;
9538 			/*
9539 			 * The new ire inherits the IRE_OFFSUBNET flags
9540 			 * and source address, if this was requested.
9541 			 */
9542 			ire = ire_create(
9543 			    (uchar_t *)&dst,		/* dest address */
9544 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9545 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9546 			    NULL,			/* gateway address */
9547 			    NULL,
9548 			    &ipif->ipif_mtu,
9549 			    NULL,			/* Fast Path header */
9550 			    dst_ill->ill_rq,		/* recv-from queue */
9551 			    dst_ill->ill_wq,		/* send-to queue */
9552 			    IRE_CACHE,
9553 			    res_mp,
9554 			    src_ipif,
9555 			    NULL,
9556 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9557 			    (fire != NULL) ?		/* Parent handle */
9558 				fire->ire_phandle : 0,
9559 			    ihandle,			/* Interface handle */
9560 			    (fire != NULL) ?
9561 				(fire->ire_flags &
9562 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9563 			    (save_ire == NULL ? &ire_uinfo_null :
9564 				&save_ire->ire_uinfo),
9565 			    NULL,
9566 			    NULL,
9567 			    ipst);
9568 
9569 			freeb(res_mp);
9570 
9571 			if (ire == NULL) {
9572 				if (save_ire != NULL)
9573 					ire_refrele(save_ire);
9574 				break;
9575 			}
9576 
9577 			ire->ire_marks |= ire_marks;
9578 
9579 			/*
9580 			 * If IRE_MARK_NOADD is set then we need to convert
9581 			 * the max_fragp to a useable value now. This is
9582 			 * normally done in ire_add_v[46]. We also need to
9583 			 * associate the ire with an nce (normally would be
9584 			 * done in ip_wput_nondata()).
9585 			 *
9586 			 * Note that IRE_MARK_NOADD packets created here
9587 			 * do not have a non-null ire_mp pointer. The null
9588 			 * value of ire_bucket indicates that they were
9589 			 * never added.
9590 			 */
9591 			if (ire->ire_marks & IRE_MARK_NOADD) {
9592 				uint_t  max_frag;
9593 
9594 				max_frag = *ire->ire_max_fragp;
9595 				ire->ire_max_fragp = NULL;
9596 				ire->ire_max_frag = max_frag;
9597 
9598 				if ((ire->ire_nce = ndp_lookup_v4(
9599 				    ire_to_ill(ire),
9600 				    (ire->ire_gateway_addr != INADDR_ANY ?
9601 				    &ire->ire_gateway_addr : &ire->ire_addr),
9602 				    B_FALSE)) == NULL) {
9603 					if (save_ire != NULL)
9604 						ire_refrele(save_ire);
9605 					break;
9606 				}
9607 				ASSERT(ire->ire_nce->nce_state ==
9608 				    ND_REACHABLE);
9609 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9610 			}
9611 
9612 			/* Prevent save_ire from getting deleted */
9613 			if (save_ire != NULL) {
9614 				IRB_REFHOLD(save_ire->ire_bucket);
9615 				/* Has it been removed already ? */
9616 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9617 					IRB_REFRELE(save_ire->ire_bucket);
9618 					ire_refrele(save_ire);
9619 					break;
9620 				}
9621 			}
9622 
9623 			ire_add_then_send(q, ire, first_mp);
9624 
9625 			/* Assert that save_ire is not deleted yet. */
9626 			if (save_ire != NULL) {
9627 				ASSERT(save_ire->ire_ptpn != NULL);
9628 				IRB_REFRELE(save_ire->ire_bucket);
9629 				ire_refrele(save_ire);
9630 				save_ire = NULL;
9631 			}
9632 			if (fire != NULL) {
9633 				ire_refrele(fire);
9634 				fire = NULL;
9635 			}
9636 
9637 			/*
9638 			 * the resolution loop is re-entered if this
9639 			 * was requested through flags and if we
9640 			 * actually are in a multirouting case.
9641 			 */
9642 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9643 				boolean_t need_resolve =
9644 				    ire_multirt_need_resolve(ipha_dst,
9645 					MBLK_GETLABEL(copy_mp), ipst);
9646 				if (!need_resolve) {
9647 					MULTIRT_DEBUG_UNTAG(copy_mp);
9648 					freemsg(copy_mp);
9649 					copy_mp = NULL;
9650 				} else {
9651 					/*
9652 					 * ipif_lookup_group() calls
9653 					 * ire_lookup_multi() that uses
9654 					 * ire_ftable_lookup() to find
9655 					 * an IRE_INTERFACE for the group.
9656 					 * In the multirt case,
9657 					 * ire_lookup_multi() then invokes
9658 					 * ire_multirt_lookup() to find
9659 					 * the next resolvable ire.
9660 					 * As a result, we obtain an new
9661 					 * interface, derived from the
9662 					 * next ire.
9663 					 */
9664 					ipif_refrele(ipif);
9665 					ipif = ipif_lookup_group(ipha_dst,
9666 					    zoneid, ipst);
9667 					ip2dbg(("ip_newroute_ipif: "
9668 					    "multirt dst %08x, ipif %p\n",
9669 					    htonl(dst), (void *)ipif));
9670 					if (ipif != NULL) {
9671 						mp = copy_mp;
9672 						copy_mp = NULL;
9673 						multirt_resolve_next = B_TRUE;
9674 						continue;
9675 					} else {
9676 						freemsg(copy_mp);
9677 					}
9678 				}
9679 			}
9680 			if (ipif != NULL)
9681 				ipif_refrele(ipif);
9682 			ill_refrele(dst_ill);
9683 			ipif_refrele(src_ipif);
9684 			return;
9685 		}
9686 		case IRE_IF_RESOLVER:
9687 			/*
9688 			 * We can't build an IRE_CACHE yet, but at least
9689 			 * we found a resolver that can help.
9690 			 */
9691 			res_mp = dst_ill->ill_resolver_mp;
9692 			if (!OK_RESOLVER_MP(res_mp))
9693 				break;
9694 
9695 			/*
9696 			 * We obtain a partial IRE_CACHE which we will pass
9697 			 * along with the resolver query.  When the response
9698 			 * comes back it will be there ready for us to add.
9699 			 * The new ire inherits the IRE_OFFSUBNET flags
9700 			 * and source address, if this was requested.
9701 			 * The ire_max_frag is atomically set under the
9702 			 * irebucket lock in ire_add_v[46]. Only in the
9703 			 * case of IRE_MARK_NOADD, we set it here itself.
9704 			 */
9705 			ire = ire_create_mp(
9706 			    (uchar_t *)&dst,		/* dest address */
9707 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9708 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9709 			    NULL,			/* gateway address */
9710 			    NULL,			/* no in_src_addr */
9711 			    (ire_marks & IRE_MARK_NOADD) ?
9712 				ipif->ipif_mtu : 0,	/* max_frag */
9713 			    NULL,			/* Fast path header */
9714 			    dst_ill->ill_rq,		/* recv-from queue */
9715 			    dst_ill->ill_wq,		/* send-to queue */
9716 			    IRE_CACHE,
9717 			    NULL,	/* let ire_nce_init figure res_mp out */
9718 			    src_ipif,
9719 			    NULL,
9720 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9721 			    (fire != NULL) ?		/* Parent handle */
9722 				fire->ire_phandle : 0,
9723 			    ihandle,			/* Interface handle */
9724 			    (fire != NULL) ?		/* flags if any */
9725 				(fire->ire_flags &
9726 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9727 			    (save_ire == NULL ? &ire_uinfo_null :
9728 				&save_ire->ire_uinfo),
9729 			    NULL,
9730 			    NULL,
9731 			    ipst);
9732 
9733 			if (save_ire != NULL) {
9734 				ire_refrele(save_ire);
9735 				save_ire = NULL;
9736 			}
9737 			if (ire == NULL)
9738 				break;
9739 
9740 			ire->ire_marks |= ire_marks;
9741 			/*
9742 			 * Construct message chain for the resolver of the
9743 			 * form:
9744 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9745 			 *
9746 			 * NOTE : ire will be added later when the response
9747 			 * comes back from ARP. If the response does not
9748 			 * come back, ARP frees the packet. For this reason,
9749 			 * we can't REFHOLD the bucket of save_ire to prevent
9750 			 * deletions. We may not be able to REFRELE the
9751 			 * bucket if the response never comes back.
9752 			 * Thus, before adding the ire, ire_add_v4 will make
9753 			 * sure that the interface route does not get deleted.
9754 			 * This is the only case unlike ip_newroute_v6,
9755 			 * ip_newroute_ipif_v6 where we can always prevent
9756 			 * deletions because ire_add_then_send is called after
9757 			 * creating the IRE.
9758 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9759 			 * does not add this IRE into the IRE CACHE.
9760 			 */
9761 			ASSERT(ire->ire_mp != NULL);
9762 			ire->ire_mp->b_cont = first_mp;
9763 			/* Have saved_mp handy, for cleanup if canput fails */
9764 			saved_mp = mp;
9765 			mp = copyb(res_mp);
9766 			if (mp == NULL) {
9767 				/* Prepare for cleanup */
9768 				mp = saved_mp; /* pkt */
9769 				ire_delete(ire); /* ire_mp */
9770 				ire = NULL;
9771 				if (copy_mp != NULL) {
9772 					MULTIRT_DEBUG_UNTAG(copy_mp);
9773 					freemsg(copy_mp);
9774 					copy_mp = NULL;
9775 				}
9776 				break;
9777 			}
9778 			linkb(mp, ire->ire_mp);
9779 
9780 			/*
9781 			 * Fill in the source and dest addrs for the resolver.
9782 			 * NOTE: this depends on memory layouts imposed by
9783 			 * ill_init().
9784 			 */
9785 			areq = (areq_t *)mp->b_rptr;
9786 			addrp = (ipaddr_t *)((char *)areq +
9787 			    areq->areq_sender_addr_offset);
9788 			*addrp = ire->ire_src_addr;
9789 			addrp = (ipaddr_t *)((char *)areq +
9790 			    areq->areq_target_addr_offset);
9791 			*addrp = dst;
9792 			/* Up to the resolver. */
9793 			if (canputnext(dst_ill->ill_rq) &&
9794 			    !(dst_ill->ill_arp_closing)) {
9795 				putnext(dst_ill->ill_rq, mp);
9796 				/*
9797 				 * The response will come back in ip_wput
9798 				 * with db_type IRE_DB_TYPE.
9799 				 */
9800 			} else {
9801 				mp->b_cont = NULL;
9802 				freeb(mp); /* areq */
9803 				ire_delete(ire); /* ire_mp */
9804 				saved_mp->b_next = NULL;
9805 				saved_mp->b_prev = NULL;
9806 				freemsg(first_mp); /* pkt */
9807 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9808 			}
9809 
9810 			if (fire != NULL) {
9811 				ire_refrele(fire);
9812 				fire = NULL;
9813 			}
9814 
9815 
9816 			/*
9817 			 * The resolution loop is re-entered if this was
9818 			 * requested through flags and we actually are
9819 			 * in a multirouting case.
9820 			 */
9821 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9822 				boolean_t need_resolve =
9823 				    ire_multirt_need_resolve(ipha_dst,
9824 					MBLK_GETLABEL(copy_mp), ipst);
9825 				if (!need_resolve) {
9826 					MULTIRT_DEBUG_UNTAG(copy_mp);
9827 					freemsg(copy_mp);
9828 					copy_mp = NULL;
9829 				} else {
9830 					/*
9831 					 * ipif_lookup_group() calls
9832 					 * ire_lookup_multi() that uses
9833 					 * ire_ftable_lookup() to find
9834 					 * an IRE_INTERFACE for the group.
9835 					 * In the multirt case,
9836 					 * ire_lookup_multi() then invokes
9837 					 * ire_multirt_lookup() to find
9838 					 * the next resolvable ire.
9839 					 * As a result, we obtain an new
9840 					 * interface, derived from the
9841 					 * next ire.
9842 					 */
9843 					ipif_refrele(ipif);
9844 					ipif = ipif_lookup_group(ipha_dst,
9845 					    zoneid, ipst);
9846 					if (ipif != NULL) {
9847 						mp = copy_mp;
9848 						copy_mp = NULL;
9849 						multirt_resolve_next = B_TRUE;
9850 						continue;
9851 					} else {
9852 						freemsg(copy_mp);
9853 					}
9854 				}
9855 			}
9856 			if (ipif != NULL)
9857 				ipif_refrele(ipif);
9858 			ill_refrele(dst_ill);
9859 			ipif_refrele(src_ipif);
9860 			return;
9861 		default:
9862 			break;
9863 		}
9864 	} while (multirt_resolve_next);
9865 
9866 err_ret:
9867 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9868 	if (fire != NULL)
9869 		ire_refrele(fire);
9870 	ipif_refrele(ipif);
9871 	/* Did this packet originate externally? */
9872 	if (dst_ill != NULL)
9873 		ill_refrele(dst_ill);
9874 	if (src_ipif != NULL)
9875 		ipif_refrele(src_ipif);
9876 	if (mp->b_prev || mp->b_next) {
9877 		mp->b_next = NULL;
9878 		mp->b_prev = NULL;
9879 	} else {
9880 		/*
9881 		 * Since ip_wput() isn't close to finished, we fill
9882 		 * in enough of the header for credible error reporting.
9883 		 */
9884 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9885 			/* Failed */
9886 			freemsg(first_mp);
9887 			if (ire != NULL)
9888 				ire_refrele(ire);
9889 			return;
9890 		}
9891 	}
9892 	/*
9893 	 * At this point we will have ire only if RTF_BLACKHOLE
9894 	 * or RTF_REJECT flags are set on the IRE. It will not
9895 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9896 	 */
9897 	if (ire != NULL) {
9898 		if (ire->ire_flags & RTF_BLACKHOLE) {
9899 			ire_refrele(ire);
9900 			freemsg(first_mp);
9901 			return;
9902 		}
9903 		ire_refrele(ire);
9904 	}
9905 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9906 }
9907 
9908 /* Name/Value Table Lookup Routine */
9909 char *
9910 ip_nv_lookup(nv_t *nv, int value)
9911 {
9912 	if (!nv)
9913 		return (NULL);
9914 	for (; nv->nv_name; nv++) {
9915 		if (nv->nv_value == value)
9916 			return (nv->nv_name);
9917 	}
9918 	return ("unknown");
9919 }
9920 
9921 /*
9922  * This is a module open, i.e. this is a control stream for access
9923  * to a DLPI device.  We allocate an ill_t as the instance data in
9924  * this case.
9925  */
9926 int
9927 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9928 {
9929 	ill_t	*ill;
9930 	int	err;
9931 	zoneid_t zoneid;
9932 	netstack_t *ns;
9933 	ip_stack_t *ipst;
9934 
9935 	/*
9936 	 * Prevent unprivileged processes from pushing IP so that
9937 	 * they can't send raw IP.
9938 	 */
9939 	if (secpolicy_net_rawaccess(credp) != 0)
9940 		return (EPERM);
9941 
9942 	ns = netstack_find_by_cred(credp);
9943 	ASSERT(ns != NULL);
9944 	ipst = ns->netstack_ip;
9945 	ASSERT(ipst != NULL);
9946 
9947 	/*
9948 	 * For exclusive stacks we set the zoneid to zero
9949 	 * to make IP operate as if in the global zone.
9950 	 */
9951 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9952 		zoneid = GLOBAL_ZONEID;
9953 	else
9954 		zoneid = crgetzoneid(credp);
9955 
9956 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9957 	q->q_ptr = WR(q)->q_ptr = ill;
9958 	ill->ill_ipst = ipst;
9959 	ill->ill_zoneid = zoneid;
9960 
9961 	/*
9962 	 * ill_init initializes the ill fields and then sends down
9963 	 * down a DL_INFO_REQ after calling qprocson.
9964 	 */
9965 	err = ill_init(q, ill);
9966 	if (err != 0) {
9967 		mi_free(ill);
9968 		netstack_rele(ipst->ips_netstack);
9969 		q->q_ptr = NULL;
9970 		WR(q)->q_ptr = NULL;
9971 		return (err);
9972 	}
9973 
9974 	/* ill_init initializes the ipsq marking this thread as writer */
9975 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9976 	/* Wait for the DL_INFO_ACK */
9977 	mutex_enter(&ill->ill_lock);
9978 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9979 		/*
9980 		 * Return value of 0 indicates a pending signal.
9981 		 */
9982 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9983 		if (err == 0) {
9984 			mutex_exit(&ill->ill_lock);
9985 			(void) ip_close(q, 0);
9986 			return (EINTR);
9987 		}
9988 	}
9989 	mutex_exit(&ill->ill_lock);
9990 
9991 	/*
9992 	 * ip_rput_other could have set an error  in ill_error on
9993 	 * receipt of M_ERROR.
9994 	 */
9995 
9996 	err = ill->ill_error;
9997 	if (err != 0) {
9998 		(void) ip_close(q, 0);
9999 		return (err);
10000 	}
10001 
10002 	ill->ill_credp = credp;
10003 	crhold(credp);
10004 
10005 	mutex_enter(&ipst->ips_ip_mi_lock);
10006 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
10007 	    credp);
10008 	mutex_exit(&ipst->ips_ip_mi_lock);
10009 	if (err) {
10010 		(void) ip_close(q, 0);
10011 		return (err);
10012 	}
10013 	return (0);
10014 }
10015 
10016 /* IP open routine. */
10017 int
10018 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
10019 {
10020 	conn_t 		*connp;
10021 	major_t		maj;
10022 	zoneid_t	zoneid;
10023 	netstack_t	*ns;
10024 	ip_stack_t	*ipst;
10025 
10026 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
10027 
10028 	/* Allow reopen. */
10029 	if (q->q_ptr != NULL)
10030 		return (0);
10031 
10032 	if (sflag & MODOPEN) {
10033 		/* This is a module open */
10034 		return (ip_modopen(q, devp, flag, sflag, credp));
10035 	}
10036 
10037 	ns = netstack_find_by_cred(credp);
10038 	ASSERT(ns != NULL);
10039 	ipst = ns->netstack_ip;
10040 	ASSERT(ipst != NULL);
10041 
10042 	/*
10043 	 * For exclusive stacks we set the zoneid to zero
10044 	 * to make IP operate as if in the global zone.
10045 	 */
10046 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
10047 		zoneid = GLOBAL_ZONEID;
10048 	else
10049 		zoneid = crgetzoneid(credp);
10050 
10051 	/*
10052 	 * We are opening as a device. This is an IP client stream, and we
10053 	 * allocate an conn_t as the instance data.
10054 	 */
10055 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
10056 
10057 	/*
10058 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
10059 	 * done by netstack_find_by_cred()
10060 	 */
10061 	netstack_rele(ipst->ips_netstack);
10062 
10063 	connp->conn_zoneid = zoneid;
10064 
10065 	connp->conn_upq = q;
10066 	q->q_ptr = WR(q)->q_ptr = connp;
10067 
10068 	if (flag & SO_SOCKSTR)
10069 		connp->conn_flags |= IPCL_SOCKET;
10070 
10071 	/* Minor tells us which /dev entry was opened */
10072 	if (geteminor(*devp) == IPV6_MINOR) {
10073 		connp->conn_flags |= IPCL_ISV6;
10074 		connp->conn_af_isv6 = B_TRUE;
10075 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
10076 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
10077 	} else {
10078 		connp->conn_af_isv6 = B_FALSE;
10079 		connp->conn_pkt_isv6 = B_FALSE;
10080 	}
10081 
10082 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
10083 		/* CONN_DEC_REF takes care of netstack_rele() */
10084 		q->q_ptr = WR(q)->q_ptr = NULL;
10085 		CONN_DEC_REF(connp);
10086 		return (EBUSY);
10087 	}
10088 
10089 	maj = getemajor(*devp);
10090 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
10091 
10092 	/*
10093 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
10094 	 */
10095 	connp->conn_cred = credp;
10096 	crhold(connp->conn_cred);
10097 
10098 	/*
10099 	 * If the caller has the process-wide flag set, then default to MAC
10100 	 * exempt mode.  This allows read-down to unlabeled hosts.
10101 	 */
10102 	if (getpflags(NET_MAC_AWARE, credp) != 0)
10103 		connp->conn_mac_exempt = B_TRUE;
10104 
10105 	/*
10106 	 * This should only happen for ndd, netstat, raw socket or other SCTP
10107 	 * administrative ops.  In these cases, we just need a normal conn_t
10108 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
10109 	 * an error will be returned.
10110 	 */
10111 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
10112 		connp->conn_rq = q;
10113 		connp->conn_wq = WR(q);
10114 	} else {
10115 		connp->conn_ulp = IPPROTO_SCTP;
10116 		connp->conn_rq = connp->conn_wq = NULL;
10117 	}
10118 	/* Non-zero default values */
10119 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
10120 
10121 	/*
10122 	 * Make the conn globally visible to walkers
10123 	 */
10124 	mutex_enter(&connp->conn_lock);
10125 	connp->conn_state_flags &= ~CONN_INCIPIENT;
10126 	mutex_exit(&connp->conn_lock);
10127 	ASSERT(connp->conn_ref == 1);
10128 
10129 	qprocson(q);
10130 
10131 	return (0);
10132 }
10133 
10134 /*
10135  * Change q_qinfo based on the value of isv6.
10136  * This can not called on an ill queue.
10137  * Note that there is no race since either q_qinfo works for conn queues - it
10138  * is just an optimization to enter the best wput routine directly.
10139  */
10140 void
10141 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
10142 {
10143 	ASSERT(q->q_flag & QREADR);
10144 	ASSERT(WR(q)->q_next == NULL);
10145 	ASSERT(q->q_ptr != NULL);
10146 
10147 	if (minor == IPV6_MINOR)  {
10148 		if (bump_mib) {
10149 			BUMP_MIB(&ipst->ips_ip6_mib,
10150 			    ipIfStatsOutSwitchIPVersion);
10151 		}
10152 		q->q_qinfo = &rinit_ipv6;
10153 		WR(q)->q_qinfo = &winit_ipv6;
10154 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
10155 	} else {
10156 		if (bump_mib) {
10157 			BUMP_MIB(&ipst->ips_ip_mib,
10158 			    ipIfStatsOutSwitchIPVersion);
10159 		}
10160 		q->q_qinfo = &iprinit;
10161 		WR(q)->q_qinfo = &ipwinit;
10162 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
10163 	}
10164 
10165 }
10166 
10167 /*
10168  * See if IPsec needs loading because of the options in mp.
10169  */
10170 static boolean_t
10171 ipsec_opt_present(mblk_t *mp)
10172 {
10173 	uint8_t *optcp, *next_optcp, *opt_endcp;
10174 	struct opthdr *opt;
10175 	struct T_opthdr *topt;
10176 	int opthdr_len;
10177 	t_uscalar_t optname, optlevel;
10178 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10179 	ipsec_req_t *ipsr;
10180 
10181 	/*
10182 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10183 	 * return TRUE.
10184 	 */
10185 
10186 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10187 	opt_endcp = optcp + tor->OPT_length;
10188 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10189 		opthdr_len = sizeof (struct T_opthdr);
10190 	} else {		/* O_OPTMGMT_REQ */
10191 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10192 		opthdr_len = sizeof (struct opthdr);
10193 	}
10194 	for (; optcp < opt_endcp; optcp = next_optcp) {
10195 		if (optcp + opthdr_len > opt_endcp)
10196 			return (B_FALSE);	/* Not enough option header. */
10197 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10198 			topt = (struct T_opthdr *)optcp;
10199 			optlevel = topt->level;
10200 			optname = topt->name;
10201 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10202 		} else {
10203 			opt = (struct opthdr *)optcp;
10204 			optlevel = opt->level;
10205 			optname = opt->name;
10206 			next_optcp = optcp + opthdr_len +
10207 			    _TPI_ALIGN_OPT(opt->len);
10208 		}
10209 		if ((next_optcp < optcp) || /* wraparound pointer space */
10210 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10211 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10212 			return (B_FALSE); /* bad option buffer */
10213 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10214 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10215 			/*
10216 			 * Check to see if it's an all-bypass or all-zeroes
10217 			 * IPsec request.  Don't bother loading IPsec if
10218 			 * the socket doesn't want to use it.  (A good example
10219 			 * is a bypass request.)
10220 			 *
10221 			 * Basically, if any of the non-NEVER bits are set,
10222 			 * load IPsec.
10223 			 */
10224 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10225 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10226 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10227 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10228 			    != 0)
10229 				return (B_TRUE);
10230 		}
10231 	}
10232 	return (B_FALSE);
10233 }
10234 
10235 /*
10236  * If conn is is waiting for ipsec to finish loading, kick it.
10237  */
10238 /* ARGSUSED */
10239 static void
10240 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10241 {
10242 	t_scalar_t	optreq_prim;
10243 	mblk_t		*mp;
10244 	cred_t		*cr;
10245 	int		err = 0;
10246 
10247 	/*
10248 	 * This function is called, after ipsec loading is complete.
10249 	 * Since IP checks exclusively and atomically (i.e it prevents
10250 	 * ipsec load from completing until ip_optcom_req completes)
10251 	 * whether ipsec load is complete, there cannot be a race with IP
10252 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10253 	 */
10254 	mutex_enter(&connp->conn_lock);
10255 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10256 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10257 		mp = connp->conn_ipsec_opt_mp;
10258 		connp->conn_ipsec_opt_mp = NULL;
10259 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10260 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10261 		mutex_exit(&connp->conn_lock);
10262 
10263 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10264 
10265 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10266 		if (optreq_prim == T_OPTMGMT_REQ) {
10267 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10268 			    &ip_opt_obj);
10269 		} else {
10270 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10271 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10272 			    &ip_opt_obj);
10273 		}
10274 		if (err != EINPROGRESS)
10275 			CONN_OPER_PENDING_DONE(connp);
10276 		return;
10277 	}
10278 	mutex_exit(&connp->conn_lock);
10279 }
10280 
10281 /*
10282  * Called from the ipsec_loader thread, outside any perimeter, to tell
10283  * ip qenable any of the queues waiting for the ipsec loader to
10284  * complete.
10285  */
10286 void
10287 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10288 {
10289 	netstack_t *ns = ipss->ipsec_netstack;
10290 
10291 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10292 }
10293 
10294 /*
10295  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10296  * determines the grp on which it has to become exclusive, queues the mp
10297  * and sq draining restarts the optmgmt
10298  */
10299 static boolean_t
10300 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10301 {
10302 	conn_t *connp = Q_TO_CONN(q);
10303 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10304 
10305 	/*
10306 	 * Take IPsec requests and treat them special.
10307 	 */
10308 	if (ipsec_opt_present(mp)) {
10309 		/* First check if IPsec is loaded. */
10310 		mutex_enter(&ipss->ipsec_loader_lock);
10311 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10312 			mutex_exit(&ipss->ipsec_loader_lock);
10313 			return (B_FALSE);
10314 		}
10315 		mutex_enter(&connp->conn_lock);
10316 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10317 
10318 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10319 		connp->conn_ipsec_opt_mp = mp;
10320 		mutex_exit(&connp->conn_lock);
10321 		mutex_exit(&ipss->ipsec_loader_lock);
10322 
10323 		ipsec_loader_loadnow(ipss);
10324 		return (B_TRUE);
10325 	}
10326 	return (B_FALSE);
10327 }
10328 
10329 /*
10330  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10331  * all of them are copied to the conn_t. If the req is "zero", the policy is
10332  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10333  * fields.
10334  * We keep only the latest setting of the policy and thus policy setting
10335  * is not incremental/cumulative.
10336  *
10337  * Requests to set policies with multiple alternative actions will
10338  * go through a different API.
10339  */
10340 int
10341 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10342 {
10343 	uint_t ah_req = 0;
10344 	uint_t esp_req = 0;
10345 	uint_t se_req = 0;
10346 	ipsec_selkey_t sel;
10347 	ipsec_act_t *actp = NULL;
10348 	uint_t nact;
10349 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10350 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10351 	ipsec_policy_root_t *pr;
10352 	ipsec_policy_head_t *ph;
10353 	int fam;
10354 	boolean_t is_pol_reset;
10355 	int error = 0;
10356 	netstack_t	*ns = connp->conn_netstack;
10357 	ip_stack_t	*ipst = ns->netstack_ip;
10358 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10359 
10360 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10361 
10362 	/*
10363 	 * The IP_SEC_OPT option does not allow variable length parameters,
10364 	 * hence a request cannot be NULL.
10365 	 */
10366 	if (req == NULL)
10367 		return (EINVAL);
10368 
10369 	ah_req = req->ipsr_ah_req;
10370 	esp_req = req->ipsr_esp_req;
10371 	se_req = req->ipsr_self_encap_req;
10372 
10373 	/*
10374 	 * Are we dealing with a request to reset the policy (i.e.
10375 	 * zero requests).
10376 	 */
10377 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10378 	    (esp_req & REQ_MASK) == 0 &&
10379 	    (se_req & REQ_MASK) == 0);
10380 
10381 	if (!is_pol_reset) {
10382 		/*
10383 		 * If we couldn't load IPsec, fail with "protocol
10384 		 * not supported".
10385 		 * IPsec may not have been loaded for a request with zero
10386 		 * policies, so we don't fail in this case.
10387 		 */
10388 		mutex_enter(&ipss->ipsec_loader_lock);
10389 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10390 			mutex_exit(&ipss->ipsec_loader_lock);
10391 			return (EPROTONOSUPPORT);
10392 		}
10393 		mutex_exit(&ipss->ipsec_loader_lock);
10394 
10395 		/*
10396 		 * Test for valid requests. Invalid algorithms
10397 		 * need to be tested by IPSEC code because new
10398 		 * algorithms can be added dynamically.
10399 		 */
10400 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10401 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10402 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10403 			return (EINVAL);
10404 		}
10405 
10406 		/*
10407 		 * Only privileged users can issue these
10408 		 * requests.
10409 		 */
10410 		if (((ah_req & IPSEC_PREF_NEVER) ||
10411 		    (esp_req & IPSEC_PREF_NEVER) ||
10412 		    (se_req & IPSEC_PREF_NEVER)) &&
10413 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10414 			return (EPERM);
10415 		}
10416 
10417 		/*
10418 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10419 		 * are mutually exclusive.
10420 		 */
10421 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10422 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10423 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10424 			/* Both of them are set */
10425 			return (EINVAL);
10426 		}
10427 	}
10428 
10429 	mutex_enter(&connp->conn_lock);
10430 
10431 	/*
10432 	 * If we have already cached policies in ip_bind_connected*(), don't
10433 	 * let them change now. We cache policies for connections
10434 	 * whose src,dst [addr, port] is known.
10435 	 */
10436 	if (connp->conn_policy_cached) {
10437 		mutex_exit(&connp->conn_lock);
10438 		return (EINVAL);
10439 	}
10440 
10441 	/*
10442 	 * We have a zero policies, reset the connection policy if already
10443 	 * set. This will cause the connection to inherit the
10444 	 * global policy, if any.
10445 	 */
10446 	if (is_pol_reset) {
10447 		if (connp->conn_policy != NULL) {
10448 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10449 			connp->conn_policy = NULL;
10450 		}
10451 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10452 		connp->conn_in_enforce_policy = B_FALSE;
10453 		connp->conn_out_enforce_policy = B_FALSE;
10454 		mutex_exit(&connp->conn_lock);
10455 		return (0);
10456 	}
10457 
10458 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10459 	    ipst->ips_netstack);
10460 	if (ph == NULL)
10461 		goto enomem;
10462 
10463 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10464 	if (actp == NULL)
10465 		goto enomem;
10466 
10467 	/*
10468 	 * Always allocate IPv4 policy entries, since they can also
10469 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10470 	 */
10471 	bzero(&sel, sizeof (sel));
10472 	sel.ipsl_valid = IPSL_IPV4;
10473 
10474 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10475 	    ipst->ips_netstack);
10476 	if (pin4 == NULL)
10477 		goto enomem;
10478 
10479 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10480 	    ipst->ips_netstack);
10481 	if (pout4 == NULL)
10482 		goto enomem;
10483 
10484 	if (connp->conn_pkt_isv6) {
10485 		/*
10486 		 * We're looking at a v6 socket, also allocate the
10487 		 * v6-specific entries...
10488 		 */
10489 		sel.ipsl_valid = IPSL_IPV6;
10490 		pin6 = ipsec_policy_create(&sel, actp, nact,
10491 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10492 		if (pin6 == NULL)
10493 			goto enomem;
10494 
10495 		pout6 = ipsec_policy_create(&sel, actp, nact,
10496 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10497 		if (pout6 == NULL)
10498 			goto enomem;
10499 
10500 		/*
10501 		 * .. and file them away in the right place.
10502 		 */
10503 		fam = IPSEC_AF_V6;
10504 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10505 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10506 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10507 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10508 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10509 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10510 	}
10511 
10512 	ipsec_actvec_free(actp, nact);
10513 
10514 	/*
10515 	 * File the v4 policies.
10516 	 */
10517 	fam = IPSEC_AF_V4;
10518 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10519 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10520 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10521 
10522 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10523 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10524 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10525 
10526 	/*
10527 	 * If the requests need security, set enforce_policy.
10528 	 * If the requests are IPSEC_PREF_NEVER, one should
10529 	 * still set conn_out_enforce_policy so that an ipsec_out
10530 	 * gets attached in ip_wput. This is needed so that
10531 	 * for connections that we don't cache policy in ip_bind,
10532 	 * if global policy matches in ip_wput_attach_policy, we
10533 	 * don't wrongly inherit global policy. Similarly, we need
10534 	 * to set conn_in_enforce_policy also so that we don't verify
10535 	 * policy wrongly.
10536 	 */
10537 	if ((ah_req & REQ_MASK) != 0 ||
10538 	    (esp_req & REQ_MASK) != 0 ||
10539 	    (se_req & REQ_MASK) != 0) {
10540 		connp->conn_in_enforce_policy = B_TRUE;
10541 		connp->conn_out_enforce_policy = B_TRUE;
10542 		connp->conn_flags |= IPCL_CHECK_POLICY;
10543 	}
10544 
10545 	mutex_exit(&connp->conn_lock);
10546 	return (error);
10547 #undef REQ_MASK
10548 
10549 	/*
10550 	 * Common memory-allocation-failure exit path.
10551 	 */
10552 enomem:
10553 	mutex_exit(&connp->conn_lock);
10554 	if (actp != NULL)
10555 		ipsec_actvec_free(actp, nact);
10556 	if (pin4 != NULL)
10557 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10558 	if (pout4 != NULL)
10559 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10560 	if (pin6 != NULL)
10561 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10562 	if (pout6 != NULL)
10563 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10564 	return (ENOMEM);
10565 }
10566 
10567 /*
10568  * Only for options that pass in an IP addr. Currently only V4 options
10569  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10570  * So this function assumes level is IPPROTO_IP
10571  */
10572 int
10573 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10574     mblk_t *first_mp)
10575 {
10576 	ipif_t *ipif = NULL;
10577 	int error;
10578 	ill_t *ill;
10579 	int zoneid;
10580 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10581 
10582 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10583 
10584 	if (addr != INADDR_ANY || checkonly) {
10585 		ASSERT(connp != NULL);
10586 		zoneid = IPCL_ZONEID(connp);
10587 		if (option == IP_NEXTHOP) {
10588 			ipif = ipif_lookup_onlink_addr(addr,
10589 			    connp->conn_zoneid, ipst);
10590 		} else {
10591 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10592 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10593 			    &error, ipst);
10594 		}
10595 		if (ipif == NULL) {
10596 			if (error == EINPROGRESS)
10597 				return (error);
10598 			else if ((option == IP_MULTICAST_IF) ||
10599 			    (option == IP_NEXTHOP))
10600 				return (EHOSTUNREACH);
10601 			else
10602 				return (EINVAL);
10603 		} else if (checkonly) {
10604 			if (option == IP_MULTICAST_IF) {
10605 				ill = ipif->ipif_ill;
10606 				/* not supported by the virtual network iface */
10607 				if (IS_VNI(ill)) {
10608 					ipif_refrele(ipif);
10609 					return (EINVAL);
10610 				}
10611 			}
10612 			ipif_refrele(ipif);
10613 			return (0);
10614 		}
10615 		ill = ipif->ipif_ill;
10616 		mutex_enter(&connp->conn_lock);
10617 		mutex_enter(&ill->ill_lock);
10618 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10619 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10620 			mutex_exit(&ill->ill_lock);
10621 			mutex_exit(&connp->conn_lock);
10622 			ipif_refrele(ipif);
10623 			return (option == IP_MULTICAST_IF ?
10624 			    EHOSTUNREACH : EINVAL);
10625 		}
10626 	} else {
10627 		mutex_enter(&connp->conn_lock);
10628 	}
10629 
10630 	/* None of the options below are supported on the VNI */
10631 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10632 		mutex_exit(&ill->ill_lock);
10633 		mutex_exit(&connp->conn_lock);
10634 		ipif_refrele(ipif);
10635 		return (EINVAL);
10636 	}
10637 
10638 	switch (option) {
10639 	case IP_DONTFAILOVER_IF:
10640 		/*
10641 		 * This option is used by in.mpathd to ensure
10642 		 * that IPMP probe packets only go out on the
10643 		 * test interfaces. in.mpathd sets this option
10644 		 * on the non-failover interfaces.
10645 		 * For backward compatibility, this option
10646 		 * implicitly sets IP_MULTICAST_IF, as used
10647 		 * be done in bind(), so that ip_wput gets
10648 		 * this ipif to send mcast packets.
10649 		 */
10650 		if (ipif != NULL) {
10651 			ASSERT(addr != INADDR_ANY);
10652 			connp->conn_nofailover_ill = ipif->ipif_ill;
10653 			connp->conn_multicast_ipif = ipif;
10654 		} else {
10655 			ASSERT(addr == INADDR_ANY);
10656 			connp->conn_nofailover_ill = NULL;
10657 			connp->conn_multicast_ipif = NULL;
10658 		}
10659 		break;
10660 
10661 	case IP_MULTICAST_IF:
10662 		connp->conn_multicast_ipif = ipif;
10663 		break;
10664 	case IP_NEXTHOP:
10665 		connp->conn_nexthop_v4 = addr;
10666 		connp->conn_nexthop_set = B_TRUE;
10667 		break;
10668 	}
10669 
10670 	if (ipif != NULL) {
10671 		mutex_exit(&ill->ill_lock);
10672 		mutex_exit(&connp->conn_lock);
10673 		ipif_refrele(ipif);
10674 		return (0);
10675 	}
10676 	mutex_exit(&connp->conn_lock);
10677 	/* We succeded in cleared the option */
10678 	return (0);
10679 }
10680 
10681 /*
10682  * For options that pass in an ifindex specifying the ill. V6 options always
10683  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10684  */
10685 int
10686 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10687     int level, int option, mblk_t *first_mp)
10688 {
10689 	ill_t *ill = NULL;
10690 	int error = 0;
10691 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10692 
10693 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10694 	if (ifindex != 0) {
10695 		ASSERT(connp != NULL);
10696 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10697 		    first_mp, ip_restart_optmgmt, &error, ipst);
10698 		if (ill != NULL) {
10699 			if (checkonly) {
10700 				/* not supported by the virtual network iface */
10701 				if (IS_VNI(ill)) {
10702 					ill_refrele(ill);
10703 					return (EINVAL);
10704 				}
10705 				ill_refrele(ill);
10706 				return (0);
10707 			}
10708 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10709 			    0, NULL)) {
10710 				ill_refrele(ill);
10711 				ill = NULL;
10712 				mutex_enter(&connp->conn_lock);
10713 				goto setit;
10714 			}
10715 			mutex_enter(&connp->conn_lock);
10716 			mutex_enter(&ill->ill_lock);
10717 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10718 				mutex_exit(&ill->ill_lock);
10719 				mutex_exit(&connp->conn_lock);
10720 				ill_refrele(ill);
10721 				ill = NULL;
10722 				mutex_enter(&connp->conn_lock);
10723 			}
10724 			goto setit;
10725 		} else if (error == EINPROGRESS) {
10726 			return (error);
10727 		} else {
10728 			error = 0;
10729 		}
10730 	}
10731 	mutex_enter(&connp->conn_lock);
10732 setit:
10733 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10734 
10735 	/*
10736 	 * The options below assume that the ILL (if any) transmits and/or
10737 	 * receives traffic. Neither of which is true for the virtual network
10738 	 * interface, so fail setting these on a VNI.
10739 	 */
10740 	if (IS_VNI(ill)) {
10741 		ASSERT(ill != NULL);
10742 		mutex_exit(&ill->ill_lock);
10743 		mutex_exit(&connp->conn_lock);
10744 		ill_refrele(ill);
10745 		return (EINVAL);
10746 	}
10747 
10748 	if (level == IPPROTO_IP) {
10749 		switch (option) {
10750 		case IP_BOUND_IF:
10751 			connp->conn_incoming_ill = ill;
10752 			connp->conn_outgoing_ill = ill;
10753 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10754 			    0 : ifindex;
10755 			break;
10756 
10757 		case IP_XMIT_IF:
10758 			/*
10759 			 * Similar to IP_BOUND_IF, but this only
10760 			 * determines the outgoing interface for
10761 			 * unicast packets. Also no IRE_CACHE entry
10762 			 * is added for the destination of the
10763 			 * outgoing packets. This feature is needed
10764 			 * for mobile IP.
10765 			 */
10766 			connp->conn_xmit_if_ill = ill;
10767 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10768 			    0 : ifindex;
10769 			break;
10770 
10771 		case IP_MULTICAST_IF:
10772 			/*
10773 			 * This option is an internal special. The socket
10774 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10775 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10776 			 * specifies an ifindex and we try first on V6 ill's.
10777 			 * If we don't find one, we they try using on v4 ill's
10778 			 * intenally and we come here.
10779 			 */
10780 			if (!checkonly && ill != NULL) {
10781 				ipif_t	*ipif;
10782 				ipif = ill->ill_ipif;
10783 
10784 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10785 					mutex_exit(&ill->ill_lock);
10786 					mutex_exit(&connp->conn_lock);
10787 					ill_refrele(ill);
10788 					ill = NULL;
10789 					mutex_enter(&connp->conn_lock);
10790 				} else {
10791 					connp->conn_multicast_ipif = ipif;
10792 				}
10793 			}
10794 			break;
10795 		}
10796 	} else {
10797 		switch (option) {
10798 		case IPV6_BOUND_IF:
10799 			connp->conn_incoming_ill = ill;
10800 			connp->conn_outgoing_ill = ill;
10801 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10802 			    0 : ifindex;
10803 			break;
10804 
10805 		case IPV6_BOUND_PIF:
10806 			/*
10807 			 * Limit all transmit to this ill.
10808 			 * Unlike IPV6_BOUND_IF, using this option
10809 			 * prevents load spreading and failover from
10810 			 * happening when the interface is part of the
10811 			 * group. That's why we don't need to remember
10812 			 * the ifindex in orig_bound_ifindex as in
10813 			 * IPV6_BOUND_IF.
10814 			 */
10815 			connp->conn_outgoing_pill = ill;
10816 			break;
10817 
10818 		case IPV6_DONTFAILOVER_IF:
10819 			/*
10820 			 * This option is used by in.mpathd to ensure
10821 			 * that IPMP probe packets only go out on the
10822 			 * test interfaces. in.mpathd sets this option
10823 			 * on the non-failover interfaces.
10824 			 */
10825 			connp->conn_nofailover_ill = ill;
10826 			/*
10827 			 * For backward compatibility, this option
10828 			 * implicitly sets ip_multicast_ill as used in
10829 			 * IP_MULTICAST_IF so that ip_wput gets
10830 			 * this ipif to send mcast packets.
10831 			 */
10832 			connp->conn_multicast_ill = ill;
10833 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10834 			    0 : ifindex;
10835 			break;
10836 
10837 		case IPV6_MULTICAST_IF:
10838 			/*
10839 			 * Set conn_multicast_ill to be the IPv6 ill.
10840 			 * Set conn_multicast_ipif to be an IPv4 ipif
10841 			 * for ifindex to make IPv4 mapped addresses
10842 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10843 			 * Even if no IPv6 ill exists for the ifindex
10844 			 * we need to check for an IPv4 ifindex in order
10845 			 * for this to work with mapped addresses. In that
10846 			 * case only set conn_multicast_ipif.
10847 			 */
10848 			if (!checkonly) {
10849 				if (ifindex == 0) {
10850 					connp->conn_multicast_ill = NULL;
10851 					connp->conn_orig_multicast_ifindex = 0;
10852 					connp->conn_multicast_ipif = NULL;
10853 				} else if (ill != NULL) {
10854 					connp->conn_multicast_ill = ill;
10855 					connp->conn_orig_multicast_ifindex =
10856 					    ifindex;
10857 				}
10858 			}
10859 			break;
10860 		}
10861 	}
10862 
10863 	if (ill != NULL) {
10864 		mutex_exit(&ill->ill_lock);
10865 		mutex_exit(&connp->conn_lock);
10866 		ill_refrele(ill);
10867 		return (0);
10868 	}
10869 	mutex_exit(&connp->conn_lock);
10870 	/*
10871 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10872 	 * locate the ill and could not set the option (ifindex != 0)
10873 	 */
10874 	return (ifindex == 0 ? 0 : EINVAL);
10875 }
10876 
10877 /* This routine sets socket options. */
10878 /* ARGSUSED */
10879 int
10880 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10881     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10882     void *dummy, cred_t *cr, mblk_t *first_mp)
10883 {
10884 	int		*i1 = (int *)invalp;
10885 	conn_t		*connp = Q_TO_CONN(q);
10886 	int		error = 0;
10887 	boolean_t	checkonly;
10888 	ire_t		*ire;
10889 	boolean_t	found;
10890 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10891 
10892 	switch (optset_context) {
10893 
10894 	case SETFN_OPTCOM_CHECKONLY:
10895 		checkonly = B_TRUE;
10896 		/*
10897 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10898 		 * inlen != 0 implies value supplied and
10899 		 * 	we have to "pretend" to set it.
10900 		 * inlen == 0 implies that there is no
10901 		 * 	value part in T_CHECK request and just validation
10902 		 * done elsewhere should be enough, we just return here.
10903 		 */
10904 		if (inlen == 0) {
10905 			*outlenp = 0;
10906 			return (0);
10907 		}
10908 		break;
10909 	case SETFN_OPTCOM_NEGOTIATE:
10910 	case SETFN_UD_NEGOTIATE:
10911 	case SETFN_CONN_NEGOTIATE:
10912 		checkonly = B_FALSE;
10913 		break;
10914 	default:
10915 		/*
10916 		 * We should never get here
10917 		 */
10918 		*outlenp = 0;
10919 		return (EINVAL);
10920 	}
10921 
10922 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10923 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10924 
10925 	/*
10926 	 * For fixed length options, no sanity check
10927 	 * of passed in length is done. It is assumed *_optcom_req()
10928 	 * routines do the right thing.
10929 	 */
10930 
10931 	switch (level) {
10932 	case SOL_SOCKET:
10933 		/*
10934 		 * conn_lock protects the bitfields, and is used to
10935 		 * set the fields atomically.
10936 		 */
10937 		switch (name) {
10938 		case SO_BROADCAST:
10939 			if (!checkonly) {
10940 				/* TODO: use value someplace? */
10941 				mutex_enter(&connp->conn_lock);
10942 				connp->conn_broadcast = *i1 ? 1 : 0;
10943 				mutex_exit(&connp->conn_lock);
10944 			}
10945 			break;	/* goto sizeof (int) option return */
10946 		case SO_USELOOPBACK:
10947 			if (!checkonly) {
10948 				/* TODO: use value someplace? */
10949 				mutex_enter(&connp->conn_lock);
10950 				connp->conn_loopback = *i1 ? 1 : 0;
10951 				mutex_exit(&connp->conn_lock);
10952 			}
10953 			break;	/* goto sizeof (int) option return */
10954 		case SO_DONTROUTE:
10955 			if (!checkonly) {
10956 				mutex_enter(&connp->conn_lock);
10957 				connp->conn_dontroute = *i1 ? 1 : 0;
10958 				mutex_exit(&connp->conn_lock);
10959 			}
10960 			break;	/* goto sizeof (int) option return */
10961 		case SO_REUSEADDR:
10962 			if (!checkonly) {
10963 				mutex_enter(&connp->conn_lock);
10964 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10965 				mutex_exit(&connp->conn_lock);
10966 			}
10967 			break;	/* goto sizeof (int) option return */
10968 		case SO_PROTOTYPE:
10969 			if (!checkonly) {
10970 				mutex_enter(&connp->conn_lock);
10971 				connp->conn_proto = *i1;
10972 				mutex_exit(&connp->conn_lock);
10973 			}
10974 			break;	/* goto sizeof (int) option return */
10975 		case SO_ALLZONES:
10976 			if (!checkonly) {
10977 				mutex_enter(&connp->conn_lock);
10978 				if (IPCL_IS_BOUND(connp)) {
10979 					mutex_exit(&connp->conn_lock);
10980 					return (EINVAL);
10981 				}
10982 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10983 				mutex_exit(&connp->conn_lock);
10984 			}
10985 			break;	/* goto sizeof (int) option return */
10986 		case SO_ANON_MLP:
10987 			if (!checkonly) {
10988 				mutex_enter(&connp->conn_lock);
10989 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10990 				mutex_exit(&connp->conn_lock);
10991 			}
10992 			break;	/* goto sizeof (int) option return */
10993 		case SO_MAC_EXEMPT:
10994 			if (secpolicy_net_mac_aware(cr) != 0 ||
10995 			    IPCL_IS_BOUND(connp))
10996 				return (EACCES);
10997 			if (!checkonly) {
10998 				mutex_enter(&connp->conn_lock);
10999 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
11000 				mutex_exit(&connp->conn_lock);
11001 			}
11002 			break;	/* goto sizeof (int) option return */
11003 		default:
11004 			/*
11005 			 * "soft" error (negative)
11006 			 * option not handled at this level
11007 			 * Note: Do not modify *outlenp
11008 			 */
11009 			return (-EINVAL);
11010 		}
11011 		break;
11012 	case IPPROTO_IP:
11013 		switch (name) {
11014 		case IP_NEXTHOP:
11015 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
11016 				return (EPERM);
11017 			/* FALLTHRU */
11018 		case IP_MULTICAST_IF:
11019 		case IP_DONTFAILOVER_IF: {
11020 			ipaddr_t addr = *i1;
11021 
11022 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
11023 			    first_mp);
11024 			if (error != 0)
11025 				return (error);
11026 			break;	/* goto sizeof (int) option return */
11027 		}
11028 
11029 		case IP_MULTICAST_TTL:
11030 			/* Recorded in transport above IP */
11031 			*outvalp = *invalp;
11032 			*outlenp = sizeof (uchar_t);
11033 			return (0);
11034 		case IP_MULTICAST_LOOP:
11035 			if (!checkonly) {
11036 				mutex_enter(&connp->conn_lock);
11037 				connp->conn_multicast_loop = *invalp ? 1 : 0;
11038 				mutex_exit(&connp->conn_lock);
11039 			}
11040 			*outvalp = *invalp;
11041 			*outlenp = sizeof (uchar_t);
11042 			return (0);
11043 		case IP_ADD_MEMBERSHIP:
11044 		case MCAST_JOIN_GROUP:
11045 		case IP_DROP_MEMBERSHIP:
11046 		case MCAST_LEAVE_GROUP: {
11047 			struct ip_mreq *mreqp;
11048 			struct group_req *greqp;
11049 			ire_t *ire;
11050 			boolean_t done = B_FALSE;
11051 			ipaddr_t group, ifaddr;
11052 			struct sockaddr_in *sin;
11053 			uint32_t *ifindexp;
11054 			boolean_t mcast_opt = B_TRUE;
11055 			mcast_record_t fmode;
11056 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11057 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11058 
11059 			switch (name) {
11060 			case IP_ADD_MEMBERSHIP:
11061 				mcast_opt = B_FALSE;
11062 				/* FALLTHRU */
11063 			case MCAST_JOIN_GROUP:
11064 				fmode = MODE_IS_EXCLUDE;
11065 				optfn = ip_opt_add_group;
11066 				break;
11067 
11068 			case IP_DROP_MEMBERSHIP:
11069 				mcast_opt = B_FALSE;
11070 				/* FALLTHRU */
11071 			case MCAST_LEAVE_GROUP:
11072 				fmode = MODE_IS_INCLUDE;
11073 				optfn = ip_opt_delete_group;
11074 				break;
11075 			}
11076 
11077 			if (mcast_opt) {
11078 				greqp = (struct group_req *)i1;
11079 				sin = (struct sockaddr_in *)&greqp->gr_group;
11080 				if (sin->sin_family != AF_INET) {
11081 					*outlenp = 0;
11082 					return (ENOPROTOOPT);
11083 				}
11084 				group = (ipaddr_t)sin->sin_addr.s_addr;
11085 				ifaddr = INADDR_ANY;
11086 				ifindexp = &greqp->gr_interface;
11087 			} else {
11088 				mreqp = (struct ip_mreq *)i1;
11089 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
11090 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
11091 				ifindexp = NULL;
11092 			}
11093 
11094 			/*
11095 			 * In the multirouting case, we need to replicate
11096 			 * the request on all interfaces that will take part
11097 			 * in replication.  We do so because multirouting is
11098 			 * reflective, thus we will probably receive multi-
11099 			 * casts on those interfaces.
11100 			 * The ip_multirt_apply_membership() succeeds if the
11101 			 * operation succeeds on at least one interface.
11102 			 */
11103 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
11104 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11105 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11106 			if (ire != NULL) {
11107 				if (ire->ire_flags & RTF_MULTIRT) {
11108 					error = ip_multirt_apply_membership(
11109 					    optfn, ire, connp, checkonly, group,
11110 					    fmode, INADDR_ANY, first_mp);
11111 					done = B_TRUE;
11112 				}
11113 				ire_refrele(ire);
11114 			}
11115 			if (!done) {
11116 				error = optfn(connp, checkonly, group, ifaddr,
11117 				    ifindexp, fmode, INADDR_ANY, first_mp);
11118 			}
11119 			if (error) {
11120 				/*
11121 				 * EINPROGRESS is a soft error, needs retry
11122 				 * so don't make *outlenp zero.
11123 				 */
11124 				if (error != EINPROGRESS)
11125 					*outlenp = 0;
11126 				return (error);
11127 			}
11128 			/* OK return - copy input buffer into output buffer */
11129 			if (invalp != outvalp) {
11130 				/* don't trust bcopy for identical src/dst */
11131 				bcopy(invalp, outvalp, inlen);
11132 			}
11133 			*outlenp = inlen;
11134 			return (0);
11135 		}
11136 		case IP_BLOCK_SOURCE:
11137 		case IP_UNBLOCK_SOURCE:
11138 		case IP_ADD_SOURCE_MEMBERSHIP:
11139 		case IP_DROP_SOURCE_MEMBERSHIP:
11140 		case MCAST_BLOCK_SOURCE:
11141 		case MCAST_UNBLOCK_SOURCE:
11142 		case MCAST_JOIN_SOURCE_GROUP:
11143 		case MCAST_LEAVE_SOURCE_GROUP: {
11144 			struct ip_mreq_source *imreqp;
11145 			struct group_source_req *gsreqp;
11146 			in_addr_t grp, src, ifaddr = INADDR_ANY;
11147 			uint32_t ifindex = 0;
11148 			mcast_record_t fmode;
11149 			struct sockaddr_in *sin;
11150 			ire_t *ire;
11151 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11152 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11153 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11154 
11155 			switch (name) {
11156 			case IP_BLOCK_SOURCE:
11157 				mcast_opt = B_FALSE;
11158 				/* FALLTHRU */
11159 			case MCAST_BLOCK_SOURCE:
11160 				fmode = MODE_IS_EXCLUDE;
11161 				optfn = ip_opt_add_group;
11162 				break;
11163 
11164 			case IP_UNBLOCK_SOURCE:
11165 				mcast_opt = B_FALSE;
11166 				/* FALLTHRU */
11167 			case MCAST_UNBLOCK_SOURCE:
11168 				fmode = MODE_IS_EXCLUDE;
11169 				optfn = ip_opt_delete_group;
11170 				break;
11171 
11172 			case IP_ADD_SOURCE_MEMBERSHIP:
11173 				mcast_opt = B_FALSE;
11174 				/* FALLTHRU */
11175 			case MCAST_JOIN_SOURCE_GROUP:
11176 				fmode = MODE_IS_INCLUDE;
11177 				optfn = ip_opt_add_group;
11178 				break;
11179 
11180 			case IP_DROP_SOURCE_MEMBERSHIP:
11181 				mcast_opt = B_FALSE;
11182 				/* FALLTHRU */
11183 			case MCAST_LEAVE_SOURCE_GROUP:
11184 				fmode = MODE_IS_INCLUDE;
11185 				optfn = ip_opt_delete_group;
11186 				break;
11187 			}
11188 
11189 			if (mcast_opt) {
11190 				gsreqp = (struct group_source_req *)i1;
11191 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11192 					*outlenp = 0;
11193 					return (ENOPROTOOPT);
11194 				}
11195 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11196 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11197 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11198 				src = (ipaddr_t)sin->sin_addr.s_addr;
11199 				ifindex = gsreqp->gsr_interface;
11200 			} else {
11201 				imreqp = (struct ip_mreq_source *)i1;
11202 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11203 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11204 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11205 			}
11206 
11207 			/*
11208 			 * In the multirouting case, we need to replicate
11209 			 * the request as noted in the mcast cases above.
11210 			 */
11211 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11212 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11213 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11214 			if (ire != NULL) {
11215 				if (ire->ire_flags & RTF_MULTIRT) {
11216 					error = ip_multirt_apply_membership(
11217 					    optfn, ire, connp, checkonly, grp,
11218 					    fmode, src, first_mp);
11219 					done = B_TRUE;
11220 				}
11221 				ire_refrele(ire);
11222 			}
11223 			if (!done) {
11224 				error = optfn(connp, checkonly, grp, ifaddr,
11225 				    &ifindex, fmode, src, first_mp);
11226 			}
11227 			if (error != 0) {
11228 				/*
11229 				 * EINPROGRESS is a soft error, needs retry
11230 				 * so don't make *outlenp zero.
11231 				 */
11232 				if (error != EINPROGRESS)
11233 					*outlenp = 0;
11234 				return (error);
11235 			}
11236 			/* OK return - copy input buffer into output buffer */
11237 			if (invalp != outvalp) {
11238 				bcopy(invalp, outvalp, inlen);
11239 			}
11240 			*outlenp = inlen;
11241 			return (0);
11242 		}
11243 		case IP_SEC_OPT:
11244 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11245 			if (error != 0) {
11246 				*outlenp = 0;
11247 				return (error);
11248 			}
11249 			break;
11250 		case IP_HDRINCL:
11251 		case IP_OPTIONS:
11252 		case T_IP_OPTIONS:
11253 		case IP_TOS:
11254 		case T_IP_TOS:
11255 		case IP_TTL:
11256 		case IP_RECVDSTADDR:
11257 		case IP_RECVOPTS:
11258 			/* OK return - copy input buffer into output buffer */
11259 			if (invalp != outvalp) {
11260 				/* don't trust bcopy for identical src/dst */
11261 				bcopy(invalp, outvalp, inlen);
11262 			}
11263 			*outlenp = inlen;
11264 			return (0);
11265 		case IP_RECVIF:
11266 			/* Retrieve the inbound interface index */
11267 			if (!checkonly) {
11268 				mutex_enter(&connp->conn_lock);
11269 				connp->conn_recvif = *i1 ? 1 : 0;
11270 				mutex_exit(&connp->conn_lock);
11271 			}
11272 			break;	/* goto sizeof (int) option return */
11273 		case IP_RECVPKTINFO:
11274 			if (!checkonly) {
11275 				mutex_enter(&connp->conn_lock);
11276 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11277 				mutex_exit(&connp->conn_lock);
11278 			}
11279 			break;	/* goto sizeof (int) option return */
11280 		case IP_RECVSLLA:
11281 			/* Retrieve the source link layer address */
11282 			if (!checkonly) {
11283 				mutex_enter(&connp->conn_lock);
11284 				connp->conn_recvslla = *i1 ? 1 : 0;
11285 				mutex_exit(&connp->conn_lock);
11286 			}
11287 			break;	/* goto sizeof (int) option return */
11288 		case MRT_INIT:
11289 		case MRT_DONE:
11290 		case MRT_ADD_VIF:
11291 		case MRT_DEL_VIF:
11292 		case MRT_ADD_MFC:
11293 		case MRT_DEL_MFC:
11294 		case MRT_ASSERT:
11295 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11296 				*outlenp = 0;
11297 				return (error);
11298 			}
11299 			error = ip_mrouter_set((int)name, q, checkonly,
11300 			    (uchar_t *)invalp, inlen, first_mp);
11301 			if (error) {
11302 				*outlenp = 0;
11303 				return (error);
11304 			}
11305 			/* OK return - copy input buffer into output buffer */
11306 			if (invalp != outvalp) {
11307 				/* don't trust bcopy for identical src/dst */
11308 				bcopy(invalp, outvalp, inlen);
11309 			}
11310 			*outlenp = inlen;
11311 			return (0);
11312 		case IP_BOUND_IF:
11313 		case IP_XMIT_IF:
11314 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11315 			    level, name, first_mp);
11316 			if (error != 0)
11317 				return (error);
11318 			break; 		/* goto sizeof (int) option return */
11319 
11320 		case IP_UNSPEC_SRC:
11321 			/* Allow sending with a zero source address */
11322 			if (!checkonly) {
11323 				mutex_enter(&connp->conn_lock);
11324 				connp->conn_unspec_src = *i1 ? 1 : 0;
11325 				mutex_exit(&connp->conn_lock);
11326 			}
11327 			break;	/* goto sizeof (int) option return */
11328 		default:
11329 			/*
11330 			 * "soft" error (negative)
11331 			 * option not handled at this level
11332 			 * Note: Do not modify *outlenp
11333 			 */
11334 			return (-EINVAL);
11335 		}
11336 		break;
11337 	case IPPROTO_IPV6:
11338 		switch (name) {
11339 		case IPV6_BOUND_IF:
11340 		case IPV6_BOUND_PIF:
11341 		case IPV6_DONTFAILOVER_IF:
11342 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11343 			    level, name, first_mp);
11344 			if (error != 0)
11345 				return (error);
11346 			break; 		/* goto sizeof (int) option return */
11347 
11348 		case IPV6_MULTICAST_IF:
11349 			/*
11350 			 * The only possible errors are EINPROGRESS and
11351 			 * EINVAL. EINPROGRESS will be restarted and is not
11352 			 * a hard error. We call this option on both V4 and V6
11353 			 * If both return EINVAL, then this call returns
11354 			 * EINVAL. If at least one of them succeeds we
11355 			 * return success.
11356 			 */
11357 			found = B_FALSE;
11358 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11359 			    level, name, first_mp);
11360 			if (error == EINPROGRESS)
11361 				return (error);
11362 			if (error == 0)
11363 				found = B_TRUE;
11364 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11365 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11366 			if (error == 0)
11367 				found = B_TRUE;
11368 			if (!found)
11369 				return (error);
11370 			break; 		/* goto sizeof (int) option return */
11371 
11372 		case IPV6_MULTICAST_HOPS:
11373 			/* Recorded in transport above IP */
11374 			break;	/* goto sizeof (int) option return */
11375 		case IPV6_MULTICAST_LOOP:
11376 			if (!checkonly) {
11377 				mutex_enter(&connp->conn_lock);
11378 				connp->conn_multicast_loop = *i1;
11379 				mutex_exit(&connp->conn_lock);
11380 			}
11381 			break;	/* goto sizeof (int) option return */
11382 		case IPV6_JOIN_GROUP:
11383 		case MCAST_JOIN_GROUP:
11384 		case IPV6_LEAVE_GROUP:
11385 		case MCAST_LEAVE_GROUP: {
11386 			struct ipv6_mreq *ip_mreqp;
11387 			struct group_req *greqp;
11388 			ire_t *ire;
11389 			boolean_t done = B_FALSE;
11390 			in6_addr_t groupv6;
11391 			uint32_t ifindex;
11392 			boolean_t mcast_opt = B_TRUE;
11393 			mcast_record_t fmode;
11394 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11395 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11396 
11397 			switch (name) {
11398 			case IPV6_JOIN_GROUP:
11399 				mcast_opt = B_FALSE;
11400 				/* FALLTHRU */
11401 			case MCAST_JOIN_GROUP:
11402 				fmode = MODE_IS_EXCLUDE;
11403 				optfn = ip_opt_add_group_v6;
11404 				break;
11405 
11406 			case IPV6_LEAVE_GROUP:
11407 				mcast_opt = B_FALSE;
11408 				/* FALLTHRU */
11409 			case MCAST_LEAVE_GROUP:
11410 				fmode = MODE_IS_INCLUDE;
11411 				optfn = ip_opt_delete_group_v6;
11412 				break;
11413 			}
11414 
11415 			if (mcast_opt) {
11416 				struct sockaddr_in *sin;
11417 				struct sockaddr_in6 *sin6;
11418 				greqp = (struct group_req *)i1;
11419 				if (greqp->gr_group.ss_family == AF_INET) {
11420 					sin = (struct sockaddr_in *)
11421 					    &(greqp->gr_group);
11422 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11423 					    &groupv6);
11424 				} else {
11425 					sin6 = (struct sockaddr_in6 *)
11426 					    &(greqp->gr_group);
11427 					groupv6 = sin6->sin6_addr;
11428 				}
11429 				ifindex = greqp->gr_interface;
11430 			} else {
11431 				ip_mreqp = (struct ipv6_mreq *)i1;
11432 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11433 				ifindex = ip_mreqp->ipv6mr_interface;
11434 			}
11435 			/*
11436 			 * In the multirouting case, we need to replicate
11437 			 * the request on all interfaces that will take part
11438 			 * in replication.  We do so because multirouting is
11439 			 * reflective, thus we will probably receive multi-
11440 			 * casts on those interfaces.
11441 			 * The ip_multirt_apply_membership_v6() succeeds if
11442 			 * the operation succeeds on at least one interface.
11443 			 */
11444 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11445 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11446 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11447 			if (ire != NULL) {
11448 				if (ire->ire_flags & RTF_MULTIRT) {
11449 					error = ip_multirt_apply_membership_v6(
11450 					    optfn, ire, connp, checkonly,
11451 					    &groupv6, fmode, &ipv6_all_zeros,
11452 					    first_mp);
11453 					done = B_TRUE;
11454 				}
11455 				ire_refrele(ire);
11456 			}
11457 			if (!done) {
11458 				error = optfn(connp, checkonly, &groupv6,
11459 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11460 			}
11461 			if (error) {
11462 				/*
11463 				 * EINPROGRESS is a soft error, needs retry
11464 				 * so don't make *outlenp zero.
11465 				 */
11466 				if (error != EINPROGRESS)
11467 					*outlenp = 0;
11468 				return (error);
11469 			}
11470 			/* OK return - copy input buffer into output buffer */
11471 			if (invalp != outvalp) {
11472 				/* don't trust bcopy for identical src/dst */
11473 				bcopy(invalp, outvalp, inlen);
11474 			}
11475 			*outlenp = inlen;
11476 			return (0);
11477 		}
11478 		case MCAST_BLOCK_SOURCE:
11479 		case MCAST_UNBLOCK_SOURCE:
11480 		case MCAST_JOIN_SOURCE_GROUP:
11481 		case MCAST_LEAVE_SOURCE_GROUP: {
11482 			struct group_source_req *gsreqp;
11483 			in6_addr_t v6grp, v6src;
11484 			uint32_t ifindex;
11485 			mcast_record_t fmode;
11486 			ire_t *ire;
11487 			boolean_t done = B_FALSE;
11488 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11489 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11490 
11491 			switch (name) {
11492 			case MCAST_BLOCK_SOURCE:
11493 				fmode = MODE_IS_EXCLUDE;
11494 				optfn = ip_opt_add_group_v6;
11495 				break;
11496 			case MCAST_UNBLOCK_SOURCE:
11497 				fmode = MODE_IS_EXCLUDE;
11498 				optfn = ip_opt_delete_group_v6;
11499 				break;
11500 			case MCAST_JOIN_SOURCE_GROUP:
11501 				fmode = MODE_IS_INCLUDE;
11502 				optfn = ip_opt_add_group_v6;
11503 				break;
11504 			case MCAST_LEAVE_SOURCE_GROUP:
11505 				fmode = MODE_IS_INCLUDE;
11506 				optfn = ip_opt_delete_group_v6;
11507 				break;
11508 			}
11509 
11510 			gsreqp = (struct group_source_req *)i1;
11511 			ifindex = gsreqp->gsr_interface;
11512 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11513 				struct sockaddr_in *s;
11514 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11515 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11516 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11517 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11518 			} else {
11519 				struct sockaddr_in6 *s6;
11520 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11521 				v6grp = s6->sin6_addr;
11522 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11523 				v6src = s6->sin6_addr;
11524 			}
11525 
11526 			/*
11527 			 * In the multirouting case, we need to replicate
11528 			 * the request as noted in the mcast cases above.
11529 			 */
11530 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11531 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11532 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11533 			if (ire != NULL) {
11534 				if (ire->ire_flags & RTF_MULTIRT) {
11535 					error = ip_multirt_apply_membership_v6(
11536 					    optfn, ire, connp, checkonly,
11537 					    &v6grp, fmode, &v6src, first_mp);
11538 					done = B_TRUE;
11539 				}
11540 				ire_refrele(ire);
11541 			}
11542 			if (!done) {
11543 				error = optfn(connp, checkonly, &v6grp,
11544 				    ifindex, fmode, &v6src, first_mp);
11545 			}
11546 			if (error != 0) {
11547 				/*
11548 				 * EINPROGRESS is a soft error, needs retry
11549 				 * so don't make *outlenp zero.
11550 				 */
11551 				if (error != EINPROGRESS)
11552 					*outlenp = 0;
11553 				return (error);
11554 			}
11555 			/* OK return - copy input buffer into output buffer */
11556 			if (invalp != outvalp) {
11557 				bcopy(invalp, outvalp, inlen);
11558 			}
11559 			*outlenp = inlen;
11560 			return (0);
11561 		}
11562 		case IPV6_UNICAST_HOPS:
11563 			/* Recorded in transport above IP */
11564 			break;	/* goto sizeof (int) option return */
11565 		case IPV6_UNSPEC_SRC:
11566 			/* Allow sending with a zero source address */
11567 			if (!checkonly) {
11568 				mutex_enter(&connp->conn_lock);
11569 				connp->conn_unspec_src = *i1 ? 1 : 0;
11570 				mutex_exit(&connp->conn_lock);
11571 			}
11572 			break;	/* goto sizeof (int) option return */
11573 		case IPV6_RECVPKTINFO:
11574 			if (!checkonly) {
11575 				mutex_enter(&connp->conn_lock);
11576 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11577 				mutex_exit(&connp->conn_lock);
11578 			}
11579 			break;	/* goto sizeof (int) option return */
11580 		case IPV6_RECVTCLASS:
11581 			if (!checkonly) {
11582 				if (*i1 < 0 || *i1 > 1) {
11583 					return (EINVAL);
11584 				}
11585 				mutex_enter(&connp->conn_lock);
11586 				connp->conn_ipv6_recvtclass = *i1;
11587 				mutex_exit(&connp->conn_lock);
11588 			}
11589 			break;
11590 		case IPV6_RECVPATHMTU:
11591 			if (!checkonly) {
11592 				if (*i1 < 0 || *i1 > 1) {
11593 					return (EINVAL);
11594 				}
11595 				mutex_enter(&connp->conn_lock);
11596 				connp->conn_ipv6_recvpathmtu = *i1;
11597 				mutex_exit(&connp->conn_lock);
11598 			}
11599 			break;
11600 		case IPV6_RECVHOPLIMIT:
11601 			if (!checkonly) {
11602 				mutex_enter(&connp->conn_lock);
11603 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11604 				mutex_exit(&connp->conn_lock);
11605 			}
11606 			break;	/* goto sizeof (int) option return */
11607 		case IPV6_RECVHOPOPTS:
11608 			if (!checkonly) {
11609 				mutex_enter(&connp->conn_lock);
11610 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11611 				mutex_exit(&connp->conn_lock);
11612 			}
11613 			break;	/* goto sizeof (int) option return */
11614 		case IPV6_RECVDSTOPTS:
11615 			if (!checkonly) {
11616 				mutex_enter(&connp->conn_lock);
11617 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11618 				mutex_exit(&connp->conn_lock);
11619 			}
11620 			break;	/* goto sizeof (int) option return */
11621 		case IPV6_RECVRTHDR:
11622 			if (!checkonly) {
11623 				mutex_enter(&connp->conn_lock);
11624 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11625 				mutex_exit(&connp->conn_lock);
11626 			}
11627 			break;	/* goto sizeof (int) option return */
11628 		case IPV6_RECVRTHDRDSTOPTS:
11629 			if (!checkonly) {
11630 				mutex_enter(&connp->conn_lock);
11631 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11632 				mutex_exit(&connp->conn_lock);
11633 			}
11634 			break;	/* goto sizeof (int) option return */
11635 		case IPV6_PKTINFO:
11636 			if (inlen == 0)
11637 				return (-EINVAL);	/* clearing option */
11638 			error = ip6_set_pktinfo(cr, connp,
11639 			    (struct in6_pktinfo *)invalp, first_mp);
11640 			if (error != 0)
11641 				*outlenp = 0;
11642 			else
11643 				*outlenp = inlen;
11644 			return (error);
11645 		case IPV6_NEXTHOP: {
11646 			struct sockaddr_in6 *sin6;
11647 
11648 			/* Verify that the nexthop is reachable */
11649 			if (inlen == 0)
11650 				return (-EINVAL);	/* clearing option */
11651 
11652 			sin6 = (struct sockaddr_in6 *)invalp;
11653 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11654 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11655 			    NULL, MATCH_IRE_DEFAULT, ipst);
11656 
11657 			if (ire == NULL) {
11658 				*outlenp = 0;
11659 				return (EHOSTUNREACH);
11660 			}
11661 			ire_refrele(ire);
11662 			return (-EINVAL);
11663 		}
11664 		case IPV6_SEC_OPT:
11665 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11666 			if (error != 0) {
11667 				*outlenp = 0;
11668 				return (error);
11669 			}
11670 			break;
11671 		case IPV6_SRC_PREFERENCES: {
11672 			/*
11673 			 * This is implemented strictly in the ip module
11674 			 * (here and in tcp_opt_*() to accomodate tcp
11675 			 * sockets).  Modules above ip pass this option
11676 			 * down here since ip is the only one that needs to
11677 			 * be aware of source address preferences.
11678 			 *
11679 			 * This socket option only affects connected
11680 			 * sockets that haven't already bound to a specific
11681 			 * IPv6 address.  In other words, sockets that
11682 			 * don't call bind() with an address other than the
11683 			 * unspecified address and that call connect().
11684 			 * ip_bind_connected_v6() passes these preferences
11685 			 * to the ipif_select_source_v6() function.
11686 			 */
11687 			if (inlen != sizeof (uint32_t))
11688 				return (EINVAL);
11689 			error = ip6_set_src_preferences(connp,
11690 			    *(uint32_t *)invalp);
11691 			if (error != 0) {
11692 				*outlenp = 0;
11693 				return (error);
11694 			} else {
11695 				*outlenp = sizeof (uint32_t);
11696 			}
11697 			break;
11698 		}
11699 		case IPV6_V6ONLY:
11700 			if (*i1 < 0 || *i1 > 1) {
11701 				return (EINVAL);
11702 			}
11703 			mutex_enter(&connp->conn_lock);
11704 			connp->conn_ipv6_v6only = *i1;
11705 			mutex_exit(&connp->conn_lock);
11706 			break;
11707 		default:
11708 			return (-EINVAL);
11709 		}
11710 		break;
11711 	default:
11712 		/*
11713 		 * "soft" error (negative)
11714 		 * option not handled at this level
11715 		 * Note: Do not modify *outlenp
11716 		 */
11717 		return (-EINVAL);
11718 	}
11719 	/*
11720 	 * Common case of return from an option that is sizeof (int)
11721 	 */
11722 	*(int *)outvalp = *i1;
11723 	*outlenp = sizeof (int);
11724 	return (0);
11725 }
11726 
11727 /*
11728  * This routine gets default values of certain options whose default
11729  * values are maintained by protocol specific code
11730  */
11731 /* ARGSUSED */
11732 int
11733 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11734 {
11735 	int *i1 = (int *)ptr;
11736 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11737 
11738 	switch (level) {
11739 	case IPPROTO_IP:
11740 		switch (name) {
11741 		case IP_MULTICAST_TTL:
11742 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11743 			return (sizeof (uchar_t));
11744 		case IP_MULTICAST_LOOP:
11745 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11746 			return (sizeof (uchar_t));
11747 		default:
11748 			return (-1);
11749 		}
11750 	case IPPROTO_IPV6:
11751 		switch (name) {
11752 		case IPV6_UNICAST_HOPS:
11753 			*i1 = ipst->ips_ipv6_def_hops;
11754 			return (sizeof (int));
11755 		case IPV6_MULTICAST_HOPS:
11756 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11757 			return (sizeof (int));
11758 		case IPV6_MULTICAST_LOOP:
11759 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11760 			return (sizeof (int));
11761 		case IPV6_V6ONLY:
11762 			*i1 = 1;
11763 			return (sizeof (int));
11764 		default:
11765 			return (-1);
11766 		}
11767 	default:
11768 		return (-1);
11769 	}
11770 	/* NOTREACHED */
11771 }
11772 
11773 /*
11774  * Given a destination address and a pointer to where to put the information
11775  * this routine fills in the mtuinfo.
11776  */
11777 int
11778 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11779     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11780 {
11781 	ire_t *ire;
11782 	ip_stack_t	*ipst = ns->netstack_ip;
11783 
11784 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11785 		return (-1);
11786 
11787 	bzero(mtuinfo, sizeof (*mtuinfo));
11788 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11789 	mtuinfo->ip6m_addr.sin6_port = port;
11790 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11791 
11792 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11793 	if (ire != NULL) {
11794 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11795 		ire_refrele(ire);
11796 	} else {
11797 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11798 	}
11799 	return (sizeof (struct ip6_mtuinfo));
11800 }
11801 
11802 /*
11803  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11804  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11805  * isn't.  This doesn't matter as the error checking is done properly for the
11806  * other MRT options coming in through ip_opt_set.
11807  */
11808 int
11809 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11810 {
11811 	conn_t		*connp = Q_TO_CONN(q);
11812 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11813 
11814 	switch (level) {
11815 	case IPPROTO_IP:
11816 		switch (name) {
11817 		case MRT_VERSION:
11818 		case MRT_ASSERT:
11819 			(void) ip_mrouter_get(name, q, ptr);
11820 			return (sizeof (int));
11821 		case IP_SEC_OPT:
11822 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11823 		case IP_NEXTHOP:
11824 			if (connp->conn_nexthop_set) {
11825 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11826 				return (sizeof (ipaddr_t));
11827 			} else
11828 				return (0);
11829 		case IP_RECVPKTINFO:
11830 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11831 			return (sizeof (int));
11832 		default:
11833 			break;
11834 		}
11835 		break;
11836 	case IPPROTO_IPV6:
11837 		switch (name) {
11838 		case IPV6_SEC_OPT:
11839 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11840 		case IPV6_SRC_PREFERENCES: {
11841 			return (ip6_get_src_preferences(connp,
11842 			    (uint32_t *)ptr));
11843 		}
11844 		case IPV6_V6ONLY:
11845 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11846 			return (sizeof (int));
11847 		case IPV6_PATHMTU:
11848 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11849 				(struct ip6_mtuinfo *)ptr,
11850 				connp->conn_netstack));
11851 		default:
11852 			break;
11853 		}
11854 		break;
11855 	default:
11856 		break;
11857 	}
11858 	return (-1);
11859 }
11860 
11861 /* Named Dispatch routine to get a current value out of our parameter table. */
11862 /* ARGSUSED */
11863 static int
11864 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11865 {
11866 	ipparam_t *ippa = (ipparam_t *)cp;
11867 
11868 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11869 	return (0);
11870 }
11871 
11872 /* ARGSUSED */
11873 static int
11874 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11875 {
11876 
11877 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11878 	return (0);
11879 }
11880 
11881 /*
11882  * Set ip{,6}_forwarding values.  This means walking through all of the
11883  * ill's and toggling their forwarding values.
11884  */
11885 /* ARGSUSED */
11886 static int
11887 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11888 {
11889 	long new_value;
11890 	int *forwarding_value = (int *)cp;
11891 	ill_t *walker;
11892 	boolean_t isv6;
11893 	ill_walk_context_t ctx;
11894 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11895 
11896 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11897 
11898 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11899 	    new_value < 0 || new_value > 1) {
11900 		return (EINVAL);
11901 	}
11902 
11903 	*forwarding_value = new_value;
11904 
11905 	/*
11906 	 * Regardless of the current value of ip_forwarding, set all per-ill
11907 	 * values of ip_forwarding to the value being set.
11908 	 *
11909 	 * Bring all the ill's up to date with the new global value.
11910 	 */
11911 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11912 
11913 	if (isv6)
11914 		walker = ILL_START_WALK_V6(&ctx, ipst);
11915 	else
11916 		walker = ILL_START_WALK_V4(&ctx, ipst);
11917 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11918 		(void) ill_forward_set(q, mp, (new_value != 0),
11919 		    (caddr_t)walker);
11920 	}
11921 	rw_exit(&ipst->ips_ill_g_lock);
11922 
11923 	return (0);
11924 }
11925 
11926 /*
11927  * Walk through the param array specified registering each element with the
11928  * Named Dispatch handler. This is called only during init. So it is ok
11929  * not to acquire any locks
11930  */
11931 static boolean_t
11932 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11933     ipndp_t *ipnd, size_t ipnd_cnt)
11934 {
11935 	for (; ippa_cnt-- > 0; ippa++) {
11936 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11937 			if (!nd_load(ndp, ippa->ip_param_name,
11938 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11939 				nd_free(ndp);
11940 				return (B_FALSE);
11941 			}
11942 		}
11943 	}
11944 
11945 	for (; ipnd_cnt-- > 0; ipnd++) {
11946 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11947 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11948 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11949 			    ipnd->ip_ndp_data)) {
11950 				nd_free(ndp);
11951 				return (B_FALSE);
11952 			}
11953 		}
11954 	}
11955 
11956 	return (B_TRUE);
11957 }
11958 
11959 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11960 /* ARGSUSED */
11961 static int
11962 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11963 {
11964 	long		new_value;
11965 	ipparam_t	*ippa = (ipparam_t *)cp;
11966 
11967 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11968 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11969 		return (EINVAL);
11970 	}
11971 	ippa->ip_param_value = new_value;
11972 	return (0);
11973 }
11974 
11975 /*
11976  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11977  * When an ipf is passed here for the first time, if
11978  * we already have in-order fragments on the queue, we convert from the fast-
11979  * path reassembly scheme to the hard-case scheme.  From then on, additional
11980  * fragments are reassembled here.  We keep track of the start and end offsets
11981  * of each piece, and the number of holes in the chain.  When the hole count
11982  * goes to zero, we are done!
11983  *
11984  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11985  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11986  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11987  * after the call to ip_reassemble().
11988  */
11989 int
11990 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11991     size_t msg_len)
11992 {
11993 	uint_t	end;
11994 	mblk_t	*next_mp;
11995 	mblk_t	*mp1;
11996 	uint_t	offset;
11997 	boolean_t incr_dups = B_TRUE;
11998 	boolean_t offset_zero_seen = B_FALSE;
11999 	boolean_t pkt_boundary_checked = B_FALSE;
12000 
12001 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
12002 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
12003 
12004 	/* Add in byte count */
12005 	ipf->ipf_count += msg_len;
12006 	if (ipf->ipf_end) {
12007 		/*
12008 		 * We were part way through in-order reassembly, but now there
12009 		 * is a hole.  We walk through messages already queued, and
12010 		 * mark them for hard case reassembly.  We know that up till
12011 		 * now they were in order starting from offset zero.
12012 		 */
12013 		offset = 0;
12014 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12015 			IP_REASS_SET_START(mp1, offset);
12016 			if (offset == 0) {
12017 				ASSERT(ipf->ipf_nf_hdr_len != 0);
12018 				offset = -ipf->ipf_nf_hdr_len;
12019 			}
12020 			offset += mp1->b_wptr - mp1->b_rptr;
12021 			IP_REASS_SET_END(mp1, offset);
12022 		}
12023 		/* One hole at the end. */
12024 		ipf->ipf_hole_cnt = 1;
12025 		/* Brand it as a hard case, forever. */
12026 		ipf->ipf_end = 0;
12027 	}
12028 	/* Walk through all the new pieces. */
12029 	do {
12030 		end = start + (mp->b_wptr - mp->b_rptr);
12031 		/*
12032 		 * If start is 0, decrease 'end' only for the first mblk of
12033 		 * the fragment. Otherwise 'end' can get wrong value in the
12034 		 * second pass of the loop if first mblk is exactly the
12035 		 * size of ipf_nf_hdr_len.
12036 		 */
12037 		if (start == 0 && !offset_zero_seen) {
12038 			/* First segment */
12039 			ASSERT(ipf->ipf_nf_hdr_len != 0);
12040 			end -= ipf->ipf_nf_hdr_len;
12041 			offset_zero_seen = B_TRUE;
12042 		}
12043 		next_mp = mp->b_cont;
12044 		/*
12045 		 * We are checking to see if there is any interesing data
12046 		 * to process.  If there isn't and the mblk isn't the
12047 		 * one which carries the unfragmentable header then we
12048 		 * drop it.  It's possible to have just the unfragmentable
12049 		 * header come through without any data.  That needs to be
12050 		 * saved.
12051 		 *
12052 		 * If the assert at the top of this function holds then the
12053 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
12054 		 * is infrequently traveled enough that the test is left in
12055 		 * to protect against future code changes which break that
12056 		 * invariant.
12057 		 */
12058 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
12059 			/* Empty.  Blast it. */
12060 			IP_REASS_SET_START(mp, 0);
12061 			IP_REASS_SET_END(mp, 0);
12062 			/*
12063 			 * If the ipf points to the mblk we are about to free,
12064 			 * update ipf to point to the next mblk (or NULL
12065 			 * if none).
12066 			 */
12067 			if (ipf->ipf_mp->b_cont == mp)
12068 				ipf->ipf_mp->b_cont = next_mp;
12069 			freeb(mp);
12070 			continue;
12071 		}
12072 		mp->b_cont = NULL;
12073 		IP_REASS_SET_START(mp, start);
12074 		IP_REASS_SET_END(mp, end);
12075 		if (!ipf->ipf_tail_mp) {
12076 			ipf->ipf_tail_mp = mp;
12077 			ipf->ipf_mp->b_cont = mp;
12078 			if (start == 0 || !more) {
12079 				ipf->ipf_hole_cnt = 1;
12080 				/*
12081 				 * if the first fragment comes in more than one
12082 				 * mblk, this loop will be executed for each
12083 				 * mblk. Need to adjust hole count so exiting
12084 				 * this routine will leave hole count at 1.
12085 				 */
12086 				if (next_mp)
12087 					ipf->ipf_hole_cnt++;
12088 			} else
12089 				ipf->ipf_hole_cnt = 2;
12090 			continue;
12091 		} else if (ipf->ipf_last_frag_seen && !more &&
12092 			    !pkt_boundary_checked) {
12093 			/*
12094 			 * We check datagram boundary only if this fragment
12095 			 * claims to be the last fragment and we have seen a
12096 			 * last fragment in the past too. We do this only
12097 			 * once for a given fragment.
12098 			 *
12099 			 * start cannot be 0 here as fragments with start=0
12100 			 * and MF=0 gets handled as a complete packet. These
12101 			 * fragments should not reach here.
12102 			 */
12103 
12104 			if (start + msgdsize(mp) !=
12105 			    IP_REASS_END(ipf->ipf_tail_mp)) {
12106 				/*
12107 				 * We have two fragments both of which claim
12108 				 * to be the last fragment but gives conflicting
12109 				 * information about the whole datagram size.
12110 				 * Something fishy is going on. Drop the
12111 				 * fragment and free up the reassembly list.
12112 				 */
12113 				return (IP_REASS_FAILED);
12114 			}
12115 
12116 			/*
12117 			 * We shouldn't come to this code block again for this
12118 			 * particular fragment.
12119 			 */
12120 			pkt_boundary_checked = B_TRUE;
12121 		}
12122 
12123 		/* New stuff at or beyond tail? */
12124 		offset = IP_REASS_END(ipf->ipf_tail_mp);
12125 		if (start >= offset) {
12126 			if (ipf->ipf_last_frag_seen) {
12127 				/* current fragment is beyond last fragment */
12128 				return (IP_REASS_FAILED);
12129 			}
12130 			/* Link it on end. */
12131 			ipf->ipf_tail_mp->b_cont = mp;
12132 			ipf->ipf_tail_mp = mp;
12133 			if (more) {
12134 				if (start != offset)
12135 					ipf->ipf_hole_cnt++;
12136 			} else if (start == offset && next_mp == NULL)
12137 					ipf->ipf_hole_cnt--;
12138 			continue;
12139 		}
12140 		mp1 = ipf->ipf_mp->b_cont;
12141 		offset = IP_REASS_START(mp1);
12142 		/* New stuff at the front? */
12143 		if (start < offset) {
12144 			if (start == 0) {
12145 				if (end >= offset) {
12146 					/* Nailed the hole at the begining. */
12147 					ipf->ipf_hole_cnt--;
12148 				}
12149 			} else if (end < offset) {
12150 				/*
12151 				 * A hole, stuff, and a hole where there used
12152 				 * to be just a hole.
12153 				 */
12154 				ipf->ipf_hole_cnt++;
12155 			}
12156 			mp->b_cont = mp1;
12157 			/* Check for overlap. */
12158 			while (end > offset) {
12159 				if (end < IP_REASS_END(mp1)) {
12160 					mp->b_wptr -= end - offset;
12161 					IP_REASS_SET_END(mp, offset);
12162 					BUMP_MIB(ill->ill_ip_mib,
12163 					    ipIfStatsReasmPartDups);
12164 					break;
12165 				}
12166 				/* Did we cover another hole? */
12167 				if ((mp1->b_cont &&
12168 				    IP_REASS_END(mp1) !=
12169 				    IP_REASS_START(mp1->b_cont) &&
12170 				    end >= IP_REASS_START(mp1->b_cont)) ||
12171 				    (!ipf->ipf_last_frag_seen && !more)) {
12172 					ipf->ipf_hole_cnt--;
12173 				}
12174 				/* Clip out mp1. */
12175 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12176 					/*
12177 					 * After clipping out mp1, this guy
12178 					 * is now hanging off the end.
12179 					 */
12180 					ipf->ipf_tail_mp = mp;
12181 				}
12182 				IP_REASS_SET_START(mp1, 0);
12183 				IP_REASS_SET_END(mp1, 0);
12184 				/* Subtract byte count */
12185 				ipf->ipf_count -= mp1->b_datap->db_lim -
12186 				    mp1->b_datap->db_base;
12187 				freeb(mp1);
12188 				BUMP_MIB(ill->ill_ip_mib,
12189 				    ipIfStatsReasmPartDups);
12190 				mp1 = mp->b_cont;
12191 				if (!mp1)
12192 					break;
12193 				offset = IP_REASS_START(mp1);
12194 			}
12195 			ipf->ipf_mp->b_cont = mp;
12196 			continue;
12197 		}
12198 		/*
12199 		 * The new piece starts somewhere between the start of the head
12200 		 * and before the end of the tail.
12201 		 */
12202 		for (; mp1; mp1 = mp1->b_cont) {
12203 			offset = IP_REASS_END(mp1);
12204 			if (start < offset) {
12205 				if (end <= offset) {
12206 					/* Nothing new. */
12207 					IP_REASS_SET_START(mp, 0);
12208 					IP_REASS_SET_END(mp, 0);
12209 					/* Subtract byte count */
12210 					ipf->ipf_count -= mp->b_datap->db_lim -
12211 					    mp->b_datap->db_base;
12212 					if (incr_dups) {
12213 						ipf->ipf_num_dups++;
12214 						incr_dups = B_FALSE;
12215 					}
12216 					freeb(mp);
12217 					BUMP_MIB(ill->ill_ip_mib,
12218 					    ipIfStatsReasmDuplicates);
12219 					break;
12220 				}
12221 				/*
12222 				 * Trim redundant stuff off beginning of new
12223 				 * piece.
12224 				 */
12225 				IP_REASS_SET_START(mp, offset);
12226 				mp->b_rptr += offset - start;
12227 				BUMP_MIB(ill->ill_ip_mib,
12228 				    ipIfStatsReasmPartDups);
12229 				start = offset;
12230 				if (!mp1->b_cont) {
12231 					/*
12232 					 * After trimming, this guy is now
12233 					 * hanging off the end.
12234 					 */
12235 					mp1->b_cont = mp;
12236 					ipf->ipf_tail_mp = mp;
12237 					if (!more) {
12238 						ipf->ipf_hole_cnt--;
12239 					}
12240 					break;
12241 				}
12242 			}
12243 			if (start >= IP_REASS_START(mp1->b_cont))
12244 				continue;
12245 			/* Fill a hole */
12246 			if (start > offset)
12247 				ipf->ipf_hole_cnt++;
12248 			mp->b_cont = mp1->b_cont;
12249 			mp1->b_cont = mp;
12250 			mp1 = mp->b_cont;
12251 			offset = IP_REASS_START(mp1);
12252 			if (end >= offset) {
12253 				ipf->ipf_hole_cnt--;
12254 				/* Check for overlap. */
12255 				while (end > offset) {
12256 					if (end < IP_REASS_END(mp1)) {
12257 						mp->b_wptr -= end - offset;
12258 						IP_REASS_SET_END(mp, offset);
12259 						/*
12260 						 * TODO we might bump
12261 						 * this up twice if there is
12262 						 * overlap at both ends.
12263 						 */
12264 						BUMP_MIB(ill->ill_ip_mib,
12265 						    ipIfStatsReasmPartDups);
12266 						break;
12267 					}
12268 					/* Did we cover another hole? */
12269 					if ((mp1->b_cont &&
12270 					    IP_REASS_END(mp1)
12271 					    != IP_REASS_START(mp1->b_cont) &&
12272 					    end >=
12273 					    IP_REASS_START(mp1->b_cont)) ||
12274 					    (!ipf->ipf_last_frag_seen &&
12275 					    !more)) {
12276 						ipf->ipf_hole_cnt--;
12277 					}
12278 					/* Clip out mp1. */
12279 					if ((mp->b_cont = mp1->b_cont) ==
12280 					    NULL) {
12281 						/*
12282 						 * After clipping out mp1,
12283 						 * this guy is now hanging
12284 						 * off the end.
12285 						 */
12286 						ipf->ipf_tail_mp = mp;
12287 					}
12288 					IP_REASS_SET_START(mp1, 0);
12289 					IP_REASS_SET_END(mp1, 0);
12290 					/* Subtract byte count */
12291 					ipf->ipf_count -=
12292 					    mp1->b_datap->db_lim -
12293 					    mp1->b_datap->db_base;
12294 					freeb(mp1);
12295 					BUMP_MIB(ill->ill_ip_mib,
12296 					    ipIfStatsReasmPartDups);
12297 					mp1 = mp->b_cont;
12298 					if (!mp1)
12299 						break;
12300 					offset = IP_REASS_START(mp1);
12301 				}
12302 			}
12303 			break;
12304 		}
12305 	} while (start = end, mp = next_mp);
12306 
12307 	/* Fragment just processed could be the last one. Remember this fact */
12308 	if (!more)
12309 		ipf->ipf_last_frag_seen = B_TRUE;
12310 
12311 	/* Still got holes? */
12312 	if (ipf->ipf_hole_cnt)
12313 		return (IP_REASS_PARTIAL);
12314 	/* Clean up overloaded fields to avoid upstream disasters. */
12315 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12316 		IP_REASS_SET_START(mp1, 0);
12317 		IP_REASS_SET_END(mp1, 0);
12318 	}
12319 	return (IP_REASS_COMPLETE);
12320 }
12321 
12322 /*
12323  * ipsec processing for the fast path, used for input UDP Packets
12324  */
12325 static boolean_t
12326 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12327     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12328 {
12329 	uint32_t	ill_index;
12330 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12331 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12332 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12333 
12334 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12335 	/* The ill_index of the incoming ILL */
12336 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12337 
12338 	/* pass packet up to the transport */
12339 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12340 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12341 		    NULL, mctl_present);
12342 		if (*first_mpp == NULL) {
12343 			return (B_FALSE);
12344 		}
12345 	}
12346 
12347 	/* Initiate IPPF processing for fastpath UDP */
12348 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12349 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12350 		if (*mpp == NULL) {
12351 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12352 			    "deferred/dropped during IPPF processing\n"));
12353 			return (B_FALSE);
12354 		}
12355 	}
12356 	/*
12357 	 * We make the checks as below since we are in the fast path
12358 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12359 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12360 	 */
12361 	if (connp->conn_recvif || connp->conn_recvslla ||
12362 	    connp->conn_ip_recvpktinfo) {
12363 		if (connp->conn_recvif) {
12364 			in_flags = IPF_RECVIF;
12365 		}
12366 		/*
12367 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12368 		 * so the flag passed to ip_add_info is based on IP version
12369 		 * of connp.
12370 		 */
12371 		if (connp->conn_ip_recvpktinfo) {
12372 			if (connp->conn_af_isv6) {
12373 				/*
12374 				 * V6 only needs index
12375 				 */
12376 				in_flags |= IPF_RECVIF;
12377 			} else {
12378 				/*
12379 				 * V4 needs index + matching address.
12380 				 */
12381 				in_flags |= IPF_RECVADDR;
12382 			}
12383 		}
12384 		if (connp->conn_recvslla) {
12385 			in_flags |= IPF_RECVSLLA;
12386 		}
12387 		/*
12388 		 * since in_flags are being set ill will be
12389 		 * referenced in ip_add_info, so it better not
12390 		 * be NULL.
12391 		 */
12392 		/*
12393 		 * the actual data will be contained in b_cont
12394 		 * upon successful return of the following call.
12395 		 * If the call fails then the original mblk is
12396 		 * returned.
12397 		 */
12398 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12399 		    ipst);
12400 	}
12401 
12402 	return (B_TRUE);
12403 }
12404 
12405 /*
12406  * Fragmentation reassembly.  Each ILL has a hash table for
12407  * queuing packets undergoing reassembly for all IPIFs
12408  * associated with the ILL.  The hash is based on the packet
12409  * IP ident field.  The ILL frag hash table was allocated
12410  * as a timer block at the time the ILL was created.  Whenever
12411  * there is anything on the reassembly queue, the timer will
12412  * be running.  Returns B_TRUE if successful else B_FALSE;
12413  * frees mp on failure.
12414  */
12415 static boolean_t
12416 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12417     uint32_t *cksum_val, uint16_t *cksum_flags)
12418 {
12419 	uint32_t	frag_offset_flags;
12420 	ill_t		*ill = (ill_t *)q->q_ptr;
12421 	mblk_t		*mp = *mpp;
12422 	mblk_t		*t_mp;
12423 	ipaddr_t	dst;
12424 	uint8_t		proto = ipha->ipha_protocol;
12425 	uint32_t	sum_val;
12426 	uint16_t	sum_flags;
12427 	ipf_t		*ipf;
12428 	ipf_t		**ipfp;
12429 	ipfb_t		*ipfb;
12430 	uint16_t	ident;
12431 	uint32_t	offset;
12432 	ipaddr_t	src;
12433 	uint_t		hdr_length;
12434 	uint32_t	end;
12435 	mblk_t		*mp1;
12436 	mblk_t		*tail_mp;
12437 	size_t		count;
12438 	size_t		msg_len;
12439 	uint8_t		ecn_info = 0;
12440 	uint32_t	packet_size;
12441 	boolean_t	pruned = B_FALSE;
12442 	ip_stack_t *ipst = ill->ill_ipst;
12443 
12444 	if (cksum_val != NULL)
12445 		*cksum_val = 0;
12446 	if (cksum_flags != NULL)
12447 		*cksum_flags = 0;
12448 
12449 	/*
12450 	 * Drop the fragmented as early as possible, if
12451 	 * we don't have resource(s) to re-assemble.
12452 	 */
12453 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12454 		freemsg(mp);
12455 		return (B_FALSE);
12456 	}
12457 
12458 	/* Check for fragmentation offset; return if there's none */
12459 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12460 	    (IPH_MF | IPH_OFFSET)) == 0)
12461 		return (B_TRUE);
12462 
12463 	/*
12464 	 * We utilize hardware computed checksum info only for UDP since
12465 	 * IP fragmentation is a normal occurence for the protocol.  In
12466 	 * addition, checksum offload support for IP fragments carrying
12467 	 * UDP payload is commonly implemented across network adapters.
12468 	 */
12469 	ASSERT(ill != NULL);
12470 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12471 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12472 		mblk_t *mp1 = mp->b_cont;
12473 		int32_t len;
12474 
12475 		/* Record checksum information from the packet */
12476 		sum_val = (uint32_t)DB_CKSUM16(mp);
12477 		sum_flags = DB_CKSUMFLAGS(mp);
12478 
12479 		/* IP payload offset from beginning of mblk */
12480 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12481 
12482 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12483 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12484 		    offset >= DB_CKSUMSTART(mp) &&
12485 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12486 			uint32_t adj;
12487 			/*
12488 			 * Partial checksum has been calculated by hardware
12489 			 * and attached to the packet; in addition, any
12490 			 * prepended extraneous data is even byte aligned.
12491 			 * If any such data exists, we adjust the checksum;
12492 			 * this would also handle any postpended data.
12493 			 */
12494 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12495 			    mp, mp1, len, adj);
12496 
12497 			/* One's complement subtract extraneous checksum */
12498 			if (adj >= sum_val)
12499 				sum_val = ~(adj - sum_val) & 0xFFFF;
12500 			else
12501 				sum_val -= adj;
12502 		}
12503 	} else {
12504 		sum_val = 0;
12505 		sum_flags = 0;
12506 	}
12507 
12508 	/* Clear hardware checksumming flag */
12509 	DB_CKSUMFLAGS(mp) = 0;
12510 
12511 	ident = ipha->ipha_ident;
12512 	offset = (frag_offset_flags << 3) & 0xFFFF;
12513 	src = ipha->ipha_src;
12514 	dst = ipha->ipha_dst;
12515 	hdr_length = IPH_HDR_LENGTH(ipha);
12516 	end = ntohs(ipha->ipha_length) - hdr_length;
12517 
12518 	/* If end == 0 then we have a packet with no data, so just free it */
12519 	if (end == 0) {
12520 		freemsg(mp);
12521 		return (B_FALSE);
12522 	}
12523 
12524 	/* Record the ECN field info. */
12525 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12526 	if (offset != 0) {
12527 		/*
12528 		 * If this isn't the first piece, strip the header, and
12529 		 * add the offset to the end value.
12530 		 */
12531 		mp->b_rptr += hdr_length;
12532 		end += offset;
12533 	}
12534 
12535 	msg_len = MBLKSIZE(mp);
12536 	tail_mp = mp;
12537 	while (tail_mp->b_cont != NULL) {
12538 		tail_mp = tail_mp->b_cont;
12539 		msg_len += MBLKSIZE(tail_mp);
12540 	}
12541 
12542 	/* If the reassembly list for this ILL will get too big, prune it */
12543 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12544 	    ipst->ips_ip_reass_queue_bytes) {
12545 		ill_frag_prune(ill,
12546 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12547 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12548 		pruned = B_TRUE;
12549 	}
12550 
12551 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12552 	mutex_enter(&ipfb->ipfb_lock);
12553 
12554 	ipfp = &ipfb->ipfb_ipf;
12555 	/* Try to find an existing fragment queue for this packet. */
12556 	for (;;) {
12557 		ipf = ipfp[0];
12558 		if (ipf != NULL) {
12559 			/*
12560 			 * It has to match on ident and src/dst address.
12561 			 */
12562 			if (ipf->ipf_ident == ident &&
12563 			    ipf->ipf_src == src &&
12564 			    ipf->ipf_dst == dst &&
12565 			    ipf->ipf_protocol == proto) {
12566 				/*
12567 				 * If we have received too many
12568 				 * duplicate fragments for this packet
12569 				 * free it.
12570 				 */
12571 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12572 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12573 					freemsg(mp);
12574 					mutex_exit(&ipfb->ipfb_lock);
12575 					return (B_FALSE);
12576 				}
12577 				/* Found it. */
12578 				break;
12579 			}
12580 			ipfp = &ipf->ipf_hash_next;
12581 			continue;
12582 		}
12583 
12584 		/*
12585 		 * If we pruned the list, do we want to store this new
12586 		 * fragment?. We apply an optimization here based on the
12587 		 * fact that most fragments will be received in order.
12588 		 * So if the offset of this incoming fragment is zero,
12589 		 * it is the first fragment of a new packet. We will
12590 		 * keep it.  Otherwise drop the fragment, as we have
12591 		 * probably pruned the packet already (since the
12592 		 * packet cannot be found).
12593 		 */
12594 		if (pruned && offset != 0) {
12595 			mutex_exit(&ipfb->ipfb_lock);
12596 			freemsg(mp);
12597 			return (B_FALSE);
12598 		}
12599 
12600 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12601 			/*
12602 			 * Too many fragmented packets in this hash
12603 			 * bucket. Free the oldest.
12604 			 */
12605 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12606 		}
12607 
12608 		/* New guy.  Allocate a frag message. */
12609 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12610 		if (mp1 == NULL) {
12611 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12612 			freemsg(mp);
12613 reass_done:
12614 			mutex_exit(&ipfb->ipfb_lock);
12615 			return (B_FALSE);
12616 		}
12617 
12618 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12619 		mp1->b_cont = mp;
12620 
12621 		/* Initialize the fragment header. */
12622 		ipf = (ipf_t *)mp1->b_rptr;
12623 		ipf->ipf_mp = mp1;
12624 		ipf->ipf_ptphn = ipfp;
12625 		ipfp[0] = ipf;
12626 		ipf->ipf_hash_next = NULL;
12627 		ipf->ipf_ident = ident;
12628 		ipf->ipf_protocol = proto;
12629 		ipf->ipf_src = src;
12630 		ipf->ipf_dst = dst;
12631 		ipf->ipf_nf_hdr_len = 0;
12632 		/* Record reassembly start time. */
12633 		ipf->ipf_timestamp = gethrestime_sec();
12634 		/* Record ipf generation and account for frag header */
12635 		ipf->ipf_gen = ill->ill_ipf_gen++;
12636 		ipf->ipf_count = MBLKSIZE(mp1);
12637 		ipf->ipf_last_frag_seen = B_FALSE;
12638 		ipf->ipf_ecn = ecn_info;
12639 		ipf->ipf_num_dups = 0;
12640 		ipfb->ipfb_frag_pkts++;
12641 		ipf->ipf_checksum = 0;
12642 		ipf->ipf_checksum_flags = 0;
12643 
12644 		/* Store checksum value in fragment header */
12645 		if (sum_flags != 0) {
12646 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12647 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12648 			ipf->ipf_checksum = sum_val;
12649 			ipf->ipf_checksum_flags = sum_flags;
12650 		}
12651 
12652 		/*
12653 		 * We handle reassembly two ways.  In the easy case,
12654 		 * where all the fragments show up in order, we do
12655 		 * minimal bookkeeping, and just clip new pieces on
12656 		 * the end.  If we ever see a hole, then we go off
12657 		 * to ip_reassemble which has to mark the pieces and
12658 		 * keep track of the number of holes, etc.  Obviously,
12659 		 * the point of having both mechanisms is so we can
12660 		 * handle the easy case as efficiently as possible.
12661 		 */
12662 		if (offset == 0) {
12663 			/* Easy case, in-order reassembly so far. */
12664 			ipf->ipf_count += msg_len;
12665 			ipf->ipf_tail_mp = tail_mp;
12666 			/*
12667 			 * Keep track of next expected offset in
12668 			 * ipf_end.
12669 			 */
12670 			ipf->ipf_end = end;
12671 			ipf->ipf_nf_hdr_len = hdr_length;
12672 		} else {
12673 			/* Hard case, hole at the beginning. */
12674 			ipf->ipf_tail_mp = NULL;
12675 			/*
12676 			 * ipf_end == 0 means that we have given up
12677 			 * on easy reassembly.
12678 			 */
12679 			ipf->ipf_end = 0;
12680 
12681 			/* Forget checksum offload from now on */
12682 			ipf->ipf_checksum_flags = 0;
12683 
12684 			/*
12685 			 * ipf_hole_cnt is set by ip_reassemble.
12686 			 * ipf_count is updated by ip_reassemble.
12687 			 * No need to check for return value here
12688 			 * as we don't expect reassembly to complete
12689 			 * or fail for the first fragment itself.
12690 			 */
12691 			(void) ip_reassemble(mp, ipf,
12692 			    (frag_offset_flags & IPH_OFFSET) << 3,
12693 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12694 		}
12695 		/* Update per ipfb and ill byte counts */
12696 		ipfb->ipfb_count += ipf->ipf_count;
12697 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12698 		ill->ill_frag_count += ipf->ipf_count;
12699 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12700 		/* If the frag timer wasn't already going, start it. */
12701 		mutex_enter(&ill->ill_lock);
12702 		ill_frag_timer_start(ill);
12703 		mutex_exit(&ill->ill_lock);
12704 		goto reass_done;
12705 	}
12706 
12707 	/*
12708 	 * If the packet's flag has changed (it could be coming up
12709 	 * from an interface different than the previous, therefore
12710 	 * possibly different checksum capability), then forget about
12711 	 * any stored checksum states.  Otherwise add the value to
12712 	 * the existing one stored in the fragment header.
12713 	 */
12714 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12715 		sum_val += ipf->ipf_checksum;
12716 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12717 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12718 		ipf->ipf_checksum = sum_val;
12719 	} else if (ipf->ipf_checksum_flags != 0) {
12720 		/* Forget checksum offload from now on */
12721 		ipf->ipf_checksum_flags = 0;
12722 	}
12723 
12724 	/*
12725 	 * We have a new piece of a datagram which is already being
12726 	 * reassembled.  Update the ECN info if all IP fragments
12727 	 * are ECN capable.  If there is one which is not, clear
12728 	 * all the info.  If there is at least one which has CE
12729 	 * code point, IP needs to report that up to transport.
12730 	 */
12731 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12732 		if (ecn_info == IPH_ECN_CE)
12733 			ipf->ipf_ecn = IPH_ECN_CE;
12734 	} else {
12735 		ipf->ipf_ecn = IPH_ECN_NECT;
12736 	}
12737 	if (offset && ipf->ipf_end == offset) {
12738 		/* The new fragment fits at the end */
12739 		ipf->ipf_tail_mp->b_cont = mp;
12740 		/* Update the byte count */
12741 		ipf->ipf_count += msg_len;
12742 		/* Update per ipfb and ill byte counts */
12743 		ipfb->ipfb_count += msg_len;
12744 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12745 		ill->ill_frag_count += msg_len;
12746 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12747 		if (frag_offset_flags & IPH_MF) {
12748 			/* More to come. */
12749 			ipf->ipf_end = end;
12750 			ipf->ipf_tail_mp = tail_mp;
12751 			goto reass_done;
12752 		}
12753 	} else {
12754 		/* Go do the hard cases. */
12755 		int ret;
12756 
12757 		if (offset == 0)
12758 			ipf->ipf_nf_hdr_len = hdr_length;
12759 
12760 		/* Save current byte count */
12761 		count = ipf->ipf_count;
12762 		ret = ip_reassemble(mp, ipf,
12763 		    (frag_offset_flags & IPH_OFFSET) << 3,
12764 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12765 		/* Count of bytes added and subtracted (freeb()ed) */
12766 		count = ipf->ipf_count - count;
12767 		if (count) {
12768 			/* Update per ipfb and ill byte counts */
12769 			ipfb->ipfb_count += count;
12770 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12771 			ill->ill_frag_count += count;
12772 			ASSERT(ill->ill_frag_count > 0);
12773 		}
12774 		if (ret == IP_REASS_PARTIAL) {
12775 			goto reass_done;
12776 		} else if (ret == IP_REASS_FAILED) {
12777 			/* Reassembly failed. Free up all resources */
12778 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12779 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12780 				IP_REASS_SET_START(t_mp, 0);
12781 				IP_REASS_SET_END(t_mp, 0);
12782 			}
12783 			freemsg(mp);
12784 			goto reass_done;
12785 		}
12786 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12787 	}
12788 	/*
12789 	 * We have completed reassembly.  Unhook the frag header from
12790 	 * the reassembly list.
12791 	 *
12792 	 * Before we free the frag header, record the ECN info
12793 	 * to report back to the transport.
12794 	 */
12795 	ecn_info = ipf->ipf_ecn;
12796 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12797 	ipfp = ipf->ipf_ptphn;
12798 
12799 	/* We need to supply these to caller */
12800 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12801 		sum_val = ipf->ipf_checksum;
12802 	else
12803 		sum_val = 0;
12804 
12805 	mp1 = ipf->ipf_mp;
12806 	count = ipf->ipf_count;
12807 	ipf = ipf->ipf_hash_next;
12808 	if (ipf != NULL)
12809 		ipf->ipf_ptphn = ipfp;
12810 	ipfp[0] = ipf;
12811 	ill->ill_frag_count -= count;
12812 	ASSERT(ipfb->ipfb_count >= count);
12813 	ipfb->ipfb_count -= count;
12814 	ipfb->ipfb_frag_pkts--;
12815 	mutex_exit(&ipfb->ipfb_lock);
12816 	/* Ditch the frag header. */
12817 	mp = mp1->b_cont;
12818 
12819 	freeb(mp1);
12820 
12821 	/* Restore original IP length in header. */
12822 	packet_size = (uint32_t)msgdsize(mp);
12823 	if (packet_size > IP_MAXPACKET) {
12824 		freemsg(mp);
12825 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12826 		return (B_FALSE);
12827 	}
12828 
12829 	if (DB_REF(mp) > 1) {
12830 		mblk_t *mp2 = copymsg(mp);
12831 
12832 		freemsg(mp);
12833 		if (mp2 == NULL) {
12834 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12835 			return (B_FALSE);
12836 		}
12837 		mp = mp2;
12838 	}
12839 	ipha = (ipha_t *)mp->b_rptr;
12840 
12841 	ipha->ipha_length = htons((uint16_t)packet_size);
12842 	/* We're now complete, zip the frag state */
12843 	ipha->ipha_fragment_offset_and_flags = 0;
12844 	/* Record the ECN info. */
12845 	ipha->ipha_type_of_service &= 0xFC;
12846 	ipha->ipha_type_of_service |= ecn_info;
12847 	*mpp = mp;
12848 
12849 	/* Reassembly is successful; return checksum information if needed */
12850 	if (cksum_val != NULL)
12851 		*cksum_val = sum_val;
12852 	if (cksum_flags != NULL)
12853 		*cksum_flags = sum_flags;
12854 
12855 	return (B_TRUE);
12856 }
12857 
12858 /*
12859  * Perform ip header check sum update local options.
12860  * return B_TRUE if all is well, else return B_FALSE and release
12861  * the mp. caller is responsible for decrementing ire ref cnt.
12862  */
12863 static boolean_t
12864 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12865     ip_stack_t *ipst)
12866 {
12867 	mblk_t		*first_mp;
12868 	boolean_t	mctl_present;
12869 	uint16_t	sum;
12870 
12871 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12872 	/*
12873 	 * Don't do the checksum if it has gone through AH/ESP
12874 	 * processing.
12875 	 */
12876 	if (!mctl_present) {
12877 		sum = ip_csum_hdr(ipha);
12878 		if (sum != 0) {
12879 			if (ill != NULL) {
12880 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12881 			} else {
12882 				BUMP_MIB(&ipst->ips_ip_mib,
12883 				    ipIfStatsInCksumErrs);
12884 			}
12885 			freemsg(first_mp);
12886 			return (B_FALSE);
12887 		}
12888 	}
12889 
12890 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12891 		if (mctl_present)
12892 			freeb(first_mp);
12893 		return (B_FALSE);
12894 	}
12895 
12896 	return (B_TRUE);
12897 }
12898 
12899 /*
12900  * All udp packet are delivered to the local host via this routine.
12901  */
12902 void
12903 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12904     ill_t *recv_ill)
12905 {
12906 	uint32_t	sum;
12907 	uint32_t	u1;
12908 	boolean_t	mctl_present;
12909 	conn_t		*connp;
12910 	mblk_t		*first_mp;
12911 	uint16_t	*up;
12912 	ill_t		*ill = (ill_t *)q->q_ptr;
12913 	uint16_t	reass_hck_flags = 0;
12914 	ip_stack_t	*ipst;
12915 
12916 	ASSERT(recv_ill != NULL);
12917 	ipst = recv_ill->ill_ipst;
12918 
12919 #define	rptr    ((uchar_t *)ipha)
12920 
12921 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12922 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12923 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12924 	ASSERT(ill != NULL);
12925 
12926 	/*
12927 	 * FAST PATH for udp packets
12928 	 */
12929 
12930 	/* u1 is # words of IP options */
12931 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12932 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12933 
12934 	/* IP options present */
12935 	if (u1 != 0)
12936 		goto ipoptions;
12937 
12938 	/* Check the IP header checksum.  */
12939 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12940 		/* Clear the IP header h/w cksum flag */
12941 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12942 	} else {
12943 #define	uph	((uint16_t *)ipha)
12944 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12945 		    uph[6] + uph[7] + uph[8] + uph[9];
12946 #undef	uph
12947 		/* finish doing IP checksum */
12948 		sum = (sum & 0xFFFF) + (sum >> 16);
12949 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12950 		/*
12951 		 * Don't verify header checksum if this packet is coming
12952 		 * back from AH/ESP as we already did it.
12953 		 */
12954 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12955 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12956 			freemsg(first_mp);
12957 			return;
12958 		}
12959 	}
12960 
12961 	/*
12962 	 * Count for SNMP of inbound packets for ire.
12963 	 * if mctl is present this might be a secure packet and
12964 	 * has already been counted for in ip_proto_input().
12965 	 */
12966 	if (!mctl_present) {
12967 		UPDATE_IB_PKT_COUNT(ire);
12968 		ire->ire_last_used_time = lbolt;
12969 	}
12970 
12971 	/* packet part of fragmented IP packet? */
12972 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12973 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12974 		goto fragmented;
12975 	}
12976 
12977 	/* u1 = IP header length (20 bytes) */
12978 	u1 = IP_SIMPLE_HDR_LENGTH;
12979 
12980 	/* packet does not contain complete IP & UDP headers */
12981 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12982 		goto udppullup;
12983 
12984 	/* up points to UDP header */
12985 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12986 #define	iphs    ((uint16_t *)ipha)
12987 
12988 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12989 	if (up[3] != 0) {
12990 		mblk_t *mp1 = mp->b_cont;
12991 		boolean_t cksum_err;
12992 		uint16_t hck_flags = 0;
12993 
12994 		/* Pseudo-header checksum */
12995 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12996 		    iphs[9] + up[2];
12997 
12998 		/*
12999 		 * Revert to software checksum calculation if the interface
13000 		 * isn't capable of checksum offload or if IPsec is present.
13001 		 */
13002 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13003 			hck_flags = DB_CKSUMFLAGS(mp);
13004 
13005 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13006 			IP_STAT(ipst, ip_in_sw_cksum);
13007 
13008 		IP_CKSUM_RECV(hck_flags, u1,
13009 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13010 		    (int32_t)((uchar_t *)up - rptr),
13011 		    mp, mp1, cksum_err);
13012 
13013 		if (cksum_err) {
13014 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13015 			if (hck_flags & HCK_FULLCKSUM)
13016 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13017 			else if (hck_flags & HCK_PARTIALCKSUM)
13018 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13019 			else
13020 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13021 
13022 			freemsg(first_mp);
13023 			return;
13024 		}
13025 	}
13026 
13027 	/* Non-fragmented broadcast or multicast packet? */
13028 	if (ire->ire_type == IRE_BROADCAST)
13029 		goto udpslowpath;
13030 
13031 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
13032 	    ire->ire_zoneid, ipst)) != NULL) {
13033 		ASSERT(connp->conn_upq != NULL);
13034 		IP_STAT(ipst, ip_udp_fast_path);
13035 
13036 		if (CONN_UDP_FLOWCTLD(connp)) {
13037 			freemsg(mp);
13038 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
13039 		} else {
13040 			if (!mctl_present) {
13041 				BUMP_MIB(ill->ill_ip_mib,
13042 				    ipIfStatsHCInDelivers);
13043 			}
13044 			/*
13045 			 * mp and first_mp can change.
13046 			 */
13047 			if (ip_udp_check(q, connp, recv_ill,
13048 			    ipha, &mp, &first_mp, mctl_present)) {
13049 				/* Send it upstream */
13050 				CONN_UDP_RECV(connp, mp);
13051 			}
13052 		}
13053 		/*
13054 		 * freeb() cannot deal with null mblk being passed
13055 		 * in and first_mp can be set to null in the call
13056 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
13057 		 */
13058 		if (mctl_present && first_mp != NULL) {
13059 			freeb(first_mp);
13060 		}
13061 		CONN_DEC_REF(connp);
13062 		return;
13063 	}
13064 
13065 	/*
13066 	 * if we got here we know the packet is not fragmented and
13067 	 * has no options. The classifier could not find a conn_t and
13068 	 * most likely its an icmp packet so send it through slow path.
13069 	 */
13070 
13071 	goto udpslowpath;
13072 
13073 ipoptions:
13074 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
13075 		goto slow_done;
13076 	}
13077 
13078 	UPDATE_IB_PKT_COUNT(ire);
13079 	ire->ire_last_used_time = lbolt;
13080 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13081 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13082 fragmented:
13083 		/*
13084 		 * "sum" and "reass_hck_flags" are non-zero if the
13085 		 * reassembled packet has a valid hardware computed
13086 		 * checksum information associated with it.
13087 		 */
13088 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
13089 			goto slow_done;
13090 		/*
13091 		 * Make sure that first_mp points back to mp as
13092 		 * the mp we came in with could have changed in
13093 		 * ip_rput_fragment().
13094 		 */
13095 		ASSERT(!mctl_present);
13096 		ipha = (ipha_t *)mp->b_rptr;
13097 		first_mp = mp;
13098 	}
13099 
13100 	/* Now we have a complete datagram, destined for this machine. */
13101 	u1 = IPH_HDR_LENGTH(ipha);
13102 	/* Pull up the UDP header, if necessary. */
13103 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
13104 udppullup:
13105 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
13106 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13107 			freemsg(first_mp);
13108 			goto slow_done;
13109 		}
13110 		ipha = (ipha_t *)mp->b_rptr;
13111 	}
13112 
13113 	/*
13114 	 * Validate the checksum for the reassembled packet; for the
13115 	 * pullup case we calculate the payload checksum in software.
13116 	 */
13117 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
13118 	if (up[3] != 0) {
13119 		boolean_t cksum_err;
13120 
13121 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13122 			IP_STAT(ipst, ip_in_sw_cksum);
13123 
13124 		IP_CKSUM_RECV_REASS(reass_hck_flags,
13125 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
13126 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13127 		    iphs[9] + up[2], sum, cksum_err);
13128 
13129 		if (cksum_err) {
13130 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13131 
13132 			if (reass_hck_flags & HCK_FULLCKSUM)
13133 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13134 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13135 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13136 			else
13137 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13138 
13139 			freemsg(first_mp);
13140 			goto slow_done;
13141 		}
13142 	}
13143 udpslowpath:
13144 
13145 	/* Clear hardware checksum flag to be safe */
13146 	DB_CKSUMFLAGS(mp) = 0;
13147 
13148 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13149 	    (ire->ire_type == IRE_BROADCAST),
13150 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13151 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13152 
13153 slow_done:
13154 	IP_STAT(ipst, ip_udp_slow_path);
13155 	return;
13156 
13157 #undef  iphs
13158 #undef  rptr
13159 }
13160 
13161 /* ARGSUSED */
13162 static mblk_t *
13163 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13164     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13165     ill_rx_ring_t *ill_ring)
13166 {
13167 	conn_t		*connp;
13168 	uint32_t	sum;
13169 	uint32_t	u1;
13170 	uint16_t	*up;
13171 	int		offset;
13172 	ssize_t		len;
13173 	mblk_t		*mp1;
13174 	boolean_t	syn_present = B_FALSE;
13175 	tcph_t		*tcph;
13176 	uint_t		ip_hdr_len;
13177 	ill_t		*ill = (ill_t *)q->q_ptr;
13178 	zoneid_t	zoneid = ire->ire_zoneid;
13179 	boolean_t	cksum_err;
13180 	uint16_t	hck_flags = 0;
13181 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13182 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13183 
13184 #define	rptr	((uchar_t *)ipha)
13185 
13186 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13187 	ASSERT(ill != NULL);
13188 
13189 	/*
13190 	 * FAST PATH for tcp packets
13191 	 */
13192 
13193 	/* u1 is # words of IP options */
13194 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13195 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13196 
13197 	/* IP options present */
13198 	if (u1) {
13199 		goto ipoptions;
13200 	} else {
13201 		/* Check the IP header checksum.  */
13202 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13203 			/* Clear the IP header h/w cksum flag */
13204 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13205 		} else {
13206 #define	uph	((uint16_t *)ipha)
13207 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13208 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13209 #undef	uph
13210 			/* finish doing IP checksum */
13211 			sum = (sum & 0xFFFF) + (sum >> 16);
13212 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13213 			/*
13214 			 * Don't verify header checksum if this packet
13215 			 * is coming back from AH/ESP as we already did it.
13216 			 */
13217 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13218 				BUMP_MIB(ill->ill_ip_mib,
13219 				    ipIfStatsInCksumErrs);
13220 				goto error;
13221 			}
13222 		}
13223 	}
13224 
13225 	if (!mctl_present) {
13226 		UPDATE_IB_PKT_COUNT(ire);
13227 		ire->ire_last_used_time = lbolt;
13228 	}
13229 
13230 	/* packet part of fragmented IP packet? */
13231 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13232 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13233 		goto fragmented;
13234 	}
13235 
13236 	/* u1 = IP header length (20 bytes) */
13237 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13238 
13239 	/* does packet contain IP+TCP headers? */
13240 	len = mp->b_wptr - rptr;
13241 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13242 		IP_STAT(ipst, ip_tcppullup);
13243 		goto tcppullup;
13244 	}
13245 
13246 	/* TCP options present? */
13247 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13248 
13249 	/*
13250 	 * If options need to be pulled up, then goto tcpoptions.
13251 	 * otherwise we are still in the fast path
13252 	 */
13253 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13254 		IP_STAT(ipst, ip_tcpoptions);
13255 		goto tcpoptions;
13256 	}
13257 
13258 	/* multiple mblks of tcp data? */
13259 	if ((mp1 = mp->b_cont) != NULL) {
13260 		/* more then two? */
13261 		if (mp1->b_cont != NULL) {
13262 			IP_STAT(ipst, ip_multipkttcp);
13263 			goto multipkttcp;
13264 		}
13265 		len += mp1->b_wptr - mp1->b_rptr;
13266 	}
13267 
13268 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13269 
13270 	/* part of pseudo checksum */
13271 
13272 	/* TCP datagram length */
13273 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13274 
13275 #define	iphs    ((uint16_t *)ipha)
13276 
13277 #ifdef	_BIG_ENDIAN
13278 	u1 += IPPROTO_TCP;
13279 #else
13280 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13281 #endif
13282 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13283 
13284 	/*
13285 	 * Revert to software checksum calculation if the interface
13286 	 * isn't capable of checksum offload or if IPsec is present.
13287 	 */
13288 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13289 		hck_flags = DB_CKSUMFLAGS(mp);
13290 
13291 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13292 		IP_STAT(ipst, ip_in_sw_cksum);
13293 
13294 	IP_CKSUM_RECV(hck_flags, u1,
13295 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13296 	    (int32_t)((uchar_t *)up - rptr),
13297 	    mp, mp1, cksum_err);
13298 
13299 	if (cksum_err) {
13300 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13301 
13302 		if (hck_flags & HCK_FULLCKSUM)
13303 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13304 		else if (hck_flags & HCK_PARTIALCKSUM)
13305 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13306 		else
13307 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13308 
13309 		goto error;
13310 	}
13311 
13312 try_again:
13313 
13314 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13315 		    zoneid, ipst)) == NULL) {
13316 		/* Send the TH_RST */
13317 		goto no_conn;
13318 	}
13319 
13320 	/*
13321 	 * TCP FAST PATH for AF_INET socket.
13322 	 *
13323 	 * TCP fast path to avoid extra work. An AF_INET socket type
13324 	 * does not have facility to receive extra information via
13325 	 * ip_process or ip_add_info. Also, when the connection was
13326 	 * established, we made a check if this connection is impacted
13327 	 * by any global IPSec policy or per connection policy (a
13328 	 * policy that comes in effect later will not apply to this
13329 	 * connection). Since all this can be determined at the
13330 	 * connection establishment time, a quick check of flags
13331 	 * can avoid extra work.
13332 	 */
13333 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13334 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13335 		ASSERT(first_mp == mp);
13336 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13337 		SET_SQUEUE(mp, tcp_rput_data, connp);
13338 		return (mp);
13339 	}
13340 
13341 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13342 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13343 		if (IPCL_IS_TCP(connp)) {
13344 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13345 			DB_CKSUMSTART(mp) =
13346 			    (intptr_t)ip_squeue_get(ill_ring);
13347 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13348 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13349 				BUMP_MIB(ill->ill_ip_mib,
13350 				    ipIfStatsHCInDelivers);
13351 				SET_SQUEUE(mp, connp->conn_recv, connp);
13352 				return (mp);
13353 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13354 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13355 				BUMP_MIB(ill->ill_ip_mib,
13356 				    ipIfStatsHCInDelivers);
13357 				ip_squeue_enter_unbound++;
13358 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13359 				    connp);
13360 				return (mp);
13361 			}
13362 			syn_present = B_TRUE;
13363 		}
13364 
13365 	}
13366 
13367 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13368 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13369 
13370 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13371 		/* No need to send this packet to TCP */
13372 		if ((flags & TH_RST) || (flags & TH_URG)) {
13373 			CONN_DEC_REF(connp);
13374 			freemsg(first_mp);
13375 			return (NULL);
13376 		}
13377 		if (flags & TH_ACK) {
13378 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13379 			    ipst->ips_netstack->netstack_tcp);
13380 			CONN_DEC_REF(connp);
13381 			return (NULL);
13382 		}
13383 
13384 		CONN_DEC_REF(connp);
13385 		freemsg(first_mp);
13386 		return (NULL);
13387 	}
13388 
13389 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13390 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13391 		    ipha, NULL, mctl_present);
13392 		if (first_mp == NULL) {
13393 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13394 			CONN_DEC_REF(connp);
13395 			return (NULL);
13396 		}
13397 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13398 			ASSERT(syn_present);
13399 			if (mctl_present) {
13400 				ASSERT(first_mp != mp);
13401 				first_mp->b_datap->db_struioflag |=
13402 				    STRUIO_POLICY;
13403 			} else {
13404 				ASSERT(first_mp == mp);
13405 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13406 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13407 			}
13408 		} else {
13409 			/*
13410 			 * Discard first_mp early since we're dealing with a
13411 			 * fully-connected conn_t and tcp doesn't do policy in
13412 			 * this case.
13413 			 */
13414 			if (mctl_present) {
13415 				freeb(first_mp);
13416 				mctl_present = B_FALSE;
13417 			}
13418 			first_mp = mp;
13419 		}
13420 	}
13421 
13422 	/* Initiate IPPF processing for fastpath */
13423 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13424 		uint32_t	ill_index;
13425 
13426 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13427 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13428 		if (mp == NULL) {
13429 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13430 			    "deferred/dropped during IPPF processing\n"));
13431 			CONN_DEC_REF(connp);
13432 			if (mctl_present)
13433 				freeb(first_mp);
13434 			return (NULL);
13435 		} else if (mctl_present) {
13436 			/*
13437 			 * ip_process might return a new mp.
13438 			 */
13439 			ASSERT(first_mp != mp);
13440 			first_mp->b_cont = mp;
13441 		} else {
13442 			first_mp = mp;
13443 		}
13444 
13445 	}
13446 
13447 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13448 		/*
13449 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13450 		 * make sure IPF_RECVIF is passed to ip_add_info.
13451 		 */
13452 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13453 		    IPCL_ZONEID(connp), ipst);
13454 		if (mp == NULL) {
13455 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13456 			CONN_DEC_REF(connp);
13457 			if (mctl_present)
13458 				freeb(first_mp);
13459 			return (NULL);
13460 		} else if (mctl_present) {
13461 			/*
13462 			 * ip_add_info might return a new mp.
13463 			 */
13464 			ASSERT(first_mp != mp);
13465 			first_mp->b_cont = mp;
13466 		} else {
13467 			first_mp = mp;
13468 		}
13469 	}
13470 
13471 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13472 	if (IPCL_IS_TCP(connp)) {
13473 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13474 		return (first_mp);
13475 	} else {
13476 		putnext(connp->conn_rq, first_mp);
13477 		CONN_DEC_REF(connp);
13478 		return (NULL);
13479 	}
13480 
13481 no_conn:
13482 	/* Initiate IPPf processing, if needed. */
13483 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13484 		uint32_t ill_index;
13485 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13486 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13487 		if (first_mp == NULL) {
13488 			return (NULL);
13489 		}
13490 	}
13491 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13492 
13493 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13494 	    ipst->ips_netstack->netstack_tcp);
13495 	return (NULL);
13496 ipoptions:
13497 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13498 		goto slow_done;
13499 	}
13500 
13501 	UPDATE_IB_PKT_COUNT(ire);
13502 	ire->ire_last_used_time = lbolt;
13503 
13504 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13505 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13506 fragmented:
13507 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13508 			if (mctl_present)
13509 				freeb(first_mp);
13510 			goto slow_done;
13511 		}
13512 		/*
13513 		 * Make sure that first_mp points back to mp as
13514 		 * the mp we came in with could have changed in
13515 		 * ip_rput_fragment().
13516 		 */
13517 		ASSERT(!mctl_present);
13518 		ipha = (ipha_t *)mp->b_rptr;
13519 		first_mp = mp;
13520 	}
13521 
13522 	/* Now we have a complete datagram, destined for this machine. */
13523 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13524 
13525 	len = mp->b_wptr - mp->b_rptr;
13526 	/* Pull up a minimal TCP header, if necessary. */
13527 	if (len < (u1 + 20)) {
13528 tcppullup:
13529 		if (!pullupmsg(mp, u1 + 20)) {
13530 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13531 			goto error;
13532 		}
13533 		ipha = (ipha_t *)mp->b_rptr;
13534 		len = mp->b_wptr - mp->b_rptr;
13535 	}
13536 
13537 	/*
13538 	 * Extract the offset field from the TCP header.  As usual, we
13539 	 * try to help the compiler more than the reader.
13540 	 */
13541 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13542 	if (offset != 5) {
13543 tcpoptions:
13544 		if (offset < 5) {
13545 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13546 			goto error;
13547 		}
13548 		/*
13549 		 * There must be TCP options.
13550 		 * Make sure we can grab them.
13551 		 */
13552 		offset <<= 2;
13553 		offset += u1;
13554 		if (len < offset) {
13555 			if (!pullupmsg(mp, offset)) {
13556 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13557 				goto error;
13558 			}
13559 			ipha = (ipha_t *)mp->b_rptr;
13560 			len = mp->b_wptr - rptr;
13561 		}
13562 	}
13563 
13564 	/* Get the total packet length in len, including headers. */
13565 	if (mp->b_cont) {
13566 multipkttcp:
13567 		len = msgdsize(mp);
13568 	}
13569 
13570 	/*
13571 	 * Check the TCP checksum by pulling together the pseudo-
13572 	 * header checksum, and passing it to ip_csum to be added in
13573 	 * with the TCP datagram.
13574 	 *
13575 	 * Since we are not using the hwcksum if available we must
13576 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13577 	 * If either of these fails along the way the mblk is freed.
13578 	 * If this logic ever changes and mblk is reused to say send
13579 	 * ICMP's back, then this flag may need to be cleared in
13580 	 * other places as well.
13581 	 */
13582 	DB_CKSUMFLAGS(mp) = 0;
13583 
13584 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13585 
13586 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13587 #ifdef	_BIG_ENDIAN
13588 	u1 += IPPROTO_TCP;
13589 #else
13590 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13591 #endif
13592 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13593 	/*
13594 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13595 	 */
13596 	IP_STAT(ipst, ip_in_sw_cksum);
13597 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13598 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13599 		goto error;
13600 	}
13601 
13602 	IP_STAT(ipst, ip_tcp_slow_path);
13603 	goto try_again;
13604 #undef  iphs
13605 #undef  rptr
13606 
13607 error:
13608 	freemsg(first_mp);
13609 slow_done:
13610 	return (NULL);
13611 }
13612 
13613 /* ARGSUSED */
13614 static void
13615 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13616     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13617 {
13618 	conn_t		*connp;
13619 	uint32_t	sum;
13620 	uint32_t	u1;
13621 	ssize_t		len;
13622 	sctp_hdr_t	*sctph;
13623 	zoneid_t	zoneid = ire->ire_zoneid;
13624 	uint32_t	pktsum;
13625 	uint32_t	calcsum;
13626 	uint32_t	ports;
13627 	in6_addr_t	map_src, map_dst;
13628 	ill_t		*ill = (ill_t *)q->q_ptr;
13629 	ip_stack_t	*ipst;
13630 	sctp_stack_t	*sctps;
13631 
13632 	ASSERT(recv_ill != NULL);
13633 	ipst = recv_ill->ill_ipst;
13634 	sctps = ipst->ips_netstack->netstack_sctp;
13635 
13636 #define	rptr	((uchar_t *)ipha)
13637 
13638 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13639 	ASSERT(ill != NULL);
13640 
13641 	/* u1 is # words of IP options */
13642 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13643 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13644 
13645 	/* IP options present */
13646 	if (u1 > 0) {
13647 		goto ipoptions;
13648 	} else {
13649 		/* Check the IP header checksum.  */
13650 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13651 #define	uph	((uint16_t *)ipha)
13652 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13653 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13654 #undef	uph
13655 			/* finish doing IP checksum */
13656 			sum = (sum & 0xFFFF) + (sum >> 16);
13657 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13658 			/*
13659 			 * Don't verify header checksum if this packet
13660 			 * is coming back from AH/ESP as we already did it.
13661 			 */
13662 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13663 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13664 				goto error;
13665 			}
13666 		}
13667 		/*
13668 		 * Since there is no SCTP h/w cksum support yet, just
13669 		 * clear the flag.
13670 		 */
13671 		DB_CKSUMFLAGS(mp) = 0;
13672 	}
13673 
13674 	/*
13675 	 * Don't verify header checksum if this packet is coming
13676 	 * back from AH/ESP as we already did it.
13677 	 */
13678 	if (!mctl_present) {
13679 		UPDATE_IB_PKT_COUNT(ire);
13680 		ire->ire_last_used_time = lbolt;
13681 	}
13682 
13683 	/* packet part of fragmented IP packet? */
13684 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13685 	if (u1 & (IPH_MF | IPH_OFFSET))
13686 		goto fragmented;
13687 
13688 	/* u1 = IP header length (20 bytes) */
13689 	u1 = IP_SIMPLE_HDR_LENGTH;
13690 
13691 find_sctp_client:
13692 	/* Pullup if we don't have the sctp common header. */
13693 	len = MBLKL(mp);
13694 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13695 		if (mp->b_cont == NULL ||
13696 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13697 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13698 			goto error;
13699 		}
13700 		ipha = (ipha_t *)mp->b_rptr;
13701 		len = MBLKL(mp);
13702 	}
13703 
13704 	sctph = (sctp_hdr_t *)(rptr + u1);
13705 #ifdef	DEBUG
13706 	if (!skip_sctp_cksum) {
13707 #endif
13708 		pktsum = sctph->sh_chksum;
13709 		sctph->sh_chksum = 0;
13710 		calcsum = sctp_cksum(mp, u1);
13711 		if (calcsum != pktsum) {
13712 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13713 			goto error;
13714 		}
13715 		sctph->sh_chksum = pktsum;
13716 #ifdef	DEBUG	/* skip_sctp_cksum */
13717 	}
13718 #endif
13719 	/* get the ports */
13720 	ports = *(uint32_t *)&sctph->sh_sport;
13721 
13722 	IRE_REFRELE(ire);
13723 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13724 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13725 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13726 	    sctps)) == NULL) {
13727 		/* Check for raw socket or OOTB handling */
13728 		goto no_conn;
13729 	}
13730 
13731 	/* Found a client; up it goes */
13732 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13733 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13734 	return;
13735 
13736 no_conn:
13737 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13738 	    ports, mctl_present, flags, B_TRUE, zoneid);
13739 	return;
13740 
13741 ipoptions:
13742 	DB_CKSUMFLAGS(mp) = 0;
13743 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13744 		goto slow_done;
13745 
13746 	UPDATE_IB_PKT_COUNT(ire);
13747 	ire->ire_last_used_time = lbolt;
13748 
13749 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13750 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13751 fragmented:
13752 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13753 			goto slow_done;
13754 		/*
13755 		 * Make sure that first_mp points back to mp as
13756 		 * the mp we came in with could have changed in
13757 		 * ip_rput_fragment().
13758 		 */
13759 		ASSERT(!mctl_present);
13760 		ipha = (ipha_t *)mp->b_rptr;
13761 		first_mp = mp;
13762 	}
13763 
13764 	/* Now we have a complete datagram, destined for this machine. */
13765 	u1 = IPH_HDR_LENGTH(ipha);
13766 	goto find_sctp_client;
13767 #undef  iphs
13768 #undef  rptr
13769 
13770 error:
13771 	freemsg(first_mp);
13772 slow_done:
13773 	IRE_REFRELE(ire);
13774 }
13775 
13776 #define	VER_BITS	0xF0
13777 #define	VERSION_6	0x60
13778 
13779 static boolean_t
13780 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13781     ipaddr_t *dstp, ip_stack_t *ipst)
13782 {
13783 	uint_t	opt_len;
13784 	ipha_t *ipha;
13785 	ssize_t len;
13786 	uint_t	pkt_len;
13787 
13788 	ASSERT(ill != NULL);
13789 	IP_STAT(ipst, ip_ipoptions);
13790 	ipha = *iphapp;
13791 
13792 #define	rptr    ((uchar_t *)ipha)
13793 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13794 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13795 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13796 		freemsg(mp);
13797 		return (B_FALSE);
13798 	}
13799 
13800 	/* multiple mblk or too short */
13801 	pkt_len = ntohs(ipha->ipha_length);
13802 
13803 	/* Get the number of words of IP options in the IP header. */
13804 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13805 	if (opt_len) {
13806 		/* IP Options present!  Validate and process. */
13807 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13808 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13809 			goto done;
13810 		}
13811 		/*
13812 		 * Recompute complete header length and make sure we
13813 		 * have access to all of it.
13814 		 */
13815 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13816 		if (len > (mp->b_wptr - rptr)) {
13817 			if (len > pkt_len) {
13818 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13819 				goto done;
13820 			}
13821 			if (!pullupmsg(mp, len)) {
13822 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13823 				goto done;
13824 			}
13825 			ipha = (ipha_t *)mp->b_rptr;
13826 		}
13827 		/*
13828 		 * Go off to ip_rput_options which returns the next hop
13829 		 * destination address, which may have been affected
13830 		 * by source routing.
13831 		 */
13832 		IP_STAT(ipst, ip_opt);
13833 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13834 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13835 			return (B_FALSE);
13836 		}
13837 	}
13838 	*iphapp = ipha;
13839 	return (B_TRUE);
13840 done:
13841 	/* clear b_prev - used by ip_mroute_decap */
13842 	mp->b_prev = NULL;
13843 	freemsg(mp);
13844 	return (B_FALSE);
13845 #undef  rptr
13846 }
13847 
13848 /*
13849  * Deal with the fact that there is no ire for the destination.
13850  * The incoming ill (in_ill) is passed in to ip_newroute only
13851  * in the case of packets coming from mobile ip forward tunnel.
13852  * It must be null otherwise.
13853  */
13854 static ire_t *
13855 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13856     ipaddr_t dst)
13857 {
13858 	ipha_t	*ipha;
13859 	ill_t	*ill;
13860 	ire_t	*ire;
13861 	boolean_t	check_multirt = B_FALSE;
13862 	ip_stack_t *ipst;
13863 
13864 	ipha = (ipha_t *)mp->b_rptr;
13865 	ill = (ill_t *)q->q_ptr;
13866 
13867 	ASSERT(ill != NULL);
13868 	ipst = ill->ill_ipst;
13869 
13870 	/*
13871 	 * No IRE for this destination, so it can't be for us.
13872 	 * Unless we are forwarding, drop the packet.
13873 	 * We have to let source routed packets through
13874 	 * since we don't yet know if they are 'ping -l'
13875 	 * packets i.e. if they will go out over the
13876 	 * same interface as they came in on.
13877 	 */
13878 	if (ll_multicast) {
13879 		freemsg(mp);
13880 		return (NULL);
13881 	}
13882 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13883 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13884 		freemsg(mp);
13885 		return (NULL);
13886 	}
13887 
13888 	/*
13889 	 * Mark this packet as having originated externally.
13890 	 *
13891 	 * For non-forwarding code path, ire_send later double
13892 	 * checks this interface to see if it is still exists
13893 	 * post-ARP resolution.
13894 	 *
13895 	 * Also, IPQOS uses this to differentiate between
13896 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13897 	 * QOS packet processing in ip_wput_attach_llhdr().
13898 	 * The QoS module can mark the b_band for a fastpath message
13899 	 * or the dl_priority field in a unitdata_req header for
13900 	 * CoS marking. This info can only be found in
13901 	 * ip_wput_attach_llhdr().
13902 	 */
13903 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13904 	/*
13905 	 * Clear the indication that this may have a hardware checksum
13906 	 * as we are not using it
13907 	 */
13908 	DB_CKSUMFLAGS(mp) = 0;
13909 
13910 	if (in_ill != NULL) {
13911 		/*
13912 		 * Now hand the packet to ip_newroute.
13913 		 */
13914 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13915 		return (NULL);
13916 	}
13917 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13918 	    MBLK_GETLABEL(mp), ipst);
13919 
13920 	if (ire == NULL && check_multirt) {
13921 		/* Let ip_newroute handle CGTP  */
13922 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13923 		return (NULL);
13924 	}
13925 
13926 	if (ire != NULL)
13927 		return (ire);
13928 
13929 	mp->b_prev = mp->b_next = 0;
13930 	/* send icmp unreachable */
13931 	q = WR(q);
13932 	/* Sent by forwarding path, and router is global zone */
13933 	if (ip_source_routed(ipha, ipst)) {
13934 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13935 		    GLOBAL_ZONEID, ipst);
13936 	} else {
13937 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13938 		    ipst);
13939 	}
13940 
13941 	return (NULL);
13942 
13943 }
13944 
13945 /*
13946  * check ip header length and align it.
13947  */
13948 static boolean_t
13949 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13950 {
13951 	ssize_t len;
13952 	ill_t *ill;
13953 	ipha_t	*ipha;
13954 
13955 	len = MBLKL(mp);
13956 
13957 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13958 		ill = (ill_t *)q->q_ptr;
13959 
13960 		if (!OK_32PTR(mp->b_rptr))
13961 			IP_STAT(ipst, ip_notaligned1);
13962 		else
13963 			IP_STAT(ipst, ip_notaligned2);
13964 		/* Guard against bogus device drivers */
13965 		if (len < 0) {
13966 			/* clear b_prev - used by ip_mroute_decap */
13967 			mp->b_prev = NULL;
13968 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13969 			freemsg(mp);
13970 			return (B_FALSE);
13971 		}
13972 
13973 		if (ip_rput_pullups++ == 0) {
13974 			ipha = (ipha_t *)mp->b_rptr;
13975 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13976 			    "ip_check_and_align_header: %s forced us to "
13977 			    " pullup pkt, hdr len %ld, hdr addr %p",
13978 			    ill->ill_name, len, ipha);
13979 		}
13980 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13981 			/* clear b_prev - used by ip_mroute_decap */
13982 			mp->b_prev = NULL;
13983 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13984 			freemsg(mp);
13985 			return (B_FALSE);
13986 		}
13987 	}
13988 	return (B_TRUE);
13989 }
13990 
13991 ire_t *
13992 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13993 {
13994 	ire_t		*new_ire;
13995 	ill_t		*ire_ill;
13996 	uint_t		ifindex;
13997 	ip_stack_t	*ipst = ill->ill_ipst;
13998 	boolean_t	strict_check = B_FALSE;
13999 
14000 	/*
14001 	 * This packet came in on an interface other than the one associated
14002 	 * with the first ire we found for the destination address. We do
14003 	 * another ire lookup here, using the ingress ill, to see if the
14004 	 * interface is in an interface group.
14005 	 * As long as the ills belong to the same group, we don't consider
14006 	 * them to be arriving on the wrong interface. Thus, if the switch
14007 	 * is doing inbound load spreading, we won't drop packets when the
14008 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
14009 	 * for 'usesrc groups' where the destination address may belong to
14010 	 * another interface to allow multipathing to happen.
14011 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
14012 	 * where the local address may not be unique. In this case we were
14013 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
14014 	 * actually returned. The new lookup, which is more specific, should
14015 	 * only find the IRE_LOCAL associated with the ingress ill if one
14016 	 * exists.
14017 	 */
14018 
14019 	if (ire->ire_ipversion == IPV4_VERSION) {
14020 		if (ipst->ips_ip_strict_dst_multihoming)
14021 			strict_check = B_TRUE;
14022 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
14023 		    ill->ill_ipif, ALL_ZONES, NULL,
14024 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14025 	} else {
14026 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
14027 		if (ipst->ips_ipv6_strict_dst_multihoming)
14028 			strict_check = B_TRUE;
14029 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
14030 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
14031 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14032 	}
14033 	/*
14034 	 * If the same ire that was returned in ip_input() is found then this
14035 	 * is an indication that interface groups are in use. The packet
14036 	 * arrived on a different ill in the group than the one associated with
14037 	 * the destination address.  If a different ire was found then the same
14038 	 * IP address must be hosted on multiple ills. This is possible with
14039 	 * unnumbered point2point interfaces. We switch to use this new ire in
14040 	 * order to have accurate interface statistics.
14041 	 */
14042 	if (new_ire != NULL) {
14043 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
14044 			ire_refrele(ire);
14045 			ire = new_ire;
14046 		} else {
14047 			ire_refrele(new_ire);
14048 		}
14049 		return (ire);
14050 	} else if ((ire->ire_rfq == NULL) &&
14051 		    (ire->ire_ipversion == IPV4_VERSION)) {
14052 		/*
14053 		 * The best match could have been the original ire which
14054 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
14055 		 * the strict multihoming checks are irrelevant as we consider
14056 		 * local addresses hosted on lo0 to be interface agnostic. We
14057 		 * only expect a null ire_rfq on IREs which are associated with
14058 		 * lo0 hence we can return now.
14059 		 */
14060 		return (ire);
14061 	}
14062 
14063 	/*
14064 	 * Chase pointers once and store locally.
14065 	 */
14066 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
14067 	    (ill_t *)(ire->ire_rfq->q_ptr);
14068 	ifindex = ill->ill_usesrc_ifindex;
14069 
14070 	/*
14071 	 * Check if it's a legal address on the 'usesrc' interface.
14072 	 */
14073 	if ((ifindex != 0) && (ire_ill != NULL) &&
14074 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
14075 		return (ire);
14076 	}
14077 
14078 	/*
14079 	 * If the ip*_strict_dst_multihoming switch is on then we can
14080 	 * only accept this packet if the interface is marked as routing.
14081 	 */
14082 	if (!(strict_check))
14083 		return (ire);
14084 
14085 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
14086 	    ILLF_ROUTER) != 0) {
14087 		return (ire);
14088 	}
14089 
14090 	ire_refrele(ire);
14091 	return (NULL);
14092 }
14093 
14094 ire_t *
14095 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
14096 {
14097 	ipha_t	*ipha;
14098 	ipaddr_t ip_dst, ip_src;
14099 	ire_t	*src_ire = NULL;
14100 	ill_t	*stq_ill;
14101 	uint_t	hlen;
14102 	uint_t	pkt_len;
14103 	uint32_t sum;
14104 	queue_t	*dev_q;
14105 	boolean_t check_multirt = B_FALSE;
14106 	ip_stack_t *ipst = ill->ill_ipst;
14107 
14108 	ipha = (ipha_t *)mp->b_rptr;
14109 
14110 	/*
14111 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14112 	 * The loopback address check for both src and dst has already
14113 	 * been checked in ip_input
14114 	 */
14115 	ip_dst = ntohl(dst);
14116 	ip_src = ntohl(ipha->ipha_src);
14117 
14118 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
14119 	    IN_CLASSD(ip_src)) {
14120 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14121 		goto drop;
14122 	}
14123 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14124 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14125 
14126 	if (src_ire != NULL) {
14127 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14128 		goto drop;
14129 	}
14130 
14131 
14132 	/* No ire cache of nexthop. So first create one  */
14133 	if (ire == NULL) {
14134 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
14135 		/*
14136 		 * We only come to ip_fast_forward if ip_cgtp_filter is
14137 		 * is not set. So upon return from ire_forward
14138 		 * check_multirt should remain as false.
14139 		 */
14140 		ASSERT(!check_multirt);
14141 		if (ire == NULL) {
14142 			/* An attempt was made to forward the packet */
14143 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14144 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14145 			mp->b_prev = mp->b_next = 0;
14146 			/* send icmp unreachable */
14147 			/* Sent by forwarding path, and router is global zone */
14148 			if (ip_source_routed(ipha, ipst)) {
14149 				icmp_unreachable(ill->ill_wq, mp,
14150 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
14151 				    ipst);
14152 			} else {
14153 				icmp_unreachable(ill->ill_wq, mp,
14154 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
14155 				    ipst);
14156 			}
14157 			return (ire);
14158 		}
14159 	}
14160 
14161 	/*
14162 	 * Forwarding fastpath exception case:
14163 	 * If either of the follwoing case is true, we take
14164 	 * the slowpath
14165 	 *	o forwarding is not enabled
14166 	 *	o incoming and outgoing interface are the same, or the same
14167 	 *	  IPMP group
14168 	 *	o corresponding ire is in incomplete state
14169 	 *	o packet needs fragmentation
14170 	 *
14171 	 * The codeflow from here on is thus:
14172 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14173 	 */
14174 	pkt_len = ntohs(ipha->ipha_length);
14175 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14176 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14177 	    !(ill->ill_flags & ILLF_ROUTER) ||
14178 	    (ill == stq_ill) ||
14179 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14180 	    (ire->ire_nce == NULL) ||
14181 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14182 	    (pkt_len > ire->ire_max_frag) ||
14183 	    ipha->ipha_ttl <= 1) {
14184 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14185 		    ipha, ill, B_FALSE);
14186 		return (ire);
14187 	}
14188 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14189 
14190 	DTRACE_PROBE4(ip4__forwarding__start,
14191 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14192 
14193 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14194 	    ipst->ips_ipv4firewall_forwarding,
14195 	    ill, stq_ill, ipha, mp, mp, ipst);
14196 
14197 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14198 
14199 	if (mp == NULL)
14200 		goto drop;
14201 
14202 	mp->b_datap->db_struioun.cksum.flags = 0;
14203 	/* Adjust the checksum to reflect the ttl decrement. */
14204 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14205 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14206 	ipha->ipha_ttl--;
14207 
14208 	dev_q = ire->ire_stq->q_next;
14209 	if ((dev_q->q_next != NULL ||
14210 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14211 		goto indiscard;
14212 	}
14213 
14214 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14215 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14216 
14217 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14218 		mblk_t *mpip = mp;
14219 
14220 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14221 		if (mp != NULL) {
14222 			DTRACE_PROBE4(ip4__physical__out__start,
14223 			    ill_t *, NULL, ill_t *, stq_ill,
14224 			    ipha_t *, ipha, mblk_t *, mp);
14225 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14226 			    ipst->ips_ipv4firewall_physical_out,
14227 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14228 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14229 			    mp);
14230 			if (mp == NULL)
14231 				goto drop;
14232 
14233 			UPDATE_IB_PKT_COUNT(ire);
14234 			ire->ire_last_used_time = lbolt;
14235 			BUMP_MIB(stq_ill->ill_ip_mib,
14236 			    ipIfStatsHCOutForwDatagrams);
14237 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14238 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14239 			    pkt_len);
14240 			putnext(ire->ire_stq, mp);
14241 			return (ire);
14242 		}
14243 	}
14244 
14245 indiscard:
14246 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14247 drop:
14248 	if (mp != NULL)
14249 		freemsg(mp);
14250 	if (src_ire != NULL)
14251 		ire_refrele(src_ire);
14252 	return (ire);
14253 
14254 }
14255 
14256 /*
14257  * This function is called in the forwarding slowpath, when
14258  * either the ire lacks the link-layer address, or the packet needs
14259  * further processing(eg. fragmentation), before transmission.
14260  */
14261 
14262 static void
14263 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14264     ill_t *ill, boolean_t ll_multicast)
14265 {
14266 	ill_group_t	*ill_group;
14267 	ill_group_t	*ire_group;
14268 	queue_t		*dev_q;
14269 	ire_t		*src_ire;
14270 	ip_stack_t	*ipst = ill->ill_ipst;
14271 
14272 	ASSERT(ire->ire_stq != NULL);
14273 
14274 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14275 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14276 
14277 	if (ll_multicast != 0) {
14278 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14279 		goto drop_pkt;
14280 	}
14281 
14282 	/*
14283 	 * check if ipha_src is a broadcast address. Note that this
14284 	 * check is redundant when we get here from ip_fast_forward()
14285 	 * which has already done this check. However, since we can
14286 	 * also get here from ip_rput_process_broadcast() or, for
14287 	 * for the slow path through ip_fast_forward(), we perform
14288 	 * the check again for code-reusability
14289 	 */
14290 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14291 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14292 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14293 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14294 		if (src_ire != NULL)
14295 			ire_refrele(src_ire);
14296 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14297 		ip2dbg(("ip_rput_process_forward: Received packet with"
14298 		    " bad src/dst address on %s\n", ill->ill_name));
14299 		goto drop_pkt;
14300 	}
14301 
14302 	ill_group = ill->ill_group;
14303 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14304 	/*
14305 	 * Check if we want to forward this one at this time.
14306 	 * We allow source routed packets on a host provided that
14307 	 * they go out the same interface or same interface group
14308 	 * as they came in on.
14309 	 *
14310 	 * XXX To be quicker, we may wish to not chase pointers to
14311 	 * get the ILLF_ROUTER flag and instead store the
14312 	 * forwarding policy in the ire.  An unfortunate
14313 	 * side-effect of that would be requiring an ire flush
14314 	 * whenever the ILLF_ROUTER flag changes.
14315 	 */
14316 	if (((ill->ill_flags &
14317 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14318 	    ILLF_ROUTER) == 0) &&
14319 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14320 	    (ill_group != NULL && ill_group == ire_group)))) {
14321 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14322 		if (ip_source_routed(ipha, ipst)) {
14323 			q = WR(q);
14324 			/*
14325 			 * Clear the indication that this may have
14326 			 * hardware checksum as we are not using it.
14327 			 */
14328 			DB_CKSUMFLAGS(mp) = 0;
14329 			/* Sent by forwarding path, and router is global zone */
14330 			icmp_unreachable(q, mp,
14331 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14332 			return;
14333 		}
14334 		goto drop_pkt;
14335 	}
14336 
14337 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14338 
14339 	/* Packet is being forwarded. Turning off hwcksum flag. */
14340 	DB_CKSUMFLAGS(mp) = 0;
14341 	if (ipst->ips_ip_g_send_redirects) {
14342 		/*
14343 		 * Check whether the incoming interface and outgoing
14344 		 * interface is part of the same group. If so,
14345 		 * send redirects.
14346 		 *
14347 		 * Check the source address to see if it originated
14348 		 * on the same logical subnet it is going back out on.
14349 		 * If so, we should be able to send it a redirect.
14350 		 * Avoid sending a redirect if the destination
14351 		 * is directly connected (i.e., ipha_dst is the same
14352 		 * as ire_gateway_addr or the ire_addr of the
14353 		 * nexthop IRE_CACHE ), or if the packet was source
14354 		 * routed out this interface.
14355 		 */
14356 		ipaddr_t src, nhop;
14357 		mblk_t	*mp1;
14358 		ire_t	*nhop_ire = NULL;
14359 
14360 		/*
14361 		 * Check whether ire_rfq and q are from the same ill
14362 		 * or if they are not same, they at least belong
14363 		 * to the same group. If so, send redirects.
14364 		 */
14365 		if ((ire->ire_rfq == q ||
14366 		    (ill_group != NULL && ill_group == ire_group)) &&
14367 		    !ip_source_routed(ipha, ipst)) {
14368 
14369 			nhop = (ire->ire_gateway_addr != 0 ?
14370 			    ire->ire_gateway_addr : ire->ire_addr);
14371 
14372 			if (ipha->ipha_dst == nhop) {
14373 				/*
14374 				 * We avoid sending a redirect if the
14375 				 * destination is directly connected
14376 				 * because it is possible that multiple
14377 				 * IP subnets may have been configured on
14378 				 * the link, and the source may not
14379 				 * be on the same subnet as ip destination,
14380 				 * even though they are on the same
14381 				 * physical link.
14382 				 */
14383 				goto sendit;
14384 			}
14385 
14386 			src = ipha->ipha_src;
14387 
14388 			/*
14389 			 * We look up the interface ire for the nexthop,
14390 			 * to see if ipha_src is in the same subnet
14391 			 * as the nexthop.
14392 			 *
14393 			 * Note that, if, in the future, IRE_CACHE entries
14394 			 * are obsoleted,  this lookup will not be needed,
14395 			 * as the ire passed to this function will be the
14396 			 * same as the nhop_ire computed below.
14397 			 */
14398 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14399 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14400 			    0, NULL, MATCH_IRE_TYPE, ipst);
14401 
14402 			if (nhop_ire != NULL) {
14403 				if ((src & nhop_ire->ire_mask) ==
14404 				    (nhop & nhop_ire->ire_mask)) {
14405 					/*
14406 					 * The source is directly connected.
14407 					 * Just copy the ip header (which is
14408 					 * in the first mblk)
14409 					 */
14410 					mp1 = copyb(mp);
14411 					if (mp1 != NULL) {
14412 						icmp_send_redirect(WR(q), mp1,
14413 						    nhop, ipst);
14414 					}
14415 				}
14416 				ire_refrele(nhop_ire);
14417 			}
14418 		}
14419 	}
14420 sendit:
14421 	dev_q = ire->ire_stq->q_next;
14422 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14423 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14424 		freemsg(mp);
14425 		return;
14426 	}
14427 
14428 	ip_rput_forward(ire, ipha, mp, ill);
14429 	return;
14430 
14431 drop_pkt:
14432 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14433 	freemsg(mp);
14434 }
14435 
14436 ire_t *
14437 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14438     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14439 {
14440 	queue_t		*q;
14441 	uint16_t	hcksumflags;
14442 	ip_stack_t	*ipst = ill->ill_ipst;
14443 
14444 	q = *qp;
14445 
14446 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14447 
14448 	/*
14449 	 * Clear the indication that this may have hardware
14450 	 * checksum as we are not using it for forwarding.
14451 	 */
14452 	hcksumflags = DB_CKSUMFLAGS(mp);
14453 	DB_CKSUMFLAGS(mp) = 0;
14454 
14455 	/*
14456 	 * Directed broadcast forwarding: if the packet came in over a
14457 	 * different interface then it is routed out over we can forward it.
14458 	 */
14459 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14460 		ire_refrele(ire);
14461 		freemsg(mp);
14462 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14463 		return (NULL);
14464 	}
14465 	/*
14466 	 * For multicast we have set dst to be INADDR_BROADCAST
14467 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14468 	 * only for broadcast packets.
14469 	 */
14470 	if (!CLASSD(ipha->ipha_dst)) {
14471 		ire_t *new_ire;
14472 		ipif_t *ipif;
14473 		/*
14474 		 * For ill groups, as the switch duplicates broadcasts
14475 		 * across all the ports, we need to filter out and
14476 		 * send up only one copy. There is one copy for every
14477 		 * broadcast address on each ill. Thus, we look for a
14478 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14479 		 * later to see whether this ill is eligible to receive
14480 		 * them or not. ill_nominate_bcast_rcv() nominates only
14481 		 * one set of IREs for receiving.
14482 		 */
14483 
14484 		ipif = ipif_get_next_ipif(NULL, ill);
14485 		if (ipif == NULL) {
14486 			ire_refrele(ire);
14487 			freemsg(mp);
14488 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14489 			return (NULL);
14490 		}
14491 		new_ire = ire_ctable_lookup(dst, 0, 0,
14492 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14493 		ipif_refrele(ipif);
14494 
14495 		if (new_ire != NULL) {
14496 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14497 				ire_refrele(ire);
14498 				ire_refrele(new_ire);
14499 				freemsg(mp);
14500 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14501 				return (NULL);
14502 			}
14503 			/*
14504 			 * In the special case of multirouted broadcast
14505 			 * packets, we unconditionally need to "gateway"
14506 			 * them to the appropriate interface here.
14507 			 * In the normal case, this cannot happen, because
14508 			 * there is no broadcast IRE tagged with the
14509 			 * RTF_MULTIRT flag.
14510 			 */
14511 			if (new_ire->ire_flags & RTF_MULTIRT) {
14512 				ire_refrele(new_ire);
14513 				if (ire->ire_rfq != NULL) {
14514 					q = ire->ire_rfq;
14515 					*qp = q;
14516 				}
14517 			} else {
14518 				ire_refrele(ire);
14519 				ire = new_ire;
14520 			}
14521 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14522 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14523 				/*
14524 				 * Free the message if
14525 				 * ip_g_forward_directed_bcast is turned
14526 				 * off for non-local broadcast.
14527 				 */
14528 				ire_refrele(ire);
14529 				freemsg(mp);
14530 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14531 				return (NULL);
14532 			}
14533 		} else {
14534 			/*
14535 			 * This CGTP packet successfully passed the
14536 			 * CGTP filter, but the related CGTP
14537 			 * broadcast IRE has not been found,
14538 			 * meaning that the redundant ipif is
14539 			 * probably down. However, if we discarded
14540 			 * this packet, its duplicate would be
14541 			 * filtered out by the CGTP filter so none
14542 			 * of them would get through. So we keep
14543 			 * going with this one.
14544 			 */
14545 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14546 			if (ire->ire_rfq != NULL) {
14547 				q = ire->ire_rfq;
14548 				*qp = q;
14549 			}
14550 		}
14551 	}
14552 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14553 		/*
14554 		 * Verify that there are not more then one
14555 		 * IRE_BROADCAST with this broadcast address which
14556 		 * has ire_stq set.
14557 		 * TODO: simplify, loop over all IRE's
14558 		 */
14559 		ire_t	*ire1;
14560 		int	num_stq = 0;
14561 		mblk_t	*mp1;
14562 
14563 		/* Find the first one with ire_stq set */
14564 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14565 		for (ire1 = ire; ire1 &&
14566 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14567 		    ire1 = ire1->ire_next)
14568 			;
14569 		if (ire1) {
14570 			ire_refrele(ire);
14571 			ire = ire1;
14572 			IRE_REFHOLD(ire);
14573 		}
14574 
14575 		/* Check if there are additional ones with stq set */
14576 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14577 			if (ire->ire_addr != ire1->ire_addr)
14578 				break;
14579 			if (ire1->ire_stq) {
14580 				num_stq++;
14581 				break;
14582 			}
14583 		}
14584 		rw_exit(&ire->ire_bucket->irb_lock);
14585 		if (num_stq == 1 && ire->ire_stq != NULL) {
14586 			ip1dbg(("ip_rput_process_broadcast: directed "
14587 			    "broadcast to 0x%x\n",
14588 			    ntohl(ire->ire_addr)));
14589 			mp1 = copymsg(mp);
14590 			if (mp1) {
14591 				switch (ipha->ipha_protocol) {
14592 				case IPPROTO_UDP:
14593 					ip_udp_input(q, mp1, ipha, ire, ill);
14594 					break;
14595 				default:
14596 					ip_proto_input(q, mp1, ipha, ire, ill);
14597 					break;
14598 				}
14599 			}
14600 			/*
14601 			 * Adjust ttl to 2 (1+1 - the forward engine
14602 			 * will decrement it by one.
14603 			 */
14604 			if (ip_csum_hdr(ipha)) {
14605 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14606 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14607 				freemsg(mp);
14608 				ire_refrele(ire);
14609 				return (NULL);
14610 			}
14611 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14612 			ipha->ipha_hdr_checksum = 0;
14613 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14614 			ip_rput_process_forward(q, mp, ire, ipha,
14615 			    ill, ll_multicast);
14616 			ire_refrele(ire);
14617 			return (NULL);
14618 		}
14619 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14620 		    ntohl(ire->ire_addr)));
14621 	}
14622 
14623 
14624 	/* Restore any hardware checksum flags */
14625 	DB_CKSUMFLAGS(mp) = hcksumflags;
14626 	return (ire);
14627 }
14628 
14629 /* ARGSUSED */
14630 static boolean_t
14631 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14632     int *ll_multicast, ipaddr_t *dstp)
14633 {
14634 	ip_stack_t	*ipst = ill->ill_ipst;
14635 
14636 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14637 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14638 	    ntohs(ipha->ipha_length));
14639 
14640 	/*
14641 	 * Forward packets only if we have joined the allmulti
14642 	 * group on this interface.
14643 	 */
14644 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14645 		int retval;
14646 
14647 		/*
14648 		 * Clear the indication that this may have hardware
14649 		 * checksum as we are not using it.
14650 		 */
14651 		DB_CKSUMFLAGS(mp) = 0;
14652 		retval = ip_mforward(ill, ipha, mp);
14653 		/* ip_mforward updates mib variables if needed */
14654 		/* clear b_prev - used by ip_mroute_decap */
14655 		mp->b_prev = NULL;
14656 
14657 		switch (retval) {
14658 		case 0:
14659 			/*
14660 			 * pkt is okay and arrived on phyint.
14661 			 *
14662 			 * If we are running as a multicast router
14663 			 * we need to see all IGMP and/or PIM packets.
14664 			 */
14665 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14666 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14667 				goto done;
14668 			}
14669 			break;
14670 		case -1:
14671 			/* pkt is mal-formed, toss it */
14672 			goto drop_pkt;
14673 		case 1:
14674 			/* pkt is okay and arrived on a tunnel */
14675 			/*
14676 			 * If we are running a multicast router
14677 			 *  we need to see all igmp packets.
14678 			 */
14679 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14680 				*dstp = INADDR_BROADCAST;
14681 				*ll_multicast = 1;
14682 				return (B_FALSE);
14683 			}
14684 
14685 			goto drop_pkt;
14686 		}
14687 	}
14688 
14689 	ILM_WALKER_HOLD(ill);
14690 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14691 		/*
14692 		 * This might just be caused by the fact that
14693 		 * multiple IP Multicast addresses map to the same
14694 		 * link layer multicast - no need to increment counter!
14695 		 */
14696 		ILM_WALKER_RELE(ill);
14697 		freemsg(mp);
14698 		return (B_TRUE);
14699 	}
14700 	ILM_WALKER_RELE(ill);
14701 done:
14702 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14703 	/*
14704 	 * This assumes the we deliver to all streams for multicast
14705 	 * and broadcast packets.
14706 	 */
14707 	*dstp = INADDR_BROADCAST;
14708 	*ll_multicast = 1;
14709 	return (B_FALSE);
14710 drop_pkt:
14711 	ip2dbg(("ip_rput: drop pkt\n"));
14712 	freemsg(mp);
14713 	return (B_TRUE);
14714 }
14715 
14716 static boolean_t
14717 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14718     int *ll_multicast, mblk_t **mpp)
14719 {
14720 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14721 	boolean_t must_copy = B_FALSE;
14722 	struct iocblk   *iocp;
14723 	ipha_t		*ipha;
14724 	ip_stack_t	*ipst = ill->ill_ipst;
14725 
14726 #define	rptr    ((uchar_t *)ipha)
14727 
14728 	first_mp = *first_mpp;
14729 	mp = *mpp;
14730 
14731 	ASSERT(first_mp == mp);
14732 
14733 	/*
14734 	 * if db_ref > 1 then copymsg and free original. Packet may be
14735 	 * changed and do not want other entity who has a reference to this
14736 	 * message to trip over the changes. This is a blind change because
14737 	 * trying to catch all places that might change packet is too
14738 	 * difficult (since it may be a module above this one)
14739 	 *
14740 	 * This corresponds to the non-fast path case. We walk down the full
14741 	 * chain in this case, and check the db_ref count of all the dblks,
14742 	 * and do a copymsg if required. It is possible that the db_ref counts
14743 	 * of the data blocks in the mblk chain can be different.
14744 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14745 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14746 	 * 'snoop' is running.
14747 	 */
14748 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14749 		if (mp1->b_datap->db_ref > 1) {
14750 			must_copy = B_TRUE;
14751 			break;
14752 		}
14753 	}
14754 
14755 	if (must_copy) {
14756 		mp1 = copymsg(mp);
14757 		if (mp1 == NULL) {
14758 			for (mp1 = mp; mp1 != NULL;
14759 			    mp1 = mp1->b_cont) {
14760 				mp1->b_next = NULL;
14761 				mp1->b_prev = NULL;
14762 			}
14763 			freemsg(mp);
14764 			if (ill != NULL) {
14765 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14766 			} else {
14767 				BUMP_MIB(&ipst->ips_ip_mib,
14768 				    ipIfStatsInDiscards);
14769 			}
14770 			return (B_TRUE);
14771 		}
14772 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14773 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14774 			/* Copy b_prev - used by ip_mroute_decap */
14775 			to_mp->b_prev = from_mp->b_prev;
14776 			from_mp->b_prev = NULL;
14777 		}
14778 		*first_mpp = first_mp = mp1;
14779 		freemsg(mp);
14780 		mp = mp1;
14781 		*mpp = mp1;
14782 	}
14783 
14784 	ipha = (ipha_t *)mp->b_rptr;
14785 
14786 	/*
14787 	 * previous code has a case for M_DATA.
14788 	 * We want to check how that happens.
14789 	 */
14790 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14791 	switch (first_mp->b_datap->db_type) {
14792 	case M_PROTO:
14793 	case M_PCPROTO:
14794 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14795 		    DL_UNITDATA_IND) {
14796 			/* Go handle anything other than data elsewhere. */
14797 			ip_rput_dlpi(q, mp);
14798 			return (B_TRUE);
14799 		}
14800 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14801 		/* Ditch the DLPI header. */
14802 		mp1 = mp->b_cont;
14803 		ASSERT(first_mp == mp);
14804 		*first_mpp = mp1;
14805 		freeb(mp);
14806 		*mpp = mp1;
14807 		return (B_FALSE);
14808 	case M_IOCACK:
14809 		ip1dbg(("got iocack "));
14810 		iocp = (struct iocblk *)mp->b_rptr;
14811 		switch (iocp->ioc_cmd) {
14812 		case DL_IOC_HDR_INFO:
14813 			ill = (ill_t *)q->q_ptr;
14814 			ill_fastpath_ack(ill, mp);
14815 			return (B_TRUE);
14816 		case SIOCSTUNPARAM:
14817 		case OSIOCSTUNPARAM:
14818 			/* Go through qwriter_ip */
14819 			break;
14820 		case SIOCGTUNPARAM:
14821 		case OSIOCGTUNPARAM:
14822 			ip_rput_other(NULL, q, mp, NULL);
14823 			return (B_TRUE);
14824 		default:
14825 			putnext(q, mp);
14826 			return (B_TRUE);
14827 		}
14828 		/* FALLTHRU */
14829 	case M_ERROR:
14830 	case M_HANGUP:
14831 		/*
14832 		 * Since this is on the ill stream we unconditionally
14833 		 * bump up the refcount
14834 		 */
14835 		ill_refhold(ill);
14836 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14837 		    B_FALSE);
14838 		return (B_TRUE);
14839 	case M_CTL:
14840 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14841 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14842 			IPHADA_M_CTL)) {
14843 			/*
14844 			 * It's an IPsec accelerated packet.
14845 			 * Make sure that the ill from which we received the
14846 			 * packet has enabled IPsec hardware acceleration.
14847 			 */
14848 			if (!(ill->ill_capabilities &
14849 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14850 				/* IPsec kstats: bean counter */
14851 				freemsg(mp);
14852 				return (B_TRUE);
14853 			}
14854 
14855 			/*
14856 			 * Make mp point to the mblk following the M_CTL,
14857 			 * then process according to type of mp.
14858 			 * After this processing, first_mp will point to
14859 			 * the data-attributes and mp to the pkt following
14860 			 * the M_CTL.
14861 			 */
14862 			mp = first_mp->b_cont;
14863 			if (mp == NULL) {
14864 				freemsg(first_mp);
14865 				return (B_TRUE);
14866 			}
14867 			/*
14868 			 * A Hardware Accelerated packet can only be M_DATA
14869 			 * ESP or AH packet.
14870 			 */
14871 			if (mp->b_datap->db_type != M_DATA) {
14872 				/* non-M_DATA IPsec accelerated packet */
14873 				IPSECHW_DEBUG(IPSECHW_PKT,
14874 				    ("non-M_DATA IPsec accelerated pkt\n"));
14875 				freemsg(first_mp);
14876 				return (B_TRUE);
14877 			}
14878 			ipha = (ipha_t *)mp->b_rptr;
14879 			if (ipha->ipha_protocol != IPPROTO_AH &&
14880 			    ipha->ipha_protocol != IPPROTO_ESP) {
14881 				IPSECHW_DEBUG(IPSECHW_PKT,
14882 				    ("non-M_DATA IPsec accelerated pkt\n"));
14883 				freemsg(first_mp);
14884 				return (B_TRUE);
14885 			}
14886 			*mpp = mp;
14887 			return (B_FALSE);
14888 		}
14889 		putnext(q, mp);
14890 		return (B_TRUE);
14891 	case M_FLUSH:
14892 		if (*mp->b_rptr & FLUSHW) {
14893 			*mp->b_rptr &= ~FLUSHR;
14894 			qreply(q, mp);
14895 			return (B_TRUE);
14896 		}
14897 		freemsg(mp);
14898 		return (B_TRUE);
14899 	case M_IOCNAK:
14900 		ip1dbg(("got iocnak "));
14901 		iocp = (struct iocblk *)mp->b_rptr;
14902 		switch (iocp->ioc_cmd) {
14903 		case DL_IOC_HDR_INFO:
14904 		case SIOCSTUNPARAM:
14905 		case OSIOCSTUNPARAM:
14906 			/*
14907 			 * Since this is on the ill stream we unconditionally
14908 			 * bump up the refcount
14909 			 */
14910 			ill_refhold(ill);
14911 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14912 			    CUR_OP, B_FALSE);
14913 			return (B_TRUE);
14914 		case SIOCGTUNPARAM:
14915 		case OSIOCGTUNPARAM:
14916 			ip_rput_other(NULL, q, mp, NULL);
14917 			return (B_TRUE);
14918 		default:
14919 			break;
14920 		}
14921 		/* FALLTHRU */
14922 	default:
14923 		putnext(q, mp);
14924 		return (B_TRUE);
14925 	}
14926 }
14927 
14928 /* Read side put procedure.  Packets coming from the wire arrive here. */
14929 void
14930 ip_rput(queue_t *q, mblk_t *mp)
14931 {
14932 	ill_t	*ill;
14933 	ip_stack_t	*ipst;
14934 
14935 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14936 
14937 	ill = (ill_t *)q->q_ptr;
14938 	ipst = ill->ill_ipst;
14939 
14940 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14941 		union DL_primitives *dl;
14942 
14943 		/*
14944 		 * Things are opening or closing. Only accept DLPI control
14945 		 * messages. In the open case, the ill->ill_ipif has not yet
14946 		 * been created. In the close case, things hanging off the
14947 		 * ill could have been freed already. In either case it
14948 		 * may not be safe to proceed further.
14949 		 */
14950 
14951 		dl = (union DL_primitives *)mp->b_rptr;
14952 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14953 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14954 			/*
14955 			 * Also SIOC[GS]TUN* ioctls can come here.
14956 			 */
14957 			inet_freemsg(mp);
14958 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14959 			    "ip_input_end: q %p (%S)", q, "uninit");
14960 			return;
14961 		}
14962 	}
14963 
14964 	/*
14965 	 * if db_ref > 1 then copymsg and free original. Packet may be
14966 	 * changed and we do not want the other entity who has a reference to
14967 	 * this message to trip over the changes. This is a blind change because
14968 	 * trying to catch all places that might change the packet is too
14969 	 * difficult.
14970 	 *
14971 	 * This corresponds to the fast path case, where we have a chain of
14972 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14973 	 * in the mblk chain. There doesn't seem to be a reason why a device
14974 	 * driver would send up data with varying db_ref counts in the mblk
14975 	 * chain. In any case the Fast path is a private interface, and our
14976 	 * drivers don't do such a thing. Given the above assumption, there is
14977 	 * no need to walk down the entire mblk chain (which could have a
14978 	 * potential performance problem)
14979 	 */
14980 	if (mp->b_datap->db_ref > 1) {
14981 		mblk_t  *mp1;
14982 		boolean_t adjusted = B_FALSE;
14983 		IP_STAT(ipst, ip_db_ref);
14984 
14985 		/*
14986 		 * The IP_RECVSLLA option depends on having the link layer
14987 		 * header. First check that:
14988 		 * a> the underlying device is of type ether, since this
14989 		 * option is currently supported only over ethernet.
14990 		 * b> there is enough room to copy over the link layer header.
14991 		 *
14992 		 * Once the checks are done, adjust rptr so that the link layer
14993 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14994 		 * be returned by some non-ethernet drivers but in this case the
14995 		 * second check will fail.
14996 		 */
14997 		if (ill->ill_type == IFT_ETHER &&
14998 		    (mp->b_rptr - mp->b_datap->db_base) >=
14999 		    sizeof (struct ether_header)) {
15000 			mp->b_rptr -= sizeof (struct ether_header);
15001 			adjusted = B_TRUE;
15002 		}
15003 		mp1 = copymsg(mp);
15004 		if (mp1 == NULL) {
15005 			mp->b_next = NULL;
15006 			/* clear b_prev - used by ip_mroute_decap */
15007 			mp->b_prev = NULL;
15008 			freemsg(mp);
15009 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15010 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15011 			    "ip_rput_end: q %p (%S)", q, "copymsg");
15012 			return;
15013 		}
15014 		if (adjusted) {
15015 			/*
15016 			 * Copy is done. Restore the pointer in the _new_ mblk
15017 			 */
15018 			mp1->b_rptr += sizeof (struct ether_header);
15019 		}
15020 		/* Copy b_prev - used by ip_mroute_decap */
15021 		mp1->b_prev = mp->b_prev;
15022 		mp->b_prev = NULL;
15023 		freemsg(mp);
15024 		mp = mp1;
15025 	}
15026 
15027 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15028 	    "ip_rput_end: q %p (%S)", q, "end");
15029 
15030 	ip_input(ill, NULL, mp, NULL);
15031 }
15032 
15033 /*
15034  * Direct read side procedure capable of dealing with chains. GLDv3 based
15035  * drivers call this function directly with mblk chains while STREAMS
15036  * read side procedure ip_rput() calls this for single packet with ip_ring
15037  * set to NULL to process one packet at a time.
15038  *
15039  * The ill will always be valid if this function is called directly from
15040  * the driver.
15041  *
15042  * If ip_input() is called from GLDv3:
15043  *
15044  *   - This must be a non-VLAN IP stream.
15045  *   - 'mp' is either an untagged or a special priority-tagged packet.
15046  *   - Any VLAN tag that was in the MAC header has been stripped.
15047  *
15048  * If the IP header in packet is not 32-bit aligned, every message in the
15049  * chain will be aligned before further operations. This is required on SPARC
15050  * platform.
15051  */
15052 /* ARGSUSED */
15053 void
15054 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
15055     struct mac_header_info_s *mhip)
15056 {
15057 	ipaddr_t		dst = NULL;
15058 	ipaddr_t		prev_dst;
15059 	ire_t			*ire = NULL;
15060 	ipha_t			*ipha;
15061 	uint_t			pkt_len;
15062 	ssize_t			len;
15063 	uint_t			opt_len;
15064 	int			ll_multicast;
15065 	int			cgtp_flt_pkt;
15066 	queue_t			*q = ill->ill_rq;
15067 	squeue_t		*curr_sqp = NULL;
15068 	mblk_t 			*head = NULL;
15069 	mblk_t			*tail = NULL;
15070 	mblk_t			*first_mp;
15071 	mblk_t 			*mp;
15072 	mblk_t			*dmp;
15073 	int			cnt = 0;
15074 	ip_stack_t		*ipst = ill->ill_ipst;
15075 
15076 	ASSERT(mp_chain != NULL);
15077 	ASSERT(ill != NULL);
15078 
15079 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15080 
15081 #define	rptr	((uchar_t *)ipha)
15082 
15083 	while (mp_chain != NULL) {
15084 		first_mp = mp = mp_chain;
15085 		mp_chain = mp_chain->b_next;
15086 		mp->b_next = NULL;
15087 		ll_multicast = 0;
15088 
15089 		/*
15090 		 * We do ire caching from one iteration to
15091 		 * another. In the event the packet chain contains
15092 		 * all packets from the same dst, this caching saves
15093 		 * an ire_cache_lookup for each of the succeeding
15094 		 * packets in a packet chain.
15095 		 */
15096 		prev_dst = dst;
15097 
15098 		/*
15099 		 * Check and align the IP header.
15100 		 */
15101 		if (DB_TYPE(mp) == M_DATA) {
15102 			dmp = mp;
15103 		} else if (DB_TYPE(mp) == M_PROTO &&
15104 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15105 			dmp = mp->b_cont;
15106 		} else {
15107 			dmp = NULL;
15108 		}
15109 		if (dmp != NULL) {
15110 			/*
15111 			 * IP header ptr not aligned?
15112 			 * OR IP header not complete in first mblk
15113 			 */
15114 			if (!OK_32PTR(dmp->b_rptr) ||
15115 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15116 				if (!ip_check_and_align_header(q, dmp, ipst))
15117 					continue;
15118 			}
15119 		}
15120 
15121 		/*
15122 		 * ip_input fast path
15123 		 */
15124 
15125 		/* mblk type is not M_DATA */
15126 		if (DB_TYPE(mp) != M_DATA) {
15127 			if (ip_rput_process_notdata(q, &first_mp, ill,
15128 			    &ll_multicast, &mp))
15129 				continue;
15130 		}
15131 
15132 		/* Make sure its an M_DATA and that its aligned */
15133 		ASSERT(DB_TYPE(mp) == M_DATA);
15134 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15135 
15136 		ipha = (ipha_t *)mp->b_rptr;
15137 		len = mp->b_wptr - rptr;
15138 		pkt_len = ntohs(ipha->ipha_length);
15139 
15140 		/*
15141 		 * We must count all incoming packets, even if they end
15142 		 * up being dropped later on.
15143 		 */
15144 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15145 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15146 
15147 		/* multiple mblk or too short */
15148 		len -= pkt_len;
15149 		if (len != 0) {
15150 			/*
15151 			 * Make sure we have data length consistent
15152 			 * with the IP header.
15153 			 */
15154 			if (mp->b_cont == NULL) {
15155 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15156 					BUMP_MIB(ill->ill_ip_mib,
15157 					    ipIfStatsInHdrErrors);
15158 					ip2dbg(("ip_input: drop pkt\n"));
15159 					freemsg(mp);
15160 					continue;
15161 				}
15162 				mp->b_wptr = rptr + pkt_len;
15163 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15164 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15165 					BUMP_MIB(ill->ill_ip_mib,
15166 					    ipIfStatsInHdrErrors);
15167 					ip2dbg(("ip_input: drop pkt\n"));
15168 					freemsg(mp);
15169 					continue;
15170 				}
15171 				(void) adjmsg(mp, -len);
15172 				IP_STAT(ipst, ip_multimblk3);
15173 			}
15174 		}
15175 
15176 		/* Obtain the dst of the current packet */
15177 		dst = ipha->ipha_dst;
15178 
15179 		if (IP_LOOPBACK_ADDR(dst) ||
15180 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15181 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15182 			cmn_err(CE_CONT, "dst %X src %X\n",
15183 			    dst, ipha->ipha_src);
15184 			freemsg(mp);
15185 			continue;
15186 		}
15187 
15188 		/*
15189 		 * The event for packets being received from a 'physical'
15190 		 * interface is placed after validation of the source and/or
15191 		 * destination address as being local so that packets can be
15192 		 * redirected to loopback addresses using ipnat.
15193 		 */
15194 		DTRACE_PROBE4(ip4__physical__in__start,
15195 		    ill_t *, ill, ill_t *, NULL,
15196 		    ipha_t *, ipha, mblk_t *, first_mp);
15197 
15198 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15199 		    ipst->ips_ipv4firewall_physical_in,
15200 		    ill, NULL, ipha, first_mp, mp, ipst);
15201 
15202 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15203 
15204 		if (first_mp == NULL) {
15205 			continue;
15206 		}
15207 		dst = ipha->ipha_dst;
15208 
15209 		/*
15210 		 * Attach any necessary label information to
15211 		 * this packet
15212 		 */
15213 		if (is_system_labeled() &&
15214 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15215 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15216 			freemsg(mp);
15217 			continue;
15218 		}
15219 
15220 		/*
15221 		 * Reuse the cached ire only if the ipha_dst of the previous
15222 		 * packet is the same as the current packet AND it is not
15223 		 * INADDR_ANY.
15224 		 */
15225 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15226 		    (ire != NULL)) {
15227 			ire_refrele(ire);
15228 			ire = NULL;
15229 		}
15230 		opt_len = ipha->ipha_version_and_hdr_length -
15231 		    IP_SIMPLE_HDR_VERSION;
15232 
15233 		/*
15234 		 * Check to see if we can take the fastpath.
15235 		 * That is possible if the following conditions are met
15236 		 *	o Tsol disabled
15237 		 *	o CGTP disabled
15238 		 *	o ipp_action_count is 0
15239 		 *	o Mobile IP not running
15240 		 *	o no options in the packet
15241 		 *	o not a RSVP packet
15242 		 * 	o not a multicast packet
15243 		 */
15244 		if (!is_system_labeled() &&
15245 		    !ip_cgtp_filter && ipp_action_count == 0 &&
15246 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
15247 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15248 		    !ll_multicast && !CLASSD(dst)) {
15249 			if (ire == NULL)
15250 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15251 				    ipst);
15252 
15253 			/* incoming packet is for forwarding */
15254 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15255 				ire = ip_fast_forward(ire, dst, ill, mp);
15256 				continue;
15257 			}
15258 			/* incoming packet is for local consumption */
15259 			if (ire->ire_type & IRE_LOCAL)
15260 				goto local;
15261 		}
15262 
15263 		/*
15264 		 * Disable ire caching for anything more complex
15265 		 * than the simple fast path case we checked for above.
15266 		 */
15267 		if (ire != NULL) {
15268 			ire_refrele(ire);
15269 			ire = NULL;
15270 		}
15271 
15272 		/* Full-blown slow path */
15273 		if (opt_len != 0) {
15274 			if (len != 0)
15275 				IP_STAT(ipst, ip_multimblk4);
15276 			else
15277 				IP_STAT(ipst, ip_ipoptions);
15278 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15279 			    &dst, ipst))
15280 				continue;
15281 		}
15282 
15283 		/*
15284 		 * Invoke the CGTP (multirouting) filtering module to process
15285 		 * the incoming packet. Packets identified as duplicates
15286 		 * must be discarded. Filtering is active only if the
15287 		 * the ip_cgtp_filter ndd variable is non-zero.
15288 		 *
15289 		 * Only applies to the shared stack since the filter_ops
15290 		 * do not carry an ip_stack_t or zoneid.
15291 		 */
15292 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15293 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
15294 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
15295 			cgtp_flt_pkt =
15296 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15297 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15298 				freemsg(first_mp);
15299 				continue;
15300 			}
15301 		}
15302 
15303 		/*
15304 		 * If rsvpd is running, let RSVP daemon handle its processing
15305 		 * and forwarding of RSVP multicast/unicast packets.
15306 		 * If rsvpd is not running but mrouted is running, RSVP
15307 		 * multicast packets are forwarded as multicast traffic
15308 		 * and RSVP unicast packets are forwarded by unicast router.
15309 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15310 		 * packets are not forwarded, but the unicast packets are
15311 		 * forwarded like unicast traffic.
15312 		 */
15313 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15314 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15315 		    NULL) {
15316 			/* RSVP packet and rsvpd running. Treat as ours */
15317 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15318 			/*
15319 			 * This assumes that we deliver to all streams for
15320 			 * multicast and broadcast packets.
15321 			 * We have to force ll_multicast to 1 to handle the
15322 			 * M_DATA messages passed in from ip_mroute_decap.
15323 			 */
15324 			dst = INADDR_BROADCAST;
15325 			ll_multicast = 1;
15326 		} else if (CLASSD(dst)) {
15327 			/* packet is multicast */
15328 			mp->b_next = NULL;
15329 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15330 			    &ll_multicast, &dst))
15331 				continue;
15332 		}
15333 
15334 
15335 		/*
15336 		 * Check if the packet is coming from the Mobile IP
15337 		 * forward tunnel interface
15338 		 */
15339 		if (ill->ill_srcif_refcnt > 0) {
15340 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15341 			    NULL, ill, MATCH_IRE_TYPE);
15342 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15343 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15344 
15345 				/* We need to resolve the link layer info */
15346 				ire_refrele(ire);
15347 				ire = NULL;
15348 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15349 				    ll_multicast, dst);
15350 				continue;
15351 			}
15352 		}
15353 
15354 		if (ire == NULL) {
15355 			ire = ire_cache_lookup(dst, ALL_ZONES,
15356 			    MBLK_GETLABEL(mp), ipst);
15357 		}
15358 
15359 		/*
15360 		 * If mipagent is running and reverse tunnel is created as per
15361 		 * mobile node request, then any packet coming through the
15362 		 * incoming interface from the mobile-node, should be reverse
15363 		 * tunneled to it's home agent except those that are destined
15364 		 * to foreign agent only.
15365 		 * This needs source address based ire lookup. The routing
15366 		 * entries for source address based lookup are only created by
15367 		 * mipagent program only when a reverse tunnel is created.
15368 		 * Reference : RFC2002, RFC2344
15369 		 */
15370 		if (ill->ill_mrtun_refcnt > 0) {
15371 			ipaddr_t	srcaddr;
15372 			ire_t		*tmp_ire;
15373 
15374 			tmp_ire = ire;	/* Save, we might need it later */
15375 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15376 			    ire->ire_type != IRE_BROADCAST)) {
15377 				srcaddr = ipha->ipha_src;
15378 				ire = ire_mrtun_lookup(srcaddr, ill);
15379 				if (ire != NULL) {
15380 					/*
15381 					 * Should not be getting iphada packet
15382 					 * here. we should only get those for
15383 					 * IRE_LOCAL traffic, excluded above.
15384 					 * Fail-safe (drop packet) in the event
15385 					 * hardware is misbehaving.
15386 					 */
15387 					if (first_mp != mp) {
15388 						/* IPsec KSTATS: beancount me */
15389 						freemsg(first_mp);
15390 					} else {
15391 						/*
15392 						 * This packet must be forwarded
15393 						 * to Reverse Tunnel
15394 						 */
15395 						ip_mrtun_forward(ire, ill, mp);
15396 					}
15397 					ire_refrele(ire);
15398 					ire = NULL;
15399 					if (tmp_ire != NULL) {
15400 						ire_refrele(tmp_ire);
15401 						tmp_ire = NULL;
15402 					}
15403 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15404 					    "ip_input_end: q %p (%S)",
15405 					    q, "uninit");
15406 					continue;
15407 				}
15408 			}
15409 			/*
15410 			 * If this packet is from a non-mobilenode  or a
15411 			 * mobile-node which does not request reverse
15412 			 * tunnel service
15413 			 */
15414 			ire = tmp_ire;
15415 		}
15416 
15417 
15418 		/*
15419 		 * If we reach here that means the incoming packet satisfies
15420 		 * one of the following conditions:
15421 		 *   - packet is from a mobile node which does not request
15422 		 *	reverse tunnel
15423 		 *   - packet is from a non-mobile node, which is the most
15424 		 *	common case
15425 		 *   - packet is from a reverse tunnel enabled mobile node
15426 		 *	and destined to foreign agent only
15427 		 */
15428 
15429 		if (ire == NULL) {
15430 			/*
15431 			 * No IRE for this destination, so it can't be for us.
15432 			 * Unless we are forwarding, drop the packet.
15433 			 * We have to let source routed packets through
15434 			 * since we don't yet know if they are 'ping -l'
15435 			 * packets i.e. if they will go out over the
15436 			 * same interface as they came in on.
15437 			 */
15438 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15439 			if (ire == NULL)
15440 				continue;
15441 		}
15442 
15443 		/*
15444 		 * Broadcast IRE may indicate either broadcast or
15445 		 * multicast packet
15446 		 */
15447 		if (ire->ire_type == IRE_BROADCAST) {
15448 			/*
15449 			 * Skip broadcast checks if packet is UDP multicast;
15450 			 * we'd rather not enter ip_rput_process_broadcast()
15451 			 * unless the packet is broadcast for real, since
15452 			 * that routine is a no-op for multicast.
15453 			 */
15454 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15455 			    !CLASSD(ipha->ipha_dst)) {
15456 				ire = ip_rput_process_broadcast(&q, mp,
15457 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15458 				    ll_multicast);
15459 				if (ire == NULL)
15460 					continue;
15461 			}
15462 		} else if (ire->ire_stq != NULL) {
15463 			/* fowarding? */
15464 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15465 			    ll_multicast);
15466 			/* ip_rput_process_forward consumed the packet */
15467 			continue;
15468 		}
15469 
15470 local:
15471 		/*
15472 		 * If the queue in the ire is different to the ingress queue
15473 		 * then we need to check to see if we can accept the packet.
15474 		 * Note that for multicast packets and broadcast packets sent
15475 		 * to a broadcast address which is shared between multiple
15476 		 * interfaces we should not do this since we just got a random
15477 		 * broadcast ire.
15478 		 */
15479 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15480 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15481 			    ill)) == NULL) {
15482 				/* Drop packet */
15483 				BUMP_MIB(ill->ill_ip_mib,
15484 				    ipIfStatsForwProhibits);
15485 				freemsg(mp);
15486 				continue;
15487 			}
15488 			if (ire->ire_rfq != NULL)
15489 				q = ire->ire_rfq;
15490 		}
15491 
15492 		switch (ipha->ipha_protocol) {
15493 		case IPPROTO_TCP:
15494 			ASSERT(first_mp == mp);
15495 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15496 				mp, 0, q, ip_ring)) != NULL) {
15497 				if (curr_sqp == NULL) {
15498 					curr_sqp = GET_SQUEUE(mp);
15499 					ASSERT(cnt == 0);
15500 					cnt++;
15501 					head = tail = mp;
15502 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15503 					ASSERT(tail != NULL);
15504 					cnt++;
15505 					tail->b_next = mp;
15506 					tail = mp;
15507 				} else {
15508 					/*
15509 					 * A different squeue. Send the
15510 					 * chain for the previous squeue on
15511 					 * its way. This shouldn't happen
15512 					 * often unless interrupt binding
15513 					 * changes.
15514 					 */
15515 					IP_STAT(ipst, ip_input_multi_squeue);
15516 					squeue_enter_chain(curr_sqp, head,
15517 					    tail, cnt, SQTAG_IP_INPUT);
15518 					curr_sqp = GET_SQUEUE(mp);
15519 					head = mp;
15520 					tail = mp;
15521 					cnt = 1;
15522 				}
15523 			}
15524 			continue;
15525 		case IPPROTO_UDP:
15526 			ASSERT(first_mp == mp);
15527 			ip_udp_input(q, mp, ipha, ire, ill);
15528 			continue;
15529 		case IPPROTO_SCTP:
15530 			ASSERT(first_mp == mp);
15531 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15532 			    q, dst);
15533 			/* ire has been released by ip_sctp_input */
15534 			ire = NULL;
15535 			continue;
15536 		default:
15537 			ip_proto_input(q, first_mp, ipha, ire, ill);
15538 			continue;
15539 		}
15540 	}
15541 
15542 	if (ire != NULL)
15543 		ire_refrele(ire);
15544 
15545 	if (head != NULL)
15546 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15547 
15548 	/*
15549 	 * This code is there just to make netperf/ttcp look good.
15550 	 *
15551 	 * Its possible that after being in polling mode (and having cleared
15552 	 * the backlog), squeues have turned the interrupt frequency higher
15553 	 * to improve latency at the expense of more CPU utilization (less
15554 	 * packets per interrupts or more number of interrupts). Workloads
15555 	 * like ttcp/netperf do manage to tickle polling once in a while
15556 	 * but for the remaining time, stay in higher interrupt mode since
15557 	 * their packet arrival rate is pretty uniform and this shows up
15558 	 * as higher CPU utilization. Since people care about CPU utilization
15559 	 * while running netperf/ttcp, turn the interrupt frequency back to
15560 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15561 	 */
15562 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15563 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15564 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15565 			ip_ring->rr_blank(ip_ring->rr_handle,
15566 			    ip_ring->rr_normal_blank_time,
15567 			    ip_ring->rr_normal_pkt_cnt);
15568 		}
15569 		}
15570 
15571 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15572 	    "ip_input_end: q %p (%S)", q, "end");
15573 #undef  rptr
15574 }
15575 
15576 static void
15577 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15578     t_uscalar_t err)
15579 {
15580 	if (dl_err == DL_SYSERR) {
15581 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15582 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15583 		    ill->ill_name, dlpi_prim_str(prim), err);
15584 		return;
15585 	}
15586 
15587 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15588 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15589 	    dlpi_err_str(dl_err));
15590 }
15591 
15592 /*
15593  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15594  * than DL_UNITDATA_IND messages. If we need to process this message
15595  * exclusively, we call qwriter_ip, in which case we also need to call
15596  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15597  */
15598 void
15599 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15600 {
15601 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15602 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15603 	ill_t		*ill;
15604 
15605 	ip1dbg(("ip_rput_dlpi"));
15606 	ill = (ill_t *)q->q_ptr;
15607 	switch (dloa->dl_primitive) {
15608 	case DL_ERROR_ACK:
15609 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15610 		    "%s (0x%x), unix %u\n", ill->ill_name,
15611 		    dlpi_prim_str(dlea->dl_error_primitive),
15612 		    dlea->dl_error_primitive,
15613 		    dlpi_err_str(dlea->dl_errno),
15614 		    dlea->dl_errno,
15615 		    dlea->dl_unix_errno));
15616 		switch (dlea->dl_error_primitive) {
15617 		case DL_UNBIND_REQ:
15618 			mutex_enter(&ill->ill_lock);
15619 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15620 			cv_signal(&ill->ill_cv);
15621 			mutex_exit(&ill->ill_lock);
15622 			/* FALLTHRU */
15623 		case DL_NOTIFY_REQ:
15624 		case DL_ATTACH_REQ:
15625 		case DL_DETACH_REQ:
15626 		case DL_INFO_REQ:
15627 		case DL_BIND_REQ:
15628 		case DL_ENABMULTI_REQ:
15629 		case DL_PHYS_ADDR_REQ:
15630 		case DL_CAPABILITY_REQ:
15631 		case DL_CONTROL_REQ:
15632 			/*
15633 			 * Refhold the ill to match qwriter_ip which does a
15634 			 * refrele. Since this is on the ill stream we
15635 			 * unconditionally bump up the refcount without
15636 			 * checking for ILL_CAN_LOOKUP
15637 			 */
15638 			ill_refhold(ill);
15639 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15640 			    CUR_OP, B_FALSE);
15641 			return;
15642 		case DL_DISABMULTI_REQ:
15643 			freemsg(mp);	/* Don't want to pass this up */
15644 			return;
15645 		default:
15646 			break;
15647 		}
15648 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15649 		    dlea->dl_errno, dlea->dl_unix_errno);
15650 		freemsg(mp);
15651 		return;
15652 	case DL_INFO_ACK:
15653 	case DL_BIND_ACK:
15654 	case DL_PHYS_ADDR_ACK:
15655 	case DL_NOTIFY_ACK:
15656 	case DL_CAPABILITY_ACK:
15657 	case DL_CONTROL_ACK:
15658 		/*
15659 		 * Refhold the ill to match qwriter_ip which does a refrele
15660 		 * Since this is on the ill stream we unconditionally
15661 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15662 		 */
15663 		ill_refhold(ill);
15664 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15665 		    CUR_OP, B_FALSE);
15666 		return;
15667 	case DL_NOTIFY_IND:
15668 		ill_refhold(ill);
15669 		/*
15670 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15671 		 * relation to the current ioctl in progress (if any). Hence we
15672 		 * pass in NEW_OP in this case.
15673 		 */
15674 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15675 		    NEW_OP, B_FALSE);
15676 		return;
15677 	case DL_OK_ACK:
15678 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15679 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15680 		switch (dloa->dl_correct_primitive) {
15681 		case DL_UNBIND_REQ:
15682 			mutex_enter(&ill->ill_lock);
15683 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15684 			cv_signal(&ill->ill_cv);
15685 			mutex_exit(&ill->ill_lock);
15686 			/* FALLTHRU */
15687 		case DL_ATTACH_REQ:
15688 		case DL_DETACH_REQ:
15689 			/*
15690 			 * Refhold the ill to match qwriter_ip which does a
15691 			 * refrele. Since this is on the ill stream we
15692 			 * unconditionally bump up the refcount
15693 			 */
15694 			ill_refhold(ill);
15695 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15696 			    CUR_OP, B_FALSE);
15697 			return;
15698 		case DL_ENABMULTI_REQ:
15699 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15700 				ill->ill_dlpi_multicast_state = IDS_OK;
15701 			break;
15702 
15703 		}
15704 		break;
15705 	default:
15706 		break;
15707 	}
15708 	freemsg(mp);
15709 }
15710 
15711 /*
15712  * Handling of DLPI messages that require exclusive access to the ipsq.
15713  *
15714  * Need to do ill_pending_mp_release on ioctl completion, which could
15715  * happen here. (along with mi_copy_done)
15716  */
15717 /* ARGSUSED */
15718 static void
15719 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15720 {
15721 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15722 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15723 	int		err = 0;
15724 	ill_t		*ill;
15725 	ipif_t		*ipif = NULL;
15726 	mblk_t		*mp1 = NULL;
15727 	conn_t		*connp = NULL;
15728 	t_uscalar_t	paddrreq;
15729 	mblk_t		*mp_hw;
15730 	boolean_t	success;
15731 	boolean_t	ioctl_aborted = B_FALSE;
15732 	boolean_t	log = B_TRUE;
15733 	hook_nic_event_t	*info;
15734 	ip_stack_t		*ipst;
15735 
15736 	ip1dbg(("ip_rput_dlpi_writer .."));
15737 	ill = (ill_t *)q->q_ptr;
15738 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15739 
15740 	ASSERT(IAM_WRITER_ILL(ill));
15741 
15742 	ipst = ill->ill_ipst;
15743 
15744 	/*
15745 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15746 	 * both are null or non-null. However we can assert that only
15747 	 * after grabbing the ipsq_lock. So we don't make any assertion
15748 	 * here and in other places in the code.
15749 	 */
15750 	ipif = ipsq->ipsq_pending_ipif;
15751 	/*
15752 	 * The current ioctl could have been aborted by the user and a new
15753 	 * ioctl to bring up another ill could have started. We could still
15754 	 * get a response from the driver later.
15755 	 */
15756 	if (ipif != NULL && ipif->ipif_ill != ill)
15757 		ioctl_aborted = B_TRUE;
15758 
15759 	switch (dloa->dl_primitive) {
15760 	case DL_ERROR_ACK:
15761 		switch (dlea->dl_error_primitive) {
15762 		case DL_UNBIND_REQ:
15763 		case DL_ATTACH_REQ:
15764 		case DL_DETACH_REQ:
15765 		case DL_INFO_REQ:
15766 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15767 			break;
15768 		case DL_NOTIFY_REQ:
15769 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15770 			log = B_FALSE;
15771 			break;
15772 		case DL_PHYS_ADDR_REQ:
15773 			/*
15774 			 * For IPv6 only, there are two additional
15775 			 * phys_addr_req's sent to the driver to get the
15776 			 * IPv6 token and lla. This allows IP to acquire
15777 			 * the hardware address format for a given interface
15778 			 * without having built in knowledge of the hardware
15779 			 * address. ill_phys_addr_pend keeps track of the last
15780 			 * DL_PAR sent so we know which response we are
15781 			 * dealing with. ill_dlpi_done will update
15782 			 * ill_phys_addr_pend when it sends the next req.
15783 			 * We don't complete the IOCTL until all three DL_PARs
15784 			 * have been attempted, so set *_len to 0 and break.
15785 			 */
15786 			paddrreq = ill->ill_phys_addr_pend;
15787 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15788 			if (paddrreq == DL_IPV6_TOKEN) {
15789 				ill->ill_token_length = 0;
15790 				log = B_FALSE;
15791 				break;
15792 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15793 				ill->ill_nd_lla_len = 0;
15794 				log = B_FALSE;
15795 				break;
15796 			}
15797 			/*
15798 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15799 			 * We presumably have an IOCTL hanging out waiting
15800 			 * for completion. Find it and complete the IOCTL
15801 			 * with the error noted.
15802 			 * However, ill_dl_phys was called on an ill queue
15803 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15804 			 * set. But the ioctl is known to be pending on ill_wq.
15805 			 */
15806 			if (!ill->ill_ifname_pending)
15807 				break;
15808 			ill->ill_ifname_pending = 0;
15809 			if (!ioctl_aborted)
15810 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15811 			if (mp1 != NULL) {
15812 				/*
15813 				 * This operation (SIOCSLIFNAME) must have
15814 				 * happened on the ill. Assert there is no conn
15815 				 */
15816 				ASSERT(connp == NULL);
15817 				q = ill->ill_wq;
15818 			}
15819 			break;
15820 		case DL_BIND_REQ:
15821 			ill_dlpi_done(ill, DL_BIND_REQ);
15822 			if (ill->ill_ifname_pending)
15823 				break;
15824 			/*
15825 			 * Something went wrong with the bind.  We presumably
15826 			 * have an IOCTL hanging out waiting for completion.
15827 			 * Find it, take down the interface that was coming
15828 			 * up, and complete the IOCTL with the error noted.
15829 			 */
15830 			if (!ioctl_aborted)
15831 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15832 			if (mp1 != NULL) {
15833 				/*
15834 				 * This operation (SIOCSLIFFLAGS) must have
15835 				 * happened from a conn.
15836 				 */
15837 				ASSERT(connp != NULL);
15838 				q = CONNP_TO_WQ(connp);
15839 				if (ill->ill_move_in_progress) {
15840 					ILL_CLEAR_MOVE(ill);
15841 				}
15842 				(void) ipif_down(ipif, NULL, NULL);
15843 				/* error is set below the switch */
15844 			}
15845 			break;
15846 		case DL_ENABMULTI_REQ:
15847 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15848 
15849 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15850 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15851 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15852 				ipif_t *ipif;
15853 
15854 				log = B_FALSE;
15855 				printf("ip: joining multicasts failed (%d)"
15856 				    " on %s - will use link layer "
15857 				    "broadcasts for multicast\n",
15858 				    dlea->dl_errno, ill->ill_name);
15859 
15860 				/*
15861 				 * Set up the multicast mapping alone.
15862 				 * writer, so ok to access ill->ill_ipif
15863 				 * without any lock.
15864 				 */
15865 				ipif = ill->ill_ipif;
15866 				mutex_enter(&ill->ill_phyint->phyint_lock);
15867 				ill->ill_phyint->phyint_flags |=
15868 				    PHYI_MULTI_BCAST;
15869 				mutex_exit(&ill->ill_phyint->phyint_lock);
15870 
15871 				if (!ill->ill_isv6) {
15872 					(void) ipif_arp_setup_multicast(ipif,
15873 					    NULL);
15874 				} else {
15875 					(void) ipif_ndp_setup_multicast(ipif,
15876 					    NULL);
15877 				}
15878 			}
15879 			freemsg(mp);	/* Don't want to pass this up */
15880 			return;
15881 		case DL_CAPABILITY_REQ:
15882 		case DL_CONTROL_REQ:
15883 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15884 			    "DL_CAPABILITY/CONTROL REQ\n"));
15885 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15886 			ill->ill_dlpi_capab_state = IDS_FAILED;
15887 			freemsg(mp);
15888 			return;
15889 		}
15890 		/*
15891 		 * Note the error for IOCTL completion (mp1 is set when
15892 		 * ready to complete ioctl). If ill_ifname_pending_err is
15893 		 * set, an error occured during plumbing (ill_ifname_pending),
15894 		 * so we want to report that error.
15895 		 *
15896 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15897 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15898 		 * expected to get errack'd if the driver doesn't support
15899 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15900 		 * if these error conditions are encountered.
15901 		 */
15902 		if (mp1 != NULL) {
15903 			if (ill->ill_ifname_pending_err != 0)  {
15904 				err = ill->ill_ifname_pending_err;
15905 				ill->ill_ifname_pending_err = 0;
15906 			} else {
15907 				err = dlea->dl_unix_errno ?
15908 				    dlea->dl_unix_errno : ENXIO;
15909 			}
15910 		/*
15911 		 * If we're plumbing an interface and an error hasn't already
15912 		 * been saved, set ill_ifname_pending_err to the error passed
15913 		 * up. Ignore the error if log is B_FALSE (see comment above).
15914 		 */
15915 		} else if (log && ill->ill_ifname_pending &&
15916 		    ill->ill_ifname_pending_err == 0) {
15917 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15918 			dlea->dl_unix_errno : ENXIO;
15919 		}
15920 
15921 		if (log)
15922 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15923 			    dlea->dl_errno, dlea->dl_unix_errno);
15924 		break;
15925 	case DL_CAPABILITY_ACK: {
15926 		boolean_t reneg_flag = B_FALSE;
15927 		/* Call a routine to handle this one. */
15928 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15929 		/*
15930 		 * Check if the ACK is due to renegotiation case since we
15931 		 * will need to send a new CAPABILITY_REQ later.
15932 		 */
15933 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15934 			/* This is the ack for a renogiation case */
15935 			reneg_flag = B_TRUE;
15936 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15937 		}
15938 		ill_capability_ack(ill, mp);
15939 		if (reneg_flag)
15940 			ill_capability_probe(ill);
15941 		break;
15942 	}
15943 	case DL_CONTROL_ACK:
15944 		/* We treat all of these as "fire and forget" */
15945 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15946 		break;
15947 	case DL_INFO_ACK:
15948 		/* Call a routine to handle this one. */
15949 		ill_dlpi_done(ill, DL_INFO_REQ);
15950 		ip_ll_subnet_defaults(ill, mp);
15951 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15952 		return;
15953 	case DL_BIND_ACK:
15954 		/*
15955 		 * We should have an IOCTL waiting on this unless
15956 		 * sent by ill_dl_phys, in which case just return
15957 		 */
15958 		ill_dlpi_done(ill, DL_BIND_REQ);
15959 		if (ill->ill_ifname_pending)
15960 			break;
15961 
15962 		if (!ioctl_aborted)
15963 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15964 		if (mp1 == NULL)
15965 			break;
15966 		/*
15967 		 * Because mp1 was added by ill_dl_up(), and it always
15968 		 * passes a valid connp, connp must be valid here.
15969 		 */
15970 		ASSERT(connp != NULL);
15971 		q = CONNP_TO_WQ(connp);
15972 
15973 		/*
15974 		 * We are exclusive. So nothing can change even after
15975 		 * we get the pending mp. If need be we can put it back
15976 		 * and restart, as in calling ipif_arp_up()  below.
15977 		 */
15978 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15979 
15980 		mutex_enter(&ill->ill_lock);
15981 
15982 		ill->ill_dl_up = 1;
15983 
15984 		if ((info = ill->ill_nic_event_info) != NULL) {
15985 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15986 			    "attached for %s\n", info->hne_event,
15987 			    ill->ill_name));
15988 			if (info->hne_data != NULL)
15989 				kmem_free(info->hne_data, info->hne_datalen);
15990 			kmem_free(info, sizeof (hook_nic_event_t));
15991 		}
15992 
15993 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15994 		if (info != NULL) {
15995 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15996 			info->hne_lif = 0;
15997 			info->hne_event = NE_UP;
15998 			info->hne_data = NULL;
15999 			info->hne_datalen = 0;
16000 			info->hne_family = ill->ill_isv6 ?
16001 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
16002 		} else
16003 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
16004 			    "event information for %s (ENOMEM)\n",
16005 			    ill->ill_name));
16006 
16007 		ill->ill_nic_event_info = info;
16008 
16009 		mutex_exit(&ill->ill_lock);
16010 
16011 		/*
16012 		 * Now bring up the resolver; when that is complete, we'll
16013 		 * create IREs.  Note that we intentionally mirror what
16014 		 * ipif_up() would have done, because we got here by way of
16015 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16016 		 */
16017 		if (ill->ill_isv6) {
16018 			/*
16019 			 * v6 interfaces.
16020 			 * Unlike ARP which has to do another bind
16021 			 * and attach, once we get here we are
16022 			 * done with NDP. Except in the case of
16023 			 * ILLF_XRESOLV, in which case we send an
16024 			 * AR_INTERFACE_UP to the external resolver.
16025 			 * If all goes well, the ioctl will complete
16026 			 * in ip_rput(). If there's an error, we
16027 			 * complete it here.
16028 			 */
16029 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
16030 			if (err == 0) {
16031 				if (ill->ill_flags & ILLF_XRESOLV) {
16032 					mutex_enter(&connp->conn_lock);
16033 					mutex_enter(&ill->ill_lock);
16034 					success = ipsq_pending_mp_add(
16035 					    connp, ipif, q, mp1, 0);
16036 					mutex_exit(&ill->ill_lock);
16037 					mutex_exit(&connp->conn_lock);
16038 					if (success) {
16039 						err = ipif_resolver_up(ipif,
16040 						    Res_act_initial);
16041 						if (err == EINPROGRESS) {
16042 							freemsg(mp);
16043 							return;
16044 						}
16045 						ASSERT(err != 0);
16046 						mp1 = ipsq_pending_mp_get(ipsq,
16047 						    &connp);
16048 						ASSERT(mp1 != NULL);
16049 					} else {
16050 						/* conn has started closing */
16051 						err = EINTR;
16052 					}
16053 				} else { /* Non XRESOLV interface */
16054 					(void) ipif_resolver_up(ipif,
16055 					    Res_act_initial);
16056 					err = ipif_up_done_v6(ipif);
16057 				}
16058 			}
16059 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16060 			/*
16061 			 * ARP and other v4 external resolvers.
16062 			 * Leave the pending mblk intact so that
16063 			 * the ioctl completes in ip_rput().
16064 			 */
16065 			mutex_enter(&connp->conn_lock);
16066 			mutex_enter(&ill->ill_lock);
16067 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16068 			mutex_exit(&ill->ill_lock);
16069 			mutex_exit(&connp->conn_lock);
16070 			if (success) {
16071 				err = ipif_resolver_up(ipif, Res_act_initial);
16072 				if (err == EINPROGRESS) {
16073 					freemsg(mp);
16074 					return;
16075 				}
16076 				ASSERT(err != 0);
16077 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16078 			} else {
16079 				/* The conn has started closing */
16080 				err = EINTR;
16081 			}
16082 		} else {
16083 			/*
16084 			 * This one is complete. Reply to pending ioctl.
16085 			 */
16086 			(void) ipif_resolver_up(ipif, Res_act_initial);
16087 			err = ipif_up_done(ipif);
16088 		}
16089 
16090 		if ((err == 0) && (ill->ill_up_ipifs)) {
16091 			err = ill_up_ipifs(ill, q, mp1);
16092 			if (err == EINPROGRESS) {
16093 				freemsg(mp);
16094 				return;
16095 			}
16096 		}
16097 
16098 		if (ill->ill_up_ipifs) {
16099 			ill_group_cleanup(ill);
16100 		}
16101 
16102 		break;
16103 	case DL_NOTIFY_IND: {
16104 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16105 		ire_t *ire;
16106 		boolean_t need_ire_walk_v4 = B_FALSE;
16107 		boolean_t need_ire_walk_v6 = B_FALSE;
16108 
16109 		switch (notify->dl_notification) {
16110 		case DL_NOTE_PHYS_ADDR:
16111 			err = ill_set_phys_addr(ill, mp);
16112 			break;
16113 
16114 		case DL_NOTE_FASTPATH_FLUSH:
16115 			ill_fastpath_flush(ill);
16116 			break;
16117 
16118 		case DL_NOTE_SDU_SIZE:
16119 			/*
16120 			 * Change the MTU size of the interface, of all
16121 			 * attached ipif's, and of all relevant ire's.  The
16122 			 * new value's a uint32_t at notify->dl_data.
16123 			 * Mtu change Vs. new ire creation - protocol below.
16124 			 *
16125 			 * a Mark the ipif as IPIF_CHANGING.
16126 			 * b Set the new mtu in the ipif.
16127 			 * c Change the ire_max_frag on all affected ires
16128 			 * d Unmark the IPIF_CHANGING
16129 			 *
16130 			 * To see how the protocol works, assume an interface
16131 			 * route is also being added simultaneously by
16132 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16133 			 * the ire. If the ire is created before step a,
16134 			 * it will be cleaned up by step c. If the ire is
16135 			 * created after step d, it will see the new value of
16136 			 * ipif_mtu. Any attempt to create the ire between
16137 			 * steps a to d will fail because of the IPIF_CHANGING
16138 			 * flag. Note that ire_create() is passed a pointer to
16139 			 * the ipif_mtu, and not the value. During ire_add
16140 			 * under the bucket lock, the ire_max_frag of the
16141 			 * new ire being created is set from the ipif/ire from
16142 			 * which it is being derived.
16143 			 */
16144 			mutex_enter(&ill->ill_lock);
16145 			ill->ill_max_frag = (uint_t)notify->dl_data;
16146 
16147 			/*
16148 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16149 			 * leave it alone
16150 			 */
16151 			if (ill->ill_mtu_userspecified) {
16152 				mutex_exit(&ill->ill_lock);
16153 				break;
16154 			}
16155 			ill->ill_max_mtu = ill->ill_max_frag;
16156 			if (ill->ill_isv6) {
16157 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16158 					ill->ill_max_mtu = IPV6_MIN_MTU;
16159 			} else {
16160 				if (ill->ill_max_mtu < IP_MIN_MTU)
16161 					ill->ill_max_mtu = IP_MIN_MTU;
16162 			}
16163 			for (ipif = ill->ill_ipif; ipif != NULL;
16164 			    ipif = ipif->ipif_next) {
16165 				/*
16166 				 * Don't override the mtu if the user
16167 				 * has explicitly set it.
16168 				 */
16169 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16170 					continue;
16171 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16172 				if (ipif->ipif_isv6)
16173 					ire = ipif_to_ire_v6(ipif);
16174 				else
16175 					ire = ipif_to_ire(ipif);
16176 				if (ire != NULL) {
16177 					ire->ire_max_frag = ipif->ipif_mtu;
16178 					ire_refrele(ire);
16179 				}
16180 				if (ipif->ipif_flags & IPIF_UP) {
16181 					if (ill->ill_isv6)
16182 						need_ire_walk_v6 = B_TRUE;
16183 					else
16184 						need_ire_walk_v4 = B_TRUE;
16185 				}
16186 			}
16187 			mutex_exit(&ill->ill_lock);
16188 			if (need_ire_walk_v4)
16189 				ire_walk_v4(ill_mtu_change, (char *)ill,
16190 				    ALL_ZONES, ipst);
16191 			if (need_ire_walk_v6)
16192 				ire_walk_v6(ill_mtu_change, (char *)ill,
16193 				    ALL_ZONES, ipst);
16194 			break;
16195 		case DL_NOTE_LINK_UP:
16196 		case DL_NOTE_LINK_DOWN: {
16197 			/*
16198 			 * We are writer. ill / phyint / ipsq assocs stable.
16199 			 * The RUNNING flag reflects the state of the link.
16200 			 */
16201 			phyint_t *phyint = ill->ill_phyint;
16202 			uint64_t new_phyint_flags;
16203 			boolean_t changed = B_FALSE;
16204 			boolean_t went_up;
16205 
16206 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16207 			mutex_enter(&phyint->phyint_lock);
16208 			new_phyint_flags = went_up ?
16209 			    phyint->phyint_flags | PHYI_RUNNING :
16210 			    phyint->phyint_flags & ~PHYI_RUNNING;
16211 			if (new_phyint_flags != phyint->phyint_flags) {
16212 				phyint->phyint_flags = new_phyint_flags;
16213 				changed = B_TRUE;
16214 			}
16215 			mutex_exit(&phyint->phyint_lock);
16216 			/*
16217 			 * ill_restart_dad handles the DAD restart and routing
16218 			 * socket notification logic.
16219 			 */
16220 			if (changed) {
16221 				ill_restart_dad(phyint->phyint_illv4, went_up);
16222 				ill_restart_dad(phyint->phyint_illv6, went_up);
16223 			}
16224 			break;
16225 		}
16226 		case DL_NOTE_PROMISC_ON_PHYS:
16227 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16228 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16229 			mutex_enter(&ill->ill_lock);
16230 			ill->ill_promisc_on_phys = B_TRUE;
16231 			mutex_exit(&ill->ill_lock);
16232 			break;
16233 		case DL_NOTE_PROMISC_OFF_PHYS:
16234 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16235 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16236 			mutex_enter(&ill->ill_lock);
16237 			ill->ill_promisc_on_phys = B_FALSE;
16238 			mutex_exit(&ill->ill_lock);
16239 			break;
16240 		case DL_NOTE_CAPAB_RENEG:
16241 			/*
16242 			 * Something changed on the driver side.
16243 			 * It wants us to renegotiate the capabilities
16244 			 * on this ill. The most likely cause is the
16245 			 * aggregation interface under us where a
16246 			 * port got added or went away.
16247 			 *
16248 			 * We reset the capabilities and set the
16249 			 * state to IDS_RENG so that when the ack
16250 			 * comes back, we can start the
16251 			 * renegotiation process.
16252 			 */
16253 			ill_capability_reset(ill);
16254 			ill->ill_dlpi_capab_state = IDS_RENEG;
16255 			break;
16256 		default:
16257 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16258 			    "type 0x%x for DL_NOTIFY_IND\n",
16259 			    notify->dl_notification));
16260 			break;
16261 		}
16262 
16263 		/*
16264 		 * As this is an asynchronous operation, we
16265 		 * should not call ill_dlpi_done
16266 		 */
16267 		break;
16268 	}
16269 	case DL_NOTIFY_ACK: {
16270 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16271 
16272 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16273 			ill->ill_note_link = 1;
16274 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16275 		break;
16276 	}
16277 	case DL_PHYS_ADDR_ACK: {
16278 		/*
16279 		 * As part of plumbing the interface via SIOCSLIFNAME,
16280 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16281 		 * whose answers we receive here.  As each answer is received,
16282 		 * we call ill_dlpi_done() to dispatch the next request as
16283 		 * we're processing the current one.  Once all answers have
16284 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16285 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16286 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16287 		 * available, but we know the ioctl is pending on ill_wq.)
16288 		 */
16289 		uint_t paddrlen, paddroff;
16290 
16291 		paddrreq = ill->ill_phys_addr_pend;
16292 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16293 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16294 
16295 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16296 		if (paddrreq == DL_IPV6_TOKEN) {
16297 			/*
16298 			 * bcopy to low-order bits of ill_token
16299 			 *
16300 			 * XXX Temporary hack - currently, all known tokens
16301 			 * are 64 bits, so I'll cheat for the moment.
16302 			 */
16303 			bcopy(mp->b_rptr + paddroff,
16304 			    &ill->ill_token.s6_addr32[2], paddrlen);
16305 			ill->ill_token_length = paddrlen;
16306 			break;
16307 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16308 			ASSERT(ill->ill_nd_lla_mp == NULL);
16309 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16310 			mp = NULL;
16311 			break;
16312 		}
16313 
16314 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16315 		ASSERT(ill->ill_phys_addr_mp == NULL);
16316 		if (!ill->ill_ifname_pending)
16317 			break;
16318 		ill->ill_ifname_pending = 0;
16319 		if (!ioctl_aborted)
16320 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16321 		if (mp1 != NULL) {
16322 			ASSERT(connp == NULL);
16323 			q = ill->ill_wq;
16324 		}
16325 		/*
16326 		 * If any error acks received during the plumbing sequence,
16327 		 * ill_ifname_pending_err will be set. Break out and send up
16328 		 * the error to the pending ioctl.
16329 		 */
16330 		if (ill->ill_ifname_pending_err != 0) {
16331 			err = ill->ill_ifname_pending_err;
16332 			ill->ill_ifname_pending_err = 0;
16333 			break;
16334 		}
16335 
16336 		ill->ill_phys_addr_mp = mp;
16337 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16338 		mp = NULL;
16339 
16340 		/*
16341 		 * If paddrlen is zero, the DLPI provider doesn't support
16342 		 * physical addresses.  The other two tests were historical
16343 		 * workarounds for bugs in our former PPP implementation, but
16344 		 * now other things have grown dependencies on them -- e.g.,
16345 		 * the tun module specifies a dl_addr_length of zero in its
16346 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16347 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16348 		 * but only after careful testing ensures that all dependent
16349 		 * broken DLPI providers have been fixed.
16350 		 */
16351 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16352 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16353 			ill->ill_phys_addr = NULL;
16354 		} else if (paddrlen != ill->ill_phys_addr_length) {
16355 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16356 			    paddrlen, ill->ill_phys_addr_length));
16357 			err = EINVAL;
16358 			break;
16359 		}
16360 
16361 		if (ill->ill_nd_lla_mp == NULL) {
16362 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16363 				err = ENOMEM;
16364 				break;
16365 			}
16366 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16367 		}
16368 
16369 		/*
16370 		 * Set the interface token.  If the zeroth interface address
16371 		 * is unspecified, then set it to the link local address.
16372 		 */
16373 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16374 			(void) ill_setdefaulttoken(ill);
16375 
16376 		ASSERT(ill->ill_ipif->ipif_id == 0);
16377 		if (ipif != NULL &&
16378 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16379 			(void) ipif_setlinklocal(ipif);
16380 		}
16381 		break;
16382 	}
16383 	case DL_OK_ACK:
16384 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16385 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16386 		    dloa->dl_correct_primitive));
16387 		switch (dloa->dl_correct_primitive) {
16388 		case DL_UNBIND_REQ:
16389 		case DL_ATTACH_REQ:
16390 		case DL_DETACH_REQ:
16391 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16392 			break;
16393 		}
16394 		break;
16395 	default:
16396 		break;
16397 	}
16398 
16399 	freemsg(mp);
16400 	if (mp1 != NULL) {
16401 		/*
16402 		 * The operation must complete without EINPROGRESS
16403 		 * since ipsq_pending_mp_get() has removed the mblk
16404 		 * from ipsq_pending_mp.  Otherwise, the operation
16405 		 * will be stuck forever in the ipsq.
16406 		 */
16407 		ASSERT(err != EINPROGRESS);
16408 
16409 		switch (ipsq->ipsq_current_ioctl) {
16410 		case 0:
16411 			ipsq_current_finish(ipsq);
16412 			break;
16413 
16414 		case SIOCLIFADDIF:
16415 		case SIOCSLIFNAME:
16416 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16417 			break;
16418 
16419 		default:
16420 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16421 			break;
16422 		}
16423 	}
16424 }
16425 
16426 /*
16427  * ip_rput_other is called by ip_rput to handle messages modifying the global
16428  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16429  */
16430 /* ARGSUSED */
16431 void
16432 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16433 {
16434 	ill_t		*ill;
16435 	struct iocblk	*iocp;
16436 	mblk_t		*mp1;
16437 	conn_t		*connp = NULL;
16438 
16439 	ip1dbg(("ip_rput_other "));
16440 	ill = (ill_t *)q->q_ptr;
16441 	/*
16442 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16443 	 * in which case ipsq is NULL.
16444 	 */
16445 	if (ipsq != NULL) {
16446 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16447 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16448 	}
16449 
16450 	switch (mp->b_datap->db_type) {
16451 	case M_ERROR:
16452 	case M_HANGUP:
16453 		/*
16454 		 * The device has a problem.  We force the ILL down.  It can
16455 		 * be brought up again manually using SIOCSIFFLAGS (via
16456 		 * ifconfig or equivalent).
16457 		 */
16458 		ASSERT(ipsq != NULL);
16459 		if (mp->b_rptr < mp->b_wptr)
16460 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16461 		if (ill->ill_error == 0)
16462 			ill->ill_error = ENXIO;
16463 		if (!ill_down_start(q, mp))
16464 			return;
16465 		ipif_all_down_tail(ipsq, q, mp, NULL);
16466 		break;
16467 	case M_IOCACK:
16468 		iocp = (struct iocblk *)mp->b_rptr;
16469 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16470 		switch (iocp->ioc_cmd) {
16471 		case SIOCSTUNPARAM:
16472 		case OSIOCSTUNPARAM:
16473 			ASSERT(ipsq != NULL);
16474 			/*
16475 			 * Finish socket ioctl passed through to tun.
16476 			 * We should have an IOCTL waiting on this.
16477 			 */
16478 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16479 			if (ill->ill_isv6) {
16480 				struct iftun_req *ta;
16481 
16482 				/*
16483 				 * if a source or destination is
16484 				 * being set, try and set the link
16485 				 * local address for the tunnel
16486 				 */
16487 				ta = (struct iftun_req *)mp->b_cont->
16488 				    b_cont->b_rptr;
16489 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16490 					ipif_set_tun_llink(ill, ta);
16491 				}
16492 
16493 			}
16494 			if (mp1 != NULL) {
16495 				/*
16496 				 * Now copy back the b_next/b_prev used by
16497 				 * mi code for the mi_copy* functions.
16498 				 * See ip_sioctl_tunparam() for the reason.
16499 				 * Also protect against missing b_cont.
16500 				 */
16501 				if (mp->b_cont != NULL) {
16502 					mp->b_cont->b_next =
16503 					    mp1->b_cont->b_next;
16504 					mp->b_cont->b_prev =
16505 					    mp1->b_cont->b_prev;
16506 				}
16507 				inet_freemsg(mp1);
16508 				ASSERT(connp != NULL);
16509 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16510 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16511 			} else {
16512 				ASSERT(connp == NULL);
16513 				putnext(q, mp);
16514 			}
16515 			break;
16516 		case SIOCGTUNPARAM:
16517 		case OSIOCGTUNPARAM:
16518 			/*
16519 			 * This is really M_IOCDATA from the tunnel driver.
16520 			 * convert back and complete the ioctl.
16521 			 * We should have an IOCTL waiting on this.
16522 			 */
16523 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16524 			if (mp1) {
16525 				/*
16526 				 * Now copy back the b_next/b_prev used by
16527 				 * mi code for the mi_copy* functions.
16528 				 * See ip_sioctl_tunparam() for the reason.
16529 				 * Also protect against missing b_cont.
16530 				 */
16531 				if (mp->b_cont != NULL) {
16532 					mp->b_cont->b_next =
16533 					    mp1->b_cont->b_next;
16534 					mp->b_cont->b_prev =
16535 					    mp1->b_cont->b_prev;
16536 				}
16537 				inet_freemsg(mp1);
16538 				if (iocp->ioc_error == 0)
16539 					mp->b_datap->db_type = M_IOCDATA;
16540 				ASSERT(connp != NULL);
16541 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16542 				    iocp->ioc_error, COPYOUT, NULL);
16543 			} else {
16544 				ASSERT(connp == NULL);
16545 				putnext(q, mp);
16546 			}
16547 			break;
16548 		default:
16549 			break;
16550 		}
16551 		break;
16552 	case M_IOCNAK:
16553 		iocp = (struct iocblk *)mp->b_rptr;
16554 
16555 		switch (iocp->ioc_cmd) {
16556 		int mode;
16557 
16558 		case DL_IOC_HDR_INFO:
16559 			/*
16560 			 * If this was the first attempt turn of the
16561 			 * fastpath probing.
16562 			 */
16563 			mutex_enter(&ill->ill_lock);
16564 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16565 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16566 				mutex_exit(&ill->ill_lock);
16567 				ill_fastpath_nack(ill);
16568 				ip1dbg(("ip_rput: DLPI fastpath off on "
16569 				    "interface %s\n",
16570 				    ill->ill_name));
16571 			} else {
16572 				mutex_exit(&ill->ill_lock);
16573 			}
16574 			freemsg(mp);
16575 			break;
16576 		case SIOCSTUNPARAM:
16577 		case OSIOCSTUNPARAM:
16578 			ASSERT(ipsq != NULL);
16579 			/*
16580 			 * Finish socket ioctl passed through to tun
16581 			 * We should have an IOCTL waiting on this.
16582 			 */
16583 			/* FALLTHRU */
16584 		case SIOCGTUNPARAM:
16585 		case OSIOCGTUNPARAM:
16586 			/*
16587 			 * This is really M_IOCDATA from the tunnel driver.
16588 			 * convert back and complete the ioctl.
16589 			 * We should have an IOCTL waiting on this.
16590 			 */
16591 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16592 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16593 				mp1 = ill_pending_mp_get(ill, &connp,
16594 				    iocp->ioc_id);
16595 				mode = COPYOUT;
16596 				ipsq = NULL;
16597 			} else {
16598 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16599 				mode = NO_COPYOUT;
16600 			}
16601 			if (mp1 != NULL) {
16602 				/*
16603 				 * Now copy back the b_next/b_prev used by
16604 				 * mi code for the mi_copy* functions.
16605 				 * See ip_sioctl_tunparam() for the reason.
16606 				 * Also protect against missing b_cont.
16607 				 */
16608 				if (mp->b_cont != NULL) {
16609 					mp->b_cont->b_next =
16610 					    mp1->b_cont->b_next;
16611 					mp->b_cont->b_prev =
16612 					    mp1->b_cont->b_prev;
16613 				}
16614 				inet_freemsg(mp1);
16615 				if (iocp->ioc_error == 0)
16616 					iocp->ioc_error = EINVAL;
16617 				ASSERT(connp != NULL);
16618 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16619 				    iocp->ioc_error, mode, ipsq);
16620 			} else {
16621 				ASSERT(connp == NULL);
16622 				putnext(q, mp);
16623 			}
16624 			break;
16625 		default:
16626 			break;
16627 		}
16628 	default:
16629 		break;
16630 	}
16631 }
16632 
16633 /*
16634  * NOTE : This function does not ire_refrele the ire argument passed in.
16635  *
16636  * IPQoS notes
16637  * IP policy is invoked twice for a forwarded packet, once on the read side
16638  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16639  * enabled. An additional parameter, in_ill, has been added for this purpose.
16640  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16641  * because ip_mroute drops this information.
16642  *
16643  */
16644 void
16645 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16646 {
16647 	uint32_t	pkt_len;
16648 	queue_t	*q;
16649 	uint32_t	sum;
16650 #define	rptr	((uchar_t *)ipha)
16651 	uint32_t	max_frag;
16652 	uint32_t	ill_index;
16653 	ill_t		*out_ill;
16654 	mib2_ipIfStatsEntry_t *mibptr;
16655 	ip_stack_t	*ipst = in_ill->ill_ipst;
16656 
16657 	/* Get the ill_index of the incoming ILL */
16658 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16659 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16660 
16661 	/* Initiate Read side IPPF processing */
16662 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16663 		ip_process(IPP_FWD_IN, &mp, ill_index);
16664 		if (mp == NULL) {
16665 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16666 			    "during IPPF processing\n"));
16667 			return;
16668 		}
16669 	}
16670 
16671 	pkt_len = ntohs(ipha->ipha_length);
16672 
16673 	/* Adjust the checksum to reflect the ttl decrement. */
16674 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16675 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16676 
16677 	if (ipha->ipha_ttl-- <= 1) {
16678 		if (ip_csum_hdr(ipha)) {
16679 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16680 			goto drop_pkt;
16681 		}
16682 		/*
16683 		 * Note: ire_stq this will be NULL for multicast
16684 		 * datagrams using the long path through arp (the IRE
16685 		 * is not an IRE_CACHE). This should not cause
16686 		 * problems since we don't generate ICMP errors for
16687 		 * multicast packets.
16688 		 */
16689 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16690 		q = ire->ire_stq;
16691 		if (q != NULL) {
16692 			/* Sent by forwarding path, and router is global zone */
16693 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16694 			    GLOBAL_ZONEID, ipst);
16695 		} else
16696 			freemsg(mp);
16697 		return;
16698 	}
16699 
16700 	/*
16701 	 * Don't forward if the interface is down
16702 	 */
16703 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16704 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16705 		ip2dbg(("ip_rput_forward:interface is down\n"));
16706 		goto drop_pkt;
16707 	}
16708 
16709 	/* Get the ill_index of the outgoing ILL */
16710 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16711 
16712 	out_ill = ire->ire_ipif->ipif_ill;
16713 
16714 	DTRACE_PROBE4(ip4__forwarding__start,
16715 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16716 
16717 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16718 	    ipst->ips_ipv4firewall_forwarding,
16719 	    in_ill, out_ill, ipha, mp, mp, ipst);
16720 
16721 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16722 
16723 	if (mp == NULL)
16724 		return;
16725 	pkt_len = ntohs(ipha->ipha_length);
16726 
16727 	if (is_system_labeled()) {
16728 		mblk_t *mp1;
16729 
16730 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16731 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16732 			goto drop_pkt;
16733 		}
16734 		/* Size may have changed */
16735 		mp = mp1;
16736 		ipha = (ipha_t *)mp->b_rptr;
16737 		pkt_len = ntohs(ipha->ipha_length);
16738 	}
16739 
16740 	/* Check if there are options to update */
16741 	if (!IS_SIMPLE_IPH(ipha)) {
16742 		if (ip_csum_hdr(ipha)) {
16743 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16744 			goto drop_pkt;
16745 		}
16746 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16747 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16748 			return;
16749 		}
16750 
16751 		ipha->ipha_hdr_checksum = 0;
16752 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16753 	}
16754 	max_frag = ire->ire_max_frag;
16755 	if (pkt_len > max_frag) {
16756 		/*
16757 		 * It needs fragging on its way out.  We haven't
16758 		 * verified the header checksum yet.  Since we
16759 		 * are going to put a surely good checksum in the
16760 		 * outgoing header, we have to make sure that it
16761 		 * was good coming in.
16762 		 */
16763 		if (ip_csum_hdr(ipha)) {
16764 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16765 			goto drop_pkt;
16766 		}
16767 		/* Initiate Write side IPPF processing */
16768 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16769 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16770 			if (mp == NULL) {
16771 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16772 				    " during IPPF processing\n"));
16773 				return;
16774 			}
16775 		}
16776 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16777 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16778 		return;
16779 	}
16780 
16781 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16782 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16783 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16784 	    ipst->ips_ipv4firewall_physical_out,
16785 	    NULL, out_ill, ipha, mp, mp, ipst);
16786 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16787 	if (mp == NULL)
16788 		return;
16789 
16790 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16791 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16792 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16793 	/* ip_xmit_v4 always consumes the packet */
16794 	return;
16795 
16796 drop_pkt:;
16797 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16798 	freemsg(mp);
16799 #undef	rptr
16800 }
16801 
16802 void
16803 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16804 {
16805 	ire_t	*ire;
16806 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16807 
16808 	ASSERT(!ipif->ipif_isv6);
16809 	/*
16810 	 * Find an IRE which matches the destination and the outgoing
16811 	 * queue in the cache table. All we need is an IRE_CACHE which
16812 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16813 	 * then it is enough to have some IRE_CACHE in the group.
16814 	 */
16815 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16816 		dst = ipif->ipif_pp_dst_addr;
16817 
16818 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16819 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16820 	if (ire == NULL) {
16821 		/*
16822 		 * Mark this packet to make it be delivered to
16823 		 * ip_rput_forward after the new ire has been
16824 		 * created.
16825 		 */
16826 		mp->b_prev = NULL;
16827 		mp->b_next = mp;
16828 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16829 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16830 	} else {
16831 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16832 		IRE_REFRELE(ire);
16833 	}
16834 }
16835 
16836 /* Update any source route, record route or timestamp options */
16837 static int
16838 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16839 {
16840 	ipoptp_t	opts;
16841 	uchar_t		*opt;
16842 	uint8_t		optval;
16843 	uint8_t		optlen;
16844 	ipaddr_t	dst;
16845 	uint32_t	ts;
16846 	ire_t		*dst_ire = NULL;
16847 	ire_t		*tmp_ire = NULL;
16848 	timestruc_t	now;
16849 
16850 	ip2dbg(("ip_rput_forward_options\n"));
16851 	dst = ipha->ipha_dst;
16852 	for (optval = ipoptp_first(&opts, ipha);
16853 	    optval != IPOPT_EOL;
16854 	    optval = ipoptp_next(&opts)) {
16855 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16856 		opt = opts.ipoptp_cur;
16857 		optlen = opts.ipoptp_len;
16858 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16859 		    optval, opts.ipoptp_len));
16860 		switch (optval) {
16861 			uint32_t off;
16862 		case IPOPT_SSRR:
16863 		case IPOPT_LSRR:
16864 			/* Check if adminstratively disabled */
16865 			if (!ipst->ips_ip_forward_src_routed) {
16866 				if (ire->ire_stq != NULL) {
16867 					/*
16868 					 * Sent by forwarding path, and router
16869 					 * is global zone
16870 					 */
16871 					icmp_unreachable(ire->ire_stq, mp,
16872 					    ICMP_SOURCE_ROUTE_FAILED,
16873 					    GLOBAL_ZONEID, ipst);
16874 				} else {
16875 					ip0dbg(("ip_rput_forward_options: "
16876 					    "unable to send unreach\n"));
16877 					freemsg(mp);
16878 				}
16879 				return (-1);
16880 			}
16881 
16882 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16883 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16884 			if (dst_ire == NULL) {
16885 				/*
16886 				 * Must be partial since ip_rput_options
16887 				 * checked for strict.
16888 				 */
16889 				break;
16890 			}
16891 			off = opt[IPOPT_OFFSET];
16892 			off--;
16893 		redo_srr:
16894 			if (optlen < IP_ADDR_LEN ||
16895 			    off > optlen - IP_ADDR_LEN) {
16896 				/* End of source route */
16897 				ip1dbg((
16898 				    "ip_rput_forward_options: end of SR\n"));
16899 				ire_refrele(dst_ire);
16900 				break;
16901 			}
16902 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16903 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16904 			    IP_ADDR_LEN);
16905 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16906 			    ntohl(dst)));
16907 
16908 			/*
16909 			 * Check if our address is present more than
16910 			 * once as consecutive hops in source route.
16911 			 */
16912 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16913 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16914 			if (tmp_ire != NULL) {
16915 				ire_refrele(tmp_ire);
16916 				off += IP_ADDR_LEN;
16917 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16918 				goto redo_srr;
16919 			}
16920 			ipha->ipha_dst = dst;
16921 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16922 			ire_refrele(dst_ire);
16923 			break;
16924 		case IPOPT_RR:
16925 			off = opt[IPOPT_OFFSET];
16926 			off--;
16927 			if (optlen < IP_ADDR_LEN ||
16928 			    off > optlen - IP_ADDR_LEN) {
16929 				/* No more room - ignore */
16930 				ip1dbg((
16931 				    "ip_rput_forward_options: end of RR\n"));
16932 				break;
16933 			}
16934 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16935 			    IP_ADDR_LEN);
16936 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16937 			break;
16938 		case IPOPT_TS:
16939 			/* Insert timestamp if there is room */
16940 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16941 			case IPOPT_TS_TSONLY:
16942 				off = IPOPT_TS_TIMELEN;
16943 				break;
16944 			case IPOPT_TS_PRESPEC:
16945 			case IPOPT_TS_PRESPEC_RFC791:
16946 				/* Verify that the address matched */
16947 				off = opt[IPOPT_OFFSET] - 1;
16948 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16949 				dst_ire = ire_ctable_lookup(dst, 0,
16950 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16951 				    MATCH_IRE_TYPE, ipst);
16952 				if (dst_ire == NULL) {
16953 					/* Not for us */
16954 					break;
16955 				}
16956 				ire_refrele(dst_ire);
16957 				/* FALLTHRU */
16958 			case IPOPT_TS_TSANDADDR:
16959 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16960 				break;
16961 			default:
16962 				/*
16963 				 * ip_*put_options should have already
16964 				 * dropped this packet.
16965 				 */
16966 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16967 				    "unknown IT - bug in ip_rput_options?\n");
16968 				return (0);	/* Keep "lint" happy */
16969 			}
16970 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16971 				/* Increase overflow counter */
16972 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16973 				opt[IPOPT_POS_OV_FLG] =
16974 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16975 				    (off << 4));
16976 				break;
16977 			}
16978 			off = opt[IPOPT_OFFSET] - 1;
16979 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16980 			case IPOPT_TS_PRESPEC:
16981 			case IPOPT_TS_PRESPEC_RFC791:
16982 			case IPOPT_TS_TSANDADDR:
16983 				bcopy(&ire->ire_src_addr,
16984 				    (char *)opt + off, IP_ADDR_LEN);
16985 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16986 				/* FALLTHRU */
16987 			case IPOPT_TS_TSONLY:
16988 				off = opt[IPOPT_OFFSET] - 1;
16989 				/* Compute # of milliseconds since midnight */
16990 				gethrestime(&now);
16991 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16992 				    now.tv_nsec / (NANOSEC / MILLISEC);
16993 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16994 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16995 				break;
16996 			}
16997 			break;
16998 		}
16999 	}
17000 	return (0);
17001 }
17002 
17003 /*
17004  * This is called after processing at least one of AH/ESP headers.
17005  *
17006  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17007  * the actual, physical interface on which the packet was received,
17008  * but, when ip_strict_dst_multihoming is set to 1, could be the
17009  * interface which had the ipha_dst configured when the packet went
17010  * through ip_rput. The ill_index corresponding to the recv_ill
17011  * is saved in ipsec_in_rill_index
17012  */
17013 void
17014 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17015 {
17016 	mblk_t *mp;
17017 	ipaddr_t dst;
17018 	in6_addr_t *v6dstp;
17019 	ipha_t *ipha;
17020 	ip6_t *ip6h;
17021 	ipsec_in_t *ii;
17022 	boolean_t ill_need_rele = B_FALSE;
17023 	boolean_t rill_need_rele = B_FALSE;
17024 	boolean_t ire_need_rele = B_FALSE;
17025 	netstack_t	*ns;
17026 	ip_stack_t	*ipst;
17027 
17028 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17029 	ASSERT(ii->ipsec_in_ill_index != 0);
17030 	ns = ii->ipsec_in_ns;
17031 	ASSERT(ii->ipsec_in_ns != NULL);
17032 	ipst = ns->netstack_ip;
17033 
17034 	mp = ipsec_mp->b_cont;
17035 	ASSERT(mp != NULL);
17036 
17037 
17038 	if (ill == NULL) {
17039 		ASSERT(recv_ill == NULL);
17040 		/*
17041 		 * We need to get the original queue on which ip_rput_local
17042 		 * or ip_rput_data_v6 was called.
17043 		 */
17044 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17045 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17046 		ill_need_rele = B_TRUE;
17047 
17048 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17049 			recv_ill = ill_lookup_on_ifindex(
17050 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17051 			    NULL, NULL, NULL, NULL, ipst);
17052 			rill_need_rele = B_TRUE;
17053 		} else {
17054 			recv_ill = ill;
17055 		}
17056 
17057 		if ((ill == NULL) || (recv_ill == NULL)) {
17058 			ip0dbg(("ip_fanout_proto_again: interface "
17059 			    "disappeared\n"));
17060 			if (ill != NULL)
17061 				ill_refrele(ill);
17062 			if (recv_ill != NULL)
17063 				ill_refrele(recv_ill);
17064 			freemsg(ipsec_mp);
17065 			return;
17066 		}
17067 	}
17068 
17069 	ASSERT(ill != NULL && recv_ill != NULL);
17070 
17071 	if (mp->b_datap->db_type == M_CTL) {
17072 		/*
17073 		 * AH/ESP is returning the ICMP message after
17074 		 * removing their headers. Fanout again till
17075 		 * it gets to the right protocol.
17076 		 */
17077 		if (ii->ipsec_in_v4) {
17078 			icmph_t *icmph;
17079 			int iph_hdr_length;
17080 			int hdr_length;
17081 
17082 			ipha = (ipha_t *)mp->b_rptr;
17083 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17084 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17085 			ipha = (ipha_t *)&icmph[1];
17086 			hdr_length = IPH_HDR_LENGTH(ipha);
17087 			/*
17088 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17089 			 * Reset the type to M_DATA.
17090 			 */
17091 			mp->b_datap->db_type = M_DATA;
17092 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17093 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17094 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17095 		} else {
17096 			icmp6_t *icmp6;
17097 			int hdr_length;
17098 
17099 			ip6h = (ip6_t *)mp->b_rptr;
17100 			/* Don't call hdr_length_v6() unless you have to. */
17101 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17102 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17103 			else
17104 				hdr_length = IPV6_HDR_LEN;
17105 
17106 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17107 			/*
17108 			 * icmp_inbound_error_fanout_v6 may need to do
17109 			 * pullupmsg.  Reset the type to M_DATA.
17110 			 */
17111 			mp->b_datap->db_type = M_DATA;
17112 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17113 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17114 		}
17115 		if (ill_need_rele)
17116 			ill_refrele(ill);
17117 		if (rill_need_rele)
17118 			ill_refrele(recv_ill);
17119 		return;
17120 	}
17121 
17122 	if (ii->ipsec_in_v4) {
17123 		ipha = (ipha_t *)mp->b_rptr;
17124 		dst = ipha->ipha_dst;
17125 		if (CLASSD(dst)) {
17126 			/*
17127 			 * Multicast has to be delivered to all streams.
17128 			 */
17129 			dst = INADDR_BROADCAST;
17130 		}
17131 
17132 		if (ire == NULL) {
17133 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17134 			    MBLK_GETLABEL(mp), ipst);
17135 			if (ire == NULL) {
17136 				if (ill_need_rele)
17137 					ill_refrele(ill);
17138 				if (rill_need_rele)
17139 					ill_refrele(recv_ill);
17140 				ip1dbg(("ip_fanout_proto_again: "
17141 				    "IRE not found"));
17142 				freemsg(ipsec_mp);
17143 				return;
17144 			}
17145 			ire_need_rele = B_TRUE;
17146 		}
17147 
17148 		switch (ipha->ipha_protocol) {
17149 			case IPPROTO_UDP:
17150 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17151 				    recv_ill);
17152 				if (ire_need_rele)
17153 					ire_refrele(ire);
17154 				break;
17155 			case IPPROTO_TCP:
17156 				if (!ire_need_rele)
17157 					IRE_REFHOLD(ire);
17158 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17159 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17160 				IRE_REFRELE(ire);
17161 				if (mp != NULL)
17162 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17163 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17164 				break;
17165 			case IPPROTO_SCTP:
17166 				if (!ire_need_rele)
17167 					IRE_REFHOLD(ire);
17168 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17169 				    ipsec_mp, 0, ill->ill_rq, dst);
17170 				break;
17171 			default:
17172 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17173 				    recv_ill);
17174 				if (ire_need_rele)
17175 					ire_refrele(ire);
17176 				break;
17177 		}
17178 	} else {
17179 		uint32_t rput_flags = 0;
17180 
17181 		ip6h = (ip6_t *)mp->b_rptr;
17182 		v6dstp = &ip6h->ip6_dst;
17183 		/*
17184 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17185 		 * address.
17186 		 *
17187 		 * Currently, we don't store that state in the IPSEC_IN
17188 		 * message, and we may need to.
17189 		 */
17190 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17191 		    IP6_IN_LLMCAST : 0);
17192 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17193 		    NULL, NULL);
17194 	}
17195 	if (ill_need_rele)
17196 		ill_refrele(ill);
17197 	if (rill_need_rele)
17198 		ill_refrele(recv_ill);
17199 }
17200 
17201 /*
17202  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17203  * returns 'true' if there are still fragments left on the queue, in
17204  * which case we restart the timer.
17205  */
17206 void
17207 ill_frag_timer(void *arg)
17208 {
17209 	ill_t	*ill = (ill_t *)arg;
17210 	boolean_t frag_pending;
17211 	ip_stack_t	*ipst = ill->ill_ipst;
17212 
17213 	mutex_enter(&ill->ill_lock);
17214 	ASSERT(!ill->ill_fragtimer_executing);
17215 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17216 		ill->ill_frag_timer_id = 0;
17217 		mutex_exit(&ill->ill_lock);
17218 		return;
17219 	}
17220 	ill->ill_fragtimer_executing = 1;
17221 	mutex_exit(&ill->ill_lock);
17222 
17223 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17224 
17225 	/*
17226 	 * Restart the timer, if we have fragments pending or if someone
17227 	 * wanted us to be scheduled again.
17228 	 */
17229 	mutex_enter(&ill->ill_lock);
17230 	ill->ill_fragtimer_executing = 0;
17231 	ill->ill_frag_timer_id = 0;
17232 	if (frag_pending || ill->ill_fragtimer_needrestart)
17233 		ill_frag_timer_start(ill);
17234 	mutex_exit(&ill->ill_lock);
17235 }
17236 
17237 void
17238 ill_frag_timer_start(ill_t *ill)
17239 {
17240 	ip_stack_t	*ipst = ill->ill_ipst;
17241 
17242 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17243 
17244 	/* If the ill is closing or opening don't proceed */
17245 	if (ill->ill_state_flags & ILL_CONDEMNED)
17246 		return;
17247 
17248 	if (ill->ill_fragtimer_executing) {
17249 		/*
17250 		 * ill_frag_timer is currently executing. Just record the
17251 		 * the fact that we want the timer to be restarted.
17252 		 * ill_frag_timer will post a timeout before it returns,
17253 		 * ensuring it will be called again.
17254 		 */
17255 		ill->ill_fragtimer_needrestart = 1;
17256 		return;
17257 	}
17258 
17259 	if (ill->ill_frag_timer_id == 0) {
17260 		/*
17261 		 * The timer is neither running nor is the timeout handler
17262 		 * executing. Post a timeout so that ill_frag_timer will be
17263 		 * called
17264 		 */
17265 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17266 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17267 		ill->ill_fragtimer_needrestart = 0;
17268 	}
17269 }
17270 
17271 /*
17272  * This routine is needed for loopback when forwarding multicasts.
17273  *
17274  * IPQoS Notes:
17275  * IPPF processing is done in fanout routines.
17276  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17277  * processing for IPSec packets is done when it comes back in clear.
17278  * NOTE : The callers of this function need to do the ire_refrele for the
17279  *	  ire that is being passed in.
17280  */
17281 void
17282 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17283     ill_t *recv_ill)
17284 {
17285 	ill_t	*ill = (ill_t *)q->q_ptr;
17286 	uint32_t	sum;
17287 	uint32_t	u1;
17288 	uint32_t	u2;
17289 	int		hdr_length;
17290 	boolean_t	mctl_present;
17291 	mblk_t		*first_mp = mp;
17292 	mblk_t		*hada_mp = NULL;
17293 	ipha_t		*inner_ipha;
17294 	ip_stack_t	*ipst;
17295 
17296 	ASSERT(recv_ill != NULL);
17297 	ipst = recv_ill->ill_ipst;
17298 
17299 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17300 	    "ip_rput_locl_start: q %p", q);
17301 
17302 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17303 	ASSERT(ill != NULL);
17304 
17305 
17306 #define	rptr	((uchar_t *)ipha)
17307 #define	iphs	((uint16_t *)ipha)
17308 
17309 	/*
17310 	 * no UDP or TCP packet should come here anymore.
17311 	 */
17312 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17313 	    (ipha->ipha_protocol != IPPROTO_UDP));
17314 
17315 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17316 	if (mctl_present &&
17317 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17318 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17319 
17320 		/*
17321 		 * It's an IPsec accelerated packet.
17322 		 * Keep a pointer to the data attributes around until
17323 		 * we allocate the ipsec_info_t.
17324 		 */
17325 		IPSECHW_DEBUG(IPSECHW_PKT,
17326 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17327 		hada_mp = first_mp;
17328 		hada_mp->b_cont = NULL;
17329 		/*
17330 		 * Since it is accelerated, it comes directly from
17331 		 * the ill and the data attributes is followed by
17332 		 * the packet data.
17333 		 */
17334 		ASSERT(mp->b_datap->db_type != M_CTL);
17335 		first_mp = mp;
17336 		mctl_present = B_FALSE;
17337 	}
17338 
17339 	/*
17340 	 * IF M_CTL is not present, then ipsec_in_is_secure
17341 	 * should return B_TRUE. There is a case where loopback
17342 	 * packets has an M_CTL in the front with all the
17343 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17344 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17345 	 * packets never comes here, it is safe to ASSERT the
17346 	 * following.
17347 	 */
17348 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17349 
17350 
17351 	/* u1 is # words of IP options */
17352 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17353 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17354 
17355 	if (u1) {
17356 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17357 			if (hada_mp != NULL)
17358 				freemsg(hada_mp);
17359 			return;
17360 		}
17361 	} else {
17362 		/* Check the IP header checksum.  */
17363 #define	uph	((uint16_t *)ipha)
17364 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17365 		    uph[6] + uph[7] + uph[8] + uph[9];
17366 #undef  uph
17367 		/* finish doing IP checksum */
17368 		sum = (sum & 0xFFFF) + (sum >> 16);
17369 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17370 		/*
17371 		 * Don't verify header checksum if this packet is coming
17372 		 * back from AH/ESP as we already did it.
17373 		 */
17374 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17375 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17376 			goto drop_pkt;
17377 		}
17378 	}
17379 
17380 	/*
17381 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17382 	 * might be called more than once for secure packets, count only
17383 	 * the first time.
17384 	 */
17385 	if (!mctl_present) {
17386 		UPDATE_IB_PKT_COUNT(ire);
17387 		ire->ire_last_used_time = lbolt;
17388 	}
17389 
17390 	/* Check for fragmentation offset. */
17391 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17392 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17393 	if (u1) {
17394 		/*
17395 		 * We re-assemble fragments before we do the AH/ESP
17396 		 * processing. Thus, M_CTL should not be present
17397 		 * while we are re-assembling.
17398 		 */
17399 		ASSERT(!mctl_present);
17400 		ASSERT(first_mp == mp);
17401 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17402 			return;
17403 		}
17404 		/*
17405 		 * Make sure that first_mp points back to mp as
17406 		 * the mp we came in with could have changed in
17407 		 * ip_rput_fragment().
17408 		 */
17409 		ipha = (ipha_t *)mp->b_rptr;
17410 		first_mp = mp;
17411 	}
17412 
17413 	/*
17414 	 * Clear hardware checksumming flag as it is currently only
17415 	 * used by TCP and UDP.
17416 	 */
17417 	DB_CKSUMFLAGS(mp) = 0;
17418 
17419 	/* Now we have a complete datagram, destined for this machine. */
17420 	u1 = IPH_HDR_LENGTH(ipha);
17421 	switch (ipha->ipha_protocol) {
17422 	case IPPROTO_ICMP: {
17423 		ire_t		*ire_zone;
17424 		ilm_t		*ilm;
17425 		mblk_t		*mp1;
17426 		zoneid_t	last_zoneid;
17427 
17428 		if (CLASSD(ipha->ipha_dst) &&
17429 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17430 			ASSERT(ire->ire_type == IRE_BROADCAST);
17431 			/*
17432 			 * In the multicast case, applications may have joined
17433 			 * the group from different zones, so we need to deliver
17434 			 * the packet to each of them. Loop through the
17435 			 * multicast memberships structures (ilm) on the receive
17436 			 * ill and send a copy of the packet up each matching
17437 			 * one. However, we don't do this for multicasts sent on
17438 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17439 			 * they must stay in the sender's zone.
17440 			 *
17441 			 * ilm_add_v6() ensures that ilms in the same zone are
17442 			 * contiguous in the ill_ilm list. We use this property
17443 			 * to avoid sending duplicates needed when two
17444 			 * applications in the same zone join the same group on
17445 			 * different logical interfaces: we ignore the ilm if
17446 			 * its zoneid is the same as the last matching one.
17447 			 * In addition, the sending of the packet for
17448 			 * ire_zoneid is delayed until all of the other ilms
17449 			 * have been exhausted.
17450 			 */
17451 			last_zoneid = -1;
17452 			ILM_WALKER_HOLD(recv_ill);
17453 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17454 			    ilm = ilm->ilm_next) {
17455 				if ((ilm->ilm_flags & ILM_DELETED) ||
17456 				    ipha->ipha_dst != ilm->ilm_addr ||
17457 				    ilm->ilm_zoneid == last_zoneid ||
17458 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17459 				    ilm->ilm_zoneid == ALL_ZONES ||
17460 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17461 					continue;
17462 				mp1 = ip_copymsg(first_mp);
17463 				if (mp1 == NULL)
17464 					continue;
17465 				icmp_inbound(q, mp1, B_TRUE, ill,
17466 				    0, sum, mctl_present, B_TRUE,
17467 				    recv_ill, ilm->ilm_zoneid);
17468 				last_zoneid = ilm->ilm_zoneid;
17469 			}
17470 			ILM_WALKER_RELE(recv_ill);
17471 		} else if (ire->ire_type == IRE_BROADCAST) {
17472 			/*
17473 			 * In the broadcast case, there may be many zones
17474 			 * which need a copy of the packet delivered to them.
17475 			 * There is one IRE_BROADCAST per broadcast address
17476 			 * and per zone; we walk those using a helper function.
17477 			 * In addition, the sending of the packet for ire is
17478 			 * delayed until all of the other ires have been
17479 			 * processed.
17480 			 */
17481 			IRB_REFHOLD(ire->ire_bucket);
17482 			ire_zone = NULL;
17483 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17484 			    ire)) != NULL) {
17485 				mp1 = ip_copymsg(first_mp);
17486 				if (mp1 == NULL)
17487 					continue;
17488 
17489 				UPDATE_IB_PKT_COUNT(ire_zone);
17490 				ire_zone->ire_last_used_time = lbolt;
17491 				icmp_inbound(q, mp1, B_TRUE, ill,
17492 				    0, sum, mctl_present, B_TRUE,
17493 				    recv_ill, ire_zone->ire_zoneid);
17494 			}
17495 			IRB_REFRELE(ire->ire_bucket);
17496 		}
17497 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17498 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17499 		    ire->ire_zoneid);
17500 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17501 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17502 		return;
17503 	}
17504 	case IPPROTO_IGMP:
17505 		/*
17506 		 * If we are not willing to accept IGMP packets in clear,
17507 		 * then check with global policy.
17508 		 */
17509 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17510 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17511 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17512 			if (first_mp == NULL)
17513 				return;
17514 		}
17515 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17516 			freemsg(first_mp);
17517 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17518 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17519 			return;
17520 		}
17521 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17522 			/* Bad packet - discarded by igmp_input */
17523 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17524 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17525 			if (mctl_present)
17526 				freeb(first_mp);
17527 			return;
17528 		}
17529 		/*
17530 		 * igmp_input() may have returned the pulled up message.
17531 		 * So first_mp and ipha need to be reinitialized.
17532 		 */
17533 		ipha = (ipha_t *)mp->b_rptr;
17534 		if (mctl_present)
17535 			first_mp->b_cont = mp;
17536 		else
17537 			first_mp = mp;
17538 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17539 		    connf_head != NULL) {
17540 			/* No user-level listener for IGMP packets */
17541 			goto drop_pkt;
17542 		}
17543 		/* deliver to local raw users */
17544 		break;
17545 	case IPPROTO_PIM:
17546 		/*
17547 		 * If we are not willing to accept PIM packets in clear,
17548 		 * then check with global policy.
17549 		 */
17550 		if (ipst->ips_pim_accept_clear_messages == 0) {
17551 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17552 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17553 			if (first_mp == NULL)
17554 				return;
17555 		}
17556 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17557 			freemsg(first_mp);
17558 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17559 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17560 			return;
17561 		}
17562 		if (pim_input(q, mp, ill) != 0) {
17563 			/* Bad packet - discarded by pim_input */
17564 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17565 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17566 			if (mctl_present)
17567 				freeb(first_mp);
17568 			return;
17569 		}
17570 
17571 		/*
17572 		 * pim_input() may have pulled up the message so ipha needs to
17573 		 * be reinitialized.
17574 		 */
17575 		ipha = (ipha_t *)mp->b_rptr;
17576 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17577 		    connf_head != NULL) {
17578 			/* No user-level listener for PIM packets */
17579 			goto drop_pkt;
17580 		}
17581 		/* deliver to local raw users */
17582 		break;
17583 	case IPPROTO_ENCAP:
17584 		/*
17585 		 * Handle self-encapsulated packets (IP-in-IP where
17586 		 * the inner addresses == the outer addresses).
17587 		 */
17588 		hdr_length = IPH_HDR_LENGTH(ipha);
17589 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17590 		    mp->b_wptr) {
17591 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17592 			    sizeof (ipha_t) - mp->b_rptr)) {
17593 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17594 				freemsg(first_mp);
17595 				return;
17596 			}
17597 			ipha = (ipha_t *)mp->b_rptr;
17598 		}
17599 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17600 		/*
17601 		 * Check the sanity of the inner IP header.
17602 		 */
17603 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17604 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17605 			freemsg(first_mp);
17606 			return;
17607 		}
17608 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17609 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17610 			freemsg(first_mp);
17611 			return;
17612 		}
17613 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17614 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17615 			ipsec_in_t *ii;
17616 
17617 			/*
17618 			 * Self-encapsulated tunnel packet. Remove
17619 			 * the outer IP header and fanout again.
17620 			 * We also need to make sure that the inner
17621 			 * header is pulled up until options.
17622 			 */
17623 			mp->b_rptr = (uchar_t *)inner_ipha;
17624 			ipha = inner_ipha;
17625 			hdr_length = IPH_HDR_LENGTH(ipha);
17626 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17627 				if (!pullupmsg(mp, (uchar_t *)ipha +
17628 				    + hdr_length - mp->b_rptr)) {
17629 					freemsg(first_mp);
17630 					return;
17631 				}
17632 				ipha = (ipha_t *)mp->b_rptr;
17633 			}
17634 			if (!mctl_present) {
17635 				ASSERT(first_mp == mp);
17636 				/*
17637 				 * This means that somebody is sending
17638 				 * Self-encapsualted packets without AH/ESP.
17639 				 * If AH/ESP was present, we would have already
17640 				 * allocated the first_mp.
17641 				 */
17642 				first_mp = ipsec_in_alloc(B_TRUE,
17643 				    ipst->ips_netstack);
17644 				if (first_mp == NULL) {
17645 					ip1dbg(("ip_proto_input: IPSEC_IN "
17646 					    "allocation failure.\n"));
17647 					BUMP_MIB(ill->ill_ip_mib,
17648 					    ipIfStatsInDiscards);
17649 					freemsg(mp);
17650 					return;
17651 				}
17652 				first_mp->b_cont = mp;
17653 			}
17654 			/*
17655 			 * We generally store the ill_index if we need to
17656 			 * do IPSEC processing as we lose the ill queue when
17657 			 * we come back. But in this case, we never should
17658 			 * have to store the ill_index here as it should have
17659 			 * been stored previously when we processed the
17660 			 * AH/ESP header in this routine or for non-ipsec
17661 			 * cases, we still have the queue. But for some bad
17662 			 * packets from the wire, we can get to IPSEC after
17663 			 * this and we better store the index for that case.
17664 			 */
17665 			ill = (ill_t *)q->q_ptr;
17666 			ii = (ipsec_in_t *)first_mp->b_rptr;
17667 			ii->ipsec_in_ill_index =
17668 			    ill->ill_phyint->phyint_ifindex;
17669 			ii->ipsec_in_rill_index =
17670 			    recv_ill->ill_phyint->phyint_ifindex;
17671 			if (ii->ipsec_in_decaps) {
17672 				/*
17673 				 * This packet is self-encapsulated multiple
17674 				 * times. We don't want to recurse infinitely.
17675 				 * To keep it simple, drop the packet.
17676 				 */
17677 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17678 				freemsg(first_mp);
17679 				return;
17680 			}
17681 			ii->ipsec_in_decaps = B_TRUE;
17682 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17683 			    ire);
17684 			return;
17685 		}
17686 		break;
17687 	case IPPROTO_AH:
17688 	case IPPROTO_ESP: {
17689 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17690 
17691 		/*
17692 		 * Fast path for AH/ESP. If this is the first time
17693 		 * we are sending a datagram to AH/ESP, allocate
17694 		 * a IPSEC_IN message and prepend it. Otherwise,
17695 		 * just fanout.
17696 		 */
17697 
17698 		int ipsec_rc;
17699 		ipsec_in_t *ii;
17700 		netstack_t *ns = ipst->ips_netstack;
17701 
17702 		IP_STAT(ipst, ipsec_proto_ahesp);
17703 		if (!mctl_present) {
17704 			ASSERT(first_mp == mp);
17705 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17706 			if (first_mp == NULL) {
17707 				ip1dbg(("ip_proto_input: IPSEC_IN "
17708 				    "allocation failure.\n"));
17709 				freemsg(hada_mp); /* okay ifnull */
17710 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17711 				freemsg(mp);
17712 				return;
17713 			}
17714 			/*
17715 			 * Store the ill_index so that when we come back
17716 			 * from IPSEC we ride on the same queue.
17717 			 */
17718 			ill = (ill_t *)q->q_ptr;
17719 			ii = (ipsec_in_t *)first_mp->b_rptr;
17720 			ii->ipsec_in_ill_index =
17721 			    ill->ill_phyint->phyint_ifindex;
17722 			ii->ipsec_in_rill_index =
17723 			    recv_ill->ill_phyint->phyint_ifindex;
17724 			first_mp->b_cont = mp;
17725 			/*
17726 			 * Cache hardware acceleration info.
17727 			 */
17728 			if (hada_mp != NULL) {
17729 				IPSECHW_DEBUG(IPSECHW_PKT,
17730 				    ("ip_rput_local: caching data attr.\n"));
17731 				ii->ipsec_in_accelerated = B_TRUE;
17732 				ii->ipsec_in_da = hada_mp;
17733 				hada_mp = NULL;
17734 			}
17735 		} else {
17736 			ii = (ipsec_in_t *)first_mp->b_rptr;
17737 		}
17738 
17739 		if (!ipsec_loaded(ipss)) {
17740 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17741 			    ire->ire_zoneid, ipst);
17742 			return;
17743 		}
17744 
17745 		ns = ipst->ips_netstack;
17746 		/* select inbound SA and have IPsec process the pkt */
17747 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17748 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17749 			if (esph == NULL)
17750 				return;
17751 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17752 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17753 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17754 			    first_mp, esph);
17755 		} else {
17756 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17757 			if (ah == NULL)
17758 				return;
17759 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17760 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17761 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17762 			    first_mp, ah);
17763 		}
17764 
17765 		switch (ipsec_rc) {
17766 		case IPSEC_STATUS_SUCCESS:
17767 			break;
17768 		case IPSEC_STATUS_FAILED:
17769 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17770 			/* FALLTHRU */
17771 		case IPSEC_STATUS_PENDING:
17772 			return;
17773 		}
17774 		/* we're done with IPsec processing, send it up */
17775 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17776 		return;
17777 	}
17778 	default:
17779 		break;
17780 	}
17781 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17782 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17783 		    ire->ire_zoneid));
17784 		goto drop_pkt;
17785 	}
17786 	/*
17787 	 * Handle protocols with which IP is less intimate.  There
17788 	 * can be more than one stream bound to a particular
17789 	 * protocol.  When this is the case, each one gets a copy
17790 	 * of any incoming packets.
17791 	 */
17792 	ip_fanout_proto(q, first_mp, ill, ipha,
17793 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17794 	    B_TRUE, recv_ill, ire->ire_zoneid);
17795 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17796 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17797 	return;
17798 
17799 drop_pkt:
17800 	freemsg(first_mp);
17801 	if (hada_mp != NULL)
17802 		freeb(hada_mp);
17803 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17804 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17805 #undef	rptr
17806 #undef  iphs
17807 
17808 }
17809 
17810 /*
17811  * Update any source route, record route or timestamp options.
17812  * Check that we are at end of strict source route.
17813  * The options have already been checked for sanity in ip_rput_options().
17814  */
17815 static boolean_t
17816 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17817     ip_stack_t *ipst)
17818 {
17819 	ipoptp_t	opts;
17820 	uchar_t		*opt;
17821 	uint8_t		optval;
17822 	uint8_t		optlen;
17823 	ipaddr_t	dst;
17824 	uint32_t	ts;
17825 	ire_t		*dst_ire;
17826 	timestruc_t	now;
17827 	zoneid_t	zoneid;
17828 	ill_t		*ill;
17829 
17830 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17831 
17832 	ip2dbg(("ip_rput_local_options\n"));
17833 
17834 	for (optval = ipoptp_first(&opts, ipha);
17835 	    optval != IPOPT_EOL;
17836 	    optval = ipoptp_next(&opts)) {
17837 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17838 		opt = opts.ipoptp_cur;
17839 		optlen = opts.ipoptp_len;
17840 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17841 		    optval, optlen));
17842 		switch (optval) {
17843 			uint32_t off;
17844 		case IPOPT_SSRR:
17845 		case IPOPT_LSRR:
17846 			off = opt[IPOPT_OFFSET];
17847 			off--;
17848 			if (optlen < IP_ADDR_LEN ||
17849 			    off > optlen - IP_ADDR_LEN) {
17850 				/* End of source route */
17851 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17852 				break;
17853 			}
17854 			/*
17855 			 * This will only happen if two consecutive entries
17856 			 * in the source route contains our address or if
17857 			 * it is a packet with a loose source route which
17858 			 * reaches us before consuming the whole source route
17859 			 */
17860 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17861 			if (optval == IPOPT_SSRR) {
17862 				goto bad_src_route;
17863 			}
17864 			/*
17865 			 * Hack: instead of dropping the packet truncate the
17866 			 * source route to what has been used by filling the
17867 			 * rest with IPOPT_NOP.
17868 			 */
17869 			opt[IPOPT_OLEN] = (uint8_t)off;
17870 			while (off < optlen) {
17871 				opt[off++] = IPOPT_NOP;
17872 			}
17873 			break;
17874 		case IPOPT_RR:
17875 			off = opt[IPOPT_OFFSET];
17876 			off--;
17877 			if (optlen < IP_ADDR_LEN ||
17878 			    off > optlen - IP_ADDR_LEN) {
17879 				/* No more room - ignore */
17880 				ip1dbg((
17881 				    "ip_rput_local_options: end of RR\n"));
17882 				break;
17883 			}
17884 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17885 			    IP_ADDR_LEN);
17886 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17887 			break;
17888 		case IPOPT_TS:
17889 			/* Insert timestamp if there is romm */
17890 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17891 			case IPOPT_TS_TSONLY:
17892 				off = IPOPT_TS_TIMELEN;
17893 				break;
17894 			case IPOPT_TS_PRESPEC:
17895 			case IPOPT_TS_PRESPEC_RFC791:
17896 				/* Verify that the address matched */
17897 				off = opt[IPOPT_OFFSET] - 1;
17898 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17899 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17900 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17901 				    ipst);
17902 				if (dst_ire == NULL) {
17903 					/* Not for us */
17904 					break;
17905 				}
17906 				ire_refrele(dst_ire);
17907 				/* FALLTHRU */
17908 			case IPOPT_TS_TSANDADDR:
17909 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17910 				break;
17911 			default:
17912 				/*
17913 				 * ip_*put_options should have already
17914 				 * dropped this packet.
17915 				 */
17916 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17917 				    "unknown IT - bug in ip_rput_options?\n");
17918 				return (B_TRUE);	/* Keep "lint" happy */
17919 			}
17920 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17921 				/* Increase overflow counter */
17922 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17923 				opt[IPOPT_POS_OV_FLG] =
17924 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17925 				    (off << 4));
17926 				break;
17927 			}
17928 			off = opt[IPOPT_OFFSET] - 1;
17929 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17930 			case IPOPT_TS_PRESPEC:
17931 			case IPOPT_TS_PRESPEC_RFC791:
17932 			case IPOPT_TS_TSANDADDR:
17933 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17934 				    IP_ADDR_LEN);
17935 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17936 				/* FALLTHRU */
17937 			case IPOPT_TS_TSONLY:
17938 				off = opt[IPOPT_OFFSET] - 1;
17939 				/* Compute # of milliseconds since midnight */
17940 				gethrestime(&now);
17941 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17942 				    now.tv_nsec / (NANOSEC / MILLISEC);
17943 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17944 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17945 				break;
17946 			}
17947 			break;
17948 		}
17949 	}
17950 	return (B_TRUE);
17951 
17952 bad_src_route:
17953 	q = WR(q);
17954 	if (q->q_next != NULL)
17955 		ill = q->q_ptr;
17956 	else
17957 		ill = NULL;
17958 
17959 	/* make sure we clear any indication of a hardware checksum */
17960 	DB_CKSUMFLAGS(mp) = 0;
17961 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17962 	if (zoneid == ALL_ZONES)
17963 		freemsg(mp);
17964 	else
17965 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17966 	return (B_FALSE);
17967 
17968 }
17969 
17970 /*
17971  * Process IP options in an inbound packet.  If an option affects the
17972  * effective destination address, return the next hop address via dstp.
17973  * Returns -1 if something fails in which case an ICMP error has been sent
17974  * and mp freed.
17975  */
17976 static int
17977 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17978     ip_stack_t *ipst)
17979 {
17980 	ipoptp_t	opts;
17981 	uchar_t		*opt;
17982 	uint8_t		optval;
17983 	uint8_t		optlen;
17984 	ipaddr_t	dst;
17985 	intptr_t	code = 0;
17986 	ire_t		*ire = NULL;
17987 	zoneid_t	zoneid;
17988 	ill_t		*ill;
17989 
17990 	ip2dbg(("ip_rput_options\n"));
17991 	dst = ipha->ipha_dst;
17992 	for (optval = ipoptp_first(&opts, ipha);
17993 	    optval != IPOPT_EOL;
17994 	    optval = ipoptp_next(&opts)) {
17995 		opt = opts.ipoptp_cur;
17996 		optlen = opts.ipoptp_len;
17997 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17998 		    optval, optlen));
17999 		/*
18000 		 * Note: we need to verify the checksum before we
18001 		 * modify anything thus this routine only extracts the next
18002 		 * hop dst from any source route.
18003 		 */
18004 		switch (optval) {
18005 			uint32_t off;
18006 		case IPOPT_SSRR:
18007 		case IPOPT_LSRR:
18008 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18009 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18010 			if (ire == NULL) {
18011 				if (optval == IPOPT_SSRR) {
18012 					ip1dbg(("ip_rput_options: not next"
18013 					    " strict source route 0x%x\n",
18014 					    ntohl(dst)));
18015 					code = (char *)&ipha->ipha_dst -
18016 					    (char *)ipha;
18017 					goto param_prob; /* RouterReq's */
18018 				}
18019 				ip2dbg(("ip_rput_options: "
18020 				    "not next source route 0x%x\n",
18021 				    ntohl(dst)));
18022 				break;
18023 			}
18024 			ire_refrele(ire);
18025 
18026 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18027 				ip1dbg((
18028 				    "ip_rput_options: bad option offset\n"));
18029 				code = (char *)&opt[IPOPT_OLEN] -
18030 				    (char *)ipha;
18031 				goto param_prob;
18032 			}
18033 			off = opt[IPOPT_OFFSET];
18034 			off--;
18035 		redo_srr:
18036 			if (optlen < IP_ADDR_LEN ||
18037 			    off > optlen - IP_ADDR_LEN) {
18038 				/* End of source route */
18039 				ip1dbg(("ip_rput_options: end of SR\n"));
18040 				break;
18041 			}
18042 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18043 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18044 			    ntohl(dst)));
18045 
18046 			/*
18047 			 * Check if our address is present more than
18048 			 * once as consecutive hops in source route.
18049 			 * XXX verify per-interface ip_forwarding
18050 			 * for source route?
18051 			 */
18052 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18053 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18054 
18055 			if (ire != NULL) {
18056 				ire_refrele(ire);
18057 				off += IP_ADDR_LEN;
18058 				goto redo_srr;
18059 			}
18060 
18061 			if (dst == htonl(INADDR_LOOPBACK)) {
18062 				ip1dbg(("ip_rput_options: loopback addr in "
18063 				    "source route!\n"));
18064 				goto bad_src_route;
18065 			}
18066 			/*
18067 			 * For strict: verify that dst is directly
18068 			 * reachable.
18069 			 */
18070 			if (optval == IPOPT_SSRR) {
18071 				ire = ire_ftable_lookup(dst, 0, 0,
18072 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18073 				    MBLK_GETLABEL(mp),
18074 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18075 				if (ire == NULL) {
18076 					ip1dbg(("ip_rput_options: SSRR not "
18077 					    "directly reachable: 0x%x\n",
18078 					    ntohl(dst)));
18079 					goto bad_src_route;
18080 				}
18081 				ire_refrele(ire);
18082 			}
18083 			/*
18084 			 * Defer update of the offset and the record route
18085 			 * until the packet is forwarded.
18086 			 */
18087 			break;
18088 		case IPOPT_RR:
18089 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18090 				ip1dbg((
18091 				    "ip_rput_options: bad option offset\n"));
18092 				code = (char *)&opt[IPOPT_OLEN] -
18093 				    (char *)ipha;
18094 				goto param_prob;
18095 			}
18096 			break;
18097 		case IPOPT_TS:
18098 			/*
18099 			 * Verify that length >= 5 and that there is either
18100 			 * room for another timestamp or that the overflow
18101 			 * counter is not maxed out.
18102 			 */
18103 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18104 			if (optlen < IPOPT_MINLEN_IT) {
18105 				goto param_prob;
18106 			}
18107 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18108 				ip1dbg((
18109 				    "ip_rput_options: bad option offset\n"));
18110 				code = (char *)&opt[IPOPT_OFFSET] -
18111 				    (char *)ipha;
18112 				goto param_prob;
18113 			}
18114 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18115 			case IPOPT_TS_TSONLY:
18116 				off = IPOPT_TS_TIMELEN;
18117 				break;
18118 			case IPOPT_TS_TSANDADDR:
18119 			case IPOPT_TS_PRESPEC:
18120 			case IPOPT_TS_PRESPEC_RFC791:
18121 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18122 				break;
18123 			default:
18124 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18125 				    (char *)ipha;
18126 				goto param_prob;
18127 			}
18128 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18129 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18130 				/*
18131 				 * No room and the overflow counter is 15
18132 				 * already.
18133 				 */
18134 				goto param_prob;
18135 			}
18136 			break;
18137 		}
18138 	}
18139 
18140 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18141 		*dstp = dst;
18142 		return (0);
18143 	}
18144 
18145 	ip1dbg(("ip_rput_options: error processing IP options."));
18146 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18147 
18148 param_prob:
18149 	q = WR(q);
18150 	if (q->q_next != NULL)
18151 		ill = q->q_ptr;
18152 	else
18153 		ill = NULL;
18154 
18155 	/* make sure we clear any indication of a hardware checksum */
18156 	DB_CKSUMFLAGS(mp) = 0;
18157 	/* Don't know whether this is for non-global or global/forwarding */
18158 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18159 	if (zoneid == ALL_ZONES)
18160 		freemsg(mp);
18161 	else
18162 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18163 	return (-1);
18164 
18165 bad_src_route:
18166 	q = WR(q);
18167 	if (q->q_next != NULL)
18168 		ill = q->q_ptr;
18169 	else
18170 		ill = NULL;
18171 
18172 	/* make sure we clear any indication of a hardware checksum */
18173 	DB_CKSUMFLAGS(mp) = 0;
18174 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18175 	if (zoneid == ALL_ZONES)
18176 		freemsg(mp);
18177 	else
18178 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18179 	return (-1);
18180 }
18181 
18182 /*
18183  * IP & ICMP info in >=14 msg's ...
18184  *  - ip fixed part (mib2_ip_t)
18185  *  - icmp fixed part (mib2_icmp_t)
18186  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18187  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18188  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18189  *  - ipRouteAttributeTable (ip 102)	labeled routes
18190  *  - ip multicast membership (ip_member_t)
18191  *  - ip multicast source filtering (ip_grpsrc_t)
18192  *  - igmp fixed part (struct igmpstat)
18193  *  - multicast routing stats (struct mrtstat)
18194  *  - multicast routing vifs (array of struct vifctl)
18195  *  - multicast routing routes (array of struct mfcctl)
18196  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18197  *					One per ill plus one generic
18198  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18199  *					One per ill plus one generic
18200  *  - ipv6RouteEntry			all IPv6 IREs
18201  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18202  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18203  *  - ipv6AddrEntry			all IPv6 ipifs
18204  *  - ipv6 multicast membership (ipv6_member_t)
18205  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18206  *
18207  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18208  *
18209  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18210  * already filled in by the caller.
18211  * Return value of 0 indicates that no messages were sent and caller
18212  * should free mpctl.
18213  */
18214 int
18215 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18216 {
18217 	ip_stack_t *ipst;
18218 	sctp_stack_t *sctps;
18219 
18220 
18221 	if (q->q_next != NULL) {
18222 		ipst = ILLQ_TO_IPST(q);
18223 	} else {
18224 		ipst = CONNQ_TO_IPST(q);
18225 	}
18226 	ASSERT(ipst != NULL);
18227 	sctps = ipst->ips_netstack->netstack_sctp;
18228 
18229 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18230 		return (0);
18231 	}
18232 
18233 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18234 	    ipst)) == NULL) {
18235 		return (1);
18236 	}
18237 
18238 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18239 		return (1);
18240 	}
18241 
18242 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18243 		return (1);
18244 	}
18245 
18246 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18247 		return (1);
18248 	}
18249 
18250 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18251 		return (1);
18252 	}
18253 
18254 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18255 		return (1);
18256 	}
18257 
18258 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18259 		return (1);
18260 	}
18261 
18262 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18263 		return (1);
18264 	}
18265 
18266 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18267 		return (1);
18268 	}
18269 
18270 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18271 		return (1);
18272 	}
18273 
18274 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18275 		return (1);
18276 	}
18277 
18278 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18279 		return (1);
18280 	}
18281 
18282 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18283 		return (1);
18284 	}
18285 
18286 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18287 		return (1);
18288 	}
18289 
18290 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18291 		return (1);
18292 	}
18293 
18294 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18295 	if (mpctl == NULL) {
18296 		return (1);
18297 	}
18298 
18299 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18300 		return (1);
18301 	}
18302 	freemsg(mpctl);
18303 	return (1);
18304 }
18305 
18306 
18307 /* Get global (legacy) IPv4 statistics */
18308 static mblk_t *
18309 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18310     ip_stack_t *ipst)
18311 {
18312 	mib2_ip_t		old_ip_mib;
18313 	struct opthdr		*optp;
18314 	mblk_t			*mp2ctl;
18315 
18316 	/*
18317 	 * make a copy of the original message
18318 	 */
18319 	mp2ctl = copymsg(mpctl);
18320 
18321 	/* fixed length IP structure... */
18322 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18323 	optp->level = MIB2_IP;
18324 	optp->name = 0;
18325 	SET_MIB(old_ip_mib.ipForwarding,
18326 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18327 	SET_MIB(old_ip_mib.ipDefaultTTL,
18328 	    (uint32_t)ipst->ips_ip_def_ttl);
18329 	SET_MIB(old_ip_mib.ipReasmTimeout,
18330 	    ipst->ips_ip_g_frag_timeout);
18331 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18332 	    sizeof (mib2_ipAddrEntry_t));
18333 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18334 	    sizeof (mib2_ipRouteEntry_t));
18335 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18336 	    sizeof (mib2_ipNetToMediaEntry_t));
18337 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18338 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18339 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18340 	    sizeof (mib2_ipAttributeEntry_t));
18341 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18342 
18343 	/*
18344 	 * Grab the statistics from the new IP MIB
18345 	 */
18346 	SET_MIB(old_ip_mib.ipInReceives,
18347 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18348 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18349 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18350 	SET_MIB(old_ip_mib.ipForwDatagrams,
18351 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18352 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18353 	    ipmib->ipIfStatsInUnknownProtos);
18354 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18355 	SET_MIB(old_ip_mib.ipInDelivers,
18356 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18357 	SET_MIB(old_ip_mib.ipOutRequests,
18358 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18359 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18360 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18361 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18362 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18363 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18364 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18365 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18366 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18367 
18368 	/* ipRoutingDiscards is not being used */
18369 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18370 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18371 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18372 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18373 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18374 	    ipmib->ipIfStatsReasmDuplicates);
18375 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18376 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18377 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18378 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18379 	SET_MIB(old_ip_mib.rawipInOverflows,
18380 	    ipmib->rawipIfStatsInOverflows);
18381 
18382 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18383 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18384 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18385 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18386 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18387 	    ipmib->ipIfStatsOutSwitchIPVersion);
18388 
18389 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18390 	    (int)sizeof (old_ip_mib))) {
18391 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18392 		    (uint_t)sizeof (old_ip_mib)));
18393 	}
18394 
18395 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18396 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18397 	    (int)optp->level, (int)optp->name, (int)optp->len));
18398 	qreply(q, mpctl);
18399 	return (mp2ctl);
18400 }
18401 
18402 /* Per interface IPv4 statistics */
18403 static mblk_t *
18404 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18405 {
18406 	struct opthdr		*optp;
18407 	mblk_t			*mp2ctl;
18408 	ill_t			*ill;
18409 	ill_walk_context_t	ctx;
18410 	mblk_t			*mp_tail = NULL;
18411 	mib2_ipIfStatsEntry_t	global_ip_mib;
18412 
18413 	/*
18414 	 * Make a copy of the original message
18415 	 */
18416 	mp2ctl = copymsg(mpctl);
18417 
18418 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18419 	optp->level = MIB2_IP;
18420 	optp->name = MIB2_IP_TRAFFIC_STATS;
18421 	/* Include "unknown interface" ip_mib */
18422 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18423 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18424 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18425 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18426 	    (ipst->ips_ip_g_forward ? 1 : 2));
18427 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18428 	    (uint32_t)ipst->ips_ip_def_ttl);
18429 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18430 	    sizeof (mib2_ipIfStatsEntry_t));
18431 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18432 	    sizeof (mib2_ipAddrEntry_t));
18433 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18434 	    sizeof (mib2_ipRouteEntry_t));
18435 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18436 	    sizeof (mib2_ipNetToMediaEntry_t));
18437 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18438 	    sizeof (ip_member_t));
18439 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18440 	    sizeof (ip_grpsrc_t));
18441 
18442 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18443 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18444 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18445 		    "failed to allocate %u bytes\n",
18446 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18447 	}
18448 
18449 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18450 
18451 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18452 	ill = ILL_START_WALK_V4(&ctx, ipst);
18453 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18454 		ill->ill_ip_mib->ipIfStatsIfIndex =
18455 		    ill->ill_phyint->phyint_ifindex;
18456 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18457 		    (ipst->ips_ip_g_forward ? 1 : 2));
18458 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18459 		    (uint32_t)ipst->ips_ip_def_ttl);
18460 
18461 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18462 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18463 		    (char *)ill->ill_ip_mib,
18464 		    (int)sizeof (*ill->ill_ip_mib))) {
18465 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18466 			    "failed to allocate %u bytes\n",
18467 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18468 		}
18469 	}
18470 	rw_exit(&ipst->ips_ill_g_lock);
18471 
18472 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18473 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18474 	    "level %d, name %d, len %d\n",
18475 	    (int)optp->level, (int)optp->name, (int)optp->len));
18476 	qreply(q, mpctl);
18477 
18478 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18479 }
18480 
18481 /* Global IPv4 ICMP statistics */
18482 static mblk_t *
18483 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18484 {
18485 	struct opthdr		*optp;
18486 	mblk_t			*mp2ctl;
18487 
18488 	/*
18489 	 * Make a copy of the original message
18490 	 */
18491 	mp2ctl = copymsg(mpctl);
18492 
18493 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18494 	optp->level = MIB2_ICMP;
18495 	optp->name = 0;
18496 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18497 	    (int)sizeof (ipst->ips_icmp_mib))) {
18498 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18499 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18500 	}
18501 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18502 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18503 	    (int)optp->level, (int)optp->name, (int)optp->len));
18504 	qreply(q, mpctl);
18505 	return (mp2ctl);
18506 }
18507 
18508 /* Global IPv4 IGMP statistics */
18509 static mblk_t *
18510 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18511 {
18512 	struct opthdr		*optp;
18513 	mblk_t			*mp2ctl;
18514 
18515 	/*
18516 	 * make a copy of the original message
18517 	 */
18518 	mp2ctl = copymsg(mpctl);
18519 
18520 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18521 	optp->level = EXPER_IGMP;
18522 	optp->name = 0;
18523 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18524 	    (int)sizeof (ipst->ips_igmpstat))) {
18525 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18526 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18527 	}
18528 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18529 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18530 	    (int)optp->level, (int)optp->name, (int)optp->len));
18531 	qreply(q, mpctl);
18532 	return (mp2ctl);
18533 }
18534 
18535 /* Global IPv4 Multicast Routing statistics */
18536 static mblk_t *
18537 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18538 {
18539 	struct opthdr		*optp;
18540 	mblk_t			*mp2ctl;
18541 
18542 	/*
18543 	 * make a copy of the original message
18544 	 */
18545 	mp2ctl = copymsg(mpctl);
18546 
18547 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18548 	optp->level = EXPER_DVMRP;
18549 	optp->name = 0;
18550 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18551 		ip0dbg(("ip_mroute_stats: failed\n"));
18552 	}
18553 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18554 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18555 	    (int)optp->level, (int)optp->name, (int)optp->len));
18556 	qreply(q, mpctl);
18557 	return (mp2ctl);
18558 }
18559 
18560 /* IPv4 address information */
18561 static mblk_t *
18562 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18563 {
18564 	struct opthdr		*optp;
18565 	mblk_t			*mp2ctl;
18566 	mblk_t			*mp_tail = NULL;
18567 	ill_t			*ill;
18568 	ipif_t			*ipif;
18569 	uint_t			bitval;
18570 	mib2_ipAddrEntry_t	mae;
18571 	zoneid_t		zoneid;
18572 	ill_walk_context_t ctx;
18573 
18574 	/*
18575 	 * make a copy of the original message
18576 	 */
18577 	mp2ctl = copymsg(mpctl);
18578 
18579 	/* ipAddrEntryTable */
18580 
18581 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18582 	optp->level = MIB2_IP;
18583 	optp->name = MIB2_IP_ADDR;
18584 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18585 
18586 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18587 	ill = ILL_START_WALK_V4(&ctx, ipst);
18588 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18589 		for (ipif = ill->ill_ipif; ipif != NULL;
18590 		    ipif = ipif->ipif_next) {
18591 			if (ipif->ipif_zoneid != zoneid &&
18592 			    ipif->ipif_zoneid != ALL_ZONES)
18593 				continue;
18594 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18595 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18596 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18597 
18598 			(void) ipif_get_name(ipif,
18599 			    mae.ipAdEntIfIndex.o_bytes,
18600 			    OCTET_LENGTH);
18601 			mae.ipAdEntIfIndex.o_length =
18602 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18603 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18604 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18605 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18606 			mae.ipAdEntInfo.ae_subnet_len =
18607 			    ip_mask_to_plen(ipif->ipif_net_mask);
18608 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18609 			for (bitval = 1;
18610 			    bitval &&
18611 			    !(bitval & ipif->ipif_brd_addr);
18612 			    bitval <<= 1)
18613 				noop;
18614 			mae.ipAdEntBcastAddr = bitval;
18615 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18616 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18617 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18618 			mae.ipAdEntInfo.ae_broadcast_addr =
18619 			    ipif->ipif_brd_addr;
18620 			mae.ipAdEntInfo.ae_pp_dst_addr =
18621 			    ipif->ipif_pp_dst_addr;
18622 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18623 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18624 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18625 
18626 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18627 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18628 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18629 				    "allocate %u bytes\n",
18630 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18631 			}
18632 		}
18633 	}
18634 	rw_exit(&ipst->ips_ill_g_lock);
18635 
18636 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18637 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18638 	    (int)optp->level, (int)optp->name, (int)optp->len));
18639 	qreply(q, mpctl);
18640 	return (mp2ctl);
18641 }
18642 
18643 /* IPv6 address information */
18644 static mblk_t *
18645 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18646 {
18647 	struct opthdr		*optp;
18648 	mblk_t			*mp2ctl;
18649 	mblk_t			*mp_tail = NULL;
18650 	ill_t			*ill;
18651 	ipif_t			*ipif;
18652 	mib2_ipv6AddrEntry_t	mae6;
18653 	zoneid_t		zoneid;
18654 	ill_walk_context_t	ctx;
18655 
18656 	/*
18657 	 * make a copy of the original message
18658 	 */
18659 	mp2ctl = copymsg(mpctl);
18660 
18661 	/* ipv6AddrEntryTable */
18662 
18663 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18664 	optp->level = MIB2_IP6;
18665 	optp->name = MIB2_IP6_ADDR;
18666 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18667 
18668 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18669 	ill = ILL_START_WALK_V6(&ctx, ipst);
18670 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18671 		for (ipif = ill->ill_ipif; ipif != NULL;
18672 		    ipif = ipif->ipif_next) {
18673 			if (ipif->ipif_zoneid != zoneid &&
18674 			    ipif->ipif_zoneid != ALL_ZONES)
18675 				continue;
18676 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18677 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18678 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18679 
18680 			(void) ipif_get_name(ipif,
18681 			    mae6.ipv6AddrIfIndex.o_bytes,
18682 			    OCTET_LENGTH);
18683 			mae6.ipv6AddrIfIndex.o_length =
18684 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18685 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18686 			mae6.ipv6AddrPfxLength =
18687 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18688 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18689 			mae6.ipv6AddrInfo.ae_subnet_len =
18690 			    mae6.ipv6AddrPfxLength;
18691 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18692 
18693 			/* Type: stateless(1), stateful(2), unknown(3) */
18694 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18695 				mae6.ipv6AddrType = 1;
18696 			else
18697 				mae6.ipv6AddrType = 2;
18698 			/* Anycast: true(1), false(2) */
18699 			if (ipif->ipif_flags & IPIF_ANYCAST)
18700 				mae6.ipv6AddrAnycastFlag = 1;
18701 			else
18702 				mae6.ipv6AddrAnycastFlag = 2;
18703 
18704 			/*
18705 			 * Address status: preferred(1), deprecated(2),
18706 			 * invalid(3), inaccessible(4), unknown(5)
18707 			 */
18708 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18709 				mae6.ipv6AddrStatus = 3;
18710 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18711 				mae6.ipv6AddrStatus = 2;
18712 			else
18713 				mae6.ipv6AddrStatus = 1;
18714 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18715 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18716 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18717 						ipif->ipif_v6pp_dst_addr;
18718 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18719 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18720 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18721 			mae6.ipv6AddrIdentifier = ill->ill_token;
18722 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18723 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18724 			mae6.ipv6AddrRetransmitTime =
18725 			    ill->ill_reachable_retrans_time;
18726 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18727 				(char *)&mae6,
18728 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18729 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18730 				    "allocate %u bytes\n",
18731 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18732 			}
18733 		}
18734 	}
18735 	rw_exit(&ipst->ips_ill_g_lock);
18736 
18737 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18738 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18739 	    (int)optp->level, (int)optp->name, (int)optp->len));
18740 	qreply(q, mpctl);
18741 	return (mp2ctl);
18742 }
18743 
18744 /* IPv4 multicast group membership. */
18745 static mblk_t *
18746 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18747 {
18748 	struct opthdr		*optp;
18749 	mblk_t			*mp2ctl;
18750 	ill_t			*ill;
18751 	ipif_t			*ipif;
18752 	ilm_t			*ilm;
18753 	ip_member_t		ipm;
18754 	mblk_t			*mp_tail = NULL;
18755 	ill_walk_context_t	ctx;
18756 	zoneid_t		zoneid;
18757 
18758 	/*
18759 	 * make a copy of the original message
18760 	 */
18761 	mp2ctl = copymsg(mpctl);
18762 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18763 
18764 	/* ipGroupMember table */
18765 	optp = (struct opthdr *)&mpctl->b_rptr[
18766 	    sizeof (struct T_optmgmt_ack)];
18767 	optp->level = MIB2_IP;
18768 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18769 
18770 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18771 	ill = ILL_START_WALK_V4(&ctx, ipst);
18772 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18773 		ILM_WALKER_HOLD(ill);
18774 		for (ipif = ill->ill_ipif; ipif != NULL;
18775 		    ipif = ipif->ipif_next) {
18776 			if (ipif->ipif_zoneid != zoneid &&
18777 			    ipif->ipif_zoneid != ALL_ZONES)
18778 				continue;	/* not this zone */
18779 			(void) ipif_get_name(ipif,
18780 			    ipm.ipGroupMemberIfIndex.o_bytes,
18781 			    OCTET_LENGTH);
18782 			ipm.ipGroupMemberIfIndex.o_length =
18783 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18784 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18785 				ASSERT(ilm->ilm_ipif != NULL);
18786 				ASSERT(ilm->ilm_ill == NULL);
18787 				if (ilm->ilm_ipif != ipif)
18788 					continue;
18789 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18790 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18791 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18792 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18793 				    (char *)&ipm, (int)sizeof (ipm))) {
18794 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18795 					    "failed to allocate %u bytes\n",
18796 						(uint_t)sizeof (ipm)));
18797 				}
18798 			}
18799 		}
18800 		ILM_WALKER_RELE(ill);
18801 	}
18802 	rw_exit(&ipst->ips_ill_g_lock);
18803 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18804 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18805 	    (int)optp->level, (int)optp->name, (int)optp->len));
18806 	qreply(q, mpctl);
18807 	return (mp2ctl);
18808 }
18809 
18810 /* IPv6 multicast group membership. */
18811 static mblk_t *
18812 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18813 {
18814 	struct opthdr		*optp;
18815 	mblk_t			*mp2ctl;
18816 	ill_t			*ill;
18817 	ilm_t			*ilm;
18818 	ipv6_member_t		ipm6;
18819 	mblk_t			*mp_tail = NULL;
18820 	ill_walk_context_t	ctx;
18821 	zoneid_t		zoneid;
18822 
18823 	/*
18824 	 * make a copy of the original message
18825 	 */
18826 	mp2ctl = copymsg(mpctl);
18827 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18828 
18829 	/* ip6GroupMember table */
18830 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18831 	optp->level = MIB2_IP6;
18832 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18833 
18834 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18835 	ill = ILL_START_WALK_V6(&ctx, ipst);
18836 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18837 		ILM_WALKER_HOLD(ill);
18838 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18839 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18840 			ASSERT(ilm->ilm_ipif == NULL);
18841 			ASSERT(ilm->ilm_ill != NULL);
18842 			if (ilm->ilm_zoneid != zoneid)
18843 				continue;	/* not this zone */
18844 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18845 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18846 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18847 			if (!snmp_append_data2(mpctl->b_cont,
18848 			    &mp_tail,
18849 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18850 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18851 				    "failed to allocate %u bytes\n",
18852 				    (uint_t)sizeof (ipm6)));
18853 			}
18854 		}
18855 		ILM_WALKER_RELE(ill);
18856 	}
18857 	rw_exit(&ipst->ips_ill_g_lock);
18858 
18859 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18860 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18861 	    (int)optp->level, (int)optp->name, (int)optp->len));
18862 	qreply(q, mpctl);
18863 	return (mp2ctl);
18864 }
18865 
18866 /* IP multicast filtered sources */
18867 static mblk_t *
18868 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18869 {
18870 	struct opthdr		*optp;
18871 	mblk_t			*mp2ctl;
18872 	ill_t			*ill;
18873 	ipif_t			*ipif;
18874 	ilm_t			*ilm;
18875 	ip_grpsrc_t		ips;
18876 	mblk_t			*mp_tail = NULL;
18877 	ill_walk_context_t	ctx;
18878 	zoneid_t		zoneid;
18879 	int			i;
18880 	slist_t			*sl;
18881 
18882 	/*
18883 	 * make a copy of the original message
18884 	 */
18885 	mp2ctl = copymsg(mpctl);
18886 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18887 
18888 	/* ipGroupSource table */
18889 	optp = (struct opthdr *)&mpctl->b_rptr[
18890 	    sizeof (struct T_optmgmt_ack)];
18891 	optp->level = MIB2_IP;
18892 	optp->name = EXPER_IP_GROUP_SOURCES;
18893 
18894 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18895 	ill = ILL_START_WALK_V4(&ctx, ipst);
18896 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18897 		ILM_WALKER_HOLD(ill);
18898 		for (ipif = ill->ill_ipif; ipif != NULL;
18899 		    ipif = ipif->ipif_next) {
18900 			if (ipif->ipif_zoneid != zoneid)
18901 				continue;	/* not this zone */
18902 			(void) ipif_get_name(ipif,
18903 			    ips.ipGroupSourceIfIndex.o_bytes,
18904 			    OCTET_LENGTH);
18905 			ips.ipGroupSourceIfIndex.o_length =
18906 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18907 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18908 				ASSERT(ilm->ilm_ipif != NULL);
18909 				ASSERT(ilm->ilm_ill == NULL);
18910 				sl = ilm->ilm_filter;
18911 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18912 					continue;
18913 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18914 				for (i = 0; i < sl->sl_numsrc; i++) {
18915 					if (!IN6_IS_ADDR_V4MAPPED(
18916 					    &sl->sl_addr[i]))
18917 						continue;
18918 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18919 					    ips.ipGroupSourceAddress);
18920 					if (snmp_append_data2(mpctl->b_cont,
18921 					    &mp_tail, (char *)&ips,
18922 					    (int)sizeof (ips)) == 0) {
18923 						ip1dbg(("ip_snmp_get_mib2_"
18924 						    "ip_group_src: failed to "
18925 						    "allocate %u bytes\n",
18926 						    (uint_t)sizeof (ips)));
18927 					}
18928 				}
18929 			}
18930 		}
18931 		ILM_WALKER_RELE(ill);
18932 	}
18933 	rw_exit(&ipst->ips_ill_g_lock);
18934 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18935 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18936 	    (int)optp->level, (int)optp->name, (int)optp->len));
18937 	qreply(q, mpctl);
18938 	return (mp2ctl);
18939 }
18940 
18941 /* IPv6 multicast filtered sources. */
18942 static mblk_t *
18943 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18944 {
18945 	struct opthdr		*optp;
18946 	mblk_t			*mp2ctl;
18947 	ill_t			*ill;
18948 	ilm_t			*ilm;
18949 	ipv6_grpsrc_t		ips6;
18950 	mblk_t			*mp_tail = NULL;
18951 	ill_walk_context_t	ctx;
18952 	zoneid_t		zoneid;
18953 	int			i;
18954 	slist_t			*sl;
18955 
18956 	/*
18957 	 * make a copy of the original message
18958 	 */
18959 	mp2ctl = copymsg(mpctl);
18960 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18961 
18962 	/* ip6GroupMember table */
18963 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18964 	optp->level = MIB2_IP6;
18965 	optp->name = EXPER_IP6_GROUP_SOURCES;
18966 
18967 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18968 	ill = ILL_START_WALK_V6(&ctx, ipst);
18969 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18970 		ILM_WALKER_HOLD(ill);
18971 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18972 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18973 			ASSERT(ilm->ilm_ipif == NULL);
18974 			ASSERT(ilm->ilm_ill != NULL);
18975 			sl = ilm->ilm_filter;
18976 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18977 				continue;
18978 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18979 			for (i = 0; i < sl->sl_numsrc; i++) {
18980 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18981 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18982 				    (char *)&ips6, (int)sizeof (ips6))) {
18983 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18984 					    "group_src: failed to allocate "
18985 					    "%u bytes\n",
18986 					    (uint_t)sizeof (ips6)));
18987 				}
18988 			}
18989 		}
18990 		ILM_WALKER_RELE(ill);
18991 	}
18992 	rw_exit(&ipst->ips_ill_g_lock);
18993 
18994 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18995 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18996 	    (int)optp->level, (int)optp->name, (int)optp->len));
18997 	qreply(q, mpctl);
18998 	return (mp2ctl);
18999 }
19000 
19001 /* Multicast routing virtual interface table. */
19002 static mblk_t *
19003 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19004 {
19005 	struct opthdr		*optp;
19006 	mblk_t			*mp2ctl;
19007 
19008 	/*
19009 	 * make a copy of the original message
19010 	 */
19011 	mp2ctl = copymsg(mpctl);
19012 
19013 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19014 	optp->level = EXPER_DVMRP;
19015 	optp->name = EXPER_DVMRP_VIF;
19016 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19017 		ip0dbg(("ip_mroute_vif: failed\n"));
19018 	}
19019 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19020 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19021 	    (int)optp->level, (int)optp->name, (int)optp->len));
19022 	qreply(q, mpctl);
19023 	return (mp2ctl);
19024 }
19025 
19026 /* Multicast routing table. */
19027 static mblk_t *
19028 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19029 {
19030 	struct opthdr		*optp;
19031 	mblk_t			*mp2ctl;
19032 
19033 	/*
19034 	 * make a copy of the original message
19035 	 */
19036 	mp2ctl = copymsg(mpctl);
19037 
19038 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19039 	optp->level = EXPER_DVMRP;
19040 	optp->name = EXPER_DVMRP_MRT;
19041 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19042 		ip0dbg(("ip_mroute_mrt: failed\n"));
19043 	}
19044 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19045 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19046 	    (int)optp->level, (int)optp->name, (int)optp->len));
19047 	qreply(q, mpctl);
19048 	return (mp2ctl);
19049 }
19050 
19051 /*
19052  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19053  * in one IRE walk.
19054  */
19055 static mblk_t *
19056 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19057 {
19058 	struct opthdr	*optp;
19059 	mblk_t		*mp2ctl;	/* Returned */
19060 	mblk_t		*mp3ctl;	/* nettomedia */
19061 	mblk_t		*mp4ctl;	/* routeattrs */
19062 	iproutedata_t	ird;
19063 	zoneid_t	zoneid;
19064 
19065 	/*
19066 	 * make copies of the original message
19067 	 *	- mp2ctl is returned unchanged to the caller for his use
19068 	 *	- mpctl is sent upstream as ipRouteEntryTable
19069 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19070 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19071 	 */
19072 	mp2ctl = copymsg(mpctl);
19073 	mp3ctl = copymsg(mpctl);
19074 	mp4ctl = copymsg(mpctl);
19075 	if (mp3ctl == NULL || mp4ctl == NULL) {
19076 		freemsg(mp4ctl);
19077 		freemsg(mp3ctl);
19078 		freemsg(mp2ctl);
19079 		freemsg(mpctl);
19080 		return (NULL);
19081 	}
19082 
19083 	bzero(&ird, sizeof (ird));
19084 
19085 	ird.ird_route.lp_head = mpctl->b_cont;
19086 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19087 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19088 
19089 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19090 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19091 	if (zoneid == GLOBAL_ZONEID) {
19092 		/*
19093 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19094 		 * requires the sys_net_config or sys_ip_config privilege,
19095 		 * it can only run in the global zone or an exclusive-IP zone,
19096 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19097 		 */
19098 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19099 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19100 	}
19101 
19102 	/* ipRouteEntryTable in mpctl */
19103 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19104 	optp->level = MIB2_IP;
19105 	optp->name = MIB2_IP_ROUTE;
19106 	optp->len = msgdsize(ird.ird_route.lp_head);
19107 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19108 	    (int)optp->level, (int)optp->name, (int)optp->len));
19109 	qreply(q, mpctl);
19110 
19111 	/* ipNetToMediaEntryTable in mp3ctl */
19112 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19113 	optp->level = MIB2_IP;
19114 	optp->name = MIB2_IP_MEDIA;
19115 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19116 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19117 	    (int)optp->level, (int)optp->name, (int)optp->len));
19118 	qreply(q, mp3ctl);
19119 
19120 	/* ipRouteAttributeTable in mp4ctl */
19121 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19122 	optp->level = MIB2_IP;
19123 	optp->name = EXPER_IP_RTATTR;
19124 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19125 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19126 	    (int)optp->level, (int)optp->name, (int)optp->len));
19127 	if (optp->len == 0)
19128 		freemsg(mp4ctl);
19129 	else
19130 		qreply(q, mp4ctl);
19131 
19132 	return (mp2ctl);
19133 }
19134 
19135 /*
19136  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19137  * ipv6NetToMediaEntryTable in an NDP walk.
19138  */
19139 static mblk_t *
19140 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19141 {
19142 	struct opthdr	*optp;
19143 	mblk_t		*mp2ctl;	/* Returned */
19144 	mblk_t		*mp3ctl;	/* nettomedia */
19145 	mblk_t		*mp4ctl;	/* routeattrs */
19146 	iproutedata_t	ird;
19147 	zoneid_t	zoneid;
19148 
19149 	/*
19150 	 * make copies of the original message
19151 	 *	- mp2ctl is returned unchanged to the caller for his use
19152 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19153 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19154 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19155 	 */
19156 	mp2ctl = copymsg(mpctl);
19157 	mp3ctl = copymsg(mpctl);
19158 	mp4ctl = copymsg(mpctl);
19159 	if (mp3ctl == NULL || mp4ctl == NULL) {
19160 		freemsg(mp4ctl);
19161 		freemsg(mp3ctl);
19162 		freemsg(mp2ctl);
19163 		freemsg(mpctl);
19164 		return (NULL);
19165 	}
19166 
19167 	bzero(&ird, sizeof (ird));
19168 
19169 	ird.ird_route.lp_head = mpctl->b_cont;
19170 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19171 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19172 
19173 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19174 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19175 
19176 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19177 	optp->level = MIB2_IP6;
19178 	optp->name = MIB2_IP6_ROUTE;
19179 	optp->len = msgdsize(ird.ird_route.lp_head);
19180 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19181 	    (int)optp->level, (int)optp->name, (int)optp->len));
19182 	qreply(q, mpctl);
19183 
19184 	/* ipv6NetToMediaEntryTable in mp3ctl */
19185 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19186 
19187 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19188 	optp->level = MIB2_IP6;
19189 	optp->name = MIB2_IP6_MEDIA;
19190 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19191 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19192 	    (int)optp->level, (int)optp->name, (int)optp->len));
19193 	qreply(q, mp3ctl);
19194 
19195 	/* ipv6RouteAttributeTable in mp4ctl */
19196 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19197 	optp->level = MIB2_IP6;
19198 	optp->name = EXPER_IP_RTATTR;
19199 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19200 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19201 	    (int)optp->level, (int)optp->name, (int)optp->len));
19202 	if (optp->len == 0)
19203 		freemsg(mp4ctl);
19204 	else
19205 		qreply(q, mp4ctl);
19206 
19207 	return (mp2ctl);
19208 }
19209 
19210 /*
19211  * IPv6 mib: One per ill
19212  */
19213 static mblk_t *
19214 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19215 {
19216 	struct opthdr		*optp;
19217 	mblk_t			*mp2ctl;
19218 	ill_t			*ill;
19219 	ill_walk_context_t	ctx;
19220 	mblk_t			*mp_tail = NULL;
19221 
19222 	/*
19223 	 * Make a copy of the original message
19224 	 */
19225 	mp2ctl = copymsg(mpctl);
19226 
19227 	/* fixed length IPv6 structure ... */
19228 
19229 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19230 	optp->level = MIB2_IP6;
19231 	optp->name = 0;
19232 	/* Include "unknown interface" ip6_mib */
19233 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19234 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19235 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19236 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19237 	    ipst->ips_ipv6_forward ? 1 : 2);
19238 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19239 	    ipst->ips_ipv6_def_hops);
19240 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19241 	    sizeof (mib2_ipIfStatsEntry_t));
19242 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19243 	    sizeof (mib2_ipv6AddrEntry_t));
19244 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19245 	    sizeof (mib2_ipv6RouteEntry_t));
19246 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19247 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19248 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19249 	    sizeof (ipv6_member_t));
19250 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19251 	    sizeof (ipv6_grpsrc_t));
19252 
19253 	/*
19254 	 * Synchronize 64- and 32-bit counters
19255 	 */
19256 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19257 	    ipIfStatsHCInReceives);
19258 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19259 	    ipIfStatsHCInDelivers);
19260 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19261 	    ipIfStatsHCOutRequests);
19262 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19263 	    ipIfStatsHCOutForwDatagrams);
19264 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19265 	    ipIfStatsHCOutMcastPkts);
19266 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19267 	    ipIfStatsHCInMcastPkts);
19268 
19269 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19270 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19271 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19272 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19273 	}
19274 
19275 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19276 	ill = ILL_START_WALK_V6(&ctx, ipst);
19277 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19278 		ill->ill_ip_mib->ipIfStatsIfIndex =
19279 		    ill->ill_phyint->phyint_ifindex;
19280 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19281 		    ipst->ips_ipv6_forward ? 1 : 2);
19282 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19283 		    ill->ill_max_hops);
19284 
19285 		/*
19286 		 * Synchronize 64- and 32-bit counters
19287 		 */
19288 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19289 		    ipIfStatsHCInReceives);
19290 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19291 		    ipIfStatsHCInDelivers);
19292 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19293 		    ipIfStatsHCOutRequests);
19294 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19295 		    ipIfStatsHCOutForwDatagrams);
19296 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19297 		    ipIfStatsHCOutMcastPkts);
19298 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19299 		    ipIfStatsHCInMcastPkts);
19300 
19301 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19302 		    (char *)ill->ill_ip_mib,
19303 		    (int)sizeof (*ill->ill_ip_mib))) {
19304 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19305 				"%u bytes\n",
19306 				(uint_t)sizeof (*ill->ill_ip_mib)));
19307 		}
19308 	}
19309 	rw_exit(&ipst->ips_ill_g_lock);
19310 
19311 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19312 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19313 	    (int)optp->level, (int)optp->name, (int)optp->len));
19314 	qreply(q, mpctl);
19315 	return (mp2ctl);
19316 }
19317 
19318 /*
19319  * ICMPv6 mib: One per ill
19320  */
19321 static mblk_t *
19322 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19323 {
19324 	struct opthdr		*optp;
19325 	mblk_t			*mp2ctl;
19326 	ill_t			*ill;
19327 	ill_walk_context_t	ctx;
19328 	mblk_t			*mp_tail = NULL;
19329 	/*
19330 	 * Make a copy of the original message
19331 	 */
19332 	mp2ctl = copymsg(mpctl);
19333 
19334 	/* fixed length ICMPv6 structure ... */
19335 
19336 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19337 	optp->level = MIB2_ICMP6;
19338 	optp->name = 0;
19339 	/* Include "unknown interface" icmp6_mib */
19340 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19341 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19342 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19343 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19344 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19345 	    (char *)&ipst->ips_icmp6_mib,
19346 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19347 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19348 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19349 	}
19350 
19351 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19352 	ill = ILL_START_WALK_V6(&ctx, ipst);
19353 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19354 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19355 		    ill->ill_phyint->phyint_ifindex;
19356 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19357 		    (char *)ill->ill_icmp6_mib,
19358 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19359 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19360 			    "%u bytes\n",
19361 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19362 		}
19363 	}
19364 	rw_exit(&ipst->ips_ill_g_lock);
19365 
19366 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19367 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19368 	    (int)optp->level, (int)optp->name, (int)optp->len));
19369 	qreply(q, mpctl);
19370 	return (mp2ctl);
19371 }
19372 
19373 /*
19374  * ire_walk routine to create both ipRouteEntryTable and
19375  * ipRouteAttributeTable in one IRE walk
19376  */
19377 static void
19378 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19379 {
19380 	ill_t				*ill;
19381 	ipif_t				*ipif;
19382 	mib2_ipRouteEntry_t		*re;
19383 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19384 	ipaddr_t			gw_addr;
19385 	tsol_ire_gw_secattr_t		*attrp;
19386 	tsol_gc_t			*gc = NULL;
19387 	tsol_gcgrp_t			*gcgrp = NULL;
19388 	uint_t				sacnt = 0;
19389 	int				i;
19390 
19391 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19392 
19393 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19394 		return;
19395 
19396 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19397 		mutex_enter(&attrp->igsa_lock);
19398 		if ((gc = attrp->igsa_gc) != NULL) {
19399 			gcgrp = gc->gc_grp;
19400 			ASSERT(gcgrp != NULL);
19401 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19402 			sacnt = 1;
19403 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19404 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19405 			gc = gcgrp->gcgrp_head;
19406 			sacnt = gcgrp->gcgrp_count;
19407 		}
19408 		mutex_exit(&attrp->igsa_lock);
19409 
19410 		/* do nothing if there's no gc to report */
19411 		if (gc == NULL) {
19412 			ASSERT(sacnt == 0);
19413 			if (gcgrp != NULL) {
19414 				/* we might as well drop the lock now */
19415 				rw_exit(&gcgrp->gcgrp_rwlock);
19416 				gcgrp = NULL;
19417 			}
19418 			attrp = NULL;
19419 		}
19420 
19421 		ASSERT(gc == NULL || (gcgrp != NULL &&
19422 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19423 	}
19424 	ASSERT(sacnt == 0 || gc != NULL);
19425 
19426 	if (sacnt != 0 &&
19427 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19428 		kmem_free(re, sizeof (*re));
19429 		rw_exit(&gcgrp->gcgrp_rwlock);
19430 		return;
19431 	}
19432 
19433 	/*
19434 	 * Return all IRE types for route table... let caller pick and choose
19435 	 */
19436 	re->ipRouteDest = ire->ire_addr;
19437 	ipif = ire->ire_ipif;
19438 	re->ipRouteIfIndex.o_length = 0;
19439 	if (ire->ire_type == IRE_CACHE) {
19440 		ill = (ill_t *)ire->ire_stq->q_ptr;
19441 		re->ipRouteIfIndex.o_length =
19442 		    ill->ill_name_length == 0 ? 0 :
19443 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19444 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19445 		    re->ipRouteIfIndex.o_length);
19446 	} else if (ipif != NULL) {
19447 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19448 		    OCTET_LENGTH);
19449 		re->ipRouteIfIndex.o_length =
19450 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19451 	}
19452 	re->ipRouteMetric1 = -1;
19453 	re->ipRouteMetric2 = -1;
19454 	re->ipRouteMetric3 = -1;
19455 	re->ipRouteMetric4 = -1;
19456 
19457 	gw_addr = ire->ire_gateway_addr;
19458 
19459 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19460 		re->ipRouteNextHop = ire->ire_src_addr;
19461 	else
19462 		re->ipRouteNextHop = gw_addr;
19463 	/* indirect(4), direct(3), or invalid(2) */
19464 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19465 		re->ipRouteType = 2;
19466 	else
19467 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19468 	re->ipRouteProto = -1;
19469 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19470 	re->ipRouteMask = ire->ire_mask;
19471 	re->ipRouteMetric5 = -1;
19472 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19473 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19474 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19475 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19476 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19477 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19478 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19479 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19480 	re->ipRouteInfo.re_in_ill.o_length = 0;
19481 
19482 	if (ire->ire_flags & RTF_DYNAMIC) {
19483 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19484 	} else {
19485 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19486 	}
19487 
19488 	if (ire->ire_in_ill != NULL) {
19489 		re->ipRouteInfo.re_in_ill.o_length =
19490 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19491 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19492 		bcopy(ire->ire_in_ill->ill_name,
19493 		    re->ipRouteInfo.re_in_ill.o_bytes,
19494 		    re->ipRouteInfo.re_in_ill.o_length);
19495 	}
19496 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19497 
19498 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19499 	    (char *)re, (int)sizeof (*re))) {
19500 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19501 		    (uint_t)sizeof (*re)));
19502 	}
19503 
19504 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19505 		iaeptr->iae_routeidx = ird->ird_idx;
19506 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19507 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19508 	}
19509 
19510 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19511 	    (char *)iae, sacnt * sizeof (*iae))) {
19512 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19513 		    (unsigned)(sacnt * sizeof (*iae))));
19514 	}
19515 
19516 	/* bump route index for next pass */
19517 	ird->ird_idx++;
19518 
19519 	kmem_free(re, sizeof (*re));
19520 	if (sacnt != 0)
19521 		kmem_free(iae, sacnt * sizeof (*iae));
19522 
19523 	if (gcgrp != NULL)
19524 		rw_exit(&gcgrp->gcgrp_rwlock);
19525 }
19526 
19527 /*
19528  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19529  */
19530 static void
19531 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19532 {
19533 	ill_t				*ill;
19534 	ipif_t				*ipif;
19535 	mib2_ipv6RouteEntry_t		*re;
19536 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19537 	in6_addr_t			gw_addr_v6;
19538 	tsol_ire_gw_secattr_t		*attrp;
19539 	tsol_gc_t			*gc = NULL;
19540 	tsol_gcgrp_t			*gcgrp = NULL;
19541 	uint_t				sacnt = 0;
19542 	int				i;
19543 
19544 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19545 
19546 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19547 		return;
19548 
19549 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19550 		mutex_enter(&attrp->igsa_lock);
19551 		if ((gc = attrp->igsa_gc) != NULL) {
19552 			gcgrp = gc->gc_grp;
19553 			ASSERT(gcgrp != NULL);
19554 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19555 			sacnt = 1;
19556 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19557 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19558 			gc = gcgrp->gcgrp_head;
19559 			sacnt = gcgrp->gcgrp_count;
19560 		}
19561 		mutex_exit(&attrp->igsa_lock);
19562 
19563 		/* do nothing if there's no gc to report */
19564 		if (gc == NULL) {
19565 			ASSERT(sacnt == 0);
19566 			if (gcgrp != NULL) {
19567 				/* we might as well drop the lock now */
19568 				rw_exit(&gcgrp->gcgrp_rwlock);
19569 				gcgrp = NULL;
19570 			}
19571 			attrp = NULL;
19572 		}
19573 
19574 		ASSERT(gc == NULL || (gcgrp != NULL &&
19575 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19576 	}
19577 	ASSERT(sacnt == 0 || gc != NULL);
19578 
19579 	if (sacnt != 0 &&
19580 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19581 		kmem_free(re, sizeof (*re));
19582 		rw_exit(&gcgrp->gcgrp_rwlock);
19583 		return;
19584 	}
19585 
19586 	/*
19587 	 * Return all IRE types for route table... let caller pick and choose
19588 	 */
19589 	re->ipv6RouteDest = ire->ire_addr_v6;
19590 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19591 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19592 	re->ipv6RouteIfIndex.o_length = 0;
19593 	ipif = ire->ire_ipif;
19594 	if (ire->ire_type == IRE_CACHE) {
19595 		ill = (ill_t *)ire->ire_stq->q_ptr;
19596 		re->ipv6RouteIfIndex.o_length =
19597 		    ill->ill_name_length == 0 ? 0 :
19598 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19599 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19600 		    re->ipv6RouteIfIndex.o_length);
19601 	} else if (ipif != NULL) {
19602 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19603 		    OCTET_LENGTH);
19604 		re->ipv6RouteIfIndex.o_length =
19605 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19606 	}
19607 
19608 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19609 
19610 	mutex_enter(&ire->ire_lock);
19611 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19612 	mutex_exit(&ire->ire_lock);
19613 
19614 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19615 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19616 	else
19617 		re->ipv6RouteNextHop = gw_addr_v6;
19618 
19619 	/* remote(4), local(3), or discard(2) */
19620 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19621 		re->ipv6RouteType = 2;
19622 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19623 		re->ipv6RouteType = 3;
19624 	else
19625 		re->ipv6RouteType = 4;
19626 
19627 	re->ipv6RouteProtocol	= -1;
19628 	re->ipv6RoutePolicy	= 0;
19629 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19630 	re->ipv6RouteNextHopRDI	= 0;
19631 	re->ipv6RouteWeight	= 0;
19632 	re->ipv6RouteMetric	= 0;
19633 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19634 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19635 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19636 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19637 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19638 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19639 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19640 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19641 
19642 	if (ire->ire_flags & RTF_DYNAMIC) {
19643 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19644 	} else {
19645 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19646 	}
19647 
19648 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19649 	    (char *)re, (int)sizeof (*re))) {
19650 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19651 		    (uint_t)sizeof (*re)));
19652 	}
19653 
19654 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19655 		iaeptr->iae_routeidx = ird->ird_idx;
19656 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19657 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19658 	}
19659 
19660 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19661 	    (char *)iae, sacnt * sizeof (*iae))) {
19662 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19663 		    (unsigned)(sacnt * sizeof (*iae))));
19664 	}
19665 
19666 	/* bump route index for next pass */
19667 	ird->ird_idx++;
19668 
19669 	kmem_free(re, sizeof (*re));
19670 	if (sacnt != 0)
19671 		kmem_free(iae, sacnt * sizeof (*iae));
19672 
19673 	if (gcgrp != NULL)
19674 		rw_exit(&gcgrp->gcgrp_rwlock);
19675 }
19676 
19677 /*
19678  * ndp_walk routine to create ipv6NetToMediaEntryTable
19679  */
19680 static int
19681 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19682 {
19683 	ill_t				*ill;
19684 	mib2_ipv6NetToMediaEntry_t	ntme;
19685 	dl_unitdata_req_t		*dl;
19686 
19687 	ill = nce->nce_ill;
19688 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19689 		return (0);
19690 
19691 	/*
19692 	 * Neighbor cache entry attached to IRE with on-link
19693 	 * destination.
19694 	 */
19695 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19696 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19697 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19698 	    (nce->nce_res_mp != NULL)) {
19699 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19700 		ntme.ipv6NetToMediaPhysAddress.o_length =
19701 		    dl->dl_dest_addr_length;
19702 	} else {
19703 		ntme.ipv6NetToMediaPhysAddress.o_length =
19704 		    ill->ill_phys_addr_length;
19705 	}
19706 	if (nce->nce_res_mp != NULL) {
19707 		bcopy((char *)nce->nce_res_mp->b_rptr +
19708 		    NCE_LL_ADDR_OFFSET(ill),
19709 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19710 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19711 	} else {
19712 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19713 		    ill->ill_phys_addr_length);
19714 	}
19715 	/*
19716 	 * Note: Returns ND_* states. Should be:
19717 	 * reachable(1), stale(2), delay(3), probe(4),
19718 	 * invalid(5), unknown(6)
19719 	 */
19720 	ntme.ipv6NetToMediaState = nce->nce_state;
19721 	ntme.ipv6NetToMediaLastUpdated = 0;
19722 
19723 	/* other(1), dynamic(2), static(3), local(4) */
19724 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19725 		ntme.ipv6NetToMediaType = 4;
19726 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19727 		ntme.ipv6NetToMediaType = 1;
19728 	} else {
19729 		ntme.ipv6NetToMediaType = 2;
19730 	}
19731 
19732 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19733 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19734 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19735 		    (uint_t)sizeof (ntme)));
19736 	}
19737 	return (0);
19738 }
19739 
19740 /*
19741  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19742  */
19743 /* ARGSUSED */
19744 int
19745 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19746 {
19747 	switch (level) {
19748 	case MIB2_IP:
19749 	case MIB2_ICMP:
19750 		switch (name) {
19751 		default:
19752 			break;
19753 		}
19754 		return (1);
19755 	default:
19756 		return (1);
19757 	}
19758 }
19759 
19760 /*
19761  * When there exists both a 64- and 32-bit counter of a particular type
19762  * (i.e., InReceives), only the 64-bit counters are added.
19763  */
19764 void
19765 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19766 {
19767 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19768 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19769 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19770 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19771 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19772 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19773 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19774 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19775 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19776 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19777 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19778 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19779 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19780 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19781 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19782 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19783 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19784 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19785 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19786 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19787 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19788 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19789 	    o2->ipIfStatsInWrongIPVersion);
19790 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19791 	    o2->ipIfStatsInWrongIPVersion);
19792 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19793 	    o2->ipIfStatsOutSwitchIPVersion);
19794 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19795 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19796 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19797 	    o2->ipIfStatsHCInForwDatagrams);
19798 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19799 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19800 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19801 	    o2->ipIfStatsHCOutForwDatagrams);
19802 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19803 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19804 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19805 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19806 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19807 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19808 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19809 	    o2->ipIfStatsHCOutMcastOctets);
19810 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19811 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19812 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19813 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19814 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19815 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19816 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19817 }
19818 
19819 void
19820 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19821 {
19822 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19823 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19824 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19825 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19826 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19827 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19828 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19829 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19830 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19831 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19832 	    o2->ipv6IfIcmpInRouterSolicits);
19833 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19834 	    o2->ipv6IfIcmpInRouterAdvertisements);
19835 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19836 	    o2->ipv6IfIcmpInNeighborSolicits);
19837 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19838 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19839 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19840 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19841 	    o2->ipv6IfIcmpInGroupMembQueries);
19842 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19843 	    o2->ipv6IfIcmpInGroupMembResponses);
19844 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19845 	    o2->ipv6IfIcmpInGroupMembReductions);
19846 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19847 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19848 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19849 	    o2->ipv6IfIcmpOutDestUnreachs);
19850 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19851 	    o2->ipv6IfIcmpOutAdminProhibs);
19852 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19853 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19854 	    o2->ipv6IfIcmpOutParmProblems);
19855 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19856 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19857 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19858 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19859 	    o2->ipv6IfIcmpOutRouterSolicits);
19860 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19861 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19862 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19863 	    o2->ipv6IfIcmpOutNeighborSolicits);
19864 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19865 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19866 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19867 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19868 	    o2->ipv6IfIcmpOutGroupMembQueries);
19869 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19870 	    o2->ipv6IfIcmpOutGroupMembResponses);
19871 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19872 	    o2->ipv6IfIcmpOutGroupMembReductions);
19873 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19874 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19875 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19876 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19877 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19878 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19879 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19880 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19881 	    o2->ipv6IfIcmpInGroupMembTotal);
19882 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19883 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19884 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19885 	    o2->ipv6IfIcmpInGroupMembBadReports);
19886 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19887 	    o2->ipv6IfIcmpInGroupMembOurReports);
19888 }
19889 
19890 /*
19891  * Called before the options are updated to check if this packet will
19892  * be source routed from here.
19893  * This routine assumes that the options are well formed i.e. that they
19894  * have already been checked.
19895  */
19896 static boolean_t
19897 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19898 {
19899 	ipoptp_t	opts;
19900 	uchar_t		*opt;
19901 	uint8_t		optval;
19902 	uint8_t		optlen;
19903 	ipaddr_t	dst;
19904 	ire_t		*ire;
19905 
19906 	if (IS_SIMPLE_IPH(ipha)) {
19907 		ip2dbg(("not source routed\n"));
19908 		return (B_FALSE);
19909 	}
19910 	dst = ipha->ipha_dst;
19911 	for (optval = ipoptp_first(&opts, ipha);
19912 	    optval != IPOPT_EOL;
19913 	    optval = ipoptp_next(&opts)) {
19914 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19915 		opt = opts.ipoptp_cur;
19916 		optlen = opts.ipoptp_len;
19917 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19918 		    optval, optlen));
19919 		switch (optval) {
19920 			uint32_t off;
19921 		case IPOPT_SSRR:
19922 		case IPOPT_LSRR:
19923 			/*
19924 			 * If dst is one of our addresses and there are some
19925 			 * entries left in the source route return (true).
19926 			 */
19927 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19928 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19929 			if (ire == NULL) {
19930 				ip2dbg(("ip_source_routed: not next"
19931 				    " source route 0x%x\n",
19932 				    ntohl(dst)));
19933 				return (B_FALSE);
19934 			}
19935 			ire_refrele(ire);
19936 			off = opt[IPOPT_OFFSET];
19937 			off--;
19938 			if (optlen < IP_ADDR_LEN ||
19939 			    off > optlen - IP_ADDR_LEN) {
19940 				/* End of source route */
19941 				ip1dbg(("ip_source_routed: end of SR\n"));
19942 				return (B_FALSE);
19943 			}
19944 			return (B_TRUE);
19945 		}
19946 	}
19947 	ip2dbg(("not source routed\n"));
19948 	return (B_FALSE);
19949 }
19950 
19951 /*
19952  * Check if the packet contains any source route.
19953  */
19954 static boolean_t
19955 ip_source_route_included(ipha_t *ipha)
19956 {
19957 	ipoptp_t	opts;
19958 	uint8_t		optval;
19959 
19960 	if (IS_SIMPLE_IPH(ipha))
19961 		return (B_FALSE);
19962 	for (optval = ipoptp_first(&opts, ipha);
19963 	    optval != IPOPT_EOL;
19964 	    optval = ipoptp_next(&opts)) {
19965 		switch (optval) {
19966 		case IPOPT_SSRR:
19967 		case IPOPT_LSRR:
19968 			return (B_TRUE);
19969 		}
19970 	}
19971 	return (B_FALSE);
19972 }
19973 
19974 /*
19975  * Called when the IRE expiration timer fires.
19976  */
19977 void
19978 ip_trash_timer_expire(void *args)
19979 {
19980 	int			flush_flag = 0;
19981 	ire_expire_arg_t	iea;
19982 	ip_stack_t		*ipst = (ip_stack_t *)args;
19983 
19984 	iea.iea_ipst = ipst;	/* No netstack_hold */
19985 
19986 	/*
19987 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19988 	 * This lock makes sure that a new invocation of this function
19989 	 * that occurs due to an almost immediate timer firing will not
19990 	 * progress beyond this point until the current invocation is done
19991 	 */
19992 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19993 	ipst->ips_ip_ire_expire_id = 0;
19994 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19995 
19996 	/* Periodic timer */
19997 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19998 	    ipst->ips_ip_ire_arp_interval) {
19999 		/*
20000 		 * Remove all IRE_CACHE entries since they might
20001 		 * contain arp information.
20002 		 */
20003 		flush_flag |= FLUSH_ARP_TIME;
20004 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20005 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20006 	}
20007 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20008 	    ipst->ips_ip_ire_redir_interval) {
20009 		/* Remove all redirects */
20010 		flush_flag |= FLUSH_REDIRECT_TIME;
20011 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20012 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20013 	}
20014 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20015 	    ipst->ips_ip_ire_pathmtu_interval) {
20016 		/* Increase path mtu */
20017 		flush_flag |= FLUSH_MTU_TIME;
20018 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20019 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20020 	}
20021 
20022 	/*
20023 	 * Optimize for the case when there are no redirects in the
20024 	 * ftable, that is, no need to walk the ftable in that case.
20025 	 */
20026 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20027 		iea.iea_flush_flag = flush_flag;
20028 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20029 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20030 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20031 		    NULL, ALL_ZONES, ipst);
20032 	}
20033 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20034 	    ipst->ips_ip_redirect_cnt > 0) {
20035 		iea.iea_flush_flag = flush_flag;
20036 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20037 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20038 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20039 	}
20040 	if (flush_flag & FLUSH_MTU_TIME) {
20041 		/*
20042 		 * Walk all IPv6 IRE's and update them
20043 		 * Note that ARP and redirect timers are not
20044 		 * needed since NUD handles stale entries.
20045 		 */
20046 		flush_flag = FLUSH_MTU_TIME;
20047 		iea.iea_flush_flag = flush_flag;
20048 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20049 		    ALL_ZONES, ipst);
20050 	}
20051 
20052 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20053 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20054 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20055 
20056 	/*
20057 	 * Hold the lock to serialize timeout calls and prevent
20058 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20059 	 * for the timer to fire and a new invocation of this function
20060 	 * to start before the return value of timeout has been stored
20061 	 * in ip_ire_expire_id by the current invocation.
20062 	 */
20063 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20064 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20065 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20066 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20067 }
20068 
20069 /*
20070  * Called by the memory allocator subsystem directly, when the system
20071  * is running low on memory.
20072  */
20073 /* ARGSUSED */
20074 void
20075 ip_trash_ire_reclaim(void *args)
20076 {
20077 	netstack_handle_t nh;
20078 	netstack_t *ns;
20079 
20080 	netstack_next_init(&nh);
20081 	while ((ns = netstack_next(&nh)) != NULL) {
20082 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20083 		netstack_rele(ns);
20084 	}
20085 	netstack_next_fini(&nh);
20086 }
20087 
20088 static void
20089 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20090 {
20091 	ire_cache_count_t icc;
20092 	ire_cache_reclaim_t icr;
20093 	ncc_cache_count_t ncc;
20094 	nce_cache_reclaim_t ncr;
20095 	uint_t delete_cnt;
20096 	/*
20097 	 * Memory reclaim call back.
20098 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20099 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20100 	 * entries, determine what fraction to free for
20101 	 * each category of IRE_CACHE entries giving absolute priority
20102 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20103 	 * entry will be freed unless all offlink entries are freed).
20104 	 */
20105 	icc.icc_total = 0;
20106 	icc.icc_unused = 0;
20107 	icc.icc_offlink = 0;
20108 	icc.icc_pmtu = 0;
20109 	icc.icc_onlink = 0;
20110 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20111 
20112 	/*
20113 	 * Free NCEs for IPv6 like the onlink ires.
20114 	 */
20115 	ncc.ncc_total = 0;
20116 	ncc.ncc_host = 0;
20117 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20118 
20119 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20120 	    icc.icc_pmtu + icc.icc_onlink);
20121 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20122 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20123 	if (delete_cnt == 0)
20124 		return;
20125 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20126 	/* Always delete all unused offlink entries */
20127 	icr.icr_ipst = ipst;
20128 	icr.icr_unused = 1;
20129 	if (delete_cnt <= icc.icc_unused) {
20130 		/*
20131 		 * Only need to free unused entries.  In other words,
20132 		 * there are enough unused entries to free to meet our
20133 		 * target number of freed ire cache entries.
20134 		 */
20135 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20136 		ncr.ncr_host = 0;
20137 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20138 		/*
20139 		 * Only need to free unused entries, plus a fraction of offlink
20140 		 * entries.  It follows from the first if statement that
20141 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20142 		 */
20143 		delete_cnt -= icc.icc_unused;
20144 		/* Round up # deleted by truncating fraction */
20145 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20146 		icr.icr_pmtu = icr.icr_onlink = 0;
20147 		ncr.ncr_host = 0;
20148 	} else if (delete_cnt <=
20149 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20150 		/*
20151 		 * Free all unused and offlink entries, plus a fraction of
20152 		 * pmtu entries.  It follows from the previous if statement
20153 		 * that icc_pmtu is non-zero, and that
20154 		 * delete_cnt != icc_unused + icc_offlink.
20155 		 */
20156 		icr.icr_offlink = 1;
20157 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20158 		/* Round up # deleted by truncating fraction */
20159 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20160 		icr.icr_onlink = 0;
20161 		ncr.ncr_host = 0;
20162 	} else {
20163 		/*
20164 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20165 		 * of onlink entries.  If we're here, then we know that
20166 		 * icc_onlink is non-zero, and that
20167 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20168 		 */
20169 		icr.icr_offlink = icr.icr_pmtu = 1;
20170 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20171 		    icc.icc_pmtu;
20172 		/* Round up # deleted by truncating fraction */
20173 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20174 		/* Using the same delete fraction as for onlink IREs */
20175 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20176 	}
20177 #ifdef DEBUG
20178 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20179 	    "fractions %d/%d/%d/%d\n",
20180 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20181 	    icc.icc_unused, icc.icc_offlink,
20182 	    icc.icc_pmtu, icc.icc_onlink,
20183 	    icr.icr_unused, icr.icr_offlink,
20184 	    icr.icr_pmtu, icr.icr_onlink));
20185 #endif
20186 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20187 	if (ncr.ncr_host != 0)
20188 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20189 		    (uchar_t *)&ncr, ipst);
20190 #ifdef DEBUG
20191 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20192 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20193 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20194 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20195 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20196 	    icc.icc_pmtu, icc.icc_onlink));
20197 #endif
20198 }
20199 
20200 /*
20201  * ip_unbind is called when a copy of an unbind request is received from the
20202  * upper level protocol.  We remove this conn from any fanout hash list it is
20203  * on, and zero out the bind information.  No reply is expected up above.
20204  */
20205 mblk_t *
20206 ip_unbind(queue_t *q, mblk_t *mp)
20207 {
20208 	conn_t	*connp = Q_TO_CONN(q);
20209 
20210 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20211 
20212 	if (is_system_labeled() && connp->conn_anon_port) {
20213 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20214 		    connp->conn_mlp_type, connp->conn_ulp,
20215 		    ntohs(connp->conn_lport), B_FALSE);
20216 		connp->conn_anon_port = 0;
20217 	}
20218 	connp->conn_mlp_type = mlptSingle;
20219 
20220 	ipcl_hash_remove(connp);
20221 
20222 	ASSERT(mp->b_cont == NULL);
20223 	/*
20224 	 * Convert mp into a T_OK_ACK
20225 	 */
20226 	mp = mi_tpi_ok_ack_alloc(mp);
20227 
20228 	/*
20229 	 * should not happen in practice... T_OK_ACK is smaller than the
20230 	 * original message.
20231 	 */
20232 	if (mp == NULL)
20233 		return (NULL);
20234 
20235 	/*
20236 	 * Don't bzero the ports if its TCP since TCP still needs the
20237 	 * lport to remove it from its own bind hash. TCP will do the
20238 	 * cleanup.
20239 	 */
20240 	if (!IPCL_IS_TCP(connp))
20241 		bzero(&connp->u_port, sizeof (connp->u_port));
20242 
20243 	return (mp);
20244 }
20245 
20246 /*
20247  * Write side put procedure.  Outbound data, IOCTLs, responses from
20248  * resolvers, etc, come down through here.
20249  *
20250  * arg2 is always a queue_t *.
20251  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20252  * the zoneid.
20253  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20254  */
20255 void
20256 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20257 {
20258 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20259 }
20260 
20261 void
20262 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20263     ip_opt_info_t *infop)
20264 {
20265 	conn_t		*connp = NULL;
20266 	queue_t		*q = (queue_t *)arg2;
20267 	ipha_t		*ipha;
20268 #define	rptr	((uchar_t *)ipha)
20269 	ire_t		*ire = NULL;
20270 	ire_t		*sctp_ire = NULL;
20271 	uint32_t	v_hlen_tos_len;
20272 	ipaddr_t	dst;
20273 	mblk_t		*first_mp = NULL;
20274 	boolean_t	mctl_present;
20275 	ipsec_out_t	*io;
20276 	int		match_flags;
20277 	ill_t		*attach_ill = NULL;
20278 					/* Bind to IPIF_NOFAILOVER ill etc. */
20279 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20280 	ipif_t		*dst_ipif;
20281 	boolean_t	multirt_need_resolve = B_FALSE;
20282 	mblk_t		*copy_mp = NULL;
20283 	int		err;
20284 	zoneid_t	zoneid;
20285 	int	adjust;
20286 	uint16_t iplen;
20287 	boolean_t	need_decref = B_FALSE;
20288 	boolean_t	ignore_dontroute = B_FALSE;
20289 	boolean_t	ignore_nexthop = B_FALSE;
20290 	boolean_t	ip_nexthop = B_FALSE;
20291 	ipaddr_t	nexthop_addr;
20292 	ip_stack_t	*ipst;
20293 
20294 #ifdef	_BIG_ENDIAN
20295 #define	V_HLEN	(v_hlen_tos_len >> 24)
20296 #else
20297 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20298 #endif
20299 
20300 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20301 	    "ip_wput_start: q %p", q);
20302 
20303 	/*
20304 	 * ip_wput fast path
20305 	 */
20306 
20307 	/* is packet from ARP ? */
20308 	if (q->q_next != NULL) {
20309 		zoneid = (zoneid_t)(uintptr_t)arg;
20310 		goto qnext;
20311 	}
20312 
20313 	connp = (conn_t *)arg;
20314 	ASSERT(connp != NULL);
20315 	zoneid = connp->conn_zoneid;
20316 	ipst = connp->conn_netstack->netstack_ip;
20317 
20318 	/* is queue flow controlled? */
20319 	if ((q->q_first != NULL || connp->conn_draining) &&
20320 	    (caller == IP_WPUT)) {
20321 		ASSERT(!need_decref);
20322 		(void) putq(q, mp);
20323 		return;
20324 	}
20325 
20326 	/* Multidata transmit? */
20327 	if (DB_TYPE(mp) == M_MULTIDATA) {
20328 		/*
20329 		 * We should never get here, since all Multidata messages
20330 		 * originating from tcp should have been directed over to
20331 		 * tcp_multisend() in the first place.
20332 		 */
20333 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20334 		freemsg(mp);
20335 		return;
20336 	} else if (DB_TYPE(mp) != M_DATA)
20337 		goto notdata;
20338 
20339 	if (mp->b_flag & MSGHASREF) {
20340 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20341 		mp->b_flag &= ~MSGHASREF;
20342 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20343 		need_decref = B_TRUE;
20344 	}
20345 	ipha = (ipha_t *)mp->b_rptr;
20346 
20347 	/* is IP header non-aligned or mblk smaller than basic IP header */
20348 #ifndef SAFETY_BEFORE_SPEED
20349 	if (!OK_32PTR(rptr) ||
20350 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20351 		goto hdrtoosmall;
20352 #endif
20353 
20354 	ASSERT(OK_32PTR(ipha));
20355 
20356 	/*
20357 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20358 	 * wrong version, we'll catch it again in ip_output_v6.
20359 	 *
20360 	 * Note that this is *only* locally-generated output here, and never
20361 	 * forwarded data, and that we need to deal only with transports that
20362 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20363 	 * label.)
20364 	 */
20365 	if (is_system_labeled() &&
20366 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20367 	    !connp->conn_ulp_labeled) {
20368 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20369 		    connp->conn_mac_exempt, ipst);
20370 		ipha = (ipha_t *)mp->b_rptr;
20371 		if (err != 0) {
20372 			first_mp = mp;
20373 			if (err == EINVAL)
20374 				goto icmp_parameter_problem;
20375 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20376 			goto discard_pkt;
20377 		}
20378 		iplen = ntohs(ipha->ipha_length) + adjust;
20379 		ipha->ipha_length = htons(iplen);
20380 	}
20381 
20382 	ASSERT(infop != NULL);
20383 
20384 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20385 		/*
20386 		 * IP_PKTINFO ancillary option is present.
20387 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20388 		 * allows using address of any zone as the source address.
20389 		 */
20390 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20391 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20392 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20393 		if (ire == NULL)
20394 			goto drop_pkt;
20395 		ire_refrele(ire);
20396 		ire = NULL;
20397 	}
20398 
20399 	/*
20400 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20401 	 * ill index passed in IP_PKTINFO.
20402 	 */
20403 	if (infop->ip_opt_ill_index != 0 &&
20404 	    connp->conn_xmit_if_ill == NULL &&
20405 	    connp->conn_nofailover_ill == NULL) {
20406 
20407 		xmit_ill = ill_lookup_on_ifindex(
20408 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20409 		    ipst);
20410 
20411 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20412 			goto drop_pkt;
20413 		/*
20414 		 * check that there is an ipif belonging
20415 		 * to our zone. IPCL_ZONEID is not used because
20416 		 * IP_ALLZONES option is valid only when the ill is
20417 		 * accessible from all zones i.e has a valid ipif in
20418 		 * all zones.
20419 		 */
20420 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20421 			goto drop_pkt;
20422 		}
20423 	}
20424 
20425 	/*
20426 	 * If there is a policy, try to attach an ipsec_out in
20427 	 * the front. At the end, first_mp either points to a
20428 	 * M_DATA message or IPSEC_OUT message linked to a
20429 	 * M_DATA message. We have to do it now as we might
20430 	 * lose the "conn" if we go through ip_newroute.
20431 	 */
20432 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20433 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
20434 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20435 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20436 			if (need_decref)
20437 				CONN_DEC_REF(connp);
20438 			return;
20439 		} else {
20440 			ASSERT(mp->b_datap->db_type == M_CTL);
20441 			first_mp = mp;
20442 			mp = mp->b_cont;
20443 			mctl_present = B_TRUE;
20444 		}
20445 	} else {
20446 		first_mp = mp;
20447 		mctl_present = B_FALSE;
20448 	}
20449 
20450 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20451 
20452 	/* is wrong version or IP options present */
20453 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20454 		goto version_hdrlen_check;
20455 	dst = ipha->ipha_dst;
20456 
20457 	if (connp->conn_nofailover_ill != NULL) {
20458 		attach_ill = conn_get_held_ill(connp,
20459 		    &connp->conn_nofailover_ill, &err);
20460 		if (err == ILL_LOOKUP_FAILED) {
20461 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20462 			if (need_decref)
20463 				CONN_DEC_REF(connp);
20464 			freemsg(first_mp);
20465 			return;
20466 		}
20467 	}
20468 
20469 
20470 	/* is packet multicast? */
20471 	if (CLASSD(dst))
20472 		goto multicast;
20473 
20474 	/*
20475 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20476 	 * takes precedence over conn_dontroute and conn_nexthop_set
20477 	 */
20478 	if (xmit_ill != NULL) {
20479 		goto send_from_ill;
20480 	}
20481 
20482 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20483 	    (connp->conn_nexthop_set)) {
20484 		/*
20485 		 * If the destination is a broadcast or a loopback
20486 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20487 		 * through the standard path. But in the case of local
20488 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20489 		 * the standard path not IP_XMIT_IF.
20490 		 */
20491 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20492 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20493 		    (ire->ire_type != IRE_LOOPBACK))) {
20494 			if ((connp->conn_dontroute ||
20495 			    connp->conn_nexthop_set) && (ire != NULL) &&
20496 			    (ire->ire_type == IRE_LOCAL))
20497 				goto standard_path;
20498 
20499 			if (ire != NULL) {
20500 				ire_refrele(ire);
20501 				/* No more access to ire */
20502 				ire = NULL;
20503 			}
20504 			/*
20505 			 * bypass routing checks and go directly to
20506 			 * interface.
20507 			 */
20508 			if (connp->conn_dontroute) {
20509 				goto dontroute;
20510 			} else if (connp->conn_nexthop_set) {
20511 				ip_nexthop = B_TRUE;
20512 				nexthop_addr = connp->conn_nexthop_v4;
20513 				goto send_from_ill;
20514 			}
20515 
20516 			/*
20517 			 * If IP_XMIT_IF socket option is set,
20518 			 * then we allow unicast and multicast
20519 			 * packets to go through the ill. It is
20520 			 * quite possible that the destination
20521 			 * is not in the ire cache table and we
20522 			 * do not want to go to ip_newroute()
20523 			 * instead we call ip_newroute_ipif.
20524 			 */
20525 			xmit_ill = conn_get_held_ill(connp,
20526 			    &connp->conn_xmit_if_ill, &err);
20527 			if (err == ILL_LOOKUP_FAILED) {
20528 				BUMP_MIB(&ipst->ips_ip_mib,
20529 				    ipIfStatsOutDiscards);
20530 				if (attach_ill != NULL)
20531 					ill_refrele(attach_ill);
20532 				if (need_decref)
20533 					CONN_DEC_REF(connp);
20534 				freemsg(first_mp);
20535 				return;
20536 			}
20537 			goto send_from_ill;
20538 		}
20539 standard_path:
20540 		/* Must be a broadcast, a loopback or a local ire */
20541 		if (ire != NULL) {
20542 			ire_refrele(ire);
20543 			/* No more access to ire */
20544 			ire = NULL;
20545 		}
20546 	}
20547 
20548 	if (attach_ill != NULL)
20549 		goto send_from_ill;
20550 
20551 	/*
20552 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20553 	 * this for the tcp global queue and listen end point
20554 	 * as it does not really have a real destination to
20555 	 * talk to.  This is also true for SCTP.
20556 	 */
20557 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20558 	    !connp->conn_fully_bound) {
20559 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20560 		if (ire == NULL)
20561 			goto noirefound;
20562 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20563 		    "ip_wput_end: q %p (%S)", q, "end");
20564 
20565 		/*
20566 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20567 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20568 		 */
20569 		if (ire->ire_flags & RTF_MULTIRT) {
20570 
20571 			/*
20572 			 * Force the TTL of multirouted packets if required.
20573 			 * The TTL of such packets is bounded by the
20574 			 * ip_multirt_ttl ndd variable.
20575 			 */
20576 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20577 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20578 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20579 				    "(was %d), dst 0x%08x\n",
20580 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20581 				    ntohl(ire->ire_addr)));
20582 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20583 			}
20584 			/*
20585 			 * We look at this point if there are pending
20586 			 * unresolved routes. ire_multirt_resolvable()
20587 			 * checks in O(n) that all IRE_OFFSUBNET ire
20588 			 * entries for the packet's destination and
20589 			 * flagged RTF_MULTIRT are currently resolved.
20590 			 * If some remain unresolved, we make a copy
20591 			 * of the current message. It will be used
20592 			 * to initiate additional route resolutions.
20593 			 */
20594 			multirt_need_resolve =
20595 			    ire_multirt_need_resolve(ire->ire_addr,
20596 			    MBLK_GETLABEL(first_mp), ipst);
20597 			ip2dbg(("ip_wput[TCP]: ire %p, "
20598 			    "multirt_need_resolve %d, first_mp %p\n",
20599 			    (void *)ire, multirt_need_resolve,
20600 			    (void *)first_mp));
20601 			if (multirt_need_resolve) {
20602 				copy_mp = copymsg(first_mp);
20603 				if (copy_mp != NULL) {
20604 					MULTIRT_DEBUG_TAG(copy_mp);
20605 				}
20606 			}
20607 		}
20608 
20609 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20610 
20611 		/*
20612 		 * Try to resolve another multiroute if
20613 		 * ire_multirt_need_resolve() deemed it necessary.
20614 		 */
20615 		if (copy_mp != NULL) {
20616 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20617 		}
20618 		if (need_decref)
20619 			CONN_DEC_REF(connp);
20620 		return;
20621 	}
20622 
20623 	/*
20624 	 * Access to conn_ire_cache. (protected by conn_lock)
20625 	 *
20626 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20627 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20628 	 * send a packet or two with the IRE_CACHE that is going away.
20629 	 * Access to the ire requires an ire refhold on the ire prior to
20630 	 * its use since an interface unplumb thread may delete the cached
20631 	 * ire and release the refhold at any time.
20632 	 *
20633 	 * Caching an ire in the conn_ire_cache
20634 	 *
20635 	 * o Caching an ire pointer in the conn requires a strict check for
20636 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20637 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20638 	 * in the conn is done after making sure under the bucket lock that the
20639 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20640 	 * caching an ire after the unplumb thread has cleaned up the conn.
20641 	 * If the conn does not send a packet subsequently the unplumb thread
20642 	 * will be hanging waiting for the ire count to drop to zero.
20643 	 *
20644 	 * o We also need to atomically test for a null conn_ire_cache and
20645 	 * set the conn_ire_cache under the the protection of the conn_lock
20646 	 * to avoid races among concurrent threads trying to simultaneously
20647 	 * cache an ire in the conn_ire_cache.
20648 	 */
20649 	mutex_enter(&connp->conn_lock);
20650 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20651 
20652 	if (ire != NULL && ire->ire_addr == dst &&
20653 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20654 
20655 		IRE_REFHOLD(ire);
20656 		mutex_exit(&connp->conn_lock);
20657 
20658 	} else {
20659 		boolean_t cached = B_FALSE;
20660 		connp->conn_ire_cache = NULL;
20661 		mutex_exit(&connp->conn_lock);
20662 		/* Release the old ire */
20663 		if (ire != NULL && sctp_ire == NULL)
20664 			IRE_REFRELE_NOTR(ire);
20665 
20666 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20667 		if (ire == NULL)
20668 			goto noirefound;
20669 		IRE_REFHOLD_NOTR(ire);
20670 
20671 		mutex_enter(&connp->conn_lock);
20672 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20673 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20674 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20675 				connp->conn_ire_cache = ire;
20676 				cached = B_TRUE;
20677 			}
20678 			rw_exit(&ire->ire_bucket->irb_lock);
20679 		}
20680 		mutex_exit(&connp->conn_lock);
20681 
20682 		/*
20683 		 * We can continue to use the ire but since it was
20684 		 * not cached, we should drop the extra reference.
20685 		 */
20686 		if (!cached)
20687 			IRE_REFRELE_NOTR(ire);
20688 	}
20689 
20690 
20691 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20692 	    "ip_wput_end: q %p (%S)", q, "end");
20693 
20694 	/*
20695 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20696 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20697 	 */
20698 	if (ire->ire_flags & RTF_MULTIRT) {
20699 
20700 		/*
20701 		 * Force the TTL of multirouted packets if required.
20702 		 * The TTL of such packets is bounded by the
20703 		 * ip_multirt_ttl ndd variable.
20704 		 */
20705 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20706 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20707 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20708 			    "(was %d), dst 0x%08x\n",
20709 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20710 			    ntohl(ire->ire_addr)));
20711 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20712 		}
20713 
20714 		/*
20715 		 * At this point, we check to see if there are any pending
20716 		 * unresolved routes. ire_multirt_resolvable()
20717 		 * checks in O(n) that all IRE_OFFSUBNET ire
20718 		 * entries for the packet's destination and
20719 		 * flagged RTF_MULTIRT are currently resolved.
20720 		 * If some remain unresolved, we make a copy
20721 		 * of the current message. It will be used
20722 		 * to initiate additional route resolutions.
20723 		 */
20724 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20725 		    MBLK_GETLABEL(first_mp), ipst);
20726 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20727 		    "multirt_need_resolve %d, first_mp %p\n",
20728 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20729 		if (multirt_need_resolve) {
20730 			copy_mp = copymsg(first_mp);
20731 			if (copy_mp != NULL) {
20732 				MULTIRT_DEBUG_TAG(copy_mp);
20733 			}
20734 		}
20735 	}
20736 
20737 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20738 
20739 	/*
20740 	 * Try to resolve another multiroute if
20741 	 * ire_multirt_resolvable() deemed it necessary
20742 	 */
20743 	if (copy_mp != NULL) {
20744 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20745 	}
20746 	if (need_decref)
20747 		CONN_DEC_REF(connp);
20748 	return;
20749 
20750 qnext:
20751 	/*
20752 	 * Upper Level Protocols pass down complete IP datagrams
20753 	 * as M_DATA messages.	Everything else is a sideshow.
20754 	 *
20755 	 * 1) We could be re-entering ip_wput because of ip_neworute
20756 	 *    in which case we could have a IPSEC_OUT message. We
20757 	 *    need to pass through ip_wput like other datagrams and
20758 	 *    hence cannot branch to ip_wput_nondata.
20759 	 *
20760 	 * 2) ARP, AH, ESP, and other clients who are on the module
20761 	 *    instance of IP stream, give us something to deal with.
20762 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20763 	 *
20764 	 * 3) ICMP replies also could come here.
20765 	 */
20766 	ipst = ILLQ_TO_IPST(q);
20767 
20768 	if (DB_TYPE(mp) != M_DATA) {
20769 	    notdata:
20770 		if (DB_TYPE(mp) == M_CTL) {
20771 			/*
20772 			 * M_CTL messages are used by ARP, AH and ESP to
20773 			 * communicate with IP. We deal with IPSEC_IN and
20774 			 * IPSEC_OUT here. ip_wput_nondata handles other
20775 			 * cases.
20776 			 */
20777 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20778 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20779 				first_mp = mp->b_cont;
20780 				first_mp->b_flag &= ~MSGHASREF;
20781 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20782 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20783 				CONN_DEC_REF(connp);
20784 				connp = NULL;
20785 			}
20786 			if (ii->ipsec_info_type == IPSEC_IN) {
20787 				/*
20788 				 * Either this message goes back to
20789 				 * IPSEC for further processing or to
20790 				 * ULP after policy checks.
20791 				 */
20792 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20793 				return;
20794 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20795 				io = (ipsec_out_t *)ii;
20796 				if (io->ipsec_out_proc_begin) {
20797 					/*
20798 					 * IPSEC processing has already started.
20799 					 * Complete it.
20800 					 * IPQoS notes: We don't care what is
20801 					 * in ipsec_out_ill_index since this
20802 					 * won't be processed for IPQoS policies
20803 					 * in ipsec_out_process.
20804 					 */
20805 					ipsec_out_process(q, mp, NULL,
20806 					    io->ipsec_out_ill_index);
20807 					return;
20808 				} else {
20809 					connp = (q->q_next != NULL) ?
20810 					    NULL : Q_TO_CONN(q);
20811 					first_mp = mp;
20812 					mp = mp->b_cont;
20813 					mctl_present = B_TRUE;
20814 				}
20815 				zoneid = io->ipsec_out_zoneid;
20816 				ASSERT(zoneid != ALL_ZONES);
20817 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20818 				/*
20819 				 * It's an IPsec control message requesting
20820 				 * an SADB update to be sent to the IPsec
20821 				 * hardware acceleration capable ills.
20822 				 */
20823 				ipsec_ctl_t *ipsec_ctl =
20824 				    (ipsec_ctl_t *)mp->b_rptr;
20825 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20826 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20827 				mblk_t *cmp = mp->b_cont;
20828 
20829 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20830 				ASSERT(cmp != NULL);
20831 
20832 				freeb(mp);
20833 				ill_ipsec_capab_send_all(satype, cmp, sa,
20834 				    ipst->ips_netstack);
20835 				return;
20836 			} else {
20837 				/*
20838 				 * This must be ARP or special TSOL signaling.
20839 				 */
20840 				ip_wput_nondata(NULL, q, mp, NULL);
20841 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20842 				    "ip_wput_end: q %p (%S)", q, "nondata");
20843 				return;
20844 			}
20845 		} else {
20846 			/*
20847 			 * This must be non-(ARP/AH/ESP) messages.
20848 			 */
20849 			ASSERT(!need_decref);
20850 			ip_wput_nondata(NULL, q, mp, NULL);
20851 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20852 			    "ip_wput_end: q %p (%S)", q, "nondata");
20853 			return;
20854 		}
20855 	} else {
20856 		first_mp = mp;
20857 		mctl_present = B_FALSE;
20858 	}
20859 
20860 	ASSERT(first_mp != NULL);
20861 	/*
20862 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20863 	 * to make sure that this packet goes out on the same interface it
20864 	 * came in. We handle that here.
20865 	 */
20866 	if (mctl_present) {
20867 		uint_t ifindex;
20868 
20869 		io = (ipsec_out_t *)first_mp->b_rptr;
20870 		if (io->ipsec_out_attach_if ||
20871 		    io->ipsec_out_xmit_if ||
20872 		    io->ipsec_out_ip_nexthop) {
20873 			ill_t	*ill;
20874 
20875 			/*
20876 			 * We may have lost the conn context if we are
20877 			 * coming here from ip_newroute(). Copy the
20878 			 * nexthop information.
20879 			 */
20880 			if (io->ipsec_out_ip_nexthop) {
20881 				ip_nexthop = B_TRUE;
20882 				nexthop_addr = io->ipsec_out_nexthop_addr;
20883 
20884 				ipha = (ipha_t *)mp->b_rptr;
20885 				dst = ipha->ipha_dst;
20886 				goto send_from_ill;
20887 			} else {
20888 				ASSERT(io->ipsec_out_ill_index != 0);
20889 				ifindex = io->ipsec_out_ill_index;
20890 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20891 				    NULL, NULL, NULL, NULL, ipst);
20892 				/*
20893 				 * ipsec_out_xmit_if bit is used to tell
20894 				 * ip_wput to use the ill to send outgoing data
20895 				 * as we have no conn when data comes from ICMP
20896 				 * error msg routines. Currently this feature is
20897 				 * only used by ip_mrtun_forward routine.
20898 				 */
20899 				if (io->ipsec_out_xmit_if) {
20900 					xmit_ill = ill;
20901 					if (xmit_ill == NULL) {
20902 						ip1dbg(("ip_output:bad ifindex "
20903 						    "for xmit_ill %d\n",
20904 						    ifindex));
20905 						freemsg(first_mp);
20906 						BUMP_MIB(&ipst->ips_ip_mib,
20907 						    ipIfStatsOutDiscards);
20908 						ASSERT(!need_decref);
20909 						return;
20910 					}
20911 					/* Free up the ipsec_out_t mblk */
20912 					ASSERT(first_mp->b_cont == mp);
20913 					first_mp->b_cont = NULL;
20914 					freeb(first_mp);
20915 					/* Just send the IP header+ICMP+data */
20916 					first_mp = mp;
20917 					ipha = (ipha_t *)mp->b_rptr;
20918 					dst = ipha->ipha_dst;
20919 					goto send_from_ill;
20920 				} else {
20921 					attach_ill = ill;
20922 				}
20923 
20924 				if (attach_ill == NULL) {
20925 					ASSERT(xmit_ill == NULL);
20926 					ip1dbg(("ip_output: bad ifindex for "
20927 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20928 					    ifindex));
20929 					freemsg(first_mp);
20930 					BUMP_MIB(&ipst->ips_ip_mib,
20931 					    ipIfStatsOutDiscards);
20932 					ASSERT(!need_decref);
20933 					return;
20934 				}
20935 			}
20936 		}
20937 	}
20938 
20939 	ASSERT(xmit_ill == NULL);
20940 
20941 	/* We have a complete IP datagram heading outbound. */
20942 	ipha = (ipha_t *)mp->b_rptr;
20943 
20944 #ifndef SPEED_BEFORE_SAFETY
20945 	/*
20946 	 * Make sure we have a full-word aligned message and that at least
20947 	 * a simple IP header is accessible in the first message.  If not,
20948 	 * try a pullup.
20949 	 */
20950 	if (!OK_32PTR(rptr) ||
20951 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20952 	    hdrtoosmall:
20953 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20954 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20955 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20956 			if (first_mp == NULL)
20957 				first_mp = mp;
20958 			goto discard_pkt;
20959 		}
20960 
20961 		/* This function assumes that mp points to an IPv4 packet. */
20962 		if (is_system_labeled() && q->q_next == NULL &&
20963 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20964 		    !connp->conn_ulp_labeled) {
20965 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20966 			    &adjust, connp->conn_mac_exempt, ipst);
20967 			ipha = (ipha_t *)mp->b_rptr;
20968 			if (first_mp != NULL)
20969 				first_mp->b_cont = mp;
20970 			if (err != 0) {
20971 				if (first_mp == NULL)
20972 					first_mp = mp;
20973 				if (err == EINVAL)
20974 					goto icmp_parameter_problem;
20975 				ip2dbg(("ip_wput: label check failed (%d)\n",
20976 				    err));
20977 				goto discard_pkt;
20978 			}
20979 			iplen = ntohs(ipha->ipha_length) + adjust;
20980 			ipha->ipha_length = htons(iplen);
20981 		}
20982 
20983 		ipha = (ipha_t *)mp->b_rptr;
20984 		if (first_mp == NULL) {
20985 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20986 			/*
20987 			 * If we got here because of "goto hdrtoosmall"
20988 			 * We need to attach a IPSEC_OUT.
20989 			 */
20990 			if (connp->conn_out_enforce_policy) {
20991 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20992 				    NULL, ipha->ipha_protocol,
20993 				    ipst->ips_netstack)) == NULL)) {
20994 					BUMP_MIB(&ipst->ips_ip_mib,
20995 					    ipIfStatsOutDiscards);
20996 					if (need_decref)
20997 						CONN_DEC_REF(connp);
20998 					return;
20999 				} else {
21000 					ASSERT(mp->b_datap->db_type == M_CTL);
21001 					first_mp = mp;
21002 					mp = mp->b_cont;
21003 					mctl_present = B_TRUE;
21004 				}
21005 			} else {
21006 				first_mp = mp;
21007 				mctl_present = B_FALSE;
21008 			}
21009 		}
21010 	}
21011 #endif
21012 
21013 	/* Most of the code below is written for speed, not readability */
21014 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21015 
21016 	/*
21017 	 * If ip_newroute() fails, we're going to need a full
21018 	 * header for the icmp wraparound.
21019 	 */
21020 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21021 		uint_t	v_hlen;
21022 	    version_hdrlen_check:
21023 		ASSERT(first_mp != NULL);
21024 		v_hlen = V_HLEN;
21025 		/*
21026 		 * siphon off IPv6 packets coming down from transport
21027 		 * layer modules here.
21028 		 * Note: high-order bit carries NUD reachability confirmation
21029 		 */
21030 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21031 			/*
21032 			 * XXX implement a IPv4 and IPv6 packet counter per
21033 			 * conn and switch when ratio exceeds e.g. 10:1
21034 			 */
21035 #ifdef notyet
21036 			if (q->q_next == NULL) /* Avoid ill queue */
21037 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
21038 #endif
21039 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21040 			ASSERT(xmit_ill == NULL);
21041 			if (attach_ill != NULL)
21042 				ill_refrele(attach_ill);
21043 			if (need_decref)
21044 				mp->b_flag |= MSGHASREF;
21045 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21046 			return;
21047 		}
21048 
21049 		if ((v_hlen >> 4) != IP_VERSION) {
21050 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21051 			    "ip_wput_end: q %p (%S)", q, "badvers");
21052 			goto discard_pkt;
21053 		}
21054 		/*
21055 		 * Is the header length at least 20 bytes?
21056 		 *
21057 		 * Are there enough bytes accessible in the header?  If
21058 		 * not, try a pullup.
21059 		 */
21060 		v_hlen &= 0xF;
21061 		v_hlen <<= 2;
21062 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21063 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21064 			    "ip_wput_end: q %p (%S)", q, "badlen");
21065 			goto discard_pkt;
21066 		}
21067 		if (v_hlen > (mp->b_wptr - rptr)) {
21068 			if (!pullupmsg(mp, v_hlen)) {
21069 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21070 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21071 				goto discard_pkt;
21072 			}
21073 			ipha = (ipha_t *)mp->b_rptr;
21074 		}
21075 		/*
21076 		 * Move first entry from any source route into ipha_dst and
21077 		 * verify the options
21078 		 */
21079 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21080 			zoneid, ipst)) {
21081 			ASSERT(xmit_ill == NULL);
21082 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21083 			if (attach_ill != NULL)
21084 				ill_refrele(attach_ill);
21085 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21086 			    "ip_wput_end: q %p (%S)", q, "badopts");
21087 			if (need_decref)
21088 				CONN_DEC_REF(connp);
21089 			return;
21090 		}
21091 	}
21092 	dst = ipha->ipha_dst;
21093 
21094 	/*
21095 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21096 	 * we have to run the packet through ip_newroute which will take
21097 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21098 	 * a resolver, or assigning a default gateway, etc.
21099 	 */
21100 	if (CLASSD(dst)) {
21101 		ipif_t	*ipif;
21102 		uint32_t setsrc = 0;
21103 
21104 	    multicast:
21105 		ASSERT(first_mp != NULL);
21106 		ip2dbg(("ip_wput: CLASSD\n"));
21107 		if (connp == NULL) {
21108 			/*
21109 			 * Use the first good ipif on the ill.
21110 			 * XXX Should this ever happen? (Appears
21111 			 * to show up with just ppp and no ethernet due
21112 			 * to in.rdisc.)
21113 			 * However, ire_send should be able to
21114 			 * call ip_wput_ire directly.
21115 			 *
21116 			 * XXX Also, this can happen for ICMP and other packets
21117 			 * with multicast source addresses.  Perhaps we should
21118 			 * fix things so that we drop the packet in question,
21119 			 * but for now, just run with it.
21120 			 */
21121 			ill_t *ill = (ill_t *)q->q_ptr;
21122 
21123 			/*
21124 			 * Don't honor attach_if for this case. If ill
21125 			 * is part of the group, ipif could belong to
21126 			 * any ill and we cannot maintain attach_ill
21127 			 * and ipif_ill same anymore and the assert
21128 			 * below would fail.
21129 			 */
21130 			if (mctl_present && io->ipsec_out_attach_if) {
21131 				io->ipsec_out_ill_index = 0;
21132 				io->ipsec_out_attach_if = B_FALSE;
21133 				ASSERT(attach_ill != NULL);
21134 				ill_refrele(attach_ill);
21135 				attach_ill = NULL;
21136 			}
21137 
21138 			ASSERT(attach_ill == NULL);
21139 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21140 			if (ipif == NULL) {
21141 				if (need_decref)
21142 					CONN_DEC_REF(connp);
21143 				freemsg(first_mp);
21144 				return;
21145 			}
21146 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21147 			    ntohl(dst), ill->ill_name));
21148 		} else {
21149 			/*
21150 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21151 			 * and IP_MULTICAST_IF.
21152 			 * Block comment above this function explains the
21153 			 * locking mechanism used here
21154 			 */
21155 			if (xmit_ill == NULL) {
21156 				xmit_ill = conn_get_held_ill(connp,
21157 				    &connp->conn_xmit_if_ill, &err);
21158 				if (err == ILL_LOOKUP_FAILED) {
21159 					ip1dbg(("ip_wput: No ill for "
21160 					    "IP_XMIT_IF\n"));
21161 					BUMP_MIB(&ipst->ips_ip_mib,
21162 					    ipIfStatsOutNoRoutes);
21163 					goto drop_pkt;
21164 				}
21165 			}
21166 
21167 			if (xmit_ill == NULL) {
21168 				ipif = conn_get_held_ipif(connp,
21169 				    &connp->conn_multicast_ipif, &err);
21170 				if (err == IPIF_LOOKUP_FAILED) {
21171 					ip1dbg(("ip_wput: No ipif for "
21172 					    "multicast\n"));
21173 					BUMP_MIB(&ipst->ips_ip_mib,
21174 					    ipIfStatsOutNoRoutes);
21175 					goto drop_pkt;
21176 				}
21177 			}
21178 			if (xmit_ill != NULL) {
21179 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21180 				if (ipif == NULL) {
21181 					ip1dbg(("ip_wput: No ipif for "
21182 					    "IP_XMIT_IF\n"));
21183 					BUMP_MIB(&ipst->ips_ip_mib,
21184 					    ipIfStatsOutNoRoutes);
21185 					goto drop_pkt;
21186 				}
21187 			} else if (ipif == NULL || ipif->ipif_isv6) {
21188 				/*
21189 				 * We must do this ipif determination here
21190 				 * else we could pass through ip_newroute
21191 				 * and come back here without the conn context.
21192 				 *
21193 				 * Note: we do late binding i.e. we bind to
21194 				 * the interface when the first packet is sent.
21195 				 * For performance reasons we do not rebind on
21196 				 * each packet but keep the binding until the
21197 				 * next IP_MULTICAST_IF option.
21198 				 *
21199 				 * conn_multicast_{ipif,ill} are shared between
21200 				 * IPv4 and IPv6 and AF_INET6 sockets can
21201 				 * send both IPv4 and IPv6 packets. Hence
21202 				 * we have to check that "isv6" matches above.
21203 				 */
21204 				if (ipif != NULL)
21205 					ipif_refrele(ipif);
21206 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21207 				if (ipif == NULL) {
21208 					ip1dbg(("ip_wput: No ipif for "
21209 					    "multicast\n"));
21210 					BUMP_MIB(&ipst->ips_ip_mib,
21211 					    ipIfStatsOutNoRoutes);
21212 					goto drop_pkt;
21213 				}
21214 				err = conn_set_held_ipif(connp,
21215 				    &connp->conn_multicast_ipif, ipif);
21216 				if (err == IPIF_LOOKUP_FAILED) {
21217 					ipif_refrele(ipif);
21218 					ip1dbg(("ip_wput: No ipif for "
21219 					    "multicast\n"));
21220 					BUMP_MIB(&ipst->ips_ip_mib,
21221 					    ipIfStatsOutNoRoutes);
21222 					goto drop_pkt;
21223 				}
21224 			}
21225 		}
21226 		ASSERT(!ipif->ipif_isv6);
21227 		/*
21228 		 * As we may lose the conn by the time we reach ip_wput_ire,
21229 		 * we copy conn_multicast_loop and conn_dontroute on to an
21230 		 * ipsec_out. In case if this datagram goes out secure,
21231 		 * we need the ill_index also. Copy that also into the
21232 		 * ipsec_out.
21233 		 */
21234 		if (mctl_present) {
21235 			io = (ipsec_out_t *)first_mp->b_rptr;
21236 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21237 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21238 		} else {
21239 			ASSERT(mp == first_mp);
21240 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21241 			    BPRI_HI)) == NULL) {
21242 				ipif_refrele(ipif);
21243 				first_mp = mp;
21244 				goto discard_pkt;
21245 			}
21246 			first_mp->b_datap->db_type = M_CTL;
21247 			first_mp->b_wptr += sizeof (ipsec_info_t);
21248 			/* ipsec_out_secure is B_FALSE now */
21249 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21250 			io = (ipsec_out_t *)first_mp->b_rptr;
21251 			io->ipsec_out_type = IPSEC_OUT;
21252 			io->ipsec_out_len = sizeof (ipsec_out_t);
21253 			io->ipsec_out_use_global_policy = B_TRUE;
21254 			io->ipsec_out_ns = ipst->ips_netstack;
21255 			first_mp->b_cont = mp;
21256 			mctl_present = B_TRUE;
21257 		}
21258 		if (attach_ill != NULL) {
21259 			ASSERT(attach_ill == ipif->ipif_ill);
21260 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21261 
21262 			/*
21263 			 * Check if we need an ire that will not be
21264 			 * looked up by anybody else i.e. HIDDEN.
21265 			 */
21266 			if (ill_is_probeonly(attach_ill)) {
21267 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21268 			}
21269 			io->ipsec_out_ill_index =
21270 			    attach_ill->ill_phyint->phyint_ifindex;
21271 			io->ipsec_out_attach_if = B_TRUE;
21272 		} else {
21273 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21274 			io->ipsec_out_ill_index =
21275 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21276 		}
21277 		if (connp != NULL) {
21278 			io->ipsec_out_multicast_loop =
21279 			    connp->conn_multicast_loop;
21280 			io->ipsec_out_dontroute = connp->conn_dontroute;
21281 			io->ipsec_out_zoneid = connp->conn_zoneid;
21282 		}
21283 		/*
21284 		 * If the application uses IP_MULTICAST_IF with
21285 		 * different logical addresses of the same ILL, we
21286 		 * need to make sure that the soruce address of
21287 		 * the packet matches the logical IP address used
21288 		 * in the option. We do it by initializing ipha_src
21289 		 * here. This should keep IPSEC also happy as
21290 		 * when we return from IPSEC processing, we don't
21291 		 * have to worry about getting the right address on
21292 		 * the packet. Thus it is sufficient to look for
21293 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21294 		 * MATCH_IRE_IPIF.
21295 		 *
21296 		 * NOTE : We need to do it for non-secure case also as
21297 		 * this might go out secure if there is a global policy
21298 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21299 		 * address, the source should be initialized already and
21300 		 * hence we won't be initializing here.
21301 		 *
21302 		 * As we do not have the ire yet, it is possible that
21303 		 * we set the source address here and then later discover
21304 		 * that the ire implies the source address to be assigned
21305 		 * through the RTF_SETSRC flag.
21306 		 * In that case, the setsrc variable will remind us
21307 		 * that overwritting the source address by the one
21308 		 * of the RTF_SETSRC-flagged ire is allowed.
21309 		 */
21310 		if (ipha->ipha_src == INADDR_ANY &&
21311 		    (connp == NULL || !connp->conn_unspec_src)) {
21312 			ipha->ipha_src = ipif->ipif_src_addr;
21313 			setsrc = RTF_SETSRC;
21314 		}
21315 		/*
21316 		 * Find an IRE which matches the destination and the outgoing
21317 		 * queue (i.e. the outgoing interface.)
21318 		 * For loopback use a unicast IP address for
21319 		 * the ire lookup.
21320 		 */
21321 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
21322 		    PHYI_LOOPBACK) {
21323 			dst = ipif->ipif_lcl_addr;
21324 		}
21325 		/*
21326 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21327 		 * We don't need to lookup ire in ctable as the packet
21328 		 * needs to be sent to the destination through the specified
21329 		 * ill irrespective of ires in the cache table.
21330 		 */
21331 		ire = NULL;
21332 		if (xmit_ill == NULL) {
21333 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21334 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21335 		}
21336 
21337 		/*
21338 		 * refrele attach_ill as its not needed anymore.
21339 		 */
21340 		if (attach_ill != NULL) {
21341 			ill_refrele(attach_ill);
21342 			attach_ill = NULL;
21343 		}
21344 
21345 		if (ire == NULL) {
21346 			/*
21347 			 * Multicast loopback and multicast forwarding is
21348 			 * done in ip_wput_ire.
21349 			 *
21350 			 * Mark this packet to make it be delivered to
21351 			 * ip_wput_ire after the new ire has been
21352 			 * created.
21353 			 *
21354 			 * The call to ip_newroute_ipif takes into account
21355 			 * the setsrc reminder. In any case, we take care
21356 			 * of the RTF_MULTIRT flag.
21357 			 */
21358 			mp->b_prev = mp->b_next = NULL;
21359 			if (xmit_ill == NULL ||
21360 			    xmit_ill->ill_ipif_up_count > 0) {
21361 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21362 				    setsrc | RTF_MULTIRT, zoneid, infop);
21363 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21364 				    "ip_wput_end: q %p (%S)", q, "noire");
21365 			} else {
21366 				freemsg(first_mp);
21367 			}
21368 			ipif_refrele(ipif);
21369 			if (xmit_ill != NULL)
21370 				ill_refrele(xmit_ill);
21371 			if (need_decref)
21372 				CONN_DEC_REF(connp);
21373 			return;
21374 		}
21375 
21376 		ipif_refrele(ipif);
21377 		ipif = NULL;
21378 		ASSERT(xmit_ill == NULL);
21379 
21380 		/*
21381 		 * Honor the RTF_SETSRC flag for multicast packets,
21382 		 * if allowed by the setsrc reminder.
21383 		 */
21384 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21385 			ipha->ipha_src = ire->ire_src_addr;
21386 		}
21387 
21388 		/*
21389 		 * Unconditionally force the TTL to 1 for
21390 		 * multirouted multicast packets:
21391 		 * multirouted multicast should not cross
21392 		 * multicast routers.
21393 		 */
21394 		if (ire->ire_flags & RTF_MULTIRT) {
21395 			if (ipha->ipha_ttl > 1) {
21396 				ip2dbg(("ip_wput: forcing multicast "
21397 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21398 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21399 				ipha->ipha_ttl = 1;
21400 			}
21401 		}
21402 	} else {
21403 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21404 		if ((ire != NULL) && (ire->ire_type &
21405 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21406 			ignore_dontroute = B_TRUE;
21407 			ignore_nexthop = B_TRUE;
21408 		}
21409 		if (ire != NULL) {
21410 			ire_refrele(ire);
21411 			ire = NULL;
21412 		}
21413 		/*
21414 		 * Guard against coming in from arp in which case conn is NULL.
21415 		 * Also guard against non M_DATA with dontroute set but
21416 		 * destined to local, loopback or broadcast addresses.
21417 		 */
21418 		if (connp != NULL && connp->conn_dontroute &&
21419 		    !ignore_dontroute) {
21420 dontroute:
21421 			/*
21422 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21423 			 * routing protocols from seeing false direct
21424 			 * connectivity.
21425 			 */
21426 			ipha->ipha_ttl = 1;
21427 			/*
21428 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21429 			 * along with SO_DONTROUTE, higher precedence is
21430 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21431 			 */
21432 			if (connp->conn_xmit_if_ill == NULL) {
21433 				/* If suitable ipif not found, drop packet */
21434 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21435 				    ipst);
21436 				if (dst_ipif == NULL) {
21437 					ip1dbg(("ip_wput: no route for "
21438 					    "dst using SO_DONTROUTE\n"));
21439 					BUMP_MIB(&ipst->ips_ip_mib,
21440 					    ipIfStatsOutNoRoutes);
21441 					mp->b_prev = mp->b_next = NULL;
21442 					if (first_mp == NULL)
21443 						first_mp = mp;
21444 					goto drop_pkt;
21445 				} else {
21446 					/*
21447 					 * If suitable ipif has been found, set
21448 					 * xmit_ill to the corresponding
21449 					 * ipif_ill because we'll be following
21450 					 * the IP_XMIT_IF logic.
21451 					 */
21452 					ASSERT(xmit_ill == NULL);
21453 					xmit_ill = dst_ipif->ipif_ill;
21454 					mutex_enter(&xmit_ill->ill_lock);
21455 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21456 						mutex_exit(&xmit_ill->ill_lock);
21457 						xmit_ill = NULL;
21458 						ipif_refrele(dst_ipif);
21459 						ip1dbg(("ip_wput: no route for"
21460 						    " dst using"
21461 						    " SO_DONTROUTE\n"));
21462 						BUMP_MIB(&ipst->ips_ip_mib,
21463 						    ipIfStatsOutNoRoutes);
21464 						mp->b_prev = mp->b_next = NULL;
21465 						if (first_mp == NULL)
21466 							first_mp = mp;
21467 						goto drop_pkt;
21468 					}
21469 					ill_refhold_locked(xmit_ill);
21470 					mutex_exit(&xmit_ill->ill_lock);
21471 					ipif_refrele(dst_ipif);
21472 				}
21473 			}
21474 
21475 		}
21476 		/*
21477 		 * If we are bound to IPIF_NOFAILOVER address, look for
21478 		 * an IRE_CACHE matching the ill.
21479 		 */
21480 send_from_ill:
21481 		if (attach_ill != NULL) {
21482 			ipif_t	*attach_ipif;
21483 
21484 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21485 
21486 			/*
21487 			 * Check if we need an ire that will not be
21488 			 * looked up by anybody else i.e. HIDDEN.
21489 			 */
21490 			if (ill_is_probeonly(attach_ill)) {
21491 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21492 			}
21493 
21494 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21495 			if (attach_ipif == NULL) {
21496 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21497 				goto discard_pkt;
21498 			}
21499 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21500 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21501 			ipif_refrele(attach_ipif);
21502 		} else if (xmit_ill != NULL || (connp != NULL &&
21503 			    connp->conn_xmit_if_ill != NULL)) {
21504 			/*
21505 			 * Mark this packet as originated locally
21506 			 */
21507 			mp->b_prev = mp->b_next = NULL;
21508 			/*
21509 			 * xmit_ill could be NULL if SO_DONTROUTE
21510 			 * is also set.
21511 			 */
21512 			if (xmit_ill == NULL) {
21513 				xmit_ill = conn_get_held_ill(connp,
21514 				    &connp->conn_xmit_if_ill, &err);
21515 				if (err == ILL_LOOKUP_FAILED) {
21516 					BUMP_MIB(&ipst->ips_ip_mib,
21517 					    ipIfStatsOutDiscards);
21518 					if (need_decref)
21519 						CONN_DEC_REF(connp);
21520 					freemsg(first_mp);
21521 					return;
21522 				}
21523 				if (xmit_ill == NULL) {
21524 					if (connp->conn_dontroute)
21525 						goto dontroute;
21526 					goto send_from_ill;
21527 				}
21528 			}
21529 			/*
21530 			 * Could be SO_DONTROUTE case also.
21531 			 * check at least one interface is UP as
21532 			 * specified by this ILL
21533 			 */
21534 			if (xmit_ill->ill_ipif_up_count > 0) {
21535 				ipif_t *ipif;
21536 
21537 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21538 				if (ipif == NULL) {
21539 					ip1dbg(("ip_output: "
21540 					    "xmit_ill NULL ipif\n"));
21541 					goto drop_pkt;
21542 				}
21543 				/*
21544 				 * Look for a ire that is part of the group,
21545 				 * if found use it else call ip_newroute_ipif.
21546 				 * IPCL_ZONEID is not used for matching because
21547 				 * IP_ALLZONES option is valid only when the
21548 				 * ill is accessible from all zones i.e has a
21549 				 * valid ipif in all zones.
21550 				 */
21551 				match_flags = MATCH_IRE_ILL_GROUP |
21552 				    MATCH_IRE_SECATTR;
21553 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21554 				    MBLK_GETLABEL(mp), match_flags, ipst);
21555 				/*
21556 				 * If an ire exists use it or else create
21557 				 * an ire but don't add it to the cache.
21558 				 * Adding an ire may cause issues with
21559 				 * asymmetric routing.
21560 				 * In case of multiroute always act as if
21561 				 * ire does not exist.
21562 				 */
21563 				if (ire == NULL ||
21564 				    ire->ire_flags & RTF_MULTIRT) {
21565 					if (ire != NULL)
21566 						ire_refrele(ire);
21567 					ip_newroute_ipif(q, first_mp, ipif,
21568 					    dst, connp, 0, zoneid, infop);
21569 					ipif_refrele(ipif);
21570 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21571 					ill_refrele(xmit_ill);
21572 					if (need_decref)
21573 						CONN_DEC_REF(connp);
21574 					return;
21575 				}
21576 				ipif_refrele(ipif);
21577 			} else {
21578 				goto drop_pkt;
21579 			}
21580 		} else if (ip_nexthop || (connp != NULL &&
21581 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21582 			if (!ip_nexthop) {
21583 				ip_nexthop = B_TRUE;
21584 				nexthop_addr = connp->conn_nexthop_v4;
21585 			}
21586 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21587 			    MATCH_IRE_GW;
21588 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21589 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21590 		} else {
21591 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21592 			    ipst);
21593 		}
21594 		if (!ire) {
21595 			/*
21596 			 * Make sure we don't load spread if this
21597 			 * is IPIF_NOFAILOVER case.
21598 			 */
21599 			if ((attach_ill != NULL) ||
21600 			    (ip_nexthop && !ignore_nexthop)) {
21601 				if (mctl_present) {
21602 					io = (ipsec_out_t *)first_mp->b_rptr;
21603 					ASSERT(first_mp->b_datap->db_type ==
21604 					    M_CTL);
21605 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21606 				} else {
21607 					ASSERT(mp == first_mp);
21608 					first_mp = allocb(
21609 					    sizeof (ipsec_info_t), BPRI_HI);
21610 					if (first_mp == NULL) {
21611 						first_mp = mp;
21612 						goto discard_pkt;
21613 					}
21614 					first_mp->b_datap->db_type = M_CTL;
21615 					first_mp->b_wptr +=
21616 					    sizeof (ipsec_info_t);
21617 					/* ipsec_out_secure is B_FALSE now */
21618 					bzero(first_mp->b_rptr,
21619 					    sizeof (ipsec_info_t));
21620 					io = (ipsec_out_t *)first_mp->b_rptr;
21621 					io->ipsec_out_type = IPSEC_OUT;
21622 					io->ipsec_out_len =
21623 					    sizeof (ipsec_out_t);
21624 					io->ipsec_out_use_global_policy =
21625 					    B_TRUE;
21626 					io->ipsec_out_ns = ipst->ips_netstack;
21627 					first_mp->b_cont = mp;
21628 					mctl_present = B_TRUE;
21629 				}
21630 				if (attach_ill != NULL) {
21631 					io->ipsec_out_ill_index = attach_ill->
21632 					    ill_phyint->phyint_ifindex;
21633 					io->ipsec_out_attach_if = B_TRUE;
21634 				} else {
21635 					io->ipsec_out_ip_nexthop = ip_nexthop;
21636 					io->ipsec_out_nexthop_addr =
21637 					    nexthop_addr;
21638 				}
21639 			}
21640 noirefound:
21641 			/*
21642 			 * Mark this packet as having originated on
21643 			 * this machine.  This will be noted in
21644 			 * ire_add_then_send, which needs to know
21645 			 * whether to run it back through ip_wput or
21646 			 * ip_rput following successful resolution.
21647 			 */
21648 			mp->b_prev = NULL;
21649 			mp->b_next = NULL;
21650 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21651 			    ipst);
21652 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21653 			    "ip_wput_end: q %p (%S)", q, "newroute");
21654 			if (attach_ill != NULL)
21655 				ill_refrele(attach_ill);
21656 			if (xmit_ill != NULL)
21657 				ill_refrele(xmit_ill);
21658 			if (need_decref)
21659 				CONN_DEC_REF(connp);
21660 			return;
21661 		}
21662 	}
21663 
21664 	/* We now know where we are going with it. */
21665 
21666 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21667 	    "ip_wput_end: q %p (%S)", q, "end");
21668 
21669 	/*
21670 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21671 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21672 	 */
21673 	if (ire->ire_flags & RTF_MULTIRT) {
21674 		/*
21675 		 * Force the TTL of multirouted packets if required.
21676 		 * The TTL of such packets is bounded by the
21677 		 * ip_multirt_ttl ndd variable.
21678 		 */
21679 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21680 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21681 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21682 			    "(was %d), dst 0x%08x\n",
21683 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21684 			    ntohl(ire->ire_addr)));
21685 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21686 		}
21687 		/*
21688 		 * At this point, we check to see if there are any pending
21689 		 * unresolved routes. ire_multirt_resolvable()
21690 		 * checks in O(n) that all IRE_OFFSUBNET ire
21691 		 * entries for the packet's destination and
21692 		 * flagged RTF_MULTIRT are currently resolved.
21693 		 * If some remain unresolved, we make a copy
21694 		 * of the current message. It will be used
21695 		 * to initiate additional route resolutions.
21696 		 */
21697 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21698 		    MBLK_GETLABEL(first_mp), ipst);
21699 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21700 		    "multirt_need_resolve %d, first_mp %p\n",
21701 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21702 		if (multirt_need_resolve) {
21703 			copy_mp = copymsg(first_mp);
21704 			if (copy_mp != NULL) {
21705 				MULTIRT_DEBUG_TAG(copy_mp);
21706 			}
21707 		}
21708 	}
21709 
21710 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21711 	/*
21712 	 * Try to resolve another multiroute if
21713 	 * ire_multirt_resolvable() deemed it necessary.
21714 	 * At this point, we need to distinguish
21715 	 * multicasts from other packets. For multicasts,
21716 	 * we call ip_newroute_ipif() and request that both
21717 	 * multirouting and setsrc flags are checked.
21718 	 */
21719 	if (copy_mp != NULL) {
21720 		if (CLASSD(dst)) {
21721 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21722 			if (ipif) {
21723 				ASSERT(infop->ip_opt_ill_index == 0);
21724 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21725 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21726 				ipif_refrele(ipif);
21727 			} else {
21728 				MULTIRT_DEBUG_UNTAG(copy_mp);
21729 				freemsg(copy_mp);
21730 				copy_mp = NULL;
21731 			}
21732 		} else {
21733 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21734 		}
21735 	}
21736 	if (attach_ill != NULL)
21737 		ill_refrele(attach_ill);
21738 	if (xmit_ill != NULL)
21739 		ill_refrele(xmit_ill);
21740 	if (need_decref)
21741 		CONN_DEC_REF(connp);
21742 	return;
21743 
21744 icmp_parameter_problem:
21745 	/* could not have originated externally */
21746 	ASSERT(mp->b_prev == NULL);
21747 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21748 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21749 		/* it's the IP header length that's in trouble */
21750 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21751 		first_mp = NULL;
21752 	}
21753 
21754 discard_pkt:
21755 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21756 drop_pkt:
21757 	ip1dbg(("ip_wput: dropped packet\n"));
21758 	if (ire != NULL)
21759 		ire_refrele(ire);
21760 	if (need_decref)
21761 		CONN_DEC_REF(connp);
21762 	freemsg(first_mp);
21763 	if (attach_ill != NULL)
21764 		ill_refrele(attach_ill);
21765 	if (xmit_ill != NULL)
21766 		ill_refrele(xmit_ill);
21767 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21768 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21769 }
21770 
21771 /*
21772  * If this is a conn_t queue, then we pass in the conn. This includes the
21773  * zoneid.
21774  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21775  * in which case we use the global zoneid since those are all part of
21776  * the global zone.
21777  */
21778 void
21779 ip_wput(queue_t *q, mblk_t *mp)
21780 {
21781 	if (CONN_Q(q))
21782 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21783 	else
21784 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21785 }
21786 
21787 /*
21788  *
21789  * The following rules must be observed when accessing any ipif or ill
21790  * that has been cached in the conn. Typically conn_nofailover_ill,
21791  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21792  *
21793  * Access: The ipif or ill pointed to from the conn can be accessed under
21794  * the protection of the conn_lock or after it has been refheld under the
21795  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21796  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21797  * The reason for this is that a concurrent unplumb could actually be
21798  * cleaning up these cached pointers by walking the conns and might have
21799  * finished cleaning up the conn in question. The macros check that an
21800  * unplumb has not yet started on the ipif or ill.
21801  *
21802  * Caching: An ipif or ill pointer may be cached in the conn only after
21803  * making sure that an unplumb has not started. So the caching is done
21804  * while holding both the conn_lock and the ill_lock and after using the
21805  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21806  * flag before starting the cleanup of conns.
21807  *
21808  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21809  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21810  * or a reference to the ipif or a reference to an ire that references the
21811  * ipif. An ipif does not change its ill except for failover/failback. Since
21812  * failover/failback happens only after bringing down the ipif and making sure
21813  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21814  * the above holds.
21815  */
21816 ipif_t *
21817 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21818 {
21819 	ipif_t	*ipif;
21820 	ill_t	*ill;
21821 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21822 
21823 	*err = 0;
21824 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21825 	mutex_enter(&connp->conn_lock);
21826 	ipif = *ipifp;
21827 	if (ipif != NULL) {
21828 		ill = ipif->ipif_ill;
21829 		mutex_enter(&ill->ill_lock);
21830 		if (IPIF_CAN_LOOKUP(ipif)) {
21831 			ipif_refhold_locked(ipif);
21832 			mutex_exit(&ill->ill_lock);
21833 			mutex_exit(&connp->conn_lock);
21834 			rw_exit(&ipst->ips_ill_g_lock);
21835 			return (ipif);
21836 		} else {
21837 			*err = IPIF_LOOKUP_FAILED;
21838 		}
21839 		mutex_exit(&ill->ill_lock);
21840 	}
21841 	mutex_exit(&connp->conn_lock);
21842 	rw_exit(&ipst->ips_ill_g_lock);
21843 	return (NULL);
21844 }
21845 
21846 ill_t *
21847 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21848 {
21849 	ill_t	*ill;
21850 
21851 	*err = 0;
21852 	mutex_enter(&connp->conn_lock);
21853 	ill = *illp;
21854 	if (ill != NULL) {
21855 		mutex_enter(&ill->ill_lock);
21856 		if (ILL_CAN_LOOKUP(ill)) {
21857 			ill_refhold_locked(ill);
21858 			mutex_exit(&ill->ill_lock);
21859 			mutex_exit(&connp->conn_lock);
21860 			return (ill);
21861 		} else {
21862 			*err = ILL_LOOKUP_FAILED;
21863 		}
21864 		mutex_exit(&ill->ill_lock);
21865 	}
21866 	mutex_exit(&connp->conn_lock);
21867 	return (NULL);
21868 }
21869 
21870 static int
21871 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21872 {
21873 	ill_t	*ill;
21874 
21875 	ill = ipif->ipif_ill;
21876 	mutex_enter(&connp->conn_lock);
21877 	mutex_enter(&ill->ill_lock);
21878 	if (IPIF_CAN_LOOKUP(ipif)) {
21879 		*ipifp = ipif;
21880 		mutex_exit(&ill->ill_lock);
21881 		mutex_exit(&connp->conn_lock);
21882 		return (0);
21883 	}
21884 	mutex_exit(&ill->ill_lock);
21885 	mutex_exit(&connp->conn_lock);
21886 	return (IPIF_LOOKUP_FAILED);
21887 }
21888 
21889 /*
21890  * This is called if the outbound datagram needs fragmentation.
21891  *
21892  * NOTE : This function does not ire_refrele the ire argument passed in.
21893  */
21894 static void
21895 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21896     ip_stack_t *ipst)
21897 {
21898 	ipha_t		*ipha;
21899 	mblk_t		*mp;
21900 	uint32_t	v_hlen_tos_len;
21901 	uint32_t	max_frag;
21902 	uint32_t	frag_flag;
21903 	boolean_t	dont_use;
21904 
21905 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21906 		mp = ipsec_mp->b_cont;
21907 	} else {
21908 		mp = ipsec_mp;
21909 	}
21910 
21911 	ipha = (ipha_t *)mp->b_rptr;
21912 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21913 
21914 #ifdef	_BIG_ENDIAN
21915 #define	V_HLEN	(v_hlen_tos_len >> 24)
21916 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21917 #else
21918 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21919 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21920 #endif
21921 
21922 #ifndef SPEED_BEFORE_SAFETY
21923 	/*
21924 	 * Check that ipha_length is consistent with
21925 	 * the mblk length
21926 	 */
21927 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21928 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21929 		    LENGTH, msgdsize(mp)));
21930 		freemsg(ipsec_mp);
21931 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21932 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21933 		    "packet length mismatch");
21934 		return;
21935 	}
21936 #endif
21937 	/*
21938 	 * Don't use frag_flag if pre-built packet or source
21939 	 * routed or if multicast (since multicast packets do not solicit
21940 	 * ICMP "packet too big" messages). Get the values of
21941 	 * max_frag and frag_flag atomically by acquiring the
21942 	 * ire_lock.
21943 	 */
21944 	mutex_enter(&ire->ire_lock);
21945 	max_frag = ire->ire_max_frag;
21946 	frag_flag = ire->ire_frag_flag;
21947 	mutex_exit(&ire->ire_lock);
21948 
21949 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21950 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21951 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21952 
21953 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21954 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21955 }
21956 
21957 /*
21958  * Used for deciding the MSS size for the upper layer. Thus
21959  * we need to check the outbound policy values in the conn.
21960  */
21961 int
21962 conn_ipsec_length(conn_t *connp)
21963 {
21964 	ipsec_latch_t *ipl;
21965 
21966 	ipl = connp->conn_latch;
21967 	if (ipl == NULL)
21968 		return (0);
21969 
21970 	if (ipl->ipl_out_policy == NULL)
21971 		return (0);
21972 
21973 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21974 }
21975 
21976 /*
21977  * Returns an estimate of the IPSEC headers size. This is used if
21978  * we don't want to call into IPSEC to get the exact size.
21979  */
21980 int
21981 ipsec_out_extra_length(mblk_t *ipsec_mp)
21982 {
21983 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21984 	ipsec_action_t *a;
21985 
21986 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21987 	if (!io->ipsec_out_secure)
21988 		return (0);
21989 
21990 	a = io->ipsec_out_act;
21991 
21992 	if (a == NULL) {
21993 		ASSERT(io->ipsec_out_policy != NULL);
21994 		a = io->ipsec_out_policy->ipsp_act;
21995 	}
21996 	ASSERT(a != NULL);
21997 
21998 	return (a->ipa_ovhd);
21999 }
22000 
22001 /*
22002  * Returns an estimate of the IPSEC headers size. This is used if
22003  * we don't want to call into IPSEC to get the exact size.
22004  */
22005 int
22006 ipsec_in_extra_length(mblk_t *ipsec_mp)
22007 {
22008 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22009 	ipsec_action_t *a;
22010 
22011 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22012 
22013 	a = ii->ipsec_in_action;
22014 	return (a == NULL ? 0 : a->ipa_ovhd);
22015 }
22016 
22017 /*
22018  * If there are any source route options, return the true final
22019  * destination. Otherwise, return the destination.
22020  */
22021 ipaddr_t
22022 ip_get_dst(ipha_t *ipha)
22023 {
22024 	ipoptp_t	opts;
22025 	uchar_t		*opt;
22026 	uint8_t		optval;
22027 	uint8_t		optlen;
22028 	ipaddr_t	dst;
22029 	uint32_t off;
22030 
22031 	dst = ipha->ipha_dst;
22032 
22033 	if (IS_SIMPLE_IPH(ipha))
22034 		return (dst);
22035 
22036 	for (optval = ipoptp_first(&opts, ipha);
22037 	    optval != IPOPT_EOL;
22038 	    optval = ipoptp_next(&opts)) {
22039 		opt = opts.ipoptp_cur;
22040 		optlen = opts.ipoptp_len;
22041 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22042 		switch (optval) {
22043 		case IPOPT_SSRR:
22044 		case IPOPT_LSRR:
22045 			off = opt[IPOPT_OFFSET];
22046 			/*
22047 			 * If one of the conditions is true, it means
22048 			 * end of options and dst already has the right
22049 			 * value.
22050 			 */
22051 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22052 				off = optlen - IP_ADDR_LEN;
22053 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22054 			}
22055 			return (dst);
22056 		default:
22057 			break;
22058 		}
22059 	}
22060 
22061 	return (dst);
22062 }
22063 
22064 mblk_t *
22065 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22066     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22067 {
22068 	ipsec_out_t	*io;
22069 	mblk_t		*first_mp;
22070 	boolean_t policy_present;
22071 	ip_stack_t	*ipst;
22072 	ipsec_stack_t	*ipss;
22073 
22074 	ASSERT(ire != NULL);
22075 	ipst = ire->ire_ipst;
22076 	ipss = ipst->ips_netstack->netstack_ipsec;
22077 
22078 	first_mp = mp;
22079 	if (mp->b_datap->db_type == M_CTL) {
22080 		io = (ipsec_out_t *)first_mp->b_rptr;
22081 		/*
22082 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22083 		 *
22084 		 * 1) There is per-socket policy (including cached global
22085 		 *    policy) or a policy on the IP-in-IP tunnel.
22086 		 * 2) There is no per-socket policy, but it is
22087 		 *    a multicast packet that needs to go out
22088 		 *    on a specific interface. This is the case
22089 		 *    where (ip_wput and ip_wput_multicast) attaches
22090 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22091 		 *
22092 		 * In case (2) we check with global policy to
22093 		 * see if there is a match and set the ill_index
22094 		 * appropriately so that we can lookup the ire
22095 		 * properly in ip_wput_ipsec_out.
22096 		 */
22097 
22098 		/*
22099 		 * ipsec_out_use_global_policy is set to B_FALSE
22100 		 * in ipsec_in_to_out(). Refer to that function for
22101 		 * details.
22102 		 */
22103 		if ((io->ipsec_out_latch == NULL) &&
22104 		    (io->ipsec_out_use_global_policy)) {
22105 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22106 				    ire, connp, unspec_src, zoneid));
22107 		}
22108 		if (!io->ipsec_out_secure) {
22109 			/*
22110 			 * If this is not a secure packet, drop
22111 			 * the IPSEC_OUT mp and treat it as a clear
22112 			 * packet. This happens when we are sending
22113 			 * a ICMP reply back to a clear packet. See
22114 			 * ipsec_in_to_out() for details.
22115 			 */
22116 			mp = first_mp->b_cont;
22117 			freeb(first_mp);
22118 		}
22119 		return (mp);
22120 	}
22121 	/*
22122 	 * See whether we need to attach a global policy here. We
22123 	 * don't depend on the conn (as it could be null) for deciding
22124 	 * what policy this datagram should go through because it
22125 	 * should have happened in ip_wput if there was some
22126 	 * policy. This normally happens for connections which are not
22127 	 * fully bound preventing us from caching policies in
22128 	 * ip_bind. Packets coming from the TCP listener/global queue
22129 	 * - which are non-hard_bound - could also be affected by
22130 	 * applying policy here.
22131 	 *
22132 	 * If this packet is coming from tcp global queue or listener,
22133 	 * we will be applying policy here.  This may not be *right*
22134 	 * if these packets are coming from the detached connection as
22135 	 * it could have gone in clear before. This happens only if a
22136 	 * TCP connection started when there is no policy and somebody
22137 	 * added policy before it became detached. Thus packets of the
22138 	 * detached connection could go out secure and the other end
22139 	 * would drop it because it will be expecting in clear. The
22140 	 * converse is not true i.e if somebody starts a TCP
22141 	 * connection and deletes the policy, all the packets will
22142 	 * still go out with the policy that existed before deleting
22143 	 * because ip_unbind sends up policy information which is used
22144 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22145 	 * TCP to attach a dummy IPSEC_OUT and set
22146 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22147 	 * affect performance for normal cases, we are not doing it.
22148 	 * Thus, set policy before starting any TCP connections.
22149 	 *
22150 	 * NOTE - We might apply policy even for a hard bound connection
22151 	 * - for which we cached policy in ip_bind - if somebody added
22152 	 * global policy after we inherited the policy in ip_bind.
22153 	 * This means that the packets that were going out in clear
22154 	 * previously would start going secure and hence get dropped
22155 	 * on the other side. To fix this, TCP attaches a dummy
22156 	 * ipsec_out and make sure that we don't apply global policy.
22157 	 */
22158 	if (ipha != NULL)
22159 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22160 	else
22161 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22162 	if (!policy_present)
22163 		return (mp);
22164 
22165 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22166 		    zoneid));
22167 }
22168 
22169 ire_t *
22170 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22171 {
22172 	ipaddr_t addr;
22173 	ire_t *save_ire;
22174 	irb_t *irb;
22175 	ill_group_t *illgrp;
22176 	int	err;
22177 
22178 	save_ire = ire;
22179 	addr = ire->ire_addr;
22180 
22181 	ASSERT(ire->ire_type == IRE_BROADCAST);
22182 
22183 	illgrp = connp->conn_outgoing_ill->ill_group;
22184 	if (illgrp == NULL) {
22185 		*conn_outgoing_ill = conn_get_held_ill(connp,
22186 		    &connp->conn_outgoing_ill, &err);
22187 		if (err == ILL_LOOKUP_FAILED) {
22188 			ire_refrele(save_ire);
22189 			return (NULL);
22190 		}
22191 		return (save_ire);
22192 	}
22193 	/*
22194 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22195 	 * If it is part of the group, we need to send on the ire
22196 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22197 	 * to this group. This is okay as IP_BOUND_IF really means
22198 	 * any ill in the group. We depend on the fact that the
22199 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22200 	 * if such an ire exists. This is possible only if you have
22201 	 * at least one ill in the group that has not failed.
22202 	 *
22203 	 * First get to the ire that matches the address and group.
22204 	 *
22205 	 * We don't look for an ire with a matching zoneid because a given zone
22206 	 * won't always have broadcast ires on all ills in the group.
22207 	 */
22208 	irb = ire->ire_bucket;
22209 	rw_enter(&irb->irb_lock, RW_READER);
22210 	if (ire->ire_marks & IRE_MARK_NORECV) {
22211 		/*
22212 		 * If the current zone only has an ire broadcast for this
22213 		 * address marked NORECV, the ire we want is ahead in the
22214 		 * bucket, so we look it up deliberately ignoring the zoneid.
22215 		 */
22216 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22217 			if (ire->ire_addr != addr)
22218 				continue;
22219 			/* skip over deleted ires */
22220 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22221 				continue;
22222 		}
22223 	}
22224 	while (ire != NULL) {
22225 		/*
22226 		 * If a new interface is coming up, we could end up
22227 		 * seeing the loopback ire and the non-loopback ire
22228 		 * may not have been added yet. So check for ire_stq
22229 		 */
22230 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22231 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22232 			break;
22233 		}
22234 		ire = ire->ire_next;
22235 	}
22236 	if (ire != NULL && ire->ire_addr == addr &&
22237 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22238 		IRE_REFHOLD(ire);
22239 		rw_exit(&irb->irb_lock);
22240 		ire_refrele(save_ire);
22241 		*conn_outgoing_ill = ire_to_ill(ire);
22242 		/*
22243 		 * Refhold the ill to make the conn_outgoing_ill
22244 		 * independent of the ire. ip_wput_ire goes in a loop
22245 		 * and may refrele the ire. Since we have an ire at this
22246 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22247 		 */
22248 		ill_refhold(*conn_outgoing_ill);
22249 		return (ire);
22250 	}
22251 	rw_exit(&irb->irb_lock);
22252 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22253 	/*
22254 	 * If we can't find a suitable ire, return the original ire.
22255 	 */
22256 	return (save_ire);
22257 }
22258 
22259 /*
22260  * This function does the ire_refrele of the ire passed in as the
22261  * argument. As this function looks up more ires i.e broadcast ires,
22262  * it needs to REFRELE them. Currently, for simplicity we don't
22263  * differentiate the one passed in and looked up here. We always
22264  * REFRELE.
22265  * IPQoS Notes:
22266  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22267  * IPSec packets are done in ipsec_out_process.
22268  *
22269  */
22270 void
22271 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22272     zoneid_t zoneid)
22273 {
22274 	ipha_t		*ipha;
22275 #define	rptr	((uchar_t *)ipha)
22276 	queue_t		*stq;
22277 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22278 	uint32_t	v_hlen_tos_len;
22279 	uint32_t	ttl_protocol;
22280 	ipaddr_t	src;
22281 	ipaddr_t	dst;
22282 	uint32_t	cksum;
22283 	ipaddr_t	orig_src;
22284 	ire_t		*ire1;
22285 	mblk_t		*next_mp;
22286 	uint_t		hlen;
22287 	uint16_t	*up;
22288 	uint32_t	max_frag = ire->ire_max_frag;
22289 	ill_t		*ill = ire_to_ill(ire);
22290 	int		clusterwide;
22291 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22292 	int		ipsec_len;
22293 	mblk_t		*first_mp;
22294 	ipsec_out_t	*io;
22295 	boolean_t	conn_dontroute;		/* conn value for multicast */
22296 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22297 	boolean_t	multicast_forward;	/* Should we forward ? */
22298 	boolean_t	unspec_src;
22299 	ill_t		*conn_outgoing_ill = NULL;
22300 	ill_t		*ire_ill;
22301 	ill_t		*ire1_ill;
22302 	ill_t		*out_ill;
22303 	uint32_t 	ill_index = 0;
22304 	boolean_t	multirt_send = B_FALSE;
22305 	int		err;
22306 	ipxmit_state_t	pktxmit_state;
22307 	ip_stack_t	*ipst = ire->ire_ipst;
22308 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22309 
22310 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22311 	    "ip_wput_ire_start: q %p", q);
22312 
22313 	multicast_forward = B_FALSE;
22314 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22315 
22316 	if (ire->ire_flags & RTF_MULTIRT) {
22317 		/*
22318 		 * Multirouting case. The bucket where ire is stored
22319 		 * probably holds other RTF_MULTIRT flagged ire
22320 		 * to the destination. In this call to ip_wput_ire,
22321 		 * we attempt to send the packet through all
22322 		 * those ires. Thus, we first ensure that ire is the
22323 		 * first RTF_MULTIRT ire in the bucket,
22324 		 * before walking the ire list.
22325 		 */
22326 		ire_t *first_ire;
22327 		irb_t *irb = ire->ire_bucket;
22328 		ASSERT(irb != NULL);
22329 
22330 		/* Make sure we do not omit any multiroute ire. */
22331 		IRB_REFHOLD(irb);
22332 		for (first_ire = irb->irb_ire;
22333 		    first_ire != NULL;
22334 		    first_ire = first_ire->ire_next) {
22335 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22336 			    (first_ire->ire_addr == ire->ire_addr) &&
22337 			    !(first_ire->ire_marks &
22338 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22339 				break;
22340 		}
22341 
22342 		if ((first_ire != NULL) && (first_ire != ire)) {
22343 			IRE_REFHOLD(first_ire);
22344 			ire_refrele(ire);
22345 			ire = first_ire;
22346 			ill = ire_to_ill(ire);
22347 		}
22348 		IRB_REFRELE(irb);
22349 	}
22350 
22351 	/*
22352 	 * conn_outgoing_ill is used only in the broadcast loop.
22353 	 * for performance we don't grab the mutexs in the fastpath
22354 	 */
22355 	if ((connp != NULL) &&
22356 	    (connp->conn_xmit_if_ill == NULL) &&
22357 	    (ire->ire_type == IRE_BROADCAST) &&
22358 	    ((connp->conn_nofailover_ill != NULL) ||
22359 	    (connp->conn_outgoing_ill != NULL))) {
22360 		/*
22361 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22362 		 * option. So, see if this endpoint is bound to a
22363 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22364 		 * that if the interface is failed, we will still send
22365 		 * the packet on the same ill which is what we want.
22366 		 */
22367 		conn_outgoing_ill = conn_get_held_ill(connp,
22368 		    &connp->conn_nofailover_ill, &err);
22369 		if (err == ILL_LOOKUP_FAILED) {
22370 			ire_refrele(ire);
22371 			freemsg(mp);
22372 			return;
22373 		}
22374 		if (conn_outgoing_ill == NULL) {
22375 			/*
22376 			 * Choose a good ill in the group to send the
22377 			 * packets on.
22378 			 */
22379 			ire = conn_set_outgoing_ill(connp, ire,
22380 			    &conn_outgoing_ill);
22381 			if (ire == NULL) {
22382 				freemsg(mp);
22383 				return;
22384 			}
22385 		}
22386 	}
22387 
22388 	if (mp->b_datap->db_type != M_CTL) {
22389 		ipha = (ipha_t *)mp->b_rptr;
22390 	} else {
22391 		io = (ipsec_out_t *)mp->b_rptr;
22392 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22393 		ASSERT(zoneid == io->ipsec_out_zoneid);
22394 		ASSERT(zoneid != ALL_ZONES);
22395 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22396 		dst = ipha->ipha_dst;
22397 		/*
22398 		 * For the multicast case, ipsec_out carries conn_dontroute and
22399 		 * conn_multicast_loop as conn may not be available here. We
22400 		 * need this for multicast loopback and forwarding which is done
22401 		 * later in the code.
22402 		 */
22403 		if (CLASSD(dst)) {
22404 			conn_dontroute = io->ipsec_out_dontroute;
22405 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22406 			/*
22407 			 * If conn_dontroute is not set or conn_multicast_loop
22408 			 * is set, we need to do forwarding/loopback. For
22409 			 * datagrams from ip_wput_multicast, conn_dontroute is
22410 			 * set to B_TRUE and conn_multicast_loop is set to
22411 			 * B_FALSE so that we neither do forwarding nor
22412 			 * loopback.
22413 			 */
22414 			if (!conn_dontroute || conn_multicast_loop)
22415 				multicast_forward = B_TRUE;
22416 		}
22417 	}
22418 
22419 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22420 	    ire->ire_zoneid != ALL_ZONES) {
22421 		/*
22422 		 * When a zone sends a packet to another zone, we try to deliver
22423 		 * the packet under the same conditions as if the destination
22424 		 * was a real node on the network. To do so, we look for a
22425 		 * matching route in the forwarding table.
22426 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22427 		 * ip_newroute() does.
22428 		 * Note that IRE_LOCAL are special, since they are used
22429 		 * when the zoneid doesn't match in some cases. This means that
22430 		 * we need to handle ipha_src differently since ire_src_addr
22431 		 * belongs to the receiving zone instead of the sending zone.
22432 		 * When ip_restrict_interzone_loopback is set, then
22433 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22434 		 * for loopback between zones when the logical "Ethernet" would
22435 		 * have looped them back.
22436 		 */
22437 		ire_t *src_ire;
22438 
22439 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22440 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22441 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22442 		if (src_ire != NULL &&
22443 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22444 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22445 		    ire_local_same_ill_group(ire, src_ire))) {
22446 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22447 				ipha->ipha_src = src_ire->ire_src_addr;
22448 			ire_refrele(src_ire);
22449 		} else {
22450 			ire_refrele(ire);
22451 			if (conn_outgoing_ill != NULL)
22452 				ill_refrele(conn_outgoing_ill);
22453 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22454 			if (src_ire != NULL) {
22455 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22456 					ire_refrele(src_ire);
22457 					freemsg(mp);
22458 					return;
22459 				}
22460 				ire_refrele(src_ire);
22461 			}
22462 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22463 				/* Failed */
22464 				freemsg(mp);
22465 				return;
22466 			}
22467 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22468 			    ipst);
22469 			return;
22470 		}
22471 	}
22472 
22473 	if (mp->b_datap->db_type == M_CTL ||
22474 	    ipss->ipsec_outbound_v4_policy_present) {
22475 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22476 		    unspec_src, zoneid);
22477 		if (mp == NULL) {
22478 			ire_refrele(ire);
22479 			if (conn_outgoing_ill != NULL)
22480 				ill_refrele(conn_outgoing_ill);
22481 			return;
22482 		}
22483 	}
22484 
22485 	first_mp = mp;
22486 	ipsec_len = 0;
22487 
22488 	if (first_mp->b_datap->db_type == M_CTL) {
22489 		io = (ipsec_out_t *)first_mp->b_rptr;
22490 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22491 		mp = first_mp->b_cont;
22492 		ipsec_len = ipsec_out_extra_length(first_mp);
22493 		ASSERT(ipsec_len >= 0);
22494 		/* We already picked up the zoneid from the M_CTL above */
22495 		ASSERT(zoneid == io->ipsec_out_zoneid);
22496 		ASSERT(zoneid != ALL_ZONES);
22497 
22498 		/*
22499 		 * Drop M_CTL here if IPsec processing is not needed.
22500 		 * (Non-IPsec use of M_CTL extracted any information it
22501 		 * needed above).
22502 		 */
22503 		if (ipsec_len == 0) {
22504 			freeb(first_mp);
22505 			first_mp = mp;
22506 		}
22507 	}
22508 
22509 	/*
22510 	 * Fast path for ip_wput_ire
22511 	 */
22512 
22513 	ipha = (ipha_t *)mp->b_rptr;
22514 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22515 	dst = ipha->ipha_dst;
22516 
22517 	/*
22518 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22519 	 * if the socket is a SOCK_RAW type. The transport checksum should
22520 	 * be provided in the pre-built packet, so we don't need to compute it.
22521 	 * Also, other application set flags, like DF, should not be altered.
22522 	 * Other transport MUST pass down zero.
22523 	 */
22524 	ip_hdr_included = ipha->ipha_ident;
22525 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22526 
22527 	if (CLASSD(dst)) {
22528 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22529 		    ntohl(dst),
22530 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22531 		    ntohl(ire->ire_addr)));
22532 	}
22533 
22534 /* Macros to extract header fields from data already in registers */
22535 #ifdef	_BIG_ENDIAN
22536 #define	V_HLEN	(v_hlen_tos_len >> 24)
22537 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22538 #define	PROTO	(ttl_protocol & 0xFF)
22539 #else
22540 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22541 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22542 #define	PROTO	(ttl_protocol >> 8)
22543 #endif
22544 
22545 
22546 	orig_src = src = ipha->ipha_src;
22547 	/* (The loop back to "another" is explained down below.) */
22548 another:;
22549 	/*
22550 	 * Assign an ident value for this packet.  We assign idents on
22551 	 * a per destination basis out of the IRE.  There could be
22552 	 * other threads targeting the same destination, so we have to
22553 	 * arrange for a atomic increment.  Note that we use a 32-bit
22554 	 * atomic add because it has better performance than its
22555 	 * 16-bit sibling.
22556 	 *
22557 	 * If running in cluster mode and if the source address
22558 	 * belongs to a replicated service then vector through
22559 	 * cl_inet_ipident vector to allocate ip identifier
22560 	 * NOTE: This is a contract private interface with the
22561 	 * clustering group.
22562 	 */
22563 	clusterwide = 0;
22564 	if (cl_inet_ipident) {
22565 		ASSERT(cl_inet_isclusterwide);
22566 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22567 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22568 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22569 			    AF_INET, (uint8_t *)(uintptr_t)src,
22570 			    (uint8_t *)(uintptr_t)dst);
22571 			clusterwide = 1;
22572 		}
22573 	}
22574 	if (!clusterwide) {
22575 		ipha->ipha_ident =
22576 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22577 	}
22578 
22579 #ifndef _BIG_ENDIAN
22580 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22581 #endif
22582 
22583 	/*
22584 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22585 	 * This is needed to obey conn_unspec_src when packets go through
22586 	 * ip_newroute + arp.
22587 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22588 	 */
22589 	if (src == INADDR_ANY && !unspec_src) {
22590 		/*
22591 		 * Assign the appropriate source address from the IRE if none
22592 		 * was specified.
22593 		 */
22594 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22595 
22596 		/*
22597 		 * With IP multipathing, broadcast packets are sent on the ire
22598 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22599 		 * the group. However, this ire might not be in the same zone so
22600 		 * we can't always use its source address. We look for a
22601 		 * broadcast ire in the same group and in the right zone.
22602 		 */
22603 		if (ire->ire_type == IRE_BROADCAST &&
22604 		    ire->ire_zoneid != zoneid) {
22605 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22606 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22607 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22608 			if (src_ire != NULL) {
22609 				src = src_ire->ire_src_addr;
22610 				ire_refrele(src_ire);
22611 			} else {
22612 				ire_refrele(ire);
22613 				if (conn_outgoing_ill != NULL)
22614 					ill_refrele(conn_outgoing_ill);
22615 				freemsg(first_mp);
22616 				if (ill != NULL) {
22617 					BUMP_MIB(ill->ill_ip_mib,
22618 					    ipIfStatsOutDiscards);
22619 				} else {
22620 					BUMP_MIB(&ipst->ips_ip_mib,
22621 					    ipIfStatsOutDiscards);
22622 				}
22623 				return;
22624 			}
22625 		} else {
22626 			src = ire->ire_src_addr;
22627 		}
22628 
22629 		if (connp == NULL) {
22630 			ip1dbg(("ip_wput_ire: no connp and no src "
22631 			    "address for dst 0x%x, using src 0x%x\n",
22632 			    ntohl(dst),
22633 			    ntohl(src)));
22634 		}
22635 		ipha->ipha_src = src;
22636 	}
22637 	stq = ire->ire_stq;
22638 
22639 	/*
22640 	 * We only allow ire chains for broadcasts since there will
22641 	 * be multiple IRE_CACHE entries for the same multicast
22642 	 * address (one per ipif).
22643 	 */
22644 	next_mp = NULL;
22645 
22646 	/* broadcast packet */
22647 	if (ire->ire_type == IRE_BROADCAST)
22648 		goto broadcast;
22649 
22650 	/* loopback ? */
22651 	if (stq == NULL)
22652 		goto nullstq;
22653 
22654 	/* The ill_index for outbound ILL */
22655 	ill_index = Q_TO_INDEX(stq);
22656 
22657 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22658 	ttl_protocol = ((uint16_t *)ipha)[4];
22659 
22660 	/* pseudo checksum (do it in parts for IP header checksum) */
22661 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22662 
22663 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22664 		queue_t *dev_q = stq->q_next;
22665 
22666 		/* flow controlled */
22667 		if ((dev_q->q_next || dev_q->q_first) &&
22668 		    !canput(dev_q))
22669 			goto blocked;
22670 		if ((PROTO == IPPROTO_UDP) &&
22671 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22672 			hlen = (V_HLEN & 0xF) << 2;
22673 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22674 			if (*up != 0) {
22675 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22676 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22677 				/* Software checksum? */
22678 				if (DB_CKSUMFLAGS(mp) == 0) {
22679 					IP_STAT(ipst, ip_out_sw_cksum);
22680 					IP_STAT_UPDATE(ipst,
22681 					    ip_udp_out_sw_cksum_bytes,
22682 					    LENGTH - hlen);
22683 				}
22684 			}
22685 		}
22686 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22687 		hlen = (V_HLEN & 0xF) << 2;
22688 		if (PROTO == IPPROTO_TCP) {
22689 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22690 			/*
22691 			 * The packet header is processed once and for all, even
22692 			 * in the multirouting case. We disable hardware
22693 			 * checksum if the packet is multirouted, as it will be
22694 			 * replicated via several interfaces, and not all of
22695 			 * them may have this capability.
22696 			 */
22697 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22698 			    LENGTH, max_frag, ipsec_len, cksum);
22699 			/* Software checksum? */
22700 			if (DB_CKSUMFLAGS(mp) == 0) {
22701 				IP_STAT(ipst, ip_out_sw_cksum);
22702 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22703 				    LENGTH - hlen);
22704 			}
22705 		} else {
22706 			sctp_hdr_t	*sctph;
22707 
22708 			ASSERT(PROTO == IPPROTO_SCTP);
22709 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22710 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22711 			/*
22712 			 * Zero out the checksum field to ensure proper
22713 			 * checksum calculation.
22714 			 */
22715 			sctph->sh_chksum = 0;
22716 #ifdef	DEBUG
22717 			if (!skip_sctp_cksum)
22718 #endif
22719 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22720 		}
22721 	}
22722 
22723 	/*
22724 	 * If this is a multicast packet and originated from ip_wput
22725 	 * we need to do loopback and forwarding checks. If it comes
22726 	 * from ip_wput_multicast, we SHOULD not do this.
22727 	 */
22728 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22729 
22730 	/* checksum */
22731 	cksum += ttl_protocol;
22732 
22733 	/* fragment the packet */
22734 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22735 		goto fragmentit;
22736 	/*
22737 	 * Don't use frag_flag if packet is pre-built or source
22738 	 * routed or if multicast (since multicast packets do
22739 	 * not solicit ICMP "packet too big" messages).
22740 	 */
22741 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22742 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22743 	    !ip_source_route_included(ipha)) &&
22744 	    !CLASSD(ipha->ipha_dst))
22745 		ipha->ipha_fragment_offset_and_flags |=
22746 		    htons(ire->ire_frag_flag);
22747 
22748 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22749 		/* calculate IP header checksum */
22750 		cksum += ipha->ipha_ident;
22751 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22752 		cksum += ipha->ipha_fragment_offset_and_flags;
22753 
22754 		/* IP options present */
22755 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22756 		if (hlen)
22757 			goto checksumoptions;
22758 
22759 		/* calculate hdr checksum */
22760 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22761 		cksum = ~(cksum + (cksum >> 16));
22762 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22763 	}
22764 	if (ipsec_len != 0) {
22765 		/*
22766 		 * We will do the rest of the processing after
22767 		 * we come back from IPSEC in ip_wput_ipsec_out().
22768 		 */
22769 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22770 
22771 		io = (ipsec_out_t *)first_mp->b_rptr;
22772 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22773 				ill_phyint->phyint_ifindex;
22774 
22775 		ipsec_out_process(q, first_mp, ire, ill_index);
22776 		ire_refrele(ire);
22777 		if (conn_outgoing_ill != NULL)
22778 			ill_refrele(conn_outgoing_ill);
22779 		return;
22780 	}
22781 
22782 	/*
22783 	 * In most cases, the emission loop below is entered only
22784 	 * once. Only in the case where the ire holds the
22785 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22786 	 * flagged ires in the bucket, and send the packet
22787 	 * through all crossed RTF_MULTIRT routes.
22788 	 */
22789 	if (ire->ire_flags & RTF_MULTIRT) {
22790 		multirt_send = B_TRUE;
22791 	}
22792 	do {
22793 		if (multirt_send) {
22794 			irb_t *irb;
22795 			/*
22796 			 * We are in a multiple send case, need to get
22797 			 * the next ire and make a duplicate of the packet.
22798 			 * ire1 holds here the next ire to process in the
22799 			 * bucket. If multirouting is expected,
22800 			 * any non-RTF_MULTIRT ire that has the
22801 			 * right destination address is ignored.
22802 			 */
22803 			irb = ire->ire_bucket;
22804 			ASSERT(irb != NULL);
22805 
22806 			IRB_REFHOLD(irb);
22807 			for (ire1 = ire->ire_next;
22808 			    ire1 != NULL;
22809 			    ire1 = ire1->ire_next) {
22810 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22811 					continue;
22812 				if (ire1->ire_addr != ire->ire_addr)
22813 					continue;
22814 				if (ire1->ire_marks &
22815 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22816 					continue;
22817 
22818 				/* Got one */
22819 				IRE_REFHOLD(ire1);
22820 				break;
22821 			}
22822 			IRB_REFRELE(irb);
22823 
22824 			if (ire1 != NULL) {
22825 				next_mp = copyb(mp);
22826 				if ((next_mp == NULL) ||
22827 				    ((mp->b_cont != NULL) &&
22828 				    ((next_mp->b_cont =
22829 				    dupmsg(mp->b_cont)) == NULL))) {
22830 					freemsg(next_mp);
22831 					next_mp = NULL;
22832 					ire_refrele(ire1);
22833 					ire1 = NULL;
22834 				}
22835 			}
22836 
22837 			/* Last multiroute ire; don't loop anymore. */
22838 			if (ire1 == NULL) {
22839 				multirt_send = B_FALSE;
22840 			}
22841 		}
22842 
22843 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22844 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22845 		    mblk_t *, mp);
22846 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22847 		    ipst->ips_ipv4firewall_physical_out,
22848 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22849 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22850 		if (mp == NULL)
22851 			goto release_ire_and_ill;
22852 
22853 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22854 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22855 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22856 		if ((pktxmit_state == SEND_FAILED) ||
22857 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22858 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22859 			    "- packet dropped\n"));
22860 release_ire_and_ill:
22861 			ire_refrele(ire);
22862 			if (next_mp != NULL) {
22863 				freemsg(next_mp);
22864 				ire_refrele(ire1);
22865 			}
22866 			if (conn_outgoing_ill != NULL)
22867 				ill_refrele(conn_outgoing_ill);
22868 			return;
22869 		}
22870 
22871 		if (CLASSD(dst)) {
22872 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22873 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22874 			    LENGTH);
22875 		}
22876 
22877 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22878 		    "ip_wput_ire_end: q %p (%S)",
22879 		    q, "last copy out");
22880 		IRE_REFRELE(ire);
22881 
22882 		if (multirt_send) {
22883 			ASSERT(ire1);
22884 			/*
22885 			 * Proceed with the next RTF_MULTIRT ire,
22886 			 * Also set up the send-to queue accordingly.
22887 			 */
22888 			ire = ire1;
22889 			ire1 = NULL;
22890 			stq = ire->ire_stq;
22891 			mp = next_mp;
22892 			next_mp = NULL;
22893 			ipha = (ipha_t *)mp->b_rptr;
22894 			ill_index = Q_TO_INDEX(stq);
22895 			ill = (ill_t *)stq->q_ptr;
22896 		}
22897 	} while (multirt_send);
22898 	if (conn_outgoing_ill != NULL)
22899 		ill_refrele(conn_outgoing_ill);
22900 	return;
22901 
22902 	/*
22903 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22904 	 */
22905 broadcast:
22906 	{
22907 		/*
22908 		 * Avoid broadcast storms by setting the ttl to 1
22909 		 * for broadcasts. This parameter can be set
22910 		 * via ndd, so make sure that for the SO_DONTROUTE
22911 		 * case that ipha_ttl is always set to 1.
22912 		 * In the event that we are replying to incoming
22913 		 * ICMP packets, conn could be NULL.
22914 		 */
22915 		if ((connp != NULL) && connp->conn_dontroute)
22916 			ipha->ipha_ttl = 1;
22917 		else
22918 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22919 
22920 		/*
22921 		 * Note that we are not doing a IRB_REFHOLD here.
22922 		 * Actually we don't care if the list changes i.e
22923 		 * if somebody deletes an IRE from the list while
22924 		 * we drop the lock, the next time we come around
22925 		 * ire_next will be NULL and hence we won't send
22926 		 * out multiple copies which is fine.
22927 		 */
22928 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22929 		ire1 = ire->ire_next;
22930 		if (conn_outgoing_ill != NULL) {
22931 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22932 				ASSERT(ire1 == ire->ire_next);
22933 				if (ire1 != NULL && ire1->ire_addr == dst) {
22934 					ire_refrele(ire);
22935 					ire = ire1;
22936 					IRE_REFHOLD(ire);
22937 					ire1 = ire->ire_next;
22938 					continue;
22939 				}
22940 				rw_exit(&ire->ire_bucket->irb_lock);
22941 				/* Did not find a matching ill */
22942 				ip1dbg(("ip_wput_ire: broadcast with no "
22943 				    "matching IP_BOUND_IF ill %s\n",
22944 				    conn_outgoing_ill->ill_name));
22945 				freemsg(first_mp);
22946 				if (ire != NULL)
22947 					ire_refrele(ire);
22948 				ill_refrele(conn_outgoing_ill);
22949 				return;
22950 			}
22951 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22952 			/*
22953 			 * If the next IRE has the same address and is not one
22954 			 * of the two copies that we need to send, try to see
22955 			 * whether this copy should be sent at all. This
22956 			 * assumes that we insert loopbacks first and then
22957 			 * non-loopbacks. This is acheived by inserting the
22958 			 * loopback always before non-loopback.
22959 			 * This is used to send a single copy of a broadcast
22960 			 * packet out all physical interfaces that have an
22961 			 * matching IRE_BROADCAST while also looping
22962 			 * back one copy (to ip_wput_local) for each
22963 			 * matching physical interface. However, we avoid
22964 			 * sending packets out different logical that match by
22965 			 * having ipif_up/ipif_down supress duplicate
22966 			 * IRE_BROADCASTS.
22967 			 *
22968 			 * This feature is currently used to get broadcasts
22969 			 * sent to multiple interfaces, when the broadcast
22970 			 * address being used applies to multiple interfaces.
22971 			 * For example, a whole net broadcast will be
22972 			 * replicated on every connected subnet of
22973 			 * the target net.
22974 			 *
22975 			 * Each zone has its own set of IRE_BROADCASTs, so that
22976 			 * we're able to distribute inbound packets to multiple
22977 			 * zones who share a broadcast address. We avoid looping
22978 			 * back outbound packets in different zones but on the
22979 			 * same ill, as the application would see duplicates.
22980 			 *
22981 			 * If the interfaces are part of the same group,
22982 			 * we would want to send only one copy out for
22983 			 * whole group.
22984 			 *
22985 			 * This logic assumes that ire_add_v4() groups the
22986 			 * IRE_BROADCAST entries so that those with the same
22987 			 * ire_addr and ill_group are kept together.
22988 			 */
22989 			ire_ill = ire->ire_ipif->ipif_ill;
22990 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22991 				if (ire_ill->ill_group != NULL &&
22992 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22993 					/*
22994 					 * If the current zone only has an ire
22995 					 * broadcast for this address marked
22996 					 * NORECV, the ire we want is ahead in
22997 					 * the bucket, so we look it up
22998 					 * deliberately ignoring the zoneid.
22999 					 */
23000 					for (ire1 = ire->ire_bucket->irb_ire;
23001 					    ire1 != NULL;
23002 					    ire1 = ire1->ire_next) {
23003 						ire1_ill =
23004 						    ire1->ire_ipif->ipif_ill;
23005 						if (ire1->ire_addr != dst)
23006 							continue;
23007 						/* skip over the current ire */
23008 						if (ire1 == ire)
23009 							continue;
23010 						/* skip over deleted ires */
23011 						if (ire1->ire_marks &
23012 						    IRE_MARK_CONDEMNED)
23013 							continue;
23014 						/*
23015 						 * non-loopback ire in our
23016 						 * group: use it for the next
23017 						 * pass in the loop
23018 						 */
23019 						if (ire1->ire_stq != NULL &&
23020 						    ire1_ill->ill_group ==
23021 						    ire_ill->ill_group)
23022 							break;
23023 					}
23024 				}
23025 			} else {
23026 				while (ire1 != NULL && ire1->ire_addr == dst) {
23027 					ire1_ill = ire1->ire_ipif->ipif_ill;
23028 					/*
23029 					 * We can have two broadcast ires on the
23030 					 * same ill in different zones; here
23031 					 * we'll send a copy of the packet on
23032 					 * each ill and the fanout code will
23033 					 * call conn_wantpacket() to check that
23034 					 * the zone has the broadcast address
23035 					 * configured on the ill. If the two
23036 					 * ires are in the same group we only
23037 					 * send one copy up.
23038 					 */
23039 					if (ire1_ill != ire_ill &&
23040 					    (ire1_ill->ill_group == NULL ||
23041 					    ire_ill->ill_group == NULL ||
23042 					    ire1_ill->ill_group !=
23043 					    ire_ill->ill_group)) {
23044 						break;
23045 					}
23046 					ire1 = ire1->ire_next;
23047 				}
23048 			}
23049 		}
23050 		ASSERT(multirt_send == B_FALSE);
23051 		if (ire1 != NULL && ire1->ire_addr == dst) {
23052 			if ((ire->ire_flags & RTF_MULTIRT) &&
23053 			    (ire1->ire_flags & RTF_MULTIRT)) {
23054 				/*
23055 				 * We are in the multirouting case.
23056 				 * The message must be sent at least
23057 				 * on both ires. These ires have been
23058 				 * inserted AFTER the standard ones
23059 				 * in ip_rt_add(). There are thus no
23060 				 * other ire entries for the destination
23061 				 * address in the rest of the bucket
23062 				 * that do not have the RTF_MULTIRT
23063 				 * flag. We don't process a copy
23064 				 * of the message here. This will be
23065 				 * done in the final sending loop.
23066 				 */
23067 				multirt_send = B_TRUE;
23068 			} else {
23069 				next_mp = ip_copymsg(first_mp);
23070 				if (next_mp != NULL)
23071 					IRE_REFHOLD(ire1);
23072 			}
23073 		}
23074 		rw_exit(&ire->ire_bucket->irb_lock);
23075 	}
23076 
23077 	if (stq) {
23078 		/*
23079 		 * A non-NULL send-to queue means this packet is going
23080 		 * out of this machine.
23081 		 */
23082 		out_ill = (ill_t *)stq->q_ptr;
23083 
23084 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23085 		ttl_protocol = ((uint16_t *)ipha)[4];
23086 		/*
23087 		 * We accumulate the pseudo header checksum in cksum.
23088 		 * This is pretty hairy code, so watch close.  One
23089 		 * thing to keep in mind is that UDP and TCP have
23090 		 * stored their respective datagram lengths in their
23091 		 * checksum fields.  This lines things up real nice.
23092 		 */
23093 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23094 		    (src >> 16) + (src & 0xFFFF);
23095 		/*
23096 		 * We assume the udp checksum field contains the
23097 		 * length, so to compute the pseudo header checksum,
23098 		 * all we need is the protocol number and src/dst.
23099 		 */
23100 		/* Provide the checksums for UDP and TCP. */
23101 		if ((PROTO == IPPROTO_TCP) &&
23102 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23103 			/* hlen gets the number of uchar_ts in the IP header */
23104 			hlen = (V_HLEN & 0xF) << 2;
23105 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23106 			IP_STAT(ipst, ip_out_sw_cksum);
23107 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23108 			    LENGTH - hlen);
23109 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23110 			if (*up == 0)
23111 				*up = 0xFFFF;
23112 		} else if (PROTO == IPPROTO_SCTP &&
23113 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23114 			sctp_hdr_t	*sctph;
23115 
23116 			hlen = (V_HLEN & 0xF) << 2;
23117 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23118 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23119 			sctph->sh_chksum = 0;
23120 #ifdef	DEBUG
23121 			if (!skip_sctp_cksum)
23122 #endif
23123 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23124 		} else {
23125 			queue_t *dev_q = stq->q_next;
23126 
23127 			if ((dev_q->q_next || dev_q->q_first) &&
23128 			    !canput(dev_q)) {
23129 			    blocked:
23130 				ipha->ipha_ident = ip_hdr_included;
23131 				/*
23132 				 * If we don't have a conn to apply
23133 				 * backpressure, free the message.
23134 				 * In the ire_send path, we don't know
23135 				 * the position to requeue the packet. Rather
23136 				 * than reorder packets, we just drop this
23137 				 * packet.
23138 				 */
23139 				if (ipst->ips_ip_output_queue &&
23140 				    connp != NULL &&
23141 				    caller != IRE_SEND) {
23142 					if (caller == IP_WSRV) {
23143 						connp->conn_did_putbq = 1;
23144 						(void) putbq(connp->conn_wq,
23145 						    first_mp);
23146 						conn_drain_insert(connp);
23147 						/*
23148 						 * This is the service thread,
23149 						 * and the queue is already
23150 						 * noenabled. The check for
23151 						 * canput and the putbq is not
23152 						 * atomic. So we need to check
23153 						 * again.
23154 						 */
23155 						if (canput(stq->q_next))
23156 							connp->conn_did_putbq
23157 							    = 0;
23158 						IP_STAT(ipst, ip_conn_flputbq);
23159 					} else {
23160 						/*
23161 						 * We are not the service proc.
23162 						 * ip_wsrv will be scheduled or
23163 						 * is already running.
23164 						 */
23165 						(void) putq(connp->conn_wq,
23166 						    first_mp);
23167 					}
23168 				} else {
23169 					out_ill = (ill_t *)stq->q_ptr;
23170 					BUMP_MIB(out_ill->ill_ip_mib,
23171 					    ipIfStatsOutDiscards);
23172 					freemsg(first_mp);
23173 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23174 					    "ip_wput_ire_end: q %p (%S)",
23175 					    q, "discard");
23176 				}
23177 				ire_refrele(ire);
23178 				if (next_mp) {
23179 					ire_refrele(ire1);
23180 					freemsg(next_mp);
23181 				}
23182 				if (conn_outgoing_ill != NULL)
23183 					ill_refrele(conn_outgoing_ill);
23184 				return;
23185 			}
23186 			if ((PROTO == IPPROTO_UDP) &&
23187 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23188 				/*
23189 				 * hlen gets the number of uchar_ts in the
23190 				 * IP header
23191 				 */
23192 				hlen = (V_HLEN & 0xF) << 2;
23193 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23194 				max_frag = ire->ire_max_frag;
23195 				if (*up != 0) {
23196 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23197 					    up, PROTO, hlen, LENGTH, max_frag,
23198 					    ipsec_len, cksum);
23199 					/* Software checksum? */
23200 					if (DB_CKSUMFLAGS(mp) == 0) {
23201 						IP_STAT(ipst, ip_out_sw_cksum);
23202 						IP_STAT_UPDATE(ipst,
23203 						    ip_udp_out_sw_cksum_bytes,
23204 						    LENGTH - hlen);
23205 					}
23206 				}
23207 			}
23208 		}
23209 		/*
23210 		 * Need to do this even when fragmenting. The local
23211 		 * loopback can be done without computing checksums
23212 		 * but forwarding out other interface must be done
23213 		 * after the IP checksum (and ULP checksums) have been
23214 		 * computed.
23215 		 *
23216 		 * NOTE : multicast_forward is set only if this packet
23217 		 * originated from ip_wput. For packets originating from
23218 		 * ip_wput_multicast, it is not set.
23219 		 */
23220 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23221 		    multi_loopback:
23222 			ip2dbg(("ip_wput: multicast, loop %d\n",
23223 			    conn_multicast_loop));
23224 
23225 			/*  Forget header checksum offload */
23226 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23227 
23228 			/*
23229 			 * Local loopback of multicasts?  Check the
23230 			 * ill.
23231 			 *
23232 			 * Note that the loopback function will not come
23233 			 * in through ip_rput - it will only do the
23234 			 * client fanout thus we need to do an mforward
23235 			 * as well.  The is different from the BSD
23236 			 * logic.
23237 			 */
23238 			if (ill != NULL) {
23239 				ilm_t	*ilm;
23240 
23241 				ILM_WALKER_HOLD(ill);
23242 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23243 				    ALL_ZONES);
23244 				ILM_WALKER_RELE(ill);
23245 				if (ilm != NULL) {
23246 					/*
23247 					 * Pass along the virtual output q.
23248 					 * ip_wput_local() will distribute the
23249 					 * packet to all the matching zones,
23250 					 * except the sending zone when
23251 					 * IP_MULTICAST_LOOP is false.
23252 					 */
23253 					ip_multicast_loopback(q, ill, first_mp,
23254 					    conn_multicast_loop ? 0 :
23255 					    IP_FF_NO_MCAST_LOOP, zoneid);
23256 				}
23257 			}
23258 			if (ipha->ipha_ttl == 0) {
23259 				/*
23260 				 * 0 => only to this host i.e. we are
23261 				 * done. We are also done if this was the
23262 				 * loopback interface since it is sufficient
23263 				 * to loopback one copy of a multicast packet.
23264 				 */
23265 				freemsg(first_mp);
23266 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23267 				    "ip_wput_ire_end: q %p (%S)",
23268 				    q, "loopback");
23269 				ire_refrele(ire);
23270 				if (conn_outgoing_ill != NULL)
23271 					ill_refrele(conn_outgoing_ill);
23272 				return;
23273 			}
23274 			/*
23275 			 * ILLF_MULTICAST is checked in ip_newroute
23276 			 * i.e. we don't need to check it here since
23277 			 * all IRE_CACHEs come from ip_newroute.
23278 			 * For multicast traffic, SO_DONTROUTE is interpreted
23279 			 * to mean only send the packet out the interface
23280 			 * (optionally specified with IP_MULTICAST_IF)
23281 			 * and do not forward it out additional interfaces.
23282 			 * RSVP and the rsvp daemon is an example of a
23283 			 * protocol and user level process that
23284 			 * handles it's own routing. Hence, it uses the
23285 			 * SO_DONTROUTE option to accomplish this.
23286 			 */
23287 
23288 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23289 			    ill != NULL) {
23290 				/* Unconditionally redo the checksum */
23291 				ipha->ipha_hdr_checksum = 0;
23292 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23293 
23294 				/*
23295 				 * If this needs to go out secure, we need
23296 				 * to wait till we finish the IPSEC
23297 				 * processing.
23298 				 */
23299 				if (ipsec_len == 0 &&
23300 				    ip_mforward(ill, ipha, mp)) {
23301 					freemsg(first_mp);
23302 					ip1dbg(("ip_wput: mforward failed\n"));
23303 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23304 					    "ip_wput_ire_end: q %p (%S)",
23305 					    q, "mforward failed");
23306 					ire_refrele(ire);
23307 					if (conn_outgoing_ill != NULL)
23308 						ill_refrele(conn_outgoing_ill);
23309 					return;
23310 				}
23311 			}
23312 		}
23313 		max_frag = ire->ire_max_frag;
23314 		cksum += ttl_protocol;
23315 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23316 			/* No fragmentation required for this one. */
23317 			/*
23318 			 * Don't use frag_flag if packet is pre-built or source
23319 			 * routed or if multicast (since multicast packets do
23320 			 * not solicit ICMP "packet too big" messages).
23321 			 */
23322 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23323 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23324 			    !ip_source_route_included(ipha)) &&
23325 			    !CLASSD(ipha->ipha_dst))
23326 				ipha->ipha_fragment_offset_and_flags |=
23327 				    htons(ire->ire_frag_flag);
23328 
23329 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23330 				/* Complete the IP header checksum. */
23331 				cksum += ipha->ipha_ident;
23332 				cksum += (v_hlen_tos_len >> 16)+
23333 				    (v_hlen_tos_len & 0xFFFF);
23334 				cksum += ipha->ipha_fragment_offset_and_flags;
23335 				hlen = (V_HLEN & 0xF) -
23336 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23337 				if (hlen) {
23338 				    checksumoptions:
23339 					/*
23340 					 * Account for the IP Options in the IP
23341 					 * header checksum.
23342 					 */
23343 					up = (uint16_t *)(rptr+
23344 					    IP_SIMPLE_HDR_LENGTH);
23345 					do {
23346 						cksum += up[0];
23347 						cksum += up[1];
23348 						up += 2;
23349 					} while (--hlen);
23350 				}
23351 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23352 				cksum = ~(cksum + (cksum >> 16));
23353 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23354 			}
23355 			if (ipsec_len != 0) {
23356 				ipsec_out_process(q, first_mp, ire, ill_index);
23357 				if (!next_mp) {
23358 					ire_refrele(ire);
23359 					if (conn_outgoing_ill != NULL)
23360 						ill_refrele(conn_outgoing_ill);
23361 					return;
23362 				}
23363 				goto next;
23364 			}
23365 
23366 			/*
23367 			 * multirt_send has already been handled
23368 			 * for broadcast, but not yet for multicast
23369 			 * or IP options.
23370 			 */
23371 			if (next_mp == NULL) {
23372 				if (ire->ire_flags & RTF_MULTIRT) {
23373 					multirt_send = B_TRUE;
23374 				}
23375 			}
23376 
23377 			/*
23378 			 * In most cases, the emission loop below is
23379 			 * entered only once. Only in the case where
23380 			 * the ire holds the RTF_MULTIRT flag, do we loop
23381 			 * to process all RTF_MULTIRT ires in the bucket,
23382 			 * and send the packet through all crossed
23383 			 * RTF_MULTIRT routes.
23384 			 */
23385 			do {
23386 				if (multirt_send) {
23387 					irb_t *irb;
23388 
23389 					irb = ire->ire_bucket;
23390 					ASSERT(irb != NULL);
23391 					/*
23392 					 * We are in a multiple send case,
23393 					 * need to get the next IRE and make
23394 					 * a duplicate of the packet.
23395 					 */
23396 					IRB_REFHOLD(irb);
23397 					for (ire1 = ire->ire_next;
23398 					    ire1 != NULL;
23399 					    ire1 = ire1->ire_next) {
23400 						if (!(ire1->ire_flags &
23401 						    RTF_MULTIRT))
23402 							continue;
23403 						if (ire1->ire_addr !=
23404 						    ire->ire_addr)
23405 							continue;
23406 						if (ire1->ire_marks &
23407 						    (IRE_MARK_CONDEMNED|
23408 							IRE_MARK_HIDDEN))
23409 							continue;
23410 
23411 						/* Got one */
23412 						IRE_REFHOLD(ire1);
23413 						break;
23414 					}
23415 					IRB_REFRELE(irb);
23416 
23417 					if (ire1 != NULL) {
23418 						next_mp = copyb(mp);
23419 						if ((next_mp == NULL) ||
23420 						    ((mp->b_cont != NULL) &&
23421 						    ((next_mp->b_cont =
23422 						    dupmsg(mp->b_cont))
23423 						    == NULL))) {
23424 							freemsg(next_mp);
23425 							next_mp = NULL;
23426 							ire_refrele(ire1);
23427 							ire1 = NULL;
23428 						}
23429 					}
23430 
23431 					/*
23432 					 * Last multiroute ire; don't loop
23433 					 * anymore. The emission is over
23434 					 * and next_mp is NULL.
23435 					 */
23436 					if (ire1 == NULL) {
23437 						multirt_send = B_FALSE;
23438 					}
23439 				}
23440 
23441 				out_ill = ire->ire_ipif->ipif_ill;
23442 				DTRACE_PROBE4(ip4__physical__out__start,
23443 				    ill_t *, NULL,
23444 				    ill_t *, out_ill,
23445 				    ipha_t *, ipha, mblk_t *, mp);
23446 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23447 				    ipst->ips_ipv4firewall_physical_out,
23448 				    NULL, out_ill, ipha, mp, mp, ipst);
23449 				DTRACE_PROBE1(ip4__physical__out__end,
23450 				    mblk_t *, mp);
23451 				if (mp == NULL)
23452 					goto release_ire_and_ill_2;
23453 
23454 				ASSERT(ipsec_len == 0);
23455 				mp->b_prev =
23456 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23457 				DTRACE_PROBE2(ip__xmit__2,
23458 				    mblk_t *, mp, ire_t *, ire);
23459 				pktxmit_state = ip_xmit_v4(mp, ire,
23460 				    NULL, B_TRUE);
23461 				if ((pktxmit_state == SEND_FAILED) ||
23462 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23463 release_ire_and_ill_2:
23464 					if (next_mp) {
23465 						freemsg(next_mp);
23466 						ire_refrele(ire1);
23467 					}
23468 					ire_refrele(ire);
23469 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23470 					    "ip_wput_ire_end: q %p (%S)",
23471 					    q, "discard MDATA");
23472 					if (conn_outgoing_ill != NULL)
23473 						ill_refrele(conn_outgoing_ill);
23474 					return;
23475 				}
23476 
23477 				if (CLASSD(dst)) {
23478 					BUMP_MIB(out_ill->ill_ip_mib,
23479 					    ipIfStatsHCOutMcastPkts);
23480 					UPDATE_MIB(out_ill->ill_ip_mib,
23481 					    ipIfStatsHCOutMcastOctets,
23482 					    LENGTH);
23483 				} else if (ire->ire_type == IRE_BROADCAST) {
23484 					BUMP_MIB(out_ill->ill_ip_mib,
23485 					    ipIfStatsHCOutBcastPkts);
23486 				}
23487 
23488 				if (multirt_send) {
23489 					/*
23490 					 * We are in a multiple send case,
23491 					 * need to re-enter the sending loop
23492 					 * using the next ire.
23493 					 */
23494 					ire_refrele(ire);
23495 					ire = ire1;
23496 					stq = ire->ire_stq;
23497 					mp = next_mp;
23498 					next_mp = NULL;
23499 					ipha = (ipha_t *)mp->b_rptr;
23500 					ill_index = Q_TO_INDEX(stq);
23501 				}
23502 			} while (multirt_send);
23503 
23504 			if (!next_mp) {
23505 				/*
23506 				 * Last copy going out (the ultra-common
23507 				 * case).  Note that we intentionally replicate
23508 				 * the putnext rather than calling it before
23509 				 * the next_mp check in hopes of a little
23510 				 * tail-call action out of the compiler.
23511 				 */
23512 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23513 				    "ip_wput_ire_end: q %p (%S)",
23514 				    q, "last copy out(1)");
23515 				ire_refrele(ire);
23516 				if (conn_outgoing_ill != NULL)
23517 					ill_refrele(conn_outgoing_ill);
23518 				return;
23519 			}
23520 			/* More copies going out below. */
23521 		} else {
23522 			int offset;
23523 		    fragmentit:
23524 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23525 			/*
23526 			 * If this would generate a icmp_frag_needed message,
23527 			 * we need to handle it before we do the IPSEC
23528 			 * processing. Otherwise, we need to strip the IPSEC
23529 			 * headers before we send up the message to the ULPs
23530 			 * which becomes messy and difficult.
23531 			 */
23532 			if (ipsec_len != 0) {
23533 				if ((max_frag < (unsigned int)(LENGTH +
23534 				    ipsec_len)) && (offset & IPH_DF)) {
23535 					out_ill = (ill_t *)stq->q_ptr;
23536 					BUMP_MIB(out_ill->ill_ip_mib,
23537 					    ipIfStatsOutFragFails);
23538 					BUMP_MIB(out_ill->ill_ip_mib,
23539 					    ipIfStatsOutFragReqds);
23540 					ipha->ipha_hdr_checksum = 0;
23541 					ipha->ipha_hdr_checksum =
23542 					    (uint16_t)ip_csum_hdr(ipha);
23543 					icmp_frag_needed(ire->ire_stq, first_mp,
23544 					    max_frag, zoneid, ipst);
23545 					if (!next_mp) {
23546 						ire_refrele(ire);
23547 						if (conn_outgoing_ill != NULL) {
23548 							ill_refrele(
23549 							    conn_outgoing_ill);
23550 						}
23551 						return;
23552 					}
23553 				} else {
23554 					/*
23555 					 * This won't cause a icmp_frag_needed
23556 					 * message. to be generated. Send it on
23557 					 * the wire. Note that this could still
23558 					 * cause fragmentation and all we
23559 					 * do is the generation of the message
23560 					 * to the ULP if needed before IPSEC.
23561 					 */
23562 					if (!next_mp) {
23563 						ipsec_out_process(q, first_mp,
23564 						    ire, ill_index);
23565 						TRACE_2(TR_FAC_IP,
23566 						    TR_IP_WPUT_IRE_END,
23567 						    "ip_wput_ire_end: q %p "
23568 						    "(%S)", q,
23569 						    "last ipsec_out_process");
23570 						ire_refrele(ire);
23571 						if (conn_outgoing_ill != NULL) {
23572 							ill_refrele(
23573 							    conn_outgoing_ill);
23574 						}
23575 						return;
23576 					}
23577 					ipsec_out_process(q, first_mp,
23578 					    ire, ill_index);
23579 				}
23580 			} else {
23581 				/*
23582 				 * Initiate IPPF processing. For
23583 				 * fragmentable packets we finish
23584 				 * all QOS packet processing before
23585 				 * calling:
23586 				 * ip_wput_ire_fragmentit->ip_wput_frag
23587 				 */
23588 
23589 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23590 					ip_process(IPP_LOCAL_OUT, &mp,
23591 					    ill_index);
23592 					if (mp == NULL) {
23593 						out_ill = (ill_t *)stq->q_ptr;
23594 						BUMP_MIB(out_ill->ill_ip_mib,
23595 						    ipIfStatsOutDiscards);
23596 						if (next_mp != NULL) {
23597 							freemsg(next_mp);
23598 							ire_refrele(ire1);
23599 						}
23600 						ire_refrele(ire);
23601 						TRACE_2(TR_FAC_IP,
23602 						    TR_IP_WPUT_IRE_END,
23603 						    "ip_wput_ire: q %p (%S)",
23604 						    q, "discard MDATA");
23605 						if (conn_outgoing_ill != NULL) {
23606 							ill_refrele(
23607 							    conn_outgoing_ill);
23608 						}
23609 						return;
23610 					}
23611 				}
23612 				if (!next_mp) {
23613 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23614 					    "ip_wput_ire_end: q %p (%S)",
23615 					    q, "last fragmentation");
23616 					ip_wput_ire_fragmentit(mp, ire,
23617 					    zoneid, ipst);
23618 					ire_refrele(ire);
23619 					if (conn_outgoing_ill != NULL)
23620 						ill_refrele(conn_outgoing_ill);
23621 					return;
23622 				}
23623 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23624 			}
23625 		}
23626 	} else {
23627 	    nullstq:
23628 		/* A NULL stq means the destination address is local. */
23629 		UPDATE_OB_PKT_COUNT(ire);
23630 		ire->ire_last_used_time = lbolt;
23631 		ASSERT(ire->ire_ipif != NULL);
23632 		if (!next_mp) {
23633 			/*
23634 			 * Is there an "in" and "out" for traffic local
23635 			 * to a host (loopback)?  The code in Solaris doesn't
23636 			 * explicitly draw a line in its code for in vs out,
23637 			 * so we've had to draw a line in the sand: ip_wput_ire
23638 			 * is considered to be the "output" side and
23639 			 * ip_wput_local to be the "input" side.
23640 			 */
23641 			out_ill = ire->ire_ipif->ipif_ill;
23642 
23643 			DTRACE_PROBE4(ip4__loopback__out__start,
23644 			    ill_t *, NULL, ill_t *, out_ill,
23645 			    ipha_t *, ipha, mblk_t *, first_mp);
23646 
23647 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23648 			    ipst->ips_ipv4firewall_loopback_out,
23649 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23650 
23651 			DTRACE_PROBE1(ip4__loopback__out_end,
23652 			    mblk_t *, first_mp);
23653 
23654 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23655 			    "ip_wput_ire_end: q %p (%S)",
23656 			    q, "local address");
23657 
23658 			if (first_mp != NULL)
23659 				ip_wput_local(q, out_ill, ipha,
23660 				    first_mp, ire, 0, ire->ire_zoneid);
23661 			ire_refrele(ire);
23662 			if (conn_outgoing_ill != NULL)
23663 				ill_refrele(conn_outgoing_ill);
23664 			return;
23665 		}
23666 
23667 		out_ill = ire->ire_ipif->ipif_ill;
23668 
23669 		DTRACE_PROBE4(ip4__loopback__out__start,
23670 		    ill_t *, NULL, ill_t *, out_ill,
23671 		    ipha_t *, ipha, mblk_t *, first_mp);
23672 
23673 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23674 		    ipst->ips_ipv4firewall_loopback_out,
23675 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23676 
23677 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23678 
23679 		if (first_mp != NULL)
23680 			ip_wput_local(q, out_ill, ipha,
23681 			    first_mp, ire, 0, ire->ire_zoneid);
23682 	}
23683 next:
23684 	/*
23685 	 * More copies going out to additional interfaces.
23686 	 * ire1 has already been held. We don't need the
23687 	 * "ire" anymore.
23688 	 */
23689 	ire_refrele(ire);
23690 	ire = ire1;
23691 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23692 	mp = next_mp;
23693 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23694 	ill = ire_to_ill(ire);
23695 	first_mp = mp;
23696 	if (ipsec_len != 0) {
23697 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23698 		mp = mp->b_cont;
23699 	}
23700 	dst = ire->ire_addr;
23701 	ipha = (ipha_t *)mp->b_rptr;
23702 	/*
23703 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23704 	 * Restore ipha_ident "no checksum" flag.
23705 	 */
23706 	src = orig_src;
23707 	ipha->ipha_ident = ip_hdr_included;
23708 	goto another;
23709 
23710 #undef	rptr
23711 #undef	Q_TO_INDEX
23712 }
23713 
23714 /*
23715  * Routine to allocate a message that is used to notify the ULP about MDT.
23716  * The caller may provide a pointer to the link-layer MDT capabilities,
23717  * or NULL if MDT is to be disabled on the stream.
23718  */
23719 mblk_t *
23720 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23721 {
23722 	mblk_t *mp;
23723 	ip_mdt_info_t *mdti;
23724 	ill_mdt_capab_t *idst;
23725 
23726 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23727 		DB_TYPE(mp) = M_CTL;
23728 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23729 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23730 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23731 		idst = &(mdti->mdt_capab);
23732 
23733 		/*
23734 		 * If the caller provides us with the capability, copy
23735 		 * it over into our notification message; otherwise
23736 		 * we zero out the capability portion.
23737 		 */
23738 		if (isrc != NULL)
23739 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23740 		else
23741 			bzero((caddr_t)idst, sizeof (*idst));
23742 	}
23743 	return (mp);
23744 }
23745 
23746 /*
23747  * Routine which determines whether MDT can be enabled on the destination
23748  * IRE and IPC combination, and if so, allocates and returns the MDT
23749  * notification mblk that may be used by ULP.  We also check if we need to
23750  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23751  * MDT usage in the past have been lifted.  This gets called during IP
23752  * and ULP binding.
23753  */
23754 mblk_t *
23755 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23756     ill_mdt_capab_t *mdt_cap)
23757 {
23758 	mblk_t *mp;
23759 	boolean_t rc = B_FALSE;
23760 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23761 
23762 	ASSERT(dst_ire != NULL);
23763 	ASSERT(connp != NULL);
23764 	ASSERT(mdt_cap != NULL);
23765 
23766 	/*
23767 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23768 	 * Multidata, which is handled in tcp_multisend().  This
23769 	 * is the reason why we do all these checks here, to ensure
23770 	 * that we don't enable Multidata for the cases which we
23771 	 * can't handle at the moment.
23772 	 */
23773 	do {
23774 		/* Only do TCP at the moment */
23775 		if (connp->conn_ulp != IPPROTO_TCP)
23776 			break;
23777 
23778 		/*
23779 		 * IPSEC outbound policy present?  Note that we get here
23780 		 * after calling ipsec_conn_cache_policy() where the global
23781 		 * policy checking is performed.  conn_latch will be
23782 		 * non-NULL as long as there's a policy defined,
23783 		 * i.e. conn_out_enforce_policy may be NULL in such case
23784 		 * when the connection is non-secure, and hence we check
23785 		 * further if the latch refers to an outbound policy.
23786 		 */
23787 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23788 			break;
23789 
23790 		/* CGTP (multiroute) is enabled? */
23791 		if (dst_ire->ire_flags & RTF_MULTIRT)
23792 			break;
23793 
23794 		/* Outbound IPQoS enabled? */
23795 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23796 			/*
23797 			 * In this case, we disable MDT for this and all
23798 			 * future connections going over the interface.
23799 			 */
23800 			mdt_cap->ill_mdt_on = 0;
23801 			break;
23802 		}
23803 
23804 		/* socket option(s) present? */
23805 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23806 			break;
23807 
23808 		rc = B_TRUE;
23809 	/* CONSTCOND */
23810 	} while (0);
23811 
23812 	/* Remember the result */
23813 	connp->conn_mdt_ok = rc;
23814 
23815 	if (!rc)
23816 		return (NULL);
23817 	else if (!mdt_cap->ill_mdt_on) {
23818 		/*
23819 		 * If MDT has been previously turned off in the past, and we
23820 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23821 		 * then enable it for this interface.
23822 		 */
23823 		mdt_cap->ill_mdt_on = 1;
23824 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23825 		    "interface %s\n", ill_name));
23826 	}
23827 
23828 	/* Allocate the MDT info mblk */
23829 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23830 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23831 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23832 		return (NULL);
23833 	}
23834 	return (mp);
23835 }
23836 
23837 /*
23838  * Routine to allocate a message that is used to notify the ULP about LSO.
23839  * The caller may provide a pointer to the link-layer LSO capabilities,
23840  * or NULL if LSO is to be disabled on the stream.
23841  */
23842 mblk_t *
23843 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23844 {
23845 	mblk_t *mp;
23846 	ip_lso_info_t *lsoi;
23847 	ill_lso_capab_t *idst;
23848 
23849 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23850 		DB_TYPE(mp) = M_CTL;
23851 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23852 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23853 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23854 		idst = &(lsoi->lso_capab);
23855 
23856 		/*
23857 		 * If the caller provides us with the capability, copy
23858 		 * it over into our notification message; otherwise
23859 		 * we zero out the capability portion.
23860 		 */
23861 		if (isrc != NULL)
23862 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23863 		else
23864 			bzero((caddr_t)idst, sizeof (*idst));
23865 	}
23866 	return (mp);
23867 }
23868 
23869 /*
23870  * Routine which determines whether LSO can be enabled on the destination
23871  * IRE and IPC combination, and if so, allocates and returns the LSO
23872  * notification mblk that may be used by ULP.  We also check if we need to
23873  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23874  * LSO usage in the past have been lifted.  This gets called during IP
23875  * and ULP binding.
23876  */
23877 mblk_t *
23878 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23879     ill_lso_capab_t *lso_cap)
23880 {
23881 	mblk_t *mp;
23882 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23883 
23884 	ASSERT(dst_ire != NULL);
23885 	ASSERT(connp != NULL);
23886 	ASSERT(lso_cap != NULL);
23887 
23888 	connp->conn_lso_ok = B_TRUE;
23889 
23890 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23891 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23892 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23893 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23894 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23895 		connp->conn_lso_ok = B_FALSE;
23896 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23897 			/*
23898 			 * Disable LSO for this and all future connections going
23899 			 * over the interface.
23900 			 */
23901 			lso_cap->ill_lso_on = 0;
23902 		}
23903 	}
23904 
23905 	if (!connp->conn_lso_ok)
23906 		return (NULL);
23907 	else if (!lso_cap->ill_lso_on) {
23908 		/*
23909 		 * If LSO has been previously turned off in the past, and we
23910 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23911 		 * then enable it for this interface.
23912 		 */
23913 		lso_cap->ill_lso_on = 1;
23914 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23915 		    ill_name));
23916 	}
23917 
23918 	/* Allocate the LSO info mblk */
23919 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23920 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23921 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23922 
23923 	return (mp);
23924 }
23925 
23926 /*
23927  * Create destination address attribute, and fill it with the physical
23928  * destination address and SAP taken from the template DL_UNITDATA_REQ
23929  * message block.
23930  */
23931 boolean_t
23932 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23933 {
23934 	dl_unitdata_req_t *dlurp;
23935 	pattr_t *pa;
23936 	pattrinfo_t pa_info;
23937 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23938 	uint_t das_len, das_off;
23939 
23940 	ASSERT(dlmp != NULL);
23941 
23942 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23943 	das_len = dlurp->dl_dest_addr_length;
23944 	das_off = dlurp->dl_dest_addr_offset;
23945 
23946 	pa_info.type = PATTR_DSTADDRSAP;
23947 	pa_info.len = sizeof (**das) + das_len - 1;
23948 
23949 	/* create and associate the attribute */
23950 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23951 	if (pa != NULL) {
23952 		ASSERT(*das != NULL);
23953 		(*das)->addr_is_group = 0;
23954 		(*das)->addr_len = (uint8_t)das_len;
23955 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23956 	}
23957 
23958 	return (pa != NULL);
23959 }
23960 
23961 /*
23962  * Create hardware checksum attribute and fill it with the values passed.
23963  */
23964 boolean_t
23965 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23966     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23967 {
23968 	pattr_t *pa;
23969 	pattrinfo_t pa_info;
23970 
23971 	ASSERT(mmd != NULL);
23972 
23973 	pa_info.type = PATTR_HCKSUM;
23974 	pa_info.len = sizeof (pattr_hcksum_t);
23975 
23976 	/* create and associate the attribute */
23977 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23978 	if (pa != NULL) {
23979 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23980 
23981 		hck->hcksum_start_offset = start_offset;
23982 		hck->hcksum_stuff_offset = stuff_offset;
23983 		hck->hcksum_end_offset = end_offset;
23984 		hck->hcksum_flags = flags;
23985 	}
23986 	return (pa != NULL);
23987 }
23988 
23989 /*
23990  * Create zerocopy attribute and fill it with the specified flags
23991  */
23992 boolean_t
23993 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23994 {
23995 	pattr_t *pa;
23996 	pattrinfo_t pa_info;
23997 
23998 	ASSERT(mmd != NULL);
23999 	pa_info.type = PATTR_ZCOPY;
24000 	pa_info.len = sizeof (pattr_zcopy_t);
24001 
24002 	/* create and associate the attribute */
24003 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24004 	if (pa != NULL) {
24005 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
24006 
24007 		zcopy->zcopy_flags = flags;
24008 	}
24009 	return (pa != NULL);
24010 }
24011 
24012 /*
24013  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
24014  * block chain. We could rewrite to handle arbitrary message block chains but
24015  * that would make the code complicated and slow. Right now there three
24016  * restrictions:
24017  *
24018  *   1. The first message block must contain the complete IP header and
24019  *	at least 1 byte of payload data.
24020  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
24021  *	so that we can use a single Multidata message.
24022  *   3. No frag must be distributed over two or more message blocks so
24023  *	that we don't need more than two packet descriptors per frag.
24024  *
24025  * The above restrictions allow us to support userland applications (which
24026  * will send down a single message block) and NFS over UDP (which will
24027  * send down a chain of at most three message blocks).
24028  *
24029  * We also don't use MDT for payloads with less than or equal to
24030  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24031  */
24032 boolean_t
24033 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24034 {
24035 	int	blocks;
24036 	ssize_t	total, missing, size;
24037 
24038 	ASSERT(mp != NULL);
24039 	ASSERT(hdr_len > 0);
24040 
24041 	size = MBLKL(mp) - hdr_len;
24042 	if (size <= 0)
24043 		return (B_FALSE);
24044 
24045 	/* The first mblk contains the header and some payload. */
24046 	blocks = 1;
24047 	total = size;
24048 	size %= len;
24049 	missing = (size == 0) ? 0 : (len - size);
24050 	mp = mp->b_cont;
24051 
24052 	while (mp != NULL) {
24053 		/*
24054 		 * Give up if we encounter a zero length message block.
24055 		 * In practice, this should rarely happen and therefore
24056 		 * not worth the trouble of freeing and re-linking the
24057 		 * mblk from the chain to handle such case.
24058 		 */
24059 		if ((size = MBLKL(mp)) == 0)
24060 			return (B_FALSE);
24061 
24062 		/* Too many payload buffers for a single Multidata message? */
24063 		if (++blocks > MULTIDATA_MAX_PBUFS)
24064 			return (B_FALSE);
24065 
24066 		total += size;
24067 		/* Is a frag distributed over two or more message blocks? */
24068 		if (missing > size)
24069 			return (B_FALSE);
24070 		size -= missing;
24071 
24072 		size %= len;
24073 		missing = (size == 0) ? 0 : (len - size);
24074 
24075 		mp = mp->b_cont;
24076 	}
24077 
24078 	return (total > ip_wput_frag_mdt_min);
24079 }
24080 
24081 /*
24082  * Outbound IPv4 fragmentation routine using MDT.
24083  */
24084 static void
24085 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24086     uint32_t frag_flag, int offset)
24087 {
24088 	ipha_t		*ipha_orig;
24089 	int		i1, ip_data_end;
24090 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24091 	mblk_t		*hdr_mp, *md_mp = NULL;
24092 	unsigned char	*hdr_ptr, *pld_ptr;
24093 	multidata_t	*mmd;
24094 	ip_pdescinfo_t	pdi;
24095 	ill_t		*ill;
24096 	ip_stack_t	*ipst = ire->ire_ipst;
24097 
24098 	ASSERT(DB_TYPE(mp) == M_DATA);
24099 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24100 
24101 	ill = ire_to_ill(ire);
24102 	ASSERT(ill != NULL);
24103 
24104 	ipha_orig = (ipha_t *)mp->b_rptr;
24105 	mp->b_rptr += sizeof (ipha_t);
24106 
24107 	/* Calculate how many packets we will send out */
24108 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24109 	pkts = (i1 + len - 1) / len;
24110 	ASSERT(pkts > 1);
24111 
24112 	/* Allocate a message block which will hold all the IP Headers. */
24113 	wroff = ipst->ips_ip_wroff_extra;
24114 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24115 
24116 	i1 = pkts * hdr_chunk_len;
24117 	/*
24118 	 * Create the header buffer, Multidata and destination address
24119 	 * and SAP attribute that should be associated with it.
24120 	 */
24121 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24122 	    ((hdr_mp->b_wptr += i1),
24123 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24124 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24125 		freemsg(mp);
24126 		if (md_mp == NULL) {
24127 			freemsg(hdr_mp);
24128 		} else {
24129 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24130 			freemsg(md_mp);
24131 		}
24132 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24133 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24134 		return;
24135 	}
24136 	IP_STAT(ipst, ip_frag_mdt_allocd);
24137 
24138 	/*
24139 	 * Add a payload buffer to the Multidata; this operation must not
24140 	 * fail, or otherwise our logic in this routine is broken.  There
24141 	 * is no memory allocation done by the routine, so any returned
24142 	 * failure simply tells us that we've done something wrong.
24143 	 *
24144 	 * A failure tells us that either we're adding the same payload
24145 	 * buffer more than once, or we're trying to add more buffers than
24146 	 * allowed.  None of the above cases should happen, and we panic
24147 	 * because either there's horrible heap corruption, and/or
24148 	 * programming mistake.
24149 	 */
24150 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24151 		goto pbuf_panic;
24152 
24153 	hdr_ptr = hdr_mp->b_rptr;
24154 	pld_ptr = mp->b_rptr;
24155 
24156 	/* Establish the ending byte offset, based on the starting offset. */
24157 	offset <<= 3;
24158 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24159 	    IP_SIMPLE_HDR_LENGTH;
24160 
24161 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24162 
24163 	while (pld_ptr < mp->b_wptr) {
24164 		ipha_t		*ipha;
24165 		uint16_t	offset_and_flags;
24166 		uint16_t	ip_len;
24167 		int		error;
24168 
24169 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24170 		ipha = (ipha_t *)(hdr_ptr + wroff);
24171 		ASSERT(OK_32PTR(ipha));
24172 		*ipha = *ipha_orig;
24173 
24174 		if (ip_data_end - offset > len) {
24175 			offset_and_flags = IPH_MF;
24176 		} else {
24177 			/*
24178 			 * Last frag. Set len to the length of this last piece.
24179 			 */
24180 			len = ip_data_end - offset;
24181 			/* A frag of a frag might have IPH_MF non-zero */
24182 			offset_and_flags =
24183 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24184 			    IPH_MF;
24185 		}
24186 		offset_and_flags |= (uint16_t)(offset >> 3);
24187 		offset_and_flags |= (uint16_t)frag_flag;
24188 		/* Store the offset and flags in the IP header. */
24189 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24190 
24191 		/* Store the length in the IP header. */
24192 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24193 		ipha->ipha_length = htons(ip_len);
24194 
24195 		/*
24196 		 * Set the IP header checksum.  Note that mp is just
24197 		 * the header, so this is easy to pass to ip_csum.
24198 		 */
24199 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24200 
24201 		/*
24202 		 * Record offset and size of header and data of the next packet
24203 		 * in the multidata message.
24204 		 */
24205 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24206 		PDESC_PLD_INIT(&pdi);
24207 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24208 		ASSERT(i1 > 0);
24209 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24210 		if (i1 == len) {
24211 			pld_ptr += len;
24212 		} else {
24213 			i1 = len - i1;
24214 			mp = mp->b_cont;
24215 			ASSERT(mp != NULL);
24216 			ASSERT(MBLKL(mp) >= i1);
24217 			/*
24218 			 * Attach the next payload message block to the
24219 			 * multidata message.
24220 			 */
24221 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24222 				goto pbuf_panic;
24223 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24224 			pld_ptr = mp->b_rptr + i1;
24225 		}
24226 
24227 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24228 		    KM_NOSLEEP)) == NULL) {
24229 			/*
24230 			 * Any failure other than ENOMEM indicates that we
24231 			 * have passed in invalid pdesc info or parameters
24232 			 * to mmd_addpdesc, which must not happen.
24233 			 *
24234 			 * EINVAL is a result of failure on boundary checks
24235 			 * against the pdesc info contents.  It should not
24236 			 * happen, and we panic because either there's
24237 			 * horrible heap corruption, and/or programming
24238 			 * mistake.
24239 			 */
24240 			if (error != ENOMEM) {
24241 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24242 				    "pdesc logic error detected for "
24243 				    "mmd %p pinfo %p (%d)\n",
24244 				    (void *)mmd, (void *)&pdi, error);
24245 				/* NOTREACHED */
24246 			}
24247 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24248 			/* Free unattached payload message blocks as well */
24249 			md_mp->b_cont = mp->b_cont;
24250 			goto free_mmd;
24251 		}
24252 
24253 		/* Advance fragment offset. */
24254 		offset += len;
24255 
24256 		/* Advance to location for next header in the buffer. */
24257 		hdr_ptr += hdr_chunk_len;
24258 
24259 		/* Did we reach the next payload message block? */
24260 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24261 			mp = mp->b_cont;
24262 			/*
24263 			 * Attach the next message block with payload
24264 			 * data to the multidata message.
24265 			 */
24266 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24267 				goto pbuf_panic;
24268 			pld_ptr = mp->b_rptr;
24269 		}
24270 	}
24271 
24272 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24273 	ASSERT(mp->b_wptr == pld_ptr);
24274 
24275 	/* Update IP statistics */
24276 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24277 
24278 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24279 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24280 
24281 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24282 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24283 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24284 
24285 	if (pkt_type == OB_PKT) {
24286 		ire->ire_ob_pkt_count += pkts;
24287 		if (ire->ire_ipif != NULL)
24288 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24289 	} else {
24290 		/*
24291 		 * The type is IB_PKT in the forwarding path and in
24292 		 * the mobile IP case when the packet is being reverse-
24293 		 * tunneled to the home agent.
24294 		 */
24295 		ire->ire_ib_pkt_count += pkts;
24296 		ASSERT(!IRE_IS_LOCAL(ire));
24297 		if (ire->ire_type & IRE_BROADCAST) {
24298 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24299 		} else {
24300 			UPDATE_MIB(ill->ill_ip_mib,
24301 			    ipIfStatsHCOutForwDatagrams, pkts);
24302 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24303 		}
24304 	}
24305 	ire->ire_last_used_time = lbolt;
24306 	/* Send it down */
24307 	putnext(ire->ire_stq, md_mp);
24308 	return;
24309 
24310 pbuf_panic:
24311 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24312 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24313 	    pbuf_idx);
24314 	/* NOTREACHED */
24315 }
24316 
24317 /*
24318  * Outbound IP fragmentation routine.
24319  *
24320  * NOTE : This routine does not ire_refrele the ire that is passed in
24321  * as the argument.
24322  */
24323 static void
24324 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24325     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24326 {
24327 	int		i1;
24328 	mblk_t		*ll_hdr_mp;
24329 	int 		ll_hdr_len;
24330 	int		hdr_len;
24331 	mblk_t		*hdr_mp;
24332 	ipha_t		*ipha;
24333 	int		ip_data_end;
24334 	int		len;
24335 	mblk_t		*mp = mp_orig, *mp1;
24336 	int		offset;
24337 	queue_t		*q;
24338 	uint32_t	v_hlen_tos_len;
24339 	mblk_t		*first_mp;
24340 	boolean_t	mctl_present;
24341 	ill_t		*ill;
24342 	ill_t		*out_ill;
24343 	mblk_t		*xmit_mp;
24344 	mblk_t		*carve_mp;
24345 	ire_t		*ire1 = NULL;
24346 	ire_t		*save_ire = NULL;
24347 	mblk_t  	*next_mp = NULL;
24348 	boolean_t	last_frag = B_FALSE;
24349 	boolean_t	multirt_send = B_FALSE;
24350 	ire_t		*first_ire = NULL;
24351 	irb_t		*irb = NULL;
24352 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24353 
24354 	ill = ire_to_ill(ire);
24355 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24356 
24357 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24358 
24359 	/*
24360 	 * IPSEC does not allow hw accelerated packets to be fragmented
24361 	 * This check is made in ip_wput_ipsec_out prior to coming here
24362 	 * via ip_wput_ire_fragmentit.
24363 	 *
24364 	 * If at this point we have an ire whose ARP request has not
24365 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24366 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24367 	 * This packet and all fragmentable packets for this ire will
24368 	 * continue to get dropped while ire_nce->nce_state remains in
24369 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24370 	 * ND_REACHABLE, all subsquent large packets for this ire will
24371 	 * get fragemented and sent out by this function.
24372 	 */
24373 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24374 		/* If nce_state is ND_INITIAL, trigger ARP query */
24375 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24376 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24377 		    " -  dropping packet\n"));
24378 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24379 		freemsg(mp);
24380 		return;
24381 	}
24382 
24383 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24384 	    "ip_wput_frag_start:");
24385 
24386 	if (mp->b_datap->db_type == M_CTL) {
24387 		first_mp = mp;
24388 		mp_orig = mp = mp->b_cont;
24389 		mctl_present = B_TRUE;
24390 	} else {
24391 		first_mp = mp;
24392 		mctl_present = B_FALSE;
24393 	}
24394 
24395 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24396 	ipha = (ipha_t *)mp->b_rptr;
24397 
24398 	/*
24399 	 * If the Don't Fragment flag is on, generate an ICMP destination
24400 	 * unreachable, fragmentation needed.
24401 	 */
24402 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24403 	if (offset & IPH_DF) {
24404 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24405 		/*
24406 		 * Need to compute hdr checksum if called from ip_wput_ire.
24407 		 * Note that ip_rput_forward verifies the checksum before
24408 		 * calling this routine so in that case this is a noop.
24409 		 */
24410 		ipha->ipha_hdr_checksum = 0;
24411 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24412 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24413 		    ipst);
24414 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24415 		    "ip_wput_frag_end:(%S)",
24416 		    "don't fragment");
24417 		return;
24418 	}
24419 	if (mctl_present)
24420 		freeb(first_mp);
24421 	/*
24422 	 * Establish the starting offset.  May not be zero if we are fragging
24423 	 * a fragment that is being forwarded.
24424 	 */
24425 	offset = offset & IPH_OFFSET;
24426 
24427 	/* TODO why is this test needed? */
24428 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24429 	if (((max_frag - LENGTH) & ~7) < 8) {
24430 		/* TODO: notify ulp somehow */
24431 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24432 		freemsg(mp);
24433 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24434 		    "ip_wput_frag_end:(%S)",
24435 		    "len < 8");
24436 		return;
24437 	}
24438 
24439 	hdr_len = (V_HLEN & 0xF) << 2;
24440 
24441 	ipha->ipha_hdr_checksum = 0;
24442 
24443 	/*
24444 	 * Establish the number of bytes maximum per frag, after putting
24445 	 * in the header.
24446 	 */
24447 	len = (max_frag - hdr_len) & ~7;
24448 
24449 	/* Check if we can use MDT to send out the frags. */
24450 	ASSERT(!IRE_IS_LOCAL(ire));
24451 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24452 	    ipst->ips_ip_multidata_outbound &&
24453 	    !(ire->ire_flags & RTF_MULTIRT) &&
24454 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24455 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24456 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24457 		ASSERT(ill->ill_mdt_capab != NULL);
24458 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24459 			/*
24460 			 * If MDT has been previously turned off in the past,
24461 			 * and we currently can do MDT (due to IPQoS policy
24462 			 * removal, etc.) then enable it for this interface.
24463 			 */
24464 			ill->ill_mdt_capab->ill_mdt_on = 1;
24465 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24466 			    ill->ill_name));
24467 		}
24468 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24469 		    offset);
24470 		return;
24471 	}
24472 
24473 	/* Get a copy of the header for the trailing frags */
24474 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24475 	if (!hdr_mp) {
24476 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24477 		freemsg(mp);
24478 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24479 		    "ip_wput_frag_end:(%S)",
24480 		    "couldn't copy hdr");
24481 		return;
24482 	}
24483 	if (DB_CRED(mp) != NULL)
24484 		mblk_setcred(hdr_mp, DB_CRED(mp));
24485 
24486 	/* Store the starting offset, with the MoreFrags flag. */
24487 	i1 = offset | IPH_MF | frag_flag;
24488 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24489 
24490 	/* Establish the ending byte offset, based on the starting offset. */
24491 	offset <<= 3;
24492 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24493 
24494 	/* Store the length of the first fragment in the IP header. */
24495 	i1 = len + hdr_len;
24496 	ASSERT(i1 <= IP_MAXPACKET);
24497 	ipha->ipha_length = htons((uint16_t)i1);
24498 
24499 	/*
24500 	 * Compute the IP header checksum for the first frag.  We have to
24501 	 * watch out that we stop at the end of the header.
24502 	 */
24503 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24504 
24505 	/*
24506 	 * Now carve off the first frag.  Note that this will include the
24507 	 * original IP header.
24508 	 */
24509 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24510 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24511 		freeb(hdr_mp);
24512 		freemsg(mp_orig);
24513 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24514 		    "ip_wput_frag_end:(%S)",
24515 		    "couldn't carve first");
24516 		return;
24517 	}
24518 
24519 	/*
24520 	 * Multirouting case. Each fragment is replicated
24521 	 * via all non-condemned RTF_MULTIRT routes
24522 	 * currently resolved.
24523 	 * We ensure that first_ire is the first RTF_MULTIRT
24524 	 * ire in the bucket.
24525 	 */
24526 	if (ire->ire_flags & RTF_MULTIRT) {
24527 		irb = ire->ire_bucket;
24528 		ASSERT(irb != NULL);
24529 
24530 		multirt_send = B_TRUE;
24531 
24532 		/* Make sure we do not omit any multiroute ire. */
24533 		IRB_REFHOLD(irb);
24534 		for (first_ire = irb->irb_ire;
24535 		    first_ire != NULL;
24536 		    first_ire = first_ire->ire_next) {
24537 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24538 			    (first_ire->ire_addr == ire->ire_addr) &&
24539 			    !(first_ire->ire_marks &
24540 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24541 				break;
24542 		}
24543 
24544 		if (first_ire != NULL) {
24545 			if (first_ire != ire) {
24546 				IRE_REFHOLD(first_ire);
24547 				/*
24548 				 * Do not release the ire passed in
24549 				 * as the argument.
24550 				 */
24551 				ire = first_ire;
24552 			} else {
24553 				first_ire = NULL;
24554 			}
24555 		}
24556 		IRB_REFRELE(irb);
24557 
24558 		/*
24559 		 * Save the first ire; we will need to restore it
24560 		 * for the trailing frags.
24561 		 * We REFHOLD save_ire, as each iterated ire will be
24562 		 * REFRELEd.
24563 		 */
24564 		save_ire = ire;
24565 		IRE_REFHOLD(save_ire);
24566 	}
24567 
24568 	/*
24569 	 * First fragment emission loop.
24570 	 * In most cases, the emission loop below is entered only
24571 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24572 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24573 	 * bucket, and send the fragment through all crossed
24574 	 * RTF_MULTIRT routes.
24575 	 */
24576 	do {
24577 		if (ire->ire_flags & RTF_MULTIRT) {
24578 			/*
24579 			 * We are in a multiple send case, need to get
24580 			 * the next ire and make a copy of the packet.
24581 			 * ire1 holds here the next ire to process in the
24582 			 * bucket. If multirouting is expected,
24583 			 * any non-RTF_MULTIRT ire that has the
24584 			 * right destination address is ignored.
24585 			 *
24586 			 * We have to take into account the MTU of
24587 			 * each walked ire. max_frag is set by the
24588 			 * the caller and generally refers to
24589 			 * the primary ire entry. Here we ensure that
24590 			 * no route with a lower MTU will be used, as
24591 			 * fragments are carved once for all ires,
24592 			 * then replicated.
24593 			 */
24594 			ASSERT(irb != NULL);
24595 			IRB_REFHOLD(irb);
24596 			for (ire1 = ire->ire_next;
24597 			    ire1 != NULL;
24598 			    ire1 = ire1->ire_next) {
24599 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24600 					continue;
24601 				if (ire1->ire_addr != ire->ire_addr)
24602 					continue;
24603 				if (ire1->ire_marks &
24604 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24605 					continue;
24606 				/*
24607 				 * Ensure we do not exceed the MTU
24608 				 * of the next route.
24609 				 */
24610 				if (ire1->ire_max_frag < max_frag) {
24611 					ip_multirt_bad_mtu(ire1, max_frag);
24612 					continue;
24613 				}
24614 
24615 				/* Got one. */
24616 				IRE_REFHOLD(ire1);
24617 				break;
24618 			}
24619 			IRB_REFRELE(irb);
24620 
24621 			if (ire1 != NULL) {
24622 				next_mp = copyb(mp);
24623 				if ((next_mp == NULL) ||
24624 				    ((mp->b_cont != NULL) &&
24625 				    ((next_mp->b_cont =
24626 				    dupmsg(mp->b_cont)) == NULL))) {
24627 					freemsg(next_mp);
24628 					next_mp = NULL;
24629 					ire_refrele(ire1);
24630 					ire1 = NULL;
24631 				}
24632 			}
24633 
24634 			/* Last multiroute ire; don't loop anymore. */
24635 			if (ire1 == NULL) {
24636 				multirt_send = B_FALSE;
24637 			}
24638 		}
24639 
24640 		ll_hdr_len = 0;
24641 		LOCK_IRE_FP_MP(ire);
24642 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24643 		if (ll_hdr_mp != NULL) {
24644 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24645 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24646 		} else {
24647 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24648 		}
24649 
24650 		/* If there is a transmit header, get a copy for this frag. */
24651 		/*
24652 		 * TODO: should check db_ref before calling ip_carve_mp since
24653 		 * it might give us a dup.
24654 		 */
24655 		if (!ll_hdr_mp) {
24656 			/* No xmit header. */
24657 			xmit_mp = mp;
24658 
24659 		/* We have a link-layer header that can fit in our mblk. */
24660 		} else if (mp->b_datap->db_ref == 1 &&
24661 		    ll_hdr_len != 0 &&
24662 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24663 			/* M_DATA fastpath */
24664 			mp->b_rptr -= ll_hdr_len;
24665 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24666 			xmit_mp = mp;
24667 
24668 		/* Corner case if copyb has failed */
24669 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24670 			UNLOCK_IRE_FP_MP(ire);
24671 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24672 			freeb(hdr_mp);
24673 			freemsg(mp);
24674 			freemsg(mp_orig);
24675 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24676 			    "ip_wput_frag_end:(%S)",
24677 			    "discard");
24678 
24679 			if (multirt_send) {
24680 				ASSERT(ire1);
24681 				ASSERT(next_mp);
24682 
24683 				freemsg(next_mp);
24684 				ire_refrele(ire1);
24685 			}
24686 			if (save_ire != NULL)
24687 				IRE_REFRELE(save_ire);
24688 
24689 			if (first_ire != NULL)
24690 				ire_refrele(first_ire);
24691 			return;
24692 
24693 		/*
24694 		 * Case of res_mp OR the fastpath mp can't fit
24695 		 * in the mblk
24696 		 */
24697 		} else {
24698 			xmit_mp->b_cont = mp;
24699 			if (DB_CRED(mp) != NULL)
24700 				mblk_setcred(xmit_mp, DB_CRED(mp));
24701 			/*
24702 			 * Get priority marking, if any.
24703 			 * We propagate the CoS marking from the
24704 			 * original packet that went to QoS processing
24705 			 * in ip_wput_ire to the newly carved mp.
24706 			 */
24707 			if (DB_TYPE(xmit_mp) == M_DATA)
24708 				xmit_mp->b_band = mp->b_band;
24709 		}
24710 		UNLOCK_IRE_FP_MP(ire);
24711 
24712 		q = ire->ire_stq;
24713 		out_ill = (ill_t *)q->q_ptr;
24714 
24715 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24716 
24717 		DTRACE_PROBE4(ip4__physical__out__start,
24718 		    ill_t *, NULL, ill_t *, out_ill,
24719 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24720 
24721 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24722 		    ipst->ips_ipv4firewall_physical_out,
24723 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24724 
24725 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24726 
24727 		if (xmit_mp != NULL) {
24728 			putnext(q, xmit_mp);
24729 
24730 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24731 			UPDATE_MIB(out_ill->ill_ip_mib,
24732 			    ipIfStatsHCOutOctets, i1);
24733 
24734 			if (pkt_type != OB_PKT) {
24735 				/*
24736 				 * Update the packet count and MIB stats
24737 				 * of trailing RTF_MULTIRT ires.
24738 				 */
24739 				UPDATE_OB_PKT_COUNT(ire);
24740 				BUMP_MIB(out_ill->ill_ip_mib,
24741 				    ipIfStatsOutFragReqds);
24742 			}
24743 		}
24744 
24745 		if (multirt_send) {
24746 			/*
24747 			 * We are in a multiple send case; look for
24748 			 * the next ire and re-enter the loop.
24749 			 */
24750 			ASSERT(ire1);
24751 			ASSERT(next_mp);
24752 			/* REFRELE the current ire before looping */
24753 			ire_refrele(ire);
24754 			ire = ire1;
24755 			ire1 = NULL;
24756 			mp = next_mp;
24757 			next_mp = NULL;
24758 		}
24759 	} while (multirt_send);
24760 
24761 	ASSERT(ire1 == NULL);
24762 
24763 	/* Restore the original ire; we need it for the trailing frags */
24764 	if (save_ire != NULL) {
24765 		/* REFRELE the last iterated ire */
24766 		ire_refrele(ire);
24767 		/* save_ire has been REFHOLDed */
24768 		ire = save_ire;
24769 		save_ire = NULL;
24770 		q = ire->ire_stq;
24771 	}
24772 
24773 	if (pkt_type == OB_PKT) {
24774 		UPDATE_OB_PKT_COUNT(ire);
24775 	} else {
24776 		out_ill = (ill_t *)q->q_ptr;
24777 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24778 		UPDATE_IB_PKT_COUNT(ire);
24779 	}
24780 
24781 	/* Advance the offset to the second frag starting point. */
24782 	offset += len;
24783 	/*
24784 	 * Update hdr_len from the copied header - there might be less options
24785 	 * in the later fragments.
24786 	 */
24787 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24788 	/* Loop until done. */
24789 	for (;;) {
24790 		uint16_t	offset_and_flags;
24791 		uint16_t	ip_len;
24792 
24793 		if (ip_data_end - offset > len) {
24794 			/*
24795 			 * Carve off the appropriate amount from the original
24796 			 * datagram.
24797 			 */
24798 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24799 				mp = NULL;
24800 				break;
24801 			}
24802 			/*
24803 			 * More frags after this one.  Get another copy
24804 			 * of the header.
24805 			 */
24806 			if (carve_mp->b_datap->db_ref == 1 &&
24807 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24808 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24809 				/* Inline IP header */
24810 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24811 				    hdr_mp->b_rptr;
24812 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24813 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24814 				mp = carve_mp;
24815 			} else {
24816 				if (!(mp = copyb(hdr_mp))) {
24817 					freemsg(carve_mp);
24818 					break;
24819 				}
24820 				/* Get priority marking, if any. */
24821 				mp->b_band = carve_mp->b_band;
24822 				mp->b_cont = carve_mp;
24823 			}
24824 			ipha = (ipha_t *)mp->b_rptr;
24825 			offset_and_flags = IPH_MF;
24826 		} else {
24827 			/*
24828 			 * Last frag.  Consume the header. Set len to
24829 			 * the length of this last piece.
24830 			 */
24831 			len = ip_data_end - offset;
24832 
24833 			/*
24834 			 * Carve off the appropriate amount from the original
24835 			 * datagram.
24836 			 */
24837 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24838 				mp = NULL;
24839 				break;
24840 			}
24841 			if (carve_mp->b_datap->db_ref == 1 &&
24842 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24843 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24844 				/* Inline IP header */
24845 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24846 				    hdr_mp->b_rptr;
24847 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24848 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24849 				mp = carve_mp;
24850 				freeb(hdr_mp);
24851 				hdr_mp = mp;
24852 			} else {
24853 				mp = hdr_mp;
24854 				/* Get priority marking, if any. */
24855 				mp->b_band = carve_mp->b_band;
24856 				mp->b_cont = carve_mp;
24857 			}
24858 			ipha = (ipha_t *)mp->b_rptr;
24859 			/* A frag of a frag might have IPH_MF non-zero */
24860 			offset_and_flags =
24861 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24862 			    IPH_MF;
24863 		}
24864 		offset_and_flags |= (uint16_t)(offset >> 3);
24865 		offset_and_flags |= (uint16_t)frag_flag;
24866 		/* Store the offset and flags in the IP header. */
24867 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24868 
24869 		/* Store the length in the IP header. */
24870 		ip_len = (uint16_t)(len + hdr_len);
24871 		ipha->ipha_length = htons(ip_len);
24872 
24873 		/*
24874 		 * Set the IP header checksum.	Note that mp is just
24875 		 * the header, so this is easy to pass to ip_csum.
24876 		 */
24877 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24878 
24879 		/* Attach a transmit header, if any, and ship it. */
24880 		if (pkt_type == OB_PKT) {
24881 			UPDATE_OB_PKT_COUNT(ire);
24882 		} else {
24883 			out_ill = (ill_t *)q->q_ptr;
24884 			BUMP_MIB(out_ill->ill_ip_mib,
24885 			    ipIfStatsHCOutForwDatagrams);
24886 			UPDATE_IB_PKT_COUNT(ire);
24887 		}
24888 
24889 		if (ire->ire_flags & RTF_MULTIRT) {
24890 			irb = ire->ire_bucket;
24891 			ASSERT(irb != NULL);
24892 
24893 			multirt_send = B_TRUE;
24894 
24895 			/*
24896 			 * Save the original ire; we will need to restore it
24897 			 * for the tailing frags.
24898 			 */
24899 			save_ire = ire;
24900 			IRE_REFHOLD(save_ire);
24901 		}
24902 		/*
24903 		 * Emission loop for this fragment, similar
24904 		 * to what is done for the first fragment.
24905 		 */
24906 		do {
24907 			if (multirt_send) {
24908 				/*
24909 				 * We are in a multiple send case, need to get
24910 				 * the next ire and make a copy of the packet.
24911 				 */
24912 				ASSERT(irb != NULL);
24913 				IRB_REFHOLD(irb);
24914 				for (ire1 = ire->ire_next;
24915 				    ire1 != NULL;
24916 				    ire1 = ire1->ire_next) {
24917 					if (!(ire1->ire_flags & RTF_MULTIRT))
24918 						continue;
24919 					if (ire1->ire_addr != ire->ire_addr)
24920 						continue;
24921 					if (ire1->ire_marks &
24922 					    (IRE_MARK_CONDEMNED|
24923 						IRE_MARK_HIDDEN))
24924 						continue;
24925 					/*
24926 					 * Ensure we do not exceed the MTU
24927 					 * of the next route.
24928 					 */
24929 					if (ire1->ire_max_frag < max_frag) {
24930 						ip_multirt_bad_mtu(ire1,
24931 						    max_frag);
24932 						continue;
24933 					}
24934 
24935 					/* Got one. */
24936 					IRE_REFHOLD(ire1);
24937 					break;
24938 				}
24939 				IRB_REFRELE(irb);
24940 
24941 				if (ire1 != NULL) {
24942 					next_mp = copyb(mp);
24943 					if ((next_mp == NULL) ||
24944 					    ((mp->b_cont != NULL) &&
24945 					    ((next_mp->b_cont =
24946 					    dupmsg(mp->b_cont)) == NULL))) {
24947 						freemsg(next_mp);
24948 						next_mp = NULL;
24949 						ire_refrele(ire1);
24950 						ire1 = NULL;
24951 					}
24952 				}
24953 
24954 				/* Last multiroute ire; don't loop anymore. */
24955 				if (ire1 == NULL) {
24956 					multirt_send = B_FALSE;
24957 				}
24958 			}
24959 
24960 			/* Update transmit header */
24961 			ll_hdr_len = 0;
24962 			LOCK_IRE_FP_MP(ire);
24963 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24964 			if (ll_hdr_mp != NULL) {
24965 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24966 				ll_hdr_len = MBLKL(ll_hdr_mp);
24967 			} else {
24968 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24969 			}
24970 
24971 			if (!ll_hdr_mp) {
24972 				xmit_mp = mp;
24973 
24974 			/*
24975 			 * We have link-layer header that can fit in
24976 			 * our mblk.
24977 			 */
24978 			} else if (mp->b_datap->db_ref == 1 &&
24979 			    ll_hdr_len != 0 &&
24980 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24981 				/* M_DATA fastpath */
24982 				mp->b_rptr -= ll_hdr_len;
24983 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24984 				    ll_hdr_len);
24985 				xmit_mp = mp;
24986 
24987 			/*
24988 			 * Case of res_mp OR the fastpath mp can't fit
24989 			 * in the mblk
24990 			 */
24991 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24992 				xmit_mp->b_cont = mp;
24993 				if (DB_CRED(mp) != NULL)
24994 					mblk_setcred(xmit_mp, DB_CRED(mp));
24995 				/* Get priority marking, if any. */
24996 				if (DB_TYPE(xmit_mp) == M_DATA)
24997 					xmit_mp->b_band = mp->b_band;
24998 
24999 			/* Corner case if copyb failed */
25000 			} else {
25001 				/*
25002 				 * Exit both the replication and
25003 				 * fragmentation loops.
25004 				 */
25005 				UNLOCK_IRE_FP_MP(ire);
25006 				goto drop_pkt;
25007 			}
25008 			UNLOCK_IRE_FP_MP(ire);
25009 
25010 			mp1 = mp;
25011 			out_ill = (ill_t *)q->q_ptr;
25012 
25013 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
25014 
25015 			DTRACE_PROBE4(ip4__physical__out__start,
25016 			    ill_t *, NULL, ill_t *, out_ill,
25017 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25018 
25019 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25020 			    ipst->ips_ipv4firewall_physical_out,
25021 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25022 
25023 			DTRACE_PROBE1(ip4__physical__out__end,
25024 			    mblk_t *, xmit_mp);
25025 
25026 			if (mp != mp1 && hdr_mp == mp1)
25027 				hdr_mp = mp;
25028 			if (mp != mp1 && mp_orig == mp1)
25029 				mp_orig = mp;
25030 
25031 			if (xmit_mp != NULL) {
25032 				putnext(q, xmit_mp);
25033 
25034 				BUMP_MIB(out_ill->ill_ip_mib,
25035 				    ipIfStatsHCOutTransmits);
25036 				UPDATE_MIB(out_ill->ill_ip_mib,
25037 				    ipIfStatsHCOutOctets, ip_len);
25038 
25039 				if (pkt_type != OB_PKT) {
25040 					/*
25041 					 * Update the packet count of trailing
25042 					 * RTF_MULTIRT ires.
25043 					 */
25044 					UPDATE_OB_PKT_COUNT(ire);
25045 				}
25046 			}
25047 
25048 			/* All done if we just consumed the hdr_mp. */
25049 			if (mp == hdr_mp) {
25050 				last_frag = B_TRUE;
25051 				BUMP_MIB(out_ill->ill_ip_mib,
25052 				    ipIfStatsOutFragOKs);
25053 			}
25054 
25055 			if (multirt_send) {
25056 				/*
25057 				 * We are in a multiple send case; look for
25058 				 * the next ire and re-enter the loop.
25059 				 */
25060 				ASSERT(ire1);
25061 				ASSERT(next_mp);
25062 				/* REFRELE the current ire before looping */
25063 				ire_refrele(ire);
25064 				ire = ire1;
25065 				ire1 = NULL;
25066 				q = ire->ire_stq;
25067 				mp = next_mp;
25068 				next_mp = NULL;
25069 			}
25070 		} while (multirt_send);
25071 		/*
25072 		 * Restore the original ire; we need it for the
25073 		 * trailing frags
25074 		 */
25075 		if (save_ire != NULL) {
25076 			ASSERT(ire1 == NULL);
25077 			/* REFRELE the last iterated ire */
25078 			ire_refrele(ire);
25079 			/* save_ire has been REFHOLDed */
25080 			ire = save_ire;
25081 			q = ire->ire_stq;
25082 			save_ire = NULL;
25083 		}
25084 
25085 		if (last_frag) {
25086 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25087 			    "ip_wput_frag_end:(%S)",
25088 			    "consumed hdr_mp");
25089 
25090 			if (first_ire != NULL)
25091 				ire_refrele(first_ire);
25092 			return;
25093 		}
25094 		/* Otherwise, advance and loop. */
25095 		offset += len;
25096 	}
25097 
25098 drop_pkt:
25099 	/* Clean up following allocation failure. */
25100 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25101 	freemsg(mp);
25102 	if (mp != hdr_mp)
25103 		freeb(hdr_mp);
25104 	if (mp != mp_orig)
25105 		freemsg(mp_orig);
25106 
25107 	if (save_ire != NULL)
25108 		IRE_REFRELE(save_ire);
25109 	if (first_ire != NULL)
25110 		ire_refrele(first_ire);
25111 
25112 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25113 	    "ip_wput_frag_end:(%S)",
25114 	    "end--alloc failure");
25115 }
25116 
25117 /*
25118  * Copy the header plus those options which have the copy bit set
25119  */
25120 static mblk_t *
25121 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25122 {
25123 	mblk_t	*mp;
25124 	uchar_t	*up;
25125 
25126 	/*
25127 	 * Quick check if we need to look for options without the copy bit
25128 	 * set
25129 	 */
25130 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25131 	if (!mp)
25132 		return (mp);
25133 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25134 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25135 		bcopy(rptr, mp->b_rptr, hdr_len);
25136 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25137 		return (mp);
25138 	}
25139 	up  = mp->b_rptr;
25140 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25141 	up += IP_SIMPLE_HDR_LENGTH;
25142 	rptr += IP_SIMPLE_HDR_LENGTH;
25143 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25144 	while (hdr_len > 0) {
25145 		uint32_t optval;
25146 		uint32_t optlen;
25147 
25148 		optval = *rptr;
25149 		if (optval == IPOPT_EOL)
25150 			break;
25151 		if (optval == IPOPT_NOP)
25152 			optlen = 1;
25153 		else
25154 			optlen = rptr[1];
25155 		if (optval & IPOPT_COPY) {
25156 			bcopy(rptr, up, optlen);
25157 			up += optlen;
25158 		}
25159 		rptr += optlen;
25160 		hdr_len -= optlen;
25161 	}
25162 	/*
25163 	 * Make sure that we drop an even number of words by filling
25164 	 * with EOL to the next word boundary.
25165 	 */
25166 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25167 	    hdr_len & 0x3; hdr_len++)
25168 		*up++ = IPOPT_EOL;
25169 	mp->b_wptr = up;
25170 	/* Update header length */
25171 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25172 	return (mp);
25173 }
25174 
25175 /*
25176  * Delivery to local recipients including fanout to multiple recipients.
25177  * Does not do checksumming of UDP/TCP.
25178  * Note: q should be the read side queue for either the ill or conn.
25179  * Note: rq should be the read side q for the lower (ill) stream.
25180  * We don't send packets to IPPF processing, thus the last argument
25181  * to all the fanout calls are B_FALSE.
25182  */
25183 void
25184 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25185     int fanout_flags, zoneid_t zoneid)
25186 {
25187 	uint32_t	protocol;
25188 	mblk_t		*first_mp;
25189 	boolean_t	mctl_present;
25190 	int		ire_type;
25191 #define	rptr	((uchar_t *)ipha)
25192 	ip_stack_t	*ipst = ill->ill_ipst;
25193 
25194 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25195 	    "ip_wput_local_start: q %p", q);
25196 
25197 	if (ire != NULL) {
25198 		ire_type = ire->ire_type;
25199 	} else {
25200 		/*
25201 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25202 		 * packet is not multicast, we can't tell the ire type.
25203 		 */
25204 		ASSERT(CLASSD(ipha->ipha_dst));
25205 		ire_type = IRE_BROADCAST;
25206 	}
25207 
25208 	first_mp = mp;
25209 	if (first_mp->b_datap->db_type == M_CTL) {
25210 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25211 		if (!io->ipsec_out_secure) {
25212 			/*
25213 			 * This ipsec_out_t was allocated in ip_wput
25214 			 * for multicast packets to store the ill_index.
25215 			 * As this is being delivered locally, we don't
25216 			 * need this anymore.
25217 			 */
25218 			mp = first_mp->b_cont;
25219 			freeb(first_mp);
25220 			first_mp = mp;
25221 			mctl_present = B_FALSE;
25222 		} else {
25223 			/*
25224 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25225 			 * security properties for the looped-back packet.
25226 			 */
25227 			mctl_present = B_TRUE;
25228 			mp = first_mp->b_cont;
25229 			ASSERT(mp != NULL);
25230 			ipsec_out_to_in(first_mp);
25231 		}
25232 	} else {
25233 		mctl_present = B_FALSE;
25234 	}
25235 
25236 	DTRACE_PROBE4(ip4__loopback__in__start,
25237 	    ill_t *, ill, ill_t *, NULL,
25238 	    ipha_t *, ipha, mblk_t *, first_mp);
25239 
25240 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25241 	    ipst->ips_ipv4firewall_loopback_in,
25242 	    ill, NULL, ipha, first_mp, mp, ipst);
25243 
25244 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25245 
25246 	if (first_mp == NULL)
25247 		return;
25248 
25249 	ipst->ips_loopback_packets++;
25250 
25251 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25252 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25253 	if (!IS_SIMPLE_IPH(ipha)) {
25254 		ip_wput_local_options(ipha, ipst);
25255 	}
25256 
25257 	protocol = ipha->ipha_protocol;
25258 	switch (protocol) {
25259 	case IPPROTO_ICMP: {
25260 		ire_t		*ire_zone;
25261 		ilm_t		*ilm;
25262 		mblk_t		*mp1;
25263 		zoneid_t	last_zoneid;
25264 
25265 		if (CLASSD(ipha->ipha_dst) &&
25266 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
25267 			ASSERT(ire_type == IRE_BROADCAST);
25268 			/*
25269 			 * In the multicast case, applications may have joined
25270 			 * the group from different zones, so we need to deliver
25271 			 * the packet to each of them. Loop through the
25272 			 * multicast memberships structures (ilm) on the receive
25273 			 * ill and send a copy of the packet up each matching
25274 			 * one. However, we don't do this for multicasts sent on
25275 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25276 			 * they must stay in the sender's zone.
25277 			 *
25278 			 * ilm_add_v6() ensures that ilms in the same zone are
25279 			 * contiguous in the ill_ilm list. We use this property
25280 			 * to avoid sending duplicates needed when two
25281 			 * applications in the same zone join the same group on
25282 			 * different logical interfaces: we ignore the ilm if
25283 			 * it's zoneid is the same as the last matching one.
25284 			 * In addition, the sending of the packet for
25285 			 * ire_zoneid is delayed until all of the other ilms
25286 			 * have been exhausted.
25287 			 */
25288 			last_zoneid = -1;
25289 			ILM_WALKER_HOLD(ill);
25290 			for (ilm = ill->ill_ilm; ilm != NULL;
25291 			    ilm = ilm->ilm_next) {
25292 				if ((ilm->ilm_flags & ILM_DELETED) ||
25293 				    ipha->ipha_dst != ilm->ilm_addr ||
25294 				    ilm->ilm_zoneid == last_zoneid ||
25295 				    ilm->ilm_zoneid == zoneid ||
25296 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25297 					continue;
25298 				mp1 = ip_copymsg(first_mp);
25299 				if (mp1 == NULL)
25300 					continue;
25301 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25302 				    mctl_present, B_FALSE, ill,
25303 				    ilm->ilm_zoneid);
25304 				last_zoneid = ilm->ilm_zoneid;
25305 			}
25306 			ILM_WALKER_RELE(ill);
25307 			/*
25308 			 * Loopback case: the sending endpoint has
25309 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25310 			 * dispatch the multicast packet to the sending zone.
25311 			 */
25312 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25313 				freemsg(first_mp);
25314 				return;
25315 			}
25316 		} else if (ire_type == IRE_BROADCAST) {
25317 			/*
25318 			 * In the broadcast case, there may be many zones
25319 			 * which need a copy of the packet delivered to them.
25320 			 * There is one IRE_BROADCAST per broadcast address
25321 			 * and per zone; we walk those using a helper function.
25322 			 * In addition, the sending of the packet for zoneid is
25323 			 * delayed until all of the other ires have been
25324 			 * processed.
25325 			 */
25326 			IRB_REFHOLD(ire->ire_bucket);
25327 			ire_zone = NULL;
25328 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25329 			    ire)) != NULL) {
25330 				mp1 = ip_copymsg(first_mp);
25331 				if (mp1 == NULL)
25332 					continue;
25333 
25334 				UPDATE_IB_PKT_COUNT(ire_zone);
25335 				ire_zone->ire_last_used_time = lbolt;
25336 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25337 				    mctl_present, B_FALSE, ill,
25338 				    ire_zone->ire_zoneid);
25339 			}
25340 			IRB_REFRELE(ire->ire_bucket);
25341 		}
25342 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25343 		    0, mctl_present, B_FALSE, ill, zoneid);
25344 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25345 		    "ip_wput_local_end: q %p (%S)",
25346 		    q, "icmp");
25347 		return;
25348 	}
25349 	case IPPROTO_IGMP:
25350 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25351 			/* Bad packet - discarded by igmp_input */
25352 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25353 			    "ip_wput_local_end: q %p (%S)",
25354 			    q, "igmp_input--bad packet");
25355 			if (mctl_present)
25356 				freeb(first_mp);
25357 			return;
25358 		}
25359 		/*
25360 		 * igmp_input() may have returned the pulled up message.
25361 		 * So first_mp and ipha need to be reinitialized.
25362 		 */
25363 		ipha = (ipha_t *)mp->b_rptr;
25364 		if (mctl_present)
25365 			first_mp->b_cont = mp;
25366 		else
25367 			first_mp = mp;
25368 		/* deliver to local raw users */
25369 		break;
25370 	case IPPROTO_ENCAP:
25371 		/*
25372 		 * This case is covered by either ip_fanout_proto, or by
25373 		 * the above security processing for self-tunneled packets.
25374 		 */
25375 		break;
25376 	case IPPROTO_UDP: {
25377 		uint16_t	*up;
25378 		uint32_t	ports;
25379 
25380 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25381 		    UDP_PORTS_OFFSET);
25382 		/* Force a 'valid' checksum. */
25383 		up[3] = 0;
25384 
25385 		ports = *(uint32_t *)up;
25386 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25387 		    (ire_type == IRE_BROADCAST),
25388 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25389 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25390 		    ill, zoneid);
25391 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25392 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25393 		return;
25394 	}
25395 	case IPPROTO_TCP: {
25396 
25397 		/*
25398 		 * For TCP, discard broadcast packets.
25399 		 */
25400 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25401 			freemsg(first_mp);
25402 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25403 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25404 			return;
25405 		}
25406 
25407 		if (mp->b_datap->db_type == M_DATA) {
25408 			/*
25409 			 * M_DATA mblk, so init mblk (chain) for no struio().
25410 			 */
25411 			mblk_t	*mp1 = mp;
25412 
25413 			do
25414 				mp1->b_datap->db_struioflag = 0;
25415 			while ((mp1 = mp1->b_cont) != NULL);
25416 		}
25417 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25418 		    <= mp->b_wptr);
25419 		ip_fanout_tcp(q, first_mp, ill, ipha,
25420 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25421 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25422 		    mctl_present, B_FALSE, zoneid);
25423 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25424 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25425 		return;
25426 	}
25427 	case IPPROTO_SCTP:
25428 	{
25429 		uint32_t	ports;
25430 
25431 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25432 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25433 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25434 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25435 		return;
25436 	}
25437 
25438 	default:
25439 		break;
25440 	}
25441 	/*
25442 	 * Find a client for some other protocol.  We give
25443 	 * copies to multiple clients, if more than one is
25444 	 * bound.
25445 	 */
25446 	ip_fanout_proto(q, first_mp, ill, ipha,
25447 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25448 	    mctl_present, B_FALSE, ill, zoneid);
25449 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25450 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25451 #undef	rptr
25452 }
25453 
25454 /*
25455  * Update any source route, record route, or timestamp options.
25456  * Check that we are at end of strict source route.
25457  * The options have been sanity checked by ip_wput_options().
25458  */
25459 static void
25460 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25461 {
25462 	ipoptp_t	opts;
25463 	uchar_t		*opt;
25464 	uint8_t		optval;
25465 	uint8_t		optlen;
25466 	ipaddr_t	dst;
25467 	uint32_t	ts;
25468 	ire_t		*ire;
25469 	timestruc_t	now;
25470 
25471 	ip2dbg(("ip_wput_local_options\n"));
25472 	for (optval = ipoptp_first(&opts, ipha);
25473 	    optval != IPOPT_EOL;
25474 	    optval = ipoptp_next(&opts)) {
25475 		opt = opts.ipoptp_cur;
25476 		optlen = opts.ipoptp_len;
25477 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25478 		switch (optval) {
25479 			uint32_t off;
25480 		case IPOPT_SSRR:
25481 		case IPOPT_LSRR:
25482 			off = opt[IPOPT_OFFSET];
25483 			off--;
25484 			if (optlen < IP_ADDR_LEN ||
25485 			    off > optlen - IP_ADDR_LEN) {
25486 				/* End of source route */
25487 				break;
25488 			}
25489 			/*
25490 			 * This will only happen if two consecutive entries
25491 			 * in the source route contains our address or if
25492 			 * it is a packet with a loose source route which
25493 			 * reaches us before consuming the whole source route
25494 			 */
25495 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25496 			if (optval == IPOPT_SSRR) {
25497 				return;
25498 			}
25499 			/*
25500 			 * Hack: instead of dropping the packet truncate the
25501 			 * source route to what has been used by filling the
25502 			 * rest with IPOPT_NOP.
25503 			 */
25504 			opt[IPOPT_OLEN] = (uint8_t)off;
25505 			while (off < optlen) {
25506 				opt[off++] = IPOPT_NOP;
25507 			}
25508 			break;
25509 		case IPOPT_RR:
25510 			off = opt[IPOPT_OFFSET];
25511 			off--;
25512 			if (optlen < IP_ADDR_LEN ||
25513 			    off > optlen - IP_ADDR_LEN) {
25514 				/* No more room - ignore */
25515 				ip1dbg((
25516 				    "ip_wput_forward_options: end of RR\n"));
25517 				break;
25518 			}
25519 			dst = htonl(INADDR_LOOPBACK);
25520 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25521 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25522 			break;
25523 		case IPOPT_TS:
25524 			/* Insert timestamp if there is romm */
25525 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25526 			case IPOPT_TS_TSONLY:
25527 				off = IPOPT_TS_TIMELEN;
25528 				break;
25529 			case IPOPT_TS_PRESPEC:
25530 			case IPOPT_TS_PRESPEC_RFC791:
25531 				/* Verify that the address matched */
25532 				off = opt[IPOPT_OFFSET] - 1;
25533 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25534 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25535 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25536 				    ipst);
25537 				if (ire == NULL) {
25538 					/* Not for us */
25539 					break;
25540 				}
25541 				ire_refrele(ire);
25542 				/* FALLTHRU */
25543 			case IPOPT_TS_TSANDADDR:
25544 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25545 				break;
25546 			default:
25547 				/*
25548 				 * ip_*put_options should have already
25549 				 * dropped this packet.
25550 				 */
25551 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25552 				    "unknown IT - bug in ip_wput_options?\n");
25553 				return;	/* Keep "lint" happy */
25554 			}
25555 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25556 				/* Increase overflow counter */
25557 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25558 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25559 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25560 				    (off << 4);
25561 				break;
25562 			}
25563 			off = opt[IPOPT_OFFSET] - 1;
25564 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25565 			case IPOPT_TS_PRESPEC:
25566 			case IPOPT_TS_PRESPEC_RFC791:
25567 			case IPOPT_TS_TSANDADDR:
25568 				dst = htonl(INADDR_LOOPBACK);
25569 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25570 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25571 				/* FALLTHRU */
25572 			case IPOPT_TS_TSONLY:
25573 				off = opt[IPOPT_OFFSET] - 1;
25574 				/* Compute # of milliseconds since midnight */
25575 				gethrestime(&now);
25576 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25577 				    now.tv_nsec / (NANOSEC / MILLISEC);
25578 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25579 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25580 				break;
25581 			}
25582 			break;
25583 		}
25584 	}
25585 }
25586 
25587 /*
25588  * Send out a multicast packet on interface ipif.
25589  * The sender does not have an conn.
25590  * Caller verifies that this isn't a PHYI_LOOPBACK.
25591  */
25592 void
25593 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25594 {
25595 	ipha_t	*ipha;
25596 	ire_t	*ire;
25597 	ipaddr_t	dst;
25598 	mblk_t		*first_mp;
25599 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25600 
25601 	/* igmp_sendpkt always allocates a ipsec_out_t */
25602 	ASSERT(mp->b_datap->db_type == M_CTL);
25603 	ASSERT(!ipif->ipif_isv6);
25604 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
25605 
25606 	first_mp = mp;
25607 	mp = first_mp->b_cont;
25608 	ASSERT(mp->b_datap->db_type == M_DATA);
25609 	ipha = (ipha_t *)mp->b_rptr;
25610 
25611 	/*
25612 	 * Find an IRE which matches the destination and the outgoing
25613 	 * queue (i.e. the outgoing interface.)
25614 	 */
25615 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25616 		dst = ipif->ipif_pp_dst_addr;
25617 	else
25618 		dst = ipha->ipha_dst;
25619 	/*
25620 	 * The source address has already been initialized by the
25621 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25622 	 * be sufficient rather than MATCH_IRE_IPIF.
25623 	 *
25624 	 * This function is used for sending IGMP packets. We need
25625 	 * to make sure that we send the packet out of the interface
25626 	 * (ipif->ipif_ill) where we joined the group. This is to
25627 	 * prevent from switches doing IGMP snooping to send us multicast
25628 	 * packets for a given group on the interface we have joined.
25629 	 * If we can't find an ire, igmp_sendpkt has already initialized
25630 	 * ipsec_out_attach_if so that this will not be load spread in
25631 	 * ip_newroute_ipif.
25632 	 */
25633 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25634 	    MATCH_IRE_ILL, ipst);
25635 	if (!ire) {
25636 		/*
25637 		 * Mark this packet to make it be delivered to
25638 		 * ip_wput_ire after the new ire has been
25639 		 * created.
25640 		 */
25641 		mp->b_prev = NULL;
25642 		mp->b_next = NULL;
25643 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25644 		    zoneid, &zero_info);
25645 		return;
25646 	}
25647 
25648 	/*
25649 	 * Honor the RTF_SETSRC flag; this is the only case
25650 	 * where we force this addr whatever the current src addr is,
25651 	 * because this address is set by igmp_sendpkt(), and
25652 	 * cannot be specified by any user.
25653 	 */
25654 	if (ire->ire_flags & RTF_SETSRC) {
25655 		ipha->ipha_src = ire->ire_src_addr;
25656 	}
25657 
25658 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25659 }
25660 
25661 /*
25662  * NOTE : This function does not ire_refrele the ire argument passed in.
25663  *
25664  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25665  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25666  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25667  * the ire_lock to access the nce_fp_mp in this case.
25668  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25669  * prepending a fastpath message IPQoS processing must precede it, we also set
25670  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25671  * (IPQoS might have set the b_band for CoS marking).
25672  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25673  * must follow it so that IPQoS can mark the dl_priority field for CoS
25674  * marking, if needed.
25675  */
25676 static mblk_t *
25677 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25678 {
25679 	uint_t	hlen;
25680 	ipha_t *ipha;
25681 	mblk_t *mp1;
25682 	boolean_t qos_done = B_FALSE;
25683 	uchar_t	*ll_hdr;
25684 	ip_stack_t	*ipst = ire->ire_ipst;
25685 
25686 #define	rptr	((uchar_t *)ipha)
25687 
25688 	ipha = (ipha_t *)mp->b_rptr;
25689 	hlen = 0;
25690 	LOCK_IRE_FP_MP(ire);
25691 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25692 		ASSERT(DB_TYPE(mp1) == M_DATA);
25693 		/* Initiate IPPF processing */
25694 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25695 			UNLOCK_IRE_FP_MP(ire);
25696 			ip_process(proc, &mp, ill_index);
25697 			if (mp == NULL)
25698 				return (NULL);
25699 
25700 			ipha = (ipha_t *)mp->b_rptr;
25701 			LOCK_IRE_FP_MP(ire);
25702 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25703 				qos_done = B_TRUE;
25704 				goto no_fp_mp;
25705 			}
25706 			ASSERT(DB_TYPE(mp1) == M_DATA);
25707 		}
25708 		hlen = MBLKL(mp1);
25709 		/*
25710 		 * Check if we have enough room to prepend fastpath
25711 		 * header
25712 		 */
25713 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25714 			ll_hdr = rptr - hlen;
25715 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25716 			/*
25717 			 * Set the b_rptr to the start of the link layer
25718 			 * header
25719 			 */
25720 			mp->b_rptr = ll_hdr;
25721 			mp1 = mp;
25722 		} else {
25723 			mp1 = copyb(mp1);
25724 			if (mp1 == NULL)
25725 				goto unlock_err;
25726 			mp1->b_band = mp->b_band;
25727 			mp1->b_cont = mp;
25728 			/*
25729 			 * certain system generated traffic may not
25730 			 * have cred/label in ip header block. This
25731 			 * is true even for a labeled system. But for
25732 			 * labeled traffic, inherit the label in the
25733 			 * new header.
25734 			 */
25735 			if (DB_CRED(mp) != NULL)
25736 				mblk_setcred(mp1, DB_CRED(mp));
25737 			/*
25738 			 * XXX disable ICK_VALID and compute checksum
25739 			 * here; can happen if nce_fp_mp changes and
25740 			 * it can't be copied now due to insufficient
25741 			 * space. (unlikely, fp mp can change, but it
25742 			 * does not increase in length)
25743 			 */
25744 		}
25745 		UNLOCK_IRE_FP_MP(ire);
25746 	} else {
25747 no_fp_mp:
25748 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25749 		if (mp1 == NULL) {
25750 unlock_err:
25751 			UNLOCK_IRE_FP_MP(ire);
25752 			freemsg(mp);
25753 			return (NULL);
25754 		}
25755 		UNLOCK_IRE_FP_MP(ire);
25756 		mp1->b_cont = mp;
25757 		/*
25758 		 * certain system generated traffic may not
25759 		 * have cred/label in ip header block. This
25760 		 * is true even for a labeled system. But for
25761 		 * labeled traffic, inherit the label in the
25762 		 * new header.
25763 		 */
25764 		if (DB_CRED(mp) != NULL)
25765 			mblk_setcred(mp1, DB_CRED(mp));
25766 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25767 			ip_process(proc, &mp1, ill_index);
25768 			if (mp1 == NULL)
25769 				return (NULL);
25770 		}
25771 	}
25772 	return (mp1);
25773 #undef rptr
25774 }
25775 
25776 /*
25777  * Finish the outbound IPsec processing for an IPv6 packet. This function
25778  * is called from ipsec_out_process() if the IPsec packet was processed
25779  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25780  * asynchronously.
25781  */
25782 void
25783 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25784     ire_t *ire_arg)
25785 {
25786 	in6_addr_t *v6dstp;
25787 	ire_t *ire;
25788 	mblk_t *mp;
25789 	ip6_t *ip6h1;
25790 	uint_t	ill_index;
25791 	ipsec_out_t *io;
25792 	boolean_t attach_if, hwaccel;
25793 	uint32_t flags = IP6_NO_IPPOLICY;
25794 	int match_flags;
25795 	zoneid_t zoneid;
25796 	boolean_t ill_need_rele = B_FALSE;
25797 	boolean_t ire_need_rele = B_FALSE;
25798 	ip_stack_t	*ipst;
25799 
25800 	mp = ipsec_mp->b_cont;
25801 	ip6h1 = (ip6_t *)mp->b_rptr;
25802 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25803 	ASSERT(io->ipsec_out_ns != NULL);
25804 	ipst = io->ipsec_out_ns->netstack_ip;
25805 	ill_index = io->ipsec_out_ill_index;
25806 	if (io->ipsec_out_reachable) {
25807 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25808 	}
25809 	attach_if = io->ipsec_out_attach_if;
25810 	hwaccel = io->ipsec_out_accelerated;
25811 	zoneid = io->ipsec_out_zoneid;
25812 	ASSERT(zoneid != ALL_ZONES);
25813 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25814 	/* Multicast addresses should have non-zero ill_index. */
25815 	v6dstp = &ip6h->ip6_dst;
25816 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25817 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25818 	ASSERT(!attach_if || ill_index != 0);
25819 	if (ill_index != 0) {
25820 		if (ill == NULL) {
25821 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25822 			    B_TRUE, ipst);
25823 
25824 			/* Failure case frees things for us. */
25825 			if (ill == NULL)
25826 				return;
25827 
25828 			ill_need_rele = B_TRUE;
25829 		}
25830 		/*
25831 		 * If this packet needs to go out on a particular interface
25832 		 * honor it.
25833 		 */
25834 		if (attach_if) {
25835 			match_flags = MATCH_IRE_ILL;
25836 
25837 			/*
25838 			 * Check if we need an ire that will not be
25839 			 * looked up by anybody else i.e. HIDDEN.
25840 			 */
25841 			if (ill_is_probeonly(ill)) {
25842 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25843 			}
25844 		}
25845 	}
25846 	ASSERT(mp != NULL);
25847 
25848 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25849 		boolean_t unspec_src;
25850 		ipif_t	*ipif;
25851 
25852 		/*
25853 		 * Use the ill_index to get the right ill.
25854 		 */
25855 		unspec_src = io->ipsec_out_unspec_src;
25856 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25857 		if (ipif == NULL) {
25858 			if (ill_need_rele)
25859 				ill_refrele(ill);
25860 			freemsg(ipsec_mp);
25861 			return;
25862 		}
25863 
25864 		if (ire_arg != NULL) {
25865 			ire = ire_arg;
25866 		} else {
25867 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25868 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25869 			ire_need_rele = B_TRUE;
25870 		}
25871 		if (ire != NULL) {
25872 			ipif_refrele(ipif);
25873 			/*
25874 			 * XXX Do the multicast forwarding now, as the IPSEC
25875 			 * processing has been done.
25876 			 */
25877 			goto send;
25878 		}
25879 
25880 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25881 		mp->b_prev = NULL;
25882 		mp->b_next = NULL;
25883 
25884 		/*
25885 		 * If the IPsec packet was processed asynchronously,
25886 		 * drop it now.
25887 		 */
25888 		if (q == NULL) {
25889 			if (ill_need_rele)
25890 				ill_refrele(ill);
25891 			freemsg(ipsec_mp);
25892 			return;
25893 		}
25894 
25895 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25896 		    unspec_src, zoneid);
25897 		ipif_refrele(ipif);
25898 	} else {
25899 		if (attach_if) {
25900 			ipif_t	*ipif;
25901 
25902 			ipif = ipif_get_next_ipif(NULL, ill);
25903 			if (ipif == NULL) {
25904 				if (ill_need_rele)
25905 					ill_refrele(ill);
25906 				freemsg(ipsec_mp);
25907 				return;
25908 			}
25909 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25910 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25911 			ire_need_rele = B_TRUE;
25912 			ipif_refrele(ipif);
25913 		} else {
25914 			if (ire_arg != NULL) {
25915 				ire = ire_arg;
25916 			} else {
25917 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25918 				    ipst);
25919 				ire_need_rele = B_TRUE;
25920 			}
25921 		}
25922 		if (ire != NULL)
25923 			goto send;
25924 		/*
25925 		 * ire disappeared underneath.
25926 		 *
25927 		 * What we need to do here is the ip_newroute
25928 		 * logic to get the ire without doing the IPSEC
25929 		 * processing. Follow the same old path. But this
25930 		 * time, ip_wput or ire_add_then_send will call us
25931 		 * directly as all the IPSEC operations are done.
25932 		 */
25933 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25934 		mp->b_prev = NULL;
25935 		mp->b_next = NULL;
25936 
25937 		/*
25938 		 * If the IPsec packet was processed asynchronously,
25939 		 * drop it now.
25940 		 */
25941 		if (q == NULL) {
25942 			if (ill_need_rele)
25943 				ill_refrele(ill);
25944 			freemsg(ipsec_mp);
25945 			return;
25946 		}
25947 
25948 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25949 		    zoneid, ipst);
25950 	}
25951 	if (ill != NULL && ill_need_rele)
25952 		ill_refrele(ill);
25953 	return;
25954 send:
25955 	if (ill != NULL && ill_need_rele)
25956 		ill_refrele(ill);
25957 
25958 	/* Local delivery */
25959 	if (ire->ire_stq == NULL) {
25960 		ill_t	*out_ill;
25961 		ASSERT(q != NULL);
25962 
25963 		/* PFHooks: LOOPBACK_OUT */
25964 		out_ill = ire->ire_ipif->ipif_ill;
25965 
25966 		DTRACE_PROBE4(ip6__loopback__out__start,
25967 		    ill_t *, NULL, ill_t *, out_ill,
25968 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25969 
25970 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25971 		    ipst->ips_ipv6firewall_loopback_out,
25972 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25973 
25974 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25975 
25976 		if (ipsec_mp != NULL)
25977 			ip_wput_local_v6(RD(q), out_ill,
25978 			    ip6h, ipsec_mp, ire, 0);
25979 		if (ire_need_rele)
25980 			ire_refrele(ire);
25981 		return;
25982 	}
25983 	/*
25984 	 * Everything is done. Send it out on the wire.
25985 	 * We force the insertion of a fragment header using the
25986 	 * IPH_FRAG_HDR flag in two cases:
25987 	 * - after reception of an ICMPv6 "packet too big" message
25988 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25989 	 * - for multirouted IPv6 packets, so that the receiver can
25990 	 *   discard duplicates according to their fragment identifier
25991 	 */
25992 	/* XXX fix flow control problems. */
25993 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25994 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25995 		if (hwaccel) {
25996 			/*
25997 			 * hardware acceleration does not handle these
25998 			 * "slow path" cases.
25999 			 */
26000 			/* IPsec KSTATS: should bump bean counter here. */
26001 			if (ire_need_rele)
26002 				ire_refrele(ire);
26003 			freemsg(ipsec_mp);
26004 			return;
26005 		}
26006 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
26007 		    (mp->b_cont ? msgdsize(mp) :
26008 		    mp->b_wptr - (uchar_t *)ip6h)) {
26009 			/* IPsec KSTATS: should bump bean counter here. */
26010 			ip0dbg(("Packet length mismatch: %d, %ld\n",
26011 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
26012 			    msgdsize(mp)));
26013 			if (ire_need_rele)
26014 				ire_refrele(ire);
26015 			freemsg(ipsec_mp);
26016 			return;
26017 		}
26018 		ASSERT(mp->b_prev == NULL);
26019 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26020 		    ntohs(ip6h->ip6_plen) +
26021 		    IPV6_HDR_LEN, ire->ire_max_frag));
26022 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26023 		    ire->ire_max_frag);
26024 	} else {
26025 		UPDATE_OB_PKT_COUNT(ire);
26026 		ire->ire_last_used_time = lbolt;
26027 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26028 	}
26029 	if (ire_need_rele)
26030 		ire_refrele(ire);
26031 	freeb(ipsec_mp);
26032 }
26033 
26034 void
26035 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26036 {
26037 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26038 	da_ipsec_t *hada;	/* data attributes */
26039 	ill_t *ill = (ill_t *)q->q_ptr;
26040 
26041 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26042 
26043 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26044 		/* IPsec KSTATS: Bump lose counter here! */
26045 		freemsg(mp);
26046 		return;
26047 	}
26048 
26049 	/*
26050 	 * It's an IPsec packet that must be
26051 	 * accelerated by the Provider, and the
26052 	 * outbound ill is IPsec acceleration capable.
26053 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26054 	 * to the ill.
26055 	 * IPsec KSTATS: should bump packet counter here.
26056 	 */
26057 
26058 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26059 	if (hada_mp == NULL) {
26060 		/* IPsec KSTATS: should bump packet counter here. */
26061 		freemsg(mp);
26062 		return;
26063 	}
26064 
26065 	hada_mp->b_datap->db_type = M_CTL;
26066 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26067 	hada_mp->b_cont = mp;
26068 
26069 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26070 	bzero(hada, sizeof (da_ipsec_t));
26071 	hada->da_type = IPHADA_M_CTL;
26072 
26073 	putnext(q, hada_mp);
26074 }
26075 
26076 /*
26077  * Finish the outbound IPsec processing. This function is called from
26078  * ipsec_out_process() if the IPsec packet was processed
26079  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26080  * asynchronously.
26081  */
26082 void
26083 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26084     ire_t *ire_arg)
26085 {
26086 	uint32_t v_hlen_tos_len;
26087 	ipaddr_t	dst;
26088 	ipif_t	*ipif = NULL;
26089 	ire_t *ire;
26090 	ire_t *ire1 = NULL;
26091 	mblk_t *next_mp = NULL;
26092 	uint32_t max_frag;
26093 	boolean_t multirt_send = B_FALSE;
26094 	mblk_t *mp;
26095 	mblk_t *mp1;
26096 	ipha_t *ipha1;
26097 	uint_t	ill_index;
26098 	ipsec_out_t *io;
26099 	boolean_t attach_if;
26100 	int match_flags, offset;
26101 	irb_t *irb = NULL;
26102 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26103 	zoneid_t zoneid;
26104 	uint32_t cksum;
26105 	uint16_t *up;
26106 	ipxmit_state_t	pktxmit_state;
26107 	ip_stack_t	*ipst;
26108 
26109 #ifdef	_BIG_ENDIAN
26110 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26111 #else
26112 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26113 #endif
26114 
26115 	mp = ipsec_mp->b_cont;
26116 	ipha1 = (ipha_t *)mp->b_rptr;
26117 	ASSERT(mp != NULL);
26118 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26119 	dst = ipha->ipha_dst;
26120 
26121 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26122 	ill_index = io->ipsec_out_ill_index;
26123 	attach_if = io->ipsec_out_attach_if;
26124 	zoneid = io->ipsec_out_zoneid;
26125 	ASSERT(zoneid != ALL_ZONES);
26126 	ipst = io->ipsec_out_ns->netstack_ip;
26127 	ASSERT(io->ipsec_out_ns != NULL);
26128 
26129 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26130 	if (ill_index != 0) {
26131 		if (ill == NULL) {
26132 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26133 			    ill_index, B_FALSE, ipst);
26134 
26135 			/* Failure case frees things for us. */
26136 			if (ill == NULL)
26137 				return;
26138 
26139 			ill_need_rele = B_TRUE;
26140 		}
26141 		/*
26142 		 * If this packet needs to go out on a particular interface
26143 		 * honor it.
26144 		 */
26145 		if (attach_if) {
26146 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26147 
26148 			/*
26149 			 * Check if we need an ire that will not be
26150 			 * looked up by anybody else i.e. HIDDEN.
26151 			 */
26152 			if (ill_is_probeonly(ill)) {
26153 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26154 			}
26155 		}
26156 	}
26157 
26158 	if (CLASSD(dst)) {
26159 		boolean_t conn_dontroute;
26160 		/*
26161 		 * Use the ill_index to get the right ipif.
26162 		 */
26163 		conn_dontroute = io->ipsec_out_dontroute;
26164 		if (ill_index == 0)
26165 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26166 		else
26167 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26168 		if (ipif == NULL) {
26169 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26170 			    " multicast\n"));
26171 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26172 			freemsg(ipsec_mp);
26173 			goto done;
26174 		}
26175 		/*
26176 		 * ipha_src has already been intialized with the
26177 		 * value of the ipif in ip_wput. All we need now is
26178 		 * an ire to send this downstream.
26179 		 */
26180 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26181 		    MBLK_GETLABEL(mp), match_flags, ipst);
26182 		if (ire != NULL) {
26183 			ill_t *ill1;
26184 			/*
26185 			 * Do the multicast forwarding now, as the IPSEC
26186 			 * processing has been done.
26187 			 */
26188 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26189 			    (ill1 = ire_to_ill(ire))) {
26190 				if (ip_mforward(ill1, ipha, mp)) {
26191 					freemsg(ipsec_mp);
26192 					ip1dbg(("ip_wput_ipsec_out: mforward "
26193 					    "failed\n"));
26194 					ire_refrele(ire);
26195 					goto done;
26196 				}
26197 			}
26198 			goto send;
26199 		}
26200 
26201 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26202 		mp->b_prev = NULL;
26203 		mp->b_next = NULL;
26204 
26205 		/*
26206 		 * If the IPsec packet was processed asynchronously,
26207 		 * drop it now.
26208 		 */
26209 		if (q == NULL) {
26210 			freemsg(ipsec_mp);
26211 			goto done;
26212 		}
26213 
26214 		/*
26215 		 * We may be using a wrong ipif to create the ire.
26216 		 * But it is okay as the source address is assigned
26217 		 * for the packet already. Next outbound packet would
26218 		 * create the IRE with the right IPIF in ip_wput.
26219 		 *
26220 		 * Also handle RTF_MULTIRT routes.
26221 		 */
26222 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26223 		    zoneid, &zero_info);
26224 	} else {
26225 		if (attach_if) {
26226 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26227 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26228 		} else {
26229 			if (ire_arg != NULL) {
26230 				ire = ire_arg;
26231 				ire_need_rele = B_FALSE;
26232 			} else {
26233 				ire = ire_cache_lookup(dst, zoneid,
26234 				    MBLK_GETLABEL(mp), ipst);
26235 			}
26236 		}
26237 		if (ire != NULL) {
26238 			goto send;
26239 		}
26240 
26241 		/*
26242 		 * ire disappeared underneath.
26243 		 *
26244 		 * What we need to do here is the ip_newroute
26245 		 * logic to get the ire without doing the IPSEC
26246 		 * processing. Follow the same old path. But this
26247 		 * time, ip_wput or ire_add_then_put will call us
26248 		 * directly as all the IPSEC operations are done.
26249 		 */
26250 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26251 		mp->b_prev = NULL;
26252 		mp->b_next = NULL;
26253 
26254 		/*
26255 		 * If the IPsec packet was processed asynchronously,
26256 		 * drop it now.
26257 		 */
26258 		if (q == NULL) {
26259 			freemsg(ipsec_mp);
26260 			goto done;
26261 		}
26262 
26263 		/*
26264 		 * Since we're going through ip_newroute() again, we
26265 		 * need to make sure we don't:
26266 		 *
26267 		 *	1.) Trigger the ASSERT() with the ipha_ident
26268 		 *	    overloading.
26269 		 *	2.) Redo transport-layer checksumming, since we've
26270 		 *	    already done all that to get this far.
26271 		 *
26272 		 * The easiest way not do either of the above is to set
26273 		 * the ipha_ident field to IP_HDR_INCLUDED.
26274 		 */
26275 		ipha->ipha_ident = IP_HDR_INCLUDED;
26276 		ip_newroute(q, ipsec_mp, dst, NULL,
26277 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26278 	}
26279 	goto done;
26280 send:
26281 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26282 	    udp_compute_checksum(ipst->ips_netstack)) {
26283 		/*
26284 		 * ESP NAT-Traversal packet.
26285 		 *
26286 		 * Just do software checksum for now.
26287 		 */
26288 
26289 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26290 		IP_STAT(ipst, ip_out_sw_cksum);
26291 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26292 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26293 #define	iphs	((uint16_t *)ipha)
26294 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26295 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26296 		    IP_SIMPLE_HDR_LENGTH);
26297 #undef iphs
26298 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
26299 			cksum = 0xFFFF;
26300 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26301 			if (mp1->b_wptr - mp1->b_rptr >=
26302 			    offset + sizeof (uint16_t)) {
26303 				up = (uint16_t *)(mp1->b_rptr + offset);
26304 				*up = cksum;
26305 				break;	/* out of for loop */
26306 			} else {
26307 				offset -= (mp->b_wptr - mp->b_rptr);
26308 			}
26309 	} /* Otherwise, just keep the all-zero checksum. */
26310 
26311 	if (ire->ire_stq == NULL) {
26312 		ill_t	*out_ill;
26313 		/*
26314 		 * Loopbacks go through ip_wput_local except for one case.
26315 		 * We come here if we generate a icmp_frag_needed message
26316 		 * after IPSEC processing is over. When this function calls
26317 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26318 		 * icmp_frag_needed. The message generated comes back here
26319 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26320 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26321 		 * source address as it is usually set in ip_wput_ire. As
26322 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26323 		 * and we end up here. We can't enter ip_wput_ire once the
26324 		 * IPSEC processing is over and hence we need to do it here.
26325 		 */
26326 		ASSERT(q != NULL);
26327 		UPDATE_OB_PKT_COUNT(ire);
26328 		ire->ire_last_used_time = lbolt;
26329 		if (ipha->ipha_src == 0)
26330 			ipha->ipha_src = ire->ire_src_addr;
26331 
26332 		/* PFHooks: LOOPBACK_OUT */
26333 		out_ill = ire->ire_ipif->ipif_ill;
26334 
26335 		DTRACE_PROBE4(ip4__loopback__out__start,
26336 		    ill_t *, NULL, ill_t *, out_ill,
26337 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26338 
26339 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26340 		    ipst->ips_ipv4firewall_loopback_out,
26341 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26342 
26343 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26344 
26345 		if (ipsec_mp != NULL)
26346 			ip_wput_local(RD(q), out_ill,
26347 			    ipha, ipsec_mp, ire, 0, zoneid);
26348 		if (ire_need_rele)
26349 			ire_refrele(ire);
26350 		goto done;
26351 	}
26352 
26353 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26354 		/*
26355 		 * We are through with IPSEC processing.
26356 		 * Fragment this and send it on the wire.
26357 		 */
26358 		if (io->ipsec_out_accelerated) {
26359 			/*
26360 			 * The packet has been accelerated but must
26361 			 * be fragmented. This should not happen
26362 			 * since AH and ESP must not accelerate
26363 			 * packets that need fragmentation, however
26364 			 * the configuration could have changed
26365 			 * since the AH or ESP processing.
26366 			 * Drop packet.
26367 			 * IPsec KSTATS: bump bean counter here.
26368 			 */
26369 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26370 			    "fragmented accelerated packet!\n"));
26371 			freemsg(ipsec_mp);
26372 		} else {
26373 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26374 		}
26375 		if (ire_need_rele)
26376 			ire_refrele(ire);
26377 		goto done;
26378 	}
26379 
26380 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26381 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26382 	    (void *)ire->ire_ipif, (void *)ipif));
26383 
26384 	/*
26385 	 * Multiroute the secured packet, unless IPsec really
26386 	 * requires the packet to go out only through a particular
26387 	 * interface.
26388 	 */
26389 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26390 		ire_t *first_ire;
26391 		irb = ire->ire_bucket;
26392 		ASSERT(irb != NULL);
26393 		/*
26394 		 * This ire has been looked up as the one that
26395 		 * goes through the given ipif;
26396 		 * make sure we do not omit any other multiroute ire
26397 		 * that may be present in the bucket before this one.
26398 		 */
26399 		IRB_REFHOLD(irb);
26400 		for (first_ire = irb->irb_ire;
26401 		    first_ire != NULL;
26402 		    first_ire = first_ire->ire_next) {
26403 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26404 			    (first_ire->ire_addr == ire->ire_addr) &&
26405 			    !(first_ire->ire_marks &
26406 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
26407 				break;
26408 		}
26409 
26410 		if ((first_ire != NULL) && (first_ire != ire)) {
26411 			/*
26412 			 * Don't change the ire if the packet must
26413 			 * be fragmented if sent via this new one.
26414 			 */
26415 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26416 				IRE_REFHOLD(first_ire);
26417 				if (ire_need_rele)
26418 					ire_refrele(ire);
26419 				else
26420 					ire_need_rele = B_TRUE;
26421 				ire = first_ire;
26422 			}
26423 		}
26424 		IRB_REFRELE(irb);
26425 
26426 		multirt_send = B_TRUE;
26427 		max_frag = ire->ire_max_frag;
26428 	} else {
26429 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26430 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26431 			    "flag, attach_if %d\n", attach_if));
26432 		}
26433 	}
26434 
26435 	/*
26436 	 * In most cases, the emission loop below is entered only once.
26437 	 * Only in the case where the ire holds the RTF_MULTIRT
26438 	 * flag, we loop to process all RTF_MULTIRT ires in the
26439 	 * bucket, and send the packet through all crossed
26440 	 * RTF_MULTIRT routes.
26441 	 */
26442 	do {
26443 		if (multirt_send) {
26444 			/*
26445 			 * ire1 holds here the next ire to process in the
26446 			 * bucket. If multirouting is expected,
26447 			 * any non-RTF_MULTIRT ire that has the
26448 			 * right destination address is ignored.
26449 			 */
26450 			ASSERT(irb != NULL);
26451 			IRB_REFHOLD(irb);
26452 			for (ire1 = ire->ire_next;
26453 			    ire1 != NULL;
26454 			    ire1 = ire1->ire_next) {
26455 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26456 					continue;
26457 				if (ire1->ire_addr != ire->ire_addr)
26458 					continue;
26459 				if (ire1->ire_marks &
26460 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26461 					continue;
26462 				/* No loopback here */
26463 				if (ire1->ire_stq == NULL)
26464 					continue;
26465 				/*
26466 				 * Ensure we do not exceed the MTU
26467 				 * of the next route.
26468 				 */
26469 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26470 					ip_multirt_bad_mtu(ire1, max_frag);
26471 					continue;
26472 				}
26473 
26474 				IRE_REFHOLD(ire1);
26475 				break;
26476 			}
26477 			IRB_REFRELE(irb);
26478 			if (ire1 != NULL) {
26479 				/*
26480 				 * We are in a multiple send case, need to
26481 				 * make a copy of the packet.
26482 				 */
26483 				next_mp = copymsg(ipsec_mp);
26484 				if (next_mp == NULL) {
26485 					ire_refrele(ire1);
26486 					ire1 = NULL;
26487 				}
26488 			}
26489 		}
26490 		/*
26491 		 * Everything is done. Send it out on the wire
26492 		 *
26493 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26494 		 * either send it on the wire or, in the case of
26495 		 * HW acceleration, call ipsec_hw_putnext.
26496 		 */
26497 		if (ire->ire_nce &&
26498 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26499 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26500 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26501 			/*
26502 			 * If ire's link-layer is unresolved (this
26503 			 * would only happen if the incomplete ire
26504 			 * was added to cachetable via forwarding path)
26505 			 * don't bother going to ip_xmit_v4. Just drop the
26506 			 * packet.
26507 			 * There is a slight risk here, in that, if we
26508 			 * have the forwarding path create an incomplete
26509 			 * IRE, then until the IRE is completed, any
26510 			 * transmitted IPSEC packets will be dropped
26511 			 * instead of being queued waiting for resolution.
26512 			 *
26513 			 * But the likelihood of a forwarding packet and a wput
26514 			 * packet sending to the same dst at the same time
26515 			 * and there not yet be an ARP entry for it is small.
26516 			 * Furthermore, if this actually happens, it might
26517 			 * be likely that wput would generate multiple
26518 			 * packets (and forwarding would also have a train
26519 			 * of packets) for that destination. If this is
26520 			 * the case, some of them would have been dropped
26521 			 * anyway, since ARP only queues a few packets while
26522 			 * waiting for resolution
26523 			 *
26524 			 * NOTE: We should really call ip_xmit_v4,
26525 			 * and let it queue the packet and send the
26526 			 * ARP query and have ARP come back thus:
26527 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26528 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26529 			 * hw accel work. But it's too complex to get
26530 			 * the IPsec hw  acceleration approach to fit
26531 			 * well with ip_xmit_v4 doing ARP without
26532 			 * doing IPSEC simplification. For now, we just
26533 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26534 			 * that we can continue with the send on the next
26535 			 * attempt.
26536 			 *
26537 			 * XXX THis should be revisited, when
26538 			 * the IPsec/IP interaction is cleaned up
26539 			 */
26540 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26541 			    " - dropping packet\n"));
26542 			freemsg(ipsec_mp);
26543 			/*
26544 			 * Call ip_xmit_v4() to trigger ARP query
26545 			 * in case the nce_state is ND_INITIAL
26546 			 */
26547 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26548 			goto drop_pkt;
26549 		}
26550 
26551 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26552 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26553 		    mblk_t *, mp);
26554 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26555 		    ipst->ips_ipv4firewall_physical_out,
26556 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp, ipst);
26557 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
26558 		if (mp == NULL)
26559 			goto drop_pkt;
26560 
26561 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26562 		pktxmit_state = ip_xmit_v4(mp, ire,
26563 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26564 
26565 		if ((pktxmit_state ==  SEND_FAILED) ||
26566 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26567 
26568 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26569 drop_pkt:
26570 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26571 			    ipIfStatsOutDiscards);
26572 			if (ire_need_rele)
26573 				ire_refrele(ire);
26574 			if (ire1 != NULL) {
26575 				ire_refrele(ire1);
26576 				freemsg(next_mp);
26577 			}
26578 			goto done;
26579 		}
26580 
26581 		freeb(ipsec_mp);
26582 		if (ire_need_rele)
26583 			ire_refrele(ire);
26584 
26585 		if (ire1 != NULL) {
26586 			ire = ire1;
26587 			ire_need_rele = B_TRUE;
26588 			ASSERT(next_mp);
26589 			ipsec_mp = next_mp;
26590 			mp = ipsec_mp->b_cont;
26591 			ire1 = NULL;
26592 			next_mp = NULL;
26593 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26594 		} else {
26595 			multirt_send = B_FALSE;
26596 		}
26597 	} while (multirt_send);
26598 done:
26599 	if (ill != NULL && ill_need_rele)
26600 		ill_refrele(ill);
26601 	if (ipif != NULL)
26602 		ipif_refrele(ipif);
26603 }
26604 
26605 /*
26606  * Get the ill corresponding to the specified ire, and compare its
26607  * capabilities with the protocol and algorithms specified by the
26608  * the SA obtained from ipsec_out. If they match, annotate the
26609  * ipsec_out structure to indicate that the packet needs acceleration.
26610  *
26611  *
26612  * A packet is eligible for outbound hardware acceleration if the
26613  * following conditions are satisfied:
26614  *
26615  * 1. the packet will not be fragmented
26616  * 2. the provider supports the algorithm
26617  * 3. there is no pending control message being exchanged
26618  * 4. snoop is not attached
26619  * 5. the destination address is not a broadcast or multicast address.
26620  *
26621  * Rationale:
26622  *	- Hardware drivers do not support fragmentation with
26623  *	  the current interface.
26624  *	- snoop, multicast, and broadcast may result in exposure of
26625  *	  a cleartext datagram.
26626  * We check all five of these conditions here.
26627  *
26628  * XXX would like to nuke "ire_t *" parameter here; problem is that
26629  * IRE is only way to figure out if a v4 address is a broadcast and
26630  * thus ineligible for acceleration...
26631  */
26632 static void
26633 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26634 {
26635 	ipsec_out_t *io;
26636 	mblk_t *data_mp;
26637 	uint_t plen, overhead;
26638 	ip_stack_t	*ipst;
26639 
26640 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26641 		return;
26642 
26643 	if (ill == NULL)
26644 		return;
26645 	ipst = ill->ill_ipst;
26646 	/*
26647 	 * Destination address is a broadcast or multicast.  Punt.
26648 	 */
26649 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26650 	    IRE_LOCAL)))
26651 		return;
26652 
26653 	data_mp = ipsec_mp->b_cont;
26654 
26655 	if (ill->ill_isv6) {
26656 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26657 
26658 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26659 			return;
26660 
26661 		plen = ip6h->ip6_plen;
26662 	} else {
26663 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26664 
26665 		if (CLASSD(ipha->ipha_dst))
26666 			return;
26667 
26668 		plen = ipha->ipha_length;
26669 	}
26670 	/*
26671 	 * Is there a pending DLPI control message being exchanged
26672 	 * between IP/IPsec and the DLS Provider? If there is, it
26673 	 * could be a SADB update, and the state of the DLS Provider
26674 	 * SADB might not be in sync with the SADB maintained by
26675 	 * IPsec. To avoid dropping packets or using the wrong keying
26676 	 * material, we do not accelerate this packet.
26677 	 */
26678 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26679 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26680 		    "ill_dlpi_pending! don't accelerate packet\n"));
26681 		return;
26682 	}
26683 
26684 	/*
26685 	 * Is the Provider in promiscous mode? If it does, we don't
26686 	 * accelerate the packet since it will bounce back up to the
26687 	 * listeners in the clear.
26688 	 */
26689 	if (ill->ill_promisc_on_phys) {
26690 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26691 		    "ill in promiscous mode, don't accelerate packet\n"));
26692 		return;
26693 	}
26694 
26695 	/*
26696 	 * Will the packet require fragmentation?
26697 	 */
26698 
26699 	/*
26700 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26701 	 * as is used elsewhere.
26702 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26703 	 *	+ 2-byte trailer
26704 	 */
26705 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26706 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26707 
26708 	if ((plen + overhead) > ill->ill_max_mtu)
26709 		return;
26710 
26711 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26712 
26713 	/*
26714 	 * Can the ill accelerate this IPsec protocol and algorithm
26715 	 * specified by the SA?
26716 	 */
26717 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26718 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26719 		return;
26720 	}
26721 
26722 	/*
26723 	 * Tell AH or ESP that the outbound ill is capable of
26724 	 * accelerating this packet.
26725 	 */
26726 	io->ipsec_out_is_capab_ill = B_TRUE;
26727 }
26728 
26729 /*
26730  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26731  *
26732  * If this function returns B_TRUE, the requested SA's have been filled
26733  * into the ipsec_out_*_sa pointers.
26734  *
26735  * If the function returns B_FALSE, the packet has been "consumed", most
26736  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26737  *
26738  * The SA references created by the protocol-specific "select"
26739  * function will be released when the ipsec_mp is freed, thanks to the
26740  * ipsec_out_free destructor -- see spd.c.
26741  */
26742 static boolean_t
26743 ipsec_out_select_sa(mblk_t *ipsec_mp)
26744 {
26745 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26746 	ipsec_out_t *io;
26747 	ipsec_policy_t *pp;
26748 	ipsec_action_t *ap;
26749 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26750 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26751 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26752 
26753 	if (!io->ipsec_out_secure) {
26754 		/*
26755 		 * We came here by mistake.
26756 		 * Don't bother with ipsec processing
26757 		 * We should "discourage" this path in the future.
26758 		 */
26759 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26760 		return (B_FALSE);
26761 	}
26762 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26763 	ASSERT((io->ipsec_out_policy != NULL) ||
26764 	    (io->ipsec_out_act != NULL));
26765 
26766 	ASSERT(io->ipsec_out_failed == B_FALSE);
26767 
26768 	/*
26769 	 * IPSEC processing has started.
26770 	 */
26771 	io->ipsec_out_proc_begin = B_TRUE;
26772 	ap = io->ipsec_out_act;
26773 	if (ap == NULL) {
26774 		pp = io->ipsec_out_policy;
26775 		ASSERT(pp != NULL);
26776 		ap = pp->ipsp_act;
26777 		ASSERT(ap != NULL);
26778 	}
26779 
26780 	/*
26781 	 * We have an action.  now, let's select SA's.
26782 	 * (In the future, we can cache this in the conn_t..)
26783 	 */
26784 	if (ap->ipa_want_esp) {
26785 		if (io->ipsec_out_esp_sa == NULL) {
26786 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26787 			    IPPROTO_ESP);
26788 		}
26789 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26790 	}
26791 
26792 	if (ap->ipa_want_ah) {
26793 		if (io->ipsec_out_ah_sa == NULL) {
26794 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26795 			    IPPROTO_AH);
26796 		}
26797 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26798 		/*
26799 		 * The ESP and AH processing order needs to be preserved
26800 		 * when both protocols are required (ESP should be applied
26801 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26802 		 * when both ESP and AH are required, and an AH ACQUIRE
26803 		 * is needed.
26804 		 */
26805 		if (ap->ipa_want_esp && need_ah_acquire)
26806 			need_esp_acquire = B_TRUE;
26807 	}
26808 
26809 	/*
26810 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26811 	 * Release SAs that got referenced, but will not be used until we
26812 	 * acquire _all_ of the SAs we need.
26813 	 */
26814 	if (need_ah_acquire || need_esp_acquire) {
26815 		if (io->ipsec_out_ah_sa != NULL) {
26816 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26817 			io->ipsec_out_ah_sa = NULL;
26818 		}
26819 		if (io->ipsec_out_esp_sa != NULL) {
26820 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26821 			io->ipsec_out_esp_sa = NULL;
26822 		}
26823 
26824 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26825 		return (B_FALSE);
26826 	}
26827 
26828 	return (B_TRUE);
26829 }
26830 
26831 /*
26832  * Process an IPSEC_OUT message and see what you can
26833  * do with it.
26834  * IPQoS Notes:
26835  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26836  * IPSec.
26837  * XXX would like to nuke ire_t.
26838  * XXX ill_index better be "real"
26839  */
26840 void
26841 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26842 {
26843 	ipsec_out_t *io;
26844 	ipsec_policy_t *pp;
26845 	ipsec_action_t *ap;
26846 	ipha_t *ipha;
26847 	ip6_t *ip6h;
26848 	mblk_t *mp;
26849 	ill_t *ill;
26850 	zoneid_t zoneid;
26851 	ipsec_status_t ipsec_rc;
26852 	boolean_t ill_need_rele = B_FALSE;
26853 	ip_stack_t	*ipst;
26854 	ipsec_stack_t	*ipss;
26855 
26856 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26857 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26858 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26859 	ipst = io->ipsec_out_ns->netstack_ip;
26860 	mp = ipsec_mp->b_cont;
26861 
26862 	/*
26863 	 * Initiate IPPF processing. We do it here to account for packets
26864 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26865 	 * We can check for ipsec_out_proc_begin even for such packets, as
26866 	 * they will always be false (asserted below).
26867 	 */
26868 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26869 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26870 		    io->ipsec_out_ill_index : ill_index);
26871 		if (mp == NULL) {
26872 			ip2dbg(("ipsec_out_process: packet dropped "\
26873 			    "during IPPF processing\n"));
26874 			freeb(ipsec_mp);
26875 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26876 			return;
26877 		}
26878 	}
26879 
26880 	if (!io->ipsec_out_secure) {
26881 		/*
26882 		 * We came here by mistake.
26883 		 * Don't bother with ipsec processing
26884 		 * Should "discourage" this path in the future.
26885 		 */
26886 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26887 		goto done;
26888 	}
26889 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26890 	ASSERT((io->ipsec_out_policy != NULL) ||
26891 	    (io->ipsec_out_act != NULL));
26892 	ASSERT(io->ipsec_out_failed == B_FALSE);
26893 
26894 	ipss = ipst->ips_netstack->netstack_ipsec;
26895 	if (!ipsec_loaded(ipss)) {
26896 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26897 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26898 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26899 		} else {
26900 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26901 		}
26902 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26903 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26904 		    &ipss->ipsec_dropper);
26905 		return;
26906 	}
26907 
26908 	/*
26909 	 * IPSEC processing has started.
26910 	 */
26911 	io->ipsec_out_proc_begin = B_TRUE;
26912 	ap = io->ipsec_out_act;
26913 	if (ap == NULL) {
26914 		pp = io->ipsec_out_policy;
26915 		ASSERT(pp != NULL);
26916 		ap = pp->ipsp_act;
26917 		ASSERT(ap != NULL);
26918 	}
26919 
26920 	/*
26921 	 * Save the outbound ill index. When the packet comes back
26922 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26923 	 * before sending it the accelerated packet.
26924 	 */
26925 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26926 		int ifindex;
26927 		ill = ire_to_ill(ire);
26928 		ifindex = ill->ill_phyint->phyint_ifindex;
26929 		io->ipsec_out_capab_ill_index = ifindex;
26930 	}
26931 
26932 	/*
26933 	 * The order of processing is first insert a IP header if needed.
26934 	 * Then insert the ESP header and then the AH header.
26935 	 */
26936 	if ((io->ipsec_out_se_done == B_FALSE) &&
26937 	    (ap->ipa_want_se)) {
26938 		/*
26939 		 * First get the outer IP header before sending
26940 		 * it to ESP.
26941 		 */
26942 		ipha_t *oipha, *iipha;
26943 		mblk_t *outer_mp, *inner_mp;
26944 
26945 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26946 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26947 			    "ipsec_out_process: "
26948 			    "Self-Encapsulation failed: Out of memory\n");
26949 			freemsg(ipsec_mp);
26950 			if (ill != NULL) {
26951 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26952 			} else {
26953 				BUMP_MIB(&ipst->ips_ip_mib,
26954 				    ipIfStatsOutDiscards);
26955 			}
26956 			return;
26957 		}
26958 		inner_mp = ipsec_mp->b_cont;
26959 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26960 		oipha = (ipha_t *)outer_mp->b_rptr;
26961 		iipha = (ipha_t *)inner_mp->b_rptr;
26962 		*oipha = *iipha;
26963 		outer_mp->b_wptr += sizeof (ipha_t);
26964 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26965 		    sizeof (ipha_t));
26966 		oipha->ipha_protocol = IPPROTO_ENCAP;
26967 		oipha->ipha_version_and_hdr_length =
26968 		    IP_SIMPLE_HDR_VERSION;
26969 		oipha->ipha_hdr_checksum = 0;
26970 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26971 		outer_mp->b_cont = inner_mp;
26972 		ipsec_mp->b_cont = outer_mp;
26973 
26974 		io->ipsec_out_se_done = B_TRUE;
26975 		io->ipsec_out_tunnel = B_TRUE;
26976 	}
26977 
26978 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26979 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26980 	    !ipsec_out_select_sa(ipsec_mp))
26981 		return;
26982 
26983 	/*
26984 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26985 	 * to do the heavy lifting.
26986 	 */
26987 	zoneid = io->ipsec_out_zoneid;
26988 	ASSERT(zoneid != ALL_ZONES);
26989 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26990 		ASSERT(io->ipsec_out_esp_sa != NULL);
26991 		io->ipsec_out_esp_done = B_TRUE;
26992 		/*
26993 		 * Note that since hw accel can only apply one transform,
26994 		 * not two, we skip hw accel for ESP if we also have AH
26995 		 * This is an design limitation of the interface
26996 		 * which should be revisited.
26997 		 */
26998 		ASSERT(ire != NULL);
26999 		if (io->ipsec_out_ah_sa == NULL) {
27000 			ill = (ill_t *)ire->ire_stq->q_ptr;
27001 			ipsec_out_is_accelerated(ipsec_mp,
27002 			    io->ipsec_out_esp_sa, ill, ire);
27003 		}
27004 
27005 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
27006 		switch (ipsec_rc) {
27007 		case IPSEC_STATUS_SUCCESS:
27008 			break;
27009 		case IPSEC_STATUS_FAILED:
27010 			if (ill != NULL) {
27011 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27012 			} else {
27013 				BUMP_MIB(&ipst->ips_ip_mib,
27014 				    ipIfStatsOutDiscards);
27015 			}
27016 			/* FALLTHRU */
27017 		case IPSEC_STATUS_PENDING:
27018 			return;
27019 		}
27020 	}
27021 
27022 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27023 		ASSERT(io->ipsec_out_ah_sa != NULL);
27024 		io->ipsec_out_ah_done = B_TRUE;
27025 		if (ire == NULL) {
27026 			int idx = io->ipsec_out_capab_ill_index;
27027 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27028 			    NULL, NULL, NULL, NULL, ipst);
27029 			ill_need_rele = B_TRUE;
27030 		} else {
27031 			ill = (ill_t *)ire->ire_stq->q_ptr;
27032 		}
27033 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27034 		    ire);
27035 
27036 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27037 		switch (ipsec_rc) {
27038 		case IPSEC_STATUS_SUCCESS:
27039 			break;
27040 		case IPSEC_STATUS_FAILED:
27041 			if (ill != NULL) {
27042 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27043 			} else {
27044 				BUMP_MIB(&ipst->ips_ip_mib,
27045 				    ipIfStatsOutDiscards);
27046 			}
27047 			/* FALLTHRU */
27048 		case IPSEC_STATUS_PENDING:
27049 			if (ill != NULL && ill_need_rele)
27050 				ill_refrele(ill);
27051 			return;
27052 		}
27053 	}
27054 	/*
27055 	 * We are done with IPSEC processing. Send it over
27056 	 * the wire.
27057 	 */
27058 done:
27059 	mp = ipsec_mp->b_cont;
27060 	ipha = (ipha_t *)mp->b_rptr;
27061 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27062 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27063 	} else {
27064 		ip6h = (ip6_t *)ipha;
27065 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27066 	}
27067 	if (ill != NULL && ill_need_rele)
27068 		ill_refrele(ill);
27069 }
27070 
27071 /* ARGSUSED */
27072 void
27073 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27074 {
27075 	opt_restart_t	*or;
27076 	int	err;
27077 	conn_t	*connp;
27078 
27079 	ASSERT(CONN_Q(q));
27080 	connp = Q_TO_CONN(q);
27081 
27082 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27083 	or = (opt_restart_t *)first_mp->b_rptr;
27084 	/*
27085 	 * We don't need to pass any credentials here since this is just
27086 	 * a restart. The credentials are passed in when svr4_optcom_req
27087 	 * is called the first time (from ip_wput_nondata).
27088 	 */
27089 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27090 		err = svr4_optcom_req(q, first_mp, NULL,
27091 		    &ip_opt_obj);
27092 	} else {
27093 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27094 		err = tpi_optcom_req(q, first_mp, NULL,
27095 		    &ip_opt_obj);
27096 	}
27097 	if (err != EINPROGRESS) {
27098 		/* operation is done */
27099 		CONN_OPER_PENDING_DONE(connp);
27100 	}
27101 }
27102 
27103 /*
27104  * ioctls that go through a down/up sequence may need to wait for the down
27105  * to complete. This involves waiting for the ire and ipif refcnts to go down
27106  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27107  */
27108 /* ARGSUSED */
27109 void
27110 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27111 {
27112 	struct iocblk *iocp;
27113 	mblk_t *mp1;
27114 	ip_ioctl_cmd_t *ipip;
27115 	int err;
27116 	sin_t	*sin;
27117 	struct lifreq *lifr;
27118 	struct ifreq *ifr;
27119 
27120 	iocp = (struct iocblk *)mp->b_rptr;
27121 	ASSERT(ipsq != NULL);
27122 	/* Existence of mp1 verified in ip_wput_nondata */
27123 	mp1 = mp->b_cont->b_cont;
27124 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27125 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27126 		/*
27127 		 * Special case where ipsq_current_ipif is not set:
27128 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27129 		 * ill could also have become part of a ipmp group in the
27130 		 * process, we are here as were not able to complete the
27131 		 * operation in ipif_set_values because we could not become
27132 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27133 		 * will not be set so we need to set it.
27134 		 */
27135 		ill_t *ill = q->q_ptr;
27136 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27137 	}
27138 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27139 
27140 	if (ipip->ipi_cmd_type == IF_CMD) {
27141 		/* This a old style SIOC[GS]IF* command */
27142 		ifr = (struct ifreq *)mp1->b_rptr;
27143 		sin = (sin_t *)&ifr->ifr_addr;
27144 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27145 		/* This a new style SIOC[GS]LIF* command */
27146 		lifr = (struct lifreq *)mp1->b_rptr;
27147 		sin = (sin_t *)&lifr->lifr_addr;
27148 	} else {
27149 		sin = NULL;
27150 	}
27151 
27152 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27153 	    ipip, mp1->b_rptr);
27154 
27155 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27156 }
27157 
27158 /*
27159  * ioctl processing
27160  *
27161  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27162  * the ioctl command in the ioctl tables and determines the copyin data size
27163  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27164  * size.
27165  *
27166  * ioctl processing then continues when the M_IOCDATA makes its way down.
27167  * Now the ioctl is looked up again in the ioctl table, and its properties are
27168  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27169  * and the general ioctl processing function ip_process_ioctl is called.
27170  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27171  * so goes thru the serialization primitive ipsq_try_enter. Then the
27172  * appropriate function to handle the ioctl is called based on the entry in
27173  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27174  * which also refreleases the 'conn' that was refheld at the start of the
27175  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27176  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27177  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27178  *
27179  * Many exclusive ioctls go thru an internal down up sequence as part of
27180  * the operation. For example an attempt to change the IP address of an
27181  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27182  * does all the cleanup such as deleting all ires that use this address.
27183  * Then we need to wait till all references to the interface go away.
27184  */
27185 void
27186 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27187 {
27188 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27189 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27190 	cmd_info_t ci;
27191 	int err;
27192 	boolean_t entered_ipsq = B_FALSE;
27193 
27194 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27195 
27196 	if (ipip == NULL)
27197 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27198 
27199 	/*
27200 	 * SIOCLIFADDIF needs to go thru a special path since the
27201 	 * ill may not exist yet. This happens in the case of lo0
27202 	 * which is created using this ioctl.
27203 	 */
27204 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27205 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27206 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27207 		return;
27208 	}
27209 
27210 	ci.ci_ipif = NULL;
27211 	switch (ipip->ipi_cmd_type) {
27212 	case IF_CMD:
27213 	case LIF_CMD:
27214 		/*
27215 		 * ioctls that pass in a [l]ifreq appear here.
27216 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27217 		 * ci.ci_ipif
27218 		 */
27219 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27220 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27221 		if (err != 0) {
27222 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27223 			return;
27224 		}
27225 		ASSERT(ci.ci_ipif != NULL);
27226 		break;
27227 
27228 	case TUN_CMD:
27229 		/*
27230 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27231 		 * a refheld ipif in ci.ci_ipif
27232 		 */
27233 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27234 		if (err != 0) {
27235 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27236 			return;
27237 		}
27238 		ASSERT(ci.ci_ipif != NULL);
27239 		break;
27240 
27241 	case MISC_CMD:
27242 		/*
27243 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27244 		 * For eg. SIOCGLIFCONF will appear here.
27245 		 */
27246 		switch (ipip->ipi_cmd) {
27247 		case IF_UNITSEL:
27248 			/* ioctl comes down the ill */
27249 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27250 			ipif_refhold(ci.ci_ipif);
27251 			break;
27252 		case SIOCGMSFILTER:
27253 		case SIOCSMSFILTER:
27254 		case SIOCGIPMSFILTER:
27255 		case SIOCSIPMSFILTER:
27256 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27257 			    ip_process_ioctl);
27258 			if (err != 0) {
27259 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27260 				    NULL);
27261 			}
27262 			break;
27263 		}
27264 		err = 0;
27265 		ci.ci_sin = NULL;
27266 		ci.ci_sin6 = NULL;
27267 		ci.ci_lifr = NULL;
27268 		break;
27269 	}
27270 
27271 	/*
27272 	 * If ipsq is non-null, we are already being called exclusively
27273 	 */
27274 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27275 	if (!(ipip->ipi_flags & IPI_WR)) {
27276 		/*
27277 		 * A return value of EINPROGRESS means the ioctl is
27278 		 * either queued and waiting for some reason or has
27279 		 * already completed.
27280 		 */
27281 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27282 		    ci.ci_lifr);
27283 		if (ci.ci_ipif != NULL)
27284 			ipif_refrele(ci.ci_ipif);
27285 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27286 		return;
27287 	}
27288 
27289 	ASSERT(ci.ci_ipif != NULL);
27290 
27291 	if (ipsq == NULL) {
27292 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27293 		    ip_process_ioctl, NEW_OP, B_TRUE);
27294 		entered_ipsq = B_TRUE;
27295 	}
27296 	/*
27297 	 * Release the ipif so that ipif_down and friends that wait for
27298 	 * references to go away are not misled about the current ipif_refcnt
27299 	 * values. We are writer so we can access the ipif even after releasing
27300 	 * the ipif.
27301 	 */
27302 	ipif_refrele(ci.ci_ipif);
27303 	if (ipsq == NULL)
27304 		return;
27305 
27306 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27307 
27308 	/*
27309 	 * For most set ioctls that come here, this serves as a single point
27310 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27311 	 * be any new references to the ipif. This helps functions that go
27312 	 * through this path and end up trying to wait for the refcnts
27313 	 * associated with the ipif to go down to zero. Some exceptions are
27314 	 * Failover, Failback, and Groupname commands that operate on more than
27315 	 * just the ci.ci_ipif. These commands internally determine the
27316 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27317 	 * flags on that set. Another exception is the Removeif command that
27318 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27319 	 * ipif to operate on.
27320 	 */
27321 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27322 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27323 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27324 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27325 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27326 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27327 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27328 
27329 	/*
27330 	 * A return value of EINPROGRESS means the ioctl is
27331 	 * either queued and waiting for some reason or has
27332 	 * already completed.
27333 	 */
27334 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27335 
27336 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27337 
27338 	if (entered_ipsq)
27339 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27340 }
27341 
27342 /*
27343  * Complete the ioctl. Typically ioctls use the mi package and need to
27344  * do mi_copyout/mi_copy_done.
27345  */
27346 void
27347 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27348 {
27349 	conn_t	*connp = NULL;
27350 
27351 	if (err == EINPROGRESS)
27352 		return;
27353 
27354 	if (CONN_Q(q)) {
27355 		connp = Q_TO_CONN(q);
27356 		ASSERT(connp->conn_ref >= 2);
27357 	}
27358 
27359 	switch (mode) {
27360 	case COPYOUT:
27361 		if (err == 0)
27362 			mi_copyout(q, mp);
27363 		else
27364 			mi_copy_done(q, mp, err);
27365 		break;
27366 
27367 	case NO_COPYOUT:
27368 		mi_copy_done(q, mp, err);
27369 		break;
27370 
27371 	default:
27372 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27373 		break;
27374 	}
27375 
27376 	/*
27377 	 * The refhold placed at the start of the ioctl is released here.
27378 	 */
27379 	if (connp != NULL)
27380 		CONN_OPER_PENDING_DONE(connp);
27381 
27382 	if (ipsq != NULL)
27383 		ipsq_current_finish(ipsq);
27384 }
27385 
27386 /*
27387  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27388  */
27389 /* ARGSUSED */
27390 void
27391 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27392 {
27393 	conn_t *connp = arg;
27394 	tcp_t	*tcp;
27395 
27396 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27397 	tcp = connp->conn_tcp;
27398 
27399 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27400 		freemsg(mp);
27401 	else
27402 		tcp_rput_other(tcp, mp);
27403 	CONN_OPER_PENDING_DONE(connp);
27404 }
27405 
27406 /* Called from ip_wput for all non data messages */
27407 /* ARGSUSED */
27408 void
27409 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27410 {
27411 	mblk_t		*mp1;
27412 	ire_t		*ire, *fake_ire;
27413 	ill_t		*ill;
27414 	struct iocblk	*iocp;
27415 	ip_ioctl_cmd_t	*ipip;
27416 	cred_t		*cr;
27417 	conn_t		*connp;
27418 	int		cmd, err;
27419 	nce_t		*nce;
27420 	ipif_t		*ipif;
27421 	ip_stack_t	*ipst;
27422 	char		*proto_str;
27423 
27424 	if (CONN_Q(q)) {
27425 		connp = Q_TO_CONN(q);
27426 		ipst = connp->conn_netstack->netstack_ip;
27427 	} else {
27428 		connp = NULL;
27429 		ipst = ILLQ_TO_IPST(q);
27430 	}
27431 
27432 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27433 
27434 	/* Check if it is a queue to /dev/sctp. */
27435 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27436 	    connp->conn_rq == NULL) {
27437 		sctp_wput(q, mp);
27438 		return;
27439 	}
27440 
27441 	switch (DB_TYPE(mp)) {
27442 	case M_IOCTL:
27443 		/*
27444 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27445 		 * will arrange to copy in associated control structures.
27446 		 */
27447 		ip_sioctl_copyin_setup(q, mp);
27448 		return;
27449 	case M_IOCDATA:
27450 		/*
27451 		 * Ensure that this is associated with one of our trans-
27452 		 * parent ioctls.  If it's not ours, discard it if we're
27453 		 * running as a driver, or pass it on if we're a module.
27454 		 */
27455 		iocp = (struct iocblk *)mp->b_rptr;
27456 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27457 		if (ipip == NULL) {
27458 			if (q->q_next == NULL) {
27459 				goto nak;
27460 			} else {
27461 				putnext(q, mp);
27462 			}
27463 			return;
27464 		} else if ((q->q_next != NULL) &&
27465 		    !(ipip->ipi_flags & IPI_MODOK)) {
27466 			/*
27467 			 * the ioctl is one we recognise, but is not
27468 			 * consumed by IP as a module, pass M_IOCDATA
27469 			 * for processing downstream, but only for
27470 			 * common Streams ioctls.
27471 			 */
27472 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27473 				putnext(q, mp);
27474 				return;
27475 			} else {
27476 				goto nak;
27477 			}
27478 		}
27479 
27480 		/* IOCTL continuation following copyin or copyout. */
27481 		if (mi_copy_state(q, mp, NULL) == -1) {
27482 			/*
27483 			 * The copy operation failed.  mi_copy_state already
27484 			 * cleaned up, so we're out of here.
27485 			 */
27486 			return;
27487 		}
27488 		/*
27489 		 * If we just completed a copy in, we become writer and
27490 		 * continue processing in ip_sioctl_copyin_done.  If it
27491 		 * was a copy out, we call mi_copyout again.  If there is
27492 		 * nothing more to copy out, it will complete the IOCTL.
27493 		 */
27494 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27495 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27496 				mi_copy_done(q, mp, EPROTO);
27497 				return;
27498 			}
27499 			/*
27500 			 * Check for cases that need more copying.  A return
27501 			 * value of 0 means a second copyin has been started,
27502 			 * so we return; a return value of 1 means no more
27503 			 * copying is needed, so we continue.
27504 			 */
27505 			cmd = iocp->ioc_cmd;
27506 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27507 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27508 			    MI_COPY_COUNT(mp) == 1) {
27509 				if (ip_copyin_msfilter(q, mp) == 0)
27510 					return;
27511 			}
27512 			/*
27513 			 * Refhold the conn, till the ioctl completes. This is
27514 			 * needed in case the ioctl ends up in the pending mp
27515 			 * list. Every mp in the ill_pending_mp list and
27516 			 * the ipsq_pending_mp must have a refhold on the conn
27517 			 * to resume processing. The refhold is released when
27518 			 * the ioctl completes. (normally or abnormally)
27519 			 * In all cases ip_ioctl_finish is called to finish
27520 			 * the ioctl.
27521 			 */
27522 			if (connp != NULL) {
27523 				/* This is not a reentry */
27524 				ASSERT(ipsq == NULL);
27525 				CONN_INC_REF(connp);
27526 			} else {
27527 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27528 					mi_copy_done(q, mp, EINVAL);
27529 					return;
27530 				}
27531 			}
27532 
27533 			ip_process_ioctl(ipsq, q, mp, ipip);
27534 
27535 		} else {
27536 			mi_copyout(q, mp);
27537 		}
27538 		return;
27539 nak:
27540 		iocp->ioc_error = EINVAL;
27541 		mp->b_datap->db_type = M_IOCNAK;
27542 		iocp->ioc_count = 0;
27543 		qreply(q, mp);
27544 		return;
27545 
27546 	case M_IOCNAK:
27547 		/*
27548 		 * The only way we could get here is if a resolver didn't like
27549 		 * an IOCTL we sent it.	 This shouldn't happen.
27550 		 */
27551 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27552 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27553 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27554 		freemsg(mp);
27555 		return;
27556 	case M_IOCACK:
27557 		/* /dev/ip shouldn't see this */
27558 		if (CONN_Q(q))
27559 			goto nak;
27560 
27561 		/* Finish socket ioctls passed through to ARP. */
27562 		ip_sioctl_iocack(q, mp);
27563 		return;
27564 	case M_FLUSH:
27565 		if (*mp->b_rptr & FLUSHW)
27566 			flushq(q, FLUSHALL);
27567 		if (q->q_next) {
27568 			/*
27569 			 * M_FLUSH is sent up to IP by some drivers during
27570 			 * unbind. ip_rput has already replied to it. We are
27571 			 * here for the M_FLUSH that we originated in IP
27572 			 * before sending the unbind request to the driver.
27573 			 * Just free it as we don't queue packets in IP
27574 			 * on the write side of the device instance.
27575 			 */
27576 			freemsg(mp);
27577 			return;
27578 		}
27579 		if (*mp->b_rptr & FLUSHR) {
27580 			*mp->b_rptr &= ~FLUSHW;
27581 			qreply(q, mp);
27582 			return;
27583 		}
27584 		freemsg(mp);
27585 		return;
27586 	case IRE_DB_REQ_TYPE:
27587 		if (connp == NULL) {
27588 			proto_str = "IRE_DB_REQ_TYPE";
27589 			goto protonak;
27590 		}
27591 		/* An Upper Level Protocol wants a copy of an IRE. */
27592 		ip_ire_req(q, mp);
27593 		return;
27594 	case M_CTL:
27595 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27596 			break;
27597 
27598 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27599 		    TUN_HELLO) {
27600 			ASSERT(connp != NULL);
27601 			connp->conn_flags |= IPCL_IPTUN;
27602 			freeb(mp);
27603 			return;
27604 		}
27605 
27606 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27607 		    IP_ULP_OUT_LABELED) {
27608 			out_labeled_t *olp;
27609 
27610 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27611 				break;
27612 			olp = (out_labeled_t *)mp->b_rptr;
27613 			connp->conn_ulp_labeled = olp->out_qnext == q;
27614 			freemsg(mp);
27615 			return;
27616 		}
27617 
27618 		/* M_CTL messages are used by ARP to tell us things. */
27619 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27620 			break;
27621 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27622 		case AR_ENTRY_SQUERY:
27623 			ip_wput_ctl(q, mp);
27624 			return;
27625 		case AR_CLIENT_NOTIFY:
27626 			ip_arp_news(q, mp);
27627 			return;
27628 		case AR_DLPIOP_DONE:
27629 			ASSERT(q->q_next != NULL);
27630 			ill = (ill_t *)q->q_ptr;
27631 			/* qwriter_ip releases the refhold */
27632 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27633 			ill_refhold(ill);
27634 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
27635 			    CUR_OP, B_FALSE);
27636 			return;
27637 		case AR_ARP_CLOSING:
27638 			/*
27639 			 * ARP (above us) is closing. If no ARP bringup is
27640 			 * currently pending, ack the message so that ARP
27641 			 * can complete its close. Also mark ill_arp_closing
27642 			 * so that new ARP bringups will fail. If any
27643 			 * ARP bringup is currently in progress, we will
27644 			 * ack this when the current ARP bringup completes.
27645 			 */
27646 			ASSERT(q->q_next != NULL);
27647 			ill = (ill_t *)q->q_ptr;
27648 			mutex_enter(&ill->ill_lock);
27649 			ill->ill_arp_closing = 1;
27650 			if (!ill->ill_arp_bringup_pending) {
27651 				mutex_exit(&ill->ill_lock);
27652 				qreply(q, mp);
27653 			} else {
27654 				mutex_exit(&ill->ill_lock);
27655 				freemsg(mp);
27656 			}
27657 			return;
27658 		case AR_ARP_EXTEND:
27659 			/*
27660 			 * The ARP module above us is capable of duplicate
27661 			 * address detection.  Old ATM drivers will not send
27662 			 * this message.
27663 			 */
27664 			ASSERT(q->q_next != NULL);
27665 			ill = (ill_t *)q->q_ptr;
27666 			ill->ill_arp_extend = B_TRUE;
27667 			freemsg(mp);
27668 			return;
27669 		default:
27670 			break;
27671 		}
27672 		break;
27673 	case M_PROTO:
27674 	case M_PCPROTO:
27675 		/*
27676 		 * The only PROTO messages we expect are ULP binds and
27677 		 * copies of option negotiation acknowledgements.
27678 		 */
27679 		switch (((union T_primitives *)mp->b_rptr)->type) {
27680 		case O_T_BIND_REQ:
27681 		case T_BIND_REQ: {
27682 			/* Request can get queued in bind */
27683 			if (connp == NULL) {
27684 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27685 				goto protonak;
27686 			}
27687 			/*
27688 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27689 			 * instead of going through this path.  We only get
27690 			 * here in the following cases:
27691 			 *
27692 			 * a. Bind retries, where ipsq is non-NULL.
27693 			 * b. T_BIND_REQ is issued from non TCP/UDP
27694 			 *    transport, e.g. icmp for raw socket,
27695 			 *    in which case ipsq will be NULL.
27696 			 */
27697 			ASSERT(ipsq != NULL ||
27698 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27699 
27700 			/* Don't increment refcnt if this is a re-entry */
27701 			if (ipsq == NULL)
27702 				CONN_INC_REF(connp);
27703 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27704 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27705 			if (mp == NULL)
27706 				return;
27707 			if (IPCL_IS_TCP(connp)) {
27708 				/*
27709 				 * In the case of TCP endpoint we
27710 				 * come here only for bind retries
27711 				 */
27712 				ASSERT(ipsq != NULL);
27713 				CONN_INC_REF(connp);
27714 				squeue_fill(connp->conn_sqp, mp,
27715 				    ip_resume_tcp_bind, connp,
27716 				    SQTAG_BIND_RETRY);
27717 				return;
27718 			} else if (IPCL_IS_UDP(connp)) {
27719 				/*
27720 				 * In the case of UDP endpoint we
27721 				 * come here only for bind retries
27722 				 */
27723 				ASSERT(ipsq != NULL);
27724 				udp_resume_bind(connp, mp);
27725 				return;
27726 			}
27727 			qreply(q, mp);
27728 			CONN_OPER_PENDING_DONE(connp);
27729 			return;
27730 		}
27731 		case T_SVR4_OPTMGMT_REQ:
27732 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27733 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27734 
27735 			if (connp == NULL) {
27736 				proto_str = "T_SVR4_OPTMGMT_REQ";
27737 				goto protonak;
27738 			}
27739 
27740 			if (!snmpcom_req(q, mp, ip_snmp_set,
27741 			    ip_snmp_get, cr)) {
27742 				/*
27743 				 * Call svr4_optcom_req so that it can
27744 				 * generate the ack. We don't come here
27745 				 * if this operation is being restarted.
27746 				 * ip_restart_optmgmt will drop the conn ref.
27747 				 * In the case of ipsec option after the ipsec
27748 				 * load is complete conn_restart_ipsec_waiter
27749 				 * drops the conn ref.
27750 				 */
27751 				ASSERT(ipsq == NULL);
27752 				CONN_INC_REF(connp);
27753 				if (ip_check_for_ipsec_opt(q, mp))
27754 					return;
27755 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27756 				if (err != EINPROGRESS) {
27757 					/* Operation is done */
27758 					CONN_OPER_PENDING_DONE(connp);
27759 				}
27760 			}
27761 			return;
27762 		case T_OPTMGMT_REQ:
27763 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27764 			/*
27765 			 * Note: No snmpcom_req support through new
27766 			 * T_OPTMGMT_REQ.
27767 			 * Call tpi_optcom_req so that it can
27768 			 * generate the ack.
27769 			 */
27770 			if (connp == NULL) {
27771 				proto_str = "T_OPTMGMT_REQ";
27772 				goto protonak;
27773 			}
27774 
27775 			ASSERT(ipsq == NULL);
27776 			/*
27777 			 * We don't come here for restart. ip_restart_optmgmt
27778 			 * will drop the conn ref. In the case of ipsec option
27779 			 * after the ipsec load is complete
27780 			 * conn_restart_ipsec_waiter drops the conn ref.
27781 			 */
27782 			CONN_INC_REF(connp);
27783 			if (ip_check_for_ipsec_opt(q, mp))
27784 				return;
27785 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27786 			if (err != EINPROGRESS) {
27787 				/* Operation is done */
27788 				CONN_OPER_PENDING_DONE(connp);
27789 			}
27790 			return;
27791 		case T_UNBIND_REQ:
27792 			if (connp == NULL) {
27793 				proto_str = "T_UNBIND_REQ";
27794 				goto protonak;
27795 			}
27796 			mp = ip_unbind(q, mp);
27797 			qreply(q, mp);
27798 			return;
27799 		default:
27800 			/*
27801 			 * Have to drop any DLPI messages coming down from
27802 			 * arp (such as an info_req which would cause ip
27803 			 * to receive an extra info_ack if it was passed
27804 			 * through.
27805 			 */
27806 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27807 			    (int)*(uint_t *)mp->b_rptr));
27808 			freemsg(mp);
27809 			return;
27810 		}
27811 		/* NOTREACHED */
27812 	case IRE_DB_TYPE: {
27813 		nce_t		*nce;
27814 		ill_t		*ill;
27815 		in6_addr_t	gw_addr_v6;
27816 
27817 
27818 		/*
27819 		 * This is a response back from a resolver.  It
27820 		 * consists of a message chain containing:
27821 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27822 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27823 		 * The LL_HDR_MBLK is the DLPI header to use to get
27824 		 * the attached packet, and subsequent ones for the
27825 		 * same destination, transmitted.
27826 		 */
27827 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27828 			break;
27829 		/*
27830 		 * First, check to make sure the resolution succeeded.
27831 		 * If it failed, the second mblk will be empty.
27832 		 * If it is, free the chain, dropping the packet.
27833 		 * (We must ire_delete the ire; that frees the ire mblk)
27834 		 * We're doing this now to support PVCs for ATM; it's
27835 		 * a partial xresolv implementation. When we fully implement
27836 		 * xresolv interfaces, instead of freeing everything here
27837 		 * we'll initiate neighbor discovery.
27838 		 *
27839 		 * For v4 (ARP and other external resolvers) the resolver
27840 		 * frees the message, so no check is needed. This check
27841 		 * is required, though, for a full xresolve implementation.
27842 		 * Including this code here now both shows how external
27843 		 * resolvers can NACK a resolution request using an
27844 		 * existing design that has no specific provisions for NACKs,
27845 		 * and also takes into account that the current non-ARP
27846 		 * external resolver has been coded to use this method of
27847 		 * NACKing for all IPv6 (xresolv) cases,
27848 		 * whether our xresolv implementation is complete or not.
27849 		 *
27850 		 */
27851 		ire = (ire_t *)mp->b_rptr;
27852 		ill = ire_to_ill(ire);
27853 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27854 		if (mp1->b_rptr == mp1->b_wptr) {
27855 			if (ire->ire_ipversion == IPV6_VERSION) {
27856 				/*
27857 				 * XRESOLV interface.
27858 				 */
27859 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27860 				mutex_enter(&ire->ire_lock);
27861 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27862 				mutex_exit(&ire->ire_lock);
27863 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27864 					nce = ndp_lookup_v6(ill,
27865 					    &ire->ire_addr_v6, B_FALSE);
27866 				} else {
27867 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27868 					    B_FALSE);
27869 				}
27870 				if (nce != NULL) {
27871 					nce_resolv_failed(nce);
27872 					ndp_delete(nce);
27873 					NCE_REFRELE(nce);
27874 				}
27875 			}
27876 			mp->b_cont = NULL;
27877 			freemsg(mp1);		/* frees the pkt as well */
27878 			ASSERT(ire->ire_nce == NULL);
27879 			ire_delete((ire_t *)mp->b_rptr);
27880 			return;
27881 		}
27882 
27883 		/*
27884 		 * Split them into IRE_MBLK and pkt and feed it into
27885 		 * ire_add_then_send. Then in ire_add_then_send
27886 		 * the IRE will be added, and then the packet will be
27887 		 * run back through ip_wput. This time it will make
27888 		 * it to the wire.
27889 		 */
27890 		mp->b_cont = NULL;
27891 		mp = mp1->b_cont;		/* now, mp points to pkt */
27892 		mp1->b_cont = NULL;
27893 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27894 		if (ire->ire_ipversion == IPV6_VERSION) {
27895 			/*
27896 			 * XRESOLV interface. Find the nce and put a copy
27897 			 * of the dl_unitdata_req in nce_res_mp
27898 			 */
27899 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27900 			mutex_enter(&ire->ire_lock);
27901 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27902 			mutex_exit(&ire->ire_lock);
27903 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27904 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27905 				    B_FALSE);
27906 			} else {
27907 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27908 			}
27909 			if (nce != NULL) {
27910 				/*
27911 				 * We have to protect nce_res_mp here
27912 				 * from being accessed by other threads
27913 				 * while we change the mblk pointer.
27914 				 * Other functions will also lock the nce when
27915 				 * accessing nce_res_mp.
27916 				 *
27917 				 * The reason we change the mblk pointer
27918 				 * here rather than copying the resolved address
27919 				 * into the template is that, unlike with
27920 				 * ethernet, we have no guarantee that the
27921 				 * resolved address length will be
27922 				 * smaller than or equal to the lla length
27923 				 * with which the template was allocated,
27924 				 * (for ethernet, they're equal)
27925 				 * so we have to use the actual resolved
27926 				 * address mblk - which holds the real
27927 				 * dl_unitdata_req with the resolved address.
27928 				 *
27929 				 * Doing this is the same behavior as was
27930 				 * previously used in the v4 ARP case.
27931 				 */
27932 				mutex_enter(&nce->nce_lock);
27933 				if (nce->nce_res_mp != NULL)
27934 					freemsg(nce->nce_res_mp);
27935 				nce->nce_res_mp = mp1;
27936 				mutex_exit(&nce->nce_lock);
27937 				/*
27938 				 * We do a fastpath probe here because
27939 				 * we have resolved the address without
27940 				 * using Neighbor Discovery.
27941 				 * In the non-XRESOLV v6 case, the fastpath
27942 				 * probe is done right after neighbor
27943 				 * discovery completes.
27944 				 */
27945 				if (nce->nce_res_mp != NULL) {
27946 					int res;
27947 					nce_fastpath_list_add(nce);
27948 					res = ill_fastpath_probe(ill,
27949 					    nce->nce_res_mp);
27950 					if (res != 0 && res != EAGAIN)
27951 						nce_fastpath_list_delete(nce);
27952 				}
27953 
27954 				ire_add_then_send(q, ire, mp);
27955 				/*
27956 				 * Now we have to clean out any packets
27957 				 * that may have been queued on the nce
27958 				 * while it was waiting for address resolution
27959 				 * to complete.
27960 				 */
27961 				mutex_enter(&nce->nce_lock);
27962 				mp1 = nce->nce_qd_mp;
27963 				nce->nce_qd_mp = NULL;
27964 				mutex_exit(&nce->nce_lock);
27965 				while (mp1 != NULL) {
27966 					mblk_t *nxt_mp;
27967 					queue_t *fwdq = NULL;
27968 					ill_t   *inbound_ill;
27969 					uint_t ifindex;
27970 
27971 					nxt_mp = mp1->b_next;
27972 					mp1->b_next = NULL;
27973 					/*
27974 					 * Retrieve ifindex stored in
27975 					 * ip_rput_data_v6()
27976 					 */
27977 					ifindex =
27978 					    (uint_t)(uintptr_t)mp1->b_prev;
27979 					inbound_ill =
27980 						ill_lookup_on_ifindex(ifindex,
27981 						    B_TRUE, NULL, NULL, NULL,
27982 						    NULL, ipst);
27983 					mp1->b_prev = NULL;
27984 					if (inbound_ill != NULL)
27985 						fwdq = inbound_ill->ill_rq;
27986 
27987 					if (fwdq != NULL) {
27988 						put(fwdq, mp1);
27989 						ill_refrele(inbound_ill);
27990 					} else
27991 						put(WR(ill->ill_rq), mp1);
27992 					mp1 = nxt_mp;
27993 				}
27994 				NCE_REFRELE(nce);
27995 			} else {	/* nce is NULL; clean up */
27996 				ire_delete(ire);
27997 				freemsg(mp);
27998 				freemsg(mp1);
27999 				return;
28000 			}
28001 		} else {
28002 			nce_t *arpce;
28003 			/*
28004 			 * Link layer resolution succeeded. Recompute the
28005 			 * ire_nce.
28006 			 */
28007 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
28008 			if ((arpce = ndp_lookup_v4(ill,
28009 			    (ire->ire_gateway_addr != INADDR_ANY ?
28010 			    &ire->ire_gateway_addr : &ire->ire_addr),
28011 			    B_FALSE)) == NULL) {
28012 				freeb(ire->ire_mp);
28013 				freeb(mp1);
28014 				freemsg(mp);
28015 				return;
28016 			}
28017 			mutex_enter(&arpce->nce_lock);
28018 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
28019 			if (arpce->nce_state == ND_REACHABLE) {
28020 				/*
28021 				 * Someone resolved this before us;
28022 				 * cleanup the res_mp. Since ire has
28023 				 * not been added yet, the call to ire_add_v4
28024 				 * from ire_add_then_send (when a dup is
28025 				 * detected) will clean up the ire.
28026 				 */
28027 				freeb(mp1);
28028 			} else {
28029 				if (arpce->nce_res_mp != NULL)
28030 					freemsg(arpce->nce_res_mp);
28031 				arpce->nce_res_mp = mp1;
28032 				arpce->nce_state = ND_REACHABLE;
28033 			}
28034 			mutex_exit(&arpce->nce_lock);
28035 			if (ire->ire_marks & IRE_MARK_NOADD) {
28036 				/*
28037 				 * this ire will not be added to the ire
28038 				 * cache table, so we can set the ire_nce
28039 				 * here, as there are no atomicity constraints.
28040 				 */
28041 				ire->ire_nce = arpce;
28042 				/*
28043 				 * We are associating this nce with the ire
28044 				 * so change the nce ref taken in
28045 				 * ndp_lookup_v4() from
28046 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28047 				 */
28048 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28049 			} else {
28050 				NCE_REFRELE(arpce);
28051 			}
28052 			ire_add_then_send(q, ire, mp);
28053 		}
28054 		return;	/* All is well, the packet has been sent. */
28055 	}
28056 	case IRE_ARPRESOLVE_TYPE: {
28057 
28058 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28059 			break;
28060 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28061 		mp->b_cont = NULL;
28062 		/*
28063 		 * First, check to make sure the resolution succeeded.
28064 		 * If it failed, the second mblk will be empty.
28065 		 */
28066 		if (mp1->b_rptr == mp1->b_wptr) {
28067 			/* cleanup  the incomplete ire, free queued packets */
28068 			freemsg(mp); /* fake ire */
28069 			freeb(mp1);  /* dl_unitdata response */
28070 			return;
28071 		}
28072 
28073 		/*
28074 		 * update any incomplete nce_t found. we lookup the ctable
28075 		 * and find the nce from the ire->ire_nce because we need
28076 		 * to pass the ire to ip_xmit_v4 later, and can find both
28077 		 * ire and nce in one lookup from the ctable.
28078 		 */
28079 		fake_ire = (ire_t *)mp->b_rptr;
28080 		/*
28081 		 * By the time we come back here from ARP
28082 		 * the logical outgoing interface  of the incomplete ire
28083 		 * we added in ire_forward could have disappeared,
28084 		 * causing the incomplete ire to also have
28085 		 * dissapeared. So we need to retreive the
28086 		 * proper ipif for the ire  before looking
28087 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28088 		 */
28089 		ill = q->q_ptr;
28090 
28091 		/* Get the outgoing ipif */
28092 		mutex_enter(&ill->ill_lock);
28093 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28094 			mutex_exit(&ill->ill_lock);
28095 			freemsg(mp); /* fake ire */
28096 			freeb(mp1);  /* dl_unitdata response */
28097 			return;
28098 		}
28099 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28100 
28101 		if (ipif == NULL) {
28102 			mutex_exit(&ill->ill_lock);
28103 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28104 			freemsg(mp);
28105 			freeb(mp1);
28106 			return;
28107 		}
28108 		ipif_refhold_locked(ipif);
28109 		mutex_exit(&ill->ill_lock);
28110 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28111 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28112 		    ipif, fake_ire->ire_zoneid, NULL,
28113 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28114 		ipif_refrele(ipif);
28115 		if (ire == NULL) {
28116 			/*
28117 			 * no ire was found; check if there is an nce
28118 			 * for this lookup; if it has no ire's pointing at it
28119 			 * cleanup.
28120 			 */
28121 			if ((nce = ndp_lookup_v4(ill,
28122 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28123 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28124 			    B_FALSE)) != NULL) {
28125 				/*
28126 				 * cleanup: just reset nce.
28127 				 * We check for refcnt 2 (one for the nce
28128 				 * hash list + 1 for the ref taken by
28129 				 * ndp_lookup_v4) to ensure that there are
28130 				 * no ire's pointing at the nce.
28131 				 */
28132 				if (nce->nce_refcnt == 2) {
28133 					nce = nce_reinit(nce);
28134 				}
28135 				if (nce != NULL)
28136 					NCE_REFRELE(nce);
28137 			}
28138 			freeb(mp1);  /* dl_unitdata response */
28139 			freemsg(mp); /* fake ire */
28140 			return;
28141 		}
28142 		nce = ire->ire_nce;
28143 		DTRACE_PROBE2(ire__arpresolve__type,
28144 		    ire_t *, ire, nce_t *, nce);
28145 		ASSERT(nce->nce_state != ND_INITIAL);
28146 		mutex_enter(&nce->nce_lock);
28147 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28148 		if (nce->nce_state == ND_REACHABLE) {
28149 			/*
28150 			 * Someone resolved this before us;
28151 			 * our response is not needed any more.
28152 			 */
28153 			mutex_exit(&nce->nce_lock);
28154 			freeb(mp1);  /* dl_unitdata response */
28155 		} else {
28156 			if (nce->nce_res_mp != NULL) {
28157 				freemsg(nce->nce_res_mp);
28158 				/* existing dl_unitdata template */
28159 			}
28160 			nce->nce_res_mp = mp1;
28161 			nce->nce_state = ND_REACHABLE;
28162 			mutex_exit(&nce->nce_lock);
28163 			nce_fastpath(nce);
28164 		}
28165 		/*
28166 		 * The cached nce_t has been updated to be reachable;
28167 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
28168 		 */
28169 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28170 		freemsg(mp);
28171 		/*
28172 		 * send out queued packets.
28173 		 */
28174 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28175 
28176 		IRE_REFRELE(ire);
28177 		return;
28178 	}
28179 	default:
28180 		break;
28181 	}
28182 	if (q->q_next) {
28183 		putnext(q, mp);
28184 	} else
28185 		freemsg(mp);
28186 	return;
28187 
28188 protonak:
28189 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28190 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28191 		qreply(q, mp);
28192 }
28193 
28194 /*
28195  * Process IP options in an outbound packet.  Modify the destination if there
28196  * is a source route option.
28197  * Returns non-zero if something fails in which case an ICMP error has been
28198  * sent and mp freed.
28199  */
28200 static int
28201 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28202     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28203 {
28204 	ipoptp_t	opts;
28205 	uchar_t		*opt;
28206 	uint8_t		optval;
28207 	uint8_t		optlen;
28208 	ipaddr_t	dst;
28209 	intptr_t	code = 0;
28210 	mblk_t		*mp;
28211 	ire_t		*ire = NULL;
28212 
28213 	ip2dbg(("ip_wput_options\n"));
28214 	mp = ipsec_mp;
28215 	if (mctl_present) {
28216 		mp = ipsec_mp->b_cont;
28217 	}
28218 
28219 	dst = ipha->ipha_dst;
28220 	for (optval = ipoptp_first(&opts, ipha);
28221 	    optval != IPOPT_EOL;
28222 	    optval = ipoptp_next(&opts)) {
28223 		opt = opts.ipoptp_cur;
28224 		optlen = opts.ipoptp_len;
28225 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28226 		    optval, optlen));
28227 		switch (optval) {
28228 			uint32_t off;
28229 		case IPOPT_SSRR:
28230 		case IPOPT_LSRR:
28231 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28232 				ip1dbg((
28233 				    "ip_wput_options: bad option offset\n"));
28234 				code = (char *)&opt[IPOPT_OLEN] -
28235 				    (char *)ipha;
28236 				goto param_prob;
28237 			}
28238 			off = opt[IPOPT_OFFSET];
28239 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28240 			    ntohl(dst)));
28241 			/*
28242 			 * For strict: verify that dst is directly
28243 			 * reachable.
28244 			 */
28245 			if (optval == IPOPT_SSRR) {
28246 				ire = ire_ftable_lookup(dst, 0, 0,
28247 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28248 				    MBLK_GETLABEL(mp),
28249 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28250 				if (ire == NULL) {
28251 					ip1dbg(("ip_wput_options: SSRR not"
28252 					    " directly reachable: 0x%x\n",
28253 					    ntohl(dst)));
28254 					goto bad_src_route;
28255 				}
28256 				ire_refrele(ire);
28257 			}
28258 			break;
28259 		case IPOPT_RR:
28260 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28261 				ip1dbg((
28262 				    "ip_wput_options: bad option offset\n"));
28263 				code = (char *)&opt[IPOPT_OLEN] -
28264 				    (char *)ipha;
28265 				goto param_prob;
28266 			}
28267 			break;
28268 		case IPOPT_TS:
28269 			/*
28270 			 * Verify that length >=5 and that there is either
28271 			 * room for another timestamp or that the overflow
28272 			 * counter is not maxed out.
28273 			 */
28274 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28275 			if (optlen < IPOPT_MINLEN_IT) {
28276 				goto param_prob;
28277 			}
28278 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28279 				ip1dbg((
28280 				    "ip_wput_options: bad option offset\n"));
28281 				code = (char *)&opt[IPOPT_OFFSET] -
28282 				    (char *)ipha;
28283 				goto param_prob;
28284 			}
28285 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28286 			case IPOPT_TS_TSONLY:
28287 				off = IPOPT_TS_TIMELEN;
28288 				break;
28289 			case IPOPT_TS_TSANDADDR:
28290 			case IPOPT_TS_PRESPEC:
28291 			case IPOPT_TS_PRESPEC_RFC791:
28292 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28293 				break;
28294 			default:
28295 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28296 				    (char *)ipha;
28297 				goto param_prob;
28298 			}
28299 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28300 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28301 				/*
28302 				 * No room and the overflow counter is 15
28303 				 * already.
28304 				 */
28305 				goto param_prob;
28306 			}
28307 			break;
28308 		}
28309 	}
28310 
28311 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28312 		return (0);
28313 
28314 	ip1dbg(("ip_wput_options: error processing IP options."));
28315 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28316 
28317 param_prob:
28318 	/*
28319 	 * Since ip_wput() isn't close to finished, we fill
28320 	 * in enough of the header for credible error reporting.
28321 	 */
28322 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28323 		/* Failed */
28324 		freemsg(ipsec_mp);
28325 		return (-1);
28326 	}
28327 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28328 	return (-1);
28329 
28330 bad_src_route:
28331 	/*
28332 	 * Since ip_wput() isn't close to finished, we fill
28333 	 * in enough of the header for credible error reporting.
28334 	 */
28335 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28336 		/* Failed */
28337 		freemsg(ipsec_mp);
28338 		return (-1);
28339 	}
28340 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28341 	return (-1);
28342 }
28343 
28344 /*
28345  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28346  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28347  * thru /etc/system.
28348  */
28349 #define	CONN_MAXDRAINCNT	64
28350 
28351 static void
28352 conn_drain_init(ip_stack_t *ipst)
28353 {
28354 	int i;
28355 
28356 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28357 
28358 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28359 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28360 		/*
28361 		 * Default value of the number of drainers is the
28362 		 * number of cpus, subject to maximum of 8 drainers.
28363 		 */
28364 		if (boot_max_ncpus != -1)
28365 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28366 		else
28367 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28368 	}
28369 
28370 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28371 	    sizeof (idl_t), KM_SLEEP);
28372 
28373 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28374 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28375 		    MUTEX_DEFAULT, NULL);
28376 	}
28377 }
28378 
28379 static void
28380 conn_drain_fini(ip_stack_t *ipst)
28381 {
28382 	int i;
28383 
28384 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28385 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28386 	kmem_free(ipst->ips_conn_drain_list,
28387 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28388 	ipst->ips_conn_drain_list = NULL;
28389 }
28390 
28391 /*
28392  * Note: For an overview of how flowcontrol is handled in IP please see the
28393  * IP Flowcontrol notes at the top of this file.
28394  *
28395  * Flow control has blocked us from proceeding. Insert the given conn in one
28396  * of the conn drain lists. These conn wq's will be qenabled later on when
28397  * STREAMS flow control does a backenable. conn_walk_drain will enable
28398  * the first conn in each of these drain lists. Each of these qenabled conns
28399  * in turn enables the next in the list, after it runs, or when it closes,
28400  * thus sustaining the drain process.
28401  *
28402  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28403  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28404  * running at any time, on a given conn, since there can be only 1 service proc
28405  * running on a queue at any time.
28406  */
28407 void
28408 conn_drain_insert(conn_t *connp)
28409 {
28410 	idl_t	*idl;
28411 	uint_t	index;
28412 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28413 
28414 	mutex_enter(&connp->conn_lock);
28415 	if (connp->conn_state_flags & CONN_CLOSING) {
28416 		/*
28417 		 * The conn is closing as a result of which CONN_CLOSING
28418 		 * is set. Return.
28419 		 */
28420 		mutex_exit(&connp->conn_lock);
28421 		return;
28422 	} else if (connp->conn_idl == NULL) {
28423 		/*
28424 		 * Assign the next drain list round robin. We dont' use
28425 		 * a lock, and thus it may not be strictly round robin.
28426 		 * Atomicity of load/stores is enough to make sure that
28427 		 * conn_drain_list_index is always within bounds.
28428 		 */
28429 		index = ipst->ips_conn_drain_list_index;
28430 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28431 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28432 		index++;
28433 		if (index == ipst->ips_conn_drain_list_cnt)
28434 			index = 0;
28435 		ipst->ips_conn_drain_list_index = index;
28436 	}
28437 	mutex_exit(&connp->conn_lock);
28438 
28439 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28440 	if ((connp->conn_drain_prev != NULL) ||
28441 	    (connp->conn_state_flags & CONN_CLOSING)) {
28442 		/*
28443 		 * The conn is already in the drain list, OR
28444 		 * the conn is closing. We need to check again for
28445 		 * the closing case again since close can happen
28446 		 * after we drop the conn_lock, and before we
28447 		 * acquire the CONN_DRAIN_LIST_LOCK.
28448 		 */
28449 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28450 		return;
28451 	} else {
28452 		idl = connp->conn_idl;
28453 	}
28454 
28455 	/*
28456 	 * The conn is not in the drain list. Insert it at the
28457 	 * tail of the drain list. The drain list is circular
28458 	 * and doubly linked. idl_conn points to the 1st element
28459 	 * in the list.
28460 	 */
28461 	if (idl->idl_conn == NULL) {
28462 		idl->idl_conn = connp;
28463 		connp->conn_drain_next = connp;
28464 		connp->conn_drain_prev = connp;
28465 	} else {
28466 		conn_t *head = idl->idl_conn;
28467 
28468 		connp->conn_drain_next = head;
28469 		connp->conn_drain_prev = head->conn_drain_prev;
28470 		head->conn_drain_prev->conn_drain_next = connp;
28471 		head->conn_drain_prev = connp;
28472 	}
28473 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28474 }
28475 
28476 /*
28477  * This conn is closing, and we are called from ip_close. OR
28478  * This conn has been serviced by ip_wsrv, and we need to do the tail
28479  * processing.
28480  * If this conn is part of the drain list, we may need to sustain the drain
28481  * process by qenabling the next conn in the drain list. We may also need to
28482  * remove this conn from the list, if it is done.
28483  */
28484 static void
28485 conn_drain_tail(conn_t *connp, boolean_t closing)
28486 {
28487 	idl_t *idl;
28488 
28489 	/*
28490 	 * connp->conn_idl is stable at this point, and no lock is needed
28491 	 * to check it. If we are called from ip_close, close has already
28492 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28493 	 * called us only because conn_idl is non-null. If we are called thru
28494 	 * service, conn_idl could be null, but it cannot change because
28495 	 * service is single-threaded per queue, and there cannot be another
28496 	 * instance of service trying to call conn_drain_insert on this conn
28497 	 * now.
28498 	 */
28499 	ASSERT(!closing || (connp->conn_idl != NULL));
28500 
28501 	/*
28502 	 * If connp->conn_idl is null, the conn has not been inserted into any
28503 	 * drain list even once since creation of the conn. Just return.
28504 	 */
28505 	if (connp->conn_idl == NULL)
28506 		return;
28507 
28508 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28509 
28510 	if (connp->conn_drain_prev == NULL) {
28511 		/* This conn is currently not in the drain list.  */
28512 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28513 		return;
28514 	}
28515 	idl = connp->conn_idl;
28516 	if (idl->idl_conn_draining == connp) {
28517 		/*
28518 		 * This conn is the current drainer. If this is the last conn
28519 		 * in the drain list, we need to do more checks, in the 'if'
28520 		 * below. Otherwwise we need to just qenable the next conn,
28521 		 * to sustain the draining, and is handled in the 'else'
28522 		 * below.
28523 		 */
28524 		if (connp->conn_drain_next == idl->idl_conn) {
28525 			/*
28526 			 * This conn is the last in this list. This round
28527 			 * of draining is complete. If idl_repeat is set,
28528 			 * it means another flow enabling has happened from
28529 			 * the driver/streams and we need to another round
28530 			 * of draining.
28531 			 * If there are more than 2 conns in the drain list,
28532 			 * do a left rotate by 1, so that all conns except the
28533 			 * conn at the head move towards the head by 1, and the
28534 			 * the conn at the head goes to the tail. This attempts
28535 			 * a more even share for all queues that are being
28536 			 * drained.
28537 			 */
28538 			if ((connp->conn_drain_next != connp) &&
28539 			    (idl->idl_conn->conn_drain_next != connp)) {
28540 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28541 			}
28542 			if (idl->idl_repeat) {
28543 				qenable(idl->idl_conn->conn_wq);
28544 				idl->idl_conn_draining = idl->idl_conn;
28545 				idl->idl_repeat = 0;
28546 			} else {
28547 				idl->idl_conn_draining = NULL;
28548 			}
28549 		} else {
28550 			/*
28551 			 * If the next queue that we are now qenable'ing,
28552 			 * is closing, it will remove itself from this list
28553 			 * and qenable the subsequent queue in ip_close().
28554 			 * Serialization is acheived thru idl_lock.
28555 			 */
28556 			qenable(connp->conn_drain_next->conn_wq);
28557 			idl->idl_conn_draining = connp->conn_drain_next;
28558 		}
28559 	}
28560 	if (!connp->conn_did_putbq || closing) {
28561 		/*
28562 		 * Remove ourself from the drain list, if we did not do
28563 		 * a putbq, or if the conn is closing.
28564 		 * Note: It is possible that q->q_first is non-null. It means
28565 		 * that these messages landed after we did a enableok() in
28566 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28567 		 * service them.
28568 		 */
28569 		if (connp->conn_drain_next == connp) {
28570 			/* Singleton in the list */
28571 			ASSERT(connp->conn_drain_prev == connp);
28572 			idl->idl_conn = NULL;
28573 			idl->idl_conn_draining = NULL;
28574 		} else {
28575 			connp->conn_drain_prev->conn_drain_next =
28576 			    connp->conn_drain_next;
28577 			connp->conn_drain_next->conn_drain_prev =
28578 			    connp->conn_drain_prev;
28579 			if (idl->idl_conn == connp)
28580 				idl->idl_conn = connp->conn_drain_next;
28581 			ASSERT(idl->idl_conn_draining != connp);
28582 
28583 		}
28584 		connp->conn_drain_next = NULL;
28585 		connp->conn_drain_prev = NULL;
28586 	}
28587 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28588 }
28589 
28590 /*
28591  * Write service routine. Shared perimeter entry point.
28592  * ip_wsrv can be called in any of the following ways.
28593  * 1. The device queue's messages has fallen below the low water mark
28594  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28595  *    the drain lists and backenable the first conn in each list.
28596  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28597  *    qenabled non-tcp upper layers. We start dequeing messages and call
28598  *    ip_wput for each message.
28599  */
28600 
28601 void
28602 ip_wsrv(queue_t *q)
28603 {
28604 	conn_t	*connp;
28605 	ill_t	*ill;
28606 	mblk_t	*mp;
28607 
28608 	if (q->q_next) {
28609 		ill = (ill_t *)q->q_ptr;
28610 		if (ill->ill_state_flags == 0) {
28611 			/*
28612 			 * The device flow control has opened up.
28613 			 * Walk through conn drain lists and qenable the
28614 			 * first conn in each list. This makes sense only
28615 			 * if the stream is fully plumbed and setup.
28616 			 * Hence the if check above.
28617 			 */
28618 			ip1dbg(("ip_wsrv: walking\n"));
28619 			conn_walk_drain(ill->ill_ipst);
28620 		}
28621 		return;
28622 	}
28623 
28624 	connp = Q_TO_CONN(q);
28625 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28626 
28627 	/*
28628 	 * 1. Set conn_draining flag to signal that service is active.
28629 	 *
28630 	 * 2. ip_output determines whether it has been called from service,
28631 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28632 	 *    has been called from service.
28633 	 *
28634 	 * 3. Message ordering is preserved by the following logic.
28635 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28636 	 *    the message at the tail, if conn_draining is set (i.e. service
28637 	 *    is running) or if q->q_first is non-null.
28638 	 *
28639 	 *    ii. If ip_output is called from service, and if ip_output cannot
28640 	 *    putnext due to flow control, it does a putbq.
28641 	 *
28642 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28643 	 *    (causing an infinite loop).
28644 	 */
28645 	ASSERT(!connp->conn_did_putbq);
28646 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28647 		connp->conn_draining = 1;
28648 		noenable(q);
28649 		while ((mp = getq(q)) != NULL) {
28650 			ASSERT(CONN_Q(q));
28651 
28652 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28653 			if (connp->conn_did_putbq) {
28654 				/* ip_wput did a putbq */
28655 				break;
28656 			}
28657 		}
28658 		/*
28659 		 * At this point, a thread coming down from top, calling
28660 		 * ip_wput, may end up queueing the message. We have not yet
28661 		 * enabled the queue, so ip_wsrv won't be called again.
28662 		 * To avoid this race, check q->q_first again (in the loop)
28663 		 * If the other thread queued the message before we call
28664 		 * enableok(), we will catch it in the q->q_first check.
28665 		 * If the other thread queues the message after we call
28666 		 * enableok(), ip_wsrv will be called again by STREAMS.
28667 		 */
28668 		connp->conn_draining = 0;
28669 		enableok(q);
28670 	}
28671 
28672 	/* Enable the next conn for draining */
28673 	conn_drain_tail(connp, B_FALSE);
28674 
28675 	connp->conn_did_putbq = 0;
28676 }
28677 
28678 /*
28679  * Walk the list of all conn's calling the function provided with the
28680  * specified argument for each.	 Note that this only walks conn's that
28681  * have been bound.
28682  * Applies to both IPv4 and IPv6.
28683  */
28684 static void
28685 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28686 {
28687 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28688 	    ipst->ips_ipcl_udp_fanout_size,
28689 	    func, arg, zoneid);
28690 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28691 	    ipst->ips_ipcl_conn_fanout_size,
28692 	    func, arg, zoneid);
28693 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28694 	    ipst->ips_ipcl_bind_fanout_size,
28695 	    func, arg, zoneid);
28696 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28697 	    IPPROTO_MAX, func, arg, zoneid);
28698 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28699 	    IPPROTO_MAX, func, arg, zoneid);
28700 }
28701 
28702 /*
28703  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28704  * of conns that need to be drained, check if drain is already in progress.
28705  * If so set the idl_repeat bit, indicating that the last conn in the list
28706  * needs to reinitiate the drain once again, for the list. If drain is not
28707  * in progress for the list, initiate the draining, by qenabling the 1st
28708  * conn in the list. The drain is self-sustaining, each qenabled conn will
28709  * in turn qenable the next conn, when it is done/blocked/closing.
28710  */
28711 static void
28712 conn_walk_drain(ip_stack_t *ipst)
28713 {
28714 	int i;
28715 	idl_t *idl;
28716 
28717 	IP_STAT(ipst, ip_conn_walk_drain);
28718 
28719 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28720 		idl = &ipst->ips_conn_drain_list[i];
28721 		mutex_enter(&idl->idl_lock);
28722 		if (idl->idl_conn == NULL) {
28723 			mutex_exit(&idl->idl_lock);
28724 			continue;
28725 		}
28726 		/*
28727 		 * If this list is not being drained currently by
28728 		 * an ip_wsrv thread, start the process.
28729 		 */
28730 		if (idl->idl_conn_draining == NULL) {
28731 			ASSERT(idl->idl_repeat == 0);
28732 			qenable(idl->idl_conn->conn_wq);
28733 			idl->idl_conn_draining = idl->idl_conn;
28734 		} else {
28735 			idl->idl_repeat = 1;
28736 		}
28737 		mutex_exit(&idl->idl_lock);
28738 	}
28739 }
28740 
28741 /*
28742  * Walk an conn hash table of `count' buckets, calling func for each entry.
28743  */
28744 static void
28745 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28746     zoneid_t zoneid)
28747 {
28748 	conn_t	*connp;
28749 
28750 	while (count-- > 0) {
28751 		mutex_enter(&connfp->connf_lock);
28752 		for (connp = connfp->connf_head; connp != NULL;
28753 		    connp = connp->conn_next) {
28754 			if (zoneid == GLOBAL_ZONEID ||
28755 			    zoneid == connp->conn_zoneid) {
28756 				CONN_INC_REF(connp);
28757 				mutex_exit(&connfp->connf_lock);
28758 				(*func)(connp, arg);
28759 				mutex_enter(&connfp->connf_lock);
28760 				CONN_DEC_REF(connp);
28761 			}
28762 		}
28763 		mutex_exit(&connfp->connf_lock);
28764 		connfp++;
28765 	}
28766 }
28767 
28768 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28769 static void
28770 conn_report1(conn_t *connp, void *mp)
28771 {
28772 	char	buf1[INET6_ADDRSTRLEN];
28773 	char	buf2[INET6_ADDRSTRLEN];
28774 	uint_t	print_len, buf_len;
28775 
28776 	ASSERT(connp != NULL);
28777 
28778 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28779 	if (buf_len <= 0)
28780 		return;
28781 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
28782 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
28783 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28784 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28785 	    "%5d %s/%05d %s/%05d\n",
28786 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28787 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28788 	    buf1, connp->conn_lport,
28789 	    buf2, connp->conn_fport);
28790 	if (print_len < buf_len) {
28791 		((mblk_t *)mp)->b_wptr += print_len;
28792 	} else {
28793 		((mblk_t *)mp)->b_wptr += buf_len;
28794 	}
28795 }
28796 
28797 /*
28798  * Named Dispatch routine to produce a formatted report on all conns
28799  * that are listed in one of the fanout tables.
28800  * This report is accessed by using the ndd utility to "get" ND variable
28801  * "ip_conn_status".
28802  */
28803 /* ARGSUSED */
28804 static int
28805 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28806 {
28807 	conn_t *connp = Q_TO_CONN(q);
28808 
28809 	(void) mi_mpprintf(mp,
28810 	    "CONN      " MI_COL_HDRPAD_STR
28811 	    "rfq      " MI_COL_HDRPAD_STR
28812 	    "stq      " MI_COL_HDRPAD_STR
28813 	    " zone local                 remote");
28814 
28815 	/*
28816 	 * Because of the ndd constraint, at most we can have 64K buffer
28817 	 * to put in all conn info.  So to be more efficient, just
28818 	 * allocate a 64K buffer here, assuming we need that large buffer.
28819 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28820 	 */
28821 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28822 		/* The following may work even if we cannot get a large buf. */
28823 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28824 		return (0);
28825 	}
28826 
28827 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28828 	    connp->conn_netstack->netstack_ip);
28829 	return (0);
28830 }
28831 
28832 /*
28833  * Determine if the ill and multicast aspects of that packets
28834  * "matches" the conn.
28835  */
28836 boolean_t
28837 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28838     zoneid_t zoneid)
28839 {
28840 	ill_t *in_ill;
28841 	boolean_t found;
28842 	ipif_t *ipif;
28843 	ire_t *ire;
28844 	ipaddr_t dst, src;
28845 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28846 
28847 	dst = ipha->ipha_dst;
28848 	src = ipha->ipha_src;
28849 
28850 	/*
28851 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28852 	 * unicast, broadcast and multicast reception to
28853 	 * conn_incoming_ill. conn_wantpacket itself is called
28854 	 * only for BROADCAST and multicast.
28855 	 *
28856 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28857 	 *    is part of a group. Hence, we should be receiving
28858 	 *    just one copy of broadcast for the whole group.
28859 	 *    Thus, if it is part of the group the packet could
28860 	 *    come on any ill of the group and hence we need a
28861 	 *    match on the group. Otherwise, match on ill should
28862 	 *    be sufficient.
28863 	 *
28864 	 * 2) ip_rput does not suppress duplicate multicast packets.
28865 	 *    If there are two interfaces in a ill group and we have
28866 	 *    2 applications (conns) joined a multicast group G on
28867 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28868 	 *    will give us two packets because we join G on both the
28869 	 *    interfaces rather than nominating just one interface
28870 	 *    for receiving multicast like broadcast above. So,
28871 	 *    we have to call ilg_lookup_ill to filter out duplicate
28872 	 *    copies, if ill is part of a group.
28873 	 */
28874 	in_ill = connp->conn_incoming_ill;
28875 	if (in_ill != NULL) {
28876 		if (in_ill->ill_group == NULL) {
28877 			if (in_ill != ill)
28878 				return (B_FALSE);
28879 		} else if (in_ill->ill_group != ill->ill_group) {
28880 			return (B_FALSE);
28881 		}
28882 	}
28883 
28884 	if (!CLASSD(dst)) {
28885 		if (IPCL_ZONE_MATCH(connp, zoneid))
28886 			return (B_TRUE);
28887 		/*
28888 		 * The conn is in a different zone; we need to check that this
28889 		 * broadcast address is configured in the application's zone and
28890 		 * on one ill in the group.
28891 		 */
28892 		ipif = ipif_get_next_ipif(NULL, ill);
28893 		if (ipif == NULL)
28894 			return (B_FALSE);
28895 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28896 		    connp->conn_zoneid, NULL,
28897 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28898 		ipif_refrele(ipif);
28899 		if (ire != NULL) {
28900 			ire_refrele(ire);
28901 			return (B_TRUE);
28902 		} else {
28903 			return (B_FALSE);
28904 		}
28905 	}
28906 
28907 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28908 	    connp->conn_zoneid == zoneid) {
28909 		/*
28910 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28911 		 * disabled, therefore we don't dispatch the multicast packet to
28912 		 * the sending zone.
28913 		 */
28914 		return (B_FALSE);
28915 	}
28916 
28917 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
28918 	    connp->conn_zoneid != zoneid) {
28919 		/*
28920 		 * Multicast packet on the loopback interface: we only match
28921 		 * conns who joined the group in the specified zone.
28922 		 */
28923 		return (B_FALSE);
28924 	}
28925 
28926 	if (connp->conn_multi_router) {
28927 		/* multicast packet and multicast router socket: send up */
28928 		return (B_TRUE);
28929 	}
28930 
28931 	mutex_enter(&connp->conn_lock);
28932 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28933 	mutex_exit(&connp->conn_lock);
28934 	return (found);
28935 }
28936 
28937 /*
28938  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28939  */
28940 /* ARGSUSED */
28941 static void
28942 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28943 {
28944 	ill_t *ill = (ill_t *)q->q_ptr;
28945 	mblk_t	*mp1, *mp2;
28946 	ipif_t  *ipif;
28947 	int err = 0;
28948 	conn_t *connp = NULL;
28949 	ipsq_t	*ipsq;
28950 	arc_t	*arc;
28951 
28952 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28953 
28954 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28955 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28956 
28957 	ASSERT(IAM_WRITER_ILL(ill));
28958 	mp2 = mp->b_cont;
28959 	mp->b_cont = NULL;
28960 
28961 	/*
28962 	 * We have now received the arp bringup completion message
28963 	 * from ARP. Mark the arp bringup as done. Also if the arp
28964 	 * stream has already started closing, send up the AR_ARP_CLOSING
28965 	 * ack now since ARP is waiting in close for this ack.
28966 	 */
28967 	mutex_enter(&ill->ill_lock);
28968 	ill->ill_arp_bringup_pending = 0;
28969 	if (ill->ill_arp_closing) {
28970 		mutex_exit(&ill->ill_lock);
28971 		/* Let's reuse the mp for sending the ack */
28972 		arc = (arc_t *)mp->b_rptr;
28973 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28974 		arc->arc_cmd = AR_ARP_CLOSING;
28975 		qreply(q, mp);
28976 	} else {
28977 		mutex_exit(&ill->ill_lock);
28978 		freeb(mp);
28979 	}
28980 
28981 	ipsq = ill->ill_phyint->phyint_ipsq;
28982 	ipif = ipsq->ipsq_pending_ipif;
28983 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28984 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28985 	if (mp1 == NULL) {
28986 		/* bringup was aborted by the user */
28987 		freemsg(mp2);
28988 		return;
28989 	}
28990 
28991 	/*
28992 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28993 	 * must have an associated conn_t.  Otherwise, we're bringing this
28994 	 * interface back up as part of handling an asynchronous event (e.g.,
28995 	 * physical address change).
28996 	 */
28997 	if (ipsq->ipsq_current_ioctl != 0) {
28998 		ASSERT(connp != NULL);
28999 		q = CONNP_TO_WQ(connp);
29000 	} else {
29001 		ASSERT(connp == NULL);
29002 		q = ill->ill_rq;
29003 	}
29004 
29005 	/*
29006 	 * If the DL_BIND_REQ fails, it is noted
29007 	 * in arc_name_offset.
29008 	 */
29009 	err = *((int *)mp2->b_rptr);
29010 	if (err == 0) {
29011 		if (ipif->ipif_isv6) {
29012 			if ((err = ipif_up_done_v6(ipif)) != 0)
29013 				ip0dbg(("ip_arp_done: init failed\n"));
29014 		} else {
29015 			if ((err = ipif_up_done(ipif)) != 0)
29016 				ip0dbg(("ip_arp_done: init failed\n"));
29017 		}
29018 	} else {
29019 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
29020 	}
29021 
29022 	freemsg(mp2);
29023 
29024 	if ((err == 0) && (ill->ill_up_ipifs)) {
29025 		err = ill_up_ipifs(ill, q, mp1);
29026 		if (err == EINPROGRESS)
29027 			return;
29028 	}
29029 
29030 	if (ill->ill_up_ipifs)
29031 		ill_group_cleanup(ill);
29032 
29033 	/*
29034 	 * The operation must complete without EINPROGRESS since
29035 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29036 	 * Otherwise, the operation will be stuck forever in the ipsq.
29037 	 */
29038 	ASSERT(err != EINPROGRESS);
29039 	if (ipsq->ipsq_current_ioctl != 0)
29040 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29041 	else
29042 		ipsq_current_finish(ipsq);
29043 }
29044 
29045 /* Allocate the private structure */
29046 static int
29047 ip_priv_alloc(void **bufp)
29048 {
29049 	void	*buf;
29050 
29051 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29052 		return (ENOMEM);
29053 
29054 	*bufp = buf;
29055 	return (0);
29056 }
29057 
29058 /* Function to delete the private structure */
29059 void
29060 ip_priv_free(void *buf)
29061 {
29062 	ASSERT(buf != NULL);
29063 	kmem_free(buf, sizeof (ip_priv_t));
29064 }
29065 
29066 /*
29067  * The entry point for IPPF processing.
29068  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29069  * routine just returns.
29070  *
29071  * When called, ip_process generates an ipp_packet_t structure
29072  * which holds the state information for this packet and invokes the
29073  * the classifier (via ipp_packet_process). The classification, depending on
29074  * configured filters, results in a list of actions for this packet. Invoking
29075  * an action may cause the packet to be dropped, in which case the resulting
29076  * mblk (*mpp) is NULL. proc indicates the callout position for
29077  * this packet and ill_index is the interface this packet on or will leave
29078  * on (inbound and outbound resp.).
29079  */
29080 void
29081 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29082 {
29083 	mblk_t		*mp;
29084 	ip_priv_t	*priv;
29085 	ipp_action_id_t	aid;
29086 	int		rc = 0;
29087 	ipp_packet_t	*pp;
29088 #define	IP_CLASS	"ip"
29089 
29090 	/* If the classifier is not loaded, return  */
29091 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29092 		return;
29093 	}
29094 
29095 	mp = *mpp;
29096 	ASSERT(mp != NULL);
29097 
29098 	/* Allocate the packet structure */
29099 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29100 	if (rc != 0) {
29101 		*mpp = NULL;
29102 		freemsg(mp);
29103 		return;
29104 	}
29105 
29106 	/* Allocate the private structure */
29107 	rc = ip_priv_alloc((void **)&priv);
29108 	if (rc != 0) {
29109 		*mpp = NULL;
29110 		freemsg(mp);
29111 		ipp_packet_free(pp);
29112 		return;
29113 	}
29114 	priv->proc = proc;
29115 	priv->ill_index = ill_index;
29116 	ipp_packet_set_private(pp, priv, ip_priv_free);
29117 	ipp_packet_set_data(pp, mp);
29118 
29119 	/* Invoke the classifier */
29120 	rc = ipp_packet_process(&pp);
29121 	if (pp != NULL) {
29122 		mp = ipp_packet_get_data(pp);
29123 		ipp_packet_free(pp);
29124 		if (rc != 0) {
29125 			freemsg(mp);
29126 			*mpp = NULL;
29127 		}
29128 	} else {
29129 		*mpp = NULL;
29130 	}
29131 #undef	IP_CLASS
29132 }
29133 
29134 /*
29135  * Propagate a multicast group membership operation (add/drop) on
29136  * all the interfaces crossed by the related multirt routes.
29137  * The call is considered successful if the operation succeeds
29138  * on at least one interface.
29139  */
29140 static int
29141 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29142     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29143     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29144     mblk_t *first_mp)
29145 {
29146 	ire_t		*ire_gw;
29147 	irb_t		*irb;
29148 	int		error = 0;
29149 	opt_restart_t	*or;
29150 	ip_stack_t	*ipst = ire->ire_ipst;
29151 
29152 	irb = ire->ire_bucket;
29153 	ASSERT(irb != NULL);
29154 
29155 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29156 
29157 	or = (opt_restart_t *)first_mp->b_rptr;
29158 	IRB_REFHOLD(irb);
29159 	for (; ire != NULL; ire = ire->ire_next) {
29160 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29161 			continue;
29162 		if (ire->ire_addr != group)
29163 			continue;
29164 
29165 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29166 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29167 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29168 		/* No resolver exists for the gateway; skip this ire. */
29169 		if (ire_gw == NULL)
29170 			continue;
29171 
29172 		/*
29173 		 * This function can return EINPROGRESS. If so the operation
29174 		 * will be restarted from ip_restart_optmgmt which will
29175 		 * call ip_opt_set and option processing will restart for
29176 		 * this option. So we may end up calling 'fn' more than once.
29177 		 * This requires that 'fn' is idempotent except for the
29178 		 * return value. The operation is considered a success if
29179 		 * it succeeds at least once on any one interface.
29180 		 */
29181 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29182 		    NULL, fmode, src, first_mp);
29183 		if (error == 0)
29184 			or->or_private = CGTP_MCAST_SUCCESS;
29185 
29186 		if (ip_debug > 0) {
29187 			ulong_t	off;
29188 			char	*ksym;
29189 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29190 			ip2dbg(("ip_multirt_apply_membership: "
29191 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29192 			    "error %d [success %u]\n",
29193 			    ksym ? ksym : "?",
29194 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29195 			    error, or->or_private));
29196 		}
29197 
29198 		ire_refrele(ire_gw);
29199 		if (error == EINPROGRESS) {
29200 			IRB_REFRELE(irb);
29201 			return (error);
29202 		}
29203 	}
29204 	IRB_REFRELE(irb);
29205 	/*
29206 	 * Consider the call as successful if we succeeded on at least
29207 	 * one interface. Otherwise, return the last encountered error.
29208 	 */
29209 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29210 }
29211 
29212 
29213 /*
29214  * Issue a warning regarding a route crossing an interface with an
29215  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29216  * amount of time is logged.
29217  */
29218 static void
29219 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29220 {
29221 	hrtime_t	current = gethrtime();
29222 	char		buf[INET_ADDRSTRLEN];
29223 	ip_stack_t	*ipst = ire->ire_ipst;
29224 
29225 	/* Convert interval in ms to hrtime in ns */
29226 	if (ipst->ips_multirt_bad_mtu_last_time +
29227 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29228 	    current) {
29229 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29230 		    "to %s, incorrect MTU %u (expected %u)\n",
29231 		    ip_dot_addr(ire->ire_addr, buf),
29232 		    ire->ire_max_frag, max_frag);
29233 
29234 		ipst->ips_multirt_bad_mtu_last_time = current;
29235 	}
29236 }
29237 
29238 
29239 /*
29240  * Get the CGTP (multirouting) filtering status.
29241  * If 0, the CGTP hooks are transparent.
29242  */
29243 /* ARGSUSED */
29244 static int
29245 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29246 {
29247 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29248 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29249 
29250 	/*
29251 	 * Only applies to the shared stack since the filter_ops
29252 	 * do not carry an ip_stack_t or zoneid.
29253 	 */
29254 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29255 		return (ENOTSUP);
29256 
29257 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29258 	return (0);
29259 }
29260 
29261 
29262 /*
29263  * Set the CGTP (multirouting) filtering status.
29264  * If the status is changed from active to transparent
29265  * or from transparent to active, forward the new status
29266  * to the filtering module (if loaded).
29267  */
29268 /* ARGSUSED */
29269 static int
29270 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29271     cred_t *ioc_cr)
29272 {
29273 	long		new_value;
29274 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29275 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29276 
29277 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
29278 		return (EPERM);
29279 
29280 	/*
29281 	 * Only applies to the shared stack since the filter_ops
29282 	 * do not carry an ip_stack_t or zoneid.
29283 	 */
29284 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29285 		return (ENOTSUP);
29286 
29287 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29288 	    new_value < 0 || new_value > 1) {
29289 		return (EINVAL);
29290 	}
29291 
29292 	/*
29293 	 * Do not enable CGTP filtering - thus preventing the hooks
29294 	 * from being invoked - if the version number of the
29295 	 * filtering module hooks does not match.
29296 	 */
29297 	if ((ip_cgtp_filter_ops != NULL) &&
29298 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29299 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29300 		    "(module hooks version %d, expecting %d)\n",
29301 		    ip_cgtp_filter_ops->cfo_filter_rev,
29302 		    CGTP_FILTER_REV);
29303 		return (ENOTSUP);
29304 	}
29305 
29306 	if ((!*ip_cgtp_filter_value) && new_value) {
29307 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29308 		    ip_cgtp_filter_ops == NULL ?
29309 		    " (module not loaded)" : "");
29310 	}
29311 	if (*ip_cgtp_filter_value && (!new_value)) {
29312 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29313 		    ip_cgtp_filter_ops == NULL ?
29314 		    " (module not loaded)" : "");
29315 	}
29316 
29317 	if (ip_cgtp_filter_ops != NULL) {
29318 		int	res;
29319 
29320 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
29321 		if (res)
29322 			return (res);
29323 	}
29324 
29325 	*ip_cgtp_filter_value = (boolean_t)new_value;
29326 
29327 	return (0);
29328 }
29329 
29330 
29331 /*
29332  * Return the expected CGTP hooks version number.
29333  */
29334 int
29335 ip_cgtp_filter_supported(void)
29336 {
29337 	ip_stack_t *ipst;
29338 	int ret;
29339 
29340 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29341 	if (ipst == NULL)
29342 		return (-1);
29343 	ret = ip_cgtp_filter_rev;
29344 	netstack_rele(ipst->ips_netstack);
29345 	return (ret);
29346 }
29347 
29348 
29349 /*
29350  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29351  * or by invoking this function. In the first case, the version number
29352  * of the registered structure is checked at hooks activation time
29353  * in ip_cgtp_filter_set().
29354  *
29355  * Only applies to the shared stack since the filter_ops
29356  * do not carry an ip_stack_t or zoneid.
29357  */
29358 int
29359 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29360 {
29361 	ip_stack_t *ipst;
29362 
29363 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29364 		return (ENOTSUP);
29365 
29366 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29367 	if (ipst == NULL)
29368 		return (EINVAL);
29369 
29370 	ip_cgtp_filter_ops = ops;
29371 	netstack_rele(ipst->ips_netstack);
29372 	return (0);
29373 }
29374 
29375 static squeue_func_t
29376 ip_squeue_switch(int val)
29377 {
29378 	squeue_func_t rval = squeue_fill;
29379 
29380 	switch (val) {
29381 	case IP_SQUEUE_ENTER_NODRAIN:
29382 		rval = squeue_enter_nodrain;
29383 		break;
29384 	case IP_SQUEUE_ENTER:
29385 		rval = squeue_enter;
29386 		break;
29387 	default:
29388 		break;
29389 	}
29390 	return (rval);
29391 }
29392 
29393 /* ARGSUSED */
29394 static int
29395 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29396     caddr_t addr, cred_t *cr)
29397 {
29398 	int *v = (int *)addr;
29399 	long new_value;
29400 
29401 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29402 		return (EPERM);
29403 
29404 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29405 		return (EINVAL);
29406 
29407 	ip_input_proc = ip_squeue_switch(new_value);
29408 	*v = new_value;
29409 	return (0);
29410 }
29411 
29412 /* ARGSUSED */
29413 static int
29414 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29415     caddr_t addr, cred_t *cr)
29416 {
29417 	int *v = (int *)addr;
29418 	long new_value;
29419 
29420 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29421 		return (EPERM);
29422 
29423 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29424 		return (EINVAL);
29425 
29426 	*v = new_value;
29427 	return (0);
29428 }
29429 
29430 static void *
29431 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29432 {
29433 	kstat_t *ksp;
29434 
29435 	ip_stat_t template = {
29436 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29437 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29438 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29439 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29440 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29441 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29442 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29443 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29444 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29445 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29446 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29447 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29448 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29449 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29450 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29451 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29452 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29453 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29454 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29455 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29456 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29457 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29458 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29459 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29460 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29461 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29462 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29463 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29464 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29465 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29466 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29467 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29468 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29469 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29470 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29471 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29472 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29473 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29474 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29475 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29476 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29477 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29478 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29479 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29480 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29481 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29482 	};
29483 
29484 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29485 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29486 	    KSTAT_FLAG_VIRTUAL, stackid);
29487 
29488 	if (ksp == NULL)
29489 		return (NULL);
29490 
29491 	bcopy(&template, ip_statisticsp, sizeof (template));
29492 	ksp->ks_data = (void *)ip_statisticsp;
29493 	ksp->ks_private = (void *)(uintptr_t)stackid;
29494 
29495 	kstat_install(ksp);
29496 	return (ksp);
29497 }
29498 
29499 static void
29500 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29501 {
29502 	if (ksp != NULL) {
29503 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29504 		kstat_delete_netstack(ksp, stackid);
29505 	}
29506 }
29507 
29508 static void *
29509 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29510 {
29511 	kstat_t	*ksp;
29512 
29513 	ip_named_kstat_t template = {
29514 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29515 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29516 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29517 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29518 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29519 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29520 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29521 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29522 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29523 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29524 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29525 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29526 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29527 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29528 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29529 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29530 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29531 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29532 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29533 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29534 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29535 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29536 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29537 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29538 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29539 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29540 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29541 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29542 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29543 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29544 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29545 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29546 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29547 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29548 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29549 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29550 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29551 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29552 	};
29553 
29554 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29555 					NUM_OF_FIELDS(ip_named_kstat_t),
29556 					0, stackid);
29557 	if (ksp == NULL || ksp->ks_data == NULL)
29558 		return (NULL);
29559 
29560 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29561 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29562 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29563 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29564 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29565 
29566 	template.netToMediaEntrySize.value.i32 =
29567 		sizeof (mib2_ipNetToMediaEntry_t);
29568 
29569 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29570 
29571 	bcopy(&template, ksp->ks_data, sizeof (template));
29572 	ksp->ks_update = ip_kstat_update;
29573 	ksp->ks_private = (void *)(uintptr_t)stackid;
29574 
29575 	kstat_install(ksp);
29576 	return (ksp);
29577 }
29578 
29579 static void
29580 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29581 {
29582 	if (ksp != NULL) {
29583 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29584 		kstat_delete_netstack(ksp, stackid);
29585 	}
29586 }
29587 
29588 static int
29589 ip_kstat_update(kstat_t *kp, int rw)
29590 {
29591 	ip_named_kstat_t *ipkp;
29592 	mib2_ipIfStatsEntry_t ipmib;
29593 	ill_walk_context_t ctx;
29594 	ill_t *ill;
29595 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29596 	netstack_t	*ns;
29597 	ip_stack_t	*ipst;
29598 
29599 	if (kp == NULL || kp->ks_data == NULL)
29600 		return (EIO);
29601 
29602 	if (rw == KSTAT_WRITE)
29603 		return (EACCES);
29604 
29605 	ns = netstack_find_by_stackid(stackid);
29606 	if (ns == NULL)
29607 		return (-1);
29608 	ipst = ns->netstack_ip;
29609 	if (ipst == NULL) {
29610 		netstack_rele(ns);
29611 		return (-1);
29612 	}
29613 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29614 
29615 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29616 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29617 	ill = ILL_START_WALK_V4(&ctx, ipst);
29618 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29619 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29620 	rw_exit(&ipst->ips_ill_g_lock);
29621 
29622 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29623 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29624 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29625 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29626 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29627 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29628 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29629 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29630 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29631 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29632 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29633 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29634 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29635 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29636 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29637 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29638 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29639 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29640 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29641 
29642 	ipkp->routingDiscards.value.ui32 =	0;
29643 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29644 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29645 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29646 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29647 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29648 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29649 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29650 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29651 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29652 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29653 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29654 
29655 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29656 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29657 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29658 
29659 	netstack_rele(ns);
29660 
29661 	return (0);
29662 }
29663 
29664 static void *
29665 icmp_kstat_init(netstackid_t stackid)
29666 {
29667 	kstat_t	*ksp;
29668 
29669 	icmp_named_kstat_t template = {
29670 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29671 		{ "inErrors",		KSTAT_DATA_UINT32 },
29672 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29673 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29674 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29675 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29676 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29677 		{ "inEchos",		KSTAT_DATA_UINT32 },
29678 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29679 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29680 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29681 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29682 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29683 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29684 		{ "outErrors",		KSTAT_DATA_UINT32 },
29685 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29686 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29687 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29688 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29689 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29690 		{ "outEchos",		KSTAT_DATA_UINT32 },
29691 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29692 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29693 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29694 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29695 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29696 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29697 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29698 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29699 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29700 		{ "outDrops",		KSTAT_DATA_UINT32 },
29701 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29702 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29703 	};
29704 
29705 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29706 					NUM_OF_FIELDS(icmp_named_kstat_t),
29707 					0, stackid);
29708 	if (ksp == NULL || ksp->ks_data == NULL)
29709 		return (NULL);
29710 
29711 	bcopy(&template, ksp->ks_data, sizeof (template));
29712 
29713 	ksp->ks_update = icmp_kstat_update;
29714 	ksp->ks_private = (void *)(uintptr_t)stackid;
29715 
29716 	kstat_install(ksp);
29717 	return (ksp);
29718 }
29719 
29720 static void
29721 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29722 {
29723 	if (ksp != NULL) {
29724 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29725 		kstat_delete_netstack(ksp, stackid);
29726 	}
29727 }
29728 
29729 static int
29730 icmp_kstat_update(kstat_t *kp, int rw)
29731 {
29732 	icmp_named_kstat_t *icmpkp;
29733 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29734 	netstack_t	*ns;
29735 	ip_stack_t	*ipst;
29736 
29737 	if ((kp == NULL) || (kp->ks_data == NULL))
29738 		return (EIO);
29739 
29740 	if (rw == KSTAT_WRITE)
29741 		return (EACCES);
29742 
29743 	ns = netstack_find_by_stackid(stackid);
29744 	if (ns == NULL)
29745 		return (-1);
29746 	ipst = ns->netstack_ip;
29747 	if (ipst == NULL) {
29748 		netstack_rele(ns);
29749 		return (-1);
29750 	}
29751 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29752 
29753 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29754 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29755 	icmpkp->inDestUnreachs.value.ui32 =
29756 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29757 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29758 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29759 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29760 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29761 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29762 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29763 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29764 	icmpkp->inTimestampReps.value.ui32 =
29765 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29766 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29767 	icmpkp->inAddrMaskReps.value.ui32 =
29768 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29769 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29770 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29771 	icmpkp->outDestUnreachs.value.ui32 =
29772 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29773 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29774 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29775 	icmpkp->outSrcQuenchs.value.ui32 =
29776 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29777 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29778 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29779 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29780 	icmpkp->outTimestamps.value.ui32 =
29781 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29782 	icmpkp->outTimestampReps.value.ui32 =
29783 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29784 	icmpkp->outAddrMasks.value.ui32 =
29785 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29786 	icmpkp->outAddrMaskReps.value.ui32 =
29787 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29788 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29789 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29790 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29791 	icmpkp->outFragNeeded.value.ui32 =
29792 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29793 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29794 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29795 	icmpkp->inBadRedirects.value.ui32 =
29796 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29797 
29798 	netstack_rele(ns);
29799 	return (0);
29800 }
29801 
29802 /*
29803  * This is the fanout function for raw socket opened for SCTP.  Note
29804  * that it is called after SCTP checks that there is no socket which
29805  * wants a packet.  Then before SCTP handles this out of the blue packet,
29806  * this function is called to see if there is any raw socket for SCTP.
29807  * If there is and it is bound to the correct address, the packet will
29808  * be sent to that socket.  Note that only one raw socket can be bound to
29809  * a port.  This is assured in ipcl_sctp_hash_insert();
29810  */
29811 void
29812 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29813     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29814     zoneid_t zoneid)
29815 {
29816 	conn_t		*connp;
29817 	queue_t		*rq;
29818 	mblk_t		*first_mp;
29819 	boolean_t	secure;
29820 	ip6_t		*ip6h;
29821 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29822 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29823 
29824 	first_mp = mp;
29825 	if (mctl_present) {
29826 		mp = first_mp->b_cont;
29827 		secure = ipsec_in_is_secure(first_mp);
29828 		ASSERT(mp != NULL);
29829 	} else {
29830 		secure = B_FALSE;
29831 	}
29832 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29833 
29834 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29835 	if (connp == NULL) {
29836 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29837 		return;
29838 	}
29839 	rq = connp->conn_rq;
29840 	if (!canputnext(rq)) {
29841 		CONN_DEC_REF(connp);
29842 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29843 		freemsg(first_mp);
29844 		return;
29845 	}
29846 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29847 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29848 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29849 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29850 		if (first_mp == NULL) {
29851 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29852 			CONN_DEC_REF(connp);
29853 			return;
29854 		}
29855 	}
29856 	/*
29857 	 * We probably should not send M_CTL message up to
29858 	 * raw socket.
29859 	 */
29860 	if (mctl_present)
29861 		freeb(first_mp);
29862 
29863 	/* Initiate IPPF processing here if needed. */
29864 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29865 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29866 		ip_process(IPP_LOCAL_IN, &mp,
29867 		    recv_ill->ill_phyint->phyint_ifindex);
29868 		if (mp == NULL) {
29869 			CONN_DEC_REF(connp);
29870 			return;
29871 		}
29872 	}
29873 
29874 	if (connp->conn_recvif || connp->conn_recvslla ||
29875 	    ((connp->conn_ip_recvpktinfo ||
29876 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29877 	    (flags & IP_FF_IPINFO))) {
29878 		int in_flags = 0;
29879 
29880 		/*
29881 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29882 		 * IPF_RECVIF.
29883 		 */
29884 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29885 			in_flags = IPF_RECVIF;
29886 		}
29887 		if (connp->conn_recvslla) {
29888 			in_flags |= IPF_RECVSLLA;
29889 		}
29890 		if (isv4) {
29891 			mp = ip_add_info(mp, recv_ill, in_flags,
29892 			    IPCL_ZONEID(connp), ipst);
29893 		} else {
29894 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29895 			if (mp == NULL) {
29896 				BUMP_MIB(recv_ill->ill_ip_mib,
29897 				    ipIfStatsInDiscards);
29898 				CONN_DEC_REF(connp);
29899 				return;
29900 			}
29901 		}
29902 	}
29903 
29904 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29905 	/*
29906 	 * We are sending the IPSEC_IN message also up. Refer
29907 	 * to comments above this function.
29908 	 */
29909 	putnext(rq, mp);
29910 	CONN_DEC_REF(connp);
29911 }
29912 
29913 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29914 {									\
29915 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29916 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29917 }
29918 /*
29919  * This function should be called only if all packet processing
29920  * including fragmentation is complete. Callers of this function
29921  * must set mp->b_prev to one of these values:
29922  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29923  * prior to handing over the mp as first argument to this function.
29924  *
29925  * If the ire passed by caller is incomplete, this function
29926  * queues the packet and if necessary, sends ARP request and bails.
29927  * If the ire passed is fully resolved, we simply prepend
29928  * the link-layer header to the packet, do ipsec hw acceleration
29929  * work if necessary, and send the packet out on the wire.
29930  *
29931  * NOTE: IPSEC will only call this function with fully resolved
29932  * ires if hw acceleration is involved.
29933  * TODO list :
29934  * 	a Handle M_MULTIDATA so that
29935  *	  tcp_multisend->tcp_multisend_data can
29936  *	  call ip_xmit_v4 directly
29937  *	b Handle post-ARP work for fragments so that
29938  *	  ip_wput_frag can call this function.
29939  */
29940 ipxmit_state_t
29941 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29942 {
29943 	nce_t		*arpce;
29944 	queue_t		*q;
29945 	int		ill_index;
29946 	mblk_t		*nxt_mp, *first_mp;
29947 	boolean_t	xmit_drop = B_FALSE;
29948 	ip_proc_t	proc;
29949 	ill_t		*out_ill;
29950 	int		pkt_len;
29951 
29952 	arpce = ire->ire_nce;
29953 	ASSERT(arpce != NULL);
29954 
29955 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29956 
29957 	mutex_enter(&arpce->nce_lock);
29958 	switch (arpce->nce_state) {
29959 	case ND_REACHABLE:
29960 		/* If there are other queued packets, queue this packet */
29961 		if (arpce->nce_qd_mp != NULL) {
29962 			if (mp != NULL)
29963 				nce_queue_mp_common(arpce, mp, B_FALSE);
29964 			mp = arpce->nce_qd_mp;
29965 		}
29966 		arpce->nce_qd_mp = NULL;
29967 		mutex_exit(&arpce->nce_lock);
29968 
29969 		/*
29970 		 * Flush the queue.  In the common case, where the
29971 		 * ARP is already resolved,  it will go through the
29972 		 * while loop only once.
29973 		 */
29974 		while (mp != NULL) {
29975 
29976 			nxt_mp = mp->b_next;
29977 			mp->b_next = NULL;
29978 			ASSERT(mp->b_datap->db_type != M_CTL);
29979 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29980 			/*
29981 			 * This info is needed for IPQOS to do COS marking
29982 			 * in ip_wput_attach_llhdr->ip_process.
29983 			 */
29984 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29985 			mp->b_prev = NULL;
29986 
29987 			/* set up ill index for outbound qos processing */
29988 			out_ill = ire->ire_ipif->ipif_ill;
29989 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29990 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29991 			    ill_index);
29992 			if (first_mp == NULL) {
29993 				xmit_drop = B_TRUE;
29994 				BUMP_MIB(out_ill->ill_ip_mib,
29995 				    ipIfStatsOutDiscards);
29996 				goto next_mp;
29997 			}
29998 			/* non-ipsec hw accel case */
29999 			if (io == NULL || !io->ipsec_out_accelerated) {
30000 				/* send it */
30001 				q = ire->ire_stq;
30002 				if (proc == IPP_FWD_OUT) {
30003 					UPDATE_IB_PKT_COUNT(ire);
30004 				} else {
30005 					UPDATE_OB_PKT_COUNT(ire);
30006 				}
30007 				ire->ire_last_used_time = lbolt;
30008 
30009 				if (flow_ctl_enabled || canputnext(q))  {
30010 					if (proc == IPP_FWD_OUT) {
30011 						BUMP_MIB(out_ill->ill_ip_mib,
30012 						ipIfStatsHCOutForwDatagrams);
30013 					}
30014 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30015 					    pkt_len);
30016 
30017 					putnext(q, first_mp);
30018 				} else {
30019 					BUMP_MIB(out_ill->ill_ip_mib,
30020 					    ipIfStatsOutDiscards);
30021 					xmit_drop = B_TRUE;
30022 					freemsg(first_mp);
30023 				}
30024 			} else {
30025 				/*
30026 				 * Safety Pup says: make sure this
30027 				 *  is going to the right interface!
30028 				 */
30029 				ill_t *ill1 =
30030 				    (ill_t *)ire->ire_stq->q_ptr;
30031 				int ifindex =
30032 				    ill1->ill_phyint->phyint_ifindex;
30033 				if (ifindex !=
30034 				    io->ipsec_out_capab_ill_index) {
30035 					xmit_drop = B_TRUE;
30036 					freemsg(mp);
30037 				} else {
30038 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30039 					    pkt_len);
30040 					ipsec_hw_putnext(ire->ire_stq, mp);
30041 				}
30042 			}
30043 next_mp:
30044 			mp = nxt_mp;
30045 		} /* while (mp != NULL) */
30046 		if (xmit_drop)
30047 			return (SEND_FAILED);
30048 		else
30049 			return (SEND_PASSED);
30050 
30051 	case ND_INITIAL:
30052 	case ND_INCOMPLETE:
30053 
30054 		/*
30055 		 * While we do send off packets to dests that
30056 		 * use fully-resolved CGTP routes, we do not
30057 		 * handle unresolved CGTP routes.
30058 		 */
30059 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30060 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30061 
30062 		if (mp != NULL) {
30063 			/* queue the packet */
30064 			nce_queue_mp_common(arpce, mp, B_FALSE);
30065 		}
30066 
30067 		if (arpce->nce_state == ND_INCOMPLETE) {
30068 			mutex_exit(&arpce->nce_lock);
30069 			DTRACE_PROBE3(ip__xmit__incomplete,
30070 			    (ire_t *), ire, (mblk_t *), mp,
30071 			    (ipsec_out_t *), io);
30072 			return (LOOKUP_IN_PROGRESS);
30073 		}
30074 
30075 		arpce->nce_state = ND_INCOMPLETE;
30076 		mutex_exit(&arpce->nce_lock);
30077 		/*
30078 		 * Note that ire_add() (called from ire_forward())
30079 		 * holds a ref on the ire until ARP is completed.
30080 		 */
30081 
30082 		ire_arpresolve(ire, ire_to_ill(ire));
30083 		return (LOOKUP_IN_PROGRESS);
30084 	default:
30085 		ASSERT(0);
30086 		mutex_exit(&arpce->nce_lock);
30087 		return (LLHDR_RESLV_FAILED);
30088 	}
30089 }
30090 
30091 #undef	UPDATE_IP_MIB_OB_COUNTERS
30092 
30093 /*
30094  * Return B_TRUE if the buffers differ in length or content.
30095  * This is used for comparing extension header buffers.
30096  * Note that an extension header would be declared different
30097  * even if all that changed was the next header value in that header i.e.
30098  * what really changed is the next extension header.
30099  */
30100 boolean_t
30101 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30102     uint_t blen)
30103 {
30104 	if (!b_valid)
30105 		blen = 0;
30106 
30107 	if (alen != blen)
30108 		return (B_TRUE);
30109 	if (alen == 0)
30110 		return (B_FALSE);	/* Both zero length */
30111 	return (bcmp(abuf, bbuf, alen));
30112 }
30113 
30114 /*
30115  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30116  * Return B_FALSE if memory allocation fails - don't change any state!
30117  */
30118 boolean_t
30119 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30120     const void *src, uint_t srclen)
30121 {
30122 	void *dst;
30123 
30124 	if (!src_valid)
30125 		srclen = 0;
30126 
30127 	ASSERT(*dstlenp == 0);
30128 	if (src != NULL && srclen != 0) {
30129 		dst = mi_alloc(srclen, BPRI_MED);
30130 		if (dst == NULL)
30131 			return (B_FALSE);
30132 	} else {
30133 		dst = NULL;
30134 	}
30135 	if (*dstp != NULL)
30136 		mi_free(*dstp);
30137 	*dstp = dst;
30138 	*dstlenp = dst == NULL ? 0 : srclen;
30139 	return (B_TRUE);
30140 }
30141 
30142 /*
30143  * Replace what is in *dst, *dstlen with the source.
30144  * Assumes ip_allocbuf has already been called.
30145  */
30146 void
30147 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30148     const void *src, uint_t srclen)
30149 {
30150 	if (!src_valid)
30151 		srclen = 0;
30152 
30153 	ASSERT(*dstlenp == srclen);
30154 	if (src != NULL && srclen != 0)
30155 		bcopy(src, *dstp, srclen);
30156 }
30157 
30158 /*
30159  * Free the storage pointed to by the members of an ip6_pkt_t.
30160  */
30161 void
30162 ip6_pkt_free(ip6_pkt_t *ipp)
30163 {
30164 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30165 
30166 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30167 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30168 		ipp->ipp_hopopts = NULL;
30169 		ipp->ipp_hopoptslen = 0;
30170 	}
30171 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30172 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30173 		ipp->ipp_rtdstopts = NULL;
30174 		ipp->ipp_rtdstoptslen = 0;
30175 	}
30176 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30177 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30178 		ipp->ipp_dstopts = NULL;
30179 		ipp->ipp_dstoptslen = 0;
30180 	}
30181 	if (ipp->ipp_fields & IPPF_RTHDR) {
30182 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30183 		ipp->ipp_rthdr = NULL;
30184 		ipp->ipp_rthdrlen = 0;
30185 	}
30186 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30187 	    IPPF_RTHDR);
30188 }
30189