xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision c8fcc830223bbda01aa320090635c8c1772e1e1a)
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  * It would be nice to have these present only in DEBUG systems, but the
158  * current design of the global symbol checking logic requires them to be
159  * unconditionally present.
160  */
161 uint_t ip_thread_data;			/* TSD key for debug support */
162 krwlock_t ip_thread_rwlock;
163 list_t	ip_thread_list;
164 
165 /*
166  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
167  */
168 
169 struct listptr_s {
170 	mblk_t	*lp_head;	/* pointer to the head of the list */
171 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
172 };
173 
174 typedef struct listptr_s listptr_t;
175 
176 /*
177  * This is used by ip_snmp_get_mib2_ip_route_media and
178  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
179  */
180 typedef struct iproutedata_s {
181 	uint_t		ird_idx;
182 	listptr_t	ird_route;	/* ipRouteEntryTable */
183 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
184 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
185 } iproutedata_t;
186 
187 /*
188  * Cluster specific hooks. These should be NULL when booted as a non-cluster
189  */
190 
191 /*
192  * Hook functions to enable cluster networking
193  * On non-clustered systems these vectors must always be NULL.
194  *
195  * Hook function to Check ip specified ip address is a shared ip address
196  * in the cluster
197  *
198  */
199 int (*cl_inet_isclusterwide)(uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp) = NULL;
201 
202 /*
203  * Hook function to generate cluster wide ip fragment identifier
204  */
205 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
206     uint8_t *laddrp, uint8_t *faddrp) = NULL;
207 
208 /*
209  * Synchronization notes:
210  *
211  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
212  * MT level protection given by STREAMS. IP uses a combination of its own
213  * internal serialization mechanism and standard Solaris locking techniques.
214  * The internal serialization is per phyint (no IPMP) or per IPMP group.
215  * This is used to serialize plumbing operations, IPMP operations, certain
216  * multicast operations, most set ioctls, igmp/mld timers etc.
217  *
218  * Plumbing is a long sequence of operations involving message
219  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
220  * involved in plumbing operations. A natural model is to serialize these
221  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
222  * parallel without any interference. But various set ioctls on hme0 are best
223  * serialized. However if the system uses IPMP, the operations are easier if
224  * they are serialized on a per IPMP group basis since IPMP operations
225  * happen across ill's of a group. Thus the lowest common denominator is to
226  * serialize most set ioctls, multicast join/leave operations, IPMP operations
227  * igmp/mld timer operations, and processing of DLPI control messages received
228  * from drivers on a per IPMP group basis. If the system does not employ
229  * IPMP the serialization is on a per phyint basis. This serialization is
230  * provided by the ipsq_t and primitives operating on this. Details can
231  * be found in ip_if.c above the core primitives operating on ipsq_t.
232  *
233  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
234  * Simiarly lookup of an ire by a thread also returns a refheld ire.
235  * In addition ipif's and ill's referenced by the ire are also indirectly
236  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
237  * the ipif's address or netmask change as long as an ipif is refheld
238  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
239  * address of an ipif has to go through the ipsq_t. This ensures that only
240  * 1 such exclusive operation proceeds at any time on the ipif. It then
241  * deletes all ires associated with this ipif, and waits for all refcnts
242  * associated with this ipif to come down to zero. The address is changed
243  * only after the ipif has been quiesced. Then the ipif is brought up again.
244  * More details are described above the comment in ip_sioctl_flags.
245  *
246  * Packet processing is based mostly on IREs and are fully multi-threaded
247  * using standard Solaris MT techniques.
248  *
249  * There are explicit locks in IP to handle:
250  * - The ip_g_head list maintained by mi_open_link() and friends.
251  *
252  * - The reassembly data structures (one lock per hash bucket)
253  *
254  * - conn_lock is meant to protect conn_t fields. The fields actually
255  *   protected by conn_lock are documented in the conn_t definition.
256  *
257  * - ire_lock to protect some of the fields of the ire, IRE tables
258  *   (one lock per hash bucket). Refer to ip_ire.c for details.
259  *
260  * - ndp_g_lock and nce_lock for protecting NCEs.
261  *
262  * - ill_lock protects fields of the ill and ipif. Details in ip.h
263  *
264  * - ill_g_lock: This is a global reader/writer lock. Protects the following
265  *	* The AVL tree based global multi list of all ills.
266  *	* The linked list of all ipifs of an ill
267  *	* The <ill-ipsq> mapping
268  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
269  *	* The illgroup list threaded by ill_group_next.
270  *	* <ill-phyint> association
271  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
272  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
273  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
274  *   will all have to hold the ill_g_lock as writer for the actual duration
275  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
276  *   may be found in the IPMP section.
277  *
278  * - ill_lock:  This is a per ill mutex.
279  *   It protects some members of the ill and is documented below.
280  *   It also protects the <ill-ipsq> mapping
281  *   It also protects the illgroup list threaded by ill_group_next.
282  *   It also protects the <ill-phyint> assoc.
283  *   It also protects the list of ipifs hanging off the ill.
284  *
285  * - ipsq_lock: This is a per ipsq_t mutex lock.
286  *   This protects all the other members of the ipsq struct except
287  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
288  *
289  * - illgrp_lock: This is a per ill_group mutex lock.
290  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
291  *   which dictates which is the next ill in an ill_group that is to be chosen
292  *   for sending outgoing packets, through creation of an IRE_CACHE that
293  *   references this ill.
294  *
295  * - phyint_lock: This is a per phyint mutex lock. Protects just the
296  *   phyint_flags
297  *
298  * - ip_g_nd_lock: This is a global reader/writer lock.
299  *   Any call to nd_load to load a new parameter to the ND table must hold the
300  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
301  *   as reader.
302  *
303  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
304  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
305  *   uniqueness check also done atomically.
306  *
307  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
308  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
309  *   as a writer when adding or deleting elements from these lists, and
310  *   as a reader when walking these lists to send a SADB update to the
311  *   IPsec capable ills.
312  *
313  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
314  *   group list linked by ill_usesrc_grp_next. It also protects the
315  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
316  *   group is being added or deleted.  This lock is taken as a reader when
317  *   walking the list/group(eg: to get the number of members in a usesrc group).
318  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
319  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
320  *   example, it is not necessary to take this lock in the initial portion
321  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
322  *   ip_sioctl_flags since the these operations are executed exclusively and
323  *   that ensures that the "usesrc group state" cannot change. The "usesrc
324  *   group state" change can happen only in the latter part of
325  *   ip_sioctl_slifusesrc and in ill_delete.
326  *
327  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
328  *
329  * To change the <ill-phyint> association, the ill_g_lock must be held
330  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
331  * must be held.
332  *
333  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
334  * and the ill_lock of the ill in question must be held.
335  *
336  * To change the <ill-illgroup> association the ill_g_lock must be held as
337  * writer and the ill_lock of the ill in question must be held.
338  *
339  * To add or delete an ipif from the list of ipifs hanging off the ill,
340  * ill_g_lock (writer) and ill_lock must be held and the thread must be
341  * a writer on the associated ipsq,.
342  *
343  * To add or delete an ill to the system, the ill_g_lock must be held as
344  * writer and the thread must be a writer on the associated ipsq.
345  *
346  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
347  * must be a writer on the associated ipsq.
348  *
349  * Lock hierarchy
350  *
351  * Some lock hierarchy scenarios are listed below.
352  *
353  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
354  * ill_g_lock -> illgrp_lock -> ill_lock
355  * ill_g_lock -> ill_lock(s) -> phyint_lock
356  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
357  * ill_g_lock -> ip_addr_avail_lock
358  * conn_lock -> irb_lock -> ill_lock -> ire_lock
359  * ill_g_lock -> ip_g_nd_lock
360  *
361  * When more than 1 ill lock is needed to be held, all ill lock addresses
362  * are sorted on address and locked starting from highest addressed lock
363  * downward.
364  *
365  * IPsec scenarios
366  *
367  * ipsa_lock -> ill_g_lock -> ill_lock
368  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
369  * ipsec_capab_ills_lock -> ipsa_lock
370  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
371  *
372  * Trusted Solaris scenarios
373  *
374  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
375  * igsa_lock -> gcdb_lock
376  * gcgrp_rwlock -> ire_lock
377  * gcgrp_rwlock -> gcdb_lock
378  *
379  *
380  * Routing/forwarding table locking notes:
381  *
382  * Lock acquisition order: Radix tree lock, irb_lock.
383  * Requirements:
384  * i.  Walker must not hold any locks during the walker callback.
385  * ii  Walker must not see a truncated tree during the walk because of any node
386  *     deletion.
387  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
388  *     in many places in the code to walk the irb list. Thus even if all the
389  *     ires in a bucket have been deleted, we still can't free the radix node
390  *     until the ires have actually been inactive'd (freed).
391  *
392  * Tree traversal - Need to hold the global tree lock in read mode.
393  * Before dropping the global tree lock, need to either increment the ire_refcnt
394  * to ensure that the radix node can't be deleted.
395  *
396  * Tree add - Need to hold the global tree lock in write mode to add a
397  * radix node. To prevent the node from being deleted, increment the
398  * irb_refcnt, after the node is added to the tree. The ire itself is
399  * added later while holding the irb_lock, but not the tree lock.
400  *
401  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
402  * All associated ires must be inactive (i.e. freed), and irb_refcnt
403  * must be zero.
404  *
405  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
406  * global tree lock (read mode) for traversal.
407  *
408  * IPsec notes :
409  *
410  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
411  * in front of the actual packet. For outbound datagrams, the M_CTL
412  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
413  * information used by the IPsec code for applying the right level of
414  * protection. The information initialized by IP in the ipsec_out_t
415  * is determined by the per-socket policy or global policy in the system.
416  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
417  * ipsec_info.h) which starts out with nothing in it. It gets filled
418  * with the right information if it goes through the AH/ESP code, which
419  * happens if the incoming packet is secure. The information initialized
420  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
421  * the policy requirements needed by per-socket policy or global policy
422  * is met or not.
423  *
424  * If there is both per-socket policy (set using setsockopt) and there
425  * is also global policy match for the 5 tuples of the socket,
426  * ipsec_override_policy() makes the decision of which one to use.
427  *
428  * For fully connected sockets i.e dst, src [addr, port] is known,
429  * conn_policy_cached is set indicating that policy has been cached.
430  * conn_in_enforce_policy may or may not be set depending on whether
431  * there is a global policy match or per-socket policy match.
432  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
433  * Once the right policy is set on the conn_t, policy cannot change for
434  * this socket. This makes life simpler for TCP (UDP ?) where
435  * re-transmissions go out with the same policy. For symmetry, policy
436  * is cached for fully connected UDP sockets also. Thus if policy is cached,
437  * it also implies that policy is latched i.e policy cannot change
438  * on these sockets. As we have the right policy on the conn, we don't
439  * have to lookup global policy for every outbound and inbound datagram
440  * and thus serving as an optimization. Note that a global policy change
441  * does not affect fully connected sockets if they have policy. If fully
442  * connected sockets did not have any policy associated with it, global
443  * policy change may affect them.
444  *
445  * IP Flow control notes:
446  *
447  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
448  * cannot be sent down to the driver by IP, because of a canput failure, IP
449  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
450  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
451  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
452  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
453  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
454  * the queued messages, and removes the conn from the drain list, if all
455  * messages were drained. It also qenables the next conn in the drain list to
456  * continue the drain process.
457  *
458  * In reality the drain list is not a single list, but a configurable number
459  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
460  * list. If the ip_wsrv of the next qenabled conn does not run, because the
461  * stream closes, ip_close takes responsibility to qenable the next conn in
462  * the drain list. The directly called ip_wput path always does a putq, if
463  * it cannot putnext. Thus synchronization problems are handled between
464  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
465  * functions that manipulate this drain list. Furthermore conn_drain_insert
466  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
467  * running on a queue at any time. conn_drain_tail can be simultaneously called
468  * from both ip_wsrv and ip_close.
469  *
470  * IPQOS notes:
471  *
472  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
473  * and IPQoS modules. IPPF includes hooks in IP at different control points
474  * (callout positions) which direct packets to IPQoS modules for policy
475  * processing. Policies, if present, are global.
476  *
477  * The callout positions are located in the following paths:
478  *		o local_in (packets destined for this host)
479  *		o local_out (packets orginating from this host )
480  *		o fwd_in  (packets forwarded by this m/c - inbound)
481  *		o fwd_out (packets forwarded by this m/c - outbound)
482  * Hooks at these callout points can be enabled/disabled using the ndd variable
483  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
484  * By default all the callout positions are enabled.
485  *
486  * Outbound (local_out)
487  * Hooks are placed in ip_wput_ire and ipsec_out_process.
488  *
489  * Inbound (local_in)
490  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
491  * TCP and UDP fanout routines.
492  *
493  * Forwarding (in and out)
494  * Hooks are placed in ip_rput_forward.
495  *
496  * IP Policy Framework processing (IPPF processing)
497  * Policy processing for a packet is initiated by ip_process, which ascertains
498  * that the classifier (ipgpc) is loaded and configured, failing which the
499  * packet resumes normal processing in IP. If the clasifier is present, the
500  * packet is acted upon by one or more IPQoS modules (action instances), per
501  * filters configured in ipgpc and resumes normal IP processing thereafter.
502  * An action instance can drop a packet in course of its processing.
503  *
504  * A boolean variable, ip_policy, is used in all the fanout routines that can
505  * invoke ip_process for a packet. This variable indicates if the packet should
506  * to be sent for policy processing. The variable is set to B_TRUE by default,
507  * i.e. when the routines are invoked in the normal ip procesing path for a
508  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
509  * ip_policy is set to B_FALSE for all the routines called in these two
510  * functions because, in the former case,  we don't process loopback traffic
511  * currently while in the latter, the packets have already been processed in
512  * icmp_inbound.
513  *
514  * Zones notes:
515  *
516  * The partitioning rules for networking are as follows:
517  * 1) Packets coming from a zone must have a source address belonging to that
518  * zone.
519  * 2) Packets coming from a zone can only be sent on a physical interface on
520  * which the zone has an IP address.
521  * 3) Between two zones on the same machine, packet delivery is only allowed if
522  * there's a matching route for the destination and zone in the forwarding
523  * table.
524  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
525  * different zones can bind to the same port with the wildcard address
526  * (INADDR_ANY).
527  *
528  * The granularity of interface partitioning is at the logical interface level.
529  * Therefore, every zone has its own IP addresses, and incoming packets can be
530  * attributed to a zone unambiguously. A logical interface is placed into a zone
531  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
532  * structure. Rule (1) is implemented by modifying the source address selection
533  * algorithm so that the list of eligible addresses is filtered based on the
534  * sending process zone.
535  *
536  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
537  * across all zones, depending on their type. Here is the break-up:
538  *
539  * IRE type				Shared/exclusive
540  * --------				----------------
541  * IRE_BROADCAST			Exclusive
542  * IRE_DEFAULT (default routes)		Shared (*)
543  * IRE_LOCAL				Exclusive (x)
544  * IRE_LOOPBACK				Exclusive
545  * IRE_PREFIX (net routes)		Shared (*)
546  * IRE_CACHE				Exclusive
547  * IRE_IF_NORESOLVER (interface routes)	Exclusive
548  * IRE_IF_RESOLVER (interface routes)	Exclusive
549  * IRE_HOST (host routes)		Shared (*)
550  *
551  * (*) A zone can only use a default or off-subnet route if the gateway is
552  * directly reachable from the zone, that is, if the gateway's address matches
553  * one of the zone's logical interfaces.
554  *
555  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
556  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
557  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
558  * address of the zone itself (the destination). Since IRE_LOCAL is used
559  * for communication between zones, ip_wput_ire has special logic to set
560  * the right source address when sending using an IRE_LOCAL.
561  *
562  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
563  * ire_cache_lookup restricts loopback using an IRE_LOCAL
564  * between zone to the case when L2 would have conceptually looped the packet
565  * back, i.e. the loopback which is required since neither Ethernet drivers
566  * nor Ethernet hardware loops them back. This is the case when the normal
567  * routes (ignoring IREs with different zoneids) would send out the packet on
568  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
569  * associated.
570  *
571  * Multiple zones can share a common broadcast address; typically all zones
572  * share the 255.255.255.255 address. Incoming as well as locally originated
573  * broadcast packets must be dispatched to all the zones on the broadcast
574  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
575  * since some zones may not be on the 10.16.72/24 network. To handle this, each
576  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
577  * sent to every zone that has an IRE_BROADCAST entry for the destination
578  * address on the input ill, see conn_wantpacket().
579  *
580  * Applications in different zones can join the same multicast group address.
581  * For IPv4, group memberships are per-logical interface, so they're already
582  * inherently part of a zone. For IPv6, group memberships are per-physical
583  * interface, so we distinguish IPv6 group memberships based on group address,
584  * interface and zoneid. In both cases, received multicast packets are sent to
585  * every zone for which a group membership entry exists. On IPv6 we need to
586  * check that the target zone still has an address on the receiving physical
587  * interface; it could have been removed since the application issued the
588  * IPV6_JOIN_GROUP.
589  */
590 
591 /*
592  * Squeue Fanout flags:
593  *	0: No fanout.
594  *	1: Fanout across all squeues
595  */
596 boolean_t	ip_squeue_fanout = 0;
597 
598 /*
599  * Maximum dups allowed per packet.
600  */
601 uint_t ip_max_frag_dups = 10;
602 
603 #define	IS_SIMPLE_IPH(ipha)						\
604 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
605 
606 /* RFC1122 Conformance */
607 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
608 
609 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
610 
611 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
612 
613 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
614 
615 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
616 		    ip_stack_t *);
617 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
618 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
619 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
620 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
621 		    mblk_t *, int, ip_stack_t *);
622 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
623 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
624 		    ill_t *, zoneid_t);
625 static void	icmp_options_update(ipha_t *);
626 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
627 		    ip_stack_t *);
628 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
629 		    zoneid_t zoneid, ip_stack_t *);
630 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
631 static void	icmp_redirect(ill_t *, mblk_t *);
632 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
633 		    ip_stack_t *);
634 
635 static void	ip_arp_news(queue_t *, mblk_t *);
636 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
637 		    ip_stack_t *);
638 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
639 char		*ip_dot_addr(ipaddr_t, char *);
640 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
641 int		ip_close(queue_t *, int);
642 static char	*ip_dot_saddr(uchar_t *, char *);
643 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
644 		    boolean_t, boolean_t, ill_t *, zoneid_t);
645 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
646 		    boolean_t, boolean_t, zoneid_t);
647 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
648 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
649 static void	ip_lrput(queue_t *, mblk_t *);
650 ipaddr_t	ip_net_mask(ipaddr_t);
651 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
652 		    ip_stack_t *);
653 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
654 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
655 char		*ip_nv_lookup(nv_t *, int);
656 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
657 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
658 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
659 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
660     ipndp_t *, size_t);
661 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
662 void	ip_rput(queue_t *, mblk_t *);
663 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
664 		    void *dummy_arg);
665 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
666 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
667     ip_stack_t *);
668 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
669 			    ire_t *, ip_stack_t *);
670 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
671 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
672 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
673     ip_stack_t *);
674 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
675 		    uint16_t *);
676 int		ip_snmp_get(queue_t *, mblk_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
678 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
680 		    ip_stack_t *);
681 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
682 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
703 		    ip_stack_t *ipst);
704 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
705 		    ip_stack_t *ipst);
706 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
707 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
708 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
709 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
710 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
711 static boolean_t	ip_source_route_included(ipha_t *);
712 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
713 
714 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
715 		    zoneid_t, ip_stack_t *);
716 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
717 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
718 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
719 		    zoneid_t, ip_stack_t *);
720 
721 static void	conn_drain_init(ip_stack_t *);
722 static void	conn_drain_fini(ip_stack_t *);
723 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
724 
725 static void	conn_walk_drain(ip_stack_t *);
726 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
727     zoneid_t);
728 
729 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
730 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
731 static void	ip_stack_fini(netstackid_t stackid, void *arg);
732 
733 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
734     zoneid_t);
735 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
736     void *dummy_arg);
737 
738 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
739 
740 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
741     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
742     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
743 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
744 
745 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
746 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
747     caddr_t, cred_t *);
748 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
749     caddr_t cp, cred_t *cr);
750 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
751     cred_t *);
752 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
753     caddr_t cp, cred_t *cr);
754 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
755     cred_t *);
756 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
757     cred_t *);
758 static squeue_func_t ip_squeue_switch(int);
759 
760 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
761 static void	ip_kstat_fini(netstackid_t, kstat_t *);
762 static int	ip_kstat_update(kstat_t *kp, int rw);
763 static void	*icmp_kstat_init(netstackid_t);
764 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
765 static int	icmp_kstat_update(kstat_t *kp, int rw);
766 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
767 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
768 
769 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
770 
771 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
772     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
773 
774 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
775     ipha_t *, ill_t *, boolean_t);
776 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
777 
778 /* How long, in seconds, we allow frags to hang around. */
779 #define	IP_FRAG_TIMEOUT	60
780 
781 /*
782  * Threshold which determines whether MDT should be used when
783  * generating IP fragments; payload size must be greater than
784  * this threshold for MDT to take place.
785  */
786 #define	IP_WPUT_FRAG_MDT_MIN	32768
787 
788 /* Setable in /etc/system only */
789 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
790 
791 static long ip_rput_pullups;
792 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
793 
794 vmem_t *ip_minor_arena;
795 
796 int	ip_debug;
797 
798 #ifdef DEBUG
799 uint32_t ipsechw_debug = 0;
800 #endif
801 
802 /*
803  * Multirouting/CGTP stuff
804  */
805 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
806 
807 /*
808  * XXX following really should only be in a header. Would need more
809  * header and .c clean up first.
810  */
811 extern optdb_obj_t	ip_opt_obj;
812 
813 ulong_t ip_squeue_enter_unbound = 0;
814 
815 /*
816  * Named Dispatch Parameter Table.
817  * All of these are alterable, within the min/max values given, at run time.
818  */
819 static ipparam_t	lcl_param_arr[] = {
820 	/* min	max	value	name */
821 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
822 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
823 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
824 	{  0,	1,	0,	"ip_respond_to_timestamp"},
825 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
826 	{  0,	1,	1,	"ip_send_redirects"},
827 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
828 	{  0,	10,	0,	"ip_debug"},
829 	{  0,	10,	0,	"ip_mrtdebug"},
830 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
831 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
832 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
833 	{  1,	255,	255,	"ip_def_ttl" },
834 	{  0,	1,	0,	"ip_forward_src_routed"},
835 	{  0,	256,	32,	"ip_wroff_extra" },
836 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
837 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
838 	{  0,	1,	1,	"ip_path_mtu_discovery" },
839 	{  0,	240,	30,	"ip_ignore_delete_time" },
840 	{  0,	1,	0,	"ip_ignore_redirect" },
841 	{  0,	1,	1,	"ip_output_queue" },
842 	{  1,	254,	1,	"ip_broadcast_ttl" },
843 	{  0,	99999,	100,	"ip_icmp_err_interval" },
844 	{  1,	99999,	10,	"ip_icmp_err_burst" },
845 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
846 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
847 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
848 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
849 	{  0,	1,	1,	"icmp_accept_clear_messages" },
850 	{  0,	1,	1,	"igmp_accept_clear_messages" },
851 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
852 				"ip_ndp_delay_first_probe_time"},
853 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
854 				"ip_ndp_max_unicast_solicit"},
855 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
856 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
857 	{  0,	1,	0,	"ip6_forward_src_routed"},
858 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
859 	{  0,	1,	1,	"ip6_send_redirects"},
860 	{  0,	1,	0,	"ip6_ignore_redirect" },
861 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
862 
863 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
864 
865 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
866 
867 	{  0,	1,	1,	"pim_accept_clear_messages" },
868 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
869 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
870 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
871 	{  0,	15,	0,	"ip_policy_mask" },
872 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
873 	{  0,	255,	1,	"ip_multirt_ttl" },
874 	{  0,	1,	1,	"ip_multidata_outbound" },
875 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
876 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
877 	{  0,	1000,	1,	"ip_max_temp_defend" },
878 	{  0,	1000,	3,	"ip_max_defend" },
879 	{  0,	999999,	30,	"ip_defend_interval" },
880 	{  0,	3600000, 300000, "ip_dup_recovery" },
881 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
882 	{  0,	1,	1,	"ip_lso_outbound" },
883 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
884 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
885 #ifdef DEBUG
886 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
887 #else
888 	{  0,	0,	0,	"" },
889 #endif
890 };
891 
892 /*
893  * Extended NDP table
894  * The addresses for the first two are filled in to be ips_ip_g_forward
895  * and ips_ipv6_forward at init time.
896  */
897 static ipndp_t	lcl_ndp_arr[] = {
898 	/* getf			setf		data			name */
899 #define	IPNDP_IP_FORWARDING_OFFSET	0
900 	{  ip_param_generic_get,	ip_forward_set,	NULL,
901 	    "ip_forwarding" },
902 #define	IPNDP_IP6_FORWARDING_OFFSET	1
903 	{  ip_param_generic_get,	ip_forward_set,	NULL,
904 	    "ip6_forwarding" },
905 	{  ip_ill_report,	NULL,		NULL,
906 	    "ip_ill_status" },
907 	{  ip_ipif_report,	NULL,		NULL,
908 	    "ip_ipif_status" },
909 	{  ip_ire_report,	NULL,		NULL,
910 	    "ipv4_ire_status" },
911 	{  ip_ire_report_v6,	NULL,		NULL,
912 	    "ipv6_ire_status" },
913 	{  ip_conn_report,	NULL,		NULL,
914 	    "ip_conn_status" },
915 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
916 	    "ip_rput_pullups" },
917 	{  ndp_report,		NULL,		NULL,
918 	    "ip_ndp_cache_report" },
919 	{  ip_srcid_report,	NULL,		NULL,
920 	    "ip_srcid_status" },
921 	{ ip_param_generic_get, ip_squeue_profile_set,
922 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
923 	{ ip_param_generic_get, ip_squeue_bind_set,
924 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
925 	{ ip_param_generic_get, ip_input_proc_set,
926 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
927 	{ ip_param_generic_get, ip_int_set,
928 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
929 #define	IPNDP_CGTP_FILTER_OFFSET	14
930 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
931 	    "ip_cgtp_filter" },
932 	{ ip_param_generic_get, ip_int_set,
933 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
934 #define	IPNDP_IPMP_HOOK_OFFSET	16
935 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
936 	    "ipmp_hook_emulation" },
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,
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 			ARP_CMD, ip_sioctl_arp, NULL },
1018 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1019 			ARP_CMD, ip_sioctl_arp, NULL },
1020 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1021 			ARP_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,
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,
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,
1262 			ip_sioctl_get_lifconf, NULL },
1263 
1264 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1265 			XARP_CMD, ip_sioctl_arp, NULL },
1266 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1267 			XARP_CMD, ip_sioctl_arp, NULL },
1268 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1269 			XARP_CMD, ip_sioctl_arp, 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 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1296 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1297 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1298 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1299 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1300 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1301 			MSFILT_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 		}
1755 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1756 		break;
1757 	case ICMP_ADDRESS_MASK_REPLY:
1758 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1759 		break;
1760 	default:
1761 		interested = B_TRUE;	/* Pass up to transport */
1762 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1763 		break;
1764 	}
1765 	/* See if there is an ICMP client. */
1766 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1767 		/* If there is an ICMP client and we want one too, copy it. */
1768 		mblk_t *first_mp1;
1769 
1770 		if (!interested) {
1771 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1772 			    ip_policy, recv_ill, zoneid);
1773 			return;
1774 		}
1775 		first_mp1 = ip_copymsg(first_mp);
1776 		if (first_mp1 != NULL) {
1777 			ip_fanout_proto(q, first_mp1, ill, ipha,
1778 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1779 		}
1780 	} else if (!interested) {
1781 		freemsg(first_mp);
1782 		return;
1783 	} else {
1784 		/*
1785 		 * Initiate policy processing for this packet if ip_policy
1786 		 * is true.
1787 		 */
1788 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1789 			ill_index = ill->ill_phyint->phyint_ifindex;
1790 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1791 			if (mp == NULL) {
1792 				if (mctl_present) {
1793 					freeb(first_mp);
1794 				}
1795 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1796 				return;
1797 			}
1798 		}
1799 	}
1800 	/* We want to do something with it. */
1801 	/* Check db_ref to make sure we can modify the packet. */
1802 	if (mp->b_datap->db_ref > 1) {
1803 		mblk_t	*first_mp1;
1804 
1805 		first_mp1 = ip_copymsg(first_mp);
1806 		freemsg(first_mp);
1807 		if (!first_mp1) {
1808 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1809 			return;
1810 		}
1811 		first_mp = first_mp1;
1812 		if (mctl_present) {
1813 			mp = first_mp->b_cont;
1814 			ASSERT(mp != NULL);
1815 		} else {
1816 			mp = first_mp;
1817 		}
1818 		ipha = (ipha_t *)mp->b_rptr;
1819 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1820 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1821 	}
1822 	switch (icmph->icmph_type) {
1823 	case ICMP_ADDRESS_MASK_REQUEST:
1824 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1825 		if (ipif == NULL) {
1826 			freemsg(first_mp);
1827 			return;
1828 		}
1829 		/*
1830 		 * outging interface must be IPv4
1831 		 */
1832 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1833 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1834 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1835 		ipif_refrele(ipif);
1836 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1837 		break;
1838 	case ICMP_ECHO_REQUEST:
1839 		icmph->icmph_type = ICMP_ECHO_REPLY;
1840 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1841 		break;
1842 	case ICMP_TIME_STAMP_REQUEST: {
1843 		uint32_t *tsp;
1844 
1845 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1846 		tsp = (uint32_t *)wptr;
1847 		tsp++;		/* Skip past 'originate time' */
1848 		/* Compute # of milliseconds since midnight */
1849 		gethrestime(&now);
1850 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1851 		    now.tv_nsec / (NANOSEC / MILLISEC);
1852 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1853 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1854 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1855 		break;
1856 	}
1857 	default:
1858 		ipha = (ipha_t *)&icmph[1];
1859 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1860 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1861 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1862 				freemsg(first_mp);
1863 				return;
1864 			}
1865 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1866 			ipha = (ipha_t *)&icmph[1];
1867 		}
1868 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1869 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1870 			freemsg(first_mp);
1871 			return;
1872 		}
1873 		hdr_length = IPH_HDR_LENGTH(ipha);
1874 		if (hdr_length < sizeof (ipha_t)) {
1875 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1876 			freemsg(first_mp);
1877 			return;
1878 		}
1879 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1880 			if (!pullupmsg(mp,
1881 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1882 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1883 				freemsg(first_mp);
1884 				return;
1885 			}
1886 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1887 			ipha = (ipha_t *)&icmph[1];
1888 		}
1889 		switch (icmph->icmph_type) {
1890 		case ICMP_REDIRECT:
1891 			/*
1892 			 * As there is no upper client to deliver, we don't
1893 			 * need the first_mp any more.
1894 			 */
1895 			if (mctl_present) {
1896 				freeb(first_mp);
1897 			}
1898 			icmp_redirect(ill, mp);
1899 			return;
1900 		case ICMP_DEST_UNREACHABLE:
1901 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1902 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1903 				    zoneid, mp, iph_hdr_length, ipst)) {
1904 					freemsg(first_mp);
1905 					return;
1906 				}
1907 				/*
1908 				 * icmp_inbound_too_big() may alter mp.
1909 				 * Resynch ipha and icmph accordingly.
1910 				 */
1911 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1912 				ipha = (ipha_t *)&icmph[1];
1913 			}
1914 			/* FALLTHRU */
1915 		default :
1916 			/*
1917 			 * IPQoS notes: Since we have already done IPQoS
1918 			 * processing we don't want to do it again in
1919 			 * the fanout routines called by
1920 			 * icmp_inbound_error_fanout, hence the last
1921 			 * argument, ip_policy, is B_FALSE.
1922 			 */
1923 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1924 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1925 			    B_FALSE, recv_ill, zoneid);
1926 		}
1927 		return;
1928 	}
1929 	/* Send out an ICMP packet */
1930 	icmph->icmph_checksum = 0;
1931 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1932 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1933 		ipif_t	*ipif_chosen;
1934 		/*
1935 		 * Make it look like it was directed to us, so we don't look
1936 		 * like a fool with a broadcast or multicast source address.
1937 		 */
1938 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1939 		/*
1940 		 * Make sure that we haven't grabbed an interface that's DOWN.
1941 		 */
1942 		if (ipif != NULL) {
1943 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1944 			    ipha->ipha_src, zoneid);
1945 			if (ipif_chosen != NULL) {
1946 				ipif_refrele(ipif);
1947 				ipif = ipif_chosen;
1948 			}
1949 		}
1950 		if (ipif == NULL) {
1951 			ip0dbg(("icmp_inbound: "
1952 			    "No source for broadcast/multicast:\n"
1953 			    "\tsrc 0x%x dst 0x%x ill %p "
1954 			    "ipif_lcl_addr 0x%x\n",
1955 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1956 			    (void *)ill,
1957 			    ill->ill_ipif->ipif_lcl_addr));
1958 			freemsg(first_mp);
1959 			return;
1960 		}
1961 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1962 		ipha->ipha_dst = ipif->ipif_src_addr;
1963 		ipif_refrele(ipif);
1964 	}
1965 	/* Reset time to live. */
1966 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1967 	{
1968 		/* Swap source and destination addresses */
1969 		ipaddr_t tmp;
1970 
1971 		tmp = ipha->ipha_src;
1972 		ipha->ipha_src = ipha->ipha_dst;
1973 		ipha->ipha_dst = tmp;
1974 	}
1975 	ipha->ipha_ident = 0;
1976 	if (!IS_SIMPLE_IPH(ipha))
1977 		icmp_options_update(ipha);
1978 
1979 	/*
1980 	 * ICMP echo replies should go out on the same interface
1981 	 * the request came on as probes used by in.mpathd for detecting
1982 	 * NIC failures are ECHO packets. We turn-off load spreading
1983 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1984 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1985 	 * function. This is in turn handled by ip_wput and ip_newroute
1986 	 * to make sure that the packet goes out on the interface it came
1987 	 * in on. If we don't turnoff load spreading, the packets might get
1988 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1989 	 * to go out and in.mpathd would wrongly detect a failure or
1990 	 * mis-detect a NIC failure for link failure. As load spreading
1991 	 * can happen only if ill_group is not NULL, we do only for
1992 	 * that case and this does not affect the normal case.
1993 	 *
1994 	 * We turn off load spreading only on echo packets that came from
1995 	 * on-link hosts. If the interface route has been deleted, this will
1996 	 * not be enforced as we can't do much. For off-link hosts, as the
1997 	 * default routes in IPv4 does not typically have an ire_ipif
1998 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
1999 	 * Moreover, expecting a default route through this interface may
2000 	 * not be correct. We use ipha_dst because of the swap above.
2001 	 */
2002 	onlink = B_FALSE;
2003 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2004 		/*
2005 		 * First, we need to make sure that it is not one of our
2006 		 * local addresses. If we set onlink when it is one of
2007 		 * our local addresses, we will end up creating IRE_CACHES
2008 		 * for one of our local addresses. Then, we will never
2009 		 * accept packets for them afterwards.
2010 		 */
2011 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2012 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2013 		if (src_ire == NULL) {
2014 			ipif = ipif_get_next_ipif(NULL, ill);
2015 			if (ipif == NULL) {
2016 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2017 				freemsg(mp);
2018 				return;
2019 			}
2020 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2021 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2022 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2023 			ipif_refrele(ipif);
2024 			if (src_ire != NULL) {
2025 				onlink = B_TRUE;
2026 				ire_refrele(src_ire);
2027 			}
2028 		} else {
2029 			ire_refrele(src_ire);
2030 		}
2031 	}
2032 	if (!mctl_present) {
2033 		/*
2034 		 * This packet should go out the same way as it
2035 		 * came in i.e in clear. To make sure that global
2036 		 * policy will not be applied to this in ip_wput_ire,
2037 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2038 		 */
2039 		ASSERT(first_mp == mp);
2040 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2041 		if (first_mp == NULL) {
2042 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2043 			freemsg(mp);
2044 			return;
2045 		}
2046 		ii = (ipsec_in_t *)first_mp->b_rptr;
2047 
2048 		/* This is not a secure packet */
2049 		ii->ipsec_in_secure = B_FALSE;
2050 		if (onlink) {
2051 			ii->ipsec_in_attach_if = B_TRUE;
2052 			ii->ipsec_in_ill_index =
2053 			    ill->ill_phyint->phyint_ifindex;
2054 			ii->ipsec_in_rill_index =
2055 			    recv_ill->ill_phyint->phyint_ifindex;
2056 		}
2057 		first_mp->b_cont = mp;
2058 	} else if (onlink) {
2059 		ii = (ipsec_in_t *)first_mp->b_rptr;
2060 		ii->ipsec_in_attach_if = B_TRUE;
2061 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2062 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2063 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2064 	} else {
2065 		ii = (ipsec_in_t *)first_mp->b_rptr;
2066 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2067 	}
2068 	ii->ipsec_in_zoneid = zoneid;
2069 	ASSERT(zoneid != ALL_ZONES);
2070 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2071 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2072 		return;
2073 	}
2074 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2075 	put(WR(q), first_mp);
2076 }
2077 
2078 static ipaddr_t
2079 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2080 {
2081 	conn_t *connp;
2082 	connf_t *connfp;
2083 	ipaddr_t nexthop_addr = INADDR_ANY;
2084 	int hdr_length = IPH_HDR_LENGTH(ipha);
2085 	uint16_t *up;
2086 	uint32_t ports;
2087 	ip_stack_t *ipst = ill->ill_ipst;
2088 
2089 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2090 	switch (ipha->ipha_protocol) {
2091 		case IPPROTO_TCP:
2092 		{
2093 			tcph_t *tcph;
2094 
2095 			/* do a reverse lookup */
2096 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2097 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2098 			    TCPS_LISTEN, ipst);
2099 			break;
2100 		}
2101 		case IPPROTO_UDP:
2102 		{
2103 			uint32_t dstport, srcport;
2104 
2105 			((uint16_t *)&ports)[0] = up[1];
2106 			((uint16_t *)&ports)[1] = up[0];
2107 
2108 			/* Extract ports in net byte order */
2109 			dstport = htons(ntohl(ports) & 0xFFFF);
2110 			srcport = htons(ntohl(ports) >> 16);
2111 
2112 			connfp = &ipst->ips_ipcl_udp_fanout[
2113 			    IPCL_UDP_HASH(dstport, ipst)];
2114 			mutex_enter(&connfp->connf_lock);
2115 			connp = connfp->connf_head;
2116 
2117 			/* do a reverse lookup */
2118 			while ((connp != NULL) &&
2119 			    (!IPCL_UDP_MATCH(connp, dstport,
2120 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2121 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2122 				connp = connp->conn_next;
2123 			}
2124 			if (connp != NULL)
2125 				CONN_INC_REF(connp);
2126 			mutex_exit(&connfp->connf_lock);
2127 			break;
2128 		}
2129 		case IPPROTO_SCTP:
2130 		{
2131 			in6_addr_t map_src, map_dst;
2132 
2133 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2134 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2135 			((uint16_t *)&ports)[0] = up[1];
2136 			((uint16_t *)&ports)[1] = up[0];
2137 
2138 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2139 			    zoneid, ipst->ips_netstack->netstack_sctp);
2140 			if (connp == NULL) {
2141 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2142 				    zoneid, ports, ipha, ipst);
2143 			} else {
2144 				CONN_INC_REF(connp);
2145 				SCTP_REFRELE(CONN2SCTP(connp));
2146 			}
2147 			break;
2148 		}
2149 		default:
2150 		{
2151 			ipha_t ripha;
2152 
2153 			ripha.ipha_src = ipha->ipha_dst;
2154 			ripha.ipha_dst = ipha->ipha_src;
2155 			ripha.ipha_protocol = ipha->ipha_protocol;
2156 
2157 			connfp = &ipst->ips_ipcl_proto_fanout[
2158 			    ipha->ipha_protocol];
2159 			mutex_enter(&connfp->connf_lock);
2160 			connp = connfp->connf_head;
2161 			for (connp = connfp->connf_head; connp != NULL;
2162 			    connp = connp->conn_next) {
2163 				if (IPCL_PROTO_MATCH(connp,
2164 				    ipha->ipha_protocol, &ripha, ill,
2165 				    0, zoneid)) {
2166 					CONN_INC_REF(connp);
2167 					break;
2168 				}
2169 			}
2170 			mutex_exit(&connfp->connf_lock);
2171 		}
2172 	}
2173 	if (connp != NULL) {
2174 		if (connp->conn_nexthop_set)
2175 			nexthop_addr = connp->conn_nexthop_v4;
2176 		CONN_DEC_REF(connp);
2177 	}
2178 	return (nexthop_addr);
2179 }
2180 
2181 /* Table from RFC 1191 */
2182 static int icmp_frag_size_table[] =
2183 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2184 
2185 /*
2186  * Process received ICMP Packet too big.
2187  * After updating any IRE it does the fanout to any matching transport streams.
2188  * Assumes the message has been pulled up till the IP header that caused
2189  * the error.
2190  *
2191  * Returns B_FALSE on failure and B_TRUE on success.
2192  */
2193 static boolean_t
2194 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2195     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2196     ip_stack_t *ipst)
2197 {
2198 	ire_t	*ire, *first_ire;
2199 	int	mtu;
2200 	int	hdr_length;
2201 	ipaddr_t nexthop_addr;
2202 
2203 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2204 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2205 	ASSERT(ill != NULL);
2206 
2207 	hdr_length = IPH_HDR_LENGTH(ipha);
2208 
2209 	/* Drop if the original packet contained a source route */
2210 	if (ip_source_route_included(ipha)) {
2211 		return (B_FALSE);
2212 	}
2213 	/*
2214 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2215 	 * header.
2216 	 */
2217 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2218 	    mp->b_wptr) {
2219 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2220 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2221 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2222 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2223 			return (B_FALSE);
2224 		}
2225 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2226 		ipha = (ipha_t *)&icmph[1];
2227 	}
2228 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2229 	if (nexthop_addr != INADDR_ANY) {
2230 		/* nexthop set */
2231 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2232 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2233 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2234 	} else {
2235 		/* nexthop not set */
2236 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2237 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2238 	}
2239 
2240 	if (!first_ire) {
2241 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2242 		    ntohl(ipha->ipha_dst)));
2243 		return (B_FALSE);
2244 	}
2245 	/* Check for MTU discovery advice as described in RFC 1191 */
2246 	mtu = ntohs(icmph->icmph_du_mtu);
2247 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2248 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2249 	    ire = ire->ire_next) {
2250 		/*
2251 		 * Look for the connection to which this ICMP message is
2252 		 * directed. If it has the IP_NEXTHOP option set, then the
2253 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2254 		 * option. Else the search is limited to regular IREs.
2255 		 */
2256 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2257 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2258 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2259 		    (nexthop_addr != INADDR_ANY)))
2260 			continue;
2261 
2262 		mutex_enter(&ire->ire_lock);
2263 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2264 			/* Reduce the IRE max frag value as advised. */
2265 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2266 			    mtu, ire->ire_max_frag));
2267 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2268 		} else {
2269 			uint32_t length;
2270 			int	i;
2271 
2272 			/*
2273 			 * Use the table from RFC 1191 to figure out
2274 			 * the next "plateau" based on the length in
2275 			 * the original IP packet.
2276 			 */
2277 			length = ntohs(ipha->ipha_length);
2278 			if (ire->ire_max_frag <= length &&
2279 			    ire->ire_max_frag >= length - hdr_length) {
2280 				/*
2281 				 * Handle broken BSD 4.2 systems that
2282 				 * return the wrong iph_length in ICMP
2283 				 * errors.
2284 				 */
2285 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2286 				    length, ire->ire_max_frag));
2287 				length -= hdr_length;
2288 			}
2289 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2290 				if (length > icmp_frag_size_table[i])
2291 					break;
2292 			}
2293 			if (i == A_CNT(icmp_frag_size_table)) {
2294 				/* Smaller than 68! */
2295 				ip1dbg(("Too big for packet size %d\n",
2296 				    length));
2297 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2298 				ire->ire_frag_flag = 0;
2299 			} else {
2300 				mtu = icmp_frag_size_table[i];
2301 				ip1dbg(("Calculated mtu %d, packet size %d, "
2302 				    "before %d", mtu, length,
2303 				    ire->ire_max_frag));
2304 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2305 				ip1dbg((", after %d\n", ire->ire_max_frag));
2306 			}
2307 			/* Record the new max frag size for the ULP. */
2308 			icmph->icmph_du_zero = 0;
2309 			icmph->icmph_du_mtu =
2310 			    htons((uint16_t)ire->ire_max_frag);
2311 		}
2312 		mutex_exit(&ire->ire_lock);
2313 	}
2314 	rw_exit(&first_ire->ire_bucket->irb_lock);
2315 	ire_refrele(first_ire);
2316 	return (B_TRUE);
2317 }
2318 
2319 /*
2320  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2321  * calls this function.
2322  */
2323 static mblk_t *
2324 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2325 {
2326 	ipha_t *ipha;
2327 	icmph_t *icmph;
2328 	ipha_t *in_ipha;
2329 	int length;
2330 
2331 	ASSERT(mp->b_datap->db_type == M_DATA);
2332 
2333 	/*
2334 	 * For Self-encapsulated packets, we added an extra IP header
2335 	 * without the options. Inner IP header is the one from which
2336 	 * the outer IP header was formed. Thus, we need to remove the
2337 	 * outer IP header. To do this, we pullup the whole message
2338 	 * and overlay whatever follows the outer IP header over the
2339 	 * outer IP header.
2340 	 */
2341 
2342 	if (!pullupmsg(mp, -1))
2343 		return (NULL);
2344 
2345 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2346 	ipha = (ipha_t *)&icmph[1];
2347 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2348 
2349 	/*
2350 	 * The length that we want to overlay is following the inner
2351 	 * IP header. Subtracting the IP header + icmp header + outer
2352 	 * IP header's length should give us the length that we want to
2353 	 * overlay.
2354 	 */
2355 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2356 	    hdr_length;
2357 	/*
2358 	 * Overlay whatever follows the inner header over the
2359 	 * outer header.
2360 	 */
2361 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2362 
2363 	/* Set the wptr to account for the outer header */
2364 	mp->b_wptr -= hdr_length;
2365 	return (mp);
2366 }
2367 
2368 /*
2369  * Try to pass the ICMP message upstream in case the ULP cares.
2370  *
2371  * If the packet that caused the ICMP error is secure, we send
2372  * it to AH/ESP to make sure that the attached packet has a
2373  * valid association. ipha in the code below points to the
2374  * IP header of the packet that caused the error.
2375  *
2376  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2377  * in the context of IPsec. Normally we tell the upper layer
2378  * whenever we send the ire (including ip_bind), the IPsec header
2379  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2380  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2381  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2382  * same thing. As TCP has the IPsec options size that needs to be
2383  * adjusted, we just pass the MTU unchanged.
2384  *
2385  * IFN could have been generated locally or by some router.
2386  *
2387  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2388  *	    This happens because IP adjusted its value of MTU on an
2389  *	    earlier IFN message and could not tell the upper layer,
2390  *	    the new adjusted value of MTU e.g. Packet was encrypted
2391  *	    or there was not enough information to fanout to upper
2392  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2393  *	    generates the IFN, where IPsec processing has *not* been
2394  *	    done.
2395  *
2396  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2397  *	    could have generated this. This happens because ire_max_frag
2398  *	    value in IP was set to a new value, while the IPsec processing
2399  *	    was being done and after we made the fragmentation check in
2400  *	    ip_wput_ire. Thus on return from IPsec processing,
2401  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2402  *	    and generates the IFN. As IPsec processing is over, we fanout
2403  *	    to AH/ESP to remove the header.
2404  *
2405  *	    In both these cases, ipsec_in_loopback will be set indicating
2406  *	    that IFN was generated locally.
2407  *
2408  * ROUTER : IFN could be secure or non-secure.
2409  *
2410  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2411  *	      packet in error has AH/ESP headers to validate the AH/ESP
2412  *	      headers. AH/ESP will verify whether there is a valid SA or
2413  *	      not and send it back. We will fanout again if we have more
2414  *	      data in the packet.
2415  *
2416  *	      If the packet in error does not have AH/ESP, we handle it
2417  *	      like any other case.
2418  *
2419  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2420  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2421  *	      for validation. AH/ESP will verify whether there is a
2422  *	      valid SA or not and send it back. We will fanout again if
2423  *	      we have more data in the packet.
2424  *
2425  *	      If the packet in error does not have AH/ESP, we handle it
2426  *	      like any other case.
2427  */
2428 static void
2429 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2430     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2431     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2432     zoneid_t zoneid)
2433 {
2434 	uint16_t *up;	/* Pointer to ports in ULP header */
2435 	uint32_t ports;	/* reversed ports for fanout */
2436 	ipha_t ripha;	/* With reversed addresses */
2437 	mblk_t *first_mp;
2438 	ipsec_in_t *ii;
2439 	tcph_t	*tcph;
2440 	conn_t	*connp;
2441 	ip_stack_t *ipst;
2442 
2443 	ASSERT(ill != NULL);
2444 
2445 	ASSERT(recv_ill != NULL);
2446 	ipst = recv_ill->ill_ipst;
2447 
2448 	first_mp = mp;
2449 	if (mctl_present) {
2450 		mp = first_mp->b_cont;
2451 		ASSERT(mp != NULL);
2452 
2453 		ii = (ipsec_in_t *)first_mp->b_rptr;
2454 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2455 	} else {
2456 		ii = NULL;
2457 	}
2458 
2459 	switch (ipha->ipha_protocol) {
2460 	case IPPROTO_UDP:
2461 		/*
2462 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2463 		 * transport header.
2464 		 */
2465 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2466 		    mp->b_wptr) {
2467 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2468 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2469 				goto discard_pkt;
2470 			}
2471 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2472 			ipha = (ipha_t *)&icmph[1];
2473 		}
2474 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2475 
2476 		/*
2477 		 * Attempt to find a client stream based on port.
2478 		 * Note that we do a reverse lookup since the header is
2479 		 * in the form we sent it out.
2480 		 * The ripha header is only used for the IP_UDP_MATCH and we
2481 		 * only set the src and dst addresses and protocol.
2482 		 */
2483 		ripha.ipha_src = ipha->ipha_dst;
2484 		ripha.ipha_dst = ipha->ipha_src;
2485 		ripha.ipha_protocol = ipha->ipha_protocol;
2486 		((uint16_t *)&ports)[0] = up[1];
2487 		((uint16_t *)&ports)[1] = up[0];
2488 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2489 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2490 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2491 		    icmph->icmph_type, icmph->icmph_code));
2492 
2493 		/* Have to change db_type after any pullupmsg */
2494 		DB_TYPE(mp) = M_CTL;
2495 
2496 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2497 		    mctl_present, ip_policy, recv_ill, zoneid);
2498 		return;
2499 
2500 	case IPPROTO_TCP:
2501 		/*
2502 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2503 		 * transport header.
2504 		 */
2505 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2506 		    mp->b_wptr) {
2507 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2508 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2509 				goto discard_pkt;
2510 			}
2511 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2512 			ipha = (ipha_t *)&icmph[1];
2513 		}
2514 		/*
2515 		 * Find a TCP client stream for this packet.
2516 		 * Note that we do a reverse lookup since the header is
2517 		 * in the form we sent it out.
2518 		 */
2519 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2520 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2521 		    ipst);
2522 		if (connp == NULL)
2523 			goto discard_pkt;
2524 
2525 		/* Have to change db_type after any pullupmsg */
2526 		DB_TYPE(mp) = M_CTL;
2527 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2528 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2529 		return;
2530 
2531 	case IPPROTO_SCTP:
2532 		/*
2533 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2534 		 * transport header.
2535 		 */
2536 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2537 		    mp->b_wptr) {
2538 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2539 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2540 				goto discard_pkt;
2541 			}
2542 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2543 			ipha = (ipha_t *)&icmph[1];
2544 		}
2545 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2546 		/*
2547 		 * Find a SCTP client stream for this packet.
2548 		 * Note that we do a reverse lookup since the header is
2549 		 * in the form we sent it out.
2550 		 * The ripha header is only used for the matching and we
2551 		 * only set the src and dst addresses, protocol, and version.
2552 		 */
2553 		ripha.ipha_src = ipha->ipha_dst;
2554 		ripha.ipha_dst = ipha->ipha_src;
2555 		ripha.ipha_protocol = ipha->ipha_protocol;
2556 		ripha.ipha_version_and_hdr_length =
2557 		    ipha->ipha_version_and_hdr_length;
2558 		((uint16_t *)&ports)[0] = up[1];
2559 		((uint16_t *)&ports)[1] = up[0];
2560 
2561 		/* Have to change db_type after any pullupmsg */
2562 		DB_TYPE(mp) = M_CTL;
2563 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2564 		    mctl_present, ip_policy, zoneid);
2565 		return;
2566 
2567 	case IPPROTO_ESP:
2568 	case IPPROTO_AH: {
2569 		int ipsec_rc;
2570 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2571 
2572 		/*
2573 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2574 		 * We will re-use the IPSEC_IN if it is already present as
2575 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2576 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2577 		 * one and attach it in the front.
2578 		 */
2579 		if (ii != NULL) {
2580 			/*
2581 			 * ip_fanout_proto_again converts the ICMP errors
2582 			 * that come back from AH/ESP to M_DATA so that
2583 			 * if it is non-AH/ESP and we do a pullupmsg in
2584 			 * this function, it would work. Convert it back
2585 			 * to M_CTL before we send up as this is a ICMP
2586 			 * error. This could have been generated locally or
2587 			 * by some router. Validate the inner IPsec
2588 			 * headers.
2589 			 *
2590 			 * NOTE : ill_index is used by ip_fanout_proto_again
2591 			 * to locate the ill.
2592 			 */
2593 			ASSERT(ill != NULL);
2594 			ii->ipsec_in_ill_index =
2595 			    ill->ill_phyint->phyint_ifindex;
2596 			ii->ipsec_in_rill_index =
2597 			    recv_ill->ill_phyint->phyint_ifindex;
2598 			DB_TYPE(first_mp->b_cont) = M_CTL;
2599 		} else {
2600 			/*
2601 			 * IPSEC_IN is not present. We attach a ipsec_in
2602 			 * message and send up to IPsec for validating
2603 			 * and removing the IPsec headers. Clear
2604 			 * ipsec_in_secure so that when we return
2605 			 * from IPsec, we don't mistakenly think that this
2606 			 * is a secure packet came from the network.
2607 			 *
2608 			 * NOTE : ill_index is used by ip_fanout_proto_again
2609 			 * to locate the ill.
2610 			 */
2611 			ASSERT(first_mp == mp);
2612 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2613 			if (first_mp == NULL) {
2614 				freemsg(mp);
2615 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2616 				return;
2617 			}
2618 			ii = (ipsec_in_t *)first_mp->b_rptr;
2619 
2620 			/* This is not a secure packet */
2621 			ii->ipsec_in_secure = B_FALSE;
2622 			first_mp->b_cont = mp;
2623 			DB_TYPE(mp) = M_CTL;
2624 			ASSERT(ill != NULL);
2625 			ii->ipsec_in_ill_index =
2626 			    ill->ill_phyint->phyint_ifindex;
2627 			ii->ipsec_in_rill_index =
2628 			    recv_ill->ill_phyint->phyint_ifindex;
2629 		}
2630 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2631 
2632 		if (!ipsec_loaded(ipss)) {
2633 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2634 			return;
2635 		}
2636 
2637 		if (ipha->ipha_protocol == IPPROTO_ESP)
2638 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2639 		else
2640 			ipsec_rc = ipsecah_icmp_error(first_mp);
2641 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2642 			return;
2643 
2644 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2645 		return;
2646 	}
2647 	default:
2648 		/*
2649 		 * The ripha header is only used for the lookup and we
2650 		 * only set the src and dst addresses and protocol.
2651 		 */
2652 		ripha.ipha_src = ipha->ipha_dst;
2653 		ripha.ipha_dst = ipha->ipha_src;
2654 		ripha.ipha_protocol = ipha->ipha_protocol;
2655 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2656 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2657 		    ntohl(ipha->ipha_dst),
2658 		    icmph->icmph_type, icmph->icmph_code));
2659 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2660 			ipha_t *in_ipha;
2661 
2662 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2663 			    mp->b_wptr) {
2664 				if (!pullupmsg(mp, (uchar_t *)ipha +
2665 				    hdr_length + sizeof (ipha_t) -
2666 				    mp->b_rptr)) {
2667 					goto discard_pkt;
2668 				}
2669 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2670 				ipha = (ipha_t *)&icmph[1];
2671 			}
2672 			/*
2673 			 * Caller has verified that length has to be
2674 			 * at least the size of IP header.
2675 			 */
2676 			ASSERT(hdr_length >= sizeof (ipha_t));
2677 			/*
2678 			 * Check the sanity of the inner IP header like
2679 			 * we did for the outer header.
2680 			 */
2681 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2682 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2683 				goto discard_pkt;
2684 			}
2685 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2686 				goto discard_pkt;
2687 			}
2688 			/* Check for Self-encapsulated tunnels */
2689 			if (in_ipha->ipha_src == ipha->ipha_src &&
2690 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2691 
2692 				mp = icmp_inbound_self_encap_error(mp,
2693 				    iph_hdr_length, hdr_length);
2694 				if (mp == NULL)
2695 					goto discard_pkt;
2696 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2697 				ipha = (ipha_t *)&icmph[1];
2698 				hdr_length = IPH_HDR_LENGTH(ipha);
2699 				/*
2700 				 * The packet in error is self-encapsualted.
2701 				 * And we are finding it further encapsulated
2702 				 * which we could not have possibly generated.
2703 				 */
2704 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2705 					goto discard_pkt;
2706 				}
2707 				icmp_inbound_error_fanout(q, ill, first_mp,
2708 				    icmph, ipha, iph_hdr_length, hdr_length,
2709 				    mctl_present, ip_policy, recv_ill, zoneid);
2710 				return;
2711 			}
2712 		}
2713 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2714 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2715 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2716 		    ii != NULL &&
2717 		    ii->ipsec_in_loopback &&
2718 		    ii->ipsec_in_secure) {
2719 			/*
2720 			 * For IP tunnels that get a looped-back
2721 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2722 			 * reported new MTU to take into account the IPsec
2723 			 * headers protecting this configured tunnel.
2724 			 *
2725 			 * This allows the tunnel module (tun.c) to blindly
2726 			 * accept the MTU reported in an ICMP "too big"
2727 			 * message.
2728 			 *
2729 			 * Non-looped back ICMP messages will just be
2730 			 * handled by the security protocols (if needed),
2731 			 * and the first subsequent packet will hit this
2732 			 * path.
2733 			 */
2734 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2735 			    ipsec_in_extra_length(first_mp));
2736 		}
2737 		/* Have to change db_type after any pullupmsg */
2738 		DB_TYPE(mp) = M_CTL;
2739 
2740 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2741 		    ip_policy, recv_ill, zoneid);
2742 		return;
2743 	}
2744 	/* NOTREACHED */
2745 discard_pkt:
2746 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2747 drop_pkt:;
2748 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2749 	freemsg(first_mp);
2750 }
2751 
2752 /*
2753  * Common IP options parser.
2754  *
2755  * Setup routine: fill in *optp with options-parsing state, then
2756  * tail-call ipoptp_next to return the first option.
2757  */
2758 uint8_t
2759 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2760 {
2761 	uint32_t totallen; /* total length of all options */
2762 
2763 	totallen = ipha->ipha_version_and_hdr_length -
2764 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2765 	totallen <<= 2;
2766 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2767 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2768 	optp->ipoptp_flags = 0;
2769 	return (ipoptp_next(optp));
2770 }
2771 
2772 /*
2773  * Common IP options parser: extract next option.
2774  */
2775 uint8_t
2776 ipoptp_next(ipoptp_t *optp)
2777 {
2778 	uint8_t *end = optp->ipoptp_end;
2779 	uint8_t *cur = optp->ipoptp_next;
2780 	uint8_t opt, len, pointer;
2781 
2782 	/*
2783 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2784 	 * has been corrupted.
2785 	 */
2786 	ASSERT(cur <= end);
2787 
2788 	if (cur == end)
2789 		return (IPOPT_EOL);
2790 
2791 	opt = cur[IPOPT_OPTVAL];
2792 
2793 	/*
2794 	 * Skip any NOP options.
2795 	 */
2796 	while (opt == IPOPT_NOP) {
2797 		cur++;
2798 		if (cur == end)
2799 			return (IPOPT_EOL);
2800 		opt = cur[IPOPT_OPTVAL];
2801 	}
2802 
2803 	if (opt == IPOPT_EOL)
2804 		return (IPOPT_EOL);
2805 
2806 	/*
2807 	 * Option requiring a length.
2808 	 */
2809 	if ((cur + 1) >= end) {
2810 		optp->ipoptp_flags |= IPOPTP_ERROR;
2811 		return (IPOPT_EOL);
2812 	}
2813 	len = cur[IPOPT_OLEN];
2814 	if (len < 2) {
2815 		optp->ipoptp_flags |= IPOPTP_ERROR;
2816 		return (IPOPT_EOL);
2817 	}
2818 	optp->ipoptp_cur = cur;
2819 	optp->ipoptp_len = len;
2820 	optp->ipoptp_next = cur + len;
2821 	if (cur + len > end) {
2822 		optp->ipoptp_flags |= IPOPTP_ERROR;
2823 		return (IPOPT_EOL);
2824 	}
2825 
2826 	/*
2827 	 * For the options which require a pointer field, make sure
2828 	 * its there, and make sure it points to either something
2829 	 * inside this option, or the end of the option.
2830 	 */
2831 	switch (opt) {
2832 	case IPOPT_RR:
2833 	case IPOPT_TS:
2834 	case IPOPT_LSRR:
2835 	case IPOPT_SSRR:
2836 		if (len <= IPOPT_OFFSET) {
2837 			optp->ipoptp_flags |= IPOPTP_ERROR;
2838 			return (opt);
2839 		}
2840 		pointer = cur[IPOPT_OFFSET];
2841 		if (pointer - 1 > len) {
2842 			optp->ipoptp_flags |= IPOPTP_ERROR;
2843 			return (opt);
2844 		}
2845 		break;
2846 	}
2847 
2848 	/*
2849 	 * Sanity check the pointer field based on the type of the
2850 	 * option.
2851 	 */
2852 	switch (opt) {
2853 	case IPOPT_RR:
2854 	case IPOPT_SSRR:
2855 	case IPOPT_LSRR:
2856 		if (pointer < IPOPT_MINOFF_SR)
2857 			optp->ipoptp_flags |= IPOPTP_ERROR;
2858 		break;
2859 	case IPOPT_TS:
2860 		if (pointer < IPOPT_MINOFF_IT)
2861 			optp->ipoptp_flags |= IPOPTP_ERROR;
2862 		/*
2863 		 * Note that the Internet Timestamp option also
2864 		 * contains two four bit fields (the Overflow field,
2865 		 * and the Flag field), which follow the pointer
2866 		 * field.  We don't need to check that these fields
2867 		 * fall within the length of the option because this
2868 		 * was implicitely done above.  We've checked that the
2869 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2870 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2871 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2872 		 */
2873 		ASSERT(len > IPOPT_POS_OV_FLG);
2874 		break;
2875 	}
2876 
2877 	return (opt);
2878 }
2879 
2880 /*
2881  * Use the outgoing IP header to create an IP_OPTIONS option the way
2882  * it was passed down from the application.
2883  */
2884 int
2885 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2886 {
2887 	ipoptp_t	opts;
2888 	const uchar_t	*opt;
2889 	uint8_t		optval;
2890 	uint8_t		optlen;
2891 	uint32_t	len = 0;
2892 	uchar_t	*buf1 = buf;
2893 
2894 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2895 	len += IP_ADDR_LEN;
2896 	bzero(buf1, IP_ADDR_LEN);
2897 
2898 	/*
2899 	 * OK to cast away const here, as we don't store through the returned
2900 	 * opts.ipoptp_cur pointer.
2901 	 */
2902 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2903 	    optval != IPOPT_EOL;
2904 	    optval = ipoptp_next(&opts)) {
2905 		int	off;
2906 
2907 		opt = opts.ipoptp_cur;
2908 		optlen = opts.ipoptp_len;
2909 		switch (optval) {
2910 		case IPOPT_SSRR:
2911 		case IPOPT_LSRR:
2912 
2913 			/*
2914 			 * Insert ipha_dst as the first entry in the source
2915 			 * route and move down the entries on step.
2916 			 * The last entry gets placed at buf1.
2917 			 */
2918 			buf[IPOPT_OPTVAL] = optval;
2919 			buf[IPOPT_OLEN] = optlen;
2920 			buf[IPOPT_OFFSET] = optlen;
2921 
2922 			off = optlen - IP_ADDR_LEN;
2923 			if (off < 0) {
2924 				/* No entries in source route */
2925 				break;
2926 			}
2927 			/* Last entry in source route */
2928 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2929 			off -= IP_ADDR_LEN;
2930 
2931 			while (off > 0) {
2932 				bcopy(opt + off,
2933 				    buf + off + IP_ADDR_LEN,
2934 				    IP_ADDR_LEN);
2935 				off -= IP_ADDR_LEN;
2936 			}
2937 			/* ipha_dst into first slot */
2938 			bcopy(&ipha->ipha_dst,
2939 			    buf + off + IP_ADDR_LEN,
2940 			    IP_ADDR_LEN);
2941 			buf += optlen;
2942 			len += optlen;
2943 			break;
2944 
2945 		case IPOPT_COMSEC:
2946 		case IPOPT_SECURITY:
2947 			/* if passing up a label is not ok, then remove */
2948 			if (is_system_labeled())
2949 				break;
2950 			/* FALLTHROUGH */
2951 		default:
2952 			bcopy(opt, buf, optlen);
2953 			buf += optlen;
2954 			len += optlen;
2955 			break;
2956 		}
2957 	}
2958 done:
2959 	/* Pad the resulting options */
2960 	while (len & 0x3) {
2961 		*buf++ = IPOPT_EOL;
2962 		len++;
2963 	}
2964 	return (len);
2965 }
2966 
2967 /*
2968  * Update any record route or timestamp options to include this host.
2969  * Reverse any source route option.
2970  * This routine assumes that the options are well formed i.e. that they
2971  * have already been checked.
2972  */
2973 static void
2974 icmp_options_update(ipha_t *ipha)
2975 {
2976 	ipoptp_t	opts;
2977 	uchar_t		*opt;
2978 	uint8_t		optval;
2979 	ipaddr_t	src;		/* Our local address */
2980 	ipaddr_t	dst;
2981 
2982 	ip2dbg(("icmp_options_update\n"));
2983 	src = ipha->ipha_src;
2984 	dst = ipha->ipha_dst;
2985 
2986 	for (optval = ipoptp_first(&opts, ipha);
2987 	    optval != IPOPT_EOL;
2988 	    optval = ipoptp_next(&opts)) {
2989 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2990 		opt = opts.ipoptp_cur;
2991 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2992 		    optval, opts.ipoptp_len));
2993 		switch (optval) {
2994 			int off1, off2;
2995 		case IPOPT_SSRR:
2996 		case IPOPT_LSRR:
2997 			/*
2998 			 * Reverse the source route.  The first entry
2999 			 * should be the next to last one in the current
3000 			 * source route (the last entry is our address).
3001 			 * The last entry should be the final destination.
3002 			 */
3003 			off1 = IPOPT_MINOFF_SR - 1;
3004 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3005 			if (off2 < 0) {
3006 				/* No entries in source route */
3007 				ip1dbg((
3008 				    "icmp_options_update: bad src route\n"));
3009 				break;
3010 			}
3011 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3012 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3013 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3014 			off2 -= IP_ADDR_LEN;
3015 
3016 			while (off1 < off2) {
3017 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3018 				bcopy((char *)opt + off2, (char *)opt + off1,
3019 				    IP_ADDR_LEN);
3020 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3021 				off1 += IP_ADDR_LEN;
3022 				off2 -= IP_ADDR_LEN;
3023 			}
3024 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3025 			break;
3026 		}
3027 	}
3028 }
3029 
3030 /*
3031  * Process received ICMP Redirect messages.
3032  */
3033 static void
3034 icmp_redirect(ill_t *ill, mblk_t *mp)
3035 {
3036 	ipha_t	*ipha;
3037 	int	iph_hdr_length;
3038 	icmph_t	*icmph;
3039 	ipha_t	*ipha_err;
3040 	ire_t	*ire;
3041 	ire_t	*prev_ire;
3042 	ire_t	*save_ire;
3043 	ipaddr_t  src, dst, gateway;
3044 	iulp_t	ulp_info = { 0 };
3045 	int	error;
3046 	ip_stack_t *ipst;
3047 
3048 	ASSERT(ill != NULL);
3049 	ipst = ill->ill_ipst;
3050 
3051 	ipha = (ipha_t *)mp->b_rptr;
3052 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3053 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3054 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3055 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3056 		freemsg(mp);
3057 		return;
3058 	}
3059 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3060 	ipha_err = (ipha_t *)&icmph[1];
3061 	src = ipha->ipha_src;
3062 	dst = ipha_err->ipha_dst;
3063 	gateway = icmph->icmph_rd_gateway;
3064 	/* Make sure the new gateway is reachable somehow. */
3065 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3066 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3067 	/*
3068 	 * Make sure we had a route for the dest in question and that
3069 	 * that route was pointing to the old gateway (the source of the
3070 	 * redirect packet.)
3071 	 */
3072 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3073 	    NULL, MATCH_IRE_GW, ipst);
3074 	/*
3075 	 * Check that
3076 	 *	the redirect was not from ourselves
3077 	 *	the new gateway and the old gateway are directly reachable
3078 	 */
3079 	if (!prev_ire ||
3080 	    !ire ||
3081 	    ire->ire_type == IRE_LOCAL) {
3082 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3083 		freemsg(mp);
3084 		if (ire != NULL)
3085 			ire_refrele(ire);
3086 		if (prev_ire != NULL)
3087 			ire_refrele(prev_ire);
3088 		return;
3089 	}
3090 
3091 	/*
3092 	 * Should we use the old ULP info to create the new gateway?  From
3093 	 * a user's perspective, we should inherit the info so that it
3094 	 * is a "smooth" transition.  If we do not do that, then new
3095 	 * connections going thru the new gateway will have no route metrics,
3096 	 * which is counter-intuitive to user.  From a network point of
3097 	 * view, this may or may not make sense even though the new gateway
3098 	 * is still directly connected to us so the route metrics should not
3099 	 * change much.
3100 	 *
3101 	 * But if the old ire_uinfo is not initialized, we do another
3102 	 * recursive lookup on the dest using the new gateway.  There may
3103 	 * be a route to that.  If so, use it to initialize the redirect
3104 	 * route.
3105 	 */
3106 	if (prev_ire->ire_uinfo.iulp_set) {
3107 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3108 	} else {
3109 		ire_t *tmp_ire;
3110 		ire_t *sire;
3111 
3112 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3113 		    ALL_ZONES, 0, NULL,
3114 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3115 		    ipst);
3116 		if (sire != NULL) {
3117 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3118 			/*
3119 			 * If sire != NULL, ire_ftable_lookup() should not
3120 			 * return a NULL value.
3121 			 */
3122 			ASSERT(tmp_ire != NULL);
3123 			ire_refrele(tmp_ire);
3124 			ire_refrele(sire);
3125 		} else if (tmp_ire != NULL) {
3126 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3127 			    sizeof (iulp_t));
3128 			ire_refrele(tmp_ire);
3129 		}
3130 	}
3131 	if (prev_ire->ire_type == IRE_CACHE)
3132 		ire_delete(prev_ire);
3133 	ire_refrele(prev_ire);
3134 	/*
3135 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3136 	 * require TOS routing
3137 	 */
3138 	switch (icmph->icmph_code) {
3139 	case 0:
3140 	case 1:
3141 		/* TODO: TOS specificity for cases 2 and 3 */
3142 	case 2:
3143 	case 3:
3144 		break;
3145 	default:
3146 		freemsg(mp);
3147 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3148 		ire_refrele(ire);
3149 		return;
3150 	}
3151 	/*
3152 	 * Create a Route Association.  This will allow us to remember that
3153 	 * someone we believe told us to use the particular gateway.
3154 	 */
3155 	save_ire = ire;
3156 	ire = ire_create(
3157 	    (uchar_t *)&dst,			/* dest addr */
3158 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3159 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3160 	    (uchar_t *)&gateway,		/* gateway addr */
3161 	    &save_ire->ire_max_frag,		/* max frag */
3162 	    NULL,				/* no src nce */
3163 	    NULL,				/* no rfq */
3164 	    NULL,				/* no stq */
3165 	    IRE_HOST,
3166 	    NULL,				/* ipif */
3167 	    0,					/* cmask */
3168 	    0,					/* phandle */
3169 	    0,					/* ihandle */
3170 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3171 	    &ulp_info,
3172 	    NULL,				/* tsol_gc_t */
3173 	    NULL,				/* gcgrp */
3174 	    ipst);
3175 
3176 	if (ire == NULL) {
3177 		freemsg(mp);
3178 		ire_refrele(save_ire);
3179 		return;
3180 	}
3181 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3182 	ire_refrele(save_ire);
3183 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3184 
3185 	if (error == 0) {
3186 		ire_refrele(ire);		/* Held in ire_add_v4 */
3187 		/* tell routing sockets that we received a redirect */
3188 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3189 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3190 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3191 	}
3192 
3193 	/*
3194 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3195 	 * This together with the added IRE has the effect of
3196 	 * modifying an existing redirect.
3197 	 */
3198 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3199 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3200 	if (prev_ire != NULL) {
3201 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3202 			ire_delete(prev_ire);
3203 		ire_refrele(prev_ire);
3204 	}
3205 
3206 	freemsg(mp);
3207 }
3208 
3209 /*
3210  * Generate an ICMP parameter problem message.
3211  */
3212 static void
3213 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3214 	ip_stack_t *ipst)
3215 {
3216 	icmph_t	icmph;
3217 	boolean_t mctl_present;
3218 	mblk_t *first_mp;
3219 
3220 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3221 
3222 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3223 		if (mctl_present)
3224 			freeb(first_mp);
3225 		return;
3226 	}
3227 
3228 	bzero(&icmph, sizeof (icmph_t));
3229 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3230 	icmph.icmph_pp_ptr = ptr;
3231 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3232 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3233 	    ipst);
3234 }
3235 
3236 /*
3237  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3238  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3239  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3240  * an icmp error packet can be sent.
3241  * Assigns an appropriate source address to the packet. If ipha_dst is
3242  * one of our addresses use it for source. Otherwise pick a source based
3243  * on a route lookup back to ipha_src.
3244  * Note that ipha_src must be set here since the
3245  * packet is likely to arrive on an ill queue in ip_wput() which will
3246  * not set a source address.
3247  */
3248 static void
3249 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3250     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3251 {
3252 	ipaddr_t dst;
3253 	icmph_t	*icmph;
3254 	ipha_t	*ipha;
3255 	uint_t	len_needed;
3256 	size_t	msg_len;
3257 	mblk_t	*mp1;
3258 	ipaddr_t src;
3259 	ire_t	*ire;
3260 	mblk_t *ipsec_mp;
3261 	ipsec_out_t	*io = NULL;
3262 
3263 	if (mctl_present) {
3264 		/*
3265 		 * If it is :
3266 		 *
3267 		 * 1) a IPSEC_OUT, then this is caused by outbound
3268 		 *    datagram originating on this host. IPsec processing
3269 		 *    may or may not have been done. Refer to comments above
3270 		 *    icmp_inbound_error_fanout for details.
3271 		 *
3272 		 * 2) a IPSEC_IN if we are generating a icmp_message
3273 		 *    for an incoming datagram destined for us i.e called
3274 		 *    from ip_fanout_send_icmp.
3275 		 */
3276 		ipsec_info_t *in;
3277 		ipsec_mp = mp;
3278 		mp = ipsec_mp->b_cont;
3279 
3280 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3281 		ipha = (ipha_t *)mp->b_rptr;
3282 
3283 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3284 		    in->ipsec_info_type == IPSEC_IN);
3285 
3286 		if (in->ipsec_info_type == IPSEC_IN) {
3287 			/*
3288 			 * Convert the IPSEC_IN to IPSEC_OUT.
3289 			 */
3290 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3291 				BUMP_MIB(&ipst->ips_ip_mib,
3292 				    ipIfStatsOutDiscards);
3293 				return;
3294 			}
3295 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3296 		} else {
3297 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3298 			io = (ipsec_out_t *)in;
3299 			/*
3300 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3301 			 * ire lookup.
3302 			 */
3303 			io->ipsec_out_proc_begin = B_FALSE;
3304 		}
3305 		ASSERT(zoneid == io->ipsec_out_zoneid);
3306 		ASSERT(zoneid != ALL_ZONES);
3307 	} else {
3308 		/*
3309 		 * This is in clear. The icmp message we are building
3310 		 * here should go out in clear.
3311 		 *
3312 		 * Pardon the convolution of it all, but it's easier to
3313 		 * allocate a "use cleartext" IPSEC_IN message and convert
3314 		 * it than it is to allocate a new one.
3315 		 */
3316 		ipsec_in_t *ii;
3317 		ASSERT(DB_TYPE(mp) == M_DATA);
3318 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3319 		if (ipsec_mp == NULL) {
3320 			freemsg(mp);
3321 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3322 			return;
3323 		}
3324 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3325 
3326 		/* This is not a secure packet */
3327 		ii->ipsec_in_secure = B_FALSE;
3328 		/*
3329 		 * For trusted extensions using a shared IP address we can
3330 		 * send using any zoneid.
3331 		 */
3332 		if (zoneid == ALL_ZONES)
3333 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3334 		else
3335 			ii->ipsec_in_zoneid = zoneid;
3336 		ipsec_mp->b_cont = mp;
3337 		ipha = (ipha_t *)mp->b_rptr;
3338 		/*
3339 		 * Convert the IPSEC_IN to IPSEC_OUT.
3340 		 */
3341 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3342 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3343 			return;
3344 		}
3345 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3346 	}
3347 
3348 	/* Remember our eventual destination */
3349 	dst = ipha->ipha_src;
3350 
3351 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3352 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3353 	if (ire != NULL &&
3354 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3355 		src = ipha->ipha_dst;
3356 	} else {
3357 		if (ire != NULL)
3358 			ire_refrele(ire);
3359 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3360 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3361 		    ipst);
3362 		if (ire == NULL) {
3363 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3364 			freemsg(ipsec_mp);
3365 			return;
3366 		}
3367 		src = ire->ire_src_addr;
3368 	}
3369 
3370 	if (ire != NULL)
3371 		ire_refrele(ire);
3372 
3373 	/*
3374 	 * Check if we can send back more then 8 bytes in addition to
3375 	 * the IP header.  We try to send 64 bytes of data and the internal
3376 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3377 	 */
3378 	len_needed = IPH_HDR_LENGTH(ipha);
3379 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3380 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3381 
3382 		if (!pullupmsg(mp, -1)) {
3383 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3384 			freemsg(ipsec_mp);
3385 			return;
3386 		}
3387 		ipha = (ipha_t *)mp->b_rptr;
3388 
3389 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3390 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3391 			    len_needed));
3392 		} else {
3393 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3394 
3395 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3396 			len_needed += ip_hdr_length_v6(mp, ip6h);
3397 		}
3398 	}
3399 	len_needed += ipst->ips_ip_icmp_return;
3400 	msg_len = msgdsize(mp);
3401 	if (msg_len > len_needed) {
3402 		(void) adjmsg(mp, len_needed - msg_len);
3403 		msg_len = len_needed;
3404 	}
3405 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3406 	if (mp1 == NULL) {
3407 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3408 		freemsg(ipsec_mp);
3409 		return;
3410 	}
3411 	mp1->b_cont = mp;
3412 	mp = mp1;
3413 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3414 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3415 	    io->ipsec_out_type == IPSEC_OUT);
3416 	ipsec_mp->b_cont = mp;
3417 
3418 	/*
3419 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3420 	 * node generates be accepted in peace by all on-host destinations.
3421 	 * If we do NOT assume that all on-host destinations trust
3422 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3423 	 * (Look for ipsec_out_icmp_loopback).
3424 	 */
3425 	io->ipsec_out_icmp_loopback = B_TRUE;
3426 
3427 	ipha = (ipha_t *)mp->b_rptr;
3428 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3429 	*ipha = icmp_ipha;
3430 	ipha->ipha_src = src;
3431 	ipha->ipha_dst = dst;
3432 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3433 	msg_len += sizeof (icmp_ipha) + len;
3434 	if (msg_len > IP_MAXPACKET) {
3435 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3436 		msg_len = IP_MAXPACKET;
3437 	}
3438 	ipha->ipha_length = htons((uint16_t)msg_len);
3439 	icmph = (icmph_t *)&ipha[1];
3440 	bcopy(stuff, icmph, len);
3441 	icmph->icmph_checksum = 0;
3442 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3443 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3444 	put(q, ipsec_mp);
3445 }
3446 
3447 /*
3448  * Determine if an ICMP error packet can be sent given the rate limit.
3449  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3450  * in milliseconds) and a burst size. Burst size number of packets can
3451  * be sent arbitrarely closely spaced.
3452  * The state is tracked using two variables to implement an approximate
3453  * token bucket filter:
3454  *	icmp_pkt_err_last - lbolt value when the last burst started
3455  *	icmp_pkt_err_sent - number of packets sent in current burst
3456  */
3457 boolean_t
3458 icmp_err_rate_limit(ip_stack_t *ipst)
3459 {
3460 	clock_t now = TICK_TO_MSEC(lbolt);
3461 	uint_t refilled; /* Number of packets refilled in tbf since last */
3462 	/* Guard against changes by loading into local variable */
3463 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3464 
3465 	if (err_interval == 0)
3466 		return (B_FALSE);
3467 
3468 	if (ipst->ips_icmp_pkt_err_last > now) {
3469 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3470 		ipst->ips_icmp_pkt_err_last = 0;
3471 		ipst->ips_icmp_pkt_err_sent = 0;
3472 	}
3473 	/*
3474 	 * If we are in a burst update the token bucket filter.
3475 	 * Update the "last" time to be close to "now" but make sure
3476 	 * we don't loose precision.
3477 	 */
3478 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3479 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3480 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3481 			ipst->ips_icmp_pkt_err_sent = 0;
3482 		} else {
3483 			ipst->ips_icmp_pkt_err_sent -= refilled;
3484 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3485 		}
3486 	}
3487 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3488 		/* Start of new burst */
3489 		ipst->ips_icmp_pkt_err_last = now;
3490 	}
3491 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3492 		ipst->ips_icmp_pkt_err_sent++;
3493 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3494 		    ipst->ips_icmp_pkt_err_sent));
3495 		return (B_FALSE);
3496 	}
3497 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3498 	return (B_TRUE);
3499 }
3500 
3501 /*
3502  * Check if it is ok to send an IPv4 ICMP error packet in
3503  * response to the IPv4 packet in mp.
3504  * Free the message and return null if no
3505  * ICMP error packet should be sent.
3506  */
3507 static mblk_t *
3508 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3509 {
3510 	icmph_t	*icmph;
3511 	ipha_t	*ipha;
3512 	uint_t	len_needed;
3513 	ire_t	*src_ire;
3514 	ire_t	*dst_ire;
3515 
3516 	if (!mp)
3517 		return (NULL);
3518 	ipha = (ipha_t *)mp->b_rptr;
3519 	if (ip_csum_hdr(ipha)) {
3520 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3521 		freemsg(mp);
3522 		return (NULL);
3523 	}
3524 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3525 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3526 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3527 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3528 	if (src_ire != NULL || dst_ire != NULL ||
3529 	    CLASSD(ipha->ipha_dst) ||
3530 	    CLASSD(ipha->ipha_src) ||
3531 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3532 		/* Note: only errors to the fragment with offset 0 */
3533 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3534 		freemsg(mp);
3535 		if (src_ire != NULL)
3536 			ire_refrele(src_ire);
3537 		if (dst_ire != NULL)
3538 			ire_refrele(dst_ire);
3539 		return (NULL);
3540 	}
3541 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3542 		/*
3543 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3544 		 * errors in response to any ICMP errors.
3545 		 */
3546 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3547 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3548 			if (!pullupmsg(mp, len_needed)) {
3549 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3550 				freemsg(mp);
3551 				return (NULL);
3552 			}
3553 			ipha = (ipha_t *)mp->b_rptr;
3554 		}
3555 		icmph = (icmph_t *)
3556 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3557 		switch (icmph->icmph_type) {
3558 		case ICMP_DEST_UNREACHABLE:
3559 		case ICMP_SOURCE_QUENCH:
3560 		case ICMP_TIME_EXCEEDED:
3561 		case ICMP_PARAM_PROBLEM:
3562 		case ICMP_REDIRECT:
3563 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3564 			freemsg(mp);
3565 			return (NULL);
3566 		default:
3567 			break;
3568 		}
3569 	}
3570 	/*
3571 	 * If this is a labeled system, then check to see if we're allowed to
3572 	 * send a response to this particular sender.  If not, then just drop.
3573 	 */
3574 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3575 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3576 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3577 		freemsg(mp);
3578 		return (NULL);
3579 	}
3580 	if (icmp_err_rate_limit(ipst)) {
3581 		/*
3582 		 * Only send ICMP error packets every so often.
3583 		 * This should be done on a per port/source basis,
3584 		 * but for now this will suffice.
3585 		 */
3586 		freemsg(mp);
3587 		return (NULL);
3588 	}
3589 	return (mp);
3590 }
3591 
3592 /*
3593  * Generate an ICMP redirect message.
3594  */
3595 static void
3596 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3597 {
3598 	icmph_t	icmph;
3599 
3600 	/*
3601 	 * We are called from ip_rput where we could
3602 	 * not have attached an IPSEC_IN.
3603 	 */
3604 	ASSERT(mp->b_datap->db_type == M_DATA);
3605 
3606 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3607 		return;
3608 	}
3609 
3610 	bzero(&icmph, sizeof (icmph_t));
3611 	icmph.icmph_type = ICMP_REDIRECT;
3612 	icmph.icmph_code = 1;
3613 	icmph.icmph_rd_gateway = gateway;
3614 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3615 	/* Redirects sent by router, and router is global zone */
3616 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3617 }
3618 
3619 /*
3620  * Generate an ICMP time exceeded message.
3621  */
3622 void
3623 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3624     ip_stack_t *ipst)
3625 {
3626 	icmph_t	icmph;
3627 	boolean_t mctl_present;
3628 	mblk_t *first_mp;
3629 
3630 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3631 
3632 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3633 		if (mctl_present)
3634 			freeb(first_mp);
3635 		return;
3636 	}
3637 
3638 	bzero(&icmph, sizeof (icmph_t));
3639 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3640 	icmph.icmph_code = code;
3641 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3642 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3643 	    ipst);
3644 }
3645 
3646 /*
3647  * Generate an ICMP unreachable message.
3648  */
3649 void
3650 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3651     ip_stack_t *ipst)
3652 {
3653 	icmph_t	icmph;
3654 	mblk_t *first_mp;
3655 	boolean_t mctl_present;
3656 
3657 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3658 
3659 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3660 		if (mctl_present)
3661 			freeb(first_mp);
3662 		return;
3663 	}
3664 
3665 	bzero(&icmph, sizeof (icmph_t));
3666 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3667 	icmph.icmph_code = code;
3668 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3669 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3670 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3671 	    zoneid, ipst);
3672 }
3673 
3674 /*
3675  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3676  * duplicate.  As long as someone else holds the address, the interface will
3677  * stay down.  When that conflict goes away, the interface is brought back up.
3678  * This is done so that accidental shutdowns of addresses aren't made
3679  * permanent.  Your server will recover from a failure.
3680  *
3681  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3682  * user space process (dhcpagent).
3683  *
3684  * Recovery completes if ARP reports that the address is now ours (via
3685  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3686  *
3687  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3688  */
3689 static void
3690 ipif_dup_recovery(void *arg)
3691 {
3692 	ipif_t *ipif = arg;
3693 	ill_t *ill = ipif->ipif_ill;
3694 	mblk_t *arp_add_mp;
3695 	mblk_t *arp_del_mp;
3696 	area_t *area;
3697 	ip_stack_t *ipst = ill->ill_ipst;
3698 
3699 	ipif->ipif_recovery_id = 0;
3700 
3701 	/*
3702 	 * No lock needed for moving or condemned check, as this is just an
3703 	 * optimization.
3704 	 */
3705 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3706 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3707 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3708 		/* No reason to try to bring this address back. */
3709 		return;
3710 	}
3711 
3712 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3713 		goto alloc_fail;
3714 
3715 	if (ipif->ipif_arp_del_mp == NULL) {
3716 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3717 			goto alloc_fail;
3718 		ipif->ipif_arp_del_mp = arp_del_mp;
3719 	}
3720 
3721 	/* Setting the 'unverified' flag restarts DAD */
3722 	area = (area_t *)arp_add_mp->b_rptr;
3723 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3724 	    ACE_F_UNVERIFIED;
3725 	putnext(ill->ill_rq, arp_add_mp);
3726 	return;
3727 
3728 alloc_fail:
3729 	/*
3730 	 * On allocation failure, just restart the timer.  Note that the ipif
3731 	 * is down here, so no other thread could be trying to start a recovery
3732 	 * timer.  The ill_lock protects the condemned flag and the recovery
3733 	 * timer ID.
3734 	 */
3735 	freemsg(arp_add_mp);
3736 	mutex_enter(&ill->ill_lock);
3737 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3738 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3739 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3740 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3741 	}
3742 	mutex_exit(&ill->ill_lock);
3743 }
3744 
3745 /*
3746  * This is for exclusive changes due to ARP.  Either tear down an interface due
3747  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3748  */
3749 /* ARGSUSED */
3750 static void
3751 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3752 {
3753 	ill_t	*ill = rq->q_ptr;
3754 	arh_t *arh;
3755 	ipaddr_t src;
3756 	ipif_t	*ipif;
3757 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3758 	char hbuf[MAC_STR_LEN];
3759 	char sbuf[INET_ADDRSTRLEN];
3760 	const char *failtype;
3761 	boolean_t bring_up;
3762 	ip_stack_t *ipst = ill->ill_ipst;
3763 
3764 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3765 	case AR_CN_READY:
3766 		failtype = NULL;
3767 		bring_up = B_TRUE;
3768 		break;
3769 	case AR_CN_FAILED:
3770 		failtype = "in use";
3771 		bring_up = B_FALSE;
3772 		break;
3773 	default:
3774 		failtype = "claimed";
3775 		bring_up = B_FALSE;
3776 		break;
3777 	}
3778 
3779 	arh = (arh_t *)mp->b_cont->b_rptr;
3780 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3781 
3782 	/* Handle failures due to probes */
3783 	if (src == 0) {
3784 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3785 		    IP_ADDR_LEN);
3786 	}
3787 
3788 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3789 	    sizeof (hbuf));
3790 	(void) ip_dot_addr(src, sbuf);
3791 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3792 
3793 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3794 		    ipif->ipif_lcl_addr != src) {
3795 			continue;
3796 		}
3797 
3798 		/*
3799 		 * If we failed on a recovery probe, then restart the timer to
3800 		 * try again later.
3801 		 */
3802 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3803 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3804 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3805 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3806 		    ipst->ips_ip_dup_recovery > 0 &&
3807 		    ipif->ipif_recovery_id == 0) {
3808 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3809 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3810 			continue;
3811 		}
3812 
3813 		/*
3814 		 * If what we're trying to do has already been done, then do
3815 		 * nothing.
3816 		 */
3817 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3818 			continue;
3819 
3820 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3821 
3822 		if (failtype == NULL) {
3823 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3824 			    ibuf);
3825 		} else {
3826 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3827 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3828 		}
3829 
3830 		if (bring_up) {
3831 			ASSERT(ill->ill_dl_up);
3832 			/*
3833 			 * Free up the ARP delete message so we can allocate
3834 			 * a fresh one through the normal path.
3835 			 */
3836 			freemsg(ipif->ipif_arp_del_mp);
3837 			ipif->ipif_arp_del_mp = NULL;
3838 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3839 			    EINPROGRESS) {
3840 				ipif->ipif_addr_ready = 1;
3841 				(void) ipif_up_done(ipif);
3842 			}
3843 			continue;
3844 		}
3845 
3846 		mutex_enter(&ill->ill_lock);
3847 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3848 		ipif->ipif_flags |= IPIF_DUPLICATE;
3849 		ill->ill_ipif_dup_count++;
3850 		mutex_exit(&ill->ill_lock);
3851 		/*
3852 		 * Already exclusive on the ill; no need to handle deferred
3853 		 * processing here.
3854 		 */
3855 		(void) ipif_down(ipif, NULL, NULL);
3856 		ipif_down_tail(ipif);
3857 		mutex_enter(&ill->ill_lock);
3858 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3859 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3860 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3861 		    ipst->ips_ip_dup_recovery > 0) {
3862 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3863 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3864 		}
3865 		mutex_exit(&ill->ill_lock);
3866 	}
3867 	freemsg(mp);
3868 }
3869 
3870 /* ARGSUSED */
3871 static void
3872 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3873 {
3874 	ill_t	*ill = rq->q_ptr;
3875 	arh_t *arh;
3876 	ipaddr_t src;
3877 	ipif_t	*ipif;
3878 
3879 	arh = (arh_t *)mp->b_cont->b_rptr;
3880 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3881 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3882 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3883 			(void) ipif_resolver_up(ipif, Res_act_defend);
3884 	}
3885 	freemsg(mp);
3886 }
3887 
3888 /*
3889  * News from ARP.  ARP sends notification of interesting events down
3890  * to its clients using M_CTL messages with the interesting ARP packet
3891  * attached via b_cont.
3892  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3893  * queue as opposed to ARP sending the message to all the clients, i.e. all
3894  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3895  * table if a cache IRE is found to delete all the entries for the address in
3896  * the packet.
3897  */
3898 static void
3899 ip_arp_news(queue_t *q, mblk_t *mp)
3900 {
3901 	arcn_t		*arcn;
3902 	arh_t		*arh;
3903 	ire_t		*ire = NULL;
3904 	char		hbuf[MAC_STR_LEN];
3905 	char		sbuf[INET_ADDRSTRLEN];
3906 	ipaddr_t	src;
3907 	in6_addr_t	v6src;
3908 	boolean_t	isv6 = B_FALSE;
3909 	ipif_t		*ipif;
3910 	ill_t		*ill;
3911 	ip_stack_t	*ipst;
3912 
3913 	if (CONN_Q(q)) {
3914 		conn_t *connp = Q_TO_CONN(q);
3915 
3916 		ipst = connp->conn_netstack->netstack_ip;
3917 	} else {
3918 		ill_t *ill = (ill_t *)q->q_ptr;
3919 
3920 		ipst = ill->ill_ipst;
3921 	}
3922 
3923 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3924 		if (q->q_next) {
3925 			putnext(q, mp);
3926 		} else
3927 			freemsg(mp);
3928 		return;
3929 	}
3930 	arh = (arh_t *)mp->b_cont->b_rptr;
3931 	/* Is it one we are interested in? */
3932 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3933 		isv6 = B_TRUE;
3934 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3935 		    IPV6_ADDR_LEN);
3936 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3937 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3938 		    IP_ADDR_LEN);
3939 	} else {
3940 		freemsg(mp);
3941 		return;
3942 	}
3943 
3944 	ill = q->q_ptr;
3945 
3946 	arcn = (arcn_t *)mp->b_rptr;
3947 	switch (arcn->arcn_code) {
3948 	case AR_CN_BOGON:
3949 		/*
3950 		 * Someone is sending ARP packets with a source protocol
3951 		 * address that we have published and for which we believe our
3952 		 * entry is authoritative and (when ill_arp_extend is set)
3953 		 * verified to be unique on the network.
3954 		 *
3955 		 * The ARP module internally handles the cases where the sender
3956 		 * is just probing (for DAD) and where the hardware address of
3957 		 * a non-authoritative entry has changed.  Thus, these are the
3958 		 * real conflicts, and we have to do resolution.
3959 		 *
3960 		 * We back away quickly from the address if it's from DHCP or
3961 		 * otherwise temporary and hasn't been used recently (or at
3962 		 * all).  We'd like to include "deprecated" addresses here as
3963 		 * well (as there's no real reason to defend something we're
3964 		 * discarding), but IPMP "reuses" this flag to mean something
3965 		 * other than the standard meaning.
3966 		 *
3967 		 * If the ARP module above is not extended (meaning that it
3968 		 * doesn't know how to defend the address), then we just log
3969 		 * the problem as we always did and continue on.  It's not
3970 		 * right, but there's little else we can do, and those old ATM
3971 		 * users are going away anyway.
3972 		 */
3973 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3974 		    hbuf, sizeof (hbuf));
3975 		(void) ip_dot_addr(src, sbuf);
3976 		if (isv6) {
3977 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3978 			    ipst);
3979 		} else {
3980 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3981 		}
3982 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3983 			uint32_t now;
3984 			uint32_t maxage;
3985 			clock_t lused;
3986 			uint_t maxdefense;
3987 			uint_t defs;
3988 
3989 			/*
3990 			 * First, figure out if this address hasn't been used
3991 			 * in a while.  If it hasn't, then it's a better
3992 			 * candidate for abandoning.
3993 			 */
3994 			ipif = ire->ire_ipif;
3995 			ASSERT(ipif != NULL);
3996 			now = gethrestime_sec();
3997 			maxage = now - ire->ire_create_time;
3998 			if (maxage > ipst->ips_ip_max_temp_idle)
3999 				maxage = ipst->ips_ip_max_temp_idle;
4000 			lused = drv_hztousec(ddi_get_lbolt() -
4001 			    ire->ire_last_used_time) / MICROSEC + 1;
4002 			if (lused >= maxage && (ipif->ipif_flags &
4003 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4004 				maxdefense = ipst->ips_ip_max_temp_defend;
4005 			else
4006 				maxdefense = ipst->ips_ip_max_defend;
4007 
4008 			/*
4009 			 * Now figure out how many times we've defended
4010 			 * ourselves.  Ignore defenses that happened long in
4011 			 * the past.
4012 			 */
4013 			mutex_enter(&ire->ire_lock);
4014 			if ((defs = ire->ire_defense_count) > 0 &&
4015 			    now - ire->ire_defense_time >
4016 			    ipst->ips_ip_defend_interval) {
4017 				ire->ire_defense_count = defs = 0;
4018 			}
4019 			ire->ire_defense_count++;
4020 			ire->ire_defense_time = now;
4021 			mutex_exit(&ire->ire_lock);
4022 			ill_refhold(ill);
4023 			ire_refrele(ire);
4024 
4025 			/*
4026 			 * If we've defended ourselves too many times already,
4027 			 * then give up and tear down the interface(s) using
4028 			 * this address.  Otherwise, defend by sending out a
4029 			 * gratuitous ARP.
4030 			 */
4031 			if (defs >= maxdefense && ill->ill_arp_extend) {
4032 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4033 				    B_FALSE);
4034 			} else {
4035 				cmn_err(CE_WARN,
4036 				    "node %s is using our IP address %s on %s",
4037 				    hbuf, sbuf, ill->ill_name);
4038 				/*
4039 				 * If this is an old (ATM) ARP module, then
4040 				 * don't try to defend the address.  Remain
4041 				 * compatible with the old behavior.  Defend
4042 				 * only with new ARP.
4043 				 */
4044 				if (ill->ill_arp_extend) {
4045 					qwriter_ip(ill, q, mp, ip_arp_defend,
4046 					    NEW_OP, B_FALSE);
4047 				} else {
4048 					ill_refrele(ill);
4049 				}
4050 			}
4051 			return;
4052 		}
4053 		cmn_err(CE_WARN,
4054 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4055 		    hbuf, sbuf, ill->ill_name);
4056 		if (ire != NULL)
4057 			ire_refrele(ire);
4058 		break;
4059 	case AR_CN_ANNOUNCE:
4060 		if (isv6) {
4061 			/*
4062 			 * For XRESOLV interfaces.
4063 			 * Delete the IRE cache entry and NCE for this
4064 			 * v6 address
4065 			 */
4066 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4067 			/*
4068 			 * If v6src is a non-zero, it's a router address
4069 			 * as below. Do the same sort of thing to clean
4070 			 * out off-net IRE_CACHE entries that go through
4071 			 * the router.
4072 			 */
4073 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4074 				ire_walk_v6(ire_delete_cache_gw_v6,
4075 				    (char *)&v6src, ALL_ZONES, ipst);
4076 			}
4077 		} else {
4078 			nce_hw_map_t hwm;
4079 
4080 			/*
4081 			 * ARP gives us a copy of any packet where it thinks
4082 			 * the address has changed, so that we can update our
4083 			 * caches.  We're responsible for caching known answers
4084 			 * in the current design.  We check whether the
4085 			 * hardware address really has changed in all of our
4086 			 * entries that have cached this mapping, and if so, we
4087 			 * blow them away.  This way we will immediately pick
4088 			 * up the rare case of a host changing hardware
4089 			 * address.
4090 			 */
4091 			if (src == 0)
4092 				break;
4093 			hwm.hwm_addr = src;
4094 			hwm.hwm_hwlen = arh->arh_hlen;
4095 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4096 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4097 			ndp_walk_common(ipst->ips_ndp4, NULL,
4098 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4099 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4100 		}
4101 		break;
4102 	case AR_CN_READY:
4103 		/* No external v6 resolver has a contract to use this */
4104 		if (isv6)
4105 			break;
4106 		/* If the link is down, we'll retry this later */
4107 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4108 			break;
4109 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4110 		    NULL, NULL, ipst);
4111 		if (ipif != NULL) {
4112 			/*
4113 			 * If this is a duplicate recovery, then we now need to
4114 			 * go exclusive to bring this thing back up.
4115 			 */
4116 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4117 			    IPIF_DUPLICATE) {
4118 				ipif_refrele(ipif);
4119 				ill_refhold(ill);
4120 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4121 				    B_FALSE);
4122 				return;
4123 			}
4124 			/*
4125 			 * If this is the first notice that this address is
4126 			 * ready, then let the user know now.
4127 			 */
4128 			if ((ipif->ipif_flags & IPIF_UP) &&
4129 			    !ipif->ipif_addr_ready) {
4130 				ipif_mask_reply(ipif);
4131 				ip_rts_ifmsg(ipif);
4132 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4133 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4134 			}
4135 			ipif->ipif_addr_ready = 1;
4136 			ipif_refrele(ipif);
4137 		}
4138 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4139 		if (ire != NULL) {
4140 			ire->ire_defense_count = 0;
4141 			ire_refrele(ire);
4142 		}
4143 		break;
4144 	case AR_CN_FAILED:
4145 		/* No external v6 resolver has a contract to use this */
4146 		if (isv6)
4147 			break;
4148 		ill_refhold(ill);
4149 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4150 		return;
4151 	}
4152 	freemsg(mp);
4153 }
4154 
4155 /*
4156  * Create a mblk suitable for carrying the interface index and/or source link
4157  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4158  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4159  * application.
4160  */
4161 mblk_t *
4162 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4163     ip_stack_t *ipst)
4164 {
4165 	mblk_t		*mp;
4166 	ip_pktinfo_t	*pinfo;
4167 	ipha_t *ipha;
4168 	struct ether_header *pether;
4169 
4170 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4171 	if (mp == NULL) {
4172 		ip1dbg(("ip_add_info: allocation failure.\n"));
4173 		return (data_mp);
4174 	}
4175 
4176 	ipha	= (ipha_t *)data_mp->b_rptr;
4177 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4178 	bzero(pinfo, sizeof (ip_pktinfo_t));
4179 	pinfo->ip_pkt_flags = (uchar_t)flags;
4180 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4181 
4182 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4183 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4184 	if (flags & IPF_RECVADDR) {
4185 		ipif_t	*ipif;
4186 		ire_t	*ire;
4187 
4188 		/*
4189 		 * Only valid for V4
4190 		 */
4191 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4192 		    (IPV4_VERSION << 4));
4193 
4194 		ipif = ipif_get_next_ipif(NULL, ill);
4195 		if (ipif != NULL) {
4196 			/*
4197 			 * Since a decision has already been made to deliver the
4198 			 * packet, there is no need to test for SECATTR and
4199 			 * ZONEONLY.
4200 			 * When a multicast packet is transmitted
4201 			 * a cache entry is created for the multicast address.
4202 			 * When delivering a copy of the packet or when new
4203 			 * packets are received we do not want to match on the
4204 			 * cached entry so explicitly match on
4205 			 * IRE_LOCAL and IRE_LOOPBACK
4206 			 */
4207 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4208 			    IRE_LOCAL | IRE_LOOPBACK,
4209 			    ipif, zoneid, NULL,
4210 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4211 			if (ire == NULL) {
4212 				/*
4213 				 * packet must have come on a different
4214 				 * interface.
4215 				 * Since a decision has already been made to
4216 				 * deliver the packet, there is no need to test
4217 				 * for SECATTR and ZONEONLY.
4218 				 * Only match on local and broadcast ire's.
4219 				 * See detailed comment above.
4220 				 */
4221 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4222 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4223 				    NULL, MATCH_IRE_TYPE, ipst);
4224 			}
4225 
4226 			if (ire == NULL) {
4227 				/*
4228 				 * This is either a multicast packet or
4229 				 * the address has been removed since
4230 				 * the packet was received.
4231 				 * Return INADDR_ANY so that normal source
4232 				 * selection occurs for the response.
4233 				 */
4234 
4235 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4236 			} else {
4237 				pinfo->ip_pkt_match_addr.s_addr =
4238 				    ire->ire_src_addr;
4239 				ire_refrele(ire);
4240 			}
4241 			ipif_refrele(ipif);
4242 		} else {
4243 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4244 		}
4245 	}
4246 
4247 	pether = (struct ether_header *)((char *)ipha
4248 	    - sizeof (struct ether_header));
4249 	/*
4250 	 * Make sure the interface is an ethernet type, since this option
4251 	 * is currently supported only on this type of interface. Also make
4252 	 * sure we are pointing correctly above db_base.
4253 	 */
4254 
4255 	if ((flags & IPF_RECVSLLA) &&
4256 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4257 	    (ill->ill_type == IFT_ETHER) &&
4258 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4259 
4260 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4261 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4262 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4263 	} else {
4264 		/*
4265 		 * Clear the bit. Indicate to upper layer that IP is not
4266 		 * sending this ancillary info.
4267 		 */
4268 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4269 	}
4270 
4271 	mp->b_datap->db_type = M_CTL;
4272 	mp->b_wptr += sizeof (ip_pktinfo_t);
4273 	mp->b_cont = data_mp;
4274 
4275 	return (mp);
4276 }
4277 
4278 /*
4279  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4280  * part of the bind request.
4281  */
4282 
4283 boolean_t
4284 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4285 {
4286 	ipsec_in_t *ii;
4287 
4288 	ASSERT(policy_mp != NULL);
4289 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4290 
4291 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4292 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4293 
4294 	connp->conn_policy = ii->ipsec_in_policy;
4295 	ii->ipsec_in_policy = NULL;
4296 
4297 	if (ii->ipsec_in_action != NULL) {
4298 		if (connp->conn_latch == NULL) {
4299 			connp->conn_latch = iplatch_create();
4300 			if (connp->conn_latch == NULL)
4301 				return (B_FALSE);
4302 		}
4303 		ipsec_latch_inbound(connp->conn_latch, ii);
4304 	}
4305 	return (B_TRUE);
4306 }
4307 
4308 /*
4309  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4310  * and to arrange for power-fanout assist.  The ULP is identified by
4311  * adding a single byte at the end of the original bind message.
4312  * A ULP other than UDP or TCP that wishes to be recognized passes
4313  * down a bind with a zero length address.
4314  *
4315  * The binding works as follows:
4316  * - A zero byte address means just bind to the protocol.
4317  * - A four byte address is treated as a request to validate
4318  *   that the address is a valid local address, appropriate for
4319  *   an application to bind to. This does not affect any fanout
4320  *   information in IP.
4321  * - A sizeof sin_t byte address is used to bind to only the local address
4322  *   and port.
4323  * - A sizeof ipa_conn_t byte address contains complete fanout information
4324  *   consisting of local and remote addresses and ports.  In
4325  *   this case, the addresses are both validated as appropriate
4326  *   for this operation, and, if so, the information is retained
4327  *   for use in the inbound fanout.
4328  *
4329  * The ULP (except in the zero-length bind) can append an
4330  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4331  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4332  * a copy of the source or destination IRE (source for local bind;
4333  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4334  * policy information contained should be copied on to the conn.
4335  *
4336  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4337  */
4338 mblk_t *
4339 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4340 {
4341 	ssize_t		len;
4342 	struct T_bind_req	*tbr;
4343 	sin_t		*sin;
4344 	ipa_conn_t	*ac;
4345 	uchar_t		*ucp;
4346 	mblk_t		*mp1;
4347 	boolean_t	ire_requested;
4348 	boolean_t	ipsec_policy_set = B_FALSE;
4349 	int		error = 0;
4350 	int		protocol;
4351 	ipa_conn_x_t	*acx;
4352 
4353 	ASSERT(!connp->conn_af_isv6);
4354 	connp->conn_pkt_isv6 = B_FALSE;
4355 
4356 	len = MBLKL(mp);
4357 	if (len < (sizeof (*tbr) + 1)) {
4358 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4359 		    "ip_bind: bogus msg, len %ld", len);
4360 		/* XXX: Need to return something better */
4361 		goto bad_addr;
4362 	}
4363 	/* Back up and extract the protocol identifier. */
4364 	mp->b_wptr--;
4365 	protocol = *mp->b_wptr & 0xFF;
4366 	tbr = (struct T_bind_req *)mp->b_rptr;
4367 	/* Reset the message type in preparation for shipping it back. */
4368 	DB_TYPE(mp) = M_PCPROTO;
4369 
4370 	connp->conn_ulp = (uint8_t)protocol;
4371 
4372 	/*
4373 	 * Check for a zero length address.  This is from a protocol that
4374 	 * wants to register to receive all packets of its type.
4375 	 */
4376 	if (tbr->ADDR_length == 0) {
4377 		/*
4378 		 * These protocols are now intercepted in ip_bind_v6().
4379 		 * Reject protocol-level binds here for now.
4380 		 *
4381 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4382 		 * so that the protocol type cannot be SCTP.
4383 		 */
4384 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4385 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4386 			goto bad_addr;
4387 		}
4388 
4389 		/*
4390 		 *
4391 		 * The udp module never sends down a zero-length address,
4392 		 * and allowing this on a labeled system will break MLP
4393 		 * functionality.
4394 		 */
4395 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4396 			goto bad_addr;
4397 
4398 		if (connp->conn_mac_exempt)
4399 			goto bad_addr;
4400 
4401 		/* No hash here really.  The table is big enough. */
4402 		connp->conn_srcv6 = ipv6_all_zeros;
4403 
4404 		ipcl_proto_insert(connp, protocol);
4405 
4406 		tbr->PRIM_type = T_BIND_ACK;
4407 		return (mp);
4408 	}
4409 
4410 	/* Extract the address pointer from the message. */
4411 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4412 	    tbr->ADDR_length);
4413 	if (ucp == NULL) {
4414 		ip1dbg(("ip_bind: no address\n"));
4415 		goto bad_addr;
4416 	}
4417 	if (!OK_32PTR(ucp)) {
4418 		ip1dbg(("ip_bind: unaligned address\n"));
4419 		goto bad_addr;
4420 	}
4421 	/*
4422 	 * Check for trailing mps.
4423 	 */
4424 
4425 	mp1 = mp->b_cont;
4426 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4427 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4428 
4429 	switch (tbr->ADDR_length) {
4430 	default:
4431 		ip1dbg(("ip_bind: bad address length %d\n",
4432 		    (int)tbr->ADDR_length));
4433 		goto bad_addr;
4434 
4435 	case IP_ADDR_LEN:
4436 		/* Verification of local address only */
4437 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4438 		    ire_requested, ipsec_policy_set, B_FALSE);
4439 		break;
4440 
4441 	case sizeof (sin_t):
4442 		sin = (sin_t *)ucp;
4443 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4444 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4445 		break;
4446 
4447 	case sizeof (ipa_conn_t):
4448 		ac = (ipa_conn_t *)ucp;
4449 		/* For raw socket, the local port is not set. */
4450 		if (ac->ac_lport == 0)
4451 			ac->ac_lport = connp->conn_lport;
4452 		/* Always verify destination reachability. */
4453 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4454 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4455 		    ipsec_policy_set, B_TRUE, B_TRUE);
4456 		break;
4457 
4458 	case sizeof (ipa_conn_x_t):
4459 		acx = (ipa_conn_x_t *)ucp;
4460 		/*
4461 		 * Whether or not to verify destination reachability depends
4462 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4463 		 */
4464 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4465 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4466 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4467 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4468 		break;
4469 	}
4470 	if (error == EINPROGRESS)
4471 		return (NULL);
4472 	else if (error != 0)
4473 		goto bad_addr;
4474 	/*
4475 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4476 	 * We can't do this in ip_bind_insert_ire because the policy
4477 	 * may not have been inherited at that point in time and hence
4478 	 * conn_out_enforce_policy may not be set.
4479 	 */
4480 	mp1 = mp->b_cont;
4481 	if (ire_requested && connp->conn_out_enforce_policy &&
4482 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4483 		ire_t *ire = (ire_t *)mp1->b_rptr;
4484 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4485 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4486 	}
4487 
4488 	/* Send it home. */
4489 	mp->b_datap->db_type = M_PCPROTO;
4490 	tbr->PRIM_type = T_BIND_ACK;
4491 	return (mp);
4492 
4493 bad_addr:
4494 	/*
4495 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4496 	 * a unix errno.
4497 	 */
4498 	if (error > 0)
4499 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4500 	else
4501 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4502 	return (mp);
4503 }
4504 
4505 /*
4506  * Here address is verified to be a valid local address.
4507  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4508  * address is also considered a valid local address.
4509  * In the case of a broadcast/multicast address, however, the
4510  * upper protocol is expected to reset the src address
4511  * to 0 if it sees a IRE_BROADCAST type returned so that
4512  * no packets are emitted with broadcast/multicast address as
4513  * source address (that violates hosts requirements RFC1122)
4514  * The addresses valid for bind are:
4515  *	(1) - INADDR_ANY (0)
4516  *	(2) - IP address of an UP interface
4517  *	(3) - IP address of a DOWN interface
4518  *	(4) - valid local IP broadcast addresses. In this case
4519  *	the conn will only receive packets destined to
4520  *	the specified broadcast address.
4521  *	(5) - a multicast address. In this case
4522  *	the conn will only receive packets destined to
4523  *	the specified multicast address. Note: the
4524  *	application still has to issue an
4525  *	IP_ADD_MEMBERSHIP socket option.
4526  *
4527  * On error, return -1 for TBADADDR otherwise pass the
4528  * errno with TSYSERR reply.
4529  *
4530  * In all the above cases, the bound address must be valid in the current zone.
4531  * When the address is loopback, multicast or broadcast, there might be many
4532  * matching IREs so bind has to look up based on the zone.
4533  *
4534  * Note: lport is in network byte order.
4535  */
4536 int
4537 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4538     boolean_t ire_requested, boolean_t ipsec_policy_set,
4539     boolean_t fanout_insert)
4540 {
4541 	int		error = 0;
4542 	ire_t		*src_ire;
4543 	mblk_t		*policy_mp;
4544 	ipif_t		*ipif;
4545 	zoneid_t	zoneid;
4546 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4547 
4548 	if (ipsec_policy_set) {
4549 		policy_mp = mp->b_cont;
4550 	}
4551 
4552 	/*
4553 	 * If it was previously connected, conn_fully_bound would have
4554 	 * been set.
4555 	 */
4556 	connp->conn_fully_bound = B_FALSE;
4557 
4558 	src_ire = NULL;
4559 	ipif = NULL;
4560 
4561 	zoneid = IPCL_ZONEID(connp);
4562 
4563 	if (src_addr) {
4564 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4565 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4566 		/*
4567 		 * If an address other than 0.0.0.0 is requested,
4568 		 * we verify that it is a valid address for bind
4569 		 * Note: Following code is in if-else-if form for
4570 		 * readability compared to a condition check.
4571 		 */
4572 		/* LINTED - statement has no consequent */
4573 		if (IRE_IS_LOCAL(src_ire)) {
4574 			/*
4575 			 * (2) Bind to address of local UP interface
4576 			 */
4577 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4578 			/*
4579 			 * (4) Bind to broadcast address
4580 			 * Note: permitted only from transports that
4581 			 * request IRE
4582 			 */
4583 			if (!ire_requested)
4584 				error = EADDRNOTAVAIL;
4585 		} else {
4586 			/*
4587 			 * (3) Bind to address of local DOWN interface
4588 			 * (ipif_lookup_addr() looks up all interfaces
4589 			 * but we do not get here for UP interfaces
4590 			 * - case (2) above)
4591 			 * We put the protocol byte back into the mblk
4592 			 * since we may come back via ip_wput_nondata()
4593 			 * later with this mblk if ipif_lookup_addr chooses
4594 			 * to defer processing.
4595 			 */
4596 			*mp->b_wptr++ = (char)connp->conn_ulp;
4597 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4598 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4599 			    &error, ipst)) != NULL) {
4600 				ipif_refrele(ipif);
4601 			} else if (error == EINPROGRESS) {
4602 				if (src_ire != NULL)
4603 					ire_refrele(src_ire);
4604 				return (EINPROGRESS);
4605 			} else if (CLASSD(src_addr)) {
4606 				error = 0;
4607 				if (src_ire != NULL)
4608 					ire_refrele(src_ire);
4609 				/*
4610 				 * (5) bind to multicast address.
4611 				 * Fake out the IRE returned to upper
4612 				 * layer to be a broadcast IRE.
4613 				 */
4614 				src_ire = ire_ctable_lookup(
4615 				    INADDR_BROADCAST, INADDR_ANY,
4616 				    IRE_BROADCAST, NULL, zoneid, NULL,
4617 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4618 				    ipst);
4619 				if (src_ire == NULL || !ire_requested)
4620 					error = EADDRNOTAVAIL;
4621 			} else {
4622 				/*
4623 				 * Not a valid address for bind
4624 				 */
4625 				error = EADDRNOTAVAIL;
4626 			}
4627 			/*
4628 			 * Just to keep it consistent with the processing in
4629 			 * ip_bind_v4()
4630 			 */
4631 			mp->b_wptr--;
4632 		}
4633 		if (error) {
4634 			/* Red Alert!  Attempting to be a bogon! */
4635 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4636 			    ntohl(src_addr)));
4637 			goto bad_addr;
4638 		}
4639 	}
4640 
4641 	/*
4642 	 * Allow setting new policies. For example, disconnects come
4643 	 * down as ipa_t bind. As we would have set conn_policy_cached
4644 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4645 	 * can change after the disconnect.
4646 	 */
4647 	connp->conn_policy_cached = B_FALSE;
4648 
4649 	/*
4650 	 * If not fanout_insert this was just an address verification
4651 	 */
4652 	if (fanout_insert) {
4653 		/*
4654 		 * The addresses have been verified. Time to insert in
4655 		 * the correct fanout list.
4656 		 */
4657 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4658 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4659 		connp->conn_lport = lport;
4660 		connp->conn_fport = 0;
4661 		/*
4662 		 * Do we need to add a check to reject Multicast packets
4663 		 *
4664 		 * We need to make sure that the conn_recv is set to a non-null
4665 		 * value before we insert the conn into the classifier table.
4666 		 * This is to avoid a race with an incoming packet which does an
4667 		 * ipcl_classify().
4668 		 */
4669 		if (*mp->b_wptr == IPPROTO_TCP)
4670 			connp->conn_recv = tcp_conn_request;
4671 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4672 	}
4673 
4674 	if (error == 0) {
4675 		if (ire_requested) {
4676 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4677 				error = -1;
4678 				/* Falls through to bad_addr */
4679 			}
4680 		} else if (ipsec_policy_set) {
4681 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4682 				error = -1;
4683 				/* Falls through to bad_addr */
4684 			}
4685 		}
4686 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4687 		connp->conn_recv = tcp_input;
4688 	}
4689 bad_addr:
4690 	if (error != 0) {
4691 		if (connp->conn_anon_port) {
4692 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4693 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4694 			    B_FALSE);
4695 		}
4696 		connp->conn_mlp_type = mlptSingle;
4697 	}
4698 	if (src_ire != NULL)
4699 		IRE_REFRELE(src_ire);
4700 	if (ipsec_policy_set) {
4701 		ASSERT(policy_mp == mp->b_cont);
4702 		ASSERT(policy_mp != NULL);
4703 		freeb(policy_mp);
4704 		/*
4705 		 * As of now assume that nothing else accompanies
4706 		 * IPSEC_POLICY_SET.
4707 		 */
4708 		mp->b_cont = NULL;
4709 	}
4710 	return (error);
4711 }
4712 
4713 /*
4714  * Verify that both the source and destination addresses
4715  * are valid.  If verify_dst is false, then the destination address may be
4716  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4717  * destination reachability, while tunnels do not.
4718  * Note that we allow connect to broadcast and multicast
4719  * addresses when ire_requested is set. Thus the ULP
4720  * has to check for IRE_BROADCAST and multicast.
4721  *
4722  * Returns zero if ok.
4723  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4724  * (for use with TSYSERR reply).
4725  *
4726  * Note: lport and fport are in network byte order.
4727  */
4728 int
4729 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4730     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4731     boolean_t ire_requested, boolean_t ipsec_policy_set,
4732     boolean_t fanout_insert, boolean_t verify_dst)
4733 {
4734 	ire_t		*src_ire;
4735 	ire_t		*dst_ire;
4736 	int		error = 0;
4737 	int 		protocol;
4738 	mblk_t		*policy_mp;
4739 	ire_t		*sire = NULL;
4740 	ire_t		*md_dst_ire = NULL;
4741 	ire_t		*lso_dst_ire = NULL;
4742 	ill_t		*ill = NULL;
4743 	zoneid_t	zoneid;
4744 	ipaddr_t	src_addr = *src_addrp;
4745 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4746 
4747 	src_ire = dst_ire = NULL;
4748 	protocol = *mp->b_wptr & 0xFF;
4749 
4750 	/*
4751 	 * If we never got a disconnect before, clear it now.
4752 	 */
4753 	connp->conn_fully_bound = B_FALSE;
4754 
4755 	if (ipsec_policy_set) {
4756 		policy_mp = mp->b_cont;
4757 	}
4758 
4759 	zoneid = IPCL_ZONEID(connp);
4760 
4761 	if (CLASSD(dst_addr)) {
4762 		/* Pick up an IRE_BROADCAST */
4763 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4764 		    NULL, zoneid, MBLK_GETLABEL(mp),
4765 		    (MATCH_IRE_RECURSIVE |
4766 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4767 		    MATCH_IRE_SECATTR), ipst);
4768 	} else {
4769 		/*
4770 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4771 		 * and onlink ipif is not found set ENETUNREACH error.
4772 		 */
4773 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4774 			ipif_t *ipif;
4775 
4776 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4777 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4778 			if (ipif == NULL) {
4779 				error = ENETUNREACH;
4780 				goto bad_addr;
4781 			}
4782 			ipif_refrele(ipif);
4783 		}
4784 
4785 		if (connp->conn_nexthop_set) {
4786 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4787 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4788 			    MATCH_IRE_SECATTR, ipst);
4789 		} else {
4790 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4791 			    &sire, zoneid, MBLK_GETLABEL(mp),
4792 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4793 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4794 			    MATCH_IRE_SECATTR), ipst);
4795 		}
4796 	}
4797 	/*
4798 	 * dst_ire can't be a broadcast when not ire_requested.
4799 	 * We also prevent ire's with src address INADDR_ANY to
4800 	 * be used, which are created temporarily for
4801 	 * sending out packets from endpoints that have
4802 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4803 	 * reachable.  If verify_dst is false, the destination needn't be
4804 	 * reachable.
4805 	 *
4806 	 * If we match on a reject or black hole, then we've got a
4807 	 * local failure.  May as well fail out the connect() attempt,
4808 	 * since it's never going to succeed.
4809 	 */
4810 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4811 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4812 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4813 		/*
4814 		 * If we're verifying destination reachability, we always want
4815 		 * to complain here.
4816 		 *
4817 		 * If we're not verifying destination reachability but the
4818 		 * destination has a route, we still want to fail on the
4819 		 * temporary address and broadcast address tests.
4820 		 */
4821 		if (verify_dst || (dst_ire != NULL)) {
4822 			if (ip_debug > 2) {
4823 				pr_addr_dbg("ip_bind_connected: bad connected "
4824 				    "dst %s\n", AF_INET, &dst_addr);
4825 			}
4826 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4827 				error = ENETUNREACH;
4828 			else
4829 				error = EHOSTUNREACH;
4830 			goto bad_addr;
4831 		}
4832 	}
4833 
4834 	/*
4835 	 * We now know that routing will allow us to reach the destination.
4836 	 * Check whether Trusted Solaris policy allows communication with this
4837 	 * host, and pretend that the destination is unreachable if not.
4838 	 *
4839 	 * This is never a problem for TCP, since that transport is known to
4840 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4841 	 * handling.  If the remote is unreachable, it will be detected at that
4842 	 * point, so there's no reason to check it here.
4843 	 *
4844 	 * Note that for sendto (and other datagram-oriented friends), this
4845 	 * check is done as part of the data path label computation instead.
4846 	 * The check here is just to make non-TCP connect() report the right
4847 	 * error.
4848 	 */
4849 	if (dst_ire != NULL && is_system_labeled() &&
4850 	    !IPCL_IS_TCP(connp) &&
4851 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4852 	    connp->conn_mac_exempt, ipst) != 0) {
4853 		error = EHOSTUNREACH;
4854 		if (ip_debug > 2) {
4855 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4856 			    AF_INET, &dst_addr);
4857 		}
4858 		goto bad_addr;
4859 	}
4860 
4861 	/*
4862 	 * If the app does a connect(), it means that it will most likely
4863 	 * send more than 1 packet to the destination.  It makes sense
4864 	 * to clear the temporary flag.
4865 	 */
4866 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4867 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4868 		irb_t *irb = dst_ire->ire_bucket;
4869 
4870 		rw_enter(&irb->irb_lock, RW_WRITER);
4871 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4872 		irb->irb_tmp_ire_cnt--;
4873 		rw_exit(&irb->irb_lock);
4874 	}
4875 
4876 	/*
4877 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4878 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4879 	 * eligibility tests for passive connects are handled separately
4880 	 * through tcp_adapt_ire().  We do this before the source address
4881 	 * selection, because dst_ire may change after a call to
4882 	 * ipif_select_source().  This is a best-effort check, as the
4883 	 * packet for this connection may not actually go through
4884 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4885 	 * calling ip_newroute().  This is why we further check on the
4886 	 * IRE during LSO/Multidata packet transmission in
4887 	 * tcp_lsosend()/tcp_multisend().
4888 	 */
4889 	if (!ipsec_policy_set && dst_ire != NULL &&
4890 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4891 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4892 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4893 			lso_dst_ire = dst_ire;
4894 			IRE_REFHOLD(lso_dst_ire);
4895 		} else if (ipst->ips_ip_multidata_outbound &&
4896 		    ILL_MDT_CAPABLE(ill)) {
4897 			md_dst_ire = dst_ire;
4898 			IRE_REFHOLD(md_dst_ire);
4899 		}
4900 	}
4901 
4902 	if (dst_ire != NULL &&
4903 	    dst_ire->ire_type == IRE_LOCAL &&
4904 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4905 		/*
4906 		 * If the IRE belongs to a different zone, look for a matching
4907 		 * route in the forwarding table and use the source address from
4908 		 * that route.
4909 		 */
4910 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4911 		    zoneid, 0, NULL,
4912 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4913 		    MATCH_IRE_RJ_BHOLE, ipst);
4914 		if (src_ire == NULL) {
4915 			error = EHOSTUNREACH;
4916 			goto bad_addr;
4917 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4918 			if (!(src_ire->ire_type & IRE_HOST))
4919 				error = ENETUNREACH;
4920 			else
4921 				error = EHOSTUNREACH;
4922 			goto bad_addr;
4923 		}
4924 		if (src_addr == INADDR_ANY)
4925 			src_addr = src_ire->ire_src_addr;
4926 		ire_refrele(src_ire);
4927 		src_ire = NULL;
4928 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4929 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4930 			src_addr = sire->ire_src_addr;
4931 			ire_refrele(dst_ire);
4932 			dst_ire = sire;
4933 			sire = NULL;
4934 		} else {
4935 			/*
4936 			 * Pick a source address so that a proper inbound
4937 			 * load spreading would happen.
4938 			 */
4939 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4940 			ipif_t *src_ipif = NULL;
4941 			ire_t *ipif_ire;
4942 
4943 			/*
4944 			 * Supply a local source address such that inbound
4945 			 * load spreading happens.
4946 			 *
4947 			 * Determine the best source address on this ill for
4948 			 * the destination.
4949 			 *
4950 			 * 1) For broadcast, we should return a broadcast ire
4951 			 *    found above so that upper layers know that the
4952 			 *    destination address is a broadcast address.
4953 			 *
4954 			 * 2) If this is part of a group, select a better
4955 			 *    source address so that better inbound load
4956 			 *    balancing happens. Do the same if the ipif
4957 			 *    is DEPRECATED.
4958 			 *
4959 			 * 3) If the outgoing interface is part of a usesrc
4960 			 *    group, then try selecting a source address from
4961 			 *    the usesrc ILL.
4962 			 */
4963 			if ((dst_ire->ire_zoneid != zoneid &&
4964 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4965 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4966 			    ((dst_ill->ill_group != NULL) ||
4967 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4968 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4969 				/*
4970 				 * If the destination is reachable via a
4971 				 * given gateway, the selected source address
4972 				 * should be in the same subnet as the gateway.
4973 				 * Otherwise, the destination is not reachable.
4974 				 *
4975 				 * If there are no interfaces on the same subnet
4976 				 * as the destination, ipif_select_source gives
4977 				 * first non-deprecated interface which might be
4978 				 * on a different subnet than the gateway.
4979 				 * This is not desirable. Hence pass the dst_ire
4980 				 * source address to ipif_select_source.
4981 				 * It is sure that the destination is reachable
4982 				 * with the dst_ire source address subnet.
4983 				 * So passing dst_ire source address to
4984 				 * ipif_select_source will make sure that the
4985 				 * selected source will be on the same subnet
4986 				 * as dst_ire source address.
4987 				 */
4988 				ipaddr_t saddr =
4989 				    dst_ire->ire_ipif->ipif_src_addr;
4990 				src_ipif = ipif_select_source(dst_ill,
4991 				    saddr, zoneid);
4992 				if (src_ipif != NULL) {
4993 					if (IS_VNI(src_ipif->ipif_ill)) {
4994 						/*
4995 						 * For VNI there is no
4996 						 * interface route
4997 						 */
4998 						src_addr =
4999 						    src_ipif->ipif_src_addr;
5000 					} else {
5001 						ipif_ire =
5002 						    ipif_to_ire(src_ipif);
5003 						if (ipif_ire != NULL) {
5004 							IRE_REFRELE(dst_ire);
5005 							dst_ire = ipif_ire;
5006 						}
5007 						src_addr =
5008 						    dst_ire->ire_src_addr;
5009 					}
5010 					ipif_refrele(src_ipif);
5011 				} else {
5012 					src_addr = dst_ire->ire_src_addr;
5013 				}
5014 			} else {
5015 				src_addr = dst_ire->ire_src_addr;
5016 			}
5017 		}
5018 	}
5019 
5020 	/*
5021 	 * We do ire_route_lookup() here (and not
5022 	 * interface lookup as we assert that
5023 	 * src_addr should only come from an
5024 	 * UP interface for hard binding.
5025 	 */
5026 	ASSERT(src_ire == NULL);
5027 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5028 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5029 	/* src_ire must be a local|loopback */
5030 	if (!IRE_IS_LOCAL(src_ire)) {
5031 		if (ip_debug > 2) {
5032 			pr_addr_dbg("ip_bind_connected: bad connected "
5033 			    "src %s\n", AF_INET, &src_addr);
5034 		}
5035 		error = EADDRNOTAVAIL;
5036 		goto bad_addr;
5037 	}
5038 
5039 	/*
5040 	 * If the source address is a loopback address, the
5041 	 * destination had best be local or multicast.
5042 	 * The transports that can't handle multicast will reject
5043 	 * those addresses.
5044 	 */
5045 	if (src_ire->ire_type == IRE_LOOPBACK &&
5046 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5047 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5048 		error = -1;
5049 		goto bad_addr;
5050 	}
5051 
5052 	/*
5053 	 * Allow setting new policies. For example, disconnects come
5054 	 * down as ipa_t bind. As we would have set conn_policy_cached
5055 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5056 	 * can change after the disconnect.
5057 	 */
5058 	connp->conn_policy_cached = B_FALSE;
5059 
5060 	/*
5061 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5062 	 * can handle their passed-in conn's.
5063 	 */
5064 
5065 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5066 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5067 	connp->conn_lport = lport;
5068 	connp->conn_fport = fport;
5069 	*src_addrp = src_addr;
5070 
5071 	ASSERT(!(ipsec_policy_set && ire_requested));
5072 	if (ire_requested) {
5073 		iulp_t *ulp_info = NULL;
5074 
5075 		/*
5076 		 * Note that sire will not be NULL if this is an off-link
5077 		 * connection and there is not cache for that dest yet.
5078 		 *
5079 		 * XXX Because of an existing bug, if there are multiple
5080 		 * default routes, the IRE returned now may not be the actual
5081 		 * default route used (default routes are chosen in a
5082 		 * round robin fashion).  So if the metrics for different
5083 		 * default routes are different, we may return the wrong
5084 		 * metrics.  This will not be a problem if the existing
5085 		 * bug is fixed.
5086 		 */
5087 		if (sire != NULL) {
5088 			ulp_info = &(sire->ire_uinfo);
5089 		}
5090 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5091 			error = -1;
5092 			goto bad_addr;
5093 		}
5094 	} else if (ipsec_policy_set) {
5095 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5096 			error = -1;
5097 			goto bad_addr;
5098 		}
5099 	}
5100 
5101 	/*
5102 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5103 	 * we'll cache that.  If we don't, we'll inherit global policy.
5104 	 *
5105 	 * We can't insert until the conn reflects the policy. Note that
5106 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5107 	 * connections where we don't have a policy. This is to prevent
5108 	 * global policy lookups in the inbound path.
5109 	 *
5110 	 * If we insert before we set conn_policy_cached,
5111 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5112 	 * because global policy cound be non-empty. We normally call
5113 	 * ipsec_check_policy() for conn_policy_cached connections only if
5114 	 * ipc_in_enforce_policy is set. But in this case,
5115 	 * conn_policy_cached can get set anytime since we made the
5116 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5117 	 * called, which will make the above assumption false.  Thus, we
5118 	 * need to insert after we set conn_policy_cached.
5119 	 */
5120 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5121 		goto bad_addr;
5122 
5123 	if (fanout_insert) {
5124 		/*
5125 		 * The addresses have been verified. Time to insert in
5126 		 * the correct fanout list.
5127 		 * We need to make sure that the conn_recv is set to a non-null
5128 		 * value before we insert into the classifier table to avoid a
5129 		 * race with an incoming packet which does an ipcl_classify().
5130 		 */
5131 		if (protocol == IPPROTO_TCP)
5132 			connp->conn_recv = tcp_input;
5133 		error = ipcl_conn_insert(connp, protocol, src_addr,
5134 		    dst_addr, connp->conn_ports);
5135 	}
5136 
5137 	if (error == 0) {
5138 		connp->conn_fully_bound = B_TRUE;
5139 		/*
5140 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5141 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5142 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5143 		 * ip_xxinfo_return(), which performs further checks
5144 		 * against them and upon success, returns the LSO/MDT info
5145 		 * mblk which we will attach to the bind acknowledgment.
5146 		 */
5147 		if (lso_dst_ire != NULL) {
5148 			mblk_t *lsoinfo_mp;
5149 
5150 			ASSERT(ill->ill_lso_capab != NULL);
5151 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5152 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5153 				linkb(mp, lsoinfo_mp);
5154 		} else if (md_dst_ire != NULL) {
5155 			mblk_t *mdinfo_mp;
5156 
5157 			ASSERT(ill->ill_mdt_capab != NULL);
5158 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5159 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5160 				linkb(mp, mdinfo_mp);
5161 		}
5162 	}
5163 bad_addr:
5164 	if (ipsec_policy_set) {
5165 		ASSERT(policy_mp == mp->b_cont);
5166 		ASSERT(policy_mp != NULL);
5167 		freeb(policy_mp);
5168 		/*
5169 		 * As of now assume that nothing else accompanies
5170 		 * IPSEC_POLICY_SET.
5171 		 */
5172 		mp->b_cont = NULL;
5173 	}
5174 	if (src_ire != NULL)
5175 		IRE_REFRELE(src_ire);
5176 	if (dst_ire != NULL)
5177 		IRE_REFRELE(dst_ire);
5178 	if (sire != NULL)
5179 		IRE_REFRELE(sire);
5180 	if (md_dst_ire != NULL)
5181 		IRE_REFRELE(md_dst_ire);
5182 	if (lso_dst_ire != NULL)
5183 		IRE_REFRELE(lso_dst_ire);
5184 	return (error);
5185 }
5186 
5187 /*
5188  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5189  * Prefers dst_ire over src_ire.
5190  */
5191 static boolean_t
5192 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5193 {
5194 	mblk_t	*mp1;
5195 	ire_t *ret_ire = NULL;
5196 
5197 	mp1 = mp->b_cont;
5198 	ASSERT(mp1 != NULL);
5199 
5200 	if (ire != NULL) {
5201 		/*
5202 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5203 		 * appended mblk. Its <upper protocol>'s
5204 		 * job to make sure there is room.
5205 		 */
5206 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5207 			return (0);
5208 
5209 		mp1->b_datap->db_type = IRE_DB_TYPE;
5210 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5211 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5212 		ret_ire = (ire_t *)mp1->b_rptr;
5213 		/*
5214 		 * Pass the latest setting of the ip_path_mtu_discovery and
5215 		 * copy the ulp info if any.
5216 		 */
5217 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5218 		    IPH_DF : 0;
5219 		if (ulp_info != NULL) {
5220 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5221 			    sizeof (iulp_t));
5222 		}
5223 		ret_ire->ire_mp = mp1;
5224 	} else {
5225 		/*
5226 		 * No IRE was found. Remove IRE mblk.
5227 		 */
5228 		mp->b_cont = mp1->b_cont;
5229 		freeb(mp1);
5230 	}
5231 
5232 	return (1);
5233 }
5234 
5235 /*
5236  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5237  * the final piece where we don't.  Return a pointer to the first mblk in the
5238  * result, and update the pointer to the next mblk to chew on.  If anything
5239  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5240  * NULL pointer.
5241  */
5242 mblk_t *
5243 ip_carve_mp(mblk_t **mpp, ssize_t len)
5244 {
5245 	mblk_t	*mp0;
5246 	mblk_t	*mp1;
5247 	mblk_t	*mp2;
5248 
5249 	if (!len || !mpp || !(mp0 = *mpp))
5250 		return (NULL);
5251 	/* If we aren't going to consume the first mblk, we need a dup. */
5252 	if (mp0->b_wptr - mp0->b_rptr > len) {
5253 		mp1 = dupb(mp0);
5254 		if (mp1) {
5255 			/* Partition the data between the two mblks. */
5256 			mp1->b_wptr = mp1->b_rptr + len;
5257 			mp0->b_rptr = mp1->b_wptr;
5258 			/*
5259 			 * after adjustments if mblk not consumed is now
5260 			 * unaligned, try to align it. If this fails free
5261 			 * all messages and let upper layer recover.
5262 			 */
5263 			if (!OK_32PTR(mp0->b_rptr)) {
5264 				if (!pullupmsg(mp0, -1)) {
5265 					freemsg(mp0);
5266 					freemsg(mp1);
5267 					*mpp = NULL;
5268 					return (NULL);
5269 				}
5270 			}
5271 		}
5272 		return (mp1);
5273 	}
5274 	/* Eat through as many mblks as we need to get len bytes. */
5275 	len -= mp0->b_wptr - mp0->b_rptr;
5276 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5277 		if (mp2->b_wptr - mp2->b_rptr > len) {
5278 			/*
5279 			 * We won't consume the entire last mblk.  Like
5280 			 * above, dup and partition it.
5281 			 */
5282 			mp1->b_cont = dupb(mp2);
5283 			mp1 = mp1->b_cont;
5284 			if (!mp1) {
5285 				/*
5286 				 * Trouble.  Rather than go to a lot of
5287 				 * trouble to clean up, we free the messages.
5288 				 * This won't be any worse than losing it on
5289 				 * the wire.
5290 				 */
5291 				freemsg(mp0);
5292 				freemsg(mp2);
5293 				*mpp = NULL;
5294 				return (NULL);
5295 			}
5296 			mp1->b_wptr = mp1->b_rptr + len;
5297 			mp2->b_rptr = mp1->b_wptr;
5298 			/*
5299 			 * after adjustments if mblk not consumed is now
5300 			 * unaligned, try to align it. If this fails free
5301 			 * all messages and let upper layer recover.
5302 			 */
5303 			if (!OK_32PTR(mp2->b_rptr)) {
5304 				if (!pullupmsg(mp2, -1)) {
5305 					freemsg(mp0);
5306 					freemsg(mp2);
5307 					*mpp = NULL;
5308 					return (NULL);
5309 				}
5310 			}
5311 			*mpp = mp2;
5312 			return (mp0);
5313 		}
5314 		/* Decrement len by the amount we just got. */
5315 		len -= mp2->b_wptr - mp2->b_rptr;
5316 	}
5317 	/*
5318 	 * len should be reduced to zero now.  If not our caller has
5319 	 * screwed up.
5320 	 */
5321 	if (len) {
5322 		/* Shouldn't happen! */
5323 		freemsg(mp0);
5324 		*mpp = NULL;
5325 		return (NULL);
5326 	}
5327 	/*
5328 	 * We consumed up to exactly the end of an mblk.  Detach the part
5329 	 * we are returning from the rest of the chain.
5330 	 */
5331 	mp1->b_cont = NULL;
5332 	*mpp = mp2;
5333 	return (mp0);
5334 }
5335 
5336 /* The ill stream is being unplumbed. Called from ip_close */
5337 int
5338 ip_modclose(ill_t *ill)
5339 {
5340 	boolean_t success;
5341 	ipsq_t	*ipsq;
5342 	ipif_t	*ipif;
5343 	queue_t	*q = ill->ill_rq;
5344 	ip_stack_t	*ipst = ill->ill_ipst;
5345 	clock_t timeout;
5346 
5347 	/*
5348 	 * Wait for the ACKs of all deferred control messages to be processed.
5349 	 * In particular, we wait for a potential capability reset initiated
5350 	 * in ip_sioctl_plink() to complete before proceeding.
5351 	 *
5352 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5353 	 * in case the driver never replies.
5354 	 */
5355 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5356 	mutex_enter(&ill->ill_lock);
5357 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5358 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5359 			/* Timeout */
5360 			break;
5361 		}
5362 	}
5363 	mutex_exit(&ill->ill_lock);
5364 
5365 	/*
5366 	 * Forcibly enter the ipsq after some delay. This is to take
5367 	 * care of the case when some ioctl does not complete because
5368 	 * we sent a control message to the driver and it did not
5369 	 * send us a reply. We want to be able to at least unplumb
5370 	 * and replumb rather than force the user to reboot the system.
5371 	 */
5372 	success = ipsq_enter(ill, B_FALSE);
5373 
5374 	/*
5375 	 * Open/close/push/pop is guaranteed to be single threaded
5376 	 * per stream by STREAMS. FS guarantees that all references
5377 	 * from top are gone before close is called. So there can't
5378 	 * be another close thread that has set CONDEMNED on this ill.
5379 	 * and cause ipsq_enter to return failure.
5380 	 */
5381 	ASSERT(success);
5382 	ipsq = ill->ill_phyint->phyint_ipsq;
5383 
5384 	/*
5385 	 * Mark it condemned. No new reference will be made to this ill.
5386 	 * Lookup functions will return an error. Threads that try to
5387 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5388 	 * that the refcnt will drop down to zero.
5389 	 */
5390 	mutex_enter(&ill->ill_lock);
5391 	ill->ill_state_flags |= ILL_CONDEMNED;
5392 	for (ipif = ill->ill_ipif; ipif != NULL;
5393 	    ipif = ipif->ipif_next) {
5394 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5395 	}
5396 	/*
5397 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5398 	 * returns  error if ILL_CONDEMNED is set
5399 	 */
5400 	cv_broadcast(&ill->ill_cv);
5401 	mutex_exit(&ill->ill_lock);
5402 
5403 	/*
5404 	 * Send all the deferred DLPI messages downstream which came in
5405 	 * during the small window right before ipsq_enter(). We do this
5406 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5407 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5408 	 */
5409 	ill_dlpi_send_deferred(ill);
5410 
5411 	/*
5412 	 * Shut down fragmentation reassembly.
5413 	 * ill_frag_timer won't start a timer again.
5414 	 * Now cancel any existing timer
5415 	 */
5416 	(void) untimeout(ill->ill_frag_timer_id);
5417 	(void) ill_frag_timeout(ill, 0);
5418 
5419 	/*
5420 	 * If MOVE was in progress, clear the
5421 	 * move_in_progress fields also.
5422 	 */
5423 	if (ill->ill_move_in_progress) {
5424 		ILL_CLEAR_MOVE(ill);
5425 	}
5426 
5427 	/*
5428 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5429 	 * this ill. Then wait for the refcnts to drop to zero.
5430 	 * ill_is_quiescent checks whether the ill is really quiescent.
5431 	 * Then make sure that threads that are waiting to enter the
5432 	 * ipsq have seen the error returned by ipsq_enter and have
5433 	 * gone away. Then we call ill_delete_tail which does the
5434 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5435 	 */
5436 	ill_delete(ill);
5437 	mutex_enter(&ill->ill_lock);
5438 	while (!ill_is_quiescent(ill))
5439 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5440 	while (ill->ill_waiters)
5441 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5442 
5443 	mutex_exit(&ill->ill_lock);
5444 
5445 	/*
5446 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5447 	 * it held until the end of the function since the cleanup
5448 	 * below needs to be able to use the ip_stack_t.
5449 	 */
5450 	netstack_hold(ipst->ips_netstack);
5451 
5452 	/* qprocsoff is called in ill_delete_tail */
5453 	ill_delete_tail(ill);
5454 	ASSERT(ill->ill_ipst == NULL);
5455 
5456 	/*
5457 	 * Walk through all upper (conn) streams and qenable
5458 	 * those that have queued data.
5459 	 * close synchronization needs this to
5460 	 * be done to ensure that all upper layers blocked
5461 	 * due to flow control to the closing device
5462 	 * get unblocked.
5463 	 */
5464 	ip1dbg(("ip_wsrv: walking\n"));
5465 	conn_walk_drain(ipst);
5466 
5467 	mutex_enter(&ipst->ips_ip_mi_lock);
5468 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5469 	mutex_exit(&ipst->ips_ip_mi_lock);
5470 
5471 	/*
5472 	 * credp could be null if the open didn't succeed and ip_modopen
5473 	 * itself calls ip_close.
5474 	 */
5475 	if (ill->ill_credp != NULL)
5476 		crfree(ill->ill_credp);
5477 
5478 	mutex_enter(&ill->ill_lock);
5479 	ill_nic_info_dispatch(ill);
5480 	mutex_exit(&ill->ill_lock);
5481 
5482 	/*
5483 	 * Now we are done with the module close pieces that
5484 	 * need the netstack_t.
5485 	 */
5486 	netstack_rele(ipst->ips_netstack);
5487 
5488 	mi_close_free((IDP)ill);
5489 	q->q_ptr = WR(q)->q_ptr = NULL;
5490 
5491 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5492 
5493 	return (0);
5494 }
5495 
5496 /*
5497  * This is called as part of close() for both IP and UDP
5498  * in order to quiesce the conn.
5499  */
5500 void
5501 ip_quiesce_conn(conn_t *connp)
5502 {
5503 	boolean_t	drain_cleanup_reqd = B_FALSE;
5504 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5505 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5506 	ip_stack_t	*ipst;
5507 
5508 	ASSERT(!IPCL_IS_TCP(connp));
5509 	ipst = connp->conn_netstack->netstack_ip;
5510 
5511 	/*
5512 	 * Mark the conn as closing, and this conn must not be
5513 	 * inserted in future into any list. Eg. conn_drain_insert(),
5514 	 * won't insert this conn into the conn_drain_list.
5515 	 * Similarly ill_pending_mp_add() will not add any mp to
5516 	 * the pending mp list, after this conn has started closing.
5517 	 *
5518 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5519 	 * cannot get set henceforth.
5520 	 */
5521 	mutex_enter(&connp->conn_lock);
5522 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5523 	connp->conn_state_flags |= CONN_CLOSING;
5524 	if (connp->conn_idl != NULL)
5525 		drain_cleanup_reqd = B_TRUE;
5526 	if (connp->conn_oper_pending_ill != NULL)
5527 		conn_ioctl_cleanup_reqd = B_TRUE;
5528 	if (connp->conn_ilg_inuse != 0)
5529 		ilg_cleanup_reqd = B_TRUE;
5530 	mutex_exit(&connp->conn_lock);
5531 
5532 	if (IPCL_IS_UDP(connp))
5533 		udp_quiesce_conn(connp);
5534 
5535 	if (conn_ioctl_cleanup_reqd)
5536 		conn_ioctl_cleanup(connp);
5537 
5538 	if (is_system_labeled() && connp->conn_anon_port) {
5539 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5540 		    connp->conn_mlp_type, connp->conn_ulp,
5541 		    ntohs(connp->conn_lport), B_FALSE);
5542 		connp->conn_anon_port = 0;
5543 	}
5544 	connp->conn_mlp_type = mlptSingle;
5545 
5546 	/*
5547 	 * Remove this conn from any fanout list it is on.
5548 	 * and then wait for any threads currently operating
5549 	 * on this endpoint to finish
5550 	 */
5551 	ipcl_hash_remove(connp);
5552 
5553 	/*
5554 	 * Remove this conn from the drain list, and do
5555 	 * any other cleanup that may be required.
5556 	 * (Only non-tcp streams may have a non-null conn_idl.
5557 	 * TCP streams are never flow controlled, and
5558 	 * conn_idl will be null)
5559 	 */
5560 	if (drain_cleanup_reqd)
5561 		conn_drain_tail(connp, B_TRUE);
5562 
5563 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5564 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5565 		(void) ip_mrouter_done(NULL, ipst);
5566 
5567 	if (ilg_cleanup_reqd)
5568 		ilg_delete_all(connp);
5569 
5570 	conn_delete_ire(connp, NULL);
5571 
5572 	/*
5573 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5574 	 * callers from write side can't be there now because close
5575 	 * is in progress. The only other caller is ipcl_walk
5576 	 * which checks for the condemned flag.
5577 	 */
5578 	mutex_enter(&connp->conn_lock);
5579 	connp->conn_state_flags |= CONN_CONDEMNED;
5580 	while (connp->conn_ref != 1)
5581 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5582 	connp->conn_state_flags |= CONN_QUIESCED;
5583 	mutex_exit(&connp->conn_lock);
5584 }
5585 
5586 /* ARGSUSED */
5587 int
5588 ip_close(queue_t *q, int flags)
5589 {
5590 	conn_t		*connp;
5591 
5592 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5593 
5594 	/*
5595 	 * Call the appropriate delete routine depending on whether this is
5596 	 * a module or device.
5597 	 */
5598 	if (WR(q)->q_next != NULL) {
5599 		/* This is a module close */
5600 		return (ip_modclose((ill_t *)q->q_ptr));
5601 	}
5602 
5603 	connp = q->q_ptr;
5604 	ip_quiesce_conn(connp);
5605 
5606 	qprocsoff(q);
5607 
5608 	/*
5609 	 * Now we are truly single threaded on this stream, and can
5610 	 * delete the things hanging off the connp, and finally the connp.
5611 	 * We removed this connp from the fanout list, it cannot be
5612 	 * accessed thru the fanouts, and we already waited for the
5613 	 * conn_ref to drop to 0. We are already in close, so
5614 	 * there cannot be any other thread from the top. qprocsoff
5615 	 * has completed, and service has completed or won't run in
5616 	 * future.
5617 	 */
5618 	ASSERT(connp->conn_ref == 1);
5619 
5620 	/*
5621 	 * A conn which was previously marked as IPCL_UDP cannot
5622 	 * retain the flag because it would have been cleared by
5623 	 * udp_close().
5624 	 */
5625 	ASSERT(!IPCL_IS_UDP(connp));
5626 
5627 	if (connp->conn_latch != NULL) {
5628 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5629 		connp->conn_latch = NULL;
5630 	}
5631 	if (connp->conn_policy != NULL) {
5632 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5633 		connp->conn_policy = NULL;
5634 	}
5635 	if (connp->conn_ipsec_opt_mp != NULL) {
5636 		freemsg(connp->conn_ipsec_opt_mp);
5637 		connp->conn_ipsec_opt_mp = NULL;
5638 	}
5639 
5640 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5641 
5642 	connp->conn_ref--;
5643 	ipcl_conn_destroy(connp);
5644 
5645 	q->q_ptr = WR(q)->q_ptr = NULL;
5646 	return (0);
5647 }
5648 
5649 int
5650 ip_snmpmod_close(queue_t *q)
5651 {
5652 	conn_t *connp = Q_TO_CONN(q);
5653 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5654 
5655 	qprocsoff(q);
5656 
5657 	if (connp->conn_flags & IPCL_UDPMOD)
5658 		udp_close_free(connp);
5659 
5660 	if (connp->conn_cred != NULL) {
5661 		crfree(connp->conn_cred);
5662 		connp->conn_cred = NULL;
5663 	}
5664 	CONN_DEC_REF(connp);
5665 	q->q_ptr = WR(q)->q_ptr = NULL;
5666 	return (0);
5667 }
5668 
5669 /*
5670  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5671  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5672  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5673  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5674  * queues as we never enqueue messages there and we don't handle any ioctls.
5675  * Everything else is freed.
5676  */
5677 void
5678 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5679 {
5680 	conn_t	*connp = q->q_ptr;
5681 	pfi_t	setfn;
5682 	pfi_t	getfn;
5683 
5684 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5685 
5686 	switch (DB_TYPE(mp)) {
5687 	case M_PROTO:
5688 	case M_PCPROTO:
5689 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5690 		    ((((union T_primitives *)mp->b_rptr)->type ==
5691 		    T_SVR4_OPTMGMT_REQ) ||
5692 		    (((union T_primitives *)mp->b_rptr)->type ==
5693 		    T_OPTMGMT_REQ))) {
5694 			/*
5695 			 * This is the only TPI primitive supported. Its
5696 			 * handling does not require tcp_t, but it does require
5697 			 * conn_t to check permissions.
5698 			 */
5699 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5700 
5701 			if (connp->conn_flags & IPCL_TCPMOD) {
5702 				setfn = tcp_snmp_set;
5703 				getfn = tcp_snmp_get;
5704 			} else {
5705 				setfn = udp_snmp_set;
5706 				getfn = udp_snmp_get;
5707 			}
5708 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5709 				freemsg(mp);
5710 				return;
5711 			}
5712 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5713 		    != NULL)
5714 			qreply(q, mp);
5715 		break;
5716 	case M_FLUSH:
5717 	case M_IOCTL:
5718 		putnext(q, mp);
5719 		break;
5720 	default:
5721 		freemsg(mp);
5722 		break;
5723 	}
5724 }
5725 
5726 /* Return the IP checksum for the IP header at "iph". */
5727 uint16_t
5728 ip_csum_hdr(ipha_t *ipha)
5729 {
5730 	uint16_t	*uph;
5731 	uint32_t	sum;
5732 	int		opt_len;
5733 
5734 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5735 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5736 	uph = (uint16_t *)ipha;
5737 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5738 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5739 	if (opt_len > 0) {
5740 		do {
5741 			sum += uph[10];
5742 			sum += uph[11];
5743 			uph += 2;
5744 		} while (--opt_len);
5745 	}
5746 	sum = (sum & 0xFFFF) + (sum >> 16);
5747 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5748 	if (sum == 0xffff)
5749 		sum = 0;
5750 	return ((uint16_t)sum);
5751 }
5752 
5753 /*
5754  * Called when the module is about to be unloaded
5755  */
5756 void
5757 ip_ddi_destroy(void)
5758 {
5759 	tnet_fini();
5760 
5761 	sctp_ddi_g_destroy();
5762 	tcp_ddi_g_destroy();
5763 	ipsec_policy_g_destroy();
5764 	ipcl_g_destroy();
5765 	ip_net_g_destroy();
5766 	ip_ire_g_fini();
5767 	inet_minor_destroy(ip_minor_arena);
5768 
5769 #ifdef DEBUG
5770 	list_destroy(&ip_thread_list);
5771 	rw_destroy(&ip_thread_rwlock);
5772 	tsd_destroy(&ip_thread_data);
5773 #endif
5774 
5775 	netstack_unregister(NS_IP);
5776 }
5777 
5778 /*
5779  * First step in cleanup.
5780  */
5781 /* ARGSUSED */
5782 static void
5783 ip_stack_shutdown(netstackid_t stackid, void *arg)
5784 {
5785 	ip_stack_t *ipst = (ip_stack_t *)arg;
5786 
5787 #ifdef NS_DEBUG
5788 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5789 #endif
5790 
5791 	/* Get rid of loopback interfaces and their IREs */
5792 	ip_loopback_cleanup(ipst);
5793 }
5794 
5795 /*
5796  * Free the IP stack instance.
5797  */
5798 static void
5799 ip_stack_fini(netstackid_t stackid, void *arg)
5800 {
5801 	ip_stack_t *ipst = (ip_stack_t *)arg;
5802 	int ret;
5803 
5804 #ifdef NS_DEBUG
5805 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5806 #endif
5807 	ipv4_hook_destroy(ipst);
5808 	ipv6_hook_destroy(ipst);
5809 	ip_net_destroy(ipst);
5810 
5811 	rw_destroy(&ipst->ips_srcid_lock);
5812 
5813 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5814 	ipst->ips_ip_mibkp = NULL;
5815 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5816 	ipst->ips_icmp_mibkp = NULL;
5817 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5818 	ipst->ips_ip_kstat = NULL;
5819 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5820 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5821 	ipst->ips_ip6_kstat = NULL;
5822 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5823 
5824 	nd_free(&ipst->ips_ip_g_nd);
5825 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5826 	ipst->ips_param_arr = NULL;
5827 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5828 	ipst->ips_ndp_arr = NULL;
5829 
5830 	ip_mrouter_stack_destroy(ipst);
5831 
5832 	mutex_destroy(&ipst->ips_ip_mi_lock);
5833 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5834 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5835 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5836 
5837 	ret = untimeout(ipst->ips_igmp_timeout_id);
5838 	if (ret == -1) {
5839 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5840 	} else {
5841 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5842 		ipst->ips_igmp_timeout_id = 0;
5843 	}
5844 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5845 	if (ret == -1) {
5846 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5847 	} else {
5848 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5849 		ipst->ips_igmp_slowtimeout_id = 0;
5850 	}
5851 	ret = untimeout(ipst->ips_mld_timeout_id);
5852 	if (ret == -1) {
5853 		ASSERT(ipst->ips_mld_timeout_id == 0);
5854 	} else {
5855 		ASSERT(ipst->ips_mld_timeout_id != 0);
5856 		ipst->ips_mld_timeout_id = 0;
5857 	}
5858 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5859 	if (ret == -1) {
5860 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5861 	} else {
5862 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5863 		ipst->ips_mld_slowtimeout_id = 0;
5864 	}
5865 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5866 	if (ret == -1) {
5867 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5868 	} else {
5869 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5870 		ipst->ips_ip_ire_expire_id = 0;
5871 	}
5872 
5873 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5874 	mutex_destroy(&ipst->ips_mld_timer_lock);
5875 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5876 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5877 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5878 	rw_destroy(&ipst->ips_ill_g_lock);
5879 
5880 	ip_ire_fini(ipst);
5881 	ip6_asp_free(ipst);
5882 	conn_drain_fini(ipst);
5883 	ipcl_destroy(ipst);
5884 
5885 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5886 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5887 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5888 	ipst->ips_ndp4 = NULL;
5889 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5890 	ipst->ips_ndp6 = NULL;
5891 
5892 	if (ipst->ips_loopback_ksp != NULL) {
5893 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5894 		ipst->ips_loopback_ksp = NULL;
5895 	}
5896 
5897 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5898 	ipst->ips_phyint_g_list = NULL;
5899 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5900 	ipst->ips_ill_g_heads = NULL;
5901 
5902 	kmem_free(ipst, sizeof (*ipst));
5903 }
5904 
5905 /*
5906  * This function is called from the TSD destructor, and is used to debug
5907  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5908  * details.
5909  */
5910 static void
5911 ip_thread_exit(void *phash)
5912 {
5913 	th_hash_t *thh = phash;
5914 
5915 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5916 	list_remove(&ip_thread_list, thh);
5917 	rw_exit(&ip_thread_rwlock);
5918 	mod_hash_destroy_hash(thh->thh_hash);
5919 	kmem_free(thh, sizeof (*thh));
5920 }
5921 
5922 /*
5923  * Called when the IP kernel module is loaded into the kernel
5924  */
5925 void
5926 ip_ddi_init(void)
5927 {
5928 	TCP6_MAJ = ddi_name_to_major(TCP6);
5929 	TCP_MAJ	= ddi_name_to_major(TCP);
5930 	SCTP_MAJ = ddi_name_to_major(SCTP);
5931 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5932 
5933 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5934 
5935 	/*
5936 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5937 	 * initial devices: ip, ip6, tcp, tcp6.
5938 	 */
5939 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5940 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5941 		cmn_err(CE_PANIC,
5942 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5943 	}
5944 
5945 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5946 
5947 	ipcl_g_init();
5948 	ip_ire_g_init();
5949 	ip_net_g_init();
5950 
5951 #ifdef DEBUG
5952 	tsd_create(&ip_thread_data, ip_thread_exit);
5953 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5954 	list_create(&ip_thread_list, sizeof (th_hash_t),
5955 	    offsetof(th_hash_t, thh_link));
5956 #endif
5957 
5958 	/*
5959 	 * We want to be informed each time a stack is created or
5960 	 * destroyed in the kernel, so we can maintain the
5961 	 * set of udp_stack_t's.
5962 	 */
5963 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5964 	    ip_stack_fini);
5965 
5966 	ipsec_policy_g_init();
5967 	tcp_ddi_g_init();
5968 	sctp_ddi_g_init();
5969 
5970 	tnet_init();
5971 }
5972 
5973 /*
5974  * Initialize the IP stack instance.
5975  */
5976 static void *
5977 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5978 {
5979 	ip_stack_t	*ipst;
5980 	ipparam_t	*pa;
5981 	ipndp_t		*na;
5982 
5983 #ifdef NS_DEBUG
5984 	printf("ip_stack_init(stack %d)\n", stackid);
5985 #endif
5986 
5987 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5988 	ipst->ips_netstack = ns;
5989 
5990 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5991 	    KM_SLEEP);
5992 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5993 	    KM_SLEEP);
5994 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5995 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5996 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5997 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5998 
5999 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6000 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6001 	ipst->ips_igmp_deferred_next = INFINITY;
6002 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6003 	ipst->ips_mld_deferred_next = INFINITY;
6004 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6005 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6006 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6007 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6008 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6009 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6010 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6011 
6012 	ipcl_init(ipst);
6013 	ip_ire_init(ipst);
6014 	ip6_asp_init(ipst);
6015 	ipif_init(ipst);
6016 	conn_drain_init(ipst);
6017 	ip_mrouter_stack_init(ipst);
6018 
6019 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6020 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6021 
6022 	ipst->ips_ip_multirt_log_interval = 1000;
6023 
6024 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6025 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6026 	ipst->ips_ill_index = 1;
6027 
6028 	ipst->ips_saved_ip_g_forward = -1;
6029 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6030 
6031 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6032 	ipst->ips_param_arr = pa;
6033 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6034 
6035 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6036 	ipst->ips_ndp_arr = na;
6037 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6038 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6039 	    (caddr_t)&ipst->ips_ip_g_forward;
6040 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6041 	    (caddr_t)&ipst->ips_ipv6_forward;
6042 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6043 	    "ip_cgtp_filter") == 0);
6044 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6045 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6046 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6047 	    "ipmp_hook_emulation") == 0);
6048 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6049 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6050 
6051 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6052 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6053 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6054 
6055 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6056 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6057 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6058 	ipst->ips_ip6_kstat =
6059 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6060 
6061 	ipst->ips_ipmp_enable_failback = B_TRUE;
6062 
6063 	ipst->ips_ip_src_id = 1;
6064 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6065 
6066 	ip_net_init(ipst, ns);
6067 	ipv4_hook_init(ipst);
6068 	ipv6_hook_init(ipst);
6069 
6070 	return (ipst);
6071 }
6072 
6073 /*
6074  * Allocate and initialize a DLPI template of the specified length.  (May be
6075  * called as writer.)
6076  */
6077 mblk_t *
6078 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6079 {
6080 	mblk_t	*mp;
6081 
6082 	mp = allocb(len, BPRI_MED);
6083 	if (!mp)
6084 		return (NULL);
6085 
6086 	/*
6087 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6088 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6089 	 * that other DLPI are M_PROTO.
6090 	 */
6091 	if (prim == DL_INFO_REQ) {
6092 		mp->b_datap->db_type = M_PCPROTO;
6093 	} else {
6094 		mp->b_datap->db_type = M_PROTO;
6095 	}
6096 
6097 	mp->b_wptr = mp->b_rptr + len;
6098 	bzero(mp->b_rptr, len);
6099 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6100 	return (mp);
6101 }
6102 
6103 const char *
6104 dlpi_prim_str(int prim)
6105 {
6106 	switch (prim) {
6107 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6108 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6109 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6110 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6111 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6112 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6113 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6114 	case DL_OK_ACK:		return ("DL_OK_ACK");
6115 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6116 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6117 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6118 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6119 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6120 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6121 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6122 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6123 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6124 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6125 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6126 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6127 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6128 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6129 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6130 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6131 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6132 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6133 	default:		return ("<unknown primitive>");
6134 	}
6135 }
6136 
6137 const char *
6138 dlpi_err_str(int err)
6139 {
6140 	switch (err) {
6141 	case DL_ACCESS:		return ("DL_ACCESS");
6142 	case DL_BADADDR:	return ("DL_BADADDR");
6143 	case DL_BADCORR:	return ("DL_BADCORR");
6144 	case DL_BADDATA:	return ("DL_BADDATA");
6145 	case DL_BADPPA:		return ("DL_BADPPA");
6146 	case DL_BADPRIM:	return ("DL_BADPRIM");
6147 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6148 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6149 	case DL_BADSAP:		return ("DL_BADSAP");
6150 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6151 	case DL_BOUND:		return ("DL_BOUND");
6152 	case DL_INITFAILED:	return ("DL_INITFAILED");
6153 	case DL_NOADDR:		return ("DL_NOADDR");
6154 	case DL_NOTINIT:	return ("DL_NOTINIT");
6155 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6156 	case DL_SYSERR:		return ("DL_SYSERR");
6157 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6158 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6159 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6160 	case DL_TOOMANY:	return ("DL_TOOMANY");
6161 	case DL_NOTENAB:	return ("DL_NOTENAB");
6162 	case DL_BUSY:		return ("DL_BUSY");
6163 	case DL_NOAUTO:		return ("DL_NOAUTO");
6164 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6165 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6166 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6167 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6168 	case DL_PENDING:	return ("DL_PENDING");
6169 	default:		return ("<unknown error>");
6170 	}
6171 }
6172 
6173 /*
6174  * Debug formatting routine.  Returns a character string representation of the
6175  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6176  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6177  *
6178  * Once the ndd table-printing interfaces are removed, this can be changed to
6179  * standard dotted-decimal form.
6180  */
6181 char *
6182 ip_dot_addr(ipaddr_t addr, char *buf)
6183 {
6184 	uint8_t *ap = (uint8_t *)&addr;
6185 
6186 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6187 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6188 	return (buf);
6189 }
6190 
6191 /*
6192  * Write the given MAC address as a printable string in the usual colon-
6193  * separated format.
6194  */
6195 const char *
6196 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6197 {
6198 	char *bp;
6199 
6200 	if (alen == 0 || buflen < 4)
6201 		return ("?");
6202 	bp = buf;
6203 	for (;;) {
6204 		/*
6205 		 * If there are more MAC address bytes available, but we won't
6206 		 * have any room to print them, then add "..." to the string
6207 		 * instead.  See below for the 'magic number' explanation.
6208 		 */
6209 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6210 			(void) strcpy(bp, "...");
6211 			break;
6212 		}
6213 		(void) sprintf(bp, "%02x", *addr++);
6214 		bp += 2;
6215 		if (--alen == 0)
6216 			break;
6217 		*bp++ = ':';
6218 		buflen -= 3;
6219 		/*
6220 		 * At this point, based on the first 'if' statement above,
6221 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6222 		 * buflen >= 4.  The first case leaves room for the final "xx"
6223 		 * number and trailing NUL byte.  The second leaves room for at
6224 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6225 		 * that statement.
6226 		 */
6227 	}
6228 	return (buf);
6229 }
6230 
6231 /*
6232  * Send an ICMP error after patching up the packet appropriately.  Returns
6233  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6234  */
6235 static boolean_t
6236 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6237     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6238     zoneid_t zoneid, ip_stack_t *ipst)
6239 {
6240 	ipha_t *ipha;
6241 	mblk_t *first_mp;
6242 	boolean_t secure;
6243 	unsigned char db_type;
6244 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6245 
6246 	first_mp = mp;
6247 	if (mctl_present) {
6248 		mp = mp->b_cont;
6249 		secure = ipsec_in_is_secure(first_mp);
6250 		ASSERT(mp != NULL);
6251 	} else {
6252 		/*
6253 		 * If this is an ICMP error being reported - which goes
6254 		 * up as M_CTLs, we need to convert them to M_DATA till
6255 		 * we finish checking with global policy because
6256 		 * ipsec_check_global_policy() assumes M_DATA as clear
6257 		 * and M_CTL as secure.
6258 		 */
6259 		db_type = DB_TYPE(mp);
6260 		DB_TYPE(mp) = M_DATA;
6261 		secure = B_FALSE;
6262 	}
6263 	/*
6264 	 * We are generating an icmp error for some inbound packet.
6265 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6266 	 * Before we generate an error, check with global policy
6267 	 * to see whether this is allowed to enter the system. As
6268 	 * there is no "conn", we are checking with global policy.
6269 	 */
6270 	ipha = (ipha_t *)mp->b_rptr;
6271 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6272 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6273 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6274 		if (first_mp == NULL)
6275 			return (B_FALSE);
6276 	}
6277 
6278 	if (!mctl_present)
6279 		DB_TYPE(mp) = db_type;
6280 
6281 	if (flags & IP_FF_SEND_ICMP) {
6282 		if (flags & IP_FF_HDR_COMPLETE) {
6283 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6284 				freemsg(first_mp);
6285 				return (B_TRUE);
6286 			}
6287 		}
6288 		if (flags & IP_FF_CKSUM) {
6289 			/*
6290 			 * Have to correct checksum since
6291 			 * the packet might have been
6292 			 * fragmented and the reassembly code in ip_rput
6293 			 * does not restore the IP checksum.
6294 			 */
6295 			ipha->ipha_hdr_checksum = 0;
6296 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6297 		}
6298 		switch (icmp_type) {
6299 		case ICMP_DEST_UNREACHABLE:
6300 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6301 			    ipst);
6302 			break;
6303 		default:
6304 			freemsg(first_mp);
6305 			break;
6306 		}
6307 	} else {
6308 		freemsg(first_mp);
6309 		return (B_FALSE);
6310 	}
6311 
6312 	return (B_TRUE);
6313 }
6314 
6315 /*
6316  * Used to send an ICMP error message when a packet is received for
6317  * a protocol that is not supported. The mblk passed as argument
6318  * is consumed by this function.
6319  */
6320 void
6321 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6322     ip_stack_t *ipst)
6323 {
6324 	mblk_t *mp;
6325 	ipha_t *ipha;
6326 	ill_t *ill;
6327 	ipsec_in_t *ii;
6328 
6329 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6330 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6331 
6332 	mp = ipsec_mp->b_cont;
6333 	ipsec_mp->b_cont = NULL;
6334 	ipha = (ipha_t *)mp->b_rptr;
6335 	/* Get ill from index in ipsec_in_t. */
6336 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6337 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6338 	    ipst);
6339 	if (ill != NULL) {
6340 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6341 			if (ip_fanout_send_icmp(q, mp, flags,
6342 			    ICMP_DEST_UNREACHABLE,
6343 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6344 				BUMP_MIB(ill->ill_ip_mib,
6345 				    ipIfStatsInUnknownProtos);
6346 			}
6347 		} else {
6348 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6349 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6350 			    0, B_FALSE, zoneid, ipst)) {
6351 				BUMP_MIB(ill->ill_ip_mib,
6352 				    ipIfStatsInUnknownProtos);
6353 			}
6354 		}
6355 		ill_refrele(ill);
6356 	} else { /* re-link for the freemsg() below. */
6357 		ipsec_mp->b_cont = mp;
6358 	}
6359 
6360 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6361 	freemsg(ipsec_mp);
6362 }
6363 
6364 /*
6365  * See if the inbound datagram has had IPsec processing applied to it.
6366  */
6367 boolean_t
6368 ipsec_in_is_secure(mblk_t *ipsec_mp)
6369 {
6370 	ipsec_in_t *ii;
6371 
6372 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6373 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6374 
6375 	if (ii->ipsec_in_loopback) {
6376 		return (ii->ipsec_in_secure);
6377 	} else {
6378 		return (ii->ipsec_in_ah_sa != NULL ||
6379 		    ii->ipsec_in_esp_sa != NULL ||
6380 		    ii->ipsec_in_decaps);
6381 	}
6382 }
6383 
6384 /*
6385  * Handle protocols with which IP is less intimate.  There
6386  * can be more than one stream bound to a particular
6387  * protocol.  When this is the case, normally each one gets a copy
6388  * of any incoming packets.
6389  *
6390  * IPsec NOTE :
6391  *
6392  * Don't allow a secure packet going up a non-secure connection.
6393  * We don't allow this because
6394  *
6395  * 1) Reply might go out in clear which will be dropped at
6396  *    the sending side.
6397  * 2) If the reply goes out in clear it will give the
6398  *    adversary enough information for getting the key in
6399  *    most of the cases.
6400  *
6401  * Moreover getting a secure packet when we expect clear
6402  * implies that SA's were added without checking for
6403  * policy on both ends. This should not happen once ISAKMP
6404  * is used to negotiate SAs as SAs will be added only after
6405  * verifying the policy.
6406  *
6407  * NOTE : If the packet was tunneled and not multicast we only send
6408  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6409  * back to delivering packets to AF_INET6 raw sockets.
6410  *
6411  * IPQoS Notes:
6412  * Once we have determined the client, invoke IPPF processing.
6413  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6414  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6415  * ip_policy will be false.
6416  *
6417  * Zones notes:
6418  * Currently only applications in the global zone can create raw sockets for
6419  * protocols other than ICMP. So unlike the broadcast / multicast case of
6420  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6421  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6422  */
6423 static void
6424 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6425     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6426     zoneid_t zoneid)
6427 {
6428 	queue_t	*rq;
6429 	mblk_t	*mp1, *first_mp1;
6430 	uint_t	protocol = ipha->ipha_protocol;
6431 	ipaddr_t dst;
6432 	boolean_t one_only;
6433 	mblk_t *first_mp = mp;
6434 	boolean_t secure;
6435 	uint32_t ill_index;
6436 	conn_t	*connp, *first_connp, *next_connp;
6437 	connf_t	*connfp;
6438 	boolean_t shared_addr;
6439 	mib2_ipIfStatsEntry_t *mibptr;
6440 	ip_stack_t *ipst = recv_ill->ill_ipst;
6441 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6442 
6443 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6444 	if (mctl_present) {
6445 		mp = first_mp->b_cont;
6446 		secure = ipsec_in_is_secure(first_mp);
6447 		ASSERT(mp != NULL);
6448 	} else {
6449 		secure = B_FALSE;
6450 	}
6451 	dst = ipha->ipha_dst;
6452 	/*
6453 	 * If the packet was tunneled and not multicast we only send to it
6454 	 * the first match.
6455 	 */
6456 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6457 	    !CLASSD(dst));
6458 
6459 	shared_addr = (zoneid == ALL_ZONES);
6460 	if (shared_addr) {
6461 		/*
6462 		 * We don't allow multilevel ports for raw IP, so no need to
6463 		 * check for that here.
6464 		 */
6465 		zoneid = tsol_packet_to_zoneid(mp);
6466 	}
6467 
6468 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6469 	mutex_enter(&connfp->connf_lock);
6470 	connp = connfp->connf_head;
6471 	for (connp = connfp->connf_head; connp != NULL;
6472 	    connp = connp->conn_next) {
6473 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6474 		    zoneid) &&
6475 		    (!is_system_labeled() ||
6476 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6477 		    connp))) {
6478 			break;
6479 		}
6480 	}
6481 
6482 	if (connp == NULL || connp->conn_upq == NULL) {
6483 		/*
6484 		 * No one bound to these addresses.  Is
6485 		 * there a client that wants all
6486 		 * unclaimed datagrams?
6487 		 */
6488 		mutex_exit(&connfp->connf_lock);
6489 		/*
6490 		 * Check for IPPROTO_ENCAP...
6491 		 */
6492 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6493 			/*
6494 			 * If an IPsec mblk is here on a multicast
6495 			 * tunnel (using ip_mroute stuff), check policy here,
6496 			 * THEN ship off to ip_mroute_decap().
6497 			 *
6498 			 * BTW,  If I match a configured IP-in-IP
6499 			 * tunnel, this path will not be reached, and
6500 			 * ip_mroute_decap will never be called.
6501 			 */
6502 			first_mp = ipsec_check_global_policy(first_mp, connp,
6503 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6504 			if (first_mp != NULL) {
6505 				if (mctl_present)
6506 					freeb(first_mp);
6507 				ip_mroute_decap(q, mp, ill);
6508 			} /* Else we already freed everything! */
6509 		} else {
6510 			/*
6511 			 * Otherwise send an ICMP protocol unreachable.
6512 			 */
6513 			if (ip_fanout_send_icmp(q, first_mp, flags,
6514 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6515 			    mctl_present, zoneid, ipst)) {
6516 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6517 			}
6518 		}
6519 		return;
6520 	}
6521 	CONN_INC_REF(connp);
6522 	first_connp = connp;
6523 
6524 	/*
6525 	 * Only send message to one tunnel driver by immediately
6526 	 * terminating the loop.
6527 	 */
6528 	connp = one_only ? NULL : connp->conn_next;
6529 
6530 	for (;;) {
6531 		while (connp != NULL) {
6532 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6533 			    flags, zoneid) &&
6534 			    (!is_system_labeled() ||
6535 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6536 			    shared_addr, connp)))
6537 				break;
6538 			connp = connp->conn_next;
6539 		}
6540 
6541 		/*
6542 		 * Copy the packet.
6543 		 */
6544 		if (connp == NULL || connp->conn_upq == NULL ||
6545 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6546 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6547 			/*
6548 			 * No more interested clients or memory
6549 			 * allocation failed
6550 			 */
6551 			connp = first_connp;
6552 			break;
6553 		}
6554 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6555 		CONN_INC_REF(connp);
6556 		mutex_exit(&connfp->connf_lock);
6557 		rq = connp->conn_rq;
6558 		if (!canputnext(rq)) {
6559 			if (flags & IP_FF_RAWIP) {
6560 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6561 			} else {
6562 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6563 			}
6564 
6565 			freemsg(first_mp1);
6566 		} else {
6567 			/*
6568 			 * Don't enforce here if we're an actual tunnel -
6569 			 * let "tun" do it instead.
6570 			 */
6571 			if (!IPCL_IS_IPTUN(connp) &&
6572 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6573 			    secure)) {
6574 				first_mp1 = ipsec_check_inbound_policy
6575 				    (first_mp1, connp, ipha, NULL,
6576 				    mctl_present);
6577 			}
6578 			if (first_mp1 != NULL) {
6579 				int in_flags = 0;
6580 				/*
6581 				 * ip_fanout_proto also gets called from
6582 				 * icmp_inbound_error_fanout, in which case
6583 				 * the msg type is M_CTL.  Don't add info
6584 				 * in this case for the time being. In future
6585 				 * when there is a need for knowing the
6586 				 * inbound iface index for ICMP error msgs,
6587 				 * then this can be changed.
6588 				 */
6589 				if (connp->conn_recvif)
6590 					in_flags = IPF_RECVIF;
6591 				/*
6592 				 * The ULP may support IP_RECVPKTINFO for both
6593 				 * IP v4 and v6 so pass the appropriate argument
6594 				 * based on conn IP version.
6595 				 */
6596 				if (connp->conn_ip_recvpktinfo) {
6597 					if (connp->conn_af_isv6) {
6598 						/*
6599 						 * V6 only needs index
6600 						 */
6601 						in_flags |= IPF_RECVIF;
6602 					} else {
6603 						/*
6604 						 * V4 needs index +
6605 						 * matching address.
6606 						 */
6607 						in_flags |= IPF_RECVADDR;
6608 					}
6609 				}
6610 				if ((in_flags != 0) &&
6611 				    (mp->b_datap->db_type != M_CTL)) {
6612 					/*
6613 					 * the actual data will be
6614 					 * contained in b_cont upon
6615 					 * successful return of the
6616 					 * following call else
6617 					 * original mblk is returned
6618 					 */
6619 					ASSERT(recv_ill != NULL);
6620 					mp1 = ip_add_info(mp1, recv_ill,
6621 					    in_flags, IPCL_ZONEID(connp), ipst);
6622 				}
6623 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6624 				if (mctl_present)
6625 					freeb(first_mp1);
6626 				putnext(rq, mp1);
6627 			}
6628 		}
6629 		mutex_enter(&connfp->connf_lock);
6630 		/* Follow the next pointer before releasing the conn. */
6631 		next_connp = connp->conn_next;
6632 		CONN_DEC_REF(connp);
6633 		connp = next_connp;
6634 	}
6635 
6636 	/* Last one.  Send it upstream. */
6637 	mutex_exit(&connfp->connf_lock);
6638 
6639 	/*
6640 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6641 	 * will be set to false.
6642 	 */
6643 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6644 		ill_index = ill->ill_phyint->phyint_ifindex;
6645 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6646 		if (mp == NULL) {
6647 			CONN_DEC_REF(connp);
6648 			if (mctl_present) {
6649 				freeb(first_mp);
6650 			}
6651 			return;
6652 		}
6653 	}
6654 
6655 	rq = connp->conn_rq;
6656 	if (!canputnext(rq)) {
6657 		if (flags & IP_FF_RAWIP) {
6658 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6659 		} else {
6660 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6661 		}
6662 
6663 		freemsg(first_mp);
6664 	} else {
6665 		if (IPCL_IS_IPTUN(connp)) {
6666 			/*
6667 			 * Tunneled packet.  We enforce policy in the tunnel
6668 			 * module itself.
6669 			 *
6670 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6671 			 * a policy check.
6672 			 */
6673 			putnext(rq, first_mp);
6674 			CONN_DEC_REF(connp);
6675 			return;
6676 		}
6677 
6678 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6679 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6680 			    ipha, NULL, mctl_present);
6681 		}
6682 
6683 		if (first_mp != NULL) {
6684 			int in_flags = 0;
6685 
6686 			/*
6687 			 * ip_fanout_proto also gets called
6688 			 * from icmp_inbound_error_fanout, in
6689 			 * which case the msg type is M_CTL.
6690 			 * Don't add info in this case for time
6691 			 * being. In future when there is a
6692 			 * need for knowing the inbound iface
6693 			 * index for ICMP error msgs, then this
6694 			 * can be changed
6695 			 */
6696 			if (connp->conn_recvif)
6697 				in_flags = IPF_RECVIF;
6698 			if (connp->conn_ip_recvpktinfo) {
6699 				if (connp->conn_af_isv6) {
6700 					/*
6701 					 * V6 only needs index
6702 					 */
6703 					in_flags |= IPF_RECVIF;
6704 				} else {
6705 					/*
6706 					 * V4 needs index +
6707 					 * matching address.
6708 					 */
6709 					in_flags |= IPF_RECVADDR;
6710 				}
6711 			}
6712 			if ((in_flags != 0) &&
6713 			    (mp->b_datap->db_type != M_CTL)) {
6714 
6715 				/*
6716 				 * the actual data will be contained in
6717 				 * b_cont upon successful return
6718 				 * of the following call else original
6719 				 * mblk is returned
6720 				 */
6721 				ASSERT(recv_ill != NULL);
6722 				mp = ip_add_info(mp, recv_ill,
6723 				    in_flags, IPCL_ZONEID(connp), ipst);
6724 			}
6725 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6726 			putnext(rq, mp);
6727 			if (mctl_present)
6728 				freeb(first_mp);
6729 		}
6730 	}
6731 	CONN_DEC_REF(connp);
6732 }
6733 
6734 /*
6735  * Fanout for TCP packets
6736  * The caller puts <fport, lport> in the ports parameter.
6737  *
6738  * IPQoS Notes
6739  * Before sending it to the client, invoke IPPF processing.
6740  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6741  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6742  * ip_policy is false.
6743  */
6744 static void
6745 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6746     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6747 {
6748 	mblk_t  *first_mp;
6749 	boolean_t secure;
6750 	uint32_t ill_index;
6751 	int	ip_hdr_len;
6752 	tcph_t	*tcph;
6753 	boolean_t syn_present = B_FALSE;
6754 	conn_t	*connp;
6755 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6756 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6757 
6758 	ASSERT(recv_ill != NULL);
6759 
6760 	first_mp = mp;
6761 	if (mctl_present) {
6762 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6763 		mp = first_mp->b_cont;
6764 		secure = ipsec_in_is_secure(first_mp);
6765 		ASSERT(mp != NULL);
6766 	} else {
6767 		secure = B_FALSE;
6768 	}
6769 
6770 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6771 
6772 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6773 	    zoneid, ipst)) == NULL) {
6774 		/*
6775 		 * No connected connection or listener. Send a
6776 		 * TH_RST via tcp_xmit_listeners_reset.
6777 		 */
6778 
6779 		/* Initiate IPPf processing, if needed. */
6780 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6781 			uint32_t ill_index;
6782 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6783 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6784 			if (first_mp == NULL)
6785 				return;
6786 		}
6787 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6788 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6789 		    zoneid));
6790 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6791 		    ipst->ips_netstack->netstack_tcp, NULL);
6792 		return;
6793 	}
6794 
6795 	/*
6796 	 * Allocate the SYN for the TCP connection here itself
6797 	 */
6798 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6799 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6800 		if (IPCL_IS_TCP(connp)) {
6801 			squeue_t *sqp;
6802 
6803 			/*
6804 			 * For fused tcp loopback, assign the eager's
6805 			 * squeue to be that of the active connect's.
6806 			 * Note that we don't check for IP_FF_LOOPBACK
6807 			 * here since this routine gets called only
6808 			 * for loopback (unlike the IPv6 counterpart).
6809 			 */
6810 			ASSERT(Q_TO_CONN(q) != NULL);
6811 			if (do_tcp_fusion &&
6812 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6813 			    !secure &&
6814 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6815 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6816 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6817 				sqp = Q_TO_CONN(q)->conn_sqp;
6818 			} else {
6819 				sqp = IP_SQUEUE_GET(lbolt);
6820 			}
6821 
6822 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6823 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6824 			syn_present = B_TRUE;
6825 		}
6826 	}
6827 
6828 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6829 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6830 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6831 		if ((flags & TH_RST) || (flags & TH_URG)) {
6832 			CONN_DEC_REF(connp);
6833 			freemsg(first_mp);
6834 			return;
6835 		}
6836 		if (flags & TH_ACK) {
6837 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6838 			    ipst->ips_netstack->netstack_tcp, connp);
6839 			CONN_DEC_REF(connp);
6840 			return;
6841 		}
6842 
6843 		CONN_DEC_REF(connp);
6844 		freemsg(first_mp);
6845 		return;
6846 	}
6847 
6848 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6849 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6850 		    NULL, mctl_present);
6851 		if (first_mp == NULL) {
6852 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6853 			CONN_DEC_REF(connp);
6854 			return;
6855 		}
6856 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6857 			ASSERT(syn_present);
6858 			if (mctl_present) {
6859 				ASSERT(first_mp != mp);
6860 				first_mp->b_datap->db_struioflag |=
6861 				    STRUIO_POLICY;
6862 			} else {
6863 				ASSERT(first_mp == mp);
6864 				mp->b_datap->db_struioflag &=
6865 				    ~STRUIO_EAGER;
6866 				mp->b_datap->db_struioflag |=
6867 				    STRUIO_POLICY;
6868 			}
6869 		} else {
6870 			/*
6871 			 * Discard first_mp early since we're dealing with a
6872 			 * fully-connected conn_t and tcp doesn't do policy in
6873 			 * this case.
6874 			 */
6875 			if (mctl_present) {
6876 				freeb(first_mp);
6877 				mctl_present = B_FALSE;
6878 			}
6879 			first_mp = mp;
6880 		}
6881 	}
6882 
6883 	/*
6884 	 * Initiate policy processing here if needed. If we get here from
6885 	 * icmp_inbound_error_fanout, ip_policy is false.
6886 	 */
6887 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6888 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6889 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6890 		if (mp == NULL) {
6891 			CONN_DEC_REF(connp);
6892 			if (mctl_present)
6893 				freeb(first_mp);
6894 			return;
6895 		} else if (mctl_present) {
6896 			ASSERT(first_mp != mp);
6897 			first_mp->b_cont = mp;
6898 		} else {
6899 			first_mp = mp;
6900 		}
6901 	}
6902 
6903 
6904 
6905 	/* Handle socket options. */
6906 	if (!syn_present &&
6907 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6908 		/* Add header */
6909 		ASSERT(recv_ill != NULL);
6910 		/*
6911 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6912 		 * IPF_RECVIF.
6913 		 */
6914 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6915 		    ipst);
6916 		if (mp == NULL) {
6917 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6918 			CONN_DEC_REF(connp);
6919 			if (mctl_present)
6920 				freeb(first_mp);
6921 			return;
6922 		} else if (mctl_present) {
6923 			/*
6924 			 * ip_add_info might return a new mp.
6925 			 */
6926 			ASSERT(first_mp != mp);
6927 			first_mp->b_cont = mp;
6928 		} else {
6929 			first_mp = mp;
6930 		}
6931 	}
6932 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6933 	if (IPCL_IS_TCP(connp)) {
6934 		/* do not drain, certain use cases can blow the stack */
6935 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6936 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6937 	} else {
6938 		putnext(connp->conn_rq, first_mp);
6939 		CONN_DEC_REF(connp);
6940 	}
6941 }
6942 
6943 /*
6944  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6945  * pass it along to ESP if the SPI is non-zero.
6946  *
6947  * One of three things can happen, all of which affect the passed-in mblk:
6948  *
6949  * 1.) The packet is stock UDP and has had its zero-SPI stripped.  Return TRUE.
6950  *     (NOTE:  ICMP messages that go through here just get returned.)
6951  *
6952  * 2.) The packet is ESP-in-UDP, has been transformed into an equivalent
6953  *     ESP packet, and is passed along to ESP.  Return FALSE.
6954  *
6955  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6956  */
6957 static boolean_t
6958 zero_spi_check(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
6959     ill_t *recv_ill, ipsec_stack_t *ipss)
6960 {
6961 	int shift, plen, iph_len = IPH_HDR_LENGTH(ipha);
6962 	udpha_t *udpha;
6963 	uint32_t *spi;
6964 	uint8_t *orptr;
6965 	boolean_t udp_pkt, free_ire;
6966 
6967 	if (DB_TYPE(mp) == M_CTL) {
6968 		/*
6969 		 * ICMP message with UDP inside.  Don't bother stripping, just
6970 		 * send it up.
6971 		 *
6972 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6973 		 * to ignore errors set by ICMP anyway ('cause they might be
6974 		 * forged), but that's the app's decision, not ours.
6975 		 */
6976 
6977 		/* Bunch of reality checks for DEBUG kernels... */
6978 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6979 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6980 		ASSERT((uint8_t *)ipha != mp->b_rptr);
6981 
6982 		return (B_TRUE);
6983 	}
6984 
6985 	ASSERT((uint8_t *)ipha == mp->b_rptr);
6986 	plen = ntohs(ipha->ipha_length);
6987 
6988 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6989 		/*
6990 		 * Most likely a keepalive for the benefit of an intervening
6991 		 * NAT.  These aren't for us, per se, so drop it.
6992 		 *
6993 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6994 		 * byte packets (keepalives are 1-byte), but we'll drop them
6995 		 * also.
6996 		 */
6997 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6998 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6999 		return (B_FALSE);
7000 	}
7001 
7002 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7003 		mblk_t *tmp = msgpullup(mp, -1);
7004 
7005 		/* might as well pull it all up - it might be ESP. */
7006 		if (tmp == NULL) {
7007 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7008 			    DROPPER(ipss, ipds_esp_nomem),
7009 			    &ipss->ipsec_dropper);
7010 			return (B_FALSE);
7011 		}
7012 		freemsg(mp);
7013 		mp = tmp;
7014 	}
7015 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7016 	if (*spi == 0) {
7017 		/* UDP packet - remove 0-spi. */
7018 		shift = sizeof (uint32_t);
7019 	} else {
7020 		/* ESP-in-UDP packet - reduce to ESP. */
7021 		ipha->ipha_protocol = IPPROTO_ESP;
7022 		shift = sizeof (udpha_t);
7023 	}
7024 
7025 	/* Fix IP header */
7026 	ipha->ipha_length = htons(plen - shift);
7027 	ipha->ipha_hdr_checksum = 0;
7028 
7029 	orptr = mp->b_rptr;
7030 	mp->b_rptr += shift;
7031 
7032 	if (*spi == 0) {
7033 		ASSERT((uint8_t *)ipha == orptr);
7034 		udpha = (udpha_t *)(orptr + iph_len);
7035 		udpha->uha_length = htons(plen - shift - iph_len);
7036 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7037 		udp_pkt = B_TRUE;
7038 	} else {
7039 		udp_pkt = B_FALSE;
7040 	}
7041 	ovbcopy(orptr, orptr + shift, iph_len);
7042 	if (!udp_pkt) /* Punt up for ESP processing. */ {
7043 		ipha = (ipha_t *)(orptr + shift);
7044 
7045 		free_ire = (ire == NULL);
7046 		if (free_ire) {
7047 			/* Re-acquire ire. */
7048 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7049 			    ipss->ipsec_netstack->netstack_ip);
7050 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7051 				if (ire != NULL)
7052 					ire_refrele(ire);
7053 				/*
7054 				 * Do a regular freemsg(), as this is an IP
7055 				 * error (no local route) not an IPsec one.
7056 				 */
7057 				freemsg(mp);
7058 			}
7059 		}
7060 
7061 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
7062 		if (free_ire)
7063 			ire_refrele(ire);
7064 	}
7065 
7066 	return (udp_pkt);
7067 }
7068 
7069 /*
7070  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7071  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7072  * Caller is responsible for dropping references to the conn, and freeing
7073  * first_mp.
7074  *
7075  * IPQoS Notes
7076  * Before sending it to the client, invoke IPPF processing. Policy processing
7077  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7078  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7079  * ip_wput_local, ip_policy is false.
7080  */
7081 static void
7082 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7083     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7084     boolean_t ip_policy)
7085 {
7086 	boolean_t	mctl_present = (first_mp != NULL);
7087 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7088 	uint32_t	ill_index;
7089 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7090 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7091 
7092 	ASSERT(ill != NULL);
7093 
7094 	if (mctl_present)
7095 		first_mp->b_cont = mp;
7096 	else
7097 		first_mp = mp;
7098 
7099 	if (CONN_UDP_FLOWCTLD(connp)) {
7100 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7101 		freemsg(first_mp);
7102 		return;
7103 	}
7104 
7105 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7106 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7107 		    NULL, mctl_present);
7108 		if (first_mp == NULL) {
7109 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7110 			return;	/* Freed by ipsec_check_inbound_policy(). */
7111 		}
7112 	}
7113 	if (mctl_present)
7114 		freeb(first_mp);
7115 
7116 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7117 	if (connp->conn_udp->udp_nat_t_endpoint) {
7118 		if (mctl_present) {
7119 			/* mctl_present *shouldn't* happen. */
7120 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7121 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7122 			    &ipss->ipsec_dropper);
7123 			return;
7124 		}
7125 
7126 		if (!zero_spi_check(ill->ill_rq, mp, ipha, NULL, recv_ill,
7127 		    ipss)) {
7128 			return;
7129 		}
7130 	}
7131 
7132 	/* Handle options. */
7133 	if (connp->conn_recvif)
7134 		in_flags = IPF_RECVIF;
7135 	/*
7136 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7137 	 * passed to ip_add_info is based on IP version of connp.
7138 	 */
7139 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7140 		if (connp->conn_af_isv6) {
7141 			/*
7142 			 * V6 only needs index
7143 			 */
7144 			in_flags |= IPF_RECVIF;
7145 		} else {
7146 			/*
7147 			 * V4 needs index + matching address.
7148 			 */
7149 			in_flags |= IPF_RECVADDR;
7150 		}
7151 	}
7152 
7153 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7154 		in_flags |= IPF_RECVSLLA;
7155 
7156 	/*
7157 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7158 	 * freed if the packet is dropped. The caller will do so.
7159 	 */
7160 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7161 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7162 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7163 		if (mp == NULL) {
7164 			return;
7165 		}
7166 	}
7167 	if ((in_flags != 0) &&
7168 	    (mp->b_datap->db_type != M_CTL)) {
7169 		/*
7170 		 * The actual data will be contained in b_cont
7171 		 * upon successful return of the following call
7172 		 * else original mblk is returned
7173 		 */
7174 		ASSERT(recv_ill != NULL);
7175 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7176 		    ipst);
7177 	}
7178 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7179 	/* Send it upstream */
7180 	CONN_UDP_RECV(connp, mp);
7181 }
7182 
7183 /*
7184  * Fanout for UDP packets.
7185  * The caller puts <fport, lport> in the ports parameter.
7186  *
7187  * If SO_REUSEADDR is set all multicast and broadcast packets
7188  * will be delivered to all streams bound to the same port.
7189  *
7190  * Zones notes:
7191  * Multicast and broadcast packets will be distributed to streams in all zones.
7192  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7193  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7194  * packets. To maintain this behavior with multiple zones, the conns are grouped
7195  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7196  * each zone. If unset, all the following conns in the same zone are skipped.
7197  */
7198 static void
7199 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7200     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7201     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7202 {
7203 	uint32_t	dstport, srcport;
7204 	ipaddr_t	dst;
7205 	mblk_t		*first_mp;
7206 	boolean_t	secure;
7207 	in6_addr_t	v6src;
7208 	conn_t		*connp;
7209 	connf_t		*connfp;
7210 	conn_t		*first_connp;
7211 	conn_t		*next_connp;
7212 	mblk_t		*mp1, *first_mp1;
7213 	ipaddr_t	src;
7214 	zoneid_t	last_zoneid;
7215 	boolean_t	reuseaddr;
7216 	boolean_t	shared_addr;
7217 	ip_stack_t	*ipst;
7218 
7219 	ASSERT(recv_ill != NULL);
7220 	ipst = recv_ill->ill_ipst;
7221 
7222 	first_mp = mp;
7223 	if (mctl_present) {
7224 		mp = first_mp->b_cont;
7225 		first_mp->b_cont = NULL;
7226 		secure = ipsec_in_is_secure(first_mp);
7227 		ASSERT(mp != NULL);
7228 	} else {
7229 		first_mp = NULL;
7230 		secure = B_FALSE;
7231 	}
7232 
7233 	/* Extract ports in net byte order */
7234 	dstport = htons(ntohl(ports) & 0xFFFF);
7235 	srcport = htons(ntohl(ports) >> 16);
7236 	dst = ipha->ipha_dst;
7237 	src = ipha->ipha_src;
7238 
7239 	shared_addr = (zoneid == ALL_ZONES);
7240 	if (shared_addr) {
7241 		/*
7242 		 * No need to handle exclusive-stack zones since ALL_ZONES
7243 		 * only applies to the shared stack.
7244 		 */
7245 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7246 		if (zoneid == ALL_ZONES)
7247 			zoneid = tsol_packet_to_zoneid(mp);
7248 	}
7249 
7250 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7251 	mutex_enter(&connfp->connf_lock);
7252 	connp = connfp->connf_head;
7253 	if (!broadcast && !CLASSD(dst)) {
7254 		/*
7255 		 * Not broadcast or multicast. Send to the one (first)
7256 		 * client we find. No need to check conn_wantpacket()
7257 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7258 		 * IPv4 unicast packets.
7259 		 */
7260 		while ((connp != NULL) &&
7261 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7262 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7263 			connp = connp->conn_next;
7264 		}
7265 
7266 		if (connp == NULL || connp->conn_upq == NULL)
7267 			goto notfound;
7268 
7269 		if (is_system_labeled() &&
7270 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7271 		    connp))
7272 			goto notfound;
7273 
7274 		CONN_INC_REF(connp);
7275 		mutex_exit(&connfp->connf_lock);
7276 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7277 		    flags, recv_ill, ip_policy);
7278 		IP_STAT(ipst, ip_udp_fannorm);
7279 		CONN_DEC_REF(connp);
7280 		return;
7281 	}
7282 
7283 	/*
7284 	 * Broadcast and multicast case
7285 	 *
7286 	 * Need to check conn_wantpacket().
7287 	 * If SO_REUSEADDR has been set on the first we send the
7288 	 * packet to all clients that have joined the group and
7289 	 * match the port.
7290 	 */
7291 
7292 	while (connp != NULL) {
7293 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7294 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7295 		    (!is_system_labeled() ||
7296 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7297 		    connp)))
7298 			break;
7299 		connp = connp->conn_next;
7300 	}
7301 
7302 	if (connp == NULL || connp->conn_upq == NULL)
7303 		goto notfound;
7304 
7305 	first_connp = connp;
7306 	/*
7307 	 * When SO_REUSEADDR is not set, send the packet only to the first
7308 	 * matching connection in its zone by keeping track of the zoneid.
7309 	 */
7310 	reuseaddr = first_connp->conn_reuseaddr;
7311 	last_zoneid = first_connp->conn_zoneid;
7312 
7313 	CONN_INC_REF(connp);
7314 	connp = connp->conn_next;
7315 	for (;;) {
7316 		while (connp != NULL) {
7317 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7318 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7319 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7320 			    (!is_system_labeled() ||
7321 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7322 			    shared_addr, connp)))
7323 				break;
7324 			connp = connp->conn_next;
7325 		}
7326 		/*
7327 		 * Just copy the data part alone. The mctl part is
7328 		 * needed just for verifying policy and it is never
7329 		 * sent up.
7330 		 */
7331 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7332 		    ((mp1 = copymsg(mp)) == NULL))) {
7333 			/*
7334 			 * No more interested clients or memory
7335 			 * allocation failed
7336 			 */
7337 			connp = first_connp;
7338 			break;
7339 		}
7340 		if (connp->conn_zoneid != last_zoneid) {
7341 			/*
7342 			 * Update the zoneid so that the packet isn't sent to
7343 			 * any more conns in the same zone unless SO_REUSEADDR
7344 			 * is set.
7345 			 */
7346 			reuseaddr = connp->conn_reuseaddr;
7347 			last_zoneid = connp->conn_zoneid;
7348 		}
7349 		if (first_mp != NULL) {
7350 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7351 			    ipsec_info_type == IPSEC_IN);
7352 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7353 			    ipst->ips_netstack);
7354 			if (first_mp1 == NULL) {
7355 				freemsg(mp1);
7356 				connp = first_connp;
7357 				break;
7358 			}
7359 		} else {
7360 			first_mp1 = NULL;
7361 		}
7362 		CONN_INC_REF(connp);
7363 		mutex_exit(&connfp->connf_lock);
7364 		/*
7365 		 * IPQoS notes: We don't send the packet for policy
7366 		 * processing here, will do it for the last one (below).
7367 		 * i.e. we do it per-packet now, but if we do policy
7368 		 * processing per-conn, then we would need to do it
7369 		 * here too.
7370 		 */
7371 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7372 		    ipha, flags, recv_ill, B_FALSE);
7373 		mutex_enter(&connfp->connf_lock);
7374 		/* Follow the next pointer before releasing the conn. */
7375 		next_connp = connp->conn_next;
7376 		IP_STAT(ipst, ip_udp_fanmb);
7377 		CONN_DEC_REF(connp);
7378 		connp = next_connp;
7379 	}
7380 
7381 	/* Last one.  Send it upstream. */
7382 	mutex_exit(&connfp->connf_lock);
7383 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7384 	    recv_ill, ip_policy);
7385 	IP_STAT(ipst, ip_udp_fanmb);
7386 	CONN_DEC_REF(connp);
7387 	return;
7388 
7389 notfound:
7390 
7391 	mutex_exit(&connfp->connf_lock);
7392 	IP_STAT(ipst, ip_udp_fanothers);
7393 	/*
7394 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7395 	 * have already been matched above, since they live in the IPv4
7396 	 * fanout tables. This implies we only need to
7397 	 * check for IPv6 in6addr_any endpoints here.
7398 	 * Thus we compare using ipv6_all_zeros instead of the destination
7399 	 * address, except for the multicast group membership lookup which
7400 	 * uses the IPv4 destination.
7401 	 */
7402 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7403 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7404 	mutex_enter(&connfp->connf_lock);
7405 	connp = connfp->connf_head;
7406 	if (!broadcast && !CLASSD(dst)) {
7407 		while (connp != NULL) {
7408 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7409 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7410 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7411 			    !connp->conn_ipv6_v6only)
7412 				break;
7413 			connp = connp->conn_next;
7414 		}
7415 
7416 		if (connp != NULL && is_system_labeled() &&
7417 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7418 		    connp))
7419 			connp = NULL;
7420 
7421 		if (connp == NULL || connp->conn_upq == NULL) {
7422 			/*
7423 			 * No one bound to this port.  Is
7424 			 * there a client that wants all
7425 			 * unclaimed datagrams?
7426 			 */
7427 			mutex_exit(&connfp->connf_lock);
7428 
7429 			if (mctl_present)
7430 				first_mp->b_cont = mp;
7431 			else
7432 				first_mp = mp;
7433 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7434 			    connf_head != NULL) {
7435 				ip_fanout_proto(q, first_mp, ill, ipha,
7436 				    flags | IP_FF_RAWIP, mctl_present,
7437 				    ip_policy, recv_ill, zoneid);
7438 			} else {
7439 				if (ip_fanout_send_icmp(q, first_mp, flags,
7440 				    ICMP_DEST_UNREACHABLE,
7441 				    ICMP_PORT_UNREACHABLE,
7442 				    mctl_present, zoneid, ipst)) {
7443 					BUMP_MIB(ill->ill_ip_mib,
7444 					    udpIfStatsNoPorts);
7445 				}
7446 			}
7447 			return;
7448 		}
7449 
7450 		CONN_INC_REF(connp);
7451 		mutex_exit(&connfp->connf_lock);
7452 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7453 		    flags, recv_ill, ip_policy);
7454 		CONN_DEC_REF(connp);
7455 		return;
7456 	}
7457 	/*
7458 	 * IPv4 multicast packet being delivered to an AF_INET6
7459 	 * in6addr_any endpoint.
7460 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7461 	 * and not conn_wantpacket_v6() since any multicast membership is
7462 	 * for an IPv4-mapped multicast address.
7463 	 * The packet is sent to all clients in all zones that have joined the
7464 	 * group and match the port.
7465 	 */
7466 	while (connp != NULL) {
7467 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7468 		    srcport, v6src) &&
7469 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7470 		    (!is_system_labeled() ||
7471 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7472 		    connp)))
7473 			break;
7474 		connp = connp->conn_next;
7475 	}
7476 
7477 	if (connp == NULL || connp->conn_upq == NULL) {
7478 		/*
7479 		 * No one bound to this port.  Is
7480 		 * there a client that wants all
7481 		 * unclaimed datagrams?
7482 		 */
7483 		mutex_exit(&connfp->connf_lock);
7484 
7485 		if (mctl_present)
7486 			first_mp->b_cont = mp;
7487 		else
7488 			first_mp = mp;
7489 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7490 		    NULL) {
7491 			ip_fanout_proto(q, first_mp, ill, ipha,
7492 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7493 			    recv_ill, zoneid);
7494 		} else {
7495 			/*
7496 			 * We used to attempt to send an icmp error here, but
7497 			 * since this is known to be a multicast packet
7498 			 * and we don't send icmp errors in response to
7499 			 * multicast, just drop the packet and give up sooner.
7500 			 */
7501 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7502 			freemsg(first_mp);
7503 		}
7504 		return;
7505 	}
7506 
7507 	first_connp = connp;
7508 
7509 	CONN_INC_REF(connp);
7510 	connp = connp->conn_next;
7511 	for (;;) {
7512 		while (connp != NULL) {
7513 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7514 			    ipv6_all_zeros, srcport, v6src) &&
7515 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7516 			    (!is_system_labeled() ||
7517 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7518 			    shared_addr, connp)))
7519 				break;
7520 			connp = connp->conn_next;
7521 		}
7522 		/*
7523 		 * Just copy the data part alone. The mctl part is
7524 		 * needed just for verifying policy and it is never
7525 		 * sent up.
7526 		 */
7527 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7528 		    ((mp1 = copymsg(mp)) == NULL))) {
7529 			/*
7530 			 * No more intested clients or memory
7531 			 * allocation failed
7532 			 */
7533 			connp = first_connp;
7534 			break;
7535 		}
7536 		if (first_mp != NULL) {
7537 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7538 			    ipsec_info_type == IPSEC_IN);
7539 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7540 			    ipst->ips_netstack);
7541 			if (first_mp1 == NULL) {
7542 				freemsg(mp1);
7543 				connp = first_connp;
7544 				break;
7545 			}
7546 		} else {
7547 			first_mp1 = NULL;
7548 		}
7549 		CONN_INC_REF(connp);
7550 		mutex_exit(&connfp->connf_lock);
7551 		/*
7552 		 * IPQoS notes: We don't send the packet for policy
7553 		 * processing here, will do it for the last one (below).
7554 		 * i.e. we do it per-packet now, but if we do policy
7555 		 * processing per-conn, then we would need to do it
7556 		 * here too.
7557 		 */
7558 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7559 		    ipha, flags, recv_ill, B_FALSE);
7560 		mutex_enter(&connfp->connf_lock);
7561 		/* Follow the next pointer before releasing the conn. */
7562 		next_connp = connp->conn_next;
7563 		CONN_DEC_REF(connp);
7564 		connp = next_connp;
7565 	}
7566 
7567 	/* Last one.  Send it upstream. */
7568 	mutex_exit(&connfp->connf_lock);
7569 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7570 	    recv_ill, ip_policy);
7571 	CONN_DEC_REF(connp);
7572 }
7573 
7574 /*
7575  * Complete the ip_wput header so that it
7576  * is possible to generate ICMP
7577  * errors.
7578  */
7579 int
7580 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7581 {
7582 	ire_t *ire;
7583 
7584 	if (ipha->ipha_src == INADDR_ANY) {
7585 		ire = ire_lookup_local(zoneid, ipst);
7586 		if (ire == NULL) {
7587 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7588 			return (1);
7589 		}
7590 		ipha->ipha_src = ire->ire_addr;
7591 		ire_refrele(ire);
7592 	}
7593 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7594 	ipha->ipha_hdr_checksum = 0;
7595 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7596 	return (0);
7597 }
7598 
7599 /*
7600  * Nobody should be sending
7601  * packets up this stream
7602  */
7603 static void
7604 ip_lrput(queue_t *q, mblk_t *mp)
7605 {
7606 	mblk_t *mp1;
7607 
7608 	switch (mp->b_datap->db_type) {
7609 	case M_FLUSH:
7610 		/* Turn around */
7611 		if (*mp->b_rptr & FLUSHW) {
7612 			*mp->b_rptr &= ~FLUSHR;
7613 			qreply(q, mp);
7614 			return;
7615 		}
7616 		break;
7617 	}
7618 	/* Could receive messages that passed through ar_rput */
7619 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7620 		mp1->b_prev = mp1->b_next = NULL;
7621 	freemsg(mp);
7622 }
7623 
7624 /* Nobody should be sending packets down this stream */
7625 /* ARGSUSED */
7626 void
7627 ip_lwput(queue_t *q, mblk_t *mp)
7628 {
7629 	freemsg(mp);
7630 }
7631 
7632 /*
7633  * Move the first hop in any source route to ipha_dst and remove that part of
7634  * the source route.  Called by other protocols.  Errors in option formatting
7635  * are ignored - will be handled by ip_wput_options Return the final
7636  * destination (either ipha_dst or the last entry in a source route.)
7637  */
7638 ipaddr_t
7639 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7640 {
7641 	ipoptp_t	opts;
7642 	uchar_t		*opt;
7643 	uint8_t		optval;
7644 	uint8_t		optlen;
7645 	ipaddr_t	dst;
7646 	int		i;
7647 	ire_t		*ire;
7648 	ip_stack_t	*ipst = ns->netstack_ip;
7649 
7650 	ip2dbg(("ip_massage_options\n"));
7651 	dst = ipha->ipha_dst;
7652 	for (optval = ipoptp_first(&opts, ipha);
7653 	    optval != IPOPT_EOL;
7654 	    optval = ipoptp_next(&opts)) {
7655 		opt = opts.ipoptp_cur;
7656 		switch (optval) {
7657 			uint8_t off;
7658 		case IPOPT_SSRR:
7659 		case IPOPT_LSRR:
7660 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7661 				ip1dbg(("ip_massage_options: bad src route\n"));
7662 				break;
7663 			}
7664 			optlen = opts.ipoptp_len;
7665 			off = opt[IPOPT_OFFSET];
7666 			off--;
7667 		redo_srr:
7668 			if (optlen < IP_ADDR_LEN ||
7669 			    off > optlen - IP_ADDR_LEN) {
7670 				/* End of source route */
7671 				ip1dbg(("ip_massage_options: end of SR\n"));
7672 				break;
7673 			}
7674 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7675 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7676 			    ntohl(dst)));
7677 			/*
7678 			 * Check if our address is present more than
7679 			 * once as consecutive hops in source route.
7680 			 * XXX verify per-interface ip_forwarding
7681 			 * for source route?
7682 			 */
7683 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7684 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7685 			if (ire != NULL) {
7686 				ire_refrele(ire);
7687 				off += IP_ADDR_LEN;
7688 				goto redo_srr;
7689 			}
7690 			if (dst == htonl(INADDR_LOOPBACK)) {
7691 				ip1dbg(("ip_massage_options: loopback addr in "
7692 				    "source route!\n"));
7693 				break;
7694 			}
7695 			/*
7696 			 * Update ipha_dst to be the first hop and remove the
7697 			 * first hop from the source route (by overwriting
7698 			 * part of the option with NOP options).
7699 			 */
7700 			ipha->ipha_dst = dst;
7701 			/* Put the last entry in dst */
7702 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7703 			    3;
7704 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7705 
7706 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7707 			    ntohl(dst)));
7708 			/* Move down and overwrite */
7709 			opt[IP_ADDR_LEN] = opt[0];
7710 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7711 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7712 			for (i = 0; i < IP_ADDR_LEN; i++)
7713 				opt[i] = IPOPT_NOP;
7714 			break;
7715 		}
7716 	}
7717 	return (dst);
7718 }
7719 
7720 /*
7721  * Return the network mask
7722  * associated with the specified address.
7723  */
7724 ipaddr_t
7725 ip_net_mask(ipaddr_t addr)
7726 {
7727 	uchar_t	*up = (uchar_t *)&addr;
7728 	ipaddr_t mask = 0;
7729 	uchar_t	*maskp = (uchar_t *)&mask;
7730 
7731 #if defined(__i386) || defined(__amd64)
7732 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7733 #endif
7734 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7735 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7736 #endif
7737 	if (CLASSD(addr)) {
7738 		maskp[0] = 0xF0;
7739 		return (mask);
7740 	}
7741 	if (addr == 0)
7742 		return (0);
7743 	maskp[0] = 0xFF;
7744 	if ((up[0] & 0x80) == 0)
7745 		return (mask);
7746 
7747 	maskp[1] = 0xFF;
7748 	if ((up[0] & 0xC0) == 0x80)
7749 		return (mask);
7750 
7751 	maskp[2] = 0xFF;
7752 	if ((up[0] & 0xE0) == 0xC0)
7753 		return (mask);
7754 
7755 	/* Must be experimental or multicast, indicate as much */
7756 	return ((ipaddr_t)0);
7757 }
7758 
7759 /*
7760  * Select an ill for the packet by considering load spreading across
7761  * a different ill in the group if dst_ill is part of some group.
7762  */
7763 ill_t *
7764 ip_newroute_get_dst_ill(ill_t *dst_ill)
7765 {
7766 	ill_t *ill;
7767 
7768 	/*
7769 	 * We schedule irrespective of whether the source address is
7770 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7771 	 */
7772 	ill = illgrp_scheduler(dst_ill);
7773 	if (ill == NULL)
7774 		return (NULL);
7775 
7776 	/*
7777 	 * For groups with names ip_sioctl_groupname ensures that all
7778 	 * ills are of same type. For groups without names, ifgrp_insert
7779 	 * ensures this.
7780 	 */
7781 	ASSERT(dst_ill->ill_type == ill->ill_type);
7782 
7783 	return (ill);
7784 }
7785 
7786 /*
7787  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7788  */
7789 ill_t *
7790 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7791     ip_stack_t *ipst)
7792 {
7793 	ill_t *ret_ill;
7794 
7795 	ASSERT(ifindex != 0);
7796 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7797 	    ipst);
7798 	if (ret_ill == NULL ||
7799 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7800 		if (isv6) {
7801 			if (ill != NULL) {
7802 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7803 			} else {
7804 				BUMP_MIB(&ipst->ips_ip6_mib,
7805 				    ipIfStatsOutDiscards);
7806 			}
7807 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7808 			    "bad ifindex %d.\n", ifindex));
7809 		} else {
7810 			if (ill != NULL) {
7811 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7812 			} else {
7813 				BUMP_MIB(&ipst->ips_ip_mib,
7814 				    ipIfStatsOutDiscards);
7815 			}
7816 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7817 			    "bad ifindex %d.\n", ifindex));
7818 		}
7819 		if (ret_ill != NULL)
7820 			ill_refrele(ret_ill);
7821 		freemsg(first_mp);
7822 		return (NULL);
7823 	}
7824 
7825 	return (ret_ill);
7826 }
7827 
7828 /*
7829  * IPv4 -
7830  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7831  * out a packet to a destination address for which we do not have specific
7832  * (or sufficient) routing information.
7833  *
7834  * NOTE : These are the scopes of some of the variables that point at IRE,
7835  *	  which needs to be followed while making any future modifications
7836  *	  to avoid memory leaks.
7837  *
7838  *	- ire and sire are the entries looked up initially by
7839  *	  ire_ftable_lookup.
7840  *	- ipif_ire is used to hold the interface ire associated with
7841  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7842  *	  it before branching out to error paths.
7843  *	- save_ire is initialized before ire_create, so that ire returned
7844  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7845  *	  before breaking out of the switch.
7846  *
7847  *	Thus on failures, we have to REFRELE only ire and sire, if they
7848  *	are not NULL.
7849  */
7850 void
7851 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7852     zoneid_t zoneid, ip_stack_t *ipst)
7853 {
7854 	areq_t	*areq;
7855 	ipaddr_t gw = 0;
7856 	ire_t	*ire = NULL;
7857 	mblk_t	*res_mp;
7858 	ipaddr_t *addrp;
7859 	ipaddr_t nexthop_addr;
7860 	ipif_t  *src_ipif = NULL;
7861 	ill_t	*dst_ill = NULL;
7862 	ipha_t  *ipha;
7863 	ire_t	*sire = NULL;
7864 	mblk_t	*first_mp;
7865 	ire_t	*save_ire;
7866 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7867 	ushort_t ire_marks = 0;
7868 	boolean_t mctl_present;
7869 	ipsec_out_t *io;
7870 	mblk_t	*saved_mp;
7871 	ire_t	*first_sire = NULL;
7872 	mblk_t	*copy_mp = NULL;
7873 	mblk_t	*xmit_mp = NULL;
7874 	ipaddr_t save_dst;
7875 	uint32_t multirt_flags =
7876 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7877 	boolean_t multirt_is_resolvable;
7878 	boolean_t multirt_resolve_next;
7879 	boolean_t do_attach_ill = B_FALSE;
7880 	boolean_t ip_nexthop = B_FALSE;
7881 	tsol_ire_gw_secattr_t *attrp = NULL;
7882 	tsol_gcgrp_t *gcgrp = NULL;
7883 	tsol_gcgrp_addr_t ga;
7884 
7885 	if (ip_debug > 2) {
7886 		/* ip1dbg */
7887 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7888 	}
7889 
7890 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7891 	if (mctl_present) {
7892 		io = (ipsec_out_t *)first_mp->b_rptr;
7893 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7894 		ASSERT(zoneid == io->ipsec_out_zoneid);
7895 		ASSERT(zoneid != ALL_ZONES);
7896 	}
7897 
7898 	ipha = (ipha_t *)mp->b_rptr;
7899 
7900 	/* All multicast lookups come through ip_newroute_ipif() */
7901 	if (CLASSD(dst)) {
7902 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7903 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7904 		freemsg(first_mp);
7905 		return;
7906 	}
7907 
7908 	if (mctl_present && io->ipsec_out_attach_if) {
7909 		/* ip_grab_attach_ill returns a held ill */
7910 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7911 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7912 
7913 		/* Failure case frees things for us. */
7914 		if (attach_ill == NULL)
7915 			return;
7916 
7917 		/*
7918 		 * Check if we need an ire that will not be
7919 		 * looked up by anybody else i.e. HIDDEN.
7920 		 */
7921 		if (ill_is_probeonly(attach_ill))
7922 			ire_marks = IRE_MARK_HIDDEN;
7923 	}
7924 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7925 		ip_nexthop = B_TRUE;
7926 		nexthop_addr = io->ipsec_out_nexthop_addr;
7927 	}
7928 	/*
7929 	 * If this IRE is created for forwarding or it is not for
7930 	 * traffic for congestion controlled protocols, mark it as temporary.
7931 	 */
7932 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7933 		ire_marks |= IRE_MARK_TEMPORARY;
7934 
7935 	/*
7936 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7937 	 * chain until it gets the most specific information available.
7938 	 * For example, we know that there is no IRE_CACHE for this dest,
7939 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7940 	 * ire_ftable_lookup will look up the gateway, etc.
7941 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7942 	 * to the destination, of equal netmask length in the forward table,
7943 	 * will be recursively explored. If no information is available
7944 	 * for the final gateway of that route, we force the returned ire
7945 	 * to be equal to sire using MATCH_IRE_PARENT.
7946 	 * At least, in this case we have a starting point (in the buckets)
7947 	 * to look for other routes to the destination in the forward table.
7948 	 * This is actually used only for multirouting, where a list
7949 	 * of routes has to be processed in sequence.
7950 	 *
7951 	 * In the process of coming up with the most specific information,
7952 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7953 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7954 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7955 	 * Two caveats when handling incomplete ire's in ip_newroute:
7956 	 * - we should be careful when accessing its ire_nce (specifically
7957 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7958 	 * - not all legacy code path callers are prepared to handle
7959 	 *   incomplete ire's, so we should not create/add incomplete
7960 	 *   ire_cache entries here. (See discussion about temporary solution
7961 	 *   further below).
7962 	 *
7963 	 * In order to minimize packet dropping, and to preserve existing
7964 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7965 	 * gateway, and instead use the IF_RESOLVER ire to send out
7966 	 * another request to ARP (this is achieved by passing the
7967 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7968 	 * arp response comes back in ip_wput_nondata, we will create
7969 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7970 	 *
7971 	 * Note that this is a temporary solution; the correct solution is
7972 	 * to create an incomplete  per-dst ire_cache entry, and send the
7973 	 * packet out when the gw's nce is resolved. In order to achieve this,
7974 	 * all packet processing must have been completed prior to calling
7975 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7976 	 * to be modified to accomodate this solution.
7977 	 */
7978 	if (ip_nexthop) {
7979 		/*
7980 		 * The first time we come here, we look for an IRE_INTERFACE
7981 		 * entry for the specified nexthop, set the dst to be the
7982 		 * nexthop address and create an IRE_CACHE entry for the
7983 		 * nexthop. The next time around, we are able to find an
7984 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7985 		 * nexthop address and create an IRE_CACHE entry for the
7986 		 * destination address via the specified nexthop.
7987 		 */
7988 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7989 		    MBLK_GETLABEL(mp), ipst);
7990 		if (ire != NULL) {
7991 			gw = nexthop_addr;
7992 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7993 		} else {
7994 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7995 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7996 			    MBLK_GETLABEL(mp),
7997 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7998 			    ipst);
7999 			if (ire != NULL) {
8000 				dst = nexthop_addr;
8001 			}
8002 		}
8003 	} else if (attach_ill == NULL) {
8004 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8005 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8006 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8007 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8008 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8009 		    ipst);
8010 	} else {
8011 		/*
8012 		 * attach_ill is set only for communicating with
8013 		 * on-link hosts. So, don't look for DEFAULT.
8014 		 */
8015 		ipif_t	*attach_ipif;
8016 
8017 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8018 		if (attach_ipif == NULL) {
8019 			ill_refrele(attach_ill);
8020 			goto icmp_err_ret;
8021 		}
8022 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8023 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8024 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8025 		    MATCH_IRE_SECATTR, ipst);
8026 		ipif_refrele(attach_ipif);
8027 	}
8028 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8029 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8030 
8031 	/*
8032 	 * This loop is run only once in most cases.
8033 	 * We loop to resolve further routes only when the destination
8034 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8035 	 */
8036 	do {
8037 		/* Clear the previous iteration's values */
8038 		if (src_ipif != NULL) {
8039 			ipif_refrele(src_ipif);
8040 			src_ipif = NULL;
8041 		}
8042 		if (dst_ill != NULL) {
8043 			ill_refrele(dst_ill);
8044 			dst_ill = NULL;
8045 		}
8046 
8047 		multirt_resolve_next = B_FALSE;
8048 		/*
8049 		 * We check if packets have to be multirouted.
8050 		 * In this case, given the current <ire, sire> couple,
8051 		 * we look for the next suitable <ire, sire>.
8052 		 * This check is done in ire_multirt_lookup(),
8053 		 * which applies various criteria to find the next route
8054 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8055 		 * unchanged if it detects it has not been tried yet.
8056 		 */
8057 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8058 			ip3dbg(("ip_newroute: starting next_resolution "
8059 			    "with first_mp %p, tag %d\n",
8060 			    (void *)first_mp,
8061 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8062 
8063 			ASSERT(sire != NULL);
8064 			multirt_is_resolvable =
8065 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8066 			    MBLK_GETLABEL(mp), ipst);
8067 
8068 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8069 			    "ire %p, sire %p\n",
8070 			    multirt_is_resolvable,
8071 			    (void *)ire, (void *)sire));
8072 
8073 			if (!multirt_is_resolvable) {
8074 				/*
8075 				 * No more multirt route to resolve; give up
8076 				 * (all routes resolved or no more
8077 				 * resolvable routes).
8078 				 */
8079 				if (ire != NULL) {
8080 					ire_refrele(ire);
8081 					ire = NULL;
8082 				}
8083 			} else {
8084 				ASSERT(sire != NULL);
8085 				ASSERT(ire != NULL);
8086 				/*
8087 				 * We simply use first_sire as a flag that
8088 				 * indicates if a resolvable multirt route
8089 				 * has already been found.
8090 				 * If it is not the case, we may have to send
8091 				 * an ICMP error to report that the
8092 				 * destination is unreachable.
8093 				 * We do not IRE_REFHOLD first_sire.
8094 				 */
8095 				if (first_sire == NULL) {
8096 					first_sire = sire;
8097 				}
8098 			}
8099 		}
8100 		if (ire == NULL) {
8101 			if (ip_debug > 3) {
8102 				/* ip2dbg */
8103 				pr_addr_dbg("ip_newroute: "
8104 				    "can't resolve %s\n", AF_INET, &dst);
8105 			}
8106 			ip3dbg(("ip_newroute: "
8107 			    "ire %p, sire %p, first_sire %p\n",
8108 			    (void *)ire, (void *)sire, (void *)first_sire));
8109 
8110 			if (sire != NULL) {
8111 				ire_refrele(sire);
8112 				sire = NULL;
8113 			}
8114 
8115 			if (first_sire != NULL) {
8116 				/*
8117 				 * At least one multirt route has been found
8118 				 * in the same call to ip_newroute();
8119 				 * there is no need to report an ICMP error.
8120 				 * first_sire was not IRE_REFHOLDed.
8121 				 */
8122 				MULTIRT_DEBUG_UNTAG(first_mp);
8123 				freemsg(first_mp);
8124 				return;
8125 			}
8126 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8127 			    RTA_DST, ipst);
8128 			if (attach_ill != NULL)
8129 				ill_refrele(attach_ill);
8130 			goto icmp_err_ret;
8131 		}
8132 
8133 		/*
8134 		 * Verify that the returned IRE does not have either
8135 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8136 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8137 		 */
8138 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8139 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8140 			if (attach_ill != NULL)
8141 				ill_refrele(attach_ill);
8142 			goto icmp_err_ret;
8143 		}
8144 		/*
8145 		 * Increment the ire_ob_pkt_count field for ire if it is an
8146 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8147 		 * increment the same for the parent IRE, sire, if it is some
8148 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8149 		 */
8150 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8151 			UPDATE_OB_PKT_COUNT(ire);
8152 			ire->ire_last_used_time = lbolt;
8153 		}
8154 
8155 		if (sire != NULL) {
8156 			gw = sire->ire_gateway_addr;
8157 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8158 			    IRE_INTERFACE)) == 0);
8159 			UPDATE_OB_PKT_COUNT(sire);
8160 			sire->ire_last_used_time = lbolt;
8161 		}
8162 		/*
8163 		 * We have a route to reach the destination.
8164 		 *
8165 		 * 1) If the interface is part of ill group, try to get a new
8166 		 *    ill taking load spreading into account.
8167 		 *
8168 		 * 2) After selecting the ill, get a source address that
8169 		 *    might create good inbound load spreading.
8170 		 *    ipif_select_source does this for us.
8171 		 *
8172 		 * If the application specified the ill (ifindex), we still
8173 		 * load spread. Only if the packets needs to go out
8174 		 * specifically on a given ill e.g. binding to
8175 		 * IPIF_NOFAILOVER address, then we don't try to use a
8176 		 * different ill for load spreading.
8177 		 */
8178 		if (attach_ill == NULL) {
8179 			/*
8180 			 * Don't perform outbound load spreading in the
8181 			 * case of an RTF_MULTIRT route, as we actually
8182 			 * typically want to replicate outgoing packets
8183 			 * through particular interfaces.
8184 			 */
8185 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8186 				dst_ill = ire->ire_ipif->ipif_ill;
8187 				/* for uniformity */
8188 				ill_refhold(dst_ill);
8189 			} else {
8190 				/*
8191 				 * If we are here trying to create an IRE_CACHE
8192 				 * for an offlink destination and have the
8193 				 * IRE_CACHE for the next hop and the latter is
8194 				 * using virtual IP source address selection i.e
8195 				 * it's ire->ire_ipif is pointing to a virtual
8196 				 * network interface (vni) then
8197 				 * ip_newroute_get_dst_ll() will return the vni
8198 				 * interface as the dst_ill. Since the vni is
8199 				 * virtual i.e not associated with any physical
8200 				 * interface, it cannot be the dst_ill, hence
8201 				 * in such a case call ip_newroute_get_dst_ll()
8202 				 * with the stq_ill instead of the ire_ipif ILL.
8203 				 * The function returns a refheld ill.
8204 				 */
8205 				if ((ire->ire_type == IRE_CACHE) &&
8206 				    IS_VNI(ire->ire_ipif->ipif_ill))
8207 					dst_ill = ip_newroute_get_dst_ill(
8208 					    ire->ire_stq->q_ptr);
8209 				else
8210 					dst_ill = ip_newroute_get_dst_ill(
8211 					    ire->ire_ipif->ipif_ill);
8212 			}
8213 			if (dst_ill == NULL) {
8214 				if (ip_debug > 2) {
8215 					pr_addr_dbg("ip_newroute: "
8216 					    "no dst ill for dst"
8217 					    " %s\n", AF_INET, &dst);
8218 				}
8219 				goto icmp_err_ret;
8220 			}
8221 		} else {
8222 			dst_ill = ire->ire_ipif->ipif_ill;
8223 			/* for uniformity */
8224 			ill_refhold(dst_ill);
8225 			/*
8226 			 * We should have found a route matching ill as we
8227 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8228 			 * Rather than asserting, when there is a mismatch,
8229 			 * we just drop the packet.
8230 			 */
8231 			if (dst_ill != attach_ill) {
8232 				ip0dbg(("ip_newroute: Packet dropped as "
8233 				    "IPIF_NOFAILOVER ill is %s, "
8234 				    "ire->ire_ipif->ipif_ill is %s\n",
8235 				    attach_ill->ill_name,
8236 				    dst_ill->ill_name));
8237 				ill_refrele(attach_ill);
8238 				goto icmp_err_ret;
8239 			}
8240 		}
8241 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8242 		if (attach_ill != NULL) {
8243 			ill_refrele(attach_ill);
8244 			attach_ill = NULL;
8245 			do_attach_ill = B_TRUE;
8246 		}
8247 		ASSERT(dst_ill != NULL);
8248 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8249 
8250 		/*
8251 		 * Pick the best source address from dst_ill.
8252 		 *
8253 		 * 1) If it is part of a multipathing group, we would
8254 		 *    like to spread the inbound packets across different
8255 		 *    interfaces. ipif_select_source picks a random source
8256 		 *    across the different ills in the group.
8257 		 *
8258 		 * 2) If it is not part of a multipathing group, we try
8259 		 *    to pick the source address from the destination
8260 		 *    route. Clustering assumes that when we have multiple
8261 		 *    prefixes hosted on an interface, the prefix of the
8262 		 *    source address matches the prefix of the destination
8263 		 *    route. We do this only if the address is not
8264 		 *    DEPRECATED.
8265 		 *
8266 		 * 3) If the conn is in a different zone than the ire, we
8267 		 *    need to pick a source address from the right zone.
8268 		 *
8269 		 * NOTE : If we hit case (1) above, the prefix of the source
8270 		 *	  address picked may not match the prefix of the
8271 		 *	  destination routes prefix as ipif_select_source
8272 		 *	  does not look at "dst" while picking a source
8273 		 *	  address.
8274 		 *	  If we want the same behavior as (2), we will need
8275 		 *	  to change the behavior of ipif_select_source.
8276 		 */
8277 		ASSERT(src_ipif == NULL);
8278 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8279 			/*
8280 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8281 			 * Check that the ipif matching the requested source
8282 			 * address still exists.
8283 			 */
8284 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8285 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8286 		}
8287 		if (src_ipif == NULL) {
8288 			ire_marks |= IRE_MARK_USESRC_CHECK;
8289 			if ((dst_ill->ill_group != NULL) ||
8290 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8291 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8292 			    ire->ire_zoneid != ALL_ZONES) ||
8293 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8294 				/*
8295 				 * If the destination is reachable via a
8296 				 * given gateway, the selected source address
8297 				 * should be in the same subnet as the gateway.
8298 				 * Otherwise, the destination is not reachable.
8299 				 *
8300 				 * If there are no interfaces on the same subnet
8301 				 * as the destination, ipif_select_source gives
8302 				 * first non-deprecated interface which might be
8303 				 * on a different subnet than the gateway.
8304 				 * This is not desirable. Hence pass the dst_ire
8305 				 * source address to ipif_select_source.
8306 				 * It is sure that the destination is reachable
8307 				 * with the dst_ire source address subnet.
8308 				 * So passing dst_ire source address to
8309 				 * ipif_select_source will make sure that the
8310 				 * selected source will be on the same subnet
8311 				 * as dst_ire source address.
8312 				 */
8313 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8314 				src_ipif = ipif_select_source(dst_ill, saddr,
8315 				    zoneid);
8316 				if (src_ipif == NULL) {
8317 					if (ip_debug > 2) {
8318 						pr_addr_dbg("ip_newroute: "
8319 						    "no src for dst %s ",
8320 						    AF_INET, &dst);
8321 						printf("through interface %s\n",
8322 						    dst_ill->ill_name);
8323 					}
8324 					goto icmp_err_ret;
8325 				}
8326 			} else {
8327 				src_ipif = ire->ire_ipif;
8328 				ASSERT(src_ipif != NULL);
8329 				/* hold src_ipif for uniformity */
8330 				ipif_refhold(src_ipif);
8331 			}
8332 		}
8333 
8334 		/*
8335 		 * Assign a source address while we have the conn.
8336 		 * We can't have ip_wput_ire pick a source address when the
8337 		 * packet returns from arp since we need to look at
8338 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8339 		 * going through arp.
8340 		 *
8341 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8342 		 *	  it uses ip6i to store this information.
8343 		 */
8344 		if (ipha->ipha_src == INADDR_ANY &&
8345 		    (connp == NULL || !connp->conn_unspec_src)) {
8346 			ipha->ipha_src = src_ipif->ipif_src_addr;
8347 		}
8348 		if (ip_debug > 3) {
8349 			/* ip2dbg */
8350 			pr_addr_dbg("ip_newroute: first hop %s\n",
8351 			    AF_INET, &gw);
8352 		}
8353 		ip2dbg(("\tire type %s (%d)\n",
8354 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8355 
8356 		/*
8357 		 * The TTL of multirouted packets is bounded by the
8358 		 * ip_multirt_ttl ndd variable.
8359 		 */
8360 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8361 			/* Force TTL of multirouted packets */
8362 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8363 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8364 				ip2dbg(("ip_newroute: forcing multirt TTL "
8365 				    "to %d (was %d), dst 0x%08x\n",
8366 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8367 				    ntohl(sire->ire_addr)));
8368 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8369 			}
8370 		}
8371 		/*
8372 		 * At this point in ip_newroute(), ire is either the
8373 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8374 		 * destination or an IRE_INTERFACE type that should be used
8375 		 * to resolve an on-subnet destination or an on-subnet
8376 		 * next-hop gateway.
8377 		 *
8378 		 * In the IRE_CACHE case, we have the following :
8379 		 *
8380 		 * 1) src_ipif - used for getting a source address.
8381 		 *
8382 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8383 		 *    means packets using this IRE_CACHE will go out on
8384 		 *    dst_ill.
8385 		 *
8386 		 * 3) The IRE sire will point to the prefix that is the
8387 		 *    longest  matching route for the destination. These
8388 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8389 		 *
8390 		 *    The newly created IRE_CACHE entry for the off-subnet
8391 		 *    destination is tied to both the prefix route and the
8392 		 *    interface route used to resolve the next-hop gateway
8393 		 *    via the ire_phandle and ire_ihandle fields,
8394 		 *    respectively.
8395 		 *
8396 		 * In the IRE_INTERFACE case, we have the following :
8397 		 *
8398 		 * 1) src_ipif - used for getting a source address.
8399 		 *
8400 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8401 		 *    means packets using the IRE_CACHE that we will build
8402 		 *    here will go out on dst_ill.
8403 		 *
8404 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8405 		 *    to be created will only be tied to the IRE_INTERFACE
8406 		 *    that was derived from the ire_ihandle field.
8407 		 *
8408 		 *    If sire is non-NULL, it means the destination is
8409 		 *    off-link and we will first create the IRE_CACHE for the
8410 		 *    gateway. Next time through ip_newroute, we will create
8411 		 *    the IRE_CACHE for the final destination as described
8412 		 *    above.
8413 		 *
8414 		 * In both cases, after the current resolution has been
8415 		 * completed (or possibly initialised, in the IRE_INTERFACE
8416 		 * case), the loop may be re-entered to attempt the resolution
8417 		 * of another RTF_MULTIRT route.
8418 		 *
8419 		 * When an IRE_CACHE entry for the off-subnet destination is
8420 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8421 		 * for further processing in emission loops.
8422 		 */
8423 		save_ire = ire;
8424 		switch (ire->ire_type) {
8425 		case IRE_CACHE: {
8426 			ire_t	*ipif_ire;
8427 
8428 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8429 			if (gw == 0)
8430 				gw = ire->ire_gateway_addr;
8431 			/*
8432 			 * We need 3 ire's to create a new cache ire for an
8433 			 * off-link destination from the cache ire of the
8434 			 * gateway.
8435 			 *
8436 			 *	1. The prefix ire 'sire' (Note that this does
8437 			 *	   not apply to the conn_nexthop_set case)
8438 			 *	2. The cache ire of the gateway 'ire'
8439 			 *	3. The interface ire 'ipif_ire'
8440 			 *
8441 			 * We have (1) and (2). We lookup (3) below.
8442 			 *
8443 			 * If there is no interface route to the gateway,
8444 			 * it is a race condition, where we found the cache
8445 			 * but the interface route has been deleted.
8446 			 */
8447 			if (ip_nexthop) {
8448 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8449 			} else {
8450 				ipif_ire =
8451 				    ire_ihandle_lookup_offlink(ire, sire);
8452 			}
8453 			if (ipif_ire == NULL) {
8454 				ip1dbg(("ip_newroute: "
8455 				    "ire_ihandle_lookup_offlink failed\n"));
8456 				goto icmp_err_ret;
8457 			}
8458 
8459 			/*
8460 			 * Check cached gateway IRE for any security
8461 			 * attributes; if found, associate the gateway
8462 			 * credentials group to the destination IRE.
8463 			 */
8464 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8465 				mutex_enter(&attrp->igsa_lock);
8466 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8467 					GCGRP_REFHOLD(gcgrp);
8468 				mutex_exit(&attrp->igsa_lock);
8469 			}
8470 
8471 			/*
8472 			 * XXX For the source of the resolver mp,
8473 			 * we are using the same DL_UNITDATA_REQ
8474 			 * (from save_ire->ire_nce->nce_res_mp)
8475 			 * though the save_ire is not pointing at the same ill.
8476 			 * This is incorrect. We need to send it up to the
8477 			 * resolver to get the right res_mp. For ethernets
8478 			 * this may be okay (ill_type == DL_ETHER).
8479 			 */
8480 
8481 			ire = ire_create(
8482 			    (uchar_t *)&dst,		/* dest address */
8483 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8484 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8485 			    (uchar_t *)&gw,		/* gateway address */
8486 			    &save_ire->ire_max_frag,
8487 			    save_ire->ire_nce,		/* src nce */
8488 			    dst_ill->ill_rq,		/* recv-from queue */
8489 			    dst_ill->ill_wq,		/* send-to queue */
8490 			    IRE_CACHE,			/* IRE type */
8491 			    src_ipif,
8492 			    (sire != NULL) ?
8493 			    sire->ire_mask : 0, 	/* Parent mask */
8494 			    (sire != NULL) ?
8495 			    sire->ire_phandle : 0,	/* Parent handle */
8496 			    ipif_ire->ire_ihandle,	/* Interface handle */
8497 			    (sire != NULL) ? (sire->ire_flags &
8498 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8499 			    (sire != NULL) ?
8500 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8501 			    NULL,
8502 			    gcgrp,
8503 			    ipst);
8504 
8505 			if (ire == NULL) {
8506 				if (gcgrp != NULL) {
8507 					GCGRP_REFRELE(gcgrp);
8508 					gcgrp = NULL;
8509 				}
8510 				ire_refrele(ipif_ire);
8511 				ire_refrele(save_ire);
8512 				break;
8513 			}
8514 
8515 			/* reference now held by IRE */
8516 			gcgrp = NULL;
8517 
8518 			ire->ire_marks |= ire_marks;
8519 
8520 			/*
8521 			 * Prevent sire and ipif_ire from getting deleted.
8522 			 * The newly created ire is tied to both of them via
8523 			 * the phandle and ihandle respectively.
8524 			 */
8525 			if (sire != NULL) {
8526 				IRB_REFHOLD(sire->ire_bucket);
8527 				/* Has it been removed already ? */
8528 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8529 					IRB_REFRELE(sire->ire_bucket);
8530 					ire_refrele(ipif_ire);
8531 					ire_refrele(save_ire);
8532 					break;
8533 				}
8534 			}
8535 
8536 			IRB_REFHOLD(ipif_ire->ire_bucket);
8537 			/* Has it been removed already ? */
8538 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8539 				IRB_REFRELE(ipif_ire->ire_bucket);
8540 				if (sire != NULL)
8541 					IRB_REFRELE(sire->ire_bucket);
8542 				ire_refrele(ipif_ire);
8543 				ire_refrele(save_ire);
8544 				break;
8545 			}
8546 
8547 			xmit_mp = first_mp;
8548 			/*
8549 			 * In the case of multirouting, a copy
8550 			 * of the packet is done before its sending.
8551 			 * The copy is used to attempt another
8552 			 * route resolution, in a next loop.
8553 			 */
8554 			if (ire->ire_flags & RTF_MULTIRT) {
8555 				copy_mp = copymsg(first_mp);
8556 				if (copy_mp != NULL) {
8557 					xmit_mp = copy_mp;
8558 					MULTIRT_DEBUG_TAG(first_mp);
8559 				}
8560 			}
8561 			ire_add_then_send(q, ire, xmit_mp);
8562 			ire_refrele(save_ire);
8563 
8564 			/* Assert that sire is not deleted yet. */
8565 			if (sire != NULL) {
8566 				ASSERT(sire->ire_ptpn != NULL);
8567 				IRB_REFRELE(sire->ire_bucket);
8568 			}
8569 
8570 			/* Assert that ipif_ire is not deleted yet. */
8571 			ASSERT(ipif_ire->ire_ptpn != NULL);
8572 			IRB_REFRELE(ipif_ire->ire_bucket);
8573 			ire_refrele(ipif_ire);
8574 
8575 			/*
8576 			 * If copy_mp is not NULL, multirouting was
8577 			 * requested. We loop to initiate a next
8578 			 * route resolution attempt, starting from sire.
8579 			 */
8580 			if (copy_mp != NULL) {
8581 				/*
8582 				 * Search for the next unresolved
8583 				 * multirt route.
8584 				 */
8585 				copy_mp = NULL;
8586 				ipif_ire = NULL;
8587 				ire = NULL;
8588 				multirt_resolve_next = B_TRUE;
8589 				continue;
8590 			}
8591 			if (sire != NULL)
8592 				ire_refrele(sire);
8593 			ipif_refrele(src_ipif);
8594 			ill_refrele(dst_ill);
8595 			return;
8596 		}
8597 		case IRE_IF_NORESOLVER: {
8598 
8599 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8600 			    dst_ill->ill_resolver_mp == NULL) {
8601 				ip1dbg(("ip_newroute: dst_ill %p "
8602 				    "for IRE_IF_NORESOLVER ire %p has "
8603 				    "no ill_resolver_mp\n",
8604 				    (void *)dst_ill, (void *)ire));
8605 				break;
8606 			}
8607 
8608 			/*
8609 			 * TSol note: We are creating the ire cache for the
8610 			 * destination 'dst'. If 'dst' is offlink, going
8611 			 * through the first hop 'gw', the security attributes
8612 			 * of 'dst' must be set to point to the gateway
8613 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8614 			 * is possible that 'dst' is a potential gateway that is
8615 			 * referenced by some route that has some security
8616 			 * attributes. Thus in the former case, we need to do a
8617 			 * gcgrp_lookup of 'gw' while in the latter case we
8618 			 * need to do gcgrp_lookup of 'dst' itself.
8619 			 */
8620 			ga.ga_af = AF_INET;
8621 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8622 			    &ga.ga_addr);
8623 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8624 
8625 			ire = ire_create(
8626 			    (uchar_t *)&dst,		/* dest address */
8627 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8628 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8629 			    (uchar_t *)&gw,		/* gateway address */
8630 			    &save_ire->ire_max_frag,
8631 			    NULL,			/* no src nce */
8632 			    dst_ill->ill_rq,		/* recv-from queue */
8633 			    dst_ill->ill_wq,		/* send-to queue */
8634 			    IRE_CACHE,
8635 			    src_ipif,
8636 			    save_ire->ire_mask,		/* Parent mask */
8637 			    (sire != NULL) ?		/* Parent handle */
8638 			    sire->ire_phandle : 0,
8639 			    save_ire->ire_ihandle,	/* Interface handle */
8640 			    (sire != NULL) ? sire->ire_flags &
8641 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8642 			    &(save_ire->ire_uinfo),
8643 			    NULL,
8644 			    gcgrp,
8645 			    ipst);
8646 
8647 			if (ire == NULL) {
8648 				if (gcgrp != NULL) {
8649 					GCGRP_REFRELE(gcgrp);
8650 					gcgrp = NULL;
8651 				}
8652 				ire_refrele(save_ire);
8653 				break;
8654 			}
8655 
8656 			/* reference now held by IRE */
8657 			gcgrp = NULL;
8658 
8659 			ire->ire_marks |= ire_marks;
8660 
8661 			/* Prevent save_ire from getting deleted */
8662 			IRB_REFHOLD(save_ire->ire_bucket);
8663 			/* Has it been removed already ? */
8664 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8665 				IRB_REFRELE(save_ire->ire_bucket);
8666 				ire_refrele(save_ire);
8667 				break;
8668 			}
8669 
8670 			/*
8671 			 * In the case of multirouting, a copy
8672 			 * of the packet is made before it is sent.
8673 			 * The copy is used in the next
8674 			 * loop to attempt another resolution.
8675 			 */
8676 			xmit_mp = first_mp;
8677 			if ((sire != NULL) &&
8678 			    (sire->ire_flags & RTF_MULTIRT)) {
8679 				copy_mp = copymsg(first_mp);
8680 				if (copy_mp != NULL) {
8681 					xmit_mp = copy_mp;
8682 					MULTIRT_DEBUG_TAG(first_mp);
8683 				}
8684 			}
8685 			ire_add_then_send(q, ire, xmit_mp);
8686 
8687 			/* Assert that it is not deleted yet. */
8688 			ASSERT(save_ire->ire_ptpn != NULL);
8689 			IRB_REFRELE(save_ire->ire_bucket);
8690 			ire_refrele(save_ire);
8691 
8692 			if (copy_mp != NULL) {
8693 				/*
8694 				 * If we found a (no)resolver, we ignore any
8695 				 * trailing top priority IRE_CACHE in further
8696 				 * loops. This ensures that we do not omit any
8697 				 * (no)resolver.
8698 				 * This IRE_CACHE, if any, will be processed
8699 				 * by another thread entering ip_newroute().
8700 				 * IRE_CACHE entries, if any, will be processed
8701 				 * by another thread entering ip_newroute(),
8702 				 * (upon resolver response, for instance).
8703 				 * This aims to force parallel multirt
8704 				 * resolutions as soon as a packet must be sent.
8705 				 * In the best case, after the tx of only one
8706 				 * packet, all reachable routes are resolved.
8707 				 * Otherwise, the resolution of all RTF_MULTIRT
8708 				 * routes would require several emissions.
8709 				 */
8710 				multirt_flags &= ~MULTIRT_CACHEGW;
8711 
8712 				/*
8713 				 * Search for the next unresolved multirt
8714 				 * route.
8715 				 */
8716 				copy_mp = NULL;
8717 				save_ire = NULL;
8718 				ire = NULL;
8719 				multirt_resolve_next = B_TRUE;
8720 				continue;
8721 			}
8722 
8723 			/*
8724 			 * Don't need sire anymore
8725 			 */
8726 			if (sire != NULL)
8727 				ire_refrele(sire);
8728 
8729 			ipif_refrele(src_ipif);
8730 			ill_refrele(dst_ill);
8731 			return;
8732 		}
8733 		case IRE_IF_RESOLVER:
8734 			/*
8735 			 * We can't build an IRE_CACHE yet, but at least we
8736 			 * found a resolver that can help.
8737 			 */
8738 			res_mp = dst_ill->ill_resolver_mp;
8739 			if (!OK_RESOLVER_MP(res_mp))
8740 				break;
8741 
8742 			/*
8743 			 * To be at this point in the code with a non-zero gw
8744 			 * means that dst is reachable through a gateway that
8745 			 * we have never resolved.  By changing dst to the gw
8746 			 * addr we resolve the gateway first.
8747 			 * When ire_add_then_send() tries to put the IP dg
8748 			 * to dst, it will reenter ip_newroute() at which
8749 			 * time we will find the IRE_CACHE for the gw and
8750 			 * create another IRE_CACHE in case IRE_CACHE above.
8751 			 */
8752 			if (gw != INADDR_ANY) {
8753 				/*
8754 				 * The source ipif that was determined above was
8755 				 * relative to the destination address, not the
8756 				 * gateway's. If src_ipif was not taken out of
8757 				 * the IRE_IF_RESOLVER entry, we'll need to call
8758 				 * ipif_select_source() again.
8759 				 */
8760 				if (src_ipif != ire->ire_ipif) {
8761 					ipif_refrele(src_ipif);
8762 					src_ipif = ipif_select_source(dst_ill,
8763 					    gw, zoneid);
8764 					if (src_ipif == NULL) {
8765 						if (ip_debug > 2) {
8766 							pr_addr_dbg(
8767 							    "ip_newroute: no "
8768 							    "src for gw %s ",
8769 							    AF_INET, &gw);
8770 							printf("through "
8771 							    "interface %s\n",
8772 							    dst_ill->ill_name);
8773 						}
8774 						goto icmp_err_ret;
8775 					}
8776 				}
8777 				save_dst = dst;
8778 				dst = gw;
8779 				gw = INADDR_ANY;
8780 			}
8781 
8782 			/*
8783 			 * We obtain a partial IRE_CACHE which we will pass
8784 			 * along with the resolver query.  When the response
8785 			 * comes back it will be there ready for us to add.
8786 			 * The ire_max_frag is atomically set under the
8787 			 * irebucket lock in ire_add_v[46].
8788 			 */
8789 
8790 			ire = ire_create_mp(
8791 			    (uchar_t *)&dst,		/* dest address */
8792 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8793 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8794 			    (uchar_t *)&gw,		/* gateway address */
8795 			    NULL,			/* ire_max_frag */
8796 			    NULL,			/* no src nce */
8797 			    dst_ill->ill_rq,		/* recv-from queue */
8798 			    dst_ill->ill_wq,		/* send-to queue */
8799 			    IRE_CACHE,
8800 			    src_ipif,			/* Interface ipif */
8801 			    save_ire->ire_mask,		/* Parent mask */
8802 			    0,
8803 			    save_ire->ire_ihandle,	/* Interface handle */
8804 			    0,				/* flags if any */
8805 			    &(save_ire->ire_uinfo),
8806 			    NULL,
8807 			    NULL,
8808 			    ipst);
8809 
8810 			if (ire == NULL) {
8811 				ire_refrele(save_ire);
8812 				break;
8813 			}
8814 
8815 			if ((sire != NULL) &&
8816 			    (sire->ire_flags & RTF_MULTIRT)) {
8817 				copy_mp = copymsg(first_mp);
8818 				if (copy_mp != NULL)
8819 					MULTIRT_DEBUG_TAG(copy_mp);
8820 			}
8821 
8822 			ire->ire_marks |= ire_marks;
8823 
8824 			/*
8825 			 * Construct message chain for the resolver
8826 			 * of the form:
8827 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8828 			 * Packet could contain a IPSEC_OUT mp.
8829 			 *
8830 			 * NOTE : ire will be added later when the response
8831 			 * comes back from ARP. If the response does not
8832 			 * come back, ARP frees the packet. For this reason,
8833 			 * we can't REFHOLD the bucket of save_ire to prevent
8834 			 * deletions. We may not be able to REFRELE the bucket
8835 			 * if the response never comes back. Thus, before
8836 			 * adding the ire, ire_add_v4 will make sure that the
8837 			 * interface route does not get deleted. This is the
8838 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8839 			 * where we can always prevent deletions because of
8840 			 * the synchronous nature of adding IRES i.e
8841 			 * ire_add_then_send is called after creating the IRE.
8842 			 */
8843 			ASSERT(ire->ire_mp != NULL);
8844 			ire->ire_mp->b_cont = first_mp;
8845 			/* Have saved_mp handy, for cleanup if canput fails */
8846 			saved_mp = mp;
8847 			mp = copyb(res_mp);
8848 			if (mp == NULL) {
8849 				/* Prepare for cleanup */
8850 				mp = saved_mp; /* pkt */
8851 				ire_delete(ire); /* ire_mp */
8852 				ire = NULL;
8853 				ire_refrele(save_ire);
8854 				if (copy_mp != NULL) {
8855 					MULTIRT_DEBUG_UNTAG(copy_mp);
8856 					freemsg(copy_mp);
8857 					copy_mp = NULL;
8858 				}
8859 				break;
8860 			}
8861 			linkb(mp, ire->ire_mp);
8862 
8863 			/*
8864 			 * Fill in the source and dest addrs for the resolver.
8865 			 * NOTE: this depends on memory layouts imposed by
8866 			 * ill_init().
8867 			 */
8868 			areq = (areq_t *)mp->b_rptr;
8869 			addrp = (ipaddr_t *)((char *)areq +
8870 			    areq->areq_sender_addr_offset);
8871 			if (do_attach_ill) {
8872 				/*
8873 				 * This is bind to no failover case.
8874 				 * arp packet also must go out on attach_ill.
8875 				 */
8876 				ASSERT(ipha->ipha_src != NULL);
8877 				*addrp = ipha->ipha_src;
8878 			} else {
8879 				*addrp = save_ire->ire_src_addr;
8880 			}
8881 
8882 			ire_refrele(save_ire);
8883 			addrp = (ipaddr_t *)((char *)areq +
8884 			    areq->areq_target_addr_offset);
8885 			*addrp = dst;
8886 			/* Up to the resolver. */
8887 			if (canputnext(dst_ill->ill_rq) &&
8888 			    !(dst_ill->ill_arp_closing)) {
8889 				putnext(dst_ill->ill_rq, mp);
8890 				ire = NULL;
8891 				if (copy_mp != NULL) {
8892 					/*
8893 					 * If we found a resolver, we ignore
8894 					 * any trailing top priority IRE_CACHE
8895 					 * in the further loops. This ensures
8896 					 * that we do not omit any resolver.
8897 					 * IRE_CACHE entries, if any, will be
8898 					 * processed next time we enter
8899 					 * ip_newroute().
8900 					 */
8901 					multirt_flags &= ~MULTIRT_CACHEGW;
8902 					/*
8903 					 * Search for the next unresolved
8904 					 * multirt route.
8905 					 */
8906 					first_mp = copy_mp;
8907 					copy_mp = NULL;
8908 					/* Prepare the next resolution loop. */
8909 					mp = first_mp;
8910 					EXTRACT_PKT_MP(mp, first_mp,
8911 					    mctl_present);
8912 					if (mctl_present)
8913 						io = (ipsec_out_t *)
8914 						    first_mp->b_rptr;
8915 					ipha = (ipha_t *)mp->b_rptr;
8916 
8917 					ASSERT(sire != NULL);
8918 
8919 					dst = save_dst;
8920 					multirt_resolve_next = B_TRUE;
8921 					continue;
8922 				}
8923 
8924 				if (sire != NULL)
8925 					ire_refrele(sire);
8926 
8927 				/*
8928 				 * The response will come back in ip_wput
8929 				 * with db_type IRE_DB_TYPE.
8930 				 */
8931 				ipif_refrele(src_ipif);
8932 				ill_refrele(dst_ill);
8933 				return;
8934 			} else {
8935 				/* Prepare for cleanup */
8936 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8937 				    mp);
8938 				mp->b_cont = NULL;
8939 				freeb(mp); /* areq */
8940 				/*
8941 				 * this is an ire that is not added to the
8942 				 * cache. ire_freemblk will handle the release
8943 				 * of any resources associated with the ire.
8944 				 */
8945 				ire_delete(ire); /* ire_mp */
8946 				mp = saved_mp; /* pkt */
8947 				ire = NULL;
8948 				if (copy_mp != NULL) {
8949 					MULTIRT_DEBUG_UNTAG(copy_mp);
8950 					freemsg(copy_mp);
8951 					copy_mp = NULL;
8952 				}
8953 				break;
8954 			}
8955 		default:
8956 			break;
8957 		}
8958 	} while (multirt_resolve_next);
8959 
8960 	ip1dbg(("ip_newroute: dropped\n"));
8961 	/* Did this packet originate externally? */
8962 	if (mp->b_prev) {
8963 		mp->b_next = NULL;
8964 		mp->b_prev = NULL;
8965 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8966 	} else {
8967 		if (dst_ill != NULL) {
8968 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8969 		} else {
8970 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8971 		}
8972 	}
8973 	ASSERT(copy_mp == NULL);
8974 	MULTIRT_DEBUG_UNTAG(first_mp);
8975 	freemsg(first_mp);
8976 	if (ire != NULL)
8977 		ire_refrele(ire);
8978 	if (sire != NULL)
8979 		ire_refrele(sire);
8980 	if (src_ipif != NULL)
8981 		ipif_refrele(src_ipif);
8982 	if (dst_ill != NULL)
8983 		ill_refrele(dst_ill);
8984 	return;
8985 
8986 icmp_err_ret:
8987 	ip1dbg(("ip_newroute: no route\n"));
8988 	if (src_ipif != NULL)
8989 		ipif_refrele(src_ipif);
8990 	if (dst_ill != NULL)
8991 		ill_refrele(dst_ill);
8992 	if (sire != NULL)
8993 		ire_refrele(sire);
8994 	/* Did this packet originate externally? */
8995 	if (mp->b_prev) {
8996 		mp->b_next = NULL;
8997 		mp->b_prev = NULL;
8998 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8999 		q = WR(q);
9000 	} else {
9001 		/*
9002 		 * There is no outgoing ill, so just increment the
9003 		 * system MIB.
9004 		 */
9005 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9006 		/*
9007 		 * Since ip_wput() isn't close to finished, we fill
9008 		 * in enough of the header for credible error reporting.
9009 		 */
9010 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9011 			/* Failed */
9012 			MULTIRT_DEBUG_UNTAG(first_mp);
9013 			freemsg(first_mp);
9014 			if (ire != NULL)
9015 				ire_refrele(ire);
9016 			return;
9017 		}
9018 	}
9019 
9020 	/*
9021 	 * At this point we will have ire only if RTF_BLACKHOLE
9022 	 * or RTF_REJECT flags are set on the IRE. It will not
9023 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9024 	 */
9025 	if (ire != NULL) {
9026 		if (ire->ire_flags & RTF_BLACKHOLE) {
9027 			ire_refrele(ire);
9028 			MULTIRT_DEBUG_UNTAG(first_mp);
9029 			freemsg(first_mp);
9030 			return;
9031 		}
9032 		ire_refrele(ire);
9033 	}
9034 	if (ip_source_routed(ipha, ipst)) {
9035 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9036 		    zoneid, ipst);
9037 		return;
9038 	}
9039 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9040 }
9041 
9042 ip_opt_info_t zero_info;
9043 
9044 /*
9045  * IPv4 -
9046  * ip_newroute_ipif is called by ip_wput_multicast and
9047  * ip_rput_forward_multicast whenever we need to send
9048  * out a packet to a destination address for which we do not have specific
9049  * routing information. It is used when the packet will be sent out
9050  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9051  * socket option is set or icmp error message wants to go out on a particular
9052  * interface for a unicast packet.
9053  *
9054  * In most cases, the destination address is resolved thanks to the ipif
9055  * intrinsic resolver. However, there are some cases where the call to
9056  * ip_newroute_ipif must take into account the potential presence of
9057  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9058  * that uses the interface. This is specified through flags,
9059  * which can be a combination of:
9060  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9061  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9062  *   and flags. Additionally, the packet source address has to be set to
9063  *   the specified address. The caller is thus expected to set this flag
9064  *   if the packet has no specific source address yet.
9065  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9066  *   flag, the resulting ire will inherit the flag. All unresolved routes
9067  *   to the destination must be explored in the same call to
9068  *   ip_newroute_ipif().
9069  */
9070 static void
9071 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9072     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9073 {
9074 	areq_t	*areq;
9075 	ire_t	*ire = NULL;
9076 	mblk_t	*res_mp;
9077 	ipaddr_t *addrp;
9078 	mblk_t *first_mp;
9079 	ire_t	*save_ire = NULL;
9080 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9081 	ipif_t	*src_ipif = NULL;
9082 	ushort_t ire_marks = 0;
9083 	ill_t	*dst_ill = NULL;
9084 	boolean_t mctl_present;
9085 	ipsec_out_t *io;
9086 	ipha_t *ipha;
9087 	int	ihandle = 0;
9088 	mblk_t	*saved_mp;
9089 	ire_t   *fire = NULL;
9090 	mblk_t  *copy_mp = NULL;
9091 	boolean_t multirt_resolve_next;
9092 	ipaddr_t ipha_dst;
9093 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9094 
9095 	/*
9096 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9097 	 * here for uniformity
9098 	 */
9099 	ipif_refhold(ipif);
9100 
9101 	/*
9102 	 * This loop is run only once in most cases.
9103 	 * We loop to resolve further routes only when the destination
9104 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9105 	 */
9106 	do {
9107 		if (dst_ill != NULL) {
9108 			ill_refrele(dst_ill);
9109 			dst_ill = NULL;
9110 		}
9111 		if (src_ipif != NULL) {
9112 			ipif_refrele(src_ipif);
9113 			src_ipif = NULL;
9114 		}
9115 		multirt_resolve_next = B_FALSE;
9116 
9117 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9118 		    ipif->ipif_ill->ill_name));
9119 
9120 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9121 		if (mctl_present)
9122 			io = (ipsec_out_t *)first_mp->b_rptr;
9123 
9124 		ipha = (ipha_t *)mp->b_rptr;
9125 
9126 		/*
9127 		 * Save the packet destination address, we may need it after
9128 		 * the packet has been consumed.
9129 		 */
9130 		ipha_dst = ipha->ipha_dst;
9131 
9132 		/*
9133 		 * If the interface is a pt-pt interface we look for an
9134 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9135 		 * local_address and the pt-pt destination address. Otherwise
9136 		 * we just match the local address.
9137 		 * NOTE: dst could be different than ipha->ipha_dst in case
9138 		 * of sending igmp multicast packets over a point-to-point
9139 		 * connection.
9140 		 * Thus we must be careful enough to check ipha_dst to be a
9141 		 * multicast address, otherwise it will take xmit_if path for
9142 		 * multicast packets resulting into kernel stack overflow by
9143 		 * repeated calls to ip_newroute_ipif from ire_send().
9144 		 */
9145 		if (CLASSD(ipha_dst) &&
9146 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9147 			goto err_ret;
9148 		}
9149 
9150 		/*
9151 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9152 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9153 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9154 		 * propagate its flags to the new ire.
9155 		 */
9156 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9157 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9158 			ip2dbg(("ip_newroute_ipif: "
9159 			    "ipif_lookup_multi_ire("
9160 			    "ipif %p, dst %08x) = fire %p\n",
9161 			    (void *)ipif, ntohl(dst), (void *)fire));
9162 		}
9163 
9164 		if (mctl_present && io->ipsec_out_attach_if) {
9165 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9166 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9167 
9168 			/* Failure case frees things for us. */
9169 			if (attach_ill == NULL) {
9170 				ipif_refrele(ipif);
9171 				if (fire != NULL)
9172 					ire_refrele(fire);
9173 				return;
9174 			}
9175 
9176 			/*
9177 			 * Check if we need an ire that will not be
9178 			 * looked up by anybody else i.e. HIDDEN.
9179 			 */
9180 			if (ill_is_probeonly(attach_ill)) {
9181 				ire_marks = IRE_MARK_HIDDEN;
9182 			}
9183 			/*
9184 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9185 			 * case.
9186 			 */
9187 			dst_ill = ipif->ipif_ill;
9188 			/* attach_ill has been refheld by ip_grab_attach_ill */
9189 			ASSERT(dst_ill == attach_ill);
9190 		} else {
9191 			/*
9192 			 * If this is set by IP_XMIT_IF, then make sure that
9193 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9194 			 * specified ill.
9195 			 */
9196 			ASSERT((connp == NULL) ||
9197 			    (connp->conn_xmit_if_ill == NULL) ||
9198 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9199 			/*
9200 			 * If the interface belongs to an interface group,
9201 			 * make sure the next possible interface in the group
9202 			 * is used.  This encourages load spreading among
9203 			 * peers in an interface group.
9204 			 * Note: load spreading is disabled for RTF_MULTIRT
9205 			 * routes.
9206 			 */
9207 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9208 			    (fire->ire_flags & RTF_MULTIRT)) {
9209 				/*
9210 				 * Don't perform outbound load spreading
9211 				 * in the case of an RTF_MULTIRT issued route,
9212 				 * we actually typically want to replicate
9213 				 * outgoing packets through particular
9214 				 * interfaces.
9215 				 */
9216 				dst_ill = ipif->ipif_ill;
9217 				ill_refhold(dst_ill);
9218 			} else {
9219 				dst_ill = ip_newroute_get_dst_ill(
9220 				    ipif->ipif_ill);
9221 			}
9222 			if (dst_ill == NULL) {
9223 				if (ip_debug > 2) {
9224 					pr_addr_dbg("ip_newroute_ipif: "
9225 					    "no dst ill for dst %s\n",
9226 					    AF_INET, &dst);
9227 				}
9228 				goto err_ret;
9229 			}
9230 		}
9231 
9232 		/*
9233 		 * Pick a source address preferring non-deprecated ones.
9234 		 * Unlike ip_newroute, we don't do any source address
9235 		 * selection here since for multicast it really does not help
9236 		 * in inbound load spreading as in the unicast case.
9237 		 */
9238 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9239 		    (fire->ire_flags & RTF_SETSRC)) {
9240 			/*
9241 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9242 			 * on that interface. This ire has RTF_SETSRC flag, so
9243 			 * the source address of the packet must be changed.
9244 			 * Check that the ipif matching the requested source
9245 			 * address still exists.
9246 			 */
9247 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9248 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9249 		}
9250 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9251 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9252 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9253 		    (src_ipif == NULL)) {
9254 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9255 			if (src_ipif == NULL) {
9256 				if (ip_debug > 2) {
9257 					/* ip1dbg */
9258 					pr_addr_dbg("ip_newroute_ipif: "
9259 					    "no src for dst %s",
9260 					    AF_INET, &dst);
9261 				}
9262 				ip1dbg((" through interface %s\n",
9263 				    dst_ill->ill_name));
9264 				goto err_ret;
9265 			}
9266 			ipif_refrele(ipif);
9267 			ipif = src_ipif;
9268 			ipif_refhold(ipif);
9269 		}
9270 		if (src_ipif == NULL) {
9271 			src_ipif = ipif;
9272 			ipif_refhold(src_ipif);
9273 		}
9274 
9275 		/*
9276 		 * Assign a source address while we have the conn.
9277 		 * We can't have ip_wput_ire pick a source address when the
9278 		 * packet returns from arp since conn_unspec_src might be set
9279 		 * and we loose the conn when going through arp.
9280 		 */
9281 		if (ipha->ipha_src == INADDR_ANY &&
9282 		    (connp == NULL || !connp->conn_unspec_src)) {
9283 			ipha->ipha_src = src_ipif->ipif_src_addr;
9284 		}
9285 
9286 		/*
9287 		 * In the case of IP_XMIT_IF, it is possible that the
9288 		 * outgoing interface does not have an interface ire.
9289 		 */
9290 		if (CLASSD(ipha_dst) && (connp == NULL ||
9291 		    connp->conn_xmit_if_ill == NULL) &&
9292 		    infop->ip_opt_ill_index == 0) {
9293 			/* ipif_to_ire returns an held ire */
9294 			ire = ipif_to_ire(ipif);
9295 			if (ire == NULL)
9296 				goto err_ret;
9297 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9298 				goto err_ret;
9299 			/*
9300 			 * ihandle is needed when the ire is added to
9301 			 * cache table.
9302 			 */
9303 			save_ire = ire;
9304 			ihandle = save_ire->ire_ihandle;
9305 
9306 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9307 			    "flags %04x\n",
9308 			    (void *)ire, (void *)ipif, flags));
9309 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9310 			    (fire->ire_flags & RTF_MULTIRT)) {
9311 				/*
9312 				 * As requested by flags, an IRE_OFFSUBNET was
9313 				 * looked up on that interface. This ire has
9314 				 * RTF_MULTIRT flag, so the resolution loop will
9315 				 * be re-entered to resolve additional routes on
9316 				 * other interfaces. For that purpose, a copy of
9317 				 * the packet is performed at this point.
9318 				 */
9319 				fire->ire_last_used_time = lbolt;
9320 				copy_mp = copymsg(first_mp);
9321 				if (copy_mp) {
9322 					MULTIRT_DEBUG_TAG(copy_mp);
9323 				}
9324 			}
9325 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9326 			    (fire->ire_flags & RTF_SETSRC)) {
9327 				/*
9328 				 * As requested by flags, an IRE_OFFSUBET was
9329 				 * looked up on that interface. This ire has
9330 				 * RTF_SETSRC flag, so the source address of the
9331 				 * packet must be changed.
9332 				 */
9333 				ipha->ipha_src = fire->ire_src_addr;
9334 			}
9335 		} else {
9336 			ASSERT((connp == NULL) ||
9337 			    (connp->conn_xmit_if_ill != NULL) ||
9338 			    (connp->conn_dontroute) ||
9339 			    infop->ip_opt_ill_index != 0);
9340 			/*
9341 			 * The only ways we can come here are:
9342 			 * 1) IP_XMIT_IF socket option is set
9343 			 * 2) SO_DONTROUTE socket option is set
9344 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9345 			 * In all cases, the new ire will not be added
9346 			 * into cache table.
9347 			 */
9348 			ire_marks |= IRE_MARK_NOADD;
9349 		}
9350 
9351 		switch (ipif->ipif_net_type) {
9352 		case IRE_IF_NORESOLVER: {
9353 			/* We have what we need to build an IRE_CACHE. */
9354 
9355 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9356 			    (dst_ill->ill_resolver_mp == NULL)) {
9357 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9358 				    "for IRE_IF_NORESOLVER ire %p has "
9359 				    "no ill_resolver_mp\n",
9360 				    (void *)dst_ill, (void *)ire));
9361 				break;
9362 			}
9363 
9364 			/*
9365 			 * The new ire inherits the IRE_OFFSUBNET flags
9366 			 * and source address, if this was requested.
9367 			 */
9368 			ire = ire_create(
9369 			    (uchar_t *)&dst,		/* dest address */
9370 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9371 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9372 			    NULL,			/* gateway address */
9373 			    &ipif->ipif_mtu,
9374 			    NULL,			/* no src nce */
9375 			    dst_ill->ill_rq,		/* recv-from queue */
9376 			    dst_ill->ill_wq,		/* send-to queue */
9377 			    IRE_CACHE,
9378 			    src_ipif,
9379 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9380 			    (fire != NULL) ?		/* Parent handle */
9381 			    fire->ire_phandle : 0,
9382 			    ihandle,			/* Interface handle */
9383 			    (fire != NULL) ?
9384 			    (fire->ire_flags &
9385 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9386 			    (save_ire == NULL ? &ire_uinfo_null :
9387 			    &save_ire->ire_uinfo),
9388 			    NULL,
9389 			    NULL,
9390 			    ipst);
9391 
9392 			if (ire == NULL) {
9393 				if (save_ire != NULL)
9394 					ire_refrele(save_ire);
9395 				break;
9396 			}
9397 
9398 			ire->ire_marks |= ire_marks;
9399 
9400 			/*
9401 			 * If IRE_MARK_NOADD is set then we need to convert
9402 			 * the max_fragp to a useable value now. This is
9403 			 * normally done in ire_add_v[46]. We also need to
9404 			 * associate the ire with an nce (normally would be
9405 			 * done in ip_wput_nondata()).
9406 			 *
9407 			 * Note that IRE_MARK_NOADD packets created here
9408 			 * do not have a non-null ire_mp pointer. The null
9409 			 * value of ire_bucket indicates that they were
9410 			 * never added.
9411 			 */
9412 			if (ire->ire_marks & IRE_MARK_NOADD) {
9413 				uint_t  max_frag;
9414 
9415 				max_frag = *ire->ire_max_fragp;
9416 				ire->ire_max_fragp = NULL;
9417 				ire->ire_max_frag = max_frag;
9418 
9419 				if ((ire->ire_nce = ndp_lookup_v4(
9420 				    ire_to_ill(ire),
9421 				    (ire->ire_gateway_addr != INADDR_ANY ?
9422 				    &ire->ire_gateway_addr : &ire->ire_addr),
9423 				    B_FALSE)) == NULL) {
9424 					if (save_ire != NULL)
9425 						ire_refrele(save_ire);
9426 					break;
9427 				}
9428 				ASSERT(ire->ire_nce->nce_state ==
9429 				    ND_REACHABLE);
9430 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9431 			}
9432 
9433 			/* Prevent save_ire from getting deleted */
9434 			if (save_ire != NULL) {
9435 				IRB_REFHOLD(save_ire->ire_bucket);
9436 				/* Has it been removed already ? */
9437 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9438 					IRB_REFRELE(save_ire->ire_bucket);
9439 					ire_refrele(save_ire);
9440 					break;
9441 				}
9442 			}
9443 
9444 			ire_add_then_send(q, ire, first_mp);
9445 
9446 			/* Assert that save_ire is not deleted yet. */
9447 			if (save_ire != NULL) {
9448 				ASSERT(save_ire->ire_ptpn != NULL);
9449 				IRB_REFRELE(save_ire->ire_bucket);
9450 				ire_refrele(save_ire);
9451 				save_ire = NULL;
9452 			}
9453 			if (fire != NULL) {
9454 				ire_refrele(fire);
9455 				fire = NULL;
9456 			}
9457 
9458 			/*
9459 			 * the resolution loop is re-entered if this
9460 			 * was requested through flags and if we
9461 			 * actually are in a multirouting case.
9462 			 */
9463 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9464 				boolean_t need_resolve =
9465 				    ire_multirt_need_resolve(ipha_dst,
9466 				    MBLK_GETLABEL(copy_mp), ipst);
9467 				if (!need_resolve) {
9468 					MULTIRT_DEBUG_UNTAG(copy_mp);
9469 					freemsg(copy_mp);
9470 					copy_mp = NULL;
9471 				} else {
9472 					/*
9473 					 * ipif_lookup_group() calls
9474 					 * ire_lookup_multi() that uses
9475 					 * ire_ftable_lookup() to find
9476 					 * an IRE_INTERFACE for the group.
9477 					 * In the multirt case,
9478 					 * ire_lookup_multi() then invokes
9479 					 * ire_multirt_lookup() to find
9480 					 * the next resolvable ire.
9481 					 * As a result, we obtain an new
9482 					 * interface, derived from the
9483 					 * next ire.
9484 					 */
9485 					ipif_refrele(ipif);
9486 					ipif = ipif_lookup_group(ipha_dst,
9487 					    zoneid, ipst);
9488 					ip2dbg(("ip_newroute_ipif: "
9489 					    "multirt dst %08x, ipif %p\n",
9490 					    htonl(dst), (void *)ipif));
9491 					if (ipif != NULL) {
9492 						mp = copy_mp;
9493 						copy_mp = NULL;
9494 						multirt_resolve_next = B_TRUE;
9495 						continue;
9496 					} else {
9497 						freemsg(copy_mp);
9498 					}
9499 				}
9500 			}
9501 			if (ipif != NULL)
9502 				ipif_refrele(ipif);
9503 			ill_refrele(dst_ill);
9504 			ipif_refrele(src_ipif);
9505 			return;
9506 		}
9507 		case IRE_IF_RESOLVER:
9508 			/*
9509 			 * We can't build an IRE_CACHE yet, but at least
9510 			 * we found a resolver that can help.
9511 			 */
9512 			res_mp = dst_ill->ill_resolver_mp;
9513 			if (!OK_RESOLVER_MP(res_mp))
9514 				break;
9515 
9516 			/*
9517 			 * We obtain a partial IRE_CACHE which we will pass
9518 			 * along with the resolver query.  When the response
9519 			 * comes back it will be there ready for us to add.
9520 			 * The new ire inherits the IRE_OFFSUBNET flags
9521 			 * and source address, if this was requested.
9522 			 * The ire_max_frag is atomically set under the
9523 			 * irebucket lock in ire_add_v[46]. Only in the
9524 			 * case of IRE_MARK_NOADD, we set it here itself.
9525 			 */
9526 			ire = ire_create_mp(
9527 			    (uchar_t *)&dst,		/* dest address */
9528 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9529 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9530 			    NULL,			/* gateway address */
9531 			    (ire_marks & IRE_MARK_NOADD) ?
9532 			    ipif->ipif_mtu : 0,		/* max_frag */
9533 			    NULL,			/* no src nce */
9534 			    dst_ill->ill_rq,		/* recv-from queue */
9535 			    dst_ill->ill_wq,		/* send-to queue */
9536 			    IRE_CACHE,
9537 			    src_ipif,
9538 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9539 			    (fire != NULL) ?		/* Parent handle */
9540 			    fire->ire_phandle : 0,
9541 			    ihandle,			/* Interface handle */
9542 			    (fire != NULL) ?		/* flags if any */
9543 			    (fire->ire_flags &
9544 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9545 			    (save_ire == NULL ? &ire_uinfo_null :
9546 			    &save_ire->ire_uinfo),
9547 			    NULL,
9548 			    NULL,
9549 			    ipst);
9550 
9551 			if (save_ire != NULL) {
9552 				ire_refrele(save_ire);
9553 				save_ire = NULL;
9554 			}
9555 			if (ire == NULL)
9556 				break;
9557 
9558 			ire->ire_marks |= ire_marks;
9559 			/*
9560 			 * Construct message chain for the resolver of the
9561 			 * form:
9562 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9563 			 *
9564 			 * NOTE : ire will be added later when the response
9565 			 * comes back from ARP. If the response does not
9566 			 * come back, ARP frees the packet. For this reason,
9567 			 * we can't REFHOLD the bucket of save_ire to prevent
9568 			 * deletions. We may not be able to REFRELE the
9569 			 * bucket if the response never comes back.
9570 			 * Thus, before adding the ire, ire_add_v4 will make
9571 			 * sure that the interface route does not get deleted.
9572 			 * This is the only case unlike ip_newroute_v6,
9573 			 * ip_newroute_ipif_v6 where we can always prevent
9574 			 * deletions because ire_add_then_send is called after
9575 			 * creating the IRE.
9576 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9577 			 * does not add this IRE into the IRE CACHE.
9578 			 */
9579 			ASSERT(ire->ire_mp != NULL);
9580 			ire->ire_mp->b_cont = first_mp;
9581 			/* Have saved_mp handy, for cleanup if canput fails */
9582 			saved_mp = mp;
9583 			mp = copyb(res_mp);
9584 			if (mp == NULL) {
9585 				/* Prepare for cleanup */
9586 				mp = saved_mp; /* pkt */
9587 				ire_delete(ire); /* ire_mp */
9588 				ire = NULL;
9589 				if (copy_mp != NULL) {
9590 					MULTIRT_DEBUG_UNTAG(copy_mp);
9591 					freemsg(copy_mp);
9592 					copy_mp = NULL;
9593 				}
9594 				break;
9595 			}
9596 			linkb(mp, ire->ire_mp);
9597 
9598 			/*
9599 			 * Fill in the source and dest addrs for the resolver.
9600 			 * NOTE: this depends on memory layouts imposed by
9601 			 * ill_init().
9602 			 */
9603 			areq = (areq_t *)mp->b_rptr;
9604 			addrp = (ipaddr_t *)((char *)areq +
9605 			    areq->areq_sender_addr_offset);
9606 			*addrp = ire->ire_src_addr;
9607 			addrp = (ipaddr_t *)((char *)areq +
9608 			    areq->areq_target_addr_offset);
9609 			*addrp = dst;
9610 			/* Up to the resolver. */
9611 			if (canputnext(dst_ill->ill_rq) &&
9612 			    !(dst_ill->ill_arp_closing)) {
9613 				putnext(dst_ill->ill_rq, mp);
9614 				/*
9615 				 * The response will come back in ip_wput
9616 				 * with db_type IRE_DB_TYPE.
9617 				 */
9618 			} else {
9619 				mp->b_cont = NULL;
9620 				freeb(mp); /* areq */
9621 				ire_delete(ire); /* ire_mp */
9622 				saved_mp->b_next = NULL;
9623 				saved_mp->b_prev = NULL;
9624 				freemsg(first_mp); /* pkt */
9625 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9626 			}
9627 
9628 			if (fire != NULL) {
9629 				ire_refrele(fire);
9630 				fire = NULL;
9631 			}
9632 
9633 
9634 			/*
9635 			 * The resolution loop is re-entered if this was
9636 			 * requested through flags and we actually are
9637 			 * in a multirouting case.
9638 			 */
9639 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9640 				boolean_t need_resolve =
9641 				    ire_multirt_need_resolve(ipha_dst,
9642 				    MBLK_GETLABEL(copy_mp), ipst);
9643 				if (!need_resolve) {
9644 					MULTIRT_DEBUG_UNTAG(copy_mp);
9645 					freemsg(copy_mp);
9646 					copy_mp = NULL;
9647 				} else {
9648 					/*
9649 					 * ipif_lookup_group() calls
9650 					 * ire_lookup_multi() that uses
9651 					 * ire_ftable_lookup() to find
9652 					 * an IRE_INTERFACE for the group.
9653 					 * In the multirt case,
9654 					 * ire_lookup_multi() then invokes
9655 					 * ire_multirt_lookup() to find
9656 					 * the next resolvable ire.
9657 					 * As a result, we obtain an new
9658 					 * interface, derived from the
9659 					 * next ire.
9660 					 */
9661 					ipif_refrele(ipif);
9662 					ipif = ipif_lookup_group(ipha_dst,
9663 					    zoneid, ipst);
9664 					if (ipif != NULL) {
9665 						mp = copy_mp;
9666 						copy_mp = NULL;
9667 						multirt_resolve_next = B_TRUE;
9668 						continue;
9669 					} else {
9670 						freemsg(copy_mp);
9671 					}
9672 				}
9673 			}
9674 			if (ipif != NULL)
9675 				ipif_refrele(ipif);
9676 			ill_refrele(dst_ill);
9677 			ipif_refrele(src_ipif);
9678 			return;
9679 		default:
9680 			break;
9681 		}
9682 	} while (multirt_resolve_next);
9683 
9684 err_ret:
9685 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9686 	if (fire != NULL)
9687 		ire_refrele(fire);
9688 	ipif_refrele(ipif);
9689 	/* Did this packet originate externally? */
9690 	if (dst_ill != NULL)
9691 		ill_refrele(dst_ill);
9692 	if (src_ipif != NULL)
9693 		ipif_refrele(src_ipif);
9694 	if (mp->b_prev || mp->b_next) {
9695 		mp->b_next = NULL;
9696 		mp->b_prev = NULL;
9697 	} else {
9698 		/*
9699 		 * Since ip_wput() isn't close to finished, we fill
9700 		 * in enough of the header for credible error reporting.
9701 		 */
9702 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9703 			/* Failed */
9704 			freemsg(first_mp);
9705 			if (ire != NULL)
9706 				ire_refrele(ire);
9707 			return;
9708 		}
9709 	}
9710 	/*
9711 	 * At this point we will have ire only if RTF_BLACKHOLE
9712 	 * or RTF_REJECT flags are set on the IRE. It will not
9713 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9714 	 */
9715 	if (ire != NULL) {
9716 		if (ire->ire_flags & RTF_BLACKHOLE) {
9717 			ire_refrele(ire);
9718 			freemsg(first_mp);
9719 			return;
9720 		}
9721 		ire_refrele(ire);
9722 	}
9723 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9724 }
9725 
9726 /* Name/Value Table Lookup Routine */
9727 char *
9728 ip_nv_lookup(nv_t *nv, int value)
9729 {
9730 	if (!nv)
9731 		return (NULL);
9732 	for (; nv->nv_name; nv++) {
9733 		if (nv->nv_value == value)
9734 			return (nv->nv_name);
9735 	}
9736 	return ("unknown");
9737 }
9738 
9739 /*
9740  * This is a module open, i.e. this is a control stream for access
9741  * to a DLPI device.  We allocate an ill_t as the instance data in
9742  * this case.
9743  */
9744 int
9745 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9746 {
9747 	ill_t	*ill;
9748 	int	err;
9749 	zoneid_t zoneid;
9750 	netstack_t *ns;
9751 	ip_stack_t *ipst;
9752 
9753 	/*
9754 	 * Prevent unprivileged processes from pushing IP so that
9755 	 * they can't send raw IP.
9756 	 */
9757 	if (secpolicy_net_rawaccess(credp) != 0)
9758 		return (EPERM);
9759 
9760 	ns = netstack_find_by_cred(credp);
9761 	ASSERT(ns != NULL);
9762 	ipst = ns->netstack_ip;
9763 	ASSERT(ipst != NULL);
9764 
9765 	/*
9766 	 * For exclusive stacks we set the zoneid to zero
9767 	 * to make IP operate as if in the global zone.
9768 	 */
9769 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9770 		zoneid = GLOBAL_ZONEID;
9771 	else
9772 		zoneid = crgetzoneid(credp);
9773 
9774 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9775 	q->q_ptr = WR(q)->q_ptr = ill;
9776 	ill->ill_ipst = ipst;
9777 	ill->ill_zoneid = zoneid;
9778 
9779 	/*
9780 	 * ill_init initializes the ill fields and then sends down
9781 	 * down a DL_INFO_REQ after calling qprocson.
9782 	 */
9783 	err = ill_init(q, ill);
9784 	if (err != 0) {
9785 		mi_free(ill);
9786 		netstack_rele(ipst->ips_netstack);
9787 		q->q_ptr = NULL;
9788 		WR(q)->q_ptr = NULL;
9789 		return (err);
9790 	}
9791 
9792 	/* ill_init initializes the ipsq marking this thread as writer */
9793 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9794 	/* Wait for the DL_INFO_ACK */
9795 	mutex_enter(&ill->ill_lock);
9796 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9797 		/*
9798 		 * Return value of 0 indicates a pending signal.
9799 		 */
9800 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9801 		if (err == 0) {
9802 			mutex_exit(&ill->ill_lock);
9803 			(void) ip_close(q, 0);
9804 			return (EINTR);
9805 		}
9806 	}
9807 	mutex_exit(&ill->ill_lock);
9808 
9809 	/*
9810 	 * ip_rput_other could have set an error  in ill_error on
9811 	 * receipt of M_ERROR.
9812 	 */
9813 
9814 	err = ill->ill_error;
9815 	if (err != 0) {
9816 		(void) ip_close(q, 0);
9817 		return (err);
9818 	}
9819 
9820 	ill->ill_credp = credp;
9821 	crhold(credp);
9822 
9823 	mutex_enter(&ipst->ips_ip_mi_lock);
9824 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9825 	    credp);
9826 	mutex_exit(&ipst->ips_ip_mi_lock);
9827 	if (err) {
9828 		(void) ip_close(q, 0);
9829 		return (err);
9830 	}
9831 	return (0);
9832 }
9833 
9834 /* IP open routine. */
9835 int
9836 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9837 {
9838 	conn_t 		*connp;
9839 	major_t		maj;
9840 	zoneid_t	zoneid;
9841 	netstack_t	*ns;
9842 	ip_stack_t	*ipst;
9843 
9844 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9845 
9846 	/* Allow reopen. */
9847 	if (q->q_ptr != NULL)
9848 		return (0);
9849 
9850 	if (sflag & MODOPEN) {
9851 		/* This is a module open */
9852 		return (ip_modopen(q, devp, flag, sflag, credp));
9853 	}
9854 
9855 	ns = netstack_find_by_cred(credp);
9856 	ASSERT(ns != NULL);
9857 	ipst = ns->netstack_ip;
9858 	ASSERT(ipst != NULL);
9859 
9860 	/*
9861 	 * For exclusive stacks we set the zoneid to zero
9862 	 * to make IP operate as if in the global zone.
9863 	 */
9864 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9865 		zoneid = GLOBAL_ZONEID;
9866 	else
9867 		zoneid = crgetzoneid(credp);
9868 
9869 	/*
9870 	 * We are opening as a device. This is an IP client stream, and we
9871 	 * allocate an conn_t as the instance data.
9872 	 */
9873 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9874 
9875 	/*
9876 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9877 	 * done by netstack_find_by_cred()
9878 	 */
9879 	netstack_rele(ipst->ips_netstack);
9880 
9881 	connp->conn_zoneid = zoneid;
9882 
9883 	connp->conn_upq = q;
9884 	q->q_ptr = WR(q)->q_ptr = connp;
9885 
9886 	if (flag & SO_SOCKSTR)
9887 		connp->conn_flags |= IPCL_SOCKET;
9888 
9889 	/* Minor tells us which /dev entry was opened */
9890 	if (geteminor(*devp) == IPV6_MINOR) {
9891 		connp->conn_flags |= IPCL_ISV6;
9892 		connp->conn_af_isv6 = B_TRUE;
9893 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
9894 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9895 	} else {
9896 		connp->conn_af_isv6 = B_FALSE;
9897 		connp->conn_pkt_isv6 = B_FALSE;
9898 	}
9899 
9900 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9901 		/* CONN_DEC_REF takes care of netstack_rele() */
9902 		q->q_ptr = WR(q)->q_ptr = NULL;
9903 		CONN_DEC_REF(connp);
9904 		return (EBUSY);
9905 	}
9906 
9907 	maj = getemajor(*devp);
9908 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9909 
9910 	/*
9911 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9912 	 */
9913 	connp->conn_cred = credp;
9914 	crhold(connp->conn_cred);
9915 
9916 	/*
9917 	 * If the caller has the process-wide flag set, then default to MAC
9918 	 * exempt mode.  This allows read-down to unlabeled hosts.
9919 	 */
9920 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9921 		connp->conn_mac_exempt = B_TRUE;
9922 
9923 	/*
9924 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9925 	 * administrative ops.  In these cases, we just need a normal conn_t
9926 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9927 	 * an error will be returned.
9928 	 */
9929 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9930 		connp->conn_rq = q;
9931 		connp->conn_wq = WR(q);
9932 	} else {
9933 		connp->conn_ulp = IPPROTO_SCTP;
9934 		connp->conn_rq = connp->conn_wq = NULL;
9935 	}
9936 	/* Non-zero default values */
9937 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9938 
9939 	/*
9940 	 * Make the conn globally visible to walkers
9941 	 */
9942 	ASSERT(connp->conn_ref == 1);
9943 	mutex_enter(&connp->conn_lock);
9944 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9945 	mutex_exit(&connp->conn_lock);
9946 
9947 	qprocson(q);
9948 
9949 	return (0);
9950 }
9951 
9952 /*
9953  * Change q_qinfo based on the value of isv6.
9954  * This can not called on an ill queue.
9955  * Note that there is no race since either q_qinfo works for conn queues - it
9956  * is just an optimization to enter the best wput routine directly.
9957  */
9958 void
9959 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
9960 {
9961 	ASSERT(q->q_flag & QREADR);
9962 	ASSERT(WR(q)->q_next == NULL);
9963 	ASSERT(q->q_ptr != NULL);
9964 
9965 	if (minor == IPV6_MINOR)  {
9966 		if (bump_mib) {
9967 			BUMP_MIB(&ipst->ips_ip6_mib,
9968 			    ipIfStatsOutSwitchIPVersion);
9969 		}
9970 		q->q_qinfo = &rinit_ipv6;
9971 		WR(q)->q_qinfo = &winit_ipv6;
9972 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9973 	} else {
9974 		if (bump_mib) {
9975 			BUMP_MIB(&ipst->ips_ip_mib,
9976 			    ipIfStatsOutSwitchIPVersion);
9977 		}
9978 		q->q_qinfo = &iprinit;
9979 		WR(q)->q_qinfo = &ipwinit;
9980 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9981 	}
9982 
9983 }
9984 
9985 /*
9986  * See if IPsec needs loading because of the options in mp.
9987  */
9988 static boolean_t
9989 ipsec_opt_present(mblk_t *mp)
9990 {
9991 	uint8_t *optcp, *next_optcp, *opt_endcp;
9992 	struct opthdr *opt;
9993 	struct T_opthdr *topt;
9994 	int opthdr_len;
9995 	t_uscalar_t optname, optlevel;
9996 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9997 	ipsec_req_t *ipsr;
9998 
9999 	/*
10000 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10001 	 * return TRUE.
10002 	 */
10003 
10004 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10005 	opt_endcp = optcp + tor->OPT_length;
10006 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10007 		opthdr_len = sizeof (struct T_opthdr);
10008 	} else {		/* O_OPTMGMT_REQ */
10009 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10010 		opthdr_len = sizeof (struct opthdr);
10011 	}
10012 	for (; optcp < opt_endcp; optcp = next_optcp) {
10013 		if (optcp + opthdr_len > opt_endcp)
10014 			return (B_FALSE);	/* Not enough option header. */
10015 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10016 			topt = (struct T_opthdr *)optcp;
10017 			optlevel = topt->level;
10018 			optname = topt->name;
10019 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10020 		} else {
10021 			opt = (struct opthdr *)optcp;
10022 			optlevel = opt->level;
10023 			optname = opt->name;
10024 			next_optcp = optcp + opthdr_len +
10025 			    _TPI_ALIGN_OPT(opt->len);
10026 		}
10027 		if ((next_optcp < optcp) || /* wraparound pointer space */
10028 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10029 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10030 			return (B_FALSE); /* bad option buffer */
10031 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10032 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10033 			/*
10034 			 * Check to see if it's an all-bypass or all-zeroes
10035 			 * IPsec request.  Don't bother loading IPsec if
10036 			 * the socket doesn't want to use it.  (A good example
10037 			 * is a bypass request.)
10038 			 *
10039 			 * Basically, if any of the non-NEVER bits are set,
10040 			 * load IPsec.
10041 			 */
10042 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10043 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10044 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10045 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10046 			    != 0)
10047 				return (B_TRUE);
10048 		}
10049 	}
10050 	return (B_FALSE);
10051 }
10052 
10053 /*
10054  * If conn is is waiting for ipsec to finish loading, kick it.
10055  */
10056 /* ARGSUSED */
10057 static void
10058 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10059 {
10060 	t_scalar_t	optreq_prim;
10061 	mblk_t		*mp;
10062 	cred_t		*cr;
10063 	int		err = 0;
10064 
10065 	/*
10066 	 * This function is called, after ipsec loading is complete.
10067 	 * Since IP checks exclusively and atomically (i.e it prevents
10068 	 * ipsec load from completing until ip_optcom_req completes)
10069 	 * whether ipsec load is complete, there cannot be a race with IP
10070 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10071 	 */
10072 	mutex_enter(&connp->conn_lock);
10073 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10074 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10075 		mp = connp->conn_ipsec_opt_mp;
10076 		connp->conn_ipsec_opt_mp = NULL;
10077 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10078 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10079 		mutex_exit(&connp->conn_lock);
10080 
10081 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10082 
10083 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10084 		if (optreq_prim == T_OPTMGMT_REQ) {
10085 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10086 			    &ip_opt_obj);
10087 		} else {
10088 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10089 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10090 			    &ip_opt_obj);
10091 		}
10092 		if (err != EINPROGRESS)
10093 			CONN_OPER_PENDING_DONE(connp);
10094 		return;
10095 	}
10096 	mutex_exit(&connp->conn_lock);
10097 }
10098 
10099 /*
10100  * Called from the ipsec_loader thread, outside any perimeter, to tell
10101  * ip qenable any of the queues waiting for the ipsec loader to
10102  * complete.
10103  */
10104 void
10105 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10106 {
10107 	netstack_t *ns = ipss->ipsec_netstack;
10108 
10109 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10110 }
10111 
10112 /*
10113  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10114  * determines the grp on which it has to become exclusive, queues the mp
10115  * and sq draining restarts the optmgmt
10116  */
10117 static boolean_t
10118 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10119 {
10120 	conn_t *connp = Q_TO_CONN(q);
10121 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10122 
10123 	/*
10124 	 * Take IPsec requests and treat them special.
10125 	 */
10126 	if (ipsec_opt_present(mp)) {
10127 		/* First check if IPsec is loaded. */
10128 		mutex_enter(&ipss->ipsec_loader_lock);
10129 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10130 			mutex_exit(&ipss->ipsec_loader_lock);
10131 			return (B_FALSE);
10132 		}
10133 		mutex_enter(&connp->conn_lock);
10134 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10135 
10136 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10137 		connp->conn_ipsec_opt_mp = mp;
10138 		mutex_exit(&connp->conn_lock);
10139 		mutex_exit(&ipss->ipsec_loader_lock);
10140 
10141 		ipsec_loader_loadnow(ipss);
10142 		return (B_TRUE);
10143 	}
10144 	return (B_FALSE);
10145 }
10146 
10147 /*
10148  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10149  * all of them are copied to the conn_t. If the req is "zero", the policy is
10150  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10151  * fields.
10152  * We keep only the latest setting of the policy and thus policy setting
10153  * is not incremental/cumulative.
10154  *
10155  * Requests to set policies with multiple alternative actions will
10156  * go through a different API.
10157  */
10158 int
10159 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10160 {
10161 	uint_t ah_req = 0;
10162 	uint_t esp_req = 0;
10163 	uint_t se_req = 0;
10164 	ipsec_selkey_t sel;
10165 	ipsec_act_t *actp = NULL;
10166 	uint_t nact;
10167 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10168 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10169 	ipsec_policy_root_t *pr;
10170 	ipsec_policy_head_t *ph;
10171 	int fam;
10172 	boolean_t is_pol_reset;
10173 	int error = 0;
10174 	netstack_t	*ns = connp->conn_netstack;
10175 	ip_stack_t	*ipst = ns->netstack_ip;
10176 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10177 
10178 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10179 
10180 	/*
10181 	 * The IP_SEC_OPT option does not allow variable length parameters,
10182 	 * hence a request cannot be NULL.
10183 	 */
10184 	if (req == NULL)
10185 		return (EINVAL);
10186 
10187 	ah_req = req->ipsr_ah_req;
10188 	esp_req = req->ipsr_esp_req;
10189 	se_req = req->ipsr_self_encap_req;
10190 
10191 	/*
10192 	 * Are we dealing with a request to reset the policy (i.e.
10193 	 * zero requests).
10194 	 */
10195 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10196 	    (esp_req & REQ_MASK) == 0 &&
10197 	    (se_req & REQ_MASK) == 0);
10198 
10199 	if (!is_pol_reset) {
10200 		/*
10201 		 * If we couldn't load IPsec, fail with "protocol
10202 		 * not supported".
10203 		 * IPsec may not have been loaded for a request with zero
10204 		 * policies, so we don't fail in this case.
10205 		 */
10206 		mutex_enter(&ipss->ipsec_loader_lock);
10207 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10208 			mutex_exit(&ipss->ipsec_loader_lock);
10209 			return (EPROTONOSUPPORT);
10210 		}
10211 		mutex_exit(&ipss->ipsec_loader_lock);
10212 
10213 		/*
10214 		 * Test for valid requests. Invalid algorithms
10215 		 * need to be tested by IPsec code because new
10216 		 * algorithms can be added dynamically.
10217 		 */
10218 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10219 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10220 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10221 			return (EINVAL);
10222 		}
10223 
10224 		/*
10225 		 * Only privileged users can issue these
10226 		 * requests.
10227 		 */
10228 		if (((ah_req & IPSEC_PREF_NEVER) ||
10229 		    (esp_req & IPSEC_PREF_NEVER) ||
10230 		    (se_req & IPSEC_PREF_NEVER)) &&
10231 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10232 			return (EPERM);
10233 		}
10234 
10235 		/*
10236 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10237 		 * are mutually exclusive.
10238 		 */
10239 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10240 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10241 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10242 			/* Both of them are set */
10243 			return (EINVAL);
10244 		}
10245 	}
10246 
10247 	mutex_enter(&connp->conn_lock);
10248 
10249 	/*
10250 	 * If we have already cached policies in ip_bind_connected*(), don't
10251 	 * let them change now. We cache policies for connections
10252 	 * whose src,dst [addr, port] is known.
10253 	 */
10254 	if (connp->conn_policy_cached) {
10255 		mutex_exit(&connp->conn_lock);
10256 		return (EINVAL);
10257 	}
10258 
10259 	/*
10260 	 * We have a zero policies, reset the connection policy if already
10261 	 * set. This will cause the connection to inherit the
10262 	 * global policy, if any.
10263 	 */
10264 	if (is_pol_reset) {
10265 		if (connp->conn_policy != NULL) {
10266 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10267 			connp->conn_policy = NULL;
10268 		}
10269 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10270 		connp->conn_in_enforce_policy = B_FALSE;
10271 		connp->conn_out_enforce_policy = B_FALSE;
10272 		mutex_exit(&connp->conn_lock);
10273 		return (0);
10274 	}
10275 
10276 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10277 	    ipst->ips_netstack);
10278 	if (ph == NULL)
10279 		goto enomem;
10280 
10281 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10282 	if (actp == NULL)
10283 		goto enomem;
10284 
10285 	/*
10286 	 * Always allocate IPv4 policy entries, since they can also
10287 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10288 	 */
10289 	bzero(&sel, sizeof (sel));
10290 	sel.ipsl_valid = IPSL_IPV4;
10291 
10292 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10293 	    ipst->ips_netstack);
10294 	if (pin4 == NULL)
10295 		goto enomem;
10296 
10297 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10298 	    ipst->ips_netstack);
10299 	if (pout4 == NULL)
10300 		goto enomem;
10301 
10302 	if (connp->conn_pkt_isv6) {
10303 		/*
10304 		 * We're looking at a v6 socket, also allocate the
10305 		 * v6-specific entries...
10306 		 */
10307 		sel.ipsl_valid = IPSL_IPV6;
10308 		pin6 = ipsec_policy_create(&sel, actp, nact,
10309 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10310 		if (pin6 == NULL)
10311 			goto enomem;
10312 
10313 		pout6 = ipsec_policy_create(&sel, actp, nact,
10314 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10315 		if (pout6 == NULL)
10316 			goto enomem;
10317 
10318 		/*
10319 		 * .. and file them away in the right place.
10320 		 */
10321 		fam = IPSEC_AF_V6;
10322 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10323 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10324 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10325 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10326 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10327 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10328 	}
10329 
10330 	ipsec_actvec_free(actp, nact);
10331 
10332 	/*
10333 	 * File the v4 policies.
10334 	 */
10335 	fam = IPSEC_AF_V4;
10336 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10337 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10338 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10339 
10340 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10341 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10342 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10343 
10344 	/*
10345 	 * If the requests need security, set enforce_policy.
10346 	 * If the requests are IPSEC_PREF_NEVER, one should
10347 	 * still set conn_out_enforce_policy so that an ipsec_out
10348 	 * gets attached in ip_wput. This is needed so that
10349 	 * for connections that we don't cache policy in ip_bind,
10350 	 * if global policy matches in ip_wput_attach_policy, we
10351 	 * don't wrongly inherit global policy. Similarly, we need
10352 	 * to set conn_in_enforce_policy also so that we don't verify
10353 	 * policy wrongly.
10354 	 */
10355 	if ((ah_req & REQ_MASK) != 0 ||
10356 	    (esp_req & REQ_MASK) != 0 ||
10357 	    (se_req & REQ_MASK) != 0) {
10358 		connp->conn_in_enforce_policy = B_TRUE;
10359 		connp->conn_out_enforce_policy = B_TRUE;
10360 		connp->conn_flags |= IPCL_CHECK_POLICY;
10361 	}
10362 
10363 	mutex_exit(&connp->conn_lock);
10364 	return (error);
10365 #undef REQ_MASK
10366 
10367 	/*
10368 	 * Common memory-allocation-failure exit path.
10369 	 */
10370 enomem:
10371 	mutex_exit(&connp->conn_lock);
10372 	if (actp != NULL)
10373 		ipsec_actvec_free(actp, nact);
10374 	if (pin4 != NULL)
10375 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10376 	if (pout4 != NULL)
10377 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10378 	if (pin6 != NULL)
10379 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10380 	if (pout6 != NULL)
10381 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10382 	return (ENOMEM);
10383 }
10384 
10385 /*
10386  * Only for options that pass in an IP addr. Currently only V4 options
10387  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10388  * So this function assumes level is IPPROTO_IP
10389  */
10390 int
10391 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10392     mblk_t *first_mp)
10393 {
10394 	ipif_t *ipif = NULL;
10395 	int error;
10396 	ill_t *ill;
10397 	int zoneid;
10398 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10399 
10400 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10401 
10402 	if (addr != INADDR_ANY || checkonly) {
10403 		ASSERT(connp != NULL);
10404 		zoneid = IPCL_ZONEID(connp);
10405 		if (option == IP_NEXTHOP) {
10406 			ipif = ipif_lookup_onlink_addr(addr,
10407 			    connp->conn_zoneid, ipst);
10408 		} else {
10409 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10410 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10411 			    &error, ipst);
10412 		}
10413 		if (ipif == NULL) {
10414 			if (error == EINPROGRESS)
10415 				return (error);
10416 			else if ((option == IP_MULTICAST_IF) ||
10417 			    (option == IP_NEXTHOP))
10418 				return (EHOSTUNREACH);
10419 			else
10420 				return (EINVAL);
10421 		} else if (checkonly) {
10422 			if (option == IP_MULTICAST_IF) {
10423 				ill = ipif->ipif_ill;
10424 				/* not supported by the virtual network iface */
10425 				if (IS_VNI(ill)) {
10426 					ipif_refrele(ipif);
10427 					return (EINVAL);
10428 				}
10429 			}
10430 			ipif_refrele(ipif);
10431 			return (0);
10432 		}
10433 		ill = ipif->ipif_ill;
10434 		mutex_enter(&connp->conn_lock);
10435 		mutex_enter(&ill->ill_lock);
10436 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10437 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10438 			mutex_exit(&ill->ill_lock);
10439 			mutex_exit(&connp->conn_lock);
10440 			ipif_refrele(ipif);
10441 			return (option == IP_MULTICAST_IF ?
10442 			    EHOSTUNREACH : EINVAL);
10443 		}
10444 	} else {
10445 		mutex_enter(&connp->conn_lock);
10446 	}
10447 
10448 	/* None of the options below are supported on the VNI */
10449 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10450 		mutex_exit(&ill->ill_lock);
10451 		mutex_exit(&connp->conn_lock);
10452 		ipif_refrele(ipif);
10453 		return (EINVAL);
10454 	}
10455 
10456 	switch (option) {
10457 	case IP_DONTFAILOVER_IF:
10458 		/*
10459 		 * This option is used by in.mpathd to ensure
10460 		 * that IPMP probe packets only go out on the
10461 		 * test interfaces. in.mpathd sets this option
10462 		 * on the non-failover interfaces.
10463 		 * For backward compatibility, this option
10464 		 * implicitly sets IP_MULTICAST_IF, as used
10465 		 * be done in bind(), so that ip_wput gets
10466 		 * this ipif to send mcast packets.
10467 		 */
10468 		if (ipif != NULL) {
10469 			ASSERT(addr != INADDR_ANY);
10470 			connp->conn_nofailover_ill = ipif->ipif_ill;
10471 			connp->conn_multicast_ipif = ipif;
10472 		} else {
10473 			ASSERT(addr == INADDR_ANY);
10474 			connp->conn_nofailover_ill = NULL;
10475 			connp->conn_multicast_ipif = NULL;
10476 		}
10477 		break;
10478 
10479 	case IP_MULTICAST_IF:
10480 		connp->conn_multicast_ipif = ipif;
10481 		break;
10482 	case IP_NEXTHOP:
10483 		connp->conn_nexthop_v4 = addr;
10484 		connp->conn_nexthop_set = B_TRUE;
10485 		break;
10486 	}
10487 
10488 	if (ipif != NULL) {
10489 		mutex_exit(&ill->ill_lock);
10490 		mutex_exit(&connp->conn_lock);
10491 		ipif_refrele(ipif);
10492 		return (0);
10493 	}
10494 	mutex_exit(&connp->conn_lock);
10495 	/* We succeded in cleared the option */
10496 	return (0);
10497 }
10498 
10499 /*
10500  * For options that pass in an ifindex specifying the ill. V6 options always
10501  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10502  */
10503 int
10504 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10505     int level, int option, mblk_t *first_mp)
10506 {
10507 	ill_t *ill = NULL;
10508 	int error = 0;
10509 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10510 
10511 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10512 	if (ifindex != 0) {
10513 		ASSERT(connp != NULL);
10514 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10515 		    first_mp, ip_restart_optmgmt, &error, ipst);
10516 		if (ill != NULL) {
10517 			if (checkonly) {
10518 				/* not supported by the virtual network iface */
10519 				if (IS_VNI(ill)) {
10520 					ill_refrele(ill);
10521 					return (EINVAL);
10522 				}
10523 				ill_refrele(ill);
10524 				return (0);
10525 			}
10526 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10527 			    0, NULL)) {
10528 				ill_refrele(ill);
10529 				ill = NULL;
10530 				mutex_enter(&connp->conn_lock);
10531 				goto setit;
10532 			}
10533 			mutex_enter(&connp->conn_lock);
10534 			mutex_enter(&ill->ill_lock);
10535 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10536 				mutex_exit(&ill->ill_lock);
10537 				mutex_exit(&connp->conn_lock);
10538 				ill_refrele(ill);
10539 				ill = NULL;
10540 				mutex_enter(&connp->conn_lock);
10541 			}
10542 			goto setit;
10543 		} else if (error == EINPROGRESS) {
10544 			return (error);
10545 		} else {
10546 			error = 0;
10547 		}
10548 	}
10549 	mutex_enter(&connp->conn_lock);
10550 setit:
10551 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10552 
10553 	/*
10554 	 * The options below assume that the ILL (if any) transmits and/or
10555 	 * receives traffic. Neither of which is true for the virtual network
10556 	 * interface, so fail setting these on a VNI.
10557 	 */
10558 	if (IS_VNI(ill)) {
10559 		ASSERT(ill != NULL);
10560 		mutex_exit(&ill->ill_lock);
10561 		mutex_exit(&connp->conn_lock);
10562 		ill_refrele(ill);
10563 		return (EINVAL);
10564 	}
10565 
10566 	if (level == IPPROTO_IP) {
10567 		switch (option) {
10568 		case IP_BOUND_IF:
10569 			connp->conn_incoming_ill = ill;
10570 			connp->conn_outgoing_ill = ill;
10571 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10572 			    0 : ifindex;
10573 			break;
10574 
10575 		case IP_XMIT_IF:
10576 			/*
10577 			 * Similar to IP_BOUND_IF, but this only
10578 			 * determines the outgoing interface for
10579 			 * unicast packets. Also no IRE_CACHE entry
10580 			 * is added for the destination of the
10581 			 * outgoing packets.
10582 			 */
10583 			connp->conn_xmit_if_ill = ill;
10584 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10585 			    0 : ifindex;
10586 			break;
10587 
10588 		case IP_MULTICAST_IF:
10589 			/*
10590 			 * This option is an internal special. The socket
10591 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10592 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10593 			 * specifies an ifindex and we try first on V6 ill's.
10594 			 * If we don't find one, we they try using on v4 ill's
10595 			 * intenally and we come here.
10596 			 */
10597 			if (!checkonly && ill != NULL) {
10598 				ipif_t	*ipif;
10599 				ipif = ill->ill_ipif;
10600 
10601 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10602 					mutex_exit(&ill->ill_lock);
10603 					mutex_exit(&connp->conn_lock);
10604 					ill_refrele(ill);
10605 					ill = NULL;
10606 					mutex_enter(&connp->conn_lock);
10607 				} else {
10608 					connp->conn_multicast_ipif = ipif;
10609 				}
10610 			}
10611 			break;
10612 		}
10613 	} else {
10614 		switch (option) {
10615 		case IPV6_BOUND_IF:
10616 			connp->conn_incoming_ill = ill;
10617 			connp->conn_outgoing_ill = ill;
10618 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10619 			    0 : ifindex;
10620 			break;
10621 
10622 		case IPV6_BOUND_PIF:
10623 			/*
10624 			 * Limit all transmit to this ill.
10625 			 * Unlike IPV6_BOUND_IF, using this option
10626 			 * prevents load spreading and failover from
10627 			 * happening when the interface is part of the
10628 			 * group. That's why we don't need to remember
10629 			 * the ifindex in orig_bound_ifindex as in
10630 			 * IPV6_BOUND_IF.
10631 			 */
10632 			connp->conn_outgoing_pill = ill;
10633 			break;
10634 
10635 		case IPV6_DONTFAILOVER_IF:
10636 			/*
10637 			 * This option is used by in.mpathd to ensure
10638 			 * that IPMP probe packets only go out on the
10639 			 * test interfaces. in.mpathd sets this option
10640 			 * on the non-failover interfaces.
10641 			 */
10642 			connp->conn_nofailover_ill = ill;
10643 			/*
10644 			 * For backward compatibility, this option
10645 			 * implicitly sets ip_multicast_ill as used in
10646 			 * IP_MULTICAST_IF so that ip_wput gets
10647 			 * this ipif to send mcast packets.
10648 			 */
10649 			connp->conn_multicast_ill = ill;
10650 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10651 			    0 : ifindex;
10652 			break;
10653 
10654 		case IPV6_MULTICAST_IF:
10655 			/*
10656 			 * Set conn_multicast_ill to be the IPv6 ill.
10657 			 * Set conn_multicast_ipif to be an IPv4 ipif
10658 			 * for ifindex to make IPv4 mapped addresses
10659 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10660 			 * Even if no IPv6 ill exists for the ifindex
10661 			 * we need to check for an IPv4 ifindex in order
10662 			 * for this to work with mapped addresses. In that
10663 			 * case only set conn_multicast_ipif.
10664 			 */
10665 			if (!checkonly) {
10666 				if (ifindex == 0) {
10667 					connp->conn_multicast_ill = NULL;
10668 					connp->conn_orig_multicast_ifindex = 0;
10669 					connp->conn_multicast_ipif = NULL;
10670 				} else if (ill != NULL) {
10671 					connp->conn_multicast_ill = ill;
10672 					connp->conn_orig_multicast_ifindex =
10673 					    ifindex;
10674 				}
10675 			}
10676 			break;
10677 		}
10678 	}
10679 
10680 	if (ill != NULL) {
10681 		mutex_exit(&ill->ill_lock);
10682 		mutex_exit(&connp->conn_lock);
10683 		ill_refrele(ill);
10684 		return (0);
10685 	}
10686 	mutex_exit(&connp->conn_lock);
10687 	/*
10688 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10689 	 * locate the ill and could not set the option (ifindex != 0)
10690 	 */
10691 	return (ifindex == 0 ? 0 : EINVAL);
10692 }
10693 
10694 /* This routine sets socket options. */
10695 /* ARGSUSED */
10696 int
10697 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10698     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10699     void *dummy, cred_t *cr, mblk_t *first_mp)
10700 {
10701 	int		*i1 = (int *)invalp;
10702 	conn_t		*connp = Q_TO_CONN(q);
10703 	int		error = 0;
10704 	boolean_t	checkonly;
10705 	ire_t		*ire;
10706 	boolean_t	found;
10707 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10708 
10709 	switch (optset_context) {
10710 
10711 	case SETFN_OPTCOM_CHECKONLY:
10712 		checkonly = B_TRUE;
10713 		/*
10714 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10715 		 * inlen != 0 implies value supplied and
10716 		 * 	we have to "pretend" to set it.
10717 		 * inlen == 0 implies that there is no
10718 		 * 	value part in T_CHECK request and just validation
10719 		 * done elsewhere should be enough, we just return here.
10720 		 */
10721 		if (inlen == 0) {
10722 			*outlenp = 0;
10723 			return (0);
10724 		}
10725 		break;
10726 	case SETFN_OPTCOM_NEGOTIATE:
10727 	case SETFN_UD_NEGOTIATE:
10728 	case SETFN_CONN_NEGOTIATE:
10729 		checkonly = B_FALSE;
10730 		break;
10731 	default:
10732 		/*
10733 		 * We should never get here
10734 		 */
10735 		*outlenp = 0;
10736 		return (EINVAL);
10737 	}
10738 
10739 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10740 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10741 
10742 	/*
10743 	 * For fixed length options, no sanity check
10744 	 * of passed in length is done. It is assumed *_optcom_req()
10745 	 * routines do the right thing.
10746 	 */
10747 
10748 	switch (level) {
10749 	case SOL_SOCKET:
10750 		/*
10751 		 * conn_lock protects the bitfields, and is used to
10752 		 * set the fields atomically.
10753 		 */
10754 		switch (name) {
10755 		case SO_BROADCAST:
10756 			if (!checkonly) {
10757 				/* TODO: use value someplace? */
10758 				mutex_enter(&connp->conn_lock);
10759 				connp->conn_broadcast = *i1 ? 1 : 0;
10760 				mutex_exit(&connp->conn_lock);
10761 			}
10762 			break;	/* goto sizeof (int) option return */
10763 		case SO_USELOOPBACK:
10764 			if (!checkonly) {
10765 				/* TODO: use value someplace? */
10766 				mutex_enter(&connp->conn_lock);
10767 				connp->conn_loopback = *i1 ? 1 : 0;
10768 				mutex_exit(&connp->conn_lock);
10769 			}
10770 			break;	/* goto sizeof (int) option return */
10771 		case SO_DONTROUTE:
10772 			if (!checkonly) {
10773 				mutex_enter(&connp->conn_lock);
10774 				connp->conn_dontroute = *i1 ? 1 : 0;
10775 				mutex_exit(&connp->conn_lock);
10776 			}
10777 			break;	/* goto sizeof (int) option return */
10778 		case SO_REUSEADDR:
10779 			if (!checkonly) {
10780 				mutex_enter(&connp->conn_lock);
10781 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10782 				mutex_exit(&connp->conn_lock);
10783 			}
10784 			break;	/* goto sizeof (int) option return */
10785 		case SO_PROTOTYPE:
10786 			if (!checkonly) {
10787 				mutex_enter(&connp->conn_lock);
10788 				connp->conn_proto = *i1;
10789 				mutex_exit(&connp->conn_lock);
10790 			}
10791 			break;	/* goto sizeof (int) option return */
10792 		case SO_ALLZONES:
10793 			if (!checkonly) {
10794 				mutex_enter(&connp->conn_lock);
10795 				if (IPCL_IS_BOUND(connp)) {
10796 					mutex_exit(&connp->conn_lock);
10797 					return (EINVAL);
10798 				}
10799 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10800 				mutex_exit(&connp->conn_lock);
10801 			}
10802 			break;	/* goto sizeof (int) option return */
10803 		case SO_ANON_MLP:
10804 			if (!checkonly) {
10805 				mutex_enter(&connp->conn_lock);
10806 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10807 				mutex_exit(&connp->conn_lock);
10808 			}
10809 			break;	/* goto sizeof (int) option return */
10810 		case SO_MAC_EXEMPT:
10811 			if (secpolicy_net_mac_aware(cr) != 0 ||
10812 			    IPCL_IS_BOUND(connp))
10813 				return (EACCES);
10814 			if (!checkonly) {
10815 				mutex_enter(&connp->conn_lock);
10816 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10817 				mutex_exit(&connp->conn_lock);
10818 			}
10819 			break;	/* goto sizeof (int) option return */
10820 		default:
10821 			/*
10822 			 * "soft" error (negative)
10823 			 * option not handled at this level
10824 			 * Note: Do not modify *outlenp
10825 			 */
10826 			return (-EINVAL);
10827 		}
10828 		break;
10829 	case IPPROTO_IP:
10830 		switch (name) {
10831 		case IP_NEXTHOP:
10832 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10833 				return (EPERM);
10834 			/* FALLTHRU */
10835 		case IP_MULTICAST_IF:
10836 		case IP_DONTFAILOVER_IF: {
10837 			ipaddr_t addr = *i1;
10838 
10839 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10840 			    first_mp);
10841 			if (error != 0)
10842 				return (error);
10843 			break;	/* goto sizeof (int) option return */
10844 		}
10845 
10846 		case IP_MULTICAST_TTL:
10847 			/* Recorded in transport above IP */
10848 			*outvalp = *invalp;
10849 			*outlenp = sizeof (uchar_t);
10850 			return (0);
10851 		case IP_MULTICAST_LOOP:
10852 			if (!checkonly) {
10853 				mutex_enter(&connp->conn_lock);
10854 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10855 				mutex_exit(&connp->conn_lock);
10856 			}
10857 			*outvalp = *invalp;
10858 			*outlenp = sizeof (uchar_t);
10859 			return (0);
10860 		case IP_ADD_MEMBERSHIP:
10861 		case MCAST_JOIN_GROUP:
10862 		case IP_DROP_MEMBERSHIP:
10863 		case MCAST_LEAVE_GROUP: {
10864 			struct ip_mreq *mreqp;
10865 			struct group_req *greqp;
10866 			ire_t *ire;
10867 			boolean_t done = B_FALSE;
10868 			ipaddr_t group, ifaddr;
10869 			struct sockaddr_in *sin;
10870 			uint32_t *ifindexp;
10871 			boolean_t mcast_opt = B_TRUE;
10872 			mcast_record_t fmode;
10873 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10874 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10875 
10876 			switch (name) {
10877 			case IP_ADD_MEMBERSHIP:
10878 				mcast_opt = B_FALSE;
10879 				/* FALLTHRU */
10880 			case MCAST_JOIN_GROUP:
10881 				fmode = MODE_IS_EXCLUDE;
10882 				optfn = ip_opt_add_group;
10883 				break;
10884 
10885 			case IP_DROP_MEMBERSHIP:
10886 				mcast_opt = B_FALSE;
10887 				/* FALLTHRU */
10888 			case MCAST_LEAVE_GROUP:
10889 				fmode = MODE_IS_INCLUDE;
10890 				optfn = ip_opt_delete_group;
10891 				break;
10892 			}
10893 
10894 			if (mcast_opt) {
10895 				greqp = (struct group_req *)i1;
10896 				sin = (struct sockaddr_in *)&greqp->gr_group;
10897 				if (sin->sin_family != AF_INET) {
10898 					*outlenp = 0;
10899 					return (ENOPROTOOPT);
10900 				}
10901 				group = (ipaddr_t)sin->sin_addr.s_addr;
10902 				ifaddr = INADDR_ANY;
10903 				ifindexp = &greqp->gr_interface;
10904 			} else {
10905 				mreqp = (struct ip_mreq *)i1;
10906 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10907 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10908 				ifindexp = NULL;
10909 			}
10910 
10911 			/*
10912 			 * In the multirouting case, we need to replicate
10913 			 * the request on all interfaces that will take part
10914 			 * in replication.  We do so because multirouting is
10915 			 * reflective, thus we will probably receive multi-
10916 			 * casts on those interfaces.
10917 			 * The ip_multirt_apply_membership() succeeds if the
10918 			 * operation succeeds on at least one interface.
10919 			 */
10920 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10921 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10922 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10923 			if (ire != NULL) {
10924 				if (ire->ire_flags & RTF_MULTIRT) {
10925 					error = ip_multirt_apply_membership(
10926 					    optfn, ire, connp, checkonly, group,
10927 					    fmode, INADDR_ANY, first_mp);
10928 					done = B_TRUE;
10929 				}
10930 				ire_refrele(ire);
10931 			}
10932 			if (!done) {
10933 				error = optfn(connp, checkonly, group, ifaddr,
10934 				    ifindexp, fmode, INADDR_ANY, first_mp);
10935 			}
10936 			if (error) {
10937 				/*
10938 				 * EINPROGRESS is a soft error, needs retry
10939 				 * so don't make *outlenp zero.
10940 				 */
10941 				if (error != EINPROGRESS)
10942 					*outlenp = 0;
10943 				return (error);
10944 			}
10945 			/* OK return - copy input buffer into output buffer */
10946 			if (invalp != outvalp) {
10947 				/* don't trust bcopy for identical src/dst */
10948 				bcopy(invalp, outvalp, inlen);
10949 			}
10950 			*outlenp = inlen;
10951 			return (0);
10952 		}
10953 		case IP_BLOCK_SOURCE:
10954 		case IP_UNBLOCK_SOURCE:
10955 		case IP_ADD_SOURCE_MEMBERSHIP:
10956 		case IP_DROP_SOURCE_MEMBERSHIP:
10957 		case MCAST_BLOCK_SOURCE:
10958 		case MCAST_UNBLOCK_SOURCE:
10959 		case MCAST_JOIN_SOURCE_GROUP:
10960 		case MCAST_LEAVE_SOURCE_GROUP: {
10961 			struct ip_mreq_source *imreqp;
10962 			struct group_source_req *gsreqp;
10963 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10964 			uint32_t ifindex = 0;
10965 			mcast_record_t fmode;
10966 			struct sockaddr_in *sin;
10967 			ire_t *ire;
10968 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10969 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10970 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10971 
10972 			switch (name) {
10973 			case IP_BLOCK_SOURCE:
10974 				mcast_opt = B_FALSE;
10975 				/* FALLTHRU */
10976 			case MCAST_BLOCK_SOURCE:
10977 				fmode = MODE_IS_EXCLUDE;
10978 				optfn = ip_opt_add_group;
10979 				break;
10980 
10981 			case IP_UNBLOCK_SOURCE:
10982 				mcast_opt = B_FALSE;
10983 				/* FALLTHRU */
10984 			case MCAST_UNBLOCK_SOURCE:
10985 				fmode = MODE_IS_EXCLUDE;
10986 				optfn = ip_opt_delete_group;
10987 				break;
10988 
10989 			case IP_ADD_SOURCE_MEMBERSHIP:
10990 				mcast_opt = B_FALSE;
10991 				/* FALLTHRU */
10992 			case MCAST_JOIN_SOURCE_GROUP:
10993 				fmode = MODE_IS_INCLUDE;
10994 				optfn = ip_opt_add_group;
10995 				break;
10996 
10997 			case IP_DROP_SOURCE_MEMBERSHIP:
10998 				mcast_opt = B_FALSE;
10999 				/* FALLTHRU */
11000 			case MCAST_LEAVE_SOURCE_GROUP:
11001 				fmode = MODE_IS_INCLUDE;
11002 				optfn = ip_opt_delete_group;
11003 				break;
11004 			}
11005 
11006 			if (mcast_opt) {
11007 				gsreqp = (struct group_source_req *)i1;
11008 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11009 					*outlenp = 0;
11010 					return (ENOPROTOOPT);
11011 				}
11012 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11013 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11014 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11015 				src = (ipaddr_t)sin->sin_addr.s_addr;
11016 				ifindex = gsreqp->gsr_interface;
11017 			} else {
11018 				imreqp = (struct ip_mreq_source *)i1;
11019 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11020 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11021 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11022 			}
11023 
11024 			/*
11025 			 * In the multirouting case, we need to replicate
11026 			 * the request as noted in the mcast cases above.
11027 			 */
11028 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11029 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11030 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11031 			if (ire != NULL) {
11032 				if (ire->ire_flags & RTF_MULTIRT) {
11033 					error = ip_multirt_apply_membership(
11034 					    optfn, ire, connp, checkonly, grp,
11035 					    fmode, src, first_mp);
11036 					done = B_TRUE;
11037 				}
11038 				ire_refrele(ire);
11039 			}
11040 			if (!done) {
11041 				error = optfn(connp, checkonly, grp, ifaddr,
11042 				    &ifindex, fmode, src, first_mp);
11043 			}
11044 			if (error != 0) {
11045 				/*
11046 				 * EINPROGRESS is a soft error, needs retry
11047 				 * so don't make *outlenp zero.
11048 				 */
11049 				if (error != EINPROGRESS)
11050 					*outlenp = 0;
11051 				return (error);
11052 			}
11053 			/* OK return - copy input buffer into output buffer */
11054 			if (invalp != outvalp) {
11055 				bcopy(invalp, outvalp, inlen);
11056 			}
11057 			*outlenp = inlen;
11058 			return (0);
11059 		}
11060 		case IP_SEC_OPT:
11061 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11062 			if (error != 0) {
11063 				*outlenp = 0;
11064 				return (error);
11065 			}
11066 			break;
11067 		case IP_HDRINCL:
11068 		case IP_OPTIONS:
11069 		case T_IP_OPTIONS:
11070 		case IP_TOS:
11071 		case T_IP_TOS:
11072 		case IP_TTL:
11073 		case IP_RECVDSTADDR:
11074 		case IP_RECVOPTS:
11075 			/* OK return - copy input buffer into output buffer */
11076 			if (invalp != outvalp) {
11077 				/* don't trust bcopy for identical src/dst */
11078 				bcopy(invalp, outvalp, inlen);
11079 			}
11080 			*outlenp = inlen;
11081 			return (0);
11082 		case IP_RECVIF:
11083 			/* Retrieve the inbound interface index */
11084 			if (!checkonly) {
11085 				mutex_enter(&connp->conn_lock);
11086 				connp->conn_recvif = *i1 ? 1 : 0;
11087 				mutex_exit(&connp->conn_lock);
11088 			}
11089 			break;	/* goto sizeof (int) option return */
11090 		case IP_RECVPKTINFO:
11091 			if (!checkonly) {
11092 				mutex_enter(&connp->conn_lock);
11093 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11094 				mutex_exit(&connp->conn_lock);
11095 			}
11096 			break;	/* goto sizeof (int) option return */
11097 		case IP_RECVSLLA:
11098 			/* Retrieve the source link layer address */
11099 			if (!checkonly) {
11100 				mutex_enter(&connp->conn_lock);
11101 				connp->conn_recvslla = *i1 ? 1 : 0;
11102 				mutex_exit(&connp->conn_lock);
11103 			}
11104 			break;	/* goto sizeof (int) option return */
11105 		case MRT_INIT:
11106 		case MRT_DONE:
11107 		case MRT_ADD_VIF:
11108 		case MRT_DEL_VIF:
11109 		case MRT_ADD_MFC:
11110 		case MRT_DEL_MFC:
11111 		case MRT_ASSERT:
11112 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11113 				*outlenp = 0;
11114 				return (error);
11115 			}
11116 			error = ip_mrouter_set((int)name, q, checkonly,
11117 			    (uchar_t *)invalp, inlen, first_mp);
11118 			if (error) {
11119 				*outlenp = 0;
11120 				return (error);
11121 			}
11122 			/* OK return - copy input buffer into output buffer */
11123 			if (invalp != outvalp) {
11124 				/* don't trust bcopy for identical src/dst */
11125 				bcopy(invalp, outvalp, inlen);
11126 			}
11127 			*outlenp = inlen;
11128 			return (0);
11129 		case IP_BOUND_IF:
11130 		case IP_XMIT_IF:
11131 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11132 			    level, name, first_mp);
11133 			if (error != 0)
11134 				return (error);
11135 			break; 		/* goto sizeof (int) option return */
11136 
11137 		case IP_UNSPEC_SRC:
11138 			/* Allow sending with a zero source address */
11139 			if (!checkonly) {
11140 				mutex_enter(&connp->conn_lock);
11141 				connp->conn_unspec_src = *i1 ? 1 : 0;
11142 				mutex_exit(&connp->conn_lock);
11143 			}
11144 			break;	/* goto sizeof (int) option return */
11145 		default:
11146 			/*
11147 			 * "soft" error (negative)
11148 			 * option not handled at this level
11149 			 * Note: Do not modify *outlenp
11150 			 */
11151 			return (-EINVAL);
11152 		}
11153 		break;
11154 	case IPPROTO_IPV6:
11155 		switch (name) {
11156 		case IPV6_BOUND_IF:
11157 		case IPV6_BOUND_PIF:
11158 		case IPV6_DONTFAILOVER_IF:
11159 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11160 			    level, name, first_mp);
11161 			if (error != 0)
11162 				return (error);
11163 			break; 		/* goto sizeof (int) option return */
11164 
11165 		case IPV6_MULTICAST_IF:
11166 			/*
11167 			 * The only possible errors are EINPROGRESS and
11168 			 * EINVAL. EINPROGRESS will be restarted and is not
11169 			 * a hard error. We call this option on both V4 and V6
11170 			 * If both return EINVAL, then this call returns
11171 			 * EINVAL. If at least one of them succeeds we
11172 			 * return success.
11173 			 */
11174 			found = B_FALSE;
11175 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11176 			    level, name, first_mp);
11177 			if (error == EINPROGRESS)
11178 				return (error);
11179 			if (error == 0)
11180 				found = B_TRUE;
11181 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11182 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11183 			if (error == 0)
11184 				found = B_TRUE;
11185 			if (!found)
11186 				return (error);
11187 			break; 		/* goto sizeof (int) option return */
11188 
11189 		case IPV6_MULTICAST_HOPS:
11190 			/* Recorded in transport above IP */
11191 			break;	/* goto sizeof (int) option return */
11192 		case IPV6_MULTICAST_LOOP:
11193 			if (!checkonly) {
11194 				mutex_enter(&connp->conn_lock);
11195 				connp->conn_multicast_loop = *i1;
11196 				mutex_exit(&connp->conn_lock);
11197 			}
11198 			break;	/* goto sizeof (int) option return */
11199 		case IPV6_JOIN_GROUP:
11200 		case MCAST_JOIN_GROUP:
11201 		case IPV6_LEAVE_GROUP:
11202 		case MCAST_LEAVE_GROUP: {
11203 			struct ipv6_mreq *ip_mreqp;
11204 			struct group_req *greqp;
11205 			ire_t *ire;
11206 			boolean_t done = B_FALSE;
11207 			in6_addr_t groupv6;
11208 			uint32_t ifindex;
11209 			boolean_t mcast_opt = B_TRUE;
11210 			mcast_record_t fmode;
11211 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11212 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11213 
11214 			switch (name) {
11215 			case IPV6_JOIN_GROUP:
11216 				mcast_opt = B_FALSE;
11217 				/* FALLTHRU */
11218 			case MCAST_JOIN_GROUP:
11219 				fmode = MODE_IS_EXCLUDE;
11220 				optfn = ip_opt_add_group_v6;
11221 				break;
11222 
11223 			case IPV6_LEAVE_GROUP:
11224 				mcast_opt = B_FALSE;
11225 				/* FALLTHRU */
11226 			case MCAST_LEAVE_GROUP:
11227 				fmode = MODE_IS_INCLUDE;
11228 				optfn = ip_opt_delete_group_v6;
11229 				break;
11230 			}
11231 
11232 			if (mcast_opt) {
11233 				struct sockaddr_in *sin;
11234 				struct sockaddr_in6 *sin6;
11235 				greqp = (struct group_req *)i1;
11236 				if (greqp->gr_group.ss_family == AF_INET) {
11237 					sin = (struct sockaddr_in *)
11238 					    &(greqp->gr_group);
11239 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11240 					    &groupv6);
11241 				} else {
11242 					sin6 = (struct sockaddr_in6 *)
11243 					    &(greqp->gr_group);
11244 					groupv6 = sin6->sin6_addr;
11245 				}
11246 				ifindex = greqp->gr_interface;
11247 			} else {
11248 				ip_mreqp = (struct ipv6_mreq *)i1;
11249 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11250 				ifindex = ip_mreqp->ipv6mr_interface;
11251 			}
11252 			/*
11253 			 * In the multirouting case, we need to replicate
11254 			 * the request on all interfaces that will take part
11255 			 * in replication.  We do so because multirouting is
11256 			 * reflective, thus we will probably receive multi-
11257 			 * casts on those interfaces.
11258 			 * The ip_multirt_apply_membership_v6() succeeds if
11259 			 * the operation succeeds on at least one interface.
11260 			 */
11261 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11262 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11263 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11264 			if (ire != NULL) {
11265 				if (ire->ire_flags & RTF_MULTIRT) {
11266 					error = ip_multirt_apply_membership_v6(
11267 					    optfn, ire, connp, checkonly,
11268 					    &groupv6, fmode, &ipv6_all_zeros,
11269 					    first_mp);
11270 					done = B_TRUE;
11271 				}
11272 				ire_refrele(ire);
11273 			}
11274 			if (!done) {
11275 				error = optfn(connp, checkonly, &groupv6,
11276 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11277 			}
11278 			if (error) {
11279 				/*
11280 				 * EINPROGRESS is a soft error, needs retry
11281 				 * so don't make *outlenp zero.
11282 				 */
11283 				if (error != EINPROGRESS)
11284 					*outlenp = 0;
11285 				return (error);
11286 			}
11287 			/* OK return - copy input buffer into output buffer */
11288 			if (invalp != outvalp) {
11289 				/* don't trust bcopy for identical src/dst */
11290 				bcopy(invalp, outvalp, inlen);
11291 			}
11292 			*outlenp = inlen;
11293 			return (0);
11294 		}
11295 		case MCAST_BLOCK_SOURCE:
11296 		case MCAST_UNBLOCK_SOURCE:
11297 		case MCAST_JOIN_SOURCE_GROUP:
11298 		case MCAST_LEAVE_SOURCE_GROUP: {
11299 			struct group_source_req *gsreqp;
11300 			in6_addr_t v6grp, v6src;
11301 			uint32_t ifindex;
11302 			mcast_record_t fmode;
11303 			ire_t *ire;
11304 			boolean_t done = B_FALSE;
11305 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11306 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11307 
11308 			switch (name) {
11309 			case MCAST_BLOCK_SOURCE:
11310 				fmode = MODE_IS_EXCLUDE;
11311 				optfn = ip_opt_add_group_v6;
11312 				break;
11313 			case MCAST_UNBLOCK_SOURCE:
11314 				fmode = MODE_IS_EXCLUDE;
11315 				optfn = ip_opt_delete_group_v6;
11316 				break;
11317 			case MCAST_JOIN_SOURCE_GROUP:
11318 				fmode = MODE_IS_INCLUDE;
11319 				optfn = ip_opt_add_group_v6;
11320 				break;
11321 			case MCAST_LEAVE_SOURCE_GROUP:
11322 				fmode = MODE_IS_INCLUDE;
11323 				optfn = ip_opt_delete_group_v6;
11324 				break;
11325 			}
11326 
11327 			gsreqp = (struct group_source_req *)i1;
11328 			ifindex = gsreqp->gsr_interface;
11329 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11330 				struct sockaddr_in *s;
11331 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11332 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11333 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11334 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11335 			} else {
11336 				struct sockaddr_in6 *s6;
11337 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11338 				v6grp = s6->sin6_addr;
11339 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11340 				v6src = s6->sin6_addr;
11341 			}
11342 
11343 			/*
11344 			 * In the multirouting case, we need to replicate
11345 			 * the request as noted in the mcast cases above.
11346 			 */
11347 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11348 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11349 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11350 			if (ire != NULL) {
11351 				if (ire->ire_flags & RTF_MULTIRT) {
11352 					error = ip_multirt_apply_membership_v6(
11353 					    optfn, ire, connp, checkonly,
11354 					    &v6grp, fmode, &v6src, first_mp);
11355 					done = B_TRUE;
11356 				}
11357 				ire_refrele(ire);
11358 			}
11359 			if (!done) {
11360 				error = optfn(connp, checkonly, &v6grp,
11361 				    ifindex, fmode, &v6src, first_mp);
11362 			}
11363 			if (error != 0) {
11364 				/*
11365 				 * EINPROGRESS is a soft error, needs retry
11366 				 * so don't make *outlenp zero.
11367 				 */
11368 				if (error != EINPROGRESS)
11369 					*outlenp = 0;
11370 				return (error);
11371 			}
11372 			/* OK return - copy input buffer into output buffer */
11373 			if (invalp != outvalp) {
11374 				bcopy(invalp, outvalp, inlen);
11375 			}
11376 			*outlenp = inlen;
11377 			return (0);
11378 		}
11379 		case IPV6_UNICAST_HOPS:
11380 			/* Recorded in transport above IP */
11381 			break;	/* goto sizeof (int) option return */
11382 		case IPV6_UNSPEC_SRC:
11383 			/* Allow sending with a zero source address */
11384 			if (!checkonly) {
11385 				mutex_enter(&connp->conn_lock);
11386 				connp->conn_unspec_src = *i1 ? 1 : 0;
11387 				mutex_exit(&connp->conn_lock);
11388 			}
11389 			break;	/* goto sizeof (int) option return */
11390 		case IPV6_RECVPKTINFO:
11391 			if (!checkonly) {
11392 				mutex_enter(&connp->conn_lock);
11393 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11394 				mutex_exit(&connp->conn_lock);
11395 			}
11396 			break;	/* goto sizeof (int) option return */
11397 		case IPV6_RECVTCLASS:
11398 			if (!checkonly) {
11399 				if (*i1 < 0 || *i1 > 1) {
11400 					return (EINVAL);
11401 				}
11402 				mutex_enter(&connp->conn_lock);
11403 				connp->conn_ipv6_recvtclass = *i1;
11404 				mutex_exit(&connp->conn_lock);
11405 			}
11406 			break;
11407 		case IPV6_RECVPATHMTU:
11408 			if (!checkonly) {
11409 				if (*i1 < 0 || *i1 > 1) {
11410 					return (EINVAL);
11411 				}
11412 				mutex_enter(&connp->conn_lock);
11413 				connp->conn_ipv6_recvpathmtu = *i1;
11414 				mutex_exit(&connp->conn_lock);
11415 			}
11416 			break;
11417 		case IPV6_RECVHOPLIMIT:
11418 			if (!checkonly) {
11419 				mutex_enter(&connp->conn_lock);
11420 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11421 				mutex_exit(&connp->conn_lock);
11422 			}
11423 			break;	/* goto sizeof (int) option return */
11424 		case IPV6_RECVHOPOPTS:
11425 			if (!checkonly) {
11426 				mutex_enter(&connp->conn_lock);
11427 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11428 				mutex_exit(&connp->conn_lock);
11429 			}
11430 			break;	/* goto sizeof (int) option return */
11431 		case IPV6_RECVDSTOPTS:
11432 			if (!checkonly) {
11433 				mutex_enter(&connp->conn_lock);
11434 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11435 				mutex_exit(&connp->conn_lock);
11436 			}
11437 			break;	/* goto sizeof (int) option return */
11438 		case IPV6_RECVRTHDR:
11439 			if (!checkonly) {
11440 				mutex_enter(&connp->conn_lock);
11441 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11442 				mutex_exit(&connp->conn_lock);
11443 			}
11444 			break;	/* goto sizeof (int) option return */
11445 		case IPV6_RECVRTHDRDSTOPTS:
11446 			if (!checkonly) {
11447 				mutex_enter(&connp->conn_lock);
11448 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11449 				mutex_exit(&connp->conn_lock);
11450 			}
11451 			break;	/* goto sizeof (int) option return */
11452 		case IPV6_PKTINFO:
11453 			if (inlen == 0)
11454 				return (-EINVAL);	/* clearing option */
11455 			error = ip6_set_pktinfo(cr, connp,
11456 			    (struct in6_pktinfo *)invalp, first_mp);
11457 			if (error != 0)
11458 				*outlenp = 0;
11459 			else
11460 				*outlenp = inlen;
11461 			return (error);
11462 		case IPV6_NEXTHOP: {
11463 			struct sockaddr_in6 *sin6;
11464 
11465 			/* Verify that the nexthop is reachable */
11466 			if (inlen == 0)
11467 				return (-EINVAL);	/* clearing option */
11468 
11469 			sin6 = (struct sockaddr_in6 *)invalp;
11470 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11471 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11472 			    NULL, MATCH_IRE_DEFAULT, ipst);
11473 
11474 			if (ire == NULL) {
11475 				*outlenp = 0;
11476 				return (EHOSTUNREACH);
11477 			}
11478 			ire_refrele(ire);
11479 			return (-EINVAL);
11480 		}
11481 		case IPV6_SEC_OPT:
11482 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11483 			if (error != 0) {
11484 				*outlenp = 0;
11485 				return (error);
11486 			}
11487 			break;
11488 		case IPV6_SRC_PREFERENCES: {
11489 			/*
11490 			 * This is implemented strictly in the ip module
11491 			 * (here and in tcp_opt_*() to accomodate tcp
11492 			 * sockets).  Modules above ip pass this option
11493 			 * down here since ip is the only one that needs to
11494 			 * be aware of source address preferences.
11495 			 *
11496 			 * This socket option only affects connected
11497 			 * sockets that haven't already bound to a specific
11498 			 * IPv6 address.  In other words, sockets that
11499 			 * don't call bind() with an address other than the
11500 			 * unspecified address and that call connect().
11501 			 * ip_bind_connected_v6() passes these preferences
11502 			 * to the ipif_select_source_v6() function.
11503 			 */
11504 			if (inlen != sizeof (uint32_t))
11505 				return (EINVAL);
11506 			error = ip6_set_src_preferences(connp,
11507 			    *(uint32_t *)invalp);
11508 			if (error != 0) {
11509 				*outlenp = 0;
11510 				return (error);
11511 			} else {
11512 				*outlenp = sizeof (uint32_t);
11513 			}
11514 			break;
11515 		}
11516 		case IPV6_V6ONLY:
11517 			if (*i1 < 0 || *i1 > 1) {
11518 				return (EINVAL);
11519 			}
11520 			mutex_enter(&connp->conn_lock);
11521 			connp->conn_ipv6_v6only = *i1;
11522 			mutex_exit(&connp->conn_lock);
11523 			break;
11524 		default:
11525 			return (-EINVAL);
11526 		}
11527 		break;
11528 	default:
11529 		/*
11530 		 * "soft" error (negative)
11531 		 * option not handled at this level
11532 		 * Note: Do not modify *outlenp
11533 		 */
11534 		return (-EINVAL);
11535 	}
11536 	/*
11537 	 * Common case of return from an option that is sizeof (int)
11538 	 */
11539 	*(int *)outvalp = *i1;
11540 	*outlenp = sizeof (int);
11541 	return (0);
11542 }
11543 
11544 /*
11545  * This routine gets default values of certain options whose default
11546  * values are maintained by protocol specific code
11547  */
11548 /* ARGSUSED */
11549 int
11550 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11551 {
11552 	int *i1 = (int *)ptr;
11553 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11554 
11555 	switch (level) {
11556 	case IPPROTO_IP:
11557 		switch (name) {
11558 		case IP_MULTICAST_TTL:
11559 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11560 			return (sizeof (uchar_t));
11561 		case IP_MULTICAST_LOOP:
11562 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11563 			return (sizeof (uchar_t));
11564 		default:
11565 			return (-1);
11566 		}
11567 	case IPPROTO_IPV6:
11568 		switch (name) {
11569 		case IPV6_UNICAST_HOPS:
11570 			*i1 = ipst->ips_ipv6_def_hops;
11571 			return (sizeof (int));
11572 		case IPV6_MULTICAST_HOPS:
11573 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11574 			return (sizeof (int));
11575 		case IPV6_MULTICAST_LOOP:
11576 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11577 			return (sizeof (int));
11578 		case IPV6_V6ONLY:
11579 			*i1 = 1;
11580 			return (sizeof (int));
11581 		default:
11582 			return (-1);
11583 		}
11584 	default:
11585 		return (-1);
11586 	}
11587 	/* NOTREACHED */
11588 }
11589 
11590 /*
11591  * Given a destination address and a pointer to where to put the information
11592  * this routine fills in the mtuinfo.
11593  */
11594 int
11595 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11596     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11597 {
11598 	ire_t *ire;
11599 	ip_stack_t	*ipst = ns->netstack_ip;
11600 
11601 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11602 		return (-1);
11603 
11604 	bzero(mtuinfo, sizeof (*mtuinfo));
11605 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11606 	mtuinfo->ip6m_addr.sin6_port = port;
11607 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11608 
11609 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11610 	if (ire != NULL) {
11611 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11612 		ire_refrele(ire);
11613 	} else {
11614 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11615 	}
11616 	return (sizeof (struct ip6_mtuinfo));
11617 }
11618 
11619 /*
11620  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11621  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11622  * isn't.  This doesn't matter as the error checking is done properly for the
11623  * other MRT options coming in through ip_opt_set.
11624  */
11625 int
11626 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11627 {
11628 	conn_t		*connp = Q_TO_CONN(q);
11629 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11630 
11631 	switch (level) {
11632 	case IPPROTO_IP:
11633 		switch (name) {
11634 		case MRT_VERSION:
11635 		case MRT_ASSERT:
11636 			(void) ip_mrouter_get(name, q, ptr);
11637 			return (sizeof (int));
11638 		case IP_SEC_OPT:
11639 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11640 		case IP_NEXTHOP:
11641 			if (connp->conn_nexthop_set) {
11642 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11643 				return (sizeof (ipaddr_t));
11644 			} else
11645 				return (0);
11646 		case IP_RECVPKTINFO:
11647 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11648 			return (sizeof (int));
11649 		default:
11650 			break;
11651 		}
11652 		break;
11653 	case IPPROTO_IPV6:
11654 		switch (name) {
11655 		case IPV6_SEC_OPT:
11656 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11657 		case IPV6_SRC_PREFERENCES: {
11658 			return (ip6_get_src_preferences(connp,
11659 			    (uint32_t *)ptr));
11660 		}
11661 		case IPV6_V6ONLY:
11662 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11663 			return (sizeof (int));
11664 		case IPV6_PATHMTU:
11665 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11666 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11667 		default:
11668 			break;
11669 		}
11670 		break;
11671 	default:
11672 		break;
11673 	}
11674 	return (-1);
11675 }
11676 
11677 /* Named Dispatch routine to get a current value out of our parameter table. */
11678 /* ARGSUSED */
11679 static int
11680 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11681 {
11682 	ipparam_t *ippa = (ipparam_t *)cp;
11683 
11684 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11685 	return (0);
11686 }
11687 
11688 /* ARGSUSED */
11689 static int
11690 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11691 {
11692 
11693 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11694 	return (0);
11695 }
11696 
11697 /*
11698  * Set ip{,6}_forwarding values.  This means walking through all of the
11699  * ill's and toggling their forwarding values.
11700  */
11701 /* ARGSUSED */
11702 static int
11703 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11704 {
11705 	long new_value;
11706 	int *forwarding_value = (int *)cp;
11707 	ill_t *ill;
11708 	boolean_t isv6;
11709 	ill_walk_context_t ctx;
11710 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11711 
11712 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11713 
11714 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11715 	    new_value < 0 || new_value > 1) {
11716 		return (EINVAL);
11717 	}
11718 
11719 	*forwarding_value = new_value;
11720 
11721 	/*
11722 	 * Regardless of the current value of ip_forwarding, set all per-ill
11723 	 * values of ip_forwarding to the value being set.
11724 	 *
11725 	 * Bring all the ill's up to date with the new global value.
11726 	 */
11727 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11728 
11729 	if (isv6)
11730 		ill = ILL_START_WALK_V6(&ctx, ipst);
11731 	else
11732 		ill = ILL_START_WALK_V4(&ctx, ipst);
11733 
11734 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11735 		(void) ill_forward_set(ill, new_value != 0);
11736 
11737 	rw_exit(&ipst->ips_ill_g_lock);
11738 	return (0);
11739 }
11740 
11741 /*
11742  * Walk through the param array specified registering each element with the
11743  * Named Dispatch handler. This is called only during init. So it is ok
11744  * not to acquire any locks
11745  */
11746 static boolean_t
11747 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11748     ipndp_t *ipnd, size_t ipnd_cnt)
11749 {
11750 	for (; ippa_cnt-- > 0; ippa++) {
11751 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11752 			if (!nd_load(ndp, ippa->ip_param_name,
11753 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11754 				nd_free(ndp);
11755 				return (B_FALSE);
11756 			}
11757 		}
11758 	}
11759 
11760 	for (; ipnd_cnt-- > 0; ipnd++) {
11761 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11762 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11763 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11764 			    ipnd->ip_ndp_data)) {
11765 				nd_free(ndp);
11766 				return (B_FALSE);
11767 			}
11768 		}
11769 	}
11770 
11771 	return (B_TRUE);
11772 }
11773 
11774 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11775 /* ARGSUSED */
11776 static int
11777 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11778 {
11779 	long		new_value;
11780 	ipparam_t	*ippa = (ipparam_t *)cp;
11781 
11782 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11783 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11784 		return (EINVAL);
11785 	}
11786 	ippa->ip_param_value = new_value;
11787 	return (0);
11788 }
11789 
11790 /*
11791  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11792  * When an ipf is passed here for the first time, if
11793  * we already have in-order fragments on the queue, we convert from the fast-
11794  * path reassembly scheme to the hard-case scheme.  From then on, additional
11795  * fragments are reassembled here.  We keep track of the start and end offsets
11796  * of each piece, and the number of holes in the chain.  When the hole count
11797  * goes to zero, we are done!
11798  *
11799  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11800  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11801  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11802  * after the call to ip_reassemble().
11803  */
11804 int
11805 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11806     size_t msg_len)
11807 {
11808 	uint_t	end;
11809 	mblk_t	*next_mp;
11810 	mblk_t	*mp1;
11811 	uint_t	offset;
11812 	boolean_t incr_dups = B_TRUE;
11813 	boolean_t offset_zero_seen = B_FALSE;
11814 	boolean_t pkt_boundary_checked = B_FALSE;
11815 
11816 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11817 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11818 
11819 	/* Add in byte count */
11820 	ipf->ipf_count += msg_len;
11821 	if (ipf->ipf_end) {
11822 		/*
11823 		 * We were part way through in-order reassembly, but now there
11824 		 * is a hole.  We walk through messages already queued, and
11825 		 * mark them for hard case reassembly.  We know that up till
11826 		 * now they were in order starting from offset zero.
11827 		 */
11828 		offset = 0;
11829 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11830 			IP_REASS_SET_START(mp1, offset);
11831 			if (offset == 0) {
11832 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11833 				offset = -ipf->ipf_nf_hdr_len;
11834 			}
11835 			offset += mp1->b_wptr - mp1->b_rptr;
11836 			IP_REASS_SET_END(mp1, offset);
11837 		}
11838 		/* One hole at the end. */
11839 		ipf->ipf_hole_cnt = 1;
11840 		/* Brand it as a hard case, forever. */
11841 		ipf->ipf_end = 0;
11842 	}
11843 	/* Walk through all the new pieces. */
11844 	do {
11845 		end = start + (mp->b_wptr - mp->b_rptr);
11846 		/*
11847 		 * If start is 0, decrease 'end' only for the first mblk of
11848 		 * the fragment. Otherwise 'end' can get wrong value in the
11849 		 * second pass of the loop if first mblk is exactly the
11850 		 * size of ipf_nf_hdr_len.
11851 		 */
11852 		if (start == 0 && !offset_zero_seen) {
11853 			/* First segment */
11854 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11855 			end -= ipf->ipf_nf_hdr_len;
11856 			offset_zero_seen = B_TRUE;
11857 		}
11858 		next_mp = mp->b_cont;
11859 		/*
11860 		 * We are checking to see if there is any interesing data
11861 		 * to process.  If there isn't and the mblk isn't the
11862 		 * one which carries the unfragmentable header then we
11863 		 * drop it.  It's possible to have just the unfragmentable
11864 		 * header come through without any data.  That needs to be
11865 		 * saved.
11866 		 *
11867 		 * If the assert at the top of this function holds then the
11868 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11869 		 * is infrequently traveled enough that the test is left in
11870 		 * to protect against future code changes which break that
11871 		 * invariant.
11872 		 */
11873 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11874 			/* Empty.  Blast it. */
11875 			IP_REASS_SET_START(mp, 0);
11876 			IP_REASS_SET_END(mp, 0);
11877 			/*
11878 			 * If the ipf points to the mblk we are about to free,
11879 			 * update ipf to point to the next mblk (or NULL
11880 			 * if none).
11881 			 */
11882 			if (ipf->ipf_mp->b_cont == mp)
11883 				ipf->ipf_mp->b_cont = next_mp;
11884 			freeb(mp);
11885 			continue;
11886 		}
11887 		mp->b_cont = NULL;
11888 		IP_REASS_SET_START(mp, start);
11889 		IP_REASS_SET_END(mp, end);
11890 		if (!ipf->ipf_tail_mp) {
11891 			ipf->ipf_tail_mp = mp;
11892 			ipf->ipf_mp->b_cont = mp;
11893 			if (start == 0 || !more) {
11894 				ipf->ipf_hole_cnt = 1;
11895 				/*
11896 				 * if the first fragment comes in more than one
11897 				 * mblk, this loop will be executed for each
11898 				 * mblk. Need to adjust hole count so exiting
11899 				 * this routine will leave hole count at 1.
11900 				 */
11901 				if (next_mp)
11902 					ipf->ipf_hole_cnt++;
11903 			} else
11904 				ipf->ipf_hole_cnt = 2;
11905 			continue;
11906 		} else if (ipf->ipf_last_frag_seen && !more &&
11907 		    !pkt_boundary_checked) {
11908 			/*
11909 			 * We check datagram boundary only if this fragment
11910 			 * claims to be the last fragment and we have seen a
11911 			 * last fragment in the past too. We do this only
11912 			 * once for a given fragment.
11913 			 *
11914 			 * start cannot be 0 here as fragments with start=0
11915 			 * and MF=0 gets handled as a complete packet. These
11916 			 * fragments should not reach here.
11917 			 */
11918 
11919 			if (start + msgdsize(mp) !=
11920 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11921 				/*
11922 				 * We have two fragments both of which claim
11923 				 * to be the last fragment but gives conflicting
11924 				 * information about the whole datagram size.
11925 				 * Something fishy is going on. Drop the
11926 				 * fragment and free up the reassembly list.
11927 				 */
11928 				return (IP_REASS_FAILED);
11929 			}
11930 
11931 			/*
11932 			 * We shouldn't come to this code block again for this
11933 			 * particular fragment.
11934 			 */
11935 			pkt_boundary_checked = B_TRUE;
11936 		}
11937 
11938 		/* New stuff at or beyond tail? */
11939 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11940 		if (start >= offset) {
11941 			if (ipf->ipf_last_frag_seen) {
11942 				/* current fragment is beyond last fragment */
11943 				return (IP_REASS_FAILED);
11944 			}
11945 			/* Link it on end. */
11946 			ipf->ipf_tail_mp->b_cont = mp;
11947 			ipf->ipf_tail_mp = mp;
11948 			if (more) {
11949 				if (start != offset)
11950 					ipf->ipf_hole_cnt++;
11951 			} else if (start == offset && next_mp == NULL)
11952 					ipf->ipf_hole_cnt--;
11953 			continue;
11954 		}
11955 		mp1 = ipf->ipf_mp->b_cont;
11956 		offset = IP_REASS_START(mp1);
11957 		/* New stuff at the front? */
11958 		if (start < offset) {
11959 			if (start == 0) {
11960 				if (end >= offset) {
11961 					/* Nailed the hole at the begining. */
11962 					ipf->ipf_hole_cnt--;
11963 				}
11964 			} else if (end < offset) {
11965 				/*
11966 				 * A hole, stuff, and a hole where there used
11967 				 * to be just a hole.
11968 				 */
11969 				ipf->ipf_hole_cnt++;
11970 			}
11971 			mp->b_cont = mp1;
11972 			/* Check for overlap. */
11973 			while (end > offset) {
11974 				if (end < IP_REASS_END(mp1)) {
11975 					mp->b_wptr -= end - offset;
11976 					IP_REASS_SET_END(mp, offset);
11977 					BUMP_MIB(ill->ill_ip_mib,
11978 					    ipIfStatsReasmPartDups);
11979 					break;
11980 				}
11981 				/* Did we cover another hole? */
11982 				if ((mp1->b_cont &&
11983 				    IP_REASS_END(mp1) !=
11984 				    IP_REASS_START(mp1->b_cont) &&
11985 				    end >= IP_REASS_START(mp1->b_cont)) ||
11986 				    (!ipf->ipf_last_frag_seen && !more)) {
11987 					ipf->ipf_hole_cnt--;
11988 				}
11989 				/* Clip out mp1. */
11990 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11991 					/*
11992 					 * After clipping out mp1, this guy
11993 					 * is now hanging off the end.
11994 					 */
11995 					ipf->ipf_tail_mp = mp;
11996 				}
11997 				IP_REASS_SET_START(mp1, 0);
11998 				IP_REASS_SET_END(mp1, 0);
11999 				/* Subtract byte count */
12000 				ipf->ipf_count -= mp1->b_datap->db_lim -
12001 				    mp1->b_datap->db_base;
12002 				freeb(mp1);
12003 				BUMP_MIB(ill->ill_ip_mib,
12004 				    ipIfStatsReasmPartDups);
12005 				mp1 = mp->b_cont;
12006 				if (!mp1)
12007 					break;
12008 				offset = IP_REASS_START(mp1);
12009 			}
12010 			ipf->ipf_mp->b_cont = mp;
12011 			continue;
12012 		}
12013 		/*
12014 		 * The new piece starts somewhere between the start of the head
12015 		 * and before the end of the tail.
12016 		 */
12017 		for (; mp1; mp1 = mp1->b_cont) {
12018 			offset = IP_REASS_END(mp1);
12019 			if (start < offset) {
12020 				if (end <= offset) {
12021 					/* Nothing new. */
12022 					IP_REASS_SET_START(mp, 0);
12023 					IP_REASS_SET_END(mp, 0);
12024 					/* Subtract byte count */
12025 					ipf->ipf_count -= mp->b_datap->db_lim -
12026 					    mp->b_datap->db_base;
12027 					if (incr_dups) {
12028 						ipf->ipf_num_dups++;
12029 						incr_dups = B_FALSE;
12030 					}
12031 					freeb(mp);
12032 					BUMP_MIB(ill->ill_ip_mib,
12033 					    ipIfStatsReasmDuplicates);
12034 					break;
12035 				}
12036 				/*
12037 				 * Trim redundant stuff off beginning of new
12038 				 * piece.
12039 				 */
12040 				IP_REASS_SET_START(mp, offset);
12041 				mp->b_rptr += offset - start;
12042 				BUMP_MIB(ill->ill_ip_mib,
12043 				    ipIfStatsReasmPartDups);
12044 				start = offset;
12045 				if (!mp1->b_cont) {
12046 					/*
12047 					 * After trimming, this guy is now
12048 					 * hanging off the end.
12049 					 */
12050 					mp1->b_cont = mp;
12051 					ipf->ipf_tail_mp = mp;
12052 					if (!more) {
12053 						ipf->ipf_hole_cnt--;
12054 					}
12055 					break;
12056 				}
12057 			}
12058 			if (start >= IP_REASS_START(mp1->b_cont))
12059 				continue;
12060 			/* Fill a hole */
12061 			if (start > offset)
12062 				ipf->ipf_hole_cnt++;
12063 			mp->b_cont = mp1->b_cont;
12064 			mp1->b_cont = mp;
12065 			mp1 = mp->b_cont;
12066 			offset = IP_REASS_START(mp1);
12067 			if (end >= offset) {
12068 				ipf->ipf_hole_cnt--;
12069 				/* Check for overlap. */
12070 				while (end > offset) {
12071 					if (end < IP_REASS_END(mp1)) {
12072 						mp->b_wptr -= end - offset;
12073 						IP_REASS_SET_END(mp, offset);
12074 						/*
12075 						 * TODO we might bump
12076 						 * this up twice if there is
12077 						 * overlap at both ends.
12078 						 */
12079 						BUMP_MIB(ill->ill_ip_mib,
12080 						    ipIfStatsReasmPartDups);
12081 						break;
12082 					}
12083 					/* Did we cover another hole? */
12084 					if ((mp1->b_cont &&
12085 					    IP_REASS_END(mp1)
12086 					    != IP_REASS_START(mp1->b_cont) &&
12087 					    end >=
12088 					    IP_REASS_START(mp1->b_cont)) ||
12089 					    (!ipf->ipf_last_frag_seen &&
12090 					    !more)) {
12091 						ipf->ipf_hole_cnt--;
12092 					}
12093 					/* Clip out mp1. */
12094 					if ((mp->b_cont = mp1->b_cont) ==
12095 					    NULL) {
12096 						/*
12097 						 * After clipping out mp1,
12098 						 * this guy is now hanging
12099 						 * off the end.
12100 						 */
12101 						ipf->ipf_tail_mp = mp;
12102 					}
12103 					IP_REASS_SET_START(mp1, 0);
12104 					IP_REASS_SET_END(mp1, 0);
12105 					/* Subtract byte count */
12106 					ipf->ipf_count -=
12107 					    mp1->b_datap->db_lim -
12108 					    mp1->b_datap->db_base;
12109 					freeb(mp1);
12110 					BUMP_MIB(ill->ill_ip_mib,
12111 					    ipIfStatsReasmPartDups);
12112 					mp1 = mp->b_cont;
12113 					if (!mp1)
12114 						break;
12115 					offset = IP_REASS_START(mp1);
12116 				}
12117 			}
12118 			break;
12119 		}
12120 	} while (start = end, mp = next_mp);
12121 
12122 	/* Fragment just processed could be the last one. Remember this fact */
12123 	if (!more)
12124 		ipf->ipf_last_frag_seen = B_TRUE;
12125 
12126 	/* Still got holes? */
12127 	if (ipf->ipf_hole_cnt)
12128 		return (IP_REASS_PARTIAL);
12129 	/* Clean up overloaded fields to avoid upstream disasters. */
12130 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12131 		IP_REASS_SET_START(mp1, 0);
12132 		IP_REASS_SET_END(mp1, 0);
12133 	}
12134 	return (IP_REASS_COMPLETE);
12135 }
12136 
12137 /*
12138  * ipsec processing for the fast path, used for input UDP Packets
12139  * Returns true if ready for passup to UDP.
12140  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12141  * was an ESP-in-UDP packet, etc.).
12142  */
12143 static boolean_t
12144 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12145     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12146 {
12147 	uint32_t	ill_index;
12148 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12149 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12150 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12151 	udp_t		*udp = connp->conn_udp;
12152 
12153 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12154 	/* The ill_index of the incoming ILL */
12155 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12156 
12157 	/* pass packet up to the transport */
12158 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12159 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12160 		    NULL, mctl_present);
12161 		if (*first_mpp == NULL) {
12162 			return (B_FALSE);
12163 		}
12164 	}
12165 
12166 	/* Initiate IPPF processing for fastpath UDP */
12167 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12168 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12169 		if (*mpp == NULL) {
12170 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12171 			    "deferred/dropped during IPPF processing\n"));
12172 			return (B_FALSE);
12173 		}
12174 	}
12175 	/*
12176 	 * Remove 0-spi if it's 0, or move everything behind
12177 	 * the UDP header over it and forward to ESP via
12178 	 * ip_proto_input().
12179 	 */
12180 	if (udp->udp_nat_t_endpoint) {
12181 		if (mctl_present) {
12182 			/* mctl_present *shouldn't* happen. */
12183 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12184 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12185 			    &ipss->ipsec_dropper);
12186 			*first_mpp = NULL;
12187 			return (B_FALSE);
12188 		}
12189 
12190 		/* "ill" is "recv_ill" in actuality. */
12191 		if (!zero_spi_check(q, *mpp, ipha, ire, ill, ipss))
12192 			return (B_FALSE);
12193 
12194 		/* Else continue like a normal UDP packet. */
12195 	}
12196 
12197 	/*
12198 	 * We make the checks as below since we are in the fast path
12199 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12200 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12201 	 */
12202 	if (connp->conn_recvif || connp->conn_recvslla ||
12203 	    connp->conn_ip_recvpktinfo) {
12204 		if (connp->conn_recvif) {
12205 			in_flags = IPF_RECVIF;
12206 		}
12207 		/*
12208 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12209 		 * so the flag passed to ip_add_info is based on IP version
12210 		 * of connp.
12211 		 */
12212 		if (connp->conn_ip_recvpktinfo) {
12213 			if (connp->conn_af_isv6) {
12214 				/*
12215 				 * V6 only needs index
12216 				 */
12217 				in_flags |= IPF_RECVIF;
12218 			} else {
12219 				/*
12220 				 * V4 needs index + matching address.
12221 				 */
12222 				in_flags |= IPF_RECVADDR;
12223 			}
12224 		}
12225 		if (connp->conn_recvslla) {
12226 			in_flags |= IPF_RECVSLLA;
12227 		}
12228 		/*
12229 		 * since in_flags are being set ill will be
12230 		 * referenced in ip_add_info, so it better not
12231 		 * be NULL.
12232 		 */
12233 		/*
12234 		 * the actual data will be contained in b_cont
12235 		 * upon successful return of the following call.
12236 		 * If the call fails then the original mblk is
12237 		 * returned.
12238 		 */
12239 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12240 		    ipst);
12241 	}
12242 
12243 	return (B_TRUE);
12244 }
12245 
12246 /*
12247  * Fragmentation reassembly.  Each ILL has a hash table for
12248  * queuing packets undergoing reassembly for all IPIFs
12249  * associated with the ILL.  The hash is based on the packet
12250  * IP ident field.  The ILL frag hash table was allocated
12251  * as a timer block at the time the ILL was created.  Whenever
12252  * there is anything on the reassembly queue, the timer will
12253  * be running.  Returns B_TRUE if successful else B_FALSE;
12254  * frees mp on failure.
12255  */
12256 static boolean_t
12257 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12258     uint32_t *cksum_val, uint16_t *cksum_flags)
12259 {
12260 	uint32_t	frag_offset_flags;
12261 	ill_t		*ill = (ill_t *)q->q_ptr;
12262 	mblk_t		*mp = *mpp;
12263 	mblk_t		*t_mp;
12264 	ipaddr_t	dst;
12265 	uint8_t		proto = ipha->ipha_protocol;
12266 	uint32_t	sum_val;
12267 	uint16_t	sum_flags;
12268 	ipf_t		*ipf;
12269 	ipf_t		**ipfp;
12270 	ipfb_t		*ipfb;
12271 	uint16_t	ident;
12272 	uint32_t	offset;
12273 	ipaddr_t	src;
12274 	uint_t		hdr_length;
12275 	uint32_t	end;
12276 	mblk_t		*mp1;
12277 	mblk_t		*tail_mp;
12278 	size_t		count;
12279 	size_t		msg_len;
12280 	uint8_t		ecn_info = 0;
12281 	uint32_t	packet_size;
12282 	boolean_t	pruned = B_FALSE;
12283 	ip_stack_t *ipst = ill->ill_ipst;
12284 
12285 	if (cksum_val != NULL)
12286 		*cksum_val = 0;
12287 	if (cksum_flags != NULL)
12288 		*cksum_flags = 0;
12289 
12290 	/*
12291 	 * Drop the fragmented as early as possible, if
12292 	 * we don't have resource(s) to re-assemble.
12293 	 */
12294 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12295 		freemsg(mp);
12296 		return (B_FALSE);
12297 	}
12298 
12299 	/* Check for fragmentation offset; return if there's none */
12300 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12301 	    (IPH_MF | IPH_OFFSET)) == 0)
12302 		return (B_TRUE);
12303 
12304 	/*
12305 	 * We utilize hardware computed checksum info only for UDP since
12306 	 * IP fragmentation is a normal occurence for the protocol.  In
12307 	 * addition, checksum offload support for IP fragments carrying
12308 	 * UDP payload is commonly implemented across network adapters.
12309 	 */
12310 	ASSERT(ill != NULL);
12311 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12312 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12313 		mblk_t *mp1 = mp->b_cont;
12314 		int32_t len;
12315 
12316 		/* Record checksum information from the packet */
12317 		sum_val = (uint32_t)DB_CKSUM16(mp);
12318 		sum_flags = DB_CKSUMFLAGS(mp);
12319 
12320 		/* IP payload offset from beginning of mblk */
12321 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12322 
12323 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12324 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12325 		    offset >= DB_CKSUMSTART(mp) &&
12326 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12327 			uint32_t adj;
12328 			/*
12329 			 * Partial checksum has been calculated by hardware
12330 			 * and attached to the packet; in addition, any
12331 			 * prepended extraneous data is even byte aligned.
12332 			 * If any such data exists, we adjust the checksum;
12333 			 * this would also handle any postpended data.
12334 			 */
12335 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12336 			    mp, mp1, len, adj);
12337 
12338 			/* One's complement subtract extraneous checksum */
12339 			if (adj >= sum_val)
12340 				sum_val = ~(adj - sum_val) & 0xFFFF;
12341 			else
12342 				sum_val -= adj;
12343 		}
12344 	} else {
12345 		sum_val = 0;
12346 		sum_flags = 0;
12347 	}
12348 
12349 	/* Clear hardware checksumming flag */
12350 	DB_CKSUMFLAGS(mp) = 0;
12351 
12352 	ident = ipha->ipha_ident;
12353 	offset = (frag_offset_flags << 3) & 0xFFFF;
12354 	src = ipha->ipha_src;
12355 	dst = ipha->ipha_dst;
12356 	hdr_length = IPH_HDR_LENGTH(ipha);
12357 	end = ntohs(ipha->ipha_length) - hdr_length;
12358 
12359 	/* If end == 0 then we have a packet with no data, so just free it */
12360 	if (end == 0) {
12361 		freemsg(mp);
12362 		return (B_FALSE);
12363 	}
12364 
12365 	/* Record the ECN field info. */
12366 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12367 	if (offset != 0) {
12368 		/*
12369 		 * If this isn't the first piece, strip the header, and
12370 		 * add the offset to the end value.
12371 		 */
12372 		mp->b_rptr += hdr_length;
12373 		end += offset;
12374 	}
12375 
12376 	msg_len = MBLKSIZE(mp);
12377 	tail_mp = mp;
12378 	while (tail_mp->b_cont != NULL) {
12379 		tail_mp = tail_mp->b_cont;
12380 		msg_len += MBLKSIZE(tail_mp);
12381 	}
12382 
12383 	/* If the reassembly list for this ILL will get too big, prune it */
12384 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12385 	    ipst->ips_ip_reass_queue_bytes) {
12386 		ill_frag_prune(ill,
12387 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12388 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12389 		pruned = B_TRUE;
12390 	}
12391 
12392 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12393 	mutex_enter(&ipfb->ipfb_lock);
12394 
12395 	ipfp = &ipfb->ipfb_ipf;
12396 	/* Try to find an existing fragment queue for this packet. */
12397 	for (;;) {
12398 		ipf = ipfp[0];
12399 		if (ipf != NULL) {
12400 			/*
12401 			 * It has to match on ident and src/dst address.
12402 			 */
12403 			if (ipf->ipf_ident == ident &&
12404 			    ipf->ipf_src == src &&
12405 			    ipf->ipf_dst == dst &&
12406 			    ipf->ipf_protocol == proto) {
12407 				/*
12408 				 * If we have received too many
12409 				 * duplicate fragments for this packet
12410 				 * free it.
12411 				 */
12412 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12413 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12414 					freemsg(mp);
12415 					mutex_exit(&ipfb->ipfb_lock);
12416 					return (B_FALSE);
12417 				}
12418 				/* Found it. */
12419 				break;
12420 			}
12421 			ipfp = &ipf->ipf_hash_next;
12422 			continue;
12423 		}
12424 
12425 		/*
12426 		 * If we pruned the list, do we want to store this new
12427 		 * fragment?. We apply an optimization here based on the
12428 		 * fact that most fragments will be received in order.
12429 		 * So if the offset of this incoming fragment is zero,
12430 		 * it is the first fragment of a new packet. We will
12431 		 * keep it.  Otherwise drop the fragment, as we have
12432 		 * probably pruned the packet already (since the
12433 		 * packet cannot be found).
12434 		 */
12435 		if (pruned && offset != 0) {
12436 			mutex_exit(&ipfb->ipfb_lock);
12437 			freemsg(mp);
12438 			return (B_FALSE);
12439 		}
12440 
12441 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12442 			/*
12443 			 * Too many fragmented packets in this hash
12444 			 * bucket. Free the oldest.
12445 			 */
12446 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12447 		}
12448 
12449 		/* New guy.  Allocate a frag message. */
12450 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12451 		if (mp1 == NULL) {
12452 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12453 			freemsg(mp);
12454 reass_done:
12455 			mutex_exit(&ipfb->ipfb_lock);
12456 			return (B_FALSE);
12457 		}
12458 
12459 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12460 		mp1->b_cont = mp;
12461 
12462 		/* Initialize the fragment header. */
12463 		ipf = (ipf_t *)mp1->b_rptr;
12464 		ipf->ipf_mp = mp1;
12465 		ipf->ipf_ptphn = ipfp;
12466 		ipfp[0] = ipf;
12467 		ipf->ipf_hash_next = NULL;
12468 		ipf->ipf_ident = ident;
12469 		ipf->ipf_protocol = proto;
12470 		ipf->ipf_src = src;
12471 		ipf->ipf_dst = dst;
12472 		ipf->ipf_nf_hdr_len = 0;
12473 		/* Record reassembly start time. */
12474 		ipf->ipf_timestamp = gethrestime_sec();
12475 		/* Record ipf generation and account for frag header */
12476 		ipf->ipf_gen = ill->ill_ipf_gen++;
12477 		ipf->ipf_count = MBLKSIZE(mp1);
12478 		ipf->ipf_last_frag_seen = B_FALSE;
12479 		ipf->ipf_ecn = ecn_info;
12480 		ipf->ipf_num_dups = 0;
12481 		ipfb->ipfb_frag_pkts++;
12482 		ipf->ipf_checksum = 0;
12483 		ipf->ipf_checksum_flags = 0;
12484 
12485 		/* Store checksum value in fragment header */
12486 		if (sum_flags != 0) {
12487 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12488 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12489 			ipf->ipf_checksum = sum_val;
12490 			ipf->ipf_checksum_flags = sum_flags;
12491 		}
12492 
12493 		/*
12494 		 * We handle reassembly two ways.  In the easy case,
12495 		 * where all the fragments show up in order, we do
12496 		 * minimal bookkeeping, and just clip new pieces on
12497 		 * the end.  If we ever see a hole, then we go off
12498 		 * to ip_reassemble which has to mark the pieces and
12499 		 * keep track of the number of holes, etc.  Obviously,
12500 		 * the point of having both mechanisms is so we can
12501 		 * handle the easy case as efficiently as possible.
12502 		 */
12503 		if (offset == 0) {
12504 			/* Easy case, in-order reassembly so far. */
12505 			ipf->ipf_count += msg_len;
12506 			ipf->ipf_tail_mp = tail_mp;
12507 			/*
12508 			 * Keep track of next expected offset in
12509 			 * ipf_end.
12510 			 */
12511 			ipf->ipf_end = end;
12512 			ipf->ipf_nf_hdr_len = hdr_length;
12513 		} else {
12514 			/* Hard case, hole at the beginning. */
12515 			ipf->ipf_tail_mp = NULL;
12516 			/*
12517 			 * ipf_end == 0 means that we have given up
12518 			 * on easy reassembly.
12519 			 */
12520 			ipf->ipf_end = 0;
12521 
12522 			/* Forget checksum offload from now on */
12523 			ipf->ipf_checksum_flags = 0;
12524 
12525 			/*
12526 			 * ipf_hole_cnt is set by ip_reassemble.
12527 			 * ipf_count is updated by ip_reassemble.
12528 			 * No need to check for return value here
12529 			 * as we don't expect reassembly to complete
12530 			 * or fail for the first fragment itself.
12531 			 */
12532 			(void) ip_reassemble(mp, ipf,
12533 			    (frag_offset_flags & IPH_OFFSET) << 3,
12534 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12535 		}
12536 		/* Update per ipfb and ill byte counts */
12537 		ipfb->ipfb_count += ipf->ipf_count;
12538 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12539 		ill->ill_frag_count += ipf->ipf_count;
12540 		/* If the frag timer wasn't already going, start it. */
12541 		mutex_enter(&ill->ill_lock);
12542 		ill_frag_timer_start(ill);
12543 		mutex_exit(&ill->ill_lock);
12544 		goto reass_done;
12545 	}
12546 
12547 	/*
12548 	 * If the packet's flag has changed (it could be coming up
12549 	 * from an interface different than the previous, therefore
12550 	 * possibly different checksum capability), then forget about
12551 	 * any stored checksum states.  Otherwise add the value to
12552 	 * the existing one stored in the fragment header.
12553 	 */
12554 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12555 		sum_val += ipf->ipf_checksum;
12556 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12557 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12558 		ipf->ipf_checksum = sum_val;
12559 	} else if (ipf->ipf_checksum_flags != 0) {
12560 		/* Forget checksum offload from now on */
12561 		ipf->ipf_checksum_flags = 0;
12562 	}
12563 
12564 	/*
12565 	 * We have a new piece of a datagram which is already being
12566 	 * reassembled.  Update the ECN info if all IP fragments
12567 	 * are ECN capable.  If there is one which is not, clear
12568 	 * all the info.  If there is at least one which has CE
12569 	 * code point, IP needs to report that up to transport.
12570 	 */
12571 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12572 		if (ecn_info == IPH_ECN_CE)
12573 			ipf->ipf_ecn = IPH_ECN_CE;
12574 	} else {
12575 		ipf->ipf_ecn = IPH_ECN_NECT;
12576 	}
12577 	if (offset && ipf->ipf_end == offset) {
12578 		/* The new fragment fits at the end */
12579 		ipf->ipf_tail_mp->b_cont = mp;
12580 		/* Update the byte count */
12581 		ipf->ipf_count += msg_len;
12582 		/* Update per ipfb and ill byte counts */
12583 		ipfb->ipfb_count += msg_len;
12584 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12585 		ill->ill_frag_count += msg_len;
12586 		if (frag_offset_flags & IPH_MF) {
12587 			/* More to come. */
12588 			ipf->ipf_end = end;
12589 			ipf->ipf_tail_mp = tail_mp;
12590 			goto reass_done;
12591 		}
12592 	} else {
12593 		/* Go do the hard cases. */
12594 		int ret;
12595 
12596 		if (offset == 0)
12597 			ipf->ipf_nf_hdr_len = hdr_length;
12598 
12599 		/* Save current byte count */
12600 		count = ipf->ipf_count;
12601 		ret = ip_reassemble(mp, ipf,
12602 		    (frag_offset_flags & IPH_OFFSET) << 3,
12603 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12604 		/* Count of bytes added and subtracted (freeb()ed) */
12605 		count = ipf->ipf_count - count;
12606 		if (count) {
12607 			/* Update per ipfb and ill byte counts */
12608 			ipfb->ipfb_count += count;
12609 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12610 			ill->ill_frag_count += count;
12611 		}
12612 		if (ret == IP_REASS_PARTIAL) {
12613 			goto reass_done;
12614 		} else if (ret == IP_REASS_FAILED) {
12615 			/* Reassembly failed. Free up all resources */
12616 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12617 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12618 				IP_REASS_SET_START(t_mp, 0);
12619 				IP_REASS_SET_END(t_mp, 0);
12620 			}
12621 			freemsg(mp);
12622 			goto reass_done;
12623 		}
12624 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12625 	}
12626 	/*
12627 	 * We have completed reassembly.  Unhook the frag header from
12628 	 * the reassembly list.
12629 	 *
12630 	 * Before we free the frag header, record the ECN info
12631 	 * to report back to the transport.
12632 	 */
12633 	ecn_info = ipf->ipf_ecn;
12634 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12635 	ipfp = ipf->ipf_ptphn;
12636 
12637 	/* We need to supply these to caller */
12638 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12639 		sum_val = ipf->ipf_checksum;
12640 	else
12641 		sum_val = 0;
12642 
12643 	mp1 = ipf->ipf_mp;
12644 	count = ipf->ipf_count;
12645 	ipf = ipf->ipf_hash_next;
12646 	if (ipf != NULL)
12647 		ipf->ipf_ptphn = ipfp;
12648 	ipfp[0] = ipf;
12649 	ill->ill_frag_count -= count;
12650 	ASSERT(ipfb->ipfb_count >= count);
12651 	ipfb->ipfb_count -= count;
12652 	ipfb->ipfb_frag_pkts--;
12653 	mutex_exit(&ipfb->ipfb_lock);
12654 	/* Ditch the frag header. */
12655 	mp = mp1->b_cont;
12656 
12657 	freeb(mp1);
12658 
12659 	/* Restore original IP length in header. */
12660 	packet_size = (uint32_t)msgdsize(mp);
12661 	if (packet_size > IP_MAXPACKET) {
12662 		freemsg(mp);
12663 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12664 		return (B_FALSE);
12665 	}
12666 
12667 	if (DB_REF(mp) > 1) {
12668 		mblk_t *mp2 = copymsg(mp);
12669 
12670 		freemsg(mp);
12671 		if (mp2 == NULL) {
12672 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12673 			return (B_FALSE);
12674 		}
12675 		mp = mp2;
12676 	}
12677 	ipha = (ipha_t *)mp->b_rptr;
12678 
12679 	ipha->ipha_length = htons((uint16_t)packet_size);
12680 	/* We're now complete, zip the frag state */
12681 	ipha->ipha_fragment_offset_and_flags = 0;
12682 	/* Record the ECN info. */
12683 	ipha->ipha_type_of_service &= 0xFC;
12684 	ipha->ipha_type_of_service |= ecn_info;
12685 	*mpp = mp;
12686 
12687 	/* Reassembly is successful; return checksum information if needed */
12688 	if (cksum_val != NULL)
12689 		*cksum_val = sum_val;
12690 	if (cksum_flags != NULL)
12691 		*cksum_flags = sum_flags;
12692 
12693 	return (B_TRUE);
12694 }
12695 
12696 /*
12697  * Perform ip header check sum update local options.
12698  * return B_TRUE if all is well, else return B_FALSE and release
12699  * the mp. caller is responsible for decrementing ire ref cnt.
12700  */
12701 static boolean_t
12702 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12703     ip_stack_t *ipst)
12704 {
12705 	mblk_t		*first_mp;
12706 	boolean_t	mctl_present;
12707 	uint16_t	sum;
12708 
12709 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12710 	/*
12711 	 * Don't do the checksum if it has gone through AH/ESP
12712 	 * processing.
12713 	 */
12714 	if (!mctl_present) {
12715 		sum = ip_csum_hdr(ipha);
12716 		if (sum != 0) {
12717 			if (ill != NULL) {
12718 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12719 			} else {
12720 				BUMP_MIB(&ipst->ips_ip_mib,
12721 				    ipIfStatsInCksumErrs);
12722 			}
12723 			freemsg(first_mp);
12724 			return (B_FALSE);
12725 		}
12726 	}
12727 
12728 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12729 		if (mctl_present)
12730 			freeb(first_mp);
12731 		return (B_FALSE);
12732 	}
12733 
12734 	return (B_TRUE);
12735 }
12736 
12737 /*
12738  * All udp packet are delivered to the local host via this routine.
12739  */
12740 void
12741 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12742     ill_t *recv_ill)
12743 {
12744 	uint32_t	sum;
12745 	uint32_t	u1;
12746 	boolean_t	mctl_present;
12747 	conn_t		*connp;
12748 	mblk_t		*first_mp;
12749 	uint16_t	*up;
12750 	ill_t		*ill = (ill_t *)q->q_ptr;
12751 	uint16_t	reass_hck_flags = 0;
12752 	ip_stack_t	*ipst;
12753 
12754 	ASSERT(recv_ill != NULL);
12755 	ipst = recv_ill->ill_ipst;
12756 
12757 #define	rptr    ((uchar_t *)ipha)
12758 
12759 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12760 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12761 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12762 	ASSERT(ill != NULL);
12763 
12764 	/*
12765 	 * FAST PATH for udp packets
12766 	 */
12767 
12768 	/* u1 is # words of IP options */
12769 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12770 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12771 
12772 	/* IP options present */
12773 	if (u1 != 0)
12774 		goto ipoptions;
12775 
12776 	/* Check the IP header checksum.  */
12777 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12778 		/* Clear the IP header h/w cksum flag */
12779 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12780 	} else if (!mctl_present) {
12781 		/*
12782 		 * Don't verify header checksum if this packet is coming
12783 		 * back from AH/ESP as we already did it.
12784 		 */
12785 #define	uph	((uint16_t *)ipha)
12786 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12787 		    uph[6] + uph[7] + uph[8] + uph[9];
12788 #undef	uph
12789 		/* finish doing IP checksum */
12790 		sum = (sum & 0xFFFF) + (sum >> 16);
12791 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12792 		if (sum != 0 && sum != 0xFFFF) {
12793 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12794 			freemsg(first_mp);
12795 			return;
12796 		}
12797 	}
12798 
12799 	/*
12800 	 * Count for SNMP of inbound packets for ire.
12801 	 * if mctl is present this might be a secure packet and
12802 	 * has already been counted for in ip_proto_input().
12803 	 */
12804 	if (!mctl_present) {
12805 		UPDATE_IB_PKT_COUNT(ire);
12806 		ire->ire_last_used_time = lbolt;
12807 	}
12808 
12809 	/* packet part of fragmented IP packet? */
12810 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12811 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12812 		goto fragmented;
12813 	}
12814 
12815 	/* u1 = IP header length (20 bytes) */
12816 	u1 = IP_SIMPLE_HDR_LENGTH;
12817 
12818 	/* packet does not contain complete IP & UDP headers */
12819 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12820 		goto udppullup;
12821 
12822 	/* up points to UDP header */
12823 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12824 #define	iphs    ((uint16_t *)ipha)
12825 
12826 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12827 	if (up[3] != 0) {
12828 		mblk_t *mp1 = mp->b_cont;
12829 		boolean_t cksum_err;
12830 		uint16_t hck_flags = 0;
12831 
12832 		/* Pseudo-header checksum */
12833 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12834 		    iphs[9] + up[2];
12835 
12836 		/*
12837 		 * Revert to software checksum calculation if the interface
12838 		 * isn't capable of checksum offload or if IPsec is present.
12839 		 */
12840 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12841 			hck_flags = DB_CKSUMFLAGS(mp);
12842 
12843 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12844 			IP_STAT(ipst, ip_in_sw_cksum);
12845 
12846 		IP_CKSUM_RECV(hck_flags, u1,
12847 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12848 		    (int32_t)((uchar_t *)up - rptr),
12849 		    mp, mp1, cksum_err);
12850 
12851 		if (cksum_err) {
12852 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12853 			if (hck_flags & HCK_FULLCKSUM)
12854 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12855 			else if (hck_flags & HCK_PARTIALCKSUM)
12856 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12857 			else
12858 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12859 
12860 			freemsg(first_mp);
12861 			return;
12862 		}
12863 	}
12864 
12865 	/* Non-fragmented broadcast or multicast packet? */
12866 	if (ire->ire_type == IRE_BROADCAST)
12867 		goto udpslowpath;
12868 
12869 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12870 	    ire->ire_zoneid, ipst)) != NULL) {
12871 		ASSERT(connp->conn_upq != NULL);
12872 		IP_STAT(ipst, ip_udp_fast_path);
12873 
12874 		if (CONN_UDP_FLOWCTLD(connp)) {
12875 			freemsg(mp);
12876 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12877 		} else {
12878 			if (!mctl_present) {
12879 				BUMP_MIB(ill->ill_ip_mib,
12880 				    ipIfStatsHCInDelivers);
12881 			}
12882 			/*
12883 			 * mp and first_mp can change.
12884 			 */
12885 			if (ip_udp_check(q, connp, recv_ill,
12886 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12887 				/* Send it upstream */
12888 				CONN_UDP_RECV(connp, mp);
12889 			}
12890 		}
12891 		/*
12892 		 * freeb() cannot deal with null mblk being passed
12893 		 * in and first_mp can be set to null in the call
12894 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12895 		 */
12896 		if (mctl_present && first_mp != NULL) {
12897 			freeb(first_mp);
12898 		}
12899 		CONN_DEC_REF(connp);
12900 		return;
12901 	}
12902 
12903 	/*
12904 	 * if we got here we know the packet is not fragmented and
12905 	 * has no options. The classifier could not find a conn_t and
12906 	 * most likely its an icmp packet so send it through slow path.
12907 	 */
12908 
12909 	goto udpslowpath;
12910 
12911 ipoptions:
12912 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12913 		goto slow_done;
12914 	}
12915 
12916 	UPDATE_IB_PKT_COUNT(ire);
12917 	ire->ire_last_used_time = lbolt;
12918 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12919 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12920 fragmented:
12921 		/*
12922 		 * "sum" and "reass_hck_flags" are non-zero if the
12923 		 * reassembled packet has a valid hardware computed
12924 		 * checksum information associated with it.
12925 		 */
12926 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12927 			goto slow_done;
12928 		/*
12929 		 * Make sure that first_mp points back to mp as
12930 		 * the mp we came in with could have changed in
12931 		 * ip_rput_fragment().
12932 		 */
12933 		ASSERT(!mctl_present);
12934 		ipha = (ipha_t *)mp->b_rptr;
12935 		first_mp = mp;
12936 	}
12937 
12938 	/* Now we have a complete datagram, destined for this machine. */
12939 	u1 = IPH_HDR_LENGTH(ipha);
12940 	/* Pull up the UDP header, if necessary. */
12941 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12942 udppullup:
12943 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12944 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12945 			freemsg(first_mp);
12946 			goto slow_done;
12947 		}
12948 		ipha = (ipha_t *)mp->b_rptr;
12949 	}
12950 
12951 	/*
12952 	 * Validate the checksum for the reassembled packet; for the
12953 	 * pullup case we calculate the payload checksum in software.
12954 	 */
12955 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12956 	if (up[3] != 0) {
12957 		boolean_t cksum_err;
12958 
12959 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12960 			IP_STAT(ipst, ip_in_sw_cksum);
12961 
12962 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12963 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12964 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12965 		    iphs[9] + up[2], sum, cksum_err);
12966 
12967 		if (cksum_err) {
12968 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12969 
12970 			if (reass_hck_flags & HCK_FULLCKSUM)
12971 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12972 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12973 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12974 			else
12975 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12976 
12977 			freemsg(first_mp);
12978 			goto slow_done;
12979 		}
12980 	}
12981 udpslowpath:
12982 
12983 	/* Clear hardware checksum flag to be safe */
12984 	DB_CKSUMFLAGS(mp) = 0;
12985 
12986 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12987 	    (ire->ire_type == IRE_BROADCAST),
12988 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12989 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12990 
12991 slow_done:
12992 	IP_STAT(ipst, ip_udp_slow_path);
12993 	return;
12994 
12995 #undef  iphs
12996 #undef  rptr
12997 }
12998 
12999 /* ARGSUSED */
13000 static mblk_t *
13001 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13002     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13003     ill_rx_ring_t *ill_ring)
13004 {
13005 	conn_t		*connp;
13006 	uint32_t	sum;
13007 	uint32_t	u1;
13008 	uint16_t	*up;
13009 	int		offset;
13010 	ssize_t		len;
13011 	mblk_t		*mp1;
13012 	boolean_t	syn_present = B_FALSE;
13013 	tcph_t		*tcph;
13014 	uint_t		ip_hdr_len;
13015 	ill_t		*ill = (ill_t *)q->q_ptr;
13016 	zoneid_t	zoneid = ire->ire_zoneid;
13017 	boolean_t	cksum_err;
13018 	uint16_t	hck_flags = 0;
13019 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13020 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13021 
13022 #define	rptr	((uchar_t *)ipha)
13023 
13024 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13025 	ASSERT(ill != NULL);
13026 
13027 	/*
13028 	 * FAST PATH for tcp packets
13029 	 */
13030 
13031 	/* u1 is # words of IP options */
13032 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13033 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13034 
13035 	/* IP options present */
13036 	if (u1) {
13037 		goto ipoptions;
13038 	} else {
13039 		/* Check the IP header checksum.  */
13040 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13041 			/* Clear the IP header h/w cksum flag */
13042 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13043 		} else if (!mctl_present) {
13044 			/*
13045 			 * Don't verify header checksum if this packet
13046 			 * is coming back from AH/ESP as we already did it.
13047 			 */
13048 #define	uph	((uint16_t *)ipha)
13049 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13050 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13051 #undef	uph
13052 			/* finish doing IP checksum */
13053 			sum = (sum & 0xFFFF) + (sum >> 16);
13054 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13055 			if (sum != 0 && sum != 0xFFFF) {
13056 				BUMP_MIB(ill->ill_ip_mib,
13057 				    ipIfStatsInCksumErrs);
13058 				goto error;
13059 			}
13060 		}
13061 	}
13062 
13063 	if (!mctl_present) {
13064 		UPDATE_IB_PKT_COUNT(ire);
13065 		ire->ire_last_used_time = lbolt;
13066 	}
13067 
13068 	/* packet part of fragmented IP packet? */
13069 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13070 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13071 		goto fragmented;
13072 	}
13073 
13074 	/* u1 = IP header length (20 bytes) */
13075 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13076 
13077 	/* does packet contain IP+TCP headers? */
13078 	len = mp->b_wptr - rptr;
13079 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13080 		IP_STAT(ipst, ip_tcppullup);
13081 		goto tcppullup;
13082 	}
13083 
13084 	/* TCP options present? */
13085 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13086 
13087 	/*
13088 	 * If options need to be pulled up, then goto tcpoptions.
13089 	 * otherwise we are still in the fast path
13090 	 */
13091 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13092 		IP_STAT(ipst, ip_tcpoptions);
13093 		goto tcpoptions;
13094 	}
13095 
13096 	/* multiple mblks of tcp data? */
13097 	if ((mp1 = mp->b_cont) != NULL) {
13098 		/* more then two? */
13099 		if (mp1->b_cont != NULL) {
13100 			IP_STAT(ipst, ip_multipkttcp);
13101 			goto multipkttcp;
13102 		}
13103 		len += mp1->b_wptr - mp1->b_rptr;
13104 	}
13105 
13106 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13107 
13108 	/* part of pseudo checksum */
13109 
13110 	/* TCP datagram length */
13111 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13112 
13113 #define	iphs    ((uint16_t *)ipha)
13114 
13115 #ifdef	_BIG_ENDIAN
13116 	u1 += IPPROTO_TCP;
13117 #else
13118 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13119 #endif
13120 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13121 
13122 	/*
13123 	 * Revert to software checksum calculation if the interface
13124 	 * isn't capable of checksum offload or if IPsec is present.
13125 	 */
13126 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13127 		hck_flags = DB_CKSUMFLAGS(mp);
13128 
13129 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13130 		IP_STAT(ipst, ip_in_sw_cksum);
13131 
13132 	IP_CKSUM_RECV(hck_flags, u1,
13133 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13134 	    (int32_t)((uchar_t *)up - rptr),
13135 	    mp, mp1, cksum_err);
13136 
13137 	if (cksum_err) {
13138 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13139 
13140 		if (hck_flags & HCK_FULLCKSUM)
13141 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13142 		else if (hck_flags & HCK_PARTIALCKSUM)
13143 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13144 		else
13145 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13146 
13147 		goto error;
13148 	}
13149 
13150 try_again:
13151 
13152 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13153 	    zoneid, ipst)) == NULL) {
13154 		/* Send the TH_RST */
13155 		goto no_conn;
13156 	}
13157 
13158 	/*
13159 	 * TCP FAST PATH for AF_INET socket.
13160 	 *
13161 	 * TCP fast path to avoid extra work. An AF_INET socket type
13162 	 * does not have facility to receive extra information via
13163 	 * ip_process or ip_add_info. Also, when the connection was
13164 	 * established, we made a check if this connection is impacted
13165 	 * by any global IPsec policy or per connection policy (a
13166 	 * policy that comes in effect later will not apply to this
13167 	 * connection). Since all this can be determined at the
13168 	 * connection establishment time, a quick check of flags
13169 	 * can avoid extra work.
13170 	 */
13171 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13172 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13173 		ASSERT(first_mp == mp);
13174 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13175 		SET_SQUEUE(mp, tcp_rput_data, connp);
13176 		return (mp);
13177 	}
13178 
13179 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13180 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13181 		if (IPCL_IS_TCP(connp)) {
13182 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13183 			DB_CKSUMSTART(mp) =
13184 			    (intptr_t)ip_squeue_get(ill_ring);
13185 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13186 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13187 				BUMP_MIB(ill->ill_ip_mib,
13188 				    ipIfStatsHCInDelivers);
13189 				SET_SQUEUE(mp, connp->conn_recv, connp);
13190 				return (mp);
13191 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13192 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13193 				BUMP_MIB(ill->ill_ip_mib,
13194 				    ipIfStatsHCInDelivers);
13195 				ip_squeue_enter_unbound++;
13196 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13197 				    connp);
13198 				return (mp);
13199 			}
13200 			syn_present = B_TRUE;
13201 		}
13202 
13203 	}
13204 
13205 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13206 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13207 
13208 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13209 		/* No need to send this packet to TCP */
13210 		if ((flags & TH_RST) || (flags & TH_URG)) {
13211 			CONN_DEC_REF(connp);
13212 			freemsg(first_mp);
13213 			return (NULL);
13214 		}
13215 		if (flags & TH_ACK) {
13216 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13217 			    ipst->ips_netstack->netstack_tcp, connp);
13218 			CONN_DEC_REF(connp);
13219 			return (NULL);
13220 		}
13221 
13222 		CONN_DEC_REF(connp);
13223 		freemsg(first_mp);
13224 		return (NULL);
13225 	}
13226 
13227 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13228 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13229 		    ipha, NULL, mctl_present);
13230 		if (first_mp == NULL) {
13231 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13232 			CONN_DEC_REF(connp);
13233 			return (NULL);
13234 		}
13235 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13236 			ASSERT(syn_present);
13237 			if (mctl_present) {
13238 				ASSERT(first_mp != mp);
13239 				first_mp->b_datap->db_struioflag |=
13240 				    STRUIO_POLICY;
13241 			} else {
13242 				ASSERT(first_mp == mp);
13243 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13244 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13245 			}
13246 		} else {
13247 			/*
13248 			 * Discard first_mp early since we're dealing with a
13249 			 * fully-connected conn_t and tcp doesn't do policy in
13250 			 * this case.
13251 			 */
13252 			if (mctl_present) {
13253 				freeb(first_mp);
13254 				mctl_present = B_FALSE;
13255 			}
13256 			first_mp = mp;
13257 		}
13258 	}
13259 
13260 	/* Initiate IPPF processing for fastpath */
13261 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13262 		uint32_t	ill_index;
13263 
13264 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13265 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13266 		if (mp == NULL) {
13267 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13268 			    "deferred/dropped during IPPF processing\n"));
13269 			CONN_DEC_REF(connp);
13270 			if (mctl_present)
13271 				freeb(first_mp);
13272 			return (NULL);
13273 		} else if (mctl_present) {
13274 			/*
13275 			 * ip_process might return a new mp.
13276 			 */
13277 			ASSERT(first_mp != mp);
13278 			first_mp->b_cont = mp;
13279 		} else {
13280 			first_mp = mp;
13281 		}
13282 
13283 	}
13284 
13285 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13286 		/*
13287 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13288 		 * make sure IPF_RECVIF is passed to ip_add_info.
13289 		 */
13290 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13291 		    IPCL_ZONEID(connp), ipst);
13292 		if (mp == NULL) {
13293 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13294 			CONN_DEC_REF(connp);
13295 			if (mctl_present)
13296 				freeb(first_mp);
13297 			return (NULL);
13298 		} else if (mctl_present) {
13299 			/*
13300 			 * ip_add_info might return a new mp.
13301 			 */
13302 			ASSERT(first_mp != mp);
13303 			first_mp->b_cont = mp;
13304 		} else {
13305 			first_mp = mp;
13306 		}
13307 	}
13308 
13309 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13310 	if (IPCL_IS_TCP(connp)) {
13311 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13312 		return (first_mp);
13313 	} else {
13314 		putnext(connp->conn_rq, first_mp);
13315 		CONN_DEC_REF(connp);
13316 		return (NULL);
13317 	}
13318 
13319 no_conn:
13320 	/* Initiate IPPf processing, if needed. */
13321 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13322 		uint32_t ill_index;
13323 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13324 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13325 		if (first_mp == NULL) {
13326 			return (NULL);
13327 		}
13328 	}
13329 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13330 
13331 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13332 	    ipst->ips_netstack->netstack_tcp, NULL);
13333 	return (NULL);
13334 ipoptions:
13335 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13336 		goto slow_done;
13337 	}
13338 
13339 	UPDATE_IB_PKT_COUNT(ire);
13340 	ire->ire_last_used_time = lbolt;
13341 
13342 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13343 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13344 fragmented:
13345 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13346 			if (mctl_present)
13347 				freeb(first_mp);
13348 			goto slow_done;
13349 		}
13350 		/*
13351 		 * Make sure that first_mp points back to mp as
13352 		 * the mp we came in with could have changed in
13353 		 * ip_rput_fragment().
13354 		 */
13355 		ASSERT(!mctl_present);
13356 		ipha = (ipha_t *)mp->b_rptr;
13357 		first_mp = mp;
13358 	}
13359 
13360 	/* Now we have a complete datagram, destined for this machine. */
13361 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13362 
13363 	len = mp->b_wptr - mp->b_rptr;
13364 	/* Pull up a minimal TCP header, if necessary. */
13365 	if (len < (u1 + 20)) {
13366 tcppullup:
13367 		if (!pullupmsg(mp, u1 + 20)) {
13368 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13369 			goto error;
13370 		}
13371 		ipha = (ipha_t *)mp->b_rptr;
13372 		len = mp->b_wptr - mp->b_rptr;
13373 	}
13374 
13375 	/*
13376 	 * Extract the offset field from the TCP header.  As usual, we
13377 	 * try to help the compiler more than the reader.
13378 	 */
13379 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13380 	if (offset != 5) {
13381 tcpoptions:
13382 		if (offset < 5) {
13383 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13384 			goto error;
13385 		}
13386 		/*
13387 		 * There must be TCP options.
13388 		 * Make sure we can grab them.
13389 		 */
13390 		offset <<= 2;
13391 		offset += u1;
13392 		if (len < offset) {
13393 			if (!pullupmsg(mp, offset)) {
13394 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13395 				goto error;
13396 			}
13397 			ipha = (ipha_t *)mp->b_rptr;
13398 			len = mp->b_wptr - rptr;
13399 		}
13400 	}
13401 
13402 	/* Get the total packet length in len, including headers. */
13403 	if (mp->b_cont) {
13404 multipkttcp:
13405 		len = msgdsize(mp);
13406 	}
13407 
13408 	/*
13409 	 * Check the TCP checksum by pulling together the pseudo-
13410 	 * header checksum, and passing it to ip_csum to be added in
13411 	 * with the TCP datagram.
13412 	 *
13413 	 * Since we are not using the hwcksum if available we must
13414 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13415 	 * If either of these fails along the way the mblk is freed.
13416 	 * If this logic ever changes and mblk is reused to say send
13417 	 * ICMP's back, then this flag may need to be cleared in
13418 	 * other places as well.
13419 	 */
13420 	DB_CKSUMFLAGS(mp) = 0;
13421 
13422 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13423 
13424 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13425 #ifdef	_BIG_ENDIAN
13426 	u1 += IPPROTO_TCP;
13427 #else
13428 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13429 #endif
13430 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13431 	/*
13432 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13433 	 */
13434 	IP_STAT(ipst, ip_in_sw_cksum);
13435 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13436 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13437 		goto error;
13438 	}
13439 
13440 	IP_STAT(ipst, ip_tcp_slow_path);
13441 	goto try_again;
13442 #undef  iphs
13443 #undef  rptr
13444 
13445 error:
13446 	freemsg(first_mp);
13447 slow_done:
13448 	return (NULL);
13449 }
13450 
13451 /* ARGSUSED */
13452 static void
13453 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13454     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13455 {
13456 	conn_t		*connp;
13457 	uint32_t	sum;
13458 	uint32_t	u1;
13459 	ssize_t		len;
13460 	sctp_hdr_t	*sctph;
13461 	zoneid_t	zoneid = ire->ire_zoneid;
13462 	uint32_t	pktsum;
13463 	uint32_t	calcsum;
13464 	uint32_t	ports;
13465 	in6_addr_t	map_src, map_dst;
13466 	ill_t		*ill = (ill_t *)q->q_ptr;
13467 	ip_stack_t	*ipst;
13468 	sctp_stack_t	*sctps;
13469 
13470 	ASSERT(recv_ill != NULL);
13471 	ipst = recv_ill->ill_ipst;
13472 	sctps = ipst->ips_netstack->netstack_sctp;
13473 
13474 #define	rptr	((uchar_t *)ipha)
13475 
13476 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13477 	ASSERT(ill != NULL);
13478 
13479 	/* u1 is # words of IP options */
13480 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13481 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13482 
13483 	/* IP options present */
13484 	if (u1 > 0) {
13485 		goto ipoptions;
13486 	} else {
13487 		/* Check the IP header checksum.  */
13488 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13489 		    !mctl_present) {
13490 #define	uph	((uint16_t *)ipha)
13491 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13492 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13493 #undef	uph
13494 			/* finish doing IP checksum */
13495 			sum = (sum & 0xFFFF) + (sum >> 16);
13496 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13497 			/*
13498 			 * Don't verify header checksum if this packet
13499 			 * is coming back from AH/ESP as we already did it.
13500 			 */
13501 			if (sum != 0 && sum != 0xFFFF) {
13502 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13503 				goto error;
13504 			}
13505 		}
13506 		/*
13507 		 * Since there is no SCTP h/w cksum support yet, just
13508 		 * clear the flag.
13509 		 */
13510 		DB_CKSUMFLAGS(mp) = 0;
13511 	}
13512 
13513 	/*
13514 	 * Don't verify header checksum if this packet is coming
13515 	 * back from AH/ESP as we already did it.
13516 	 */
13517 	if (!mctl_present) {
13518 		UPDATE_IB_PKT_COUNT(ire);
13519 		ire->ire_last_used_time = lbolt;
13520 	}
13521 
13522 	/* packet part of fragmented IP packet? */
13523 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13524 	if (u1 & (IPH_MF | IPH_OFFSET))
13525 		goto fragmented;
13526 
13527 	/* u1 = IP header length (20 bytes) */
13528 	u1 = IP_SIMPLE_HDR_LENGTH;
13529 
13530 find_sctp_client:
13531 	/* Pullup if we don't have the sctp common header. */
13532 	len = MBLKL(mp);
13533 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13534 		if (mp->b_cont == NULL ||
13535 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13536 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13537 			goto error;
13538 		}
13539 		ipha = (ipha_t *)mp->b_rptr;
13540 		len = MBLKL(mp);
13541 	}
13542 
13543 	sctph = (sctp_hdr_t *)(rptr + u1);
13544 #ifdef	DEBUG
13545 	if (!skip_sctp_cksum) {
13546 #endif
13547 		pktsum = sctph->sh_chksum;
13548 		sctph->sh_chksum = 0;
13549 		calcsum = sctp_cksum(mp, u1);
13550 		if (calcsum != pktsum) {
13551 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13552 			goto error;
13553 		}
13554 		sctph->sh_chksum = pktsum;
13555 #ifdef	DEBUG	/* skip_sctp_cksum */
13556 	}
13557 #endif
13558 	/* get the ports */
13559 	ports = *(uint32_t *)&sctph->sh_sport;
13560 
13561 	IRE_REFRELE(ire);
13562 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13563 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13564 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13565 	    sctps)) == NULL) {
13566 		/* Check for raw socket or OOTB handling */
13567 		goto no_conn;
13568 	}
13569 
13570 	/* Found a client; up it goes */
13571 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13572 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13573 	return;
13574 
13575 no_conn:
13576 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13577 	    ports, mctl_present, flags, B_TRUE, zoneid);
13578 	return;
13579 
13580 ipoptions:
13581 	DB_CKSUMFLAGS(mp) = 0;
13582 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13583 		goto slow_done;
13584 
13585 	UPDATE_IB_PKT_COUNT(ire);
13586 	ire->ire_last_used_time = lbolt;
13587 
13588 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13589 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13590 fragmented:
13591 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13592 			goto slow_done;
13593 		/*
13594 		 * Make sure that first_mp points back to mp as
13595 		 * the mp we came in with could have changed in
13596 		 * ip_rput_fragment().
13597 		 */
13598 		ASSERT(!mctl_present);
13599 		ipha = (ipha_t *)mp->b_rptr;
13600 		first_mp = mp;
13601 	}
13602 
13603 	/* Now we have a complete datagram, destined for this machine. */
13604 	u1 = IPH_HDR_LENGTH(ipha);
13605 	goto find_sctp_client;
13606 #undef  iphs
13607 #undef  rptr
13608 
13609 error:
13610 	freemsg(first_mp);
13611 slow_done:
13612 	IRE_REFRELE(ire);
13613 }
13614 
13615 #define	VER_BITS	0xF0
13616 #define	VERSION_6	0x60
13617 
13618 static boolean_t
13619 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13620     ipaddr_t *dstp, ip_stack_t *ipst)
13621 {
13622 	uint_t	opt_len;
13623 	ipha_t *ipha;
13624 	ssize_t len;
13625 	uint_t	pkt_len;
13626 
13627 	ASSERT(ill != NULL);
13628 	IP_STAT(ipst, ip_ipoptions);
13629 	ipha = *iphapp;
13630 
13631 #define	rptr    ((uchar_t *)ipha)
13632 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13633 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13634 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13635 		freemsg(mp);
13636 		return (B_FALSE);
13637 	}
13638 
13639 	/* multiple mblk or too short */
13640 	pkt_len = ntohs(ipha->ipha_length);
13641 
13642 	/* Get the number of words of IP options in the IP header. */
13643 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13644 	if (opt_len) {
13645 		/* IP Options present!  Validate and process. */
13646 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13647 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13648 			goto done;
13649 		}
13650 		/*
13651 		 * Recompute complete header length and make sure we
13652 		 * have access to all of it.
13653 		 */
13654 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13655 		if (len > (mp->b_wptr - rptr)) {
13656 			if (len > pkt_len) {
13657 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13658 				goto done;
13659 			}
13660 			if (!pullupmsg(mp, len)) {
13661 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13662 				goto done;
13663 			}
13664 			ipha = (ipha_t *)mp->b_rptr;
13665 		}
13666 		/*
13667 		 * Go off to ip_rput_options which returns the next hop
13668 		 * destination address, which may have been affected
13669 		 * by source routing.
13670 		 */
13671 		IP_STAT(ipst, ip_opt);
13672 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13673 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13674 			return (B_FALSE);
13675 		}
13676 	}
13677 	*iphapp = ipha;
13678 	return (B_TRUE);
13679 done:
13680 	/* clear b_prev - used by ip_mroute_decap */
13681 	mp->b_prev = NULL;
13682 	freemsg(mp);
13683 	return (B_FALSE);
13684 #undef  rptr
13685 }
13686 
13687 /*
13688  * Deal with the fact that there is no ire for the destination.
13689  */
13690 static ire_t *
13691 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13692 {
13693 	ipha_t	*ipha;
13694 	ill_t	*ill;
13695 	ire_t	*ire;
13696 	boolean_t	check_multirt = B_FALSE;
13697 	ip_stack_t *ipst;
13698 
13699 	ipha = (ipha_t *)mp->b_rptr;
13700 	ill = (ill_t *)q->q_ptr;
13701 
13702 	ASSERT(ill != NULL);
13703 	ipst = ill->ill_ipst;
13704 
13705 	/*
13706 	 * No IRE for this destination, so it can't be for us.
13707 	 * Unless we are forwarding, drop the packet.
13708 	 * We have to let source routed packets through
13709 	 * since we don't yet know if they are 'ping -l'
13710 	 * packets i.e. if they will go out over the
13711 	 * same interface as they came in on.
13712 	 */
13713 	if (ll_multicast) {
13714 		freemsg(mp);
13715 		return (NULL);
13716 	}
13717 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13718 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13719 		freemsg(mp);
13720 		return (NULL);
13721 	}
13722 
13723 	/*
13724 	 * Mark this packet as having originated externally.
13725 	 *
13726 	 * For non-forwarding code path, ire_send later double
13727 	 * checks this interface to see if it is still exists
13728 	 * post-ARP resolution.
13729 	 *
13730 	 * Also, IPQOS uses this to differentiate between
13731 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13732 	 * QOS packet processing in ip_wput_attach_llhdr().
13733 	 * The QoS module can mark the b_band for a fastpath message
13734 	 * or the dl_priority field in a unitdata_req header for
13735 	 * CoS marking. This info can only be found in
13736 	 * ip_wput_attach_llhdr().
13737 	 */
13738 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13739 	/*
13740 	 * Clear the indication that this may have a hardware checksum
13741 	 * as we are not using it
13742 	 */
13743 	DB_CKSUMFLAGS(mp) = 0;
13744 
13745 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13746 	    MBLK_GETLABEL(mp), ipst);
13747 
13748 	if (ire == NULL && check_multirt) {
13749 		/* Let ip_newroute handle CGTP  */
13750 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13751 		return (NULL);
13752 	}
13753 
13754 	if (ire != NULL)
13755 		return (ire);
13756 
13757 	mp->b_prev = mp->b_next = 0;
13758 	/* send icmp unreachable */
13759 	q = WR(q);
13760 	/* Sent by forwarding path, and router is global zone */
13761 	if (ip_source_routed(ipha, ipst)) {
13762 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13763 		    GLOBAL_ZONEID, ipst);
13764 	} else {
13765 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13766 		    ipst);
13767 	}
13768 
13769 	return (NULL);
13770 
13771 }
13772 
13773 /*
13774  * check ip header length and align it.
13775  */
13776 static boolean_t
13777 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13778 {
13779 	ssize_t len;
13780 	ill_t *ill;
13781 	ipha_t	*ipha;
13782 
13783 	len = MBLKL(mp);
13784 
13785 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13786 		ill = (ill_t *)q->q_ptr;
13787 
13788 		if (!OK_32PTR(mp->b_rptr))
13789 			IP_STAT(ipst, ip_notaligned1);
13790 		else
13791 			IP_STAT(ipst, ip_notaligned2);
13792 		/* Guard against bogus device drivers */
13793 		if (len < 0) {
13794 			/* clear b_prev - used by ip_mroute_decap */
13795 			mp->b_prev = NULL;
13796 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13797 			freemsg(mp);
13798 			return (B_FALSE);
13799 		}
13800 
13801 		if (ip_rput_pullups++ == 0) {
13802 			ipha = (ipha_t *)mp->b_rptr;
13803 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13804 			    "ip_check_and_align_header: %s forced us to "
13805 			    " pullup pkt, hdr len %ld, hdr addr %p",
13806 			    ill->ill_name, len, ipha);
13807 		}
13808 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13809 			/* clear b_prev - used by ip_mroute_decap */
13810 			mp->b_prev = NULL;
13811 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13812 			freemsg(mp);
13813 			return (B_FALSE);
13814 		}
13815 	}
13816 	return (B_TRUE);
13817 }
13818 
13819 ire_t *
13820 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13821 {
13822 	ire_t		*new_ire;
13823 	ill_t		*ire_ill;
13824 	uint_t		ifindex;
13825 	ip_stack_t	*ipst = ill->ill_ipst;
13826 	boolean_t	strict_check = B_FALSE;
13827 
13828 	/*
13829 	 * This packet came in on an interface other than the one associated
13830 	 * with the first ire we found for the destination address. We do
13831 	 * another ire lookup here, using the ingress ill, to see if the
13832 	 * interface is in an interface group.
13833 	 * As long as the ills belong to the same group, we don't consider
13834 	 * them to be arriving on the wrong interface. Thus, if the switch
13835 	 * is doing inbound load spreading, we won't drop packets when the
13836 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13837 	 * for 'usesrc groups' where the destination address may belong to
13838 	 * another interface to allow multipathing to happen.
13839 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13840 	 * where the local address may not be unique. In this case we were
13841 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13842 	 * actually returned. The new lookup, which is more specific, should
13843 	 * only find the IRE_LOCAL associated with the ingress ill if one
13844 	 * exists.
13845 	 */
13846 
13847 	if (ire->ire_ipversion == IPV4_VERSION) {
13848 		if (ipst->ips_ip_strict_dst_multihoming)
13849 			strict_check = B_TRUE;
13850 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13851 		    ill->ill_ipif, ALL_ZONES, NULL,
13852 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13853 	} else {
13854 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13855 		if (ipst->ips_ipv6_strict_dst_multihoming)
13856 			strict_check = B_TRUE;
13857 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13858 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13859 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13860 	}
13861 	/*
13862 	 * If the same ire that was returned in ip_input() is found then this
13863 	 * is an indication that interface groups are in use. The packet
13864 	 * arrived on a different ill in the group than the one associated with
13865 	 * the destination address.  If a different ire was found then the same
13866 	 * IP address must be hosted on multiple ills. This is possible with
13867 	 * unnumbered point2point interfaces. We switch to use this new ire in
13868 	 * order to have accurate interface statistics.
13869 	 */
13870 	if (new_ire != NULL) {
13871 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13872 			ire_refrele(ire);
13873 			ire = new_ire;
13874 		} else {
13875 			ire_refrele(new_ire);
13876 		}
13877 		return (ire);
13878 	} else if ((ire->ire_rfq == NULL) &&
13879 	    (ire->ire_ipversion == IPV4_VERSION)) {
13880 		/*
13881 		 * The best match could have been the original ire which
13882 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13883 		 * the strict multihoming checks are irrelevant as we consider
13884 		 * local addresses hosted on lo0 to be interface agnostic. We
13885 		 * only expect a null ire_rfq on IREs which are associated with
13886 		 * lo0 hence we can return now.
13887 		 */
13888 		return (ire);
13889 	}
13890 
13891 	/*
13892 	 * Chase pointers once and store locally.
13893 	 */
13894 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13895 	    (ill_t *)(ire->ire_rfq->q_ptr);
13896 	ifindex = ill->ill_usesrc_ifindex;
13897 
13898 	/*
13899 	 * Check if it's a legal address on the 'usesrc' interface.
13900 	 */
13901 	if ((ifindex != 0) && (ire_ill != NULL) &&
13902 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13903 		return (ire);
13904 	}
13905 
13906 	/*
13907 	 * If the ip*_strict_dst_multihoming switch is on then we can
13908 	 * only accept this packet if the interface is marked as routing.
13909 	 */
13910 	if (!(strict_check))
13911 		return (ire);
13912 
13913 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13914 	    ILLF_ROUTER) != 0) {
13915 		return (ire);
13916 	}
13917 
13918 	ire_refrele(ire);
13919 	return (NULL);
13920 }
13921 
13922 ire_t *
13923 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13924 {
13925 	ipha_t	*ipha;
13926 	ipaddr_t ip_dst, ip_src;
13927 	ire_t	*src_ire = NULL;
13928 	ill_t	*stq_ill;
13929 	uint_t	hlen;
13930 	uint_t	pkt_len;
13931 	uint32_t sum;
13932 	queue_t	*dev_q;
13933 	boolean_t check_multirt = B_FALSE;
13934 	ip_stack_t *ipst = ill->ill_ipst;
13935 
13936 	ipha = (ipha_t *)mp->b_rptr;
13937 
13938 	/*
13939 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13940 	 * The loopback address check for both src and dst has already
13941 	 * been checked in ip_input
13942 	 */
13943 	ip_dst = ntohl(dst);
13944 	ip_src = ntohl(ipha->ipha_src);
13945 
13946 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13947 	    IN_CLASSD(ip_src)) {
13948 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13949 		goto drop;
13950 	}
13951 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13952 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13953 
13954 	if (src_ire != NULL) {
13955 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13956 		goto drop;
13957 	}
13958 
13959 
13960 	/* No ire cache of nexthop. So first create one  */
13961 	if (ire == NULL) {
13962 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13963 		/*
13964 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13965 		 * is not set. So upon return from ire_forward
13966 		 * check_multirt should remain as false.
13967 		 */
13968 		ASSERT(!check_multirt);
13969 		if (ire == NULL) {
13970 			/* An attempt was made to forward the packet */
13971 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13972 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13973 			mp->b_prev = mp->b_next = 0;
13974 			/* send icmp unreachable */
13975 			/* Sent by forwarding path, and router is global zone */
13976 			if (ip_source_routed(ipha, ipst)) {
13977 				icmp_unreachable(ill->ill_wq, mp,
13978 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13979 				    ipst);
13980 			} else {
13981 				icmp_unreachable(ill->ill_wq, mp,
13982 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13983 				    ipst);
13984 			}
13985 			return (ire);
13986 		}
13987 	}
13988 
13989 	/*
13990 	 * Forwarding fastpath exception case:
13991 	 * If either of the follwoing case is true, we take
13992 	 * the slowpath
13993 	 *	o forwarding is not enabled
13994 	 *	o incoming and outgoing interface are the same, or the same
13995 	 *	  IPMP group
13996 	 *	o corresponding ire is in incomplete state
13997 	 *	o packet needs fragmentation
13998 	 *
13999 	 * The codeflow from here on is thus:
14000 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14001 	 */
14002 	pkt_len = ntohs(ipha->ipha_length);
14003 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14004 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14005 	    !(ill->ill_flags & ILLF_ROUTER) ||
14006 	    (ill == stq_ill) ||
14007 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14008 	    (ire->ire_nce == NULL) ||
14009 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14010 	    (pkt_len > ire->ire_max_frag) ||
14011 	    ipha->ipha_ttl <= 1) {
14012 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14013 		    ipha, ill, B_FALSE);
14014 		return (ire);
14015 	}
14016 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14017 
14018 	DTRACE_PROBE4(ip4__forwarding__start,
14019 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14020 
14021 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14022 	    ipst->ips_ipv4firewall_forwarding,
14023 	    ill, stq_ill, ipha, mp, mp, ipst);
14024 
14025 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14026 
14027 	if (mp == NULL)
14028 		goto drop;
14029 
14030 	mp->b_datap->db_struioun.cksum.flags = 0;
14031 	/* Adjust the checksum to reflect the ttl decrement. */
14032 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14033 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14034 	ipha->ipha_ttl--;
14035 
14036 	dev_q = ire->ire_stq->q_next;
14037 	if ((dev_q->q_next != NULL ||
14038 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14039 		goto indiscard;
14040 	}
14041 
14042 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14043 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14044 
14045 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14046 		mblk_t *mpip = mp;
14047 
14048 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14049 		if (mp != NULL) {
14050 			DTRACE_PROBE4(ip4__physical__out__start,
14051 			    ill_t *, NULL, ill_t *, stq_ill,
14052 			    ipha_t *, ipha, mblk_t *, mp);
14053 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14054 			    ipst->ips_ipv4firewall_physical_out,
14055 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14056 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14057 			    mp);
14058 			if (mp == NULL)
14059 				goto drop;
14060 
14061 			UPDATE_IB_PKT_COUNT(ire);
14062 			ire->ire_last_used_time = lbolt;
14063 			BUMP_MIB(stq_ill->ill_ip_mib,
14064 			    ipIfStatsHCOutForwDatagrams);
14065 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14066 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14067 			    pkt_len);
14068 			putnext(ire->ire_stq, mp);
14069 			return (ire);
14070 		}
14071 	}
14072 
14073 indiscard:
14074 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14075 drop:
14076 	if (mp != NULL)
14077 		freemsg(mp);
14078 	if (src_ire != NULL)
14079 		ire_refrele(src_ire);
14080 	return (ire);
14081 
14082 }
14083 
14084 /*
14085  * This function is called in the forwarding slowpath, when
14086  * either the ire lacks the link-layer address, or the packet needs
14087  * further processing(eg. fragmentation), before transmission.
14088  */
14089 
14090 static void
14091 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14092     ill_t *ill, boolean_t ll_multicast)
14093 {
14094 	ill_group_t	*ill_group;
14095 	ill_group_t	*ire_group;
14096 	queue_t		*dev_q;
14097 	ire_t		*src_ire;
14098 	ip_stack_t	*ipst = ill->ill_ipst;
14099 
14100 	ASSERT(ire->ire_stq != NULL);
14101 
14102 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14103 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14104 
14105 	if (ll_multicast != 0) {
14106 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14107 		goto drop_pkt;
14108 	}
14109 
14110 	/*
14111 	 * check if ipha_src is a broadcast address. Note that this
14112 	 * check is redundant when we get here from ip_fast_forward()
14113 	 * which has already done this check. However, since we can
14114 	 * also get here from ip_rput_process_broadcast() or, for
14115 	 * for the slow path through ip_fast_forward(), we perform
14116 	 * the check again for code-reusability
14117 	 */
14118 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14119 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14120 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14121 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14122 		if (src_ire != NULL)
14123 			ire_refrele(src_ire);
14124 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14125 		ip2dbg(("ip_rput_process_forward: Received packet with"
14126 		    " bad src/dst address on %s\n", ill->ill_name));
14127 		goto drop_pkt;
14128 	}
14129 
14130 	ill_group = ill->ill_group;
14131 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14132 	/*
14133 	 * Check if we want to forward this one at this time.
14134 	 * We allow source routed packets on a host provided that
14135 	 * they go out the same interface or same interface group
14136 	 * as they came in on.
14137 	 *
14138 	 * XXX To be quicker, we may wish to not chase pointers to
14139 	 * get the ILLF_ROUTER flag and instead store the
14140 	 * forwarding policy in the ire.  An unfortunate
14141 	 * side-effect of that would be requiring an ire flush
14142 	 * whenever the ILLF_ROUTER flag changes.
14143 	 */
14144 	if (((ill->ill_flags &
14145 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14146 	    ILLF_ROUTER) == 0) &&
14147 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14148 	    (ill_group != NULL && ill_group == ire_group)))) {
14149 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14150 		if (ip_source_routed(ipha, ipst)) {
14151 			q = WR(q);
14152 			/*
14153 			 * Clear the indication that this may have
14154 			 * hardware checksum as we are not using it.
14155 			 */
14156 			DB_CKSUMFLAGS(mp) = 0;
14157 			/* Sent by forwarding path, and router is global zone */
14158 			icmp_unreachable(q, mp,
14159 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14160 			return;
14161 		}
14162 		goto drop_pkt;
14163 	}
14164 
14165 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14166 
14167 	/* Packet is being forwarded. Turning off hwcksum flag. */
14168 	DB_CKSUMFLAGS(mp) = 0;
14169 	if (ipst->ips_ip_g_send_redirects) {
14170 		/*
14171 		 * Check whether the incoming interface and outgoing
14172 		 * interface is part of the same group. If so,
14173 		 * send redirects.
14174 		 *
14175 		 * Check the source address to see if it originated
14176 		 * on the same logical subnet it is going back out on.
14177 		 * If so, we should be able to send it a redirect.
14178 		 * Avoid sending a redirect if the destination
14179 		 * is directly connected (i.e., ipha_dst is the same
14180 		 * as ire_gateway_addr or the ire_addr of the
14181 		 * nexthop IRE_CACHE ), or if the packet was source
14182 		 * routed out this interface.
14183 		 */
14184 		ipaddr_t src, nhop;
14185 		mblk_t	*mp1;
14186 		ire_t	*nhop_ire = NULL;
14187 
14188 		/*
14189 		 * Check whether ire_rfq and q are from the same ill
14190 		 * or if they are not same, they at least belong
14191 		 * to the same group. If so, send redirects.
14192 		 */
14193 		if ((ire->ire_rfq == q ||
14194 		    (ill_group != NULL && ill_group == ire_group)) &&
14195 		    !ip_source_routed(ipha, ipst)) {
14196 
14197 			nhop = (ire->ire_gateway_addr != 0 ?
14198 			    ire->ire_gateway_addr : ire->ire_addr);
14199 
14200 			if (ipha->ipha_dst == nhop) {
14201 				/*
14202 				 * We avoid sending a redirect if the
14203 				 * destination is directly connected
14204 				 * because it is possible that multiple
14205 				 * IP subnets may have been configured on
14206 				 * the link, and the source may not
14207 				 * be on the same subnet as ip destination,
14208 				 * even though they are on the same
14209 				 * physical link.
14210 				 */
14211 				goto sendit;
14212 			}
14213 
14214 			src = ipha->ipha_src;
14215 
14216 			/*
14217 			 * We look up the interface ire for the nexthop,
14218 			 * to see if ipha_src is in the same subnet
14219 			 * as the nexthop.
14220 			 *
14221 			 * Note that, if, in the future, IRE_CACHE entries
14222 			 * are obsoleted,  this lookup will not be needed,
14223 			 * as the ire passed to this function will be the
14224 			 * same as the nhop_ire computed below.
14225 			 */
14226 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14227 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14228 			    0, NULL, MATCH_IRE_TYPE, ipst);
14229 
14230 			if (nhop_ire != NULL) {
14231 				if ((src & nhop_ire->ire_mask) ==
14232 				    (nhop & nhop_ire->ire_mask)) {
14233 					/*
14234 					 * The source is directly connected.
14235 					 * Just copy the ip header (which is
14236 					 * in the first mblk)
14237 					 */
14238 					mp1 = copyb(mp);
14239 					if (mp1 != NULL) {
14240 						icmp_send_redirect(WR(q), mp1,
14241 						    nhop, ipst);
14242 					}
14243 				}
14244 				ire_refrele(nhop_ire);
14245 			}
14246 		}
14247 	}
14248 sendit:
14249 	dev_q = ire->ire_stq->q_next;
14250 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14251 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14252 		freemsg(mp);
14253 		return;
14254 	}
14255 
14256 	ip_rput_forward(ire, ipha, mp, ill);
14257 	return;
14258 
14259 drop_pkt:
14260 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14261 	freemsg(mp);
14262 }
14263 
14264 ire_t *
14265 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14266     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14267 {
14268 	queue_t		*q;
14269 	uint16_t	hcksumflags;
14270 	ip_stack_t	*ipst = ill->ill_ipst;
14271 
14272 	q = *qp;
14273 
14274 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14275 
14276 	/*
14277 	 * Clear the indication that this may have hardware
14278 	 * checksum as we are not using it for forwarding.
14279 	 */
14280 	hcksumflags = DB_CKSUMFLAGS(mp);
14281 	DB_CKSUMFLAGS(mp) = 0;
14282 
14283 	/*
14284 	 * Directed broadcast forwarding: if the packet came in over a
14285 	 * different interface then it is routed out over we can forward it.
14286 	 */
14287 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14288 		ire_refrele(ire);
14289 		freemsg(mp);
14290 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14291 		return (NULL);
14292 	}
14293 	/*
14294 	 * For multicast we have set dst to be INADDR_BROADCAST
14295 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14296 	 * only for broadcast packets.
14297 	 */
14298 	if (!CLASSD(ipha->ipha_dst)) {
14299 		ire_t *new_ire;
14300 		ipif_t *ipif;
14301 		/*
14302 		 * For ill groups, as the switch duplicates broadcasts
14303 		 * across all the ports, we need to filter out and
14304 		 * send up only one copy. There is one copy for every
14305 		 * broadcast address on each ill. Thus, we look for a
14306 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14307 		 * later to see whether this ill is eligible to receive
14308 		 * them or not. ill_nominate_bcast_rcv() nominates only
14309 		 * one set of IREs for receiving.
14310 		 */
14311 
14312 		ipif = ipif_get_next_ipif(NULL, ill);
14313 		if (ipif == NULL) {
14314 			ire_refrele(ire);
14315 			freemsg(mp);
14316 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14317 			return (NULL);
14318 		}
14319 		new_ire = ire_ctable_lookup(dst, 0, 0,
14320 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14321 		ipif_refrele(ipif);
14322 
14323 		if (new_ire != NULL) {
14324 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14325 				ire_refrele(ire);
14326 				ire_refrele(new_ire);
14327 				freemsg(mp);
14328 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14329 				return (NULL);
14330 			}
14331 			/*
14332 			 * In the special case of multirouted broadcast
14333 			 * packets, we unconditionally need to "gateway"
14334 			 * them to the appropriate interface here.
14335 			 * In the normal case, this cannot happen, because
14336 			 * there is no broadcast IRE tagged with the
14337 			 * RTF_MULTIRT flag.
14338 			 */
14339 			if (new_ire->ire_flags & RTF_MULTIRT) {
14340 				ire_refrele(new_ire);
14341 				if (ire->ire_rfq != NULL) {
14342 					q = ire->ire_rfq;
14343 					*qp = q;
14344 				}
14345 			} else {
14346 				ire_refrele(ire);
14347 				ire = new_ire;
14348 			}
14349 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14350 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14351 				/*
14352 				 * Free the message if
14353 				 * ip_g_forward_directed_bcast is turned
14354 				 * off for non-local broadcast.
14355 				 */
14356 				ire_refrele(ire);
14357 				freemsg(mp);
14358 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14359 				return (NULL);
14360 			}
14361 		} else {
14362 			/*
14363 			 * This CGTP packet successfully passed the
14364 			 * CGTP filter, but the related CGTP
14365 			 * broadcast IRE has not been found,
14366 			 * meaning that the redundant ipif is
14367 			 * probably down. However, if we discarded
14368 			 * this packet, its duplicate would be
14369 			 * filtered out by the CGTP filter so none
14370 			 * of them would get through. So we keep
14371 			 * going with this one.
14372 			 */
14373 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14374 			if (ire->ire_rfq != NULL) {
14375 				q = ire->ire_rfq;
14376 				*qp = q;
14377 			}
14378 		}
14379 	}
14380 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14381 		/*
14382 		 * Verify that there are not more then one
14383 		 * IRE_BROADCAST with this broadcast address which
14384 		 * has ire_stq set.
14385 		 * TODO: simplify, loop over all IRE's
14386 		 */
14387 		ire_t	*ire1;
14388 		int	num_stq = 0;
14389 		mblk_t	*mp1;
14390 
14391 		/* Find the first one with ire_stq set */
14392 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14393 		for (ire1 = ire; ire1 &&
14394 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14395 		    ire1 = ire1->ire_next)
14396 			;
14397 		if (ire1) {
14398 			ire_refrele(ire);
14399 			ire = ire1;
14400 			IRE_REFHOLD(ire);
14401 		}
14402 
14403 		/* Check if there are additional ones with stq set */
14404 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14405 			if (ire->ire_addr != ire1->ire_addr)
14406 				break;
14407 			if (ire1->ire_stq) {
14408 				num_stq++;
14409 				break;
14410 			}
14411 		}
14412 		rw_exit(&ire->ire_bucket->irb_lock);
14413 		if (num_stq == 1 && ire->ire_stq != NULL) {
14414 			ip1dbg(("ip_rput_process_broadcast: directed "
14415 			    "broadcast to 0x%x\n",
14416 			    ntohl(ire->ire_addr)));
14417 			mp1 = copymsg(mp);
14418 			if (mp1) {
14419 				switch (ipha->ipha_protocol) {
14420 				case IPPROTO_UDP:
14421 					ip_udp_input(q, mp1, ipha, ire, ill);
14422 					break;
14423 				default:
14424 					ip_proto_input(q, mp1, ipha, ire, ill,
14425 					    B_FALSE);
14426 					break;
14427 				}
14428 			}
14429 			/*
14430 			 * Adjust ttl to 2 (1+1 - the forward engine
14431 			 * will decrement it by one.
14432 			 */
14433 			if (ip_csum_hdr(ipha)) {
14434 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14435 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14436 				freemsg(mp);
14437 				ire_refrele(ire);
14438 				return (NULL);
14439 			}
14440 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14441 			ipha->ipha_hdr_checksum = 0;
14442 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14443 			ip_rput_process_forward(q, mp, ire, ipha,
14444 			    ill, ll_multicast);
14445 			ire_refrele(ire);
14446 			return (NULL);
14447 		}
14448 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14449 		    ntohl(ire->ire_addr)));
14450 	}
14451 
14452 
14453 	/* Restore any hardware checksum flags */
14454 	DB_CKSUMFLAGS(mp) = hcksumflags;
14455 	return (ire);
14456 }
14457 
14458 /* ARGSUSED */
14459 static boolean_t
14460 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14461     int *ll_multicast, ipaddr_t *dstp)
14462 {
14463 	ip_stack_t	*ipst = ill->ill_ipst;
14464 
14465 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14466 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14467 	    ntohs(ipha->ipha_length));
14468 
14469 	/*
14470 	 * Forward packets only if we have joined the allmulti
14471 	 * group on this interface.
14472 	 */
14473 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14474 		int retval;
14475 
14476 		/*
14477 		 * Clear the indication that this may have hardware
14478 		 * checksum as we are not using it.
14479 		 */
14480 		DB_CKSUMFLAGS(mp) = 0;
14481 		retval = ip_mforward(ill, ipha, mp);
14482 		/* ip_mforward updates mib variables if needed */
14483 		/* clear b_prev - used by ip_mroute_decap */
14484 		mp->b_prev = NULL;
14485 
14486 		switch (retval) {
14487 		case 0:
14488 			/*
14489 			 * pkt is okay and arrived on phyint.
14490 			 *
14491 			 * If we are running as a multicast router
14492 			 * we need to see all IGMP and/or PIM packets.
14493 			 */
14494 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14495 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14496 				goto done;
14497 			}
14498 			break;
14499 		case -1:
14500 			/* pkt is mal-formed, toss it */
14501 			goto drop_pkt;
14502 		case 1:
14503 			/* pkt is okay and arrived on a tunnel */
14504 			/*
14505 			 * If we are running a multicast router
14506 			 *  we need to see all igmp packets.
14507 			 */
14508 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14509 				*dstp = INADDR_BROADCAST;
14510 				*ll_multicast = 1;
14511 				return (B_FALSE);
14512 			}
14513 
14514 			goto drop_pkt;
14515 		}
14516 	}
14517 
14518 	ILM_WALKER_HOLD(ill);
14519 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14520 		/*
14521 		 * This might just be caused by the fact that
14522 		 * multiple IP Multicast addresses map to the same
14523 		 * link layer multicast - no need to increment counter!
14524 		 */
14525 		ILM_WALKER_RELE(ill);
14526 		freemsg(mp);
14527 		return (B_TRUE);
14528 	}
14529 	ILM_WALKER_RELE(ill);
14530 done:
14531 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14532 	/*
14533 	 * This assumes the we deliver to all streams for multicast
14534 	 * and broadcast packets.
14535 	 */
14536 	*dstp = INADDR_BROADCAST;
14537 	*ll_multicast = 1;
14538 	return (B_FALSE);
14539 drop_pkt:
14540 	ip2dbg(("ip_rput: drop pkt\n"));
14541 	freemsg(mp);
14542 	return (B_TRUE);
14543 }
14544 
14545 static boolean_t
14546 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14547     int *ll_multicast, mblk_t **mpp)
14548 {
14549 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14550 	boolean_t must_copy = B_FALSE;
14551 	struct iocblk   *iocp;
14552 	ipha_t		*ipha;
14553 	ip_stack_t	*ipst = ill->ill_ipst;
14554 
14555 #define	rptr    ((uchar_t *)ipha)
14556 
14557 	first_mp = *first_mpp;
14558 	mp = *mpp;
14559 
14560 	ASSERT(first_mp == mp);
14561 
14562 	/*
14563 	 * if db_ref > 1 then copymsg and free original. Packet may be
14564 	 * changed and do not want other entity who has a reference to this
14565 	 * message to trip over the changes. This is a blind change because
14566 	 * trying to catch all places that might change packet is too
14567 	 * difficult (since it may be a module above this one)
14568 	 *
14569 	 * This corresponds to the non-fast path case. We walk down the full
14570 	 * chain in this case, and check the db_ref count of all the dblks,
14571 	 * and do a copymsg if required. It is possible that the db_ref counts
14572 	 * of the data blocks in the mblk chain can be different.
14573 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14574 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14575 	 * 'snoop' is running.
14576 	 */
14577 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14578 		if (mp1->b_datap->db_ref > 1) {
14579 			must_copy = B_TRUE;
14580 			break;
14581 		}
14582 	}
14583 
14584 	if (must_copy) {
14585 		mp1 = copymsg(mp);
14586 		if (mp1 == NULL) {
14587 			for (mp1 = mp; mp1 != NULL;
14588 			    mp1 = mp1->b_cont) {
14589 				mp1->b_next = NULL;
14590 				mp1->b_prev = NULL;
14591 			}
14592 			freemsg(mp);
14593 			if (ill != NULL) {
14594 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14595 			} else {
14596 				BUMP_MIB(&ipst->ips_ip_mib,
14597 				    ipIfStatsInDiscards);
14598 			}
14599 			return (B_TRUE);
14600 		}
14601 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14602 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14603 			/* Copy b_prev - used by ip_mroute_decap */
14604 			to_mp->b_prev = from_mp->b_prev;
14605 			from_mp->b_prev = NULL;
14606 		}
14607 		*first_mpp = first_mp = mp1;
14608 		freemsg(mp);
14609 		mp = mp1;
14610 		*mpp = mp1;
14611 	}
14612 
14613 	ipha = (ipha_t *)mp->b_rptr;
14614 
14615 	/*
14616 	 * previous code has a case for M_DATA.
14617 	 * We want to check how that happens.
14618 	 */
14619 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14620 	switch (first_mp->b_datap->db_type) {
14621 	case M_PROTO:
14622 	case M_PCPROTO:
14623 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14624 		    DL_UNITDATA_IND) {
14625 			/* Go handle anything other than data elsewhere. */
14626 			ip_rput_dlpi(q, mp);
14627 			return (B_TRUE);
14628 		}
14629 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14630 		/* Ditch the DLPI header. */
14631 		mp1 = mp->b_cont;
14632 		ASSERT(first_mp == mp);
14633 		*first_mpp = mp1;
14634 		freeb(mp);
14635 		*mpp = mp1;
14636 		return (B_FALSE);
14637 	case M_IOCACK:
14638 		ip1dbg(("got iocack "));
14639 		iocp = (struct iocblk *)mp->b_rptr;
14640 		switch (iocp->ioc_cmd) {
14641 		case DL_IOC_HDR_INFO:
14642 			ill = (ill_t *)q->q_ptr;
14643 			ill_fastpath_ack(ill, mp);
14644 			return (B_TRUE);
14645 		case SIOCSTUNPARAM:
14646 		case OSIOCSTUNPARAM:
14647 			/* Go through qwriter_ip */
14648 			break;
14649 		case SIOCGTUNPARAM:
14650 		case OSIOCGTUNPARAM:
14651 			ip_rput_other(NULL, q, mp, NULL);
14652 			return (B_TRUE);
14653 		default:
14654 			putnext(q, mp);
14655 			return (B_TRUE);
14656 		}
14657 		/* FALLTHRU */
14658 	case M_ERROR:
14659 	case M_HANGUP:
14660 		/*
14661 		 * Since this is on the ill stream we unconditionally
14662 		 * bump up the refcount
14663 		 */
14664 		ill_refhold(ill);
14665 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14666 		return (B_TRUE);
14667 	case M_CTL:
14668 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14669 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14670 		    IPHADA_M_CTL)) {
14671 			/*
14672 			 * It's an IPsec accelerated packet.
14673 			 * Make sure that the ill from which we received the
14674 			 * packet has enabled IPsec hardware acceleration.
14675 			 */
14676 			if (!(ill->ill_capabilities &
14677 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14678 				/* IPsec kstats: bean counter */
14679 				freemsg(mp);
14680 				return (B_TRUE);
14681 			}
14682 
14683 			/*
14684 			 * Make mp point to the mblk following the M_CTL,
14685 			 * then process according to type of mp.
14686 			 * After this processing, first_mp will point to
14687 			 * the data-attributes and mp to the pkt following
14688 			 * the M_CTL.
14689 			 */
14690 			mp = first_mp->b_cont;
14691 			if (mp == NULL) {
14692 				freemsg(first_mp);
14693 				return (B_TRUE);
14694 			}
14695 			/*
14696 			 * A Hardware Accelerated packet can only be M_DATA
14697 			 * ESP or AH packet.
14698 			 */
14699 			if (mp->b_datap->db_type != M_DATA) {
14700 				/* non-M_DATA IPsec accelerated packet */
14701 				IPSECHW_DEBUG(IPSECHW_PKT,
14702 				    ("non-M_DATA IPsec accelerated pkt\n"));
14703 				freemsg(first_mp);
14704 				return (B_TRUE);
14705 			}
14706 			ipha = (ipha_t *)mp->b_rptr;
14707 			if (ipha->ipha_protocol != IPPROTO_AH &&
14708 			    ipha->ipha_protocol != IPPROTO_ESP) {
14709 				IPSECHW_DEBUG(IPSECHW_PKT,
14710 				    ("non-M_DATA IPsec accelerated pkt\n"));
14711 				freemsg(first_mp);
14712 				return (B_TRUE);
14713 			}
14714 			*mpp = mp;
14715 			return (B_FALSE);
14716 		}
14717 		putnext(q, mp);
14718 		return (B_TRUE);
14719 	case M_IOCNAK:
14720 		ip1dbg(("got iocnak "));
14721 		iocp = (struct iocblk *)mp->b_rptr;
14722 		switch (iocp->ioc_cmd) {
14723 		case SIOCSTUNPARAM:
14724 		case OSIOCSTUNPARAM:
14725 			/*
14726 			 * Since this is on the ill stream we unconditionally
14727 			 * bump up the refcount
14728 			 */
14729 			ill_refhold(ill);
14730 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14731 			return (B_TRUE);
14732 		case DL_IOC_HDR_INFO:
14733 		case SIOCGTUNPARAM:
14734 		case OSIOCGTUNPARAM:
14735 			ip_rput_other(NULL, q, mp, NULL);
14736 			return (B_TRUE);
14737 		default:
14738 			break;
14739 		}
14740 		/* FALLTHRU */
14741 	default:
14742 		putnext(q, mp);
14743 		return (B_TRUE);
14744 	}
14745 }
14746 
14747 /* Read side put procedure.  Packets coming from the wire arrive here. */
14748 void
14749 ip_rput(queue_t *q, mblk_t *mp)
14750 {
14751 	ill_t		*ill = (ill_t *)q->q_ptr;
14752 	ip_stack_t	*ipst = ill->ill_ipst;
14753 	union DL_primitives *dl;
14754 
14755 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14756 
14757 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14758 		/*
14759 		 * If things are opening or closing, only accept high-priority
14760 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14761 		 * created; on close, things hanging off the ill may have been
14762 		 * freed already.)
14763 		 */
14764 		dl = (union DL_primitives *)mp->b_rptr;
14765 		if (DB_TYPE(mp) != M_PCPROTO ||
14766 		    dl->dl_primitive == DL_UNITDATA_IND) {
14767 			/*
14768 			 * SIOC[GS]TUNPARAM ioctls can come here.
14769 			 */
14770 			inet_freemsg(mp);
14771 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14772 			    "ip_rput_end: q %p (%S)", q, "uninit");
14773 			return;
14774 		}
14775 	}
14776 
14777 	/*
14778 	 * if db_ref > 1 then copymsg and free original. Packet may be
14779 	 * changed and we do not want the other entity who has a reference to
14780 	 * this message to trip over the changes. This is a blind change because
14781 	 * trying to catch all places that might change the packet is too
14782 	 * difficult.
14783 	 *
14784 	 * This corresponds to the fast path case, where we have a chain of
14785 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14786 	 * in the mblk chain. There doesn't seem to be a reason why a device
14787 	 * driver would send up data with varying db_ref counts in the mblk
14788 	 * chain. In any case the Fast path is a private interface, and our
14789 	 * drivers don't do such a thing. Given the above assumption, there is
14790 	 * no need to walk down the entire mblk chain (which could have a
14791 	 * potential performance problem)
14792 	 */
14793 	if (mp->b_datap->db_ref > 1) {
14794 		mblk_t  *mp1;
14795 		boolean_t adjusted = B_FALSE;
14796 		IP_STAT(ipst, ip_db_ref);
14797 
14798 		/*
14799 		 * The IP_RECVSLLA option depends on having the link layer
14800 		 * header. First check that:
14801 		 * a> the underlying device is of type ether, since this
14802 		 * option is currently supported only over ethernet.
14803 		 * b> there is enough room to copy over the link layer header.
14804 		 *
14805 		 * Once the checks are done, adjust rptr so that the link layer
14806 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14807 		 * be returned by some non-ethernet drivers but in this case the
14808 		 * second check will fail.
14809 		 */
14810 		if (ill->ill_type == IFT_ETHER &&
14811 		    (mp->b_rptr - mp->b_datap->db_base) >=
14812 		    sizeof (struct ether_header)) {
14813 			mp->b_rptr -= sizeof (struct ether_header);
14814 			adjusted = B_TRUE;
14815 		}
14816 		mp1 = copymsg(mp);
14817 		if (mp1 == NULL) {
14818 			mp->b_next = NULL;
14819 			/* clear b_prev - used by ip_mroute_decap */
14820 			mp->b_prev = NULL;
14821 			freemsg(mp);
14822 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14823 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14824 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14825 			return;
14826 		}
14827 		if (adjusted) {
14828 			/*
14829 			 * Copy is done. Restore the pointer in the _new_ mblk
14830 			 */
14831 			mp1->b_rptr += sizeof (struct ether_header);
14832 		}
14833 		/* Copy b_prev - used by ip_mroute_decap */
14834 		mp1->b_prev = mp->b_prev;
14835 		mp->b_prev = NULL;
14836 		freemsg(mp);
14837 		mp = mp1;
14838 	}
14839 
14840 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14841 	    "ip_rput_end: q %p (%S)", q, "end");
14842 
14843 	ip_input(ill, NULL, mp, NULL);
14844 }
14845 
14846 /*
14847  * Direct read side procedure capable of dealing with chains. GLDv3 based
14848  * drivers call this function directly with mblk chains while STREAMS
14849  * read side procedure ip_rput() calls this for single packet with ip_ring
14850  * set to NULL to process one packet at a time.
14851  *
14852  * The ill will always be valid if this function is called directly from
14853  * the driver.
14854  *
14855  * If ip_input() is called from GLDv3:
14856  *
14857  *   - This must be a non-VLAN IP stream.
14858  *   - 'mp' is either an untagged or a special priority-tagged packet.
14859  *   - Any VLAN tag that was in the MAC header has been stripped.
14860  *
14861  * If the IP header in packet is not 32-bit aligned, every message in the
14862  * chain will be aligned before further operations. This is required on SPARC
14863  * platform.
14864  */
14865 /* ARGSUSED */
14866 void
14867 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14868     struct mac_header_info_s *mhip)
14869 {
14870 	ipaddr_t		dst = NULL;
14871 	ipaddr_t		prev_dst;
14872 	ire_t			*ire = NULL;
14873 	ipha_t			*ipha;
14874 	uint_t			pkt_len;
14875 	ssize_t			len;
14876 	uint_t			opt_len;
14877 	int			ll_multicast;
14878 	int			cgtp_flt_pkt;
14879 	queue_t			*q = ill->ill_rq;
14880 	squeue_t		*curr_sqp = NULL;
14881 	mblk_t 			*head = NULL;
14882 	mblk_t			*tail = NULL;
14883 	mblk_t			*first_mp;
14884 	mblk_t 			*mp;
14885 	mblk_t			*dmp;
14886 	int			cnt = 0;
14887 	ip_stack_t		*ipst = ill->ill_ipst;
14888 
14889 	ASSERT(mp_chain != NULL);
14890 	ASSERT(ill != NULL);
14891 
14892 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14893 
14894 #define	rptr	((uchar_t *)ipha)
14895 
14896 	while (mp_chain != NULL) {
14897 		first_mp = mp = mp_chain;
14898 		mp_chain = mp_chain->b_next;
14899 		mp->b_next = NULL;
14900 		ll_multicast = 0;
14901 
14902 		/*
14903 		 * We do ire caching from one iteration to
14904 		 * another. In the event the packet chain contains
14905 		 * all packets from the same dst, this caching saves
14906 		 * an ire_cache_lookup for each of the succeeding
14907 		 * packets in a packet chain.
14908 		 */
14909 		prev_dst = dst;
14910 
14911 		/*
14912 		 * Check and align the IP header.
14913 		 */
14914 		if (DB_TYPE(mp) == M_DATA) {
14915 			dmp = mp;
14916 		} else if (DB_TYPE(mp) == M_PROTO &&
14917 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14918 			dmp = mp->b_cont;
14919 		} else {
14920 			dmp = NULL;
14921 		}
14922 		if (dmp != NULL) {
14923 			/*
14924 			 * IP header ptr not aligned?
14925 			 * OR IP header not complete in first mblk
14926 			 */
14927 			if (!OK_32PTR(dmp->b_rptr) ||
14928 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14929 				if (!ip_check_and_align_header(q, dmp, ipst))
14930 					continue;
14931 			}
14932 		}
14933 
14934 		/*
14935 		 * ip_input fast path
14936 		 */
14937 
14938 		/* mblk type is not M_DATA */
14939 		if (DB_TYPE(mp) != M_DATA) {
14940 			if (ip_rput_process_notdata(q, &first_mp, ill,
14941 			    &ll_multicast, &mp))
14942 				continue;
14943 		}
14944 
14945 		/* Make sure its an M_DATA and that its aligned */
14946 		ASSERT(DB_TYPE(mp) == M_DATA);
14947 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14948 
14949 		ipha = (ipha_t *)mp->b_rptr;
14950 		len = mp->b_wptr - rptr;
14951 		pkt_len = ntohs(ipha->ipha_length);
14952 
14953 		/*
14954 		 * We must count all incoming packets, even if they end
14955 		 * up being dropped later on.
14956 		 */
14957 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14958 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14959 
14960 		/* multiple mblk or too short */
14961 		len -= pkt_len;
14962 		if (len != 0) {
14963 			/*
14964 			 * Make sure we have data length consistent
14965 			 * with the IP header.
14966 			 */
14967 			if (mp->b_cont == NULL) {
14968 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14969 					BUMP_MIB(ill->ill_ip_mib,
14970 					    ipIfStatsInHdrErrors);
14971 					ip2dbg(("ip_input: drop pkt\n"));
14972 					freemsg(mp);
14973 					continue;
14974 				}
14975 				mp->b_wptr = rptr + pkt_len;
14976 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14977 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14978 					BUMP_MIB(ill->ill_ip_mib,
14979 					    ipIfStatsInHdrErrors);
14980 					ip2dbg(("ip_input: drop pkt\n"));
14981 					freemsg(mp);
14982 					continue;
14983 				}
14984 				(void) adjmsg(mp, -len);
14985 				IP_STAT(ipst, ip_multimblk3);
14986 			}
14987 		}
14988 
14989 		/* Obtain the dst of the current packet */
14990 		dst = ipha->ipha_dst;
14991 
14992 		if (IP_LOOPBACK_ADDR(dst) ||
14993 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14994 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14995 			cmn_err(CE_CONT, "dst %X src %X\n",
14996 			    dst, ipha->ipha_src);
14997 			freemsg(mp);
14998 			continue;
14999 		}
15000 
15001 		/*
15002 		 * The event for packets being received from a 'physical'
15003 		 * interface is placed after validation of the source and/or
15004 		 * destination address as being local so that packets can be
15005 		 * redirected to loopback addresses using ipnat.
15006 		 */
15007 		DTRACE_PROBE4(ip4__physical__in__start,
15008 		    ill_t *, ill, ill_t *, NULL,
15009 		    ipha_t *, ipha, mblk_t *, first_mp);
15010 
15011 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15012 		    ipst->ips_ipv4firewall_physical_in,
15013 		    ill, NULL, ipha, first_mp, mp, ipst);
15014 
15015 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15016 
15017 		if (first_mp == NULL) {
15018 			continue;
15019 		}
15020 		dst = ipha->ipha_dst;
15021 
15022 		/*
15023 		 * Attach any necessary label information to
15024 		 * this packet
15025 		 */
15026 		if (is_system_labeled() &&
15027 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15028 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15029 			freemsg(mp);
15030 			continue;
15031 		}
15032 
15033 		/*
15034 		 * Reuse the cached ire only if the ipha_dst of the previous
15035 		 * packet is the same as the current packet AND it is not
15036 		 * INADDR_ANY.
15037 		 */
15038 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15039 		    (ire != NULL)) {
15040 			ire_refrele(ire);
15041 			ire = NULL;
15042 		}
15043 		opt_len = ipha->ipha_version_and_hdr_length -
15044 		    IP_SIMPLE_HDR_VERSION;
15045 
15046 		/*
15047 		 * Check to see if we can take the fastpath.
15048 		 * That is possible if the following conditions are met
15049 		 *	o Tsol disabled
15050 		 *	o CGTP disabled
15051 		 *	o ipp_action_count is 0
15052 		 *	o no options in the packet
15053 		 *	o not a RSVP packet
15054 		 * 	o not a multicast packet
15055 		 */
15056 		if (!is_system_labeled() &&
15057 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15058 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15059 		    !ll_multicast && !CLASSD(dst)) {
15060 			if (ire == NULL)
15061 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15062 				    ipst);
15063 
15064 			/* incoming packet is for forwarding */
15065 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15066 				ire = ip_fast_forward(ire, dst, ill, mp);
15067 				continue;
15068 			}
15069 			/* incoming packet is for local consumption */
15070 			if (ire->ire_type & IRE_LOCAL)
15071 				goto local;
15072 		}
15073 
15074 		/*
15075 		 * Disable ire caching for anything more complex
15076 		 * than the simple fast path case we checked for above.
15077 		 */
15078 		if (ire != NULL) {
15079 			ire_refrele(ire);
15080 			ire = NULL;
15081 		}
15082 
15083 		/* Full-blown slow path */
15084 		if (opt_len != 0) {
15085 			if (len != 0)
15086 				IP_STAT(ipst, ip_multimblk4);
15087 			else
15088 				IP_STAT(ipst, ip_ipoptions);
15089 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15090 			    &dst, ipst))
15091 				continue;
15092 		}
15093 
15094 		/*
15095 		 * Invoke the CGTP (multirouting) filtering module to process
15096 		 * the incoming packet. Packets identified as duplicates
15097 		 * must be discarded. Filtering is active only if the
15098 		 * the ip_cgtp_filter ndd variable is non-zero.
15099 		 */
15100 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15101 		if (ipst->ips_ip_cgtp_filter &&
15102 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15103 			netstackid_t stackid;
15104 
15105 			stackid = ipst->ips_netstack->netstack_stackid;
15106 			cgtp_flt_pkt =
15107 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15108 			    ill->ill_phyint->phyint_ifindex, mp);
15109 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15110 				freemsg(first_mp);
15111 				continue;
15112 			}
15113 		}
15114 
15115 		/*
15116 		 * If rsvpd is running, let RSVP daemon handle its processing
15117 		 * and forwarding of RSVP multicast/unicast packets.
15118 		 * If rsvpd is not running but mrouted is running, RSVP
15119 		 * multicast packets are forwarded as multicast traffic
15120 		 * and RSVP unicast packets are forwarded by unicast router.
15121 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15122 		 * packets are not forwarded, but the unicast packets are
15123 		 * forwarded like unicast traffic.
15124 		 */
15125 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15126 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15127 		    NULL) {
15128 			/* RSVP packet and rsvpd running. Treat as ours */
15129 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15130 			/*
15131 			 * This assumes that we deliver to all streams for
15132 			 * multicast and broadcast packets.
15133 			 * We have to force ll_multicast to 1 to handle the
15134 			 * M_DATA messages passed in from ip_mroute_decap.
15135 			 */
15136 			dst = INADDR_BROADCAST;
15137 			ll_multicast = 1;
15138 		} else if (CLASSD(dst)) {
15139 			/* packet is multicast */
15140 			mp->b_next = NULL;
15141 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15142 			    &ll_multicast, &dst))
15143 				continue;
15144 		}
15145 
15146 		if (ire == NULL) {
15147 			ire = ire_cache_lookup(dst, ALL_ZONES,
15148 			    MBLK_GETLABEL(mp), ipst);
15149 		}
15150 
15151 		if (ire == NULL) {
15152 			/*
15153 			 * No IRE for this destination, so it can't be for us.
15154 			 * Unless we are forwarding, drop the packet.
15155 			 * We have to let source routed packets through
15156 			 * since we don't yet know if they are 'ping -l'
15157 			 * packets i.e. if they will go out over the
15158 			 * same interface as they came in on.
15159 			 */
15160 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15161 			if (ire == NULL)
15162 				continue;
15163 		}
15164 
15165 		/*
15166 		 * Broadcast IRE may indicate either broadcast or
15167 		 * multicast packet
15168 		 */
15169 		if (ire->ire_type == IRE_BROADCAST) {
15170 			/*
15171 			 * Skip broadcast checks if packet is UDP multicast;
15172 			 * we'd rather not enter ip_rput_process_broadcast()
15173 			 * unless the packet is broadcast for real, since
15174 			 * that routine is a no-op for multicast.
15175 			 */
15176 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15177 			    !CLASSD(ipha->ipha_dst)) {
15178 				ire = ip_rput_process_broadcast(&q, mp,
15179 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15180 				    ll_multicast);
15181 				if (ire == NULL)
15182 					continue;
15183 			}
15184 		} else if (ire->ire_stq != NULL) {
15185 			/* fowarding? */
15186 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15187 			    ll_multicast);
15188 			/* ip_rput_process_forward consumed the packet */
15189 			continue;
15190 		}
15191 
15192 local:
15193 		/*
15194 		 * If the queue in the ire is different to the ingress queue
15195 		 * then we need to check to see if we can accept the packet.
15196 		 * Note that for multicast packets and broadcast packets sent
15197 		 * to a broadcast address which is shared between multiple
15198 		 * interfaces we should not do this since we just got a random
15199 		 * broadcast ire.
15200 		 */
15201 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15202 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15203 			    ill)) == NULL) {
15204 				/* Drop packet */
15205 				BUMP_MIB(ill->ill_ip_mib,
15206 				    ipIfStatsForwProhibits);
15207 				freemsg(mp);
15208 				continue;
15209 			}
15210 			if (ire->ire_rfq != NULL)
15211 				q = ire->ire_rfq;
15212 		}
15213 
15214 		switch (ipha->ipha_protocol) {
15215 		case IPPROTO_TCP:
15216 			ASSERT(first_mp == mp);
15217 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15218 			    mp, 0, q, ip_ring)) != NULL) {
15219 				if (curr_sqp == NULL) {
15220 					curr_sqp = GET_SQUEUE(mp);
15221 					ASSERT(cnt == 0);
15222 					cnt++;
15223 					head = tail = mp;
15224 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15225 					ASSERT(tail != NULL);
15226 					cnt++;
15227 					tail->b_next = mp;
15228 					tail = mp;
15229 				} else {
15230 					/*
15231 					 * A different squeue. Send the
15232 					 * chain for the previous squeue on
15233 					 * its way. This shouldn't happen
15234 					 * often unless interrupt binding
15235 					 * changes.
15236 					 */
15237 					IP_STAT(ipst, ip_input_multi_squeue);
15238 					squeue_enter_chain(curr_sqp, head,
15239 					    tail, cnt, SQTAG_IP_INPUT);
15240 					curr_sqp = GET_SQUEUE(mp);
15241 					head = mp;
15242 					tail = mp;
15243 					cnt = 1;
15244 				}
15245 			}
15246 			continue;
15247 		case IPPROTO_UDP:
15248 			ASSERT(first_mp == mp);
15249 			ip_udp_input(q, mp, ipha, ire, ill);
15250 			continue;
15251 		case IPPROTO_SCTP:
15252 			ASSERT(first_mp == mp);
15253 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15254 			    q, dst);
15255 			/* ire has been released by ip_sctp_input */
15256 			ire = NULL;
15257 			continue;
15258 		default:
15259 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15260 			continue;
15261 		}
15262 	}
15263 
15264 	if (ire != NULL)
15265 		ire_refrele(ire);
15266 
15267 	if (head != NULL)
15268 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15269 
15270 	/*
15271 	 * This code is there just to make netperf/ttcp look good.
15272 	 *
15273 	 * Its possible that after being in polling mode (and having cleared
15274 	 * the backlog), squeues have turned the interrupt frequency higher
15275 	 * to improve latency at the expense of more CPU utilization (less
15276 	 * packets per interrupts or more number of interrupts). Workloads
15277 	 * like ttcp/netperf do manage to tickle polling once in a while
15278 	 * but for the remaining time, stay in higher interrupt mode since
15279 	 * their packet arrival rate is pretty uniform and this shows up
15280 	 * as higher CPU utilization. Since people care about CPU utilization
15281 	 * while running netperf/ttcp, turn the interrupt frequency back to
15282 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15283 	 */
15284 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15285 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15286 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15287 			ip_ring->rr_blank(ip_ring->rr_handle,
15288 			    ip_ring->rr_normal_blank_time,
15289 			    ip_ring->rr_normal_pkt_cnt);
15290 		}
15291 		}
15292 
15293 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15294 	    "ip_input_end: q %p (%S)", q, "end");
15295 #undef  rptr
15296 }
15297 
15298 static void
15299 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15300     t_uscalar_t err)
15301 {
15302 	if (dl_err == DL_SYSERR) {
15303 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15304 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15305 		    ill->ill_name, dlpi_prim_str(prim), err);
15306 		return;
15307 	}
15308 
15309 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15310 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15311 	    dlpi_err_str(dl_err));
15312 }
15313 
15314 /*
15315  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15316  * than DL_UNITDATA_IND messages. If we need to process this message
15317  * exclusively, we call qwriter_ip, in which case we also need to call
15318  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15319  */
15320 void
15321 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15322 {
15323 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15324 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15325 	ill_t		*ill = (ill_t *)q->q_ptr;
15326 	boolean_t	pending;
15327 
15328 	ip1dbg(("ip_rput_dlpi"));
15329 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15330 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15331 		    "%s (0x%x), unix %u\n", ill->ill_name,
15332 		    dlpi_prim_str(dlea->dl_error_primitive),
15333 		    dlea->dl_error_primitive,
15334 		    dlpi_err_str(dlea->dl_errno),
15335 		    dlea->dl_errno,
15336 		    dlea->dl_unix_errno));
15337 	}
15338 
15339 	/*
15340 	 * If we received an ACK but didn't send a request for it, then it
15341 	 * can't be part of any pending operation; discard up-front.
15342 	 */
15343 	switch (dloa->dl_primitive) {
15344 	case DL_NOTIFY_IND:
15345 		pending = B_TRUE;
15346 		break;
15347 	case DL_ERROR_ACK:
15348 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15349 		break;
15350 	case DL_OK_ACK:
15351 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15352 		break;
15353 	case DL_INFO_ACK:
15354 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15355 		break;
15356 	case DL_BIND_ACK:
15357 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15358 		break;
15359 	case DL_PHYS_ADDR_ACK:
15360 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15361 		break;
15362 	case DL_NOTIFY_ACK:
15363 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15364 		break;
15365 	case DL_CONTROL_ACK:
15366 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15367 		break;
15368 	case DL_CAPABILITY_ACK:
15369 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15370 		break;
15371 	default:
15372 		/* Not a DLPI message we support or were expecting */
15373 		freemsg(mp);
15374 		return;
15375 	}
15376 
15377 	if (!pending) {
15378 		freemsg(mp);
15379 		return;
15380 	}
15381 
15382 	switch (dloa->dl_primitive) {
15383 	case DL_ERROR_ACK:
15384 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15385 			mutex_enter(&ill->ill_lock);
15386 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15387 			cv_signal(&ill->ill_cv);
15388 			mutex_exit(&ill->ill_lock);
15389 		}
15390 		break;
15391 
15392 	case DL_OK_ACK:
15393 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15394 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15395 		switch (dloa->dl_correct_primitive) {
15396 		case DL_UNBIND_REQ:
15397 			mutex_enter(&ill->ill_lock);
15398 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15399 			cv_signal(&ill->ill_cv);
15400 			mutex_exit(&ill->ill_lock);
15401 			break;
15402 
15403 		case DL_ENABMULTI_REQ:
15404 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15405 				ill->ill_dlpi_multicast_state = IDS_OK;
15406 			break;
15407 		}
15408 		break;
15409 	default:
15410 		break;
15411 	}
15412 
15413 	/*
15414 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15415 	 * and we need to become writer to continue to process it. If it's not
15416 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15417 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15418 	 * some work as part of the current exclusive operation that actually
15419 	 * is not part of it -- which is wrong, but better than the
15420 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15421 	 * should track which DLPI requests have ACKs that we wait on
15422 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15423 	 *
15424 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15425 	 * Since this is on the ill stream we unconditionally bump up the
15426 	 * refcount without doing ILL_CAN_LOOKUP().
15427 	 */
15428 	ill_refhold(ill);
15429 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15430 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15431 	else
15432 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15433 }
15434 
15435 /*
15436  * Handling of DLPI messages that require exclusive access to the ipsq.
15437  *
15438  * Need to do ill_pending_mp_release on ioctl completion, which could
15439  * happen here. (along with mi_copy_done)
15440  */
15441 /* ARGSUSED */
15442 static void
15443 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15444 {
15445 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15446 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15447 	int		err = 0;
15448 	ill_t		*ill;
15449 	ipif_t		*ipif = NULL;
15450 	mblk_t		*mp1 = NULL;
15451 	conn_t		*connp = NULL;
15452 	t_uscalar_t	paddrreq;
15453 	mblk_t		*mp_hw;
15454 	boolean_t	success;
15455 	boolean_t	ioctl_aborted = B_FALSE;
15456 	boolean_t	log = B_TRUE;
15457 	hook_nic_event_t	*info;
15458 	ip_stack_t		*ipst;
15459 
15460 	ip1dbg(("ip_rput_dlpi_writer .."));
15461 	ill = (ill_t *)q->q_ptr;
15462 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15463 
15464 	ASSERT(IAM_WRITER_ILL(ill));
15465 
15466 	ipst = ill->ill_ipst;
15467 
15468 	/*
15469 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15470 	 * both are null or non-null. However we can assert that only
15471 	 * after grabbing the ipsq_lock. So we don't make any assertion
15472 	 * here and in other places in the code.
15473 	 */
15474 	ipif = ipsq->ipsq_pending_ipif;
15475 	/*
15476 	 * The current ioctl could have been aborted by the user and a new
15477 	 * ioctl to bring up another ill could have started. We could still
15478 	 * get a response from the driver later.
15479 	 */
15480 	if (ipif != NULL && ipif->ipif_ill != ill)
15481 		ioctl_aborted = B_TRUE;
15482 
15483 	switch (dloa->dl_primitive) {
15484 	case DL_ERROR_ACK:
15485 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15486 		    dlpi_prim_str(dlea->dl_error_primitive)));
15487 
15488 		switch (dlea->dl_error_primitive) {
15489 		case DL_PROMISCON_REQ:
15490 		case DL_PROMISCOFF_REQ:
15491 		case DL_DISABMULTI_REQ:
15492 		case DL_UNBIND_REQ:
15493 		case DL_ATTACH_REQ:
15494 		case DL_INFO_REQ:
15495 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15496 			break;
15497 		case DL_NOTIFY_REQ:
15498 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15499 			log = B_FALSE;
15500 			break;
15501 		case DL_PHYS_ADDR_REQ:
15502 			/*
15503 			 * For IPv6 only, there are two additional
15504 			 * phys_addr_req's sent to the driver to get the
15505 			 * IPv6 token and lla. This allows IP to acquire
15506 			 * the hardware address format for a given interface
15507 			 * without having built in knowledge of the hardware
15508 			 * address. ill_phys_addr_pend keeps track of the last
15509 			 * DL_PAR sent so we know which response we are
15510 			 * dealing with. ill_dlpi_done will update
15511 			 * ill_phys_addr_pend when it sends the next req.
15512 			 * We don't complete the IOCTL until all three DL_PARs
15513 			 * have been attempted, so set *_len to 0 and break.
15514 			 */
15515 			paddrreq = ill->ill_phys_addr_pend;
15516 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15517 			if (paddrreq == DL_IPV6_TOKEN) {
15518 				ill->ill_token_length = 0;
15519 				log = B_FALSE;
15520 				break;
15521 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15522 				ill->ill_nd_lla_len = 0;
15523 				log = B_FALSE;
15524 				break;
15525 			}
15526 			/*
15527 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15528 			 * We presumably have an IOCTL hanging out waiting
15529 			 * for completion. Find it and complete the IOCTL
15530 			 * with the error noted.
15531 			 * However, ill_dl_phys was called on an ill queue
15532 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15533 			 * set. But the ioctl is known to be pending on ill_wq.
15534 			 */
15535 			if (!ill->ill_ifname_pending)
15536 				break;
15537 			ill->ill_ifname_pending = 0;
15538 			if (!ioctl_aborted)
15539 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15540 			if (mp1 != NULL) {
15541 				/*
15542 				 * This operation (SIOCSLIFNAME) must have
15543 				 * happened on the ill. Assert there is no conn
15544 				 */
15545 				ASSERT(connp == NULL);
15546 				q = ill->ill_wq;
15547 			}
15548 			break;
15549 		case DL_BIND_REQ:
15550 			ill_dlpi_done(ill, DL_BIND_REQ);
15551 			if (ill->ill_ifname_pending)
15552 				break;
15553 			/*
15554 			 * Something went wrong with the bind.  We presumably
15555 			 * have an IOCTL hanging out waiting for completion.
15556 			 * Find it, take down the interface that was coming
15557 			 * up, and complete the IOCTL with the error noted.
15558 			 */
15559 			if (!ioctl_aborted)
15560 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15561 			if (mp1 != NULL) {
15562 				/*
15563 				 * This operation (SIOCSLIFFLAGS) must have
15564 				 * happened from a conn.
15565 				 */
15566 				ASSERT(connp != NULL);
15567 				q = CONNP_TO_WQ(connp);
15568 				if (ill->ill_move_in_progress) {
15569 					ILL_CLEAR_MOVE(ill);
15570 				}
15571 				(void) ipif_down(ipif, NULL, NULL);
15572 				/* error is set below the switch */
15573 			}
15574 			break;
15575 		case DL_ENABMULTI_REQ:
15576 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15577 
15578 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15579 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15580 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15581 				ipif_t *ipif;
15582 
15583 				printf("ip: joining multicasts failed (%d)"
15584 				    " on %s - will use link layer "
15585 				    "broadcasts for multicast\n",
15586 				    dlea->dl_errno, ill->ill_name);
15587 
15588 				/*
15589 				 * Set up the multicast mapping alone.
15590 				 * writer, so ok to access ill->ill_ipif
15591 				 * without any lock.
15592 				 */
15593 				ipif = ill->ill_ipif;
15594 				mutex_enter(&ill->ill_phyint->phyint_lock);
15595 				ill->ill_phyint->phyint_flags |=
15596 				    PHYI_MULTI_BCAST;
15597 				mutex_exit(&ill->ill_phyint->phyint_lock);
15598 
15599 				if (!ill->ill_isv6) {
15600 					(void) ipif_arp_setup_multicast(ipif,
15601 					    NULL);
15602 				} else {
15603 					(void) ipif_ndp_setup_multicast(ipif,
15604 					    NULL);
15605 				}
15606 			}
15607 			freemsg(mp);	/* Don't want to pass this up */
15608 			return;
15609 
15610 		case DL_CAPABILITY_REQ:
15611 		case DL_CONTROL_REQ:
15612 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15613 			ill->ill_dlpi_capab_state = IDS_FAILED;
15614 			freemsg(mp);
15615 			return;
15616 		}
15617 		/*
15618 		 * Note the error for IOCTL completion (mp1 is set when
15619 		 * ready to complete ioctl). If ill_ifname_pending_err is
15620 		 * set, an error occured during plumbing (ill_ifname_pending),
15621 		 * so we want to report that error.
15622 		 *
15623 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15624 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15625 		 * expected to get errack'd if the driver doesn't support
15626 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15627 		 * if these error conditions are encountered.
15628 		 */
15629 		if (mp1 != NULL) {
15630 			if (ill->ill_ifname_pending_err != 0)  {
15631 				err = ill->ill_ifname_pending_err;
15632 				ill->ill_ifname_pending_err = 0;
15633 			} else {
15634 				err = dlea->dl_unix_errno ?
15635 				    dlea->dl_unix_errno : ENXIO;
15636 			}
15637 		/*
15638 		 * If we're plumbing an interface and an error hasn't already
15639 		 * been saved, set ill_ifname_pending_err to the error passed
15640 		 * up. Ignore the error if log is B_FALSE (see comment above).
15641 		 */
15642 		} else if (log && ill->ill_ifname_pending &&
15643 		    ill->ill_ifname_pending_err == 0) {
15644 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15645 			    dlea->dl_unix_errno : ENXIO;
15646 		}
15647 
15648 		if (log)
15649 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15650 			    dlea->dl_errno, dlea->dl_unix_errno);
15651 		break;
15652 	case DL_CAPABILITY_ACK: {
15653 		boolean_t reneg_flag = B_FALSE;
15654 		/* Call a routine to handle this one. */
15655 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15656 		/*
15657 		 * Check if the ACK is due to renegotiation case since we
15658 		 * will need to send a new CAPABILITY_REQ later.
15659 		 */
15660 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15661 			/* This is the ack for a renogiation case */
15662 			reneg_flag = B_TRUE;
15663 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15664 		}
15665 		ill_capability_ack(ill, mp);
15666 		if (reneg_flag)
15667 			ill_capability_probe(ill);
15668 		break;
15669 	}
15670 	case DL_CONTROL_ACK:
15671 		/* We treat all of these as "fire and forget" */
15672 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15673 		break;
15674 	case DL_INFO_ACK:
15675 		/* Call a routine to handle this one. */
15676 		ill_dlpi_done(ill, DL_INFO_REQ);
15677 		ip_ll_subnet_defaults(ill, mp);
15678 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15679 		return;
15680 	case DL_BIND_ACK:
15681 		/*
15682 		 * We should have an IOCTL waiting on this unless
15683 		 * sent by ill_dl_phys, in which case just return
15684 		 */
15685 		ill_dlpi_done(ill, DL_BIND_REQ);
15686 		if (ill->ill_ifname_pending)
15687 			break;
15688 
15689 		if (!ioctl_aborted)
15690 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15691 		if (mp1 == NULL)
15692 			break;
15693 		/*
15694 		 * Because mp1 was added by ill_dl_up(), and it always
15695 		 * passes a valid connp, connp must be valid here.
15696 		 */
15697 		ASSERT(connp != NULL);
15698 		q = CONNP_TO_WQ(connp);
15699 
15700 		/*
15701 		 * We are exclusive. So nothing can change even after
15702 		 * we get the pending mp. If need be we can put it back
15703 		 * and restart, as in calling ipif_arp_up()  below.
15704 		 */
15705 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15706 
15707 		mutex_enter(&ill->ill_lock);
15708 
15709 		ill->ill_dl_up = 1;
15710 
15711 		if ((info = ill->ill_nic_event_info) != NULL) {
15712 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15713 			    "attached for %s\n", info->hne_event,
15714 			    ill->ill_name));
15715 			if (info->hne_data != NULL)
15716 				kmem_free(info->hne_data, info->hne_datalen);
15717 			kmem_free(info, sizeof (hook_nic_event_t));
15718 		}
15719 
15720 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15721 		if (info != NULL) {
15722 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15723 			info->hne_lif = 0;
15724 			info->hne_event = NE_UP;
15725 			info->hne_data = NULL;
15726 			info->hne_datalen = 0;
15727 			info->hne_family = ill->ill_isv6 ?
15728 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15729 		} else
15730 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15731 			    "event information for %s (ENOMEM)\n",
15732 			    ill->ill_name));
15733 
15734 		ill->ill_nic_event_info = info;
15735 
15736 		mutex_exit(&ill->ill_lock);
15737 
15738 		/*
15739 		 * Now bring up the resolver; when that is complete, we'll
15740 		 * create IREs.  Note that we intentionally mirror what
15741 		 * ipif_up() would have done, because we got here by way of
15742 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15743 		 */
15744 		if (ill->ill_isv6) {
15745 			/*
15746 			 * v6 interfaces.
15747 			 * Unlike ARP which has to do another bind
15748 			 * and attach, once we get here we are
15749 			 * done with NDP. Except in the case of
15750 			 * ILLF_XRESOLV, in which case we send an
15751 			 * AR_INTERFACE_UP to the external resolver.
15752 			 * If all goes well, the ioctl will complete
15753 			 * in ip_rput(). If there's an error, we
15754 			 * complete it here.
15755 			 */
15756 			if ((err = ipif_ndp_up(ipif)) == 0) {
15757 				if (ill->ill_flags & ILLF_XRESOLV) {
15758 					mutex_enter(&connp->conn_lock);
15759 					mutex_enter(&ill->ill_lock);
15760 					success = ipsq_pending_mp_add(
15761 					    connp, ipif, q, mp1, 0);
15762 					mutex_exit(&ill->ill_lock);
15763 					mutex_exit(&connp->conn_lock);
15764 					if (success) {
15765 						err = ipif_resolver_up(ipif,
15766 						    Res_act_initial);
15767 						if (err == EINPROGRESS) {
15768 							freemsg(mp);
15769 							return;
15770 						}
15771 						ASSERT(err != 0);
15772 						mp1 = ipsq_pending_mp_get(ipsq,
15773 						    &connp);
15774 						ASSERT(mp1 != NULL);
15775 					} else {
15776 						/* conn has started closing */
15777 						err = EINTR;
15778 					}
15779 				} else { /* Non XRESOLV interface */
15780 					(void) ipif_resolver_up(ipif,
15781 					    Res_act_initial);
15782 					err = ipif_up_done_v6(ipif);
15783 				}
15784 			}
15785 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15786 			/*
15787 			 * ARP and other v4 external resolvers.
15788 			 * Leave the pending mblk intact so that
15789 			 * the ioctl completes in ip_rput().
15790 			 */
15791 			mutex_enter(&connp->conn_lock);
15792 			mutex_enter(&ill->ill_lock);
15793 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15794 			mutex_exit(&ill->ill_lock);
15795 			mutex_exit(&connp->conn_lock);
15796 			if (success) {
15797 				err = ipif_resolver_up(ipif, Res_act_initial);
15798 				if (err == EINPROGRESS) {
15799 					freemsg(mp);
15800 					return;
15801 				}
15802 				ASSERT(err != 0);
15803 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15804 			} else {
15805 				/* The conn has started closing */
15806 				err = EINTR;
15807 			}
15808 		} else {
15809 			/*
15810 			 * This one is complete. Reply to pending ioctl.
15811 			 */
15812 			(void) ipif_resolver_up(ipif, Res_act_initial);
15813 			err = ipif_up_done(ipif);
15814 		}
15815 
15816 		if ((err == 0) && (ill->ill_up_ipifs)) {
15817 			err = ill_up_ipifs(ill, q, mp1);
15818 			if (err == EINPROGRESS) {
15819 				freemsg(mp);
15820 				return;
15821 			}
15822 		}
15823 
15824 		if (ill->ill_up_ipifs) {
15825 			ill_group_cleanup(ill);
15826 		}
15827 
15828 		break;
15829 	case DL_NOTIFY_IND: {
15830 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15831 		ire_t *ire;
15832 		boolean_t need_ire_walk_v4 = B_FALSE;
15833 		boolean_t need_ire_walk_v6 = B_FALSE;
15834 
15835 		switch (notify->dl_notification) {
15836 		case DL_NOTE_PHYS_ADDR:
15837 			err = ill_set_phys_addr(ill, mp);
15838 			break;
15839 
15840 		case DL_NOTE_FASTPATH_FLUSH:
15841 			ill_fastpath_flush(ill);
15842 			break;
15843 
15844 		case DL_NOTE_SDU_SIZE:
15845 			/*
15846 			 * Change the MTU size of the interface, of all
15847 			 * attached ipif's, and of all relevant ire's.  The
15848 			 * new value's a uint32_t at notify->dl_data.
15849 			 * Mtu change Vs. new ire creation - protocol below.
15850 			 *
15851 			 * a Mark the ipif as IPIF_CHANGING.
15852 			 * b Set the new mtu in the ipif.
15853 			 * c Change the ire_max_frag on all affected ires
15854 			 * d Unmark the IPIF_CHANGING
15855 			 *
15856 			 * To see how the protocol works, assume an interface
15857 			 * route is also being added simultaneously by
15858 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15859 			 * the ire. If the ire is created before step a,
15860 			 * it will be cleaned up by step c. If the ire is
15861 			 * created after step d, it will see the new value of
15862 			 * ipif_mtu. Any attempt to create the ire between
15863 			 * steps a to d will fail because of the IPIF_CHANGING
15864 			 * flag. Note that ire_create() is passed a pointer to
15865 			 * the ipif_mtu, and not the value. During ire_add
15866 			 * under the bucket lock, the ire_max_frag of the
15867 			 * new ire being created is set from the ipif/ire from
15868 			 * which it is being derived.
15869 			 */
15870 			mutex_enter(&ill->ill_lock);
15871 			ill->ill_max_frag = (uint_t)notify->dl_data;
15872 
15873 			/*
15874 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15875 			 * leave it alone
15876 			 */
15877 			if (ill->ill_mtu_userspecified) {
15878 				mutex_exit(&ill->ill_lock);
15879 				break;
15880 			}
15881 			ill->ill_max_mtu = ill->ill_max_frag;
15882 			if (ill->ill_isv6) {
15883 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15884 					ill->ill_max_mtu = IPV6_MIN_MTU;
15885 			} else {
15886 				if (ill->ill_max_mtu < IP_MIN_MTU)
15887 					ill->ill_max_mtu = IP_MIN_MTU;
15888 			}
15889 			for (ipif = ill->ill_ipif; ipif != NULL;
15890 			    ipif = ipif->ipif_next) {
15891 				/*
15892 				 * Don't override the mtu if the user
15893 				 * has explicitly set it.
15894 				 */
15895 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15896 					continue;
15897 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15898 				if (ipif->ipif_isv6)
15899 					ire = ipif_to_ire_v6(ipif);
15900 				else
15901 					ire = ipif_to_ire(ipif);
15902 				if (ire != NULL) {
15903 					ire->ire_max_frag = ipif->ipif_mtu;
15904 					ire_refrele(ire);
15905 				}
15906 				if (ipif->ipif_flags & IPIF_UP) {
15907 					if (ill->ill_isv6)
15908 						need_ire_walk_v6 = B_TRUE;
15909 					else
15910 						need_ire_walk_v4 = B_TRUE;
15911 				}
15912 			}
15913 			mutex_exit(&ill->ill_lock);
15914 			if (need_ire_walk_v4)
15915 				ire_walk_v4(ill_mtu_change, (char *)ill,
15916 				    ALL_ZONES, ipst);
15917 			if (need_ire_walk_v6)
15918 				ire_walk_v6(ill_mtu_change, (char *)ill,
15919 				    ALL_ZONES, ipst);
15920 			break;
15921 		case DL_NOTE_LINK_UP:
15922 		case DL_NOTE_LINK_DOWN: {
15923 			/*
15924 			 * We are writer. ill / phyint / ipsq assocs stable.
15925 			 * The RUNNING flag reflects the state of the link.
15926 			 */
15927 			phyint_t *phyint = ill->ill_phyint;
15928 			uint64_t new_phyint_flags;
15929 			boolean_t changed = B_FALSE;
15930 			boolean_t went_up;
15931 
15932 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15933 			mutex_enter(&phyint->phyint_lock);
15934 			new_phyint_flags = went_up ?
15935 			    phyint->phyint_flags | PHYI_RUNNING :
15936 			    phyint->phyint_flags & ~PHYI_RUNNING;
15937 			if (new_phyint_flags != phyint->phyint_flags) {
15938 				phyint->phyint_flags = new_phyint_flags;
15939 				changed = B_TRUE;
15940 			}
15941 			mutex_exit(&phyint->phyint_lock);
15942 			/*
15943 			 * ill_restart_dad handles the DAD restart and routing
15944 			 * socket notification logic.
15945 			 */
15946 			if (changed) {
15947 				ill_restart_dad(phyint->phyint_illv4, went_up);
15948 				ill_restart_dad(phyint->phyint_illv6, went_up);
15949 			}
15950 			break;
15951 		}
15952 		case DL_NOTE_PROMISC_ON_PHYS:
15953 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15954 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15955 			mutex_enter(&ill->ill_lock);
15956 			ill->ill_promisc_on_phys = B_TRUE;
15957 			mutex_exit(&ill->ill_lock);
15958 			break;
15959 		case DL_NOTE_PROMISC_OFF_PHYS:
15960 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15961 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15962 			mutex_enter(&ill->ill_lock);
15963 			ill->ill_promisc_on_phys = B_FALSE;
15964 			mutex_exit(&ill->ill_lock);
15965 			break;
15966 		case DL_NOTE_CAPAB_RENEG:
15967 			/*
15968 			 * Something changed on the driver side.
15969 			 * It wants us to renegotiate the capabilities
15970 			 * on this ill. The most likely cause is the
15971 			 * aggregation interface under us where a
15972 			 * port got added or went away.
15973 			 *
15974 			 * We reset the capabilities and set the
15975 			 * state to IDS_RENG so that when the ack
15976 			 * comes back, we can start the
15977 			 * renegotiation process.
15978 			 */
15979 			ill_capability_reset(ill);
15980 			ill->ill_dlpi_capab_state = IDS_RENEG;
15981 			break;
15982 		default:
15983 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15984 			    "type 0x%x for DL_NOTIFY_IND\n",
15985 			    notify->dl_notification));
15986 			break;
15987 		}
15988 
15989 		/*
15990 		 * As this is an asynchronous operation, we
15991 		 * should not call ill_dlpi_done
15992 		 */
15993 		break;
15994 	}
15995 	case DL_NOTIFY_ACK: {
15996 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15997 
15998 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15999 			ill->ill_note_link = 1;
16000 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16001 		break;
16002 	}
16003 	case DL_PHYS_ADDR_ACK: {
16004 		/*
16005 		 * As part of plumbing the interface via SIOCSLIFNAME,
16006 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16007 		 * whose answers we receive here.  As each answer is received,
16008 		 * we call ill_dlpi_done() to dispatch the next request as
16009 		 * we're processing the current one.  Once all answers have
16010 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16011 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16012 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16013 		 * available, but we know the ioctl is pending on ill_wq.)
16014 		 */
16015 		uint_t paddrlen, paddroff;
16016 
16017 		paddrreq = ill->ill_phys_addr_pend;
16018 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16019 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16020 
16021 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16022 		if (paddrreq == DL_IPV6_TOKEN) {
16023 			/*
16024 			 * bcopy to low-order bits of ill_token
16025 			 *
16026 			 * XXX Temporary hack - currently, all known tokens
16027 			 * are 64 bits, so I'll cheat for the moment.
16028 			 */
16029 			bcopy(mp->b_rptr + paddroff,
16030 			    &ill->ill_token.s6_addr32[2], paddrlen);
16031 			ill->ill_token_length = paddrlen;
16032 			break;
16033 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16034 			ASSERT(ill->ill_nd_lla_mp == NULL);
16035 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16036 			mp = NULL;
16037 			break;
16038 		}
16039 
16040 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16041 		ASSERT(ill->ill_phys_addr_mp == NULL);
16042 		if (!ill->ill_ifname_pending)
16043 			break;
16044 		ill->ill_ifname_pending = 0;
16045 		if (!ioctl_aborted)
16046 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16047 		if (mp1 != NULL) {
16048 			ASSERT(connp == NULL);
16049 			q = ill->ill_wq;
16050 		}
16051 		/*
16052 		 * If any error acks received during the plumbing sequence,
16053 		 * ill_ifname_pending_err will be set. Break out and send up
16054 		 * the error to the pending ioctl.
16055 		 */
16056 		if (ill->ill_ifname_pending_err != 0) {
16057 			err = ill->ill_ifname_pending_err;
16058 			ill->ill_ifname_pending_err = 0;
16059 			break;
16060 		}
16061 
16062 		ill->ill_phys_addr_mp = mp;
16063 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16064 		mp = NULL;
16065 
16066 		/*
16067 		 * If paddrlen is zero, the DLPI provider doesn't support
16068 		 * physical addresses.  The other two tests were historical
16069 		 * workarounds for bugs in our former PPP implementation, but
16070 		 * now other things have grown dependencies on them -- e.g.,
16071 		 * the tun module specifies a dl_addr_length of zero in its
16072 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16073 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16074 		 * but only after careful testing ensures that all dependent
16075 		 * broken DLPI providers have been fixed.
16076 		 */
16077 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16078 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16079 			ill->ill_phys_addr = NULL;
16080 		} else if (paddrlen != ill->ill_phys_addr_length) {
16081 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16082 			    paddrlen, ill->ill_phys_addr_length));
16083 			err = EINVAL;
16084 			break;
16085 		}
16086 
16087 		if (ill->ill_nd_lla_mp == NULL) {
16088 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16089 				err = ENOMEM;
16090 				break;
16091 			}
16092 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16093 		}
16094 
16095 		/*
16096 		 * Set the interface token.  If the zeroth interface address
16097 		 * is unspecified, then set it to the link local address.
16098 		 */
16099 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16100 			(void) ill_setdefaulttoken(ill);
16101 
16102 		ASSERT(ill->ill_ipif->ipif_id == 0);
16103 		if (ipif != NULL &&
16104 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16105 			(void) ipif_setlinklocal(ipif);
16106 		}
16107 		break;
16108 	}
16109 	case DL_OK_ACK:
16110 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16111 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16112 		    dloa->dl_correct_primitive));
16113 		switch (dloa->dl_correct_primitive) {
16114 		case DL_PROMISCON_REQ:
16115 		case DL_PROMISCOFF_REQ:
16116 		case DL_ENABMULTI_REQ:
16117 		case DL_DISABMULTI_REQ:
16118 		case DL_UNBIND_REQ:
16119 		case DL_ATTACH_REQ:
16120 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16121 			break;
16122 		}
16123 		break;
16124 	default:
16125 		break;
16126 	}
16127 
16128 	freemsg(mp);
16129 	if (mp1 != NULL) {
16130 		/*
16131 		 * The operation must complete without EINPROGRESS
16132 		 * since ipsq_pending_mp_get() has removed the mblk
16133 		 * from ipsq_pending_mp.  Otherwise, the operation
16134 		 * will be stuck forever in the ipsq.
16135 		 */
16136 		ASSERT(err != EINPROGRESS);
16137 
16138 		switch (ipsq->ipsq_current_ioctl) {
16139 		case 0:
16140 			ipsq_current_finish(ipsq);
16141 			break;
16142 
16143 		case SIOCLIFADDIF:
16144 		case SIOCSLIFNAME:
16145 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16146 			break;
16147 
16148 		default:
16149 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16150 			break;
16151 		}
16152 	}
16153 }
16154 
16155 /*
16156  * ip_rput_other is called by ip_rput to handle messages modifying the global
16157  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16158  */
16159 /* ARGSUSED */
16160 void
16161 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16162 {
16163 	ill_t		*ill;
16164 	struct iocblk	*iocp;
16165 	mblk_t		*mp1;
16166 	conn_t		*connp = NULL;
16167 
16168 	ip1dbg(("ip_rput_other "));
16169 	ill = (ill_t *)q->q_ptr;
16170 	/*
16171 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16172 	 * in which case ipsq is NULL.
16173 	 */
16174 	if (ipsq != NULL) {
16175 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16176 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16177 	}
16178 
16179 	switch (mp->b_datap->db_type) {
16180 	case M_ERROR:
16181 	case M_HANGUP:
16182 		/*
16183 		 * The device has a problem.  We force the ILL down.  It can
16184 		 * be brought up again manually using SIOCSIFFLAGS (via
16185 		 * ifconfig or equivalent).
16186 		 */
16187 		ASSERT(ipsq != NULL);
16188 		if (mp->b_rptr < mp->b_wptr)
16189 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16190 		if (ill->ill_error == 0)
16191 			ill->ill_error = ENXIO;
16192 		if (!ill_down_start(q, mp))
16193 			return;
16194 		ipif_all_down_tail(ipsq, q, mp, NULL);
16195 		break;
16196 	case M_IOCACK:
16197 		iocp = (struct iocblk *)mp->b_rptr;
16198 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16199 		switch (iocp->ioc_cmd) {
16200 		case SIOCSTUNPARAM:
16201 		case OSIOCSTUNPARAM:
16202 			ASSERT(ipsq != NULL);
16203 			/*
16204 			 * Finish socket ioctl passed through to tun.
16205 			 * We should have an IOCTL waiting on this.
16206 			 */
16207 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16208 			if (ill->ill_isv6) {
16209 				struct iftun_req *ta;
16210 
16211 				/*
16212 				 * if a source or destination is
16213 				 * being set, try and set the link
16214 				 * local address for the tunnel
16215 				 */
16216 				ta = (struct iftun_req *)mp->b_cont->
16217 				    b_cont->b_rptr;
16218 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16219 					ipif_set_tun_llink(ill, ta);
16220 				}
16221 
16222 			}
16223 			if (mp1 != NULL) {
16224 				/*
16225 				 * Now copy back the b_next/b_prev used by
16226 				 * mi code for the mi_copy* functions.
16227 				 * See ip_sioctl_tunparam() for the reason.
16228 				 * Also protect against missing b_cont.
16229 				 */
16230 				if (mp->b_cont != NULL) {
16231 					mp->b_cont->b_next =
16232 					    mp1->b_cont->b_next;
16233 					mp->b_cont->b_prev =
16234 					    mp1->b_cont->b_prev;
16235 				}
16236 				inet_freemsg(mp1);
16237 				ASSERT(connp != NULL);
16238 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16239 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16240 			} else {
16241 				ASSERT(connp == NULL);
16242 				putnext(q, mp);
16243 			}
16244 			break;
16245 		case SIOCGTUNPARAM:
16246 		case OSIOCGTUNPARAM:
16247 			/*
16248 			 * This is really M_IOCDATA from the tunnel driver.
16249 			 * convert back and complete the ioctl.
16250 			 * We should have an IOCTL waiting on this.
16251 			 */
16252 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16253 			if (mp1) {
16254 				/*
16255 				 * Now copy back the b_next/b_prev used by
16256 				 * mi code for the mi_copy* functions.
16257 				 * See ip_sioctl_tunparam() for the reason.
16258 				 * Also protect against missing b_cont.
16259 				 */
16260 				if (mp->b_cont != NULL) {
16261 					mp->b_cont->b_next =
16262 					    mp1->b_cont->b_next;
16263 					mp->b_cont->b_prev =
16264 					    mp1->b_cont->b_prev;
16265 				}
16266 				inet_freemsg(mp1);
16267 				if (iocp->ioc_error == 0)
16268 					mp->b_datap->db_type = M_IOCDATA;
16269 				ASSERT(connp != NULL);
16270 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16271 				    iocp->ioc_error, COPYOUT, NULL);
16272 			} else {
16273 				ASSERT(connp == NULL);
16274 				putnext(q, mp);
16275 			}
16276 			break;
16277 		default:
16278 			break;
16279 		}
16280 		break;
16281 	case M_IOCNAK:
16282 		iocp = (struct iocblk *)mp->b_rptr;
16283 
16284 		switch (iocp->ioc_cmd) {
16285 		int mode;
16286 
16287 		case DL_IOC_HDR_INFO:
16288 			/*
16289 			 * If this was the first attempt turn of the
16290 			 * fastpath probing.
16291 			 */
16292 			mutex_enter(&ill->ill_lock);
16293 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16294 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16295 				mutex_exit(&ill->ill_lock);
16296 				ill_fastpath_nack(ill);
16297 				ip1dbg(("ip_rput: DLPI fastpath off on "
16298 				    "interface %s\n",
16299 				    ill->ill_name));
16300 			} else {
16301 				mutex_exit(&ill->ill_lock);
16302 			}
16303 			freemsg(mp);
16304 			break;
16305 		case SIOCSTUNPARAM:
16306 		case OSIOCSTUNPARAM:
16307 			ASSERT(ipsq != NULL);
16308 			/*
16309 			 * Finish socket ioctl passed through to tun
16310 			 * We should have an IOCTL waiting on this.
16311 			 */
16312 			/* FALLTHRU */
16313 		case SIOCGTUNPARAM:
16314 		case OSIOCGTUNPARAM:
16315 			/*
16316 			 * This is really M_IOCDATA from the tunnel driver.
16317 			 * convert back and complete the ioctl.
16318 			 * We should have an IOCTL waiting on this.
16319 			 */
16320 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16321 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16322 				mp1 = ill_pending_mp_get(ill, &connp,
16323 				    iocp->ioc_id);
16324 				mode = COPYOUT;
16325 				ipsq = NULL;
16326 			} else {
16327 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16328 				mode = NO_COPYOUT;
16329 			}
16330 			if (mp1 != NULL) {
16331 				/*
16332 				 * Now copy back the b_next/b_prev used by
16333 				 * mi code for the mi_copy* functions.
16334 				 * See ip_sioctl_tunparam() for the reason.
16335 				 * Also protect against missing b_cont.
16336 				 */
16337 				if (mp->b_cont != NULL) {
16338 					mp->b_cont->b_next =
16339 					    mp1->b_cont->b_next;
16340 					mp->b_cont->b_prev =
16341 					    mp1->b_cont->b_prev;
16342 				}
16343 				inet_freemsg(mp1);
16344 				if (iocp->ioc_error == 0)
16345 					iocp->ioc_error = EINVAL;
16346 				ASSERT(connp != NULL);
16347 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16348 				    iocp->ioc_error, mode, ipsq);
16349 			} else {
16350 				ASSERT(connp == NULL);
16351 				putnext(q, mp);
16352 			}
16353 			break;
16354 		default:
16355 			break;
16356 		}
16357 	default:
16358 		break;
16359 	}
16360 }
16361 
16362 /*
16363  * NOTE : This function does not ire_refrele the ire argument passed in.
16364  *
16365  * IPQoS notes
16366  * IP policy is invoked twice for a forwarded packet, once on the read side
16367  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16368  * enabled. An additional parameter, in_ill, has been added for this purpose.
16369  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16370  * because ip_mroute drops this information.
16371  *
16372  */
16373 void
16374 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16375 {
16376 	uint32_t	old_pkt_len;
16377 	uint32_t	pkt_len;
16378 	queue_t	*q;
16379 	uint32_t	sum;
16380 #define	rptr	((uchar_t *)ipha)
16381 	uint32_t	max_frag;
16382 	uint32_t	ill_index;
16383 	ill_t		*out_ill;
16384 	mib2_ipIfStatsEntry_t *mibptr;
16385 	ip_stack_t	*ipst = in_ill->ill_ipst;
16386 
16387 	/* Get the ill_index of the incoming ILL */
16388 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16389 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16390 
16391 	/* Initiate Read side IPPF processing */
16392 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16393 		ip_process(IPP_FWD_IN, &mp, ill_index);
16394 		if (mp == NULL) {
16395 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16396 			    "during IPPF processing\n"));
16397 			return;
16398 		}
16399 	}
16400 
16401 	/* Adjust the checksum to reflect the ttl decrement. */
16402 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16403 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16404 
16405 	if (ipha->ipha_ttl-- <= 1) {
16406 		if (ip_csum_hdr(ipha)) {
16407 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16408 			goto drop_pkt;
16409 		}
16410 		/*
16411 		 * Note: ire_stq this will be NULL for multicast
16412 		 * datagrams using the long path through arp (the IRE
16413 		 * is not an IRE_CACHE). This should not cause
16414 		 * problems since we don't generate ICMP errors for
16415 		 * multicast packets.
16416 		 */
16417 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16418 		q = ire->ire_stq;
16419 		if (q != NULL) {
16420 			/* Sent by forwarding path, and router is global zone */
16421 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16422 			    GLOBAL_ZONEID, ipst);
16423 		} else
16424 			freemsg(mp);
16425 		return;
16426 	}
16427 
16428 	/*
16429 	 * Don't forward if the interface is down
16430 	 */
16431 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16432 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16433 		ip2dbg(("ip_rput_forward:interface is down\n"));
16434 		goto drop_pkt;
16435 	}
16436 
16437 	/* Get the ill_index of the outgoing ILL */
16438 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16439 
16440 	out_ill = ire->ire_ipif->ipif_ill;
16441 
16442 	DTRACE_PROBE4(ip4__forwarding__start,
16443 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16444 
16445 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16446 	    ipst->ips_ipv4firewall_forwarding,
16447 	    in_ill, out_ill, ipha, mp, mp, ipst);
16448 
16449 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16450 
16451 	if (mp == NULL)
16452 		return;
16453 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16454 
16455 	if (is_system_labeled()) {
16456 		mblk_t *mp1;
16457 
16458 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16459 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16460 			goto drop_pkt;
16461 		}
16462 		/* Size may have changed */
16463 		mp = mp1;
16464 		ipha = (ipha_t *)mp->b_rptr;
16465 		pkt_len = ntohs(ipha->ipha_length);
16466 	}
16467 
16468 	/* Check if there are options to update */
16469 	if (!IS_SIMPLE_IPH(ipha)) {
16470 		if (ip_csum_hdr(ipha)) {
16471 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16472 			goto drop_pkt;
16473 		}
16474 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16475 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16476 			return;
16477 		}
16478 
16479 		ipha->ipha_hdr_checksum = 0;
16480 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16481 	}
16482 	max_frag = ire->ire_max_frag;
16483 	if (pkt_len > max_frag) {
16484 		/*
16485 		 * It needs fragging on its way out.  We haven't
16486 		 * verified the header checksum yet.  Since we
16487 		 * are going to put a surely good checksum in the
16488 		 * outgoing header, we have to make sure that it
16489 		 * was good coming in.
16490 		 */
16491 		if (ip_csum_hdr(ipha)) {
16492 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16493 			goto drop_pkt;
16494 		}
16495 		/* Initiate Write side IPPF processing */
16496 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16497 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16498 			if (mp == NULL) {
16499 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16500 				    " during IPPF processing\n"));
16501 				return;
16502 			}
16503 		}
16504 		/*
16505 		 * Handle labeled packet resizing.
16506 		 *
16507 		 * If we have added a label, inform ip_wput_frag() of its
16508 		 * effect on the MTU for ICMP messages.
16509 		 */
16510 		if (pkt_len > old_pkt_len) {
16511 			uint32_t secopt_size;
16512 
16513 			secopt_size = pkt_len - old_pkt_len;
16514 			if (secopt_size < max_frag)
16515 				max_frag -= secopt_size;
16516 		}
16517 
16518 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16519 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16520 		return;
16521 	}
16522 
16523 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16524 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16525 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16526 	    ipst->ips_ipv4firewall_physical_out,
16527 	    NULL, out_ill, ipha, mp, mp, ipst);
16528 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16529 	if (mp == NULL)
16530 		return;
16531 
16532 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16533 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16534 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16535 	/* ip_xmit_v4 always consumes the packet */
16536 	return;
16537 
16538 drop_pkt:;
16539 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16540 	freemsg(mp);
16541 #undef	rptr
16542 }
16543 
16544 void
16545 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16546 {
16547 	ire_t	*ire;
16548 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16549 
16550 	ASSERT(!ipif->ipif_isv6);
16551 	/*
16552 	 * Find an IRE which matches the destination and the outgoing
16553 	 * queue in the cache table. All we need is an IRE_CACHE which
16554 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16555 	 * then it is enough to have some IRE_CACHE in the group.
16556 	 */
16557 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16558 		dst = ipif->ipif_pp_dst_addr;
16559 
16560 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16561 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16562 	if (ire == NULL) {
16563 		/*
16564 		 * Mark this packet to make it be delivered to
16565 		 * ip_rput_forward after the new ire has been
16566 		 * created.
16567 		 */
16568 		mp->b_prev = NULL;
16569 		mp->b_next = mp;
16570 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16571 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16572 	} else {
16573 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16574 		IRE_REFRELE(ire);
16575 	}
16576 }
16577 
16578 /* Update any source route, record route or timestamp options */
16579 static int
16580 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16581 {
16582 	ipoptp_t	opts;
16583 	uchar_t		*opt;
16584 	uint8_t		optval;
16585 	uint8_t		optlen;
16586 	ipaddr_t	dst;
16587 	uint32_t	ts;
16588 	ire_t		*dst_ire = NULL;
16589 	ire_t		*tmp_ire = NULL;
16590 	timestruc_t	now;
16591 
16592 	ip2dbg(("ip_rput_forward_options\n"));
16593 	dst = ipha->ipha_dst;
16594 	for (optval = ipoptp_first(&opts, ipha);
16595 	    optval != IPOPT_EOL;
16596 	    optval = ipoptp_next(&opts)) {
16597 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16598 		opt = opts.ipoptp_cur;
16599 		optlen = opts.ipoptp_len;
16600 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16601 		    optval, opts.ipoptp_len));
16602 		switch (optval) {
16603 			uint32_t off;
16604 		case IPOPT_SSRR:
16605 		case IPOPT_LSRR:
16606 			/* Check if adminstratively disabled */
16607 			if (!ipst->ips_ip_forward_src_routed) {
16608 				if (ire->ire_stq != NULL) {
16609 					/*
16610 					 * Sent by forwarding path, and router
16611 					 * is global zone
16612 					 */
16613 					icmp_unreachable(ire->ire_stq, mp,
16614 					    ICMP_SOURCE_ROUTE_FAILED,
16615 					    GLOBAL_ZONEID, ipst);
16616 				} else {
16617 					ip0dbg(("ip_rput_forward_options: "
16618 					    "unable to send unreach\n"));
16619 					freemsg(mp);
16620 				}
16621 				return (-1);
16622 			}
16623 
16624 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16625 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16626 			if (dst_ire == NULL) {
16627 				/*
16628 				 * Must be partial since ip_rput_options
16629 				 * checked for strict.
16630 				 */
16631 				break;
16632 			}
16633 			off = opt[IPOPT_OFFSET];
16634 			off--;
16635 		redo_srr:
16636 			if (optlen < IP_ADDR_LEN ||
16637 			    off > optlen - IP_ADDR_LEN) {
16638 				/* End of source route */
16639 				ip1dbg((
16640 				    "ip_rput_forward_options: end of SR\n"));
16641 				ire_refrele(dst_ire);
16642 				break;
16643 			}
16644 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16645 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16646 			    IP_ADDR_LEN);
16647 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16648 			    ntohl(dst)));
16649 
16650 			/*
16651 			 * Check if our address is present more than
16652 			 * once as consecutive hops in source route.
16653 			 */
16654 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16655 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16656 			if (tmp_ire != NULL) {
16657 				ire_refrele(tmp_ire);
16658 				off += IP_ADDR_LEN;
16659 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16660 				goto redo_srr;
16661 			}
16662 			ipha->ipha_dst = dst;
16663 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16664 			ire_refrele(dst_ire);
16665 			break;
16666 		case IPOPT_RR:
16667 			off = opt[IPOPT_OFFSET];
16668 			off--;
16669 			if (optlen < IP_ADDR_LEN ||
16670 			    off > optlen - IP_ADDR_LEN) {
16671 				/* No more room - ignore */
16672 				ip1dbg((
16673 				    "ip_rput_forward_options: end of RR\n"));
16674 				break;
16675 			}
16676 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16677 			    IP_ADDR_LEN);
16678 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16679 			break;
16680 		case IPOPT_TS:
16681 			/* Insert timestamp if there is room */
16682 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16683 			case IPOPT_TS_TSONLY:
16684 				off = IPOPT_TS_TIMELEN;
16685 				break;
16686 			case IPOPT_TS_PRESPEC:
16687 			case IPOPT_TS_PRESPEC_RFC791:
16688 				/* Verify that the address matched */
16689 				off = opt[IPOPT_OFFSET] - 1;
16690 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16691 				dst_ire = ire_ctable_lookup(dst, 0,
16692 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16693 				    MATCH_IRE_TYPE, ipst);
16694 				if (dst_ire == NULL) {
16695 					/* Not for us */
16696 					break;
16697 				}
16698 				ire_refrele(dst_ire);
16699 				/* FALLTHRU */
16700 			case IPOPT_TS_TSANDADDR:
16701 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16702 				break;
16703 			default:
16704 				/*
16705 				 * ip_*put_options should have already
16706 				 * dropped this packet.
16707 				 */
16708 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16709 				    "unknown IT - bug in ip_rput_options?\n");
16710 				return (0);	/* Keep "lint" happy */
16711 			}
16712 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16713 				/* Increase overflow counter */
16714 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16715 				opt[IPOPT_POS_OV_FLG] =
16716 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16717 				    (off << 4));
16718 				break;
16719 			}
16720 			off = opt[IPOPT_OFFSET] - 1;
16721 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16722 			case IPOPT_TS_PRESPEC:
16723 			case IPOPT_TS_PRESPEC_RFC791:
16724 			case IPOPT_TS_TSANDADDR:
16725 				bcopy(&ire->ire_src_addr,
16726 				    (char *)opt + off, IP_ADDR_LEN);
16727 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16728 				/* FALLTHRU */
16729 			case IPOPT_TS_TSONLY:
16730 				off = opt[IPOPT_OFFSET] - 1;
16731 				/* Compute # of milliseconds since midnight */
16732 				gethrestime(&now);
16733 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16734 				    now.tv_nsec / (NANOSEC / MILLISEC);
16735 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16736 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16737 				break;
16738 			}
16739 			break;
16740 		}
16741 	}
16742 	return (0);
16743 }
16744 
16745 /*
16746  * This is called after processing at least one of AH/ESP headers.
16747  *
16748  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16749  * the actual, physical interface on which the packet was received,
16750  * but, when ip_strict_dst_multihoming is set to 1, could be the
16751  * interface which had the ipha_dst configured when the packet went
16752  * through ip_rput. The ill_index corresponding to the recv_ill
16753  * is saved in ipsec_in_rill_index
16754  *
16755  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16756  * cannot assume "ire" points to valid data for any IPv6 cases.
16757  */
16758 void
16759 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16760 {
16761 	mblk_t *mp;
16762 	ipaddr_t dst;
16763 	in6_addr_t *v6dstp;
16764 	ipha_t *ipha;
16765 	ip6_t *ip6h;
16766 	ipsec_in_t *ii;
16767 	boolean_t ill_need_rele = B_FALSE;
16768 	boolean_t rill_need_rele = B_FALSE;
16769 	boolean_t ire_need_rele = B_FALSE;
16770 	netstack_t	*ns;
16771 	ip_stack_t	*ipst;
16772 
16773 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16774 	ASSERT(ii->ipsec_in_ill_index != 0);
16775 	ns = ii->ipsec_in_ns;
16776 	ASSERT(ii->ipsec_in_ns != NULL);
16777 	ipst = ns->netstack_ip;
16778 
16779 	mp = ipsec_mp->b_cont;
16780 	ASSERT(mp != NULL);
16781 
16782 
16783 	if (ill == NULL) {
16784 		ASSERT(recv_ill == NULL);
16785 		/*
16786 		 * We need to get the original queue on which ip_rput_local
16787 		 * or ip_rput_data_v6 was called.
16788 		 */
16789 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16790 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16791 		ill_need_rele = B_TRUE;
16792 
16793 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16794 			recv_ill = ill_lookup_on_ifindex(
16795 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16796 			    NULL, NULL, NULL, NULL, ipst);
16797 			rill_need_rele = B_TRUE;
16798 		} else {
16799 			recv_ill = ill;
16800 		}
16801 
16802 		if ((ill == NULL) || (recv_ill == NULL)) {
16803 			ip0dbg(("ip_fanout_proto_again: interface "
16804 			    "disappeared\n"));
16805 			if (ill != NULL)
16806 				ill_refrele(ill);
16807 			if (recv_ill != NULL)
16808 				ill_refrele(recv_ill);
16809 			freemsg(ipsec_mp);
16810 			return;
16811 		}
16812 	}
16813 
16814 	ASSERT(ill != NULL && recv_ill != NULL);
16815 
16816 	if (mp->b_datap->db_type == M_CTL) {
16817 		/*
16818 		 * AH/ESP is returning the ICMP message after
16819 		 * removing their headers. Fanout again till
16820 		 * it gets to the right protocol.
16821 		 */
16822 		if (ii->ipsec_in_v4) {
16823 			icmph_t *icmph;
16824 			int iph_hdr_length;
16825 			int hdr_length;
16826 
16827 			ipha = (ipha_t *)mp->b_rptr;
16828 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16829 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16830 			ipha = (ipha_t *)&icmph[1];
16831 			hdr_length = IPH_HDR_LENGTH(ipha);
16832 			/*
16833 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16834 			 * Reset the type to M_DATA.
16835 			 */
16836 			mp->b_datap->db_type = M_DATA;
16837 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16838 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16839 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16840 		} else {
16841 			icmp6_t *icmp6;
16842 			int hdr_length;
16843 
16844 			ip6h = (ip6_t *)mp->b_rptr;
16845 			/* Don't call hdr_length_v6() unless you have to. */
16846 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16847 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16848 			else
16849 				hdr_length = IPV6_HDR_LEN;
16850 
16851 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16852 			/*
16853 			 * icmp_inbound_error_fanout_v6 may need to do
16854 			 * pullupmsg.  Reset the type to M_DATA.
16855 			 */
16856 			mp->b_datap->db_type = M_DATA;
16857 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16858 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16859 		}
16860 		if (ill_need_rele)
16861 			ill_refrele(ill);
16862 		if (rill_need_rele)
16863 			ill_refrele(recv_ill);
16864 		return;
16865 	}
16866 
16867 	if (ii->ipsec_in_v4) {
16868 		ipha = (ipha_t *)mp->b_rptr;
16869 		dst = ipha->ipha_dst;
16870 		if (CLASSD(dst)) {
16871 			/*
16872 			 * Multicast has to be delivered to all streams.
16873 			 */
16874 			dst = INADDR_BROADCAST;
16875 		}
16876 
16877 		if (ire == NULL) {
16878 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16879 			    MBLK_GETLABEL(mp), ipst);
16880 			if (ire == NULL) {
16881 				if (ill_need_rele)
16882 					ill_refrele(ill);
16883 				if (rill_need_rele)
16884 					ill_refrele(recv_ill);
16885 				ip1dbg(("ip_fanout_proto_again: "
16886 				    "IRE not found"));
16887 				freemsg(ipsec_mp);
16888 				return;
16889 			}
16890 			ire_need_rele = B_TRUE;
16891 		}
16892 
16893 		switch (ipha->ipha_protocol) {
16894 			case IPPROTO_UDP:
16895 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16896 				    recv_ill);
16897 				if (ire_need_rele)
16898 					ire_refrele(ire);
16899 				break;
16900 			case IPPROTO_TCP:
16901 				if (!ire_need_rele)
16902 					IRE_REFHOLD(ire);
16903 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16904 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16905 				IRE_REFRELE(ire);
16906 				if (mp != NULL)
16907 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16908 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16909 				break;
16910 			case IPPROTO_SCTP:
16911 				if (!ire_need_rele)
16912 					IRE_REFHOLD(ire);
16913 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16914 				    ipsec_mp, 0, ill->ill_rq, dst);
16915 				break;
16916 			default:
16917 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16918 				    recv_ill, B_FALSE);
16919 				if (ire_need_rele)
16920 					ire_refrele(ire);
16921 				break;
16922 		}
16923 	} else {
16924 		uint32_t rput_flags = 0;
16925 
16926 		ip6h = (ip6_t *)mp->b_rptr;
16927 		v6dstp = &ip6h->ip6_dst;
16928 		/*
16929 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16930 		 * address.
16931 		 *
16932 		 * Currently, we don't store that state in the IPSEC_IN
16933 		 * message, and we may need to.
16934 		 */
16935 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16936 		    IP6_IN_LLMCAST : 0);
16937 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16938 		    NULL, NULL);
16939 	}
16940 	if (ill_need_rele)
16941 		ill_refrele(ill);
16942 	if (rill_need_rele)
16943 		ill_refrele(recv_ill);
16944 }
16945 
16946 /*
16947  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16948  * returns 'true' if there are still fragments left on the queue, in
16949  * which case we restart the timer.
16950  */
16951 void
16952 ill_frag_timer(void *arg)
16953 {
16954 	ill_t	*ill = (ill_t *)arg;
16955 	boolean_t frag_pending;
16956 	ip_stack_t	*ipst = ill->ill_ipst;
16957 
16958 	mutex_enter(&ill->ill_lock);
16959 	ASSERT(!ill->ill_fragtimer_executing);
16960 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16961 		ill->ill_frag_timer_id = 0;
16962 		mutex_exit(&ill->ill_lock);
16963 		return;
16964 	}
16965 	ill->ill_fragtimer_executing = 1;
16966 	mutex_exit(&ill->ill_lock);
16967 
16968 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16969 
16970 	/*
16971 	 * Restart the timer, if we have fragments pending or if someone
16972 	 * wanted us to be scheduled again.
16973 	 */
16974 	mutex_enter(&ill->ill_lock);
16975 	ill->ill_fragtimer_executing = 0;
16976 	ill->ill_frag_timer_id = 0;
16977 	if (frag_pending || ill->ill_fragtimer_needrestart)
16978 		ill_frag_timer_start(ill);
16979 	mutex_exit(&ill->ill_lock);
16980 }
16981 
16982 void
16983 ill_frag_timer_start(ill_t *ill)
16984 {
16985 	ip_stack_t	*ipst = ill->ill_ipst;
16986 
16987 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16988 
16989 	/* If the ill is closing or opening don't proceed */
16990 	if (ill->ill_state_flags & ILL_CONDEMNED)
16991 		return;
16992 
16993 	if (ill->ill_fragtimer_executing) {
16994 		/*
16995 		 * ill_frag_timer is currently executing. Just record the
16996 		 * the fact that we want the timer to be restarted.
16997 		 * ill_frag_timer will post a timeout before it returns,
16998 		 * ensuring it will be called again.
16999 		 */
17000 		ill->ill_fragtimer_needrestart = 1;
17001 		return;
17002 	}
17003 
17004 	if (ill->ill_frag_timer_id == 0) {
17005 		/*
17006 		 * The timer is neither running nor is the timeout handler
17007 		 * executing. Post a timeout so that ill_frag_timer will be
17008 		 * called
17009 		 */
17010 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17011 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17012 		ill->ill_fragtimer_needrestart = 0;
17013 	}
17014 }
17015 
17016 /*
17017  * This routine is needed for loopback when forwarding multicasts.
17018  *
17019  * IPQoS Notes:
17020  * IPPF processing is done in fanout routines.
17021  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17022  * processing for IPsec packets is done when it comes back in clear.
17023  * NOTE : The callers of this function need to do the ire_refrele for the
17024  *	  ire that is being passed in.
17025  */
17026 void
17027 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17028     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17029 {
17030 	ill_t	*ill = (ill_t *)q->q_ptr;
17031 	uint32_t	sum;
17032 	uint32_t	u1;
17033 	uint32_t	u2;
17034 	int		hdr_length;
17035 	boolean_t	mctl_present;
17036 	mblk_t		*first_mp = mp;
17037 	mblk_t		*hada_mp = NULL;
17038 	ipha_t		*inner_ipha;
17039 	ip_stack_t	*ipst;
17040 
17041 	ASSERT(recv_ill != NULL);
17042 	ipst = recv_ill->ill_ipst;
17043 
17044 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17045 	    "ip_rput_locl_start: q %p", q);
17046 
17047 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17048 	ASSERT(ill != NULL);
17049 
17050 
17051 #define	rptr	((uchar_t *)ipha)
17052 #define	iphs	((uint16_t *)ipha)
17053 
17054 	/*
17055 	 * no UDP or TCP packet should come here anymore.
17056 	 */
17057 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17058 	    ipha->ipha_protocol != IPPROTO_UDP);
17059 
17060 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17061 	if (mctl_present &&
17062 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17063 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17064 
17065 		/*
17066 		 * It's an IPsec accelerated packet.
17067 		 * Keep a pointer to the data attributes around until
17068 		 * we allocate the ipsec_info_t.
17069 		 */
17070 		IPSECHW_DEBUG(IPSECHW_PKT,
17071 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17072 		hada_mp = first_mp;
17073 		hada_mp->b_cont = NULL;
17074 		/*
17075 		 * Since it is accelerated, it comes directly from
17076 		 * the ill and the data attributes is followed by
17077 		 * the packet data.
17078 		 */
17079 		ASSERT(mp->b_datap->db_type != M_CTL);
17080 		first_mp = mp;
17081 		mctl_present = B_FALSE;
17082 	}
17083 
17084 	/*
17085 	 * IF M_CTL is not present, then ipsec_in_is_secure
17086 	 * should return B_TRUE. There is a case where loopback
17087 	 * packets has an M_CTL in the front with all the
17088 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17089 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17090 	 * packets never comes here, it is safe to ASSERT the
17091 	 * following.
17092 	 */
17093 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17094 
17095 	/*
17096 	 * Also, we should never have an mctl_present if this is an
17097 	 * ESP-in-UDP packet.
17098 	 */
17099 	ASSERT(!mctl_present || !esp_in_udp_packet);
17100 
17101 
17102 	/* u1 is # words of IP options */
17103 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17104 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17105 
17106 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17107 		if (u1) {
17108 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17109 				if (hada_mp != NULL)
17110 					freemsg(hada_mp);
17111 				return;
17112 			}
17113 		} else {
17114 			/* Check the IP header checksum.  */
17115 #define	uph	((uint16_t *)ipha)
17116 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17117 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17118 #undef  uph
17119 			/* finish doing IP checksum */
17120 			sum = (sum & 0xFFFF) + (sum >> 16);
17121 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17122 			if (sum && sum != 0xFFFF) {
17123 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17124 				goto drop_pkt;
17125 			}
17126 		}
17127 	}
17128 
17129 	/*
17130 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17131 	 * might be called more than once for secure packets, count only
17132 	 * the first time.
17133 	 */
17134 	if (!mctl_present) {
17135 		UPDATE_IB_PKT_COUNT(ire);
17136 		ire->ire_last_used_time = lbolt;
17137 	}
17138 
17139 	/* Check for fragmentation offset. */
17140 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17141 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17142 	if (u1) {
17143 		/*
17144 		 * We re-assemble fragments before we do the AH/ESP
17145 		 * processing. Thus, M_CTL should not be present
17146 		 * while we are re-assembling.
17147 		 */
17148 		ASSERT(!mctl_present);
17149 		ASSERT(first_mp == mp);
17150 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17151 			return;
17152 		}
17153 		/*
17154 		 * Make sure that first_mp points back to mp as
17155 		 * the mp we came in with could have changed in
17156 		 * ip_rput_fragment().
17157 		 */
17158 		ipha = (ipha_t *)mp->b_rptr;
17159 		first_mp = mp;
17160 	}
17161 
17162 	/*
17163 	 * Clear hardware checksumming flag as it is currently only
17164 	 * used by TCP and UDP.
17165 	 */
17166 	DB_CKSUMFLAGS(mp) = 0;
17167 
17168 	/* Now we have a complete datagram, destined for this machine. */
17169 	u1 = IPH_HDR_LENGTH(ipha);
17170 	switch (ipha->ipha_protocol) {
17171 	case IPPROTO_ICMP: {
17172 		ire_t		*ire_zone;
17173 		ilm_t		*ilm;
17174 		mblk_t		*mp1;
17175 		zoneid_t	last_zoneid;
17176 
17177 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17178 			ASSERT(ire->ire_type == IRE_BROADCAST);
17179 			/*
17180 			 * In the multicast case, applications may have joined
17181 			 * the group from different zones, so we need to deliver
17182 			 * the packet to each of them. Loop through the
17183 			 * multicast memberships structures (ilm) on the receive
17184 			 * ill and send a copy of the packet up each matching
17185 			 * one. However, we don't do this for multicasts sent on
17186 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17187 			 * they must stay in the sender's zone.
17188 			 *
17189 			 * ilm_add_v6() ensures that ilms in the same zone are
17190 			 * contiguous in the ill_ilm list. We use this property
17191 			 * to avoid sending duplicates needed when two
17192 			 * applications in the same zone join the same group on
17193 			 * different logical interfaces: we ignore the ilm if
17194 			 * its zoneid is the same as the last matching one.
17195 			 * In addition, the sending of the packet for
17196 			 * ire_zoneid is delayed until all of the other ilms
17197 			 * have been exhausted.
17198 			 */
17199 			last_zoneid = -1;
17200 			ILM_WALKER_HOLD(recv_ill);
17201 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17202 			    ilm = ilm->ilm_next) {
17203 				if ((ilm->ilm_flags & ILM_DELETED) ||
17204 				    ipha->ipha_dst != ilm->ilm_addr ||
17205 				    ilm->ilm_zoneid == last_zoneid ||
17206 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17207 				    ilm->ilm_zoneid == ALL_ZONES ||
17208 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17209 					continue;
17210 				mp1 = ip_copymsg(first_mp);
17211 				if (mp1 == NULL)
17212 					continue;
17213 				icmp_inbound(q, mp1, B_TRUE, ill,
17214 				    0, sum, mctl_present, B_TRUE,
17215 				    recv_ill, ilm->ilm_zoneid);
17216 				last_zoneid = ilm->ilm_zoneid;
17217 			}
17218 			ILM_WALKER_RELE(recv_ill);
17219 		} else if (ire->ire_type == IRE_BROADCAST) {
17220 			/*
17221 			 * In the broadcast case, there may be many zones
17222 			 * which need a copy of the packet delivered to them.
17223 			 * There is one IRE_BROADCAST per broadcast address
17224 			 * and per zone; we walk those using a helper function.
17225 			 * In addition, the sending of the packet for ire is
17226 			 * delayed until all of the other ires have been
17227 			 * processed.
17228 			 */
17229 			IRB_REFHOLD(ire->ire_bucket);
17230 			ire_zone = NULL;
17231 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17232 			    ire)) != NULL) {
17233 				mp1 = ip_copymsg(first_mp);
17234 				if (mp1 == NULL)
17235 					continue;
17236 
17237 				UPDATE_IB_PKT_COUNT(ire_zone);
17238 				ire_zone->ire_last_used_time = lbolt;
17239 				icmp_inbound(q, mp1, B_TRUE, ill,
17240 				    0, sum, mctl_present, B_TRUE,
17241 				    recv_ill, ire_zone->ire_zoneid);
17242 			}
17243 			IRB_REFRELE(ire->ire_bucket);
17244 		}
17245 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17246 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17247 		    ire->ire_zoneid);
17248 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17249 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17250 		return;
17251 	}
17252 	case IPPROTO_IGMP:
17253 		/*
17254 		 * If we are not willing to accept IGMP packets in clear,
17255 		 * then check with global policy.
17256 		 */
17257 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17258 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17259 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17260 			if (first_mp == NULL)
17261 				return;
17262 		}
17263 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17264 			freemsg(first_mp);
17265 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17266 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17267 			return;
17268 		}
17269 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17270 			/* Bad packet - discarded by igmp_input */
17271 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17272 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17273 			if (mctl_present)
17274 				freeb(first_mp);
17275 			return;
17276 		}
17277 		/*
17278 		 * igmp_input() may have returned the pulled up message.
17279 		 * So first_mp and ipha need to be reinitialized.
17280 		 */
17281 		ipha = (ipha_t *)mp->b_rptr;
17282 		if (mctl_present)
17283 			first_mp->b_cont = mp;
17284 		else
17285 			first_mp = mp;
17286 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17287 		    connf_head != NULL) {
17288 			/* No user-level listener for IGMP packets */
17289 			goto drop_pkt;
17290 		}
17291 		/* deliver to local raw users */
17292 		break;
17293 	case IPPROTO_PIM:
17294 		/*
17295 		 * If we are not willing to accept PIM packets in clear,
17296 		 * then check with global policy.
17297 		 */
17298 		if (ipst->ips_pim_accept_clear_messages == 0) {
17299 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17300 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17301 			if (first_mp == NULL)
17302 				return;
17303 		}
17304 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17305 			freemsg(first_mp);
17306 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17307 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17308 			return;
17309 		}
17310 		if (pim_input(q, mp, ill) != 0) {
17311 			/* Bad packet - discarded by pim_input */
17312 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17313 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17314 			if (mctl_present)
17315 				freeb(first_mp);
17316 			return;
17317 		}
17318 
17319 		/*
17320 		 * pim_input() may have pulled up the message so ipha needs to
17321 		 * be reinitialized.
17322 		 */
17323 		ipha = (ipha_t *)mp->b_rptr;
17324 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17325 		    connf_head != NULL) {
17326 			/* No user-level listener for PIM packets */
17327 			goto drop_pkt;
17328 		}
17329 		/* deliver to local raw users */
17330 		break;
17331 	case IPPROTO_ENCAP:
17332 		/*
17333 		 * Handle self-encapsulated packets (IP-in-IP where
17334 		 * the inner addresses == the outer addresses).
17335 		 */
17336 		hdr_length = IPH_HDR_LENGTH(ipha);
17337 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17338 		    mp->b_wptr) {
17339 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17340 			    sizeof (ipha_t) - mp->b_rptr)) {
17341 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17342 				freemsg(first_mp);
17343 				return;
17344 			}
17345 			ipha = (ipha_t *)mp->b_rptr;
17346 		}
17347 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17348 		/*
17349 		 * Check the sanity of the inner IP header.
17350 		 */
17351 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17352 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17353 			freemsg(first_mp);
17354 			return;
17355 		}
17356 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17357 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17358 			freemsg(first_mp);
17359 			return;
17360 		}
17361 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17362 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17363 			ipsec_in_t *ii;
17364 
17365 			/*
17366 			 * Self-encapsulated tunnel packet. Remove
17367 			 * the outer IP header and fanout again.
17368 			 * We also need to make sure that the inner
17369 			 * header is pulled up until options.
17370 			 */
17371 			mp->b_rptr = (uchar_t *)inner_ipha;
17372 			ipha = inner_ipha;
17373 			hdr_length = IPH_HDR_LENGTH(ipha);
17374 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17375 				if (!pullupmsg(mp, (uchar_t *)ipha +
17376 				    + hdr_length - mp->b_rptr)) {
17377 					freemsg(first_mp);
17378 					return;
17379 				}
17380 				ipha = (ipha_t *)mp->b_rptr;
17381 			}
17382 			if (!mctl_present) {
17383 				ASSERT(first_mp == mp);
17384 				/*
17385 				 * This means that somebody is sending
17386 				 * Self-encapsualted packets without AH/ESP.
17387 				 * If AH/ESP was present, we would have already
17388 				 * allocated the first_mp.
17389 				 */
17390 				first_mp = ipsec_in_alloc(B_TRUE,
17391 				    ipst->ips_netstack);
17392 				if (first_mp == NULL) {
17393 					ip1dbg(("ip_proto_input: IPSEC_IN "
17394 					    "allocation failure.\n"));
17395 					BUMP_MIB(ill->ill_ip_mib,
17396 					    ipIfStatsInDiscards);
17397 					freemsg(mp);
17398 					return;
17399 				}
17400 				first_mp->b_cont = mp;
17401 			}
17402 			/*
17403 			 * We generally store the ill_index if we need to
17404 			 * do IPsec processing as we lose the ill queue when
17405 			 * we come back. But in this case, we never should
17406 			 * have to store the ill_index here as it should have
17407 			 * been stored previously when we processed the
17408 			 * AH/ESP header in this routine or for non-ipsec
17409 			 * cases, we still have the queue. But for some bad
17410 			 * packets from the wire, we can get to IPsec after
17411 			 * this and we better store the index for that case.
17412 			 */
17413 			ill = (ill_t *)q->q_ptr;
17414 			ii = (ipsec_in_t *)first_mp->b_rptr;
17415 			ii->ipsec_in_ill_index =
17416 			    ill->ill_phyint->phyint_ifindex;
17417 			ii->ipsec_in_rill_index =
17418 			    recv_ill->ill_phyint->phyint_ifindex;
17419 			if (ii->ipsec_in_decaps) {
17420 				/*
17421 				 * This packet is self-encapsulated multiple
17422 				 * times. We don't want to recurse infinitely.
17423 				 * To keep it simple, drop the packet.
17424 				 */
17425 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17426 				freemsg(first_mp);
17427 				return;
17428 			}
17429 			ii->ipsec_in_decaps = B_TRUE;
17430 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17431 			    ire);
17432 			return;
17433 		}
17434 		break;
17435 	case IPPROTO_AH:
17436 	case IPPROTO_ESP: {
17437 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17438 
17439 		/*
17440 		 * Fast path for AH/ESP. If this is the first time
17441 		 * we are sending a datagram to AH/ESP, allocate
17442 		 * a IPSEC_IN message and prepend it. Otherwise,
17443 		 * just fanout.
17444 		 */
17445 
17446 		int ipsec_rc;
17447 		ipsec_in_t *ii;
17448 		netstack_t *ns = ipst->ips_netstack;
17449 
17450 		IP_STAT(ipst, ipsec_proto_ahesp);
17451 		if (!mctl_present) {
17452 			ASSERT(first_mp == mp);
17453 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17454 			if (first_mp == NULL) {
17455 				ip1dbg(("ip_proto_input: IPSEC_IN "
17456 				    "allocation failure.\n"));
17457 				freemsg(hada_mp); /* okay ifnull */
17458 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17459 				freemsg(mp);
17460 				return;
17461 			}
17462 			/*
17463 			 * Store the ill_index so that when we come back
17464 			 * from IPsec we ride on the same queue.
17465 			 */
17466 			ill = (ill_t *)q->q_ptr;
17467 			ii = (ipsec_in_t *)first_mp->b_rptr;
17468 			ii->ipsec_in_ill_index =
17469 			    ill->ill_phyint->phyint_ifindex;
17470 			ii->ipsec_in_rill_index =
17471 			    recv_ill->ill_phyint->phyint_ifindex;
17472 			first_mp->b_cont = mp;
17473 			/*
17474 			 * Cache hardware acceleration info.
17475 			 */
17476 			if (hada_mp != NULL) {
17477 				IPSECHW_DEBUG(IPSECHW_PKT,
17478 				    ("ip_rput_local: caching data attr.\n"));
17479 				ii->ipsec_in_accelerated = B_TRUE;
17480 				ii->ipsec_in_da = hada_mp;
17481 				hada_mp = NULL;
17482 			}
17483 		} else {
17484 			ii = (ipsec_in_t *)first_mp->b_rptr;
17485 		}
17486 
17487 		if (!ipsec_loaded(ipss)) {
17488 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17489 			    ire->ire_zoneid, ipst);
17490 			return;
17491 		}
17492 
17493 		ns = ipst->ips_netstack;
17494 		/* select inbound SA and have IPsec process the pkt */
17495 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17496 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17497 			boolean_t esp_in_udp_sa;
17498 			if (esph == NULL)
17499 				return;
17500 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17501 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17502 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17503 			    IPSA_F_NATT) != 0);
17504 			/*
17505 			 * The following is a fancy, but quick, way of saying:
17506 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17507 			 *    OR
17508 			 * ESP SA and ESP-in-UDP packet --> drop
17509 			 */
17510 			if (esp_in_udp_sa != esp_in_udp_packet) {
17511 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17512 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17513 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17514 				    &ns->netstack_ipsec->ipsec_dropper);
17515 				return;
17516 			}
17517 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17518 			    first_mp, esph);
17519 		} else {
17520 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17521 			if (ah == NULL)
17522 				return;
17523 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17524 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17525 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17526 			    first_mp, ah);
17527 		}
17528 
17529 		switch (ipsec_rc) {
17530 		case IPSEC_STATUS_SUCCESS:
17531 			break;
17532 		case IPSEC_STATUS_FAILED:
17533 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17534 			/* FALLTHRU */
17535 		case IPSEC_STATUS_PENDING:
17536 			return;
17537 		}
17538 		/* we're done with IPsec processing, send it up */
17539 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17540 		return;
17541 	}
17542 	default:
17543 		break;
17544 	}
17545 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17546 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17547 		    ire->ire_zoneid));
17548 		goto drop_pkt;
17549 	}
17550 	/*
17551 	 * Handle protocols with which IP is less intimate.  There
17552 	 * can be more than one stream bound to a particular
17553 	 * protocol.  When this is the case, each one gets a copy
17554 	 * of any incoming packets.
17555 	 */
17556 	ip_fanout_proto(q, first_mp, ill, ipha,
17557 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17558 	    B_TRUE, recv_ill, ire->ire_zoneid);
17559 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17560 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17561 	return;
17562 
17563 drop_pkt:
17564 	freemsg(first_mp);
17565 	if (hada_mp != NULL)
17566 		freeb(hada_mp);
17567 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17568 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17569 #undef	rptr
17570 #undef  iphs
17571 
17572 }
17573 
17574 /*
17575  * Update any source route, record route or timestamp options.
17576  * Check that we are at end of strict source route.
17577  * The options have already been checked for sanity in ip_rput_options().
17578  */
17579 static boolean_t
17580 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17581     ip_stack_t *ipst)
17582 {
17583 	ipoptp_t	opts;
17584 	uchar_t		*opt;
17585 	uint8_t		optval;
17586 	uint8_t		optlen;
17587 	ipaddr_t	dst;
17588 	uint32_t	ts;
17589 	ire_t		*dst_ire;
17590 	timestruc_t	now;
17591 	zoneid_t	zoneid;
17592 	ill_t		*ill;
17593 
17594 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17595 
17596 	ip2dbg(("ip_rput_local_options\n"));
17597 
17598 	for (optval = ipoptp_first(&opts, ipha);
17599 	    optval != IPOPT_EOL;
17600 	    optval = ipoptp_next(&opts)) {
17601 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17602 		opt = opts.ipoptp_cur;
17603 		optlen = opts.ipoptp_len;
17604 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17605 		    optval, optlen));
17606 		switch (optval) {
17607 			uint32_t off;
17608 		case IPOPT_SSRR:
17609 		case IPOPT_LSRR:
17610 			off = opt[IPOPT_OFFSET];
17611 			off--;
17612 			if (optlen < IP_ADDR_LEN ||
17613 			    off > optlen - IP_ADDR_LEN) {
17614 				/* End of source route */
17615 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17616 				break;
17617 			}
17618 			/*
17619 			 * This will only happen if two consecutive entries
17620 			 * in the source route contains our address or if
17621 			 * it is a packet with a loose source route which
17622 			 * reaches us before consuming the whole source route
17623 			 */
17624 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17625 			if (optval == IPOPT_SSRR) {
17626 				goto bad_src_route;
17627 			}
17628 			/*
17629 			 * Hack: instead of dropping the packet truncate the
17630 			 * source route to what has been used by filling the
17631 			 * rest with IPOPT_NOP.
17632 			 */
17633 			opt[IPOPT_OLEN] = (uint8_t)off;
17634 			while (off < optlen) {
17635 				opt[off++] = IPOPT_NOP;
17636 			}
17637 			break;
17638 		case IPOPT_RR:
17639 			off = opt[IPOPT_OFFSET];
17640 			off--;
17641 			if (optlen < IP_ADDR_LEN ||
17642 			    off > optlen - IP_ADDR_LEN) {
17643 				/* No more room - ignore */
17644 				ip1dbg((
17645 				    "ip_rput_local_options: end of RR\n"));
17646 				break;
17647 			}
17648 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17649 			    IP_ADDR_LEN);
17650 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17651 			break;
17652 		case IPOPT_TS:
17653 			/* Insert timestamp if there is romm */
17654 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17655 			case IPOPT_TS_TSONLY:
17656 				off = IPOPT_TS_TIMELEN;
17657 				break;
17658 			case IPOPT_TS_PRESPEC:
17659 			case IPOPT_TS_PRESPEC_RFC791:
17660 				/* Verify that the address matched */
17661 				off = opt[IPOPT_OFFSET] - 1;
17662 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17663 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17664 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17665 				    ipst);
17666 				if (dst_ire == NULL) {
17667 					/* Not for us */
17668 					break;
17669 				}
17670 				ire_refrele(dst_ire);
17671 				/* FALLTHRU */
17672 			case IPOPT_TS_TSANDADDR:
17673 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17674 				break;
17675 			default:
17676 				/*
17677 				 * ip_*put_options should have already
17678 				 * dropped this packet.
17679 				 */
17680 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17681 				    "unknown IT - bug in ip_rput_options?\n");
17682 				return (B_TRUE);	/* Keep "lint" happy */
17683 			}
17684 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17685 				/* Increase overflow counter */
17686 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17687 				opt[IPOPT_POS_OV_FLG] =
17688 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17689 				    (off << 4));
17690 				break;
17691 			}
17692 			off = opt[IPOPT_OFFSET] - 1;
17693 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17694 			case IPOPT_TS_PRESPEC:
17695 			case IPOPT_TS_PRESPEC_RFC791:
17696 			case IPOPT_TS_TSANDADDR:
17697 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17698 				    IP_ADDR_LEN);
17699 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17700 				/* FALLTHRU */
17701 			case IPOPT_TS_TSONLY:
17702 				off = opt[IPOPT_OFFSET] - 1;
17703 				/* Compute # of milliseconds since midnight */
17704 				gethrestime(&now);
17705 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17706 				    now.tv_nsec / (NANOSEC / MILLISEC);
17707 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17708 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17709 				break;
17710 			}
17711 			break;
17712 		}
17713 	}
17714 	return (B_TRUE);
17715 
17716 bad_src_route:
17717 	q = WR(q);
17718 	if (q->q_next != NULL)
17719 		ill = q->q_ptr;
17720 	else
17721 		ill = NULL;
17722 
17723 	/* make sure we clear any indication of a hardware checksum */
17724 	DB_CKSUMFLAGS(mp) = 0;
17725 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17726 	if (zoneid == ALL_ZONES)
17727 		freemsg(mp);
17728 	else
17729 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17730 	return (B_FALSE);
17731 
17732 }
17733 
17734 /*
17735  * Process IP options in an inbound packet.  If an option affects the
17736  * effective destination address, return the next hop address via dstp.
17737  * Returns -1 if something fails in which case an ICMP error has been sent
17738  * and mp freed.
17739  */
17740 static int
17741 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17742     ip_stack_t *ipst)
17743 {
17744 	ipoptp_t	opts;
17745 	uchar_t		*opt;
17746 	uint8_t		optval;
17747 	uint8_t		optlen;
17748 	ipaddr_t	dst;
17749 	intptr_t	code = 0;
17750 	ire_t		*ire = NULL;
17751 	zoneid_t	zoneid;
17752 	ill_t		*ill;
17753 
17754 	ip2dbg(("ip_rput_options\n"));
17755 	dst = ipha->ipha_dst;
17756 	for (optval = ipoptp_first(&opts, ipha);
17757 	    optval != IPOPT_EOL;
17758 	    optval = ipoptp_next(&opts)) {
17759 		opt = opts.ipoptp_cur;
17760 		optlen = opts.ipoptp_len;
17761 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17762 		    optval, optlen));
17763 		/*
17764 		 * Note: we need to verify the checksum before we
17765 		 * modify anything thus this routine only extracts the next
17766 		 * hop dst from any source route.
17767 		 */
17768 		switch (optval) {
17769 			uint32_t off;
17770 		case IPOPT_SSRR:
17771 		case IPOPT_LSRR:
17772 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17773 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17774 			if (ire == NULL) {
17775 				if (optval == IPOPT_SSRR) {
17776 					ip1dbg(("ip_rput_options: not next"
17777 					    " strict source route 0x%x\n",
17778 					    ntohl(dst)));
17779 					code = (char *)&ipha->ipha_dst -
17780 					    (char *)ipha;
17781 					goto param_prob; /* RouterReq's */
17782 				}
17783 				ip2dbg(("ip_rput_options: "
17784 				    "not next source route 0x%x\n",
17785 				    ntohl(dst)));
17786 				break;
17787 			}
17788 			ire_refrele(ire);
17789 
17790 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17791 				ip1dbg((
17792 				    "ip_rput_options: bad option offset\n"));
17793 				code = (char *)&opt[IPOPT_OLEN] -
17794 				    (char *)ipha;
17795 				goto param_prob;
17796 			}
17797 			off = opt[IPOPT_OFFSET];
17798 			off--;
17799 		redo_srr:
17800 			if (optlen < IP_ADDR_LEN ||
17801 			    off > optlen - IP_ADDR_LEN) {
17802 				/* End of source route */
17803 				ip1dbg(("ip_rput_options: end of SR\n"));
17804 				break;
17805 			}
17806 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17807 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17808 			    ntohl(dst)));
17809 
17810 			/*
17811 			 * Check if our address is present more than
17812 			 * once as consecutive hops in source route.
17813 			 * XXX verify per-interface ip_forwarding
17814 			 * for source route?
17815 			 */
17816 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17817 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17818 
17819 			if (ire != NULL) {
17820 				ire_refrele(ire);
17821 				off += IP_ADDR_LEN;
17822 				goto redo_srr;
17823 			}
17824 
17825 			if (dst == htonl(INADDR_LOOPBACK)) {
17826 				ip1dbg(("ip_rput_options: loopback addr in "
17827 				    "source route!\n"));
17828 				goto bad_src_route;
17829 			}
17830 			/*
17831 			 * For strict: verify that dst is directly
17832 			 * reachable.
17833 			 */
17834 			if (optval == IPOPT_SSRR) {
17835 				ire = ire_ftable_lookup(dst, 0, 0,
17836 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17837 				    MBLK_GETLABEL(mp),
17838 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17839 				if (ire == NULL) {
17840 					ip1dbg(("ip_rput_options: SSRR not "
17841 					    "directly reachable: 0x%x\n",
17842 					    ntohl(dst)));
17843 					goto bad_src_route;
17844 				}
17845 				ire_refrele(ire);
17846 			}
17847 			/*
17848 			 * Defer update of the offset and the record route
17849 			 * until the packet is forwarded.
17850 			 */
17851 			break;
17852 		case IPOPT_RR:
17853 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17854 				ip1dbg((
17855 				    "ip_rput_options: bad option offset\n"));
17856 				code = (char *)&opt[IPOPT_OLEN] -
17857 				    (char *)ipha;
17858 				goto param_prob;
17859 			}
17860 			break;
17861 		case IPOPT_TS:
17862 			/*
17863 			 * Verify that length >= 5 and that there is either
17864 			 * room for another timestamp or that the overflow
17865 			 * counter is not maxed out.
17866 			 */
17867 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17868 			if (optlen < IPOPT_MINLEN_IT) {
17869 				goto param_prob;
17870 			}
17871 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17872 				ip1dbg((
17873 				    "ip_rput_options: bad option offset\n"));
17874 				code = (char *)&opt[IPOPT_OFFSET] -
17875 				    (char *)ipha;
17876 				goto param_prob;
17877 			}
17878 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17879 			case IPOPT_TS_TSONLY:
17880 				off = IPOPT_TS_TIMELEN;
17881 				break;
17882 			case IPOPT_TS_TSANDADDR:
17883 			case IPOPT_TS_PRESPEC:
17884 			case IPOPT_TS_PRESPEC_RFC791:
17885 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17886 				break;
17887 			default:
17888 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17889 				    (char *)ipha;
17890 				goto param_prob;
17891 			}
17892 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17893 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17894 				/*
17895 				 * No room and the overflow counter is 15
17896 				 * already.
17897 				 */
17898 				goto param_prob;
17899 			}
17900 			break;
17901 		}
17902 	}
17903 
17904 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17905 		*dstp = dst;
17906 		return (0);
17907 	}
17908 
17909 	ip1dbg(("ip_rput_options: error processing IP options."));
17910 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17911 
17912 param_prob:
17913 	q = WR(q);
17914 	if (q->q_next != NULL)
17915 		ill = q->q_ptr;
17916 	else
17917 		ill = NULL;
17918 
17919 	/* make sure we clear any indication of a hardware checksum */
17920 	DB_CKSUMFLAGS(mp) = 0;
17921 	/* Don't know whether this is for non-global or global/forwarding */
17922 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17923 	if (zoneid == ALL_ZONES)
17924 		freemsg(mp);
17925 	else
17926 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17927 	return (-1);
17928 
17929 bad_src_route:
17930 	q = WR(q);
17931 	if (q->q_next != NULL)
17932 		ill = q->q_ptr;
17933 	else
17934 		ill = NULL;
17935 
17936 	/* make sure we clear any indication of a hardware checksum */
17937 	DB_CKSUMFLAGS(mp) = 0;
17938 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17939 	if (zoneid == ALL_ZONES)
17940 		freemsg(mp);
17941 	else
17942 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17943 	return (-1);
17944 }
17945 
17946 /*
17947  * IP & ICMP info in >=14 msg's ...
17948  *  - ip fixed part (mib2_ip_t)
17949  *  - icmp fixed part (mib2_icmp_t)
17950  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17951  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17952  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17953  *  - ipRouteAttributeTable (ip 102)	labeled routes
17954  *  - ip multicast membership (ip_member_t)
17955  *  - ip multicast source filtering (ip_grpsrc_t)
17956  *  - igmp fixed part (struct igmpstat)
17957  *  - multicast routing stats (struct mrtstat)
17958  *  - multicast routing vifs (array of struct vifctl)
17959  *  - multicast routing routes (array of struct mfcctl)
17960  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17961  *					One per ill plus one generic
17962  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17963  *					One per ill plus one generic
17964  *  - ipv6RouteEntry			all IPv6 IREs
17965  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17966  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17967  *  - ipv6AddrEntry			all IPv6 ipifs
17968  *  - ipv6 multicast membership (ipv6_member_t)
17969  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17970  *
17971  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17972  *
17973  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17974  * already filled in by the caller.
17975  * Return value of 0 indicates that no messages were sent and caller
17976  * should free mpctl.
17977  */
17978 int
17979 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17980 {
17981 	ip_stack_t *ipst;
17982 	sctp_stack_t *sctps;
17983 
17984 
17985 	if (q->q_next != NULL) {
17986 		ipst = ILLQ_TO_IPST(q);
17987 	} else {
17988 		ipst = CONNQ_TO_IPST(q);
17989 	}
17990 	ASSERT(ipst != NULL);
17991 	sctps = ipst->ips_netstack->netstack_sctp;
17992 
17993 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17994 		return (0);
17995 	}
17996 
17997 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
17998 	    ipst)) == NULL) {
17999 		return (1);
18000 	}
18001 
18002 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18003 		return (1);
18004 	}
18005 
18006 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18007 		return (1);
18008 	}
18009 
18010 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18011 		return (1);
18012 	}
18013 
18014 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18015 		return (1);
18016 	}
18017 
18018 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18019 		return (1);
18020 	}
18021 
18022 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18023 		return (1);
18024 	}
18025 
18026 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18027 		return (1);
18028 	}
18029 
18030 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18031 		return (1);
18032 	}
18033 
18034 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18035 		return (1);
18036 	}
18037 
18038 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18039 		return (1);
18040 	}
18041 
18042 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18043 		return (1);
18044 	}
18045 
18046 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18047 		return (1);
18048 	}
18049 
18050 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18051 		return (1);
18052 	}
18053 
18054 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18055 		return (1);
18056 	}
18057 
18058 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18059 	if (mpctl == NULL) {
18060 		return (1);
18061 	}
18062 
18063 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18064 		return (1);
18065 	}
18066 	freemsg(mpctl);
18067 	return (1);
18068 }
18069 
18070 
18071 /* Get global (legacy) IPv4 statistics */
18072 static mblk_t *
18073 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18074     ip_stack_t *ipst)
18075 {
18076 	mib2_ip_t		old_ip_mib;
18077 	struct opthdr		*optp;
18078 	mblk_t			*mp2ctl;
18079 
18080 	/*
18081 	 * make a copy of the original message
18082 	 */
18083 	mp2ctl = copymsg(mpctl);
18084 
18085 	/* fixed length IP structure... */
18086 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18087 	optp->level = MIB2_IP;
18088 	optp->name = 0;
18089 	SET_MIB(old_ip_mib.ipForwarding,
18090 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18091 	SET_MIB(old_ip_mib.ipDefaultTTL,
18092 	    (uint32_t)ipst->ips_ip_def_ttl);
18093 	SET_MIB(old_ip_mib.ipReasmTimeout,
18094 	    ipst->ips_ip_g_frag_timeout);
18095 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18096 	    sizeof (mib2_ipAddrEntry_t));
18097 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18098 	    sizeof (mib2_ipRouteEntry_t));
18099 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18100 	    sizeof (mib2_ipNetToMediaEntry_t));
18101 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18102 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18103 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18104 	    sizeof (mib2_ipAttributeEntry_t));
18105 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18106 
18107 	/*
18108 	 * Grab the statistics from the new IP MIB
18109 	 */
18110 	SET_MIB(old_ip_mib.ipInReceives,
18111 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18112 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18113 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18114 	SET_MIB(old_ip_mib.ipForwDatagrams,
18115 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18116 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18117 	    ipmib->ipIfStatsInUnknownProtos);
18118 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18119 	SET_MIB(old_ip_mib.ipInDelivers,
18120 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18121 	SET_MIB(old_ip_mib.ipOutRequests,
18122 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18123 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18124 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18125 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18126 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18127 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18128 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18129 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18130 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18131 
18132 	/* ipRoutingDiscards is not being used */
18133 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18134 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18135 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18136 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18137 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18138 	    ipmib->ipIfStatsReasmDuplicates);
18139 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18140 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18141 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18142 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18143 	SET_MIB(old_ip_mib.rawipInOverflows,
18144 	    ipmib->rawipIfStatsInOverflows);
18145 
18146 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18147 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18148 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18149 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18150 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18151 	    ipmib->ipIfStatsOutSwitchIPVersion);
18152 
18153 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18154 	    (int)sizeof (old_ip_mib))) {
18155 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18156 		    (uint_t)sizeof (old_ip_mib)));
18157 	}
18158 
18159 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18160 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18161 	    (int)optp->level, (int)optp->name, (int)optp->len));
18162 	qreply(q, mpctl);
18163 	return (mp2ctl);
18164 }
18165 
18166 /* Per interface IPv4 statistics */
18167 static mblk_t *
18168 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18169 {
18170 	struct opthdr		*optp;
18171 	mblk_t			*mp2ctl;
18172 	ill_t			*ill;
18173 	ill_walk_context_t	ctx;
18174 	mblk_t			*mp_tail = NULL;
18175 	mib2_ipIfStatsEntry_t	global_ip_mib;
18176 
18177 	/*
18178 	 * Make a copy of the original message
18179 	 */
18180 	mp2ctl = copymsg(mpctl);
18181 
18182 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18183 	optp->level = MIB2_IP;
18184 	optp->name = MIB2_IP_TRAFFIC_STATS;
18185 	/* Include "unknown interface" ip_mib */
18186 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18187 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18188 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18189 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18190 	    (ipst->ips_ip_g_forward ? 1 : 2));
18191 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18192 	    (uint32_t)ipst->ips_ip_def_ttl);
18193 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18194 	    sizeof (mib2_ipIfStatsEntry_t));
18195 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18196 	    sizeof (mib2_ipAddrEntry_t));
18197 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18198 	    sizeof (mib2_ipRouteEntry_t));
18199 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18200 	    sizeof (mib2_ipNetToMediaEntry_t));
18201 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18202 	    sizeof (ip_member_t));
18203 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18204 	    sizeof (ip_grpsrc_t));
18205 
18206 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18207 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18208 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18209 		    "failed to allocate %u bytes\n",
18210 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18211 	}
18212 
18213 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18214 
18215 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18216 	ill = ILL_START_WALK_V4(&ctx, ipst);
18217 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18218 		ill->ill_ip_mib->ipIfStatsIfIndex =
18219 		    ill->ill_phyint->phyint_ifindex;
18220 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18221 		    (ipst->ips_ip_g_forward ? 1 : 2));
18222 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18223 		    (uint32_t)ipst->ips_ip_def_ttl);
18224 
18225 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18226 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18227 		    (char *)ill->ill_ip_mib,
18228 		    (int)sizeof (*ill->ill_ip_mib))) {
18229 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18230 			    "failed to allocate %u bytes\n",
18231 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18232 		}
18233 	}
18234 	rw_exit(&ipst->ips_ill_g_lock);
18235 
18236 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18237 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18238 	    "level %d, name %d, len %d\n",
18239 	    (int)optp->level, (int)optp->name, (int)optp->len));
18240 	qreply(q, mpctl);
18241 
18242 	if (mp2ctl == NULL)
18243 		return (NULL);
18244 
18245 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18246 }
18247 
18248 /* Global IPv4 ICMP statistics */
18249 static mblk_t *
18250 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18251 {
18252 	struct opthdr		*optp;
18253 	mblk_t			*mp2ctl;
18254 
18255 	/*
18256 	 * Make a copy of the original message
18257 	 */
18258 	mp2ctl = copymsg(mpctl);
18259 
18260 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18261 	optp->level = MIB2_ICMP;
18262 	optp->name = 0;
18263 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18264 	    (int)sizeof (ipst->ips_icmp_mib))) {
18265 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18266 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18267 	}
18268 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18269 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18270 	    (int)optp->level, (int)optp->name, (int)optp->len));
18271 	qreply(q, mpctl);
18272 	return (mp2ctl);
18273 }
18274 
18275 /* Global IPv4 IGMP statistics */
18276 static mblk_t *
18277 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18278 {
18279 	struct opthdr		*optp;
18280 	mblk_t			*mp2ctl;
18281 
18282 	/*
18283 	 * make a copy of the original message
18284 	 */
18285 	mp2ctl = copymsg(mpctl);
18286 
18287 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18288 	optp->level = EXPER_IGMP;
18289 	optp->name = 0;
18290 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18291 	    (int)sizeof (ipst->ips_igmpstat))) {
18292 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18293 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18294 	}
18295 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18296 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18297 	    (int)optp->level, (int)optp->name, (int)optp->len));
18298 	qreply(q, mpctl);
18299 	return (mp2ctl);
18300 }
18301 
18302 /* Global IPv4 Multicast Routing statistics */
18303 static mblk_t *
18304 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18305 {
18306 	struct opthdr		*optp;
18307 	mblk_t			*mp2ctl;
18308 
18309 	/*
18310 	 * make a copy of the original message
18311 	 */
18312 	mp2ctl = copymsg(mpctl);
18313 
18314 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18315 	optp->level = EXPER_DVMRP;
18316 	optp->name = 0;
18317 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18318 		ip0dbg(("ip_mroute_stats: failed\n"));
18319 	}
18320 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18321 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18322 	    (int)optp->level, (int)optp->name, (int)optp->len));
18323 	qreply(q, mpctl);
18324 	return (mp2ctl);
18325 }
18326 
18327 /* IPv4 address information */
18328 static mblk_t *
18329 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18330 {
18331 	struct opthdr		*optp;
18332 	mblk_t			*mp2ctl;
18333 	mblk_t			*mp_tail = NULL;
18334 	ill_t			*ill;
18335 	ipif_t			*ipif;
18336 	uint_t			bitval;
18337 	mib2_ipAddrEntry_t	mae;
18338 	zoneid_t		zoneid;
18339 	ill_walk_context_t ctx;
18340 
18341 	/*
18342 	 * make a copy of the original message
18343 	 */
18344 	mp2ctl = copymsg(mpctl);
18345 
18346 	/* ipAddrEntryTable */
18347 
18348 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18349 	optp->level = MIB2_IP;
18350 	optp->name = MIB2_IP_ADDR;
18351 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18352 
18353 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18354 	ill = ILL_START_WALK_V4(&ctx, ipst);
18355 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18356 		for (ipif = ill->ill_ipif; ipif != NULL;
18357 		    ipif = ipif->ipif_next) {
18358 			if (ipif->ipif_zoneid != zoneid &&
18359 			    ipif->ipif_zoneid != ALL_ZONES)
18360 				continue;
18361 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18362 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18363 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18364 
18365 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18366 			    OCTET_LENGTH);
18367 			mae.ipAdEntIfIndex.o_length =
18368 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18369 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18370 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18371 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18372 			mae.ipAdEntInfo.ae_subnet_len =
18373 			    ip_mask_to_plen(ipif->ipif_net_mask);
18374 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18375 			for (bitval = 1;
18376 			    bitval &&
18377 			    !(bitval & ipif->ipif_brd_addr);
18378 			    bitval <<= 1)
18379 				noop;
18380 			mae.ipAdEntBcastAddr = bitval;
18381 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18382 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18383 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18384 			mae.ipAdEntInfo.ae_broadcast_addr =
18385 			    ipif->ipif_brd_addr;
18386 			mae.ipAdEntInfo.ae_pp_dst_addr =
18387 			    ipif->ipif_pp_dst_addr;
18388 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18389 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18390 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18391 
18392 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18393 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18394 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18395 				    "allocate %u bytes\n",
18396 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18397 			}
18398 		}
18399 	}
18400 	rw_exit(&ipst->ips_ill_g_lock);
18401 
18402 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18403 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18404 	    (int)optp->level, (int)optp->name, (int)optp->len));
18405 	qreply(q, mpctl);
18406 	return (mp2ctl);
18407 }
18408 
18409 /* IPv6 address information */
18410 static mblk_t *
18411 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18412 {
18413 	struct opthdr		*optp;
18414 	mblk_t			*mp2ctl;
18415 	mblk_t			*mp_tail = NULL;
18416 	ill_t			*ill;
18417 	ipif_t			*ipif;
18418 	mib2_ipv6AddrEntry_t	mae6;
18419 	zoneid_t		zoneid;
18420 	ill_walk_context_t	ctx;
18421 
18422 	/*
18423 	 * make a copy of the original message
18424 	 */
18425 	mp2ctl = copymsg(mpctl);
18426 
18427 	/* ipv6AddrEntryTable */
18428 
18429 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18430 	optp->level = MIB2_IP6;
18431 	optp->name = MIB2_IP6_ADDR;
18432 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18433 
18434 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18435 	ill = ILL_START_WALK_V6(&ctx, ipst);
18436 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18437 		for (ipif = ill->ill_ipif; ipif != NULL;
18438 		    ipif = ipif->ipif_next) {
18439 			if (ipif->ipif_zoneid != zoneid &&
18440 			    ipif->ipif_zoneid != ALL_ZONES)
18441 				continue;
18442 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18443 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18444 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18445 
18446 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18447 			    OCTET_LENGTH);
18448 			mae6.ipv6AddrIfIndex.o_length =
18449 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18450 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18451 			mae6.ipv6AddrPfxLength =
18452 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18453 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18454 			mae6.ipv6AddrInfo.ae_subnet_len =
18455 			    mae6.ipv6AddrPfxLength;
18456 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18457 
18458 			/* Type: stateless(1), stateful(2), unknown(3) */
18459 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18460 				mae6.ipv6AddrType = 1;
18461 			else
18462 				mae6.ipv6AddrType = 2;
18463 			/* Anycast: true(1), false(2) */
18464 			if (ipif->ipif_flags & IPIF_ANYCAST)
18465 				mae6.ipv6AddrAnycastFlag = 1;
18466 			else
18467 				mae6.ipv6AddrAnycastFlag = 2;
18468 
18469 			/*
18470 			 * Address status: preferred(1), deprecated(2),
18471 			 * invalid(3), inaccessible(4), unknown(5)
18472 			 */
18473 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18474 				mae6.ipv6AddrStatus = 3;
18475 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18476 				mae6.ipv6AddrStatus = 2;
18477 			else
18478 				mae6.ipv6AddrStatus = 1;
18479 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18480 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18481 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18482 			    ipif->ipif_v6pp_dst_addr;
18483 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18484 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18485 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18486 			mae6.ipv6AddrIdentifier = ill->ill_token;
18487 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18488 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18489 			mae6.ipv6AddrRetransmitTime =
18490 			    ill->ill_reachable_retrans_time;
18491 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18492 			    (char *)&mae6,
18493 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18494 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18495 				    "allocate %u bytes\n",
18496 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18497 			}
18498 		}
18499 	}
18500 	rw_exit(&ipst->ips_ill_g_lock);
18501 
18502 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18503 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18504 	    (int)optp->level, (int)optp->name, (int)optp->len));
18505 	qreply(q, mpctl);
18506 	return (mp2ctl);
18507 }
18508 
18509 /* IPv4 multicast group membership. */
18510 static mblk_t *
18511 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18512 {
18513 	struct opthdr		*optp;
18514 	mblk_t			*mp2ctl;
18515 	ill_t			*ill;
18516 	ipif_t			*ipif;
18517 	ilm_t			*ilm;
18518 	ip_member_t		ipm;
18519 	mblk_t			*mp_tail = NULL;
18520 	ill_walk_context_t	ctx;
18521 	zoneid_t		zoneid;
18522 
18523 	/*
18524 	 * make a copy of the original message
18525 	 */
18526 	mp2ctl = copymsg(mpctl);
18527 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18528 
18529 	/* ipGroupMember table */
18530 	optp = (struct opthdr *)&mpctl->b_rptr[
18531 	    sizeof (struct T_optmgmt_ack)];
18532 	optp->level = MIB2_IP;
18533 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18534 
18535 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18536 	ill = ILL_START_WALK_V4(&ctx, ipst);
18537 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18538 		ILM_WALKER_HOLD(ill);
18539 		for (ipif = ill->ill_ipif; ipif != NULL;
18540 		    ipif = ipif->ipif_next) {
18541 			if (ipif->ipif_zoneid != zoneid &&
18542 			    ipif->ipif_zoneid != ALL_ZONES)
18543 				continue;	/* not this zone */
18544 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18545 			    OCTET_LENGTH);
18546 			ipm.ipGroupMemberIfIndex.o_length =
18547 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18548 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18549 				ASSERT(ilm->ilm_ipif != NULL);
18550 				ASSERT(ilm->ilm_ill == NULL);
18551 				if (ilm->ilm_ipif != ipif)
18552 					continue;
18553 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18554 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18555 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18556 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18557 				    (char *)&ipm, (int)sizeof (ipm))) {
18558 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18559 					    "failed to allocate %u bytes\n",
18560 					    (uint_t)sizeof (ipm)));
18561 				}
18562 			}
18563 		}
18564 		ILM_WALKER_RELE(ill);
18565 	}
18566 	rw_exit(&ipst->ips_ill_g_lock);
18567 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18568 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18569 	    (int)optp->level, (int)optp->name, (int)optp->len));
18570 	qreply(q, mpctl);
18571 	return (mp2ctl);
18572 }
18573 
18574 /* IPv6 multicast group membership. */
18575 static mblk_t *
18576 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18577 {
18578 	struct opthdr		*optp;
18579 	mblk_t			*mp2ctl;
18580 	ill_t			*ill;
18581 	ilm_t			*ilm;
18582 	ipv6_member_t		ipm6;
18583 	mblk_t			*mp_tail = NULL;
18584 	ill_walk_context_t	ctx;
18585 	zoneid_t		zoneid;
18586 
18587 	/*
18588 	 * make a copy of the original message
18589 	 */
18590 	mp2ctl = copymsg(mpctl);
18591 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18592 
18593 	/* ip6GroupMember table */
18594 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18595 	optp->level = MIB2_IP6;
18596 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18597 
18598 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18599 	ill = ILL_START_WALK_V6(&ctx, ipst);
18600 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18601 		ILM_WALKER_HOLD(ill);
18602 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18603 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18604 			ASSERT(ilm->ilm_ipif == NULL);
18605 			ASSERT(ilm->ilm_ill != NULL);
18606 			if (ilm->ilm_zoneid != zoneid)
18607 				continue;	/* not this zone */
18608 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18609 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18610 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18611 			if (!snmp_append_data2(mpctl->b_cont,
18612 			    &mp_tail,
18613 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18614 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18615 				    "failed to allocate %u bytes\n",
18616 				    (uint_t)sizeof (ipm6)));
18617 			}
18618 		}
18619 		ILM_WALKER_RELE(ill);
18620 	}
18621 	rw_exit(&ipst->ips_ill_g_lock);
18622 
18623 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18624 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18625 	    (int)optp->level, (int)optp->name, (int)optp->len));
18626 	qreply(q, mpctl);
18627 	return (mp2ctl);
18628 }
18629 
18630 /* IP multicast filtered sources */
18631 static mblk_t *
18632 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18633 {
18634 	struct opthdr		*optp;
18635 	mblk_t			*mp2ctl;
18636 	ill_t			*ill;
18637 	ipif_t			*ipif;
18638 	ilm_t			*ilm;
18639 	ip_grpsrc_t		ips;
18640 	mblk_t			*mp_tail = NULL;
18641 	ill_walk_context_t	ctx;
18642 	zoneid_t		zoneid;
18643 	int			i;
18644 	slist_t			*sl;
18645 
18646 	/*
18647 	 * make a copy of the original message
18648 	 */
18649 	mp2ctl = copymsg(mpctl);
18650 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18651 
18652 	/* ipGroupSource table */
18653 	optp = (struct opthdr *)&mpctl->b_rptr[
18654 	    sizeof (struct T_optmgmt_ack)];
18655 	optp->level = MIB2_IP;
18656 	optp->name = EXPER_IP_GROUP_SOURCES;
18657 
18658 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18659 	ill = ILL_START_WALK_V4(&ctx, ipst);
18660 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18661 		ILM_WALKER_HOLD(ill);
18662 		for (ipif = ill->ill_ipif; ipif != NULL;
18663 		    ipif = ipif->ipif_next) {
18664 			if (ipif->ipif_zoneid != zoneid)
18665 				continue;	/* not this zone */
18666 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18667 			    OCTET_LENGTH);
18668 			ips.ipGroupSourceIfIndex.o_length =
18669 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18670 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18671 				ASSERT(ilm->ilm_ipif != NULL);
18672 				ASSERT(ilm->ilm_ill == NULL);
18673 				sl = ilm->ilm_filter;
18674 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18675 					continue;
18676 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18677 				for (i = 0; i < sl->sl_numsrc; i++) {
18678 					if (!IN6_IS_ADDR_V4MAPPED(
18679 					    &sl->sl_addr[i]))
18680 						continue;
18681 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18682 					    ips.ipGroupSourceAddress);
18683 					if (snmp_append_data2(mpctl->b_cont,
18684 					    &mp_tail, (char *)&ips,
18685 					    (int)sizeof (ips)) == 0) {
18686 						ip1dbg(("ip_snmp_get_mib2_"
18687 						    "ip_group_src: failed to "
18688 						    "allocate %u bytes\n",
18689 						    (uint_t)sizeof (ips)));
18690 					}
18691 				}
18692 			}
18693 		}
18694 		ILM_WALKER_RELE(ill);
18695 	}
18696 	rw_exit(&ipst->ips_ill_g_lock);
18697 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18698 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18699 	    (int)optp->level, (int)optp->name, (int)optp->len));
18700 	qreply(q, mpctl);
18701 	return (mp2ctl);
18702 }
18703 
18704 /* IPv6 multicast filtered sources. */
18705 static mblk_t *
18706 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18707 {
18708 	struct opthdr		*optp;
18709 	mblk_t			*mp2ctl;
18710 	ill_t			*ill;
18711 	ilm_t			*ilm;
18712 	ipv6_grpsrc_t		ips6;
18713 	mblk_t			*mp_tail = NULL;
18714 	ill_walk_context_t	ctx;
18715 	zoneid_t		zoneid;
18716 	int			i;
18717 	slist_t			*sl;
18718 
18719 	/*
18720 	 * make a copy of the original message
18721 	 */
18722 	mp2ctl = copymsg(mpctl);
18723 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18724 
18725 	/* ip6GroupMember table */
18726 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18727 	optp->level = MIB2_IP6;
18728 	optp->name = EXPER_IP6_GROUP_SOURCES;
18729 
18730 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18731 	ill = ILL_START_WALK_V6(&ctx, ipst);
18732 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18733 		ILM_WALKER_HOLD(ill);
18734 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18735 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18736 			ASSERT(ilm->ilm_ipif == NULL);
18737 			ASSERT(ilm->ilm_ill != NULL);
18738 			sl = ilm->ilm_filter;
18739 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18740 				continue;
18741 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18742 			for (i = 0; i < sl->sl_numsrc; i++) {
18743 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18744 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18745 				    (char *)&ips6, (int)sizeof (ips6))) {
18746 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18747 					    "group_src: failed to allocate "
18748 					    "%u bytes\n",
18749 					    (uint_t)sizeof (ips6)));
18750 				}
18751 			}
18752 		}
18753 		ILM_WALKER_RELE(ill);
18754 	}
18755 	rw_exit(&ipst->ips_ill_g_lock);
18756 
18757 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18758 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18759 	    (int)optp->level, (int)optp->name, (int)optp->len));
18760 	qreply(q, mpctl);
18761 	return (mp2ctl);
18762 }
18763 
18764 /* Multicast routing virtual interface table. */
18765 static mblk_t *
18766 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18767 {
18768 	struct opthdr		*optp;
18769 	mblk_t			*mp2ctl;
18770 
18771 	/*
18772 	 * make a copy of the original message
18773 	 */
18774 	mp2ctl = copymsg(mpctl);
18775 
18776 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18777 	optp->level = EXPER_DVMRP;
18778 	optp->name = EXPER_DVMRP_VIF;
18779 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18780 		ip0dbg(("ip_mroute_vif: failed\n"));
18781 	}
18782 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18783 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18784 	    (int)optp->level, (int)optp->name, (int)optp->len));
18785 	qreply(q, mpctl);
18786 	return (mp2ctl);
18787 }
18788 
18789 /* Multicast routing table. */
18790 static mblk_t *
18791 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18792 {
18793 	struct opthdr		*optp;
18794 	mblk_t			*mp2ctl;
18795 
18796 	/*
18797 	 * make a copy of the original message
18798 	 */
18799 	mp2ctl = copymsg(mpctl);
18800 
18801 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18802 	optp->level = EXPER_DVMRP;
18803 	optp->name = EXPER_DVMRP_MRT;
18804 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18805 		ip0dbg(("ip_mroute_mrt: failed\n"));
18806 	}
18807 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18808 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18809 	    (int)optp->level, (int)optp->name, (int)optp->len));
18810 	qreply(q, mpctl);
18811 	return (mp2ctl);
18812 }
18813 
18814 /*
18815  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18816  * in one IRE walk.
18817  */
18818 static mblk_t *
18819 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18820 {
18821 	struct opthdr	*optp;
18822 	mblk_t		*mp2ctl;	/* Returned */
18823 	mblk_t		*mp3ctl;	/* nettomedia */
18824 	mblk_t		*mp4ctl;	/* routeattrs */
18825 	iproutedata_t	ird;
18826 	zoneid_t	zoneid;
18827 
18828 	/*
18829 	 * make copies of the original message
18830 	 *	- mp2ctl is returned unchanged to the caller for his use
18831 	 *	- mpctl is sent upstream as ipRouteEntryTable
18832 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18833 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18834 	 */
18835 	mp2ctl = copymsg(mpctl);
18836 	mp3ctl = copymsg(mpctl);
18837 	mp4ctl = copymsg(mpctl);
18838 	if (mp3ctl == NULL || mp4ctl == NULL) {
18839 		freemsg(mp4ctl);
18840 		freemsg(mp3ctl);
18841 		freemsg(mp2ctl);
18842 		freemsg(mpctl);
18843 		return (NULL);
18844 	}
18845 
18846 	bzero(&ird, sizeof (ird));
18847 
18848 	ird.ird_route.lp_head = mpctl->b_cont;
18849 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18850 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18851 
18852 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18853 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18854 
18855 	/* ipRouteEntryTable in mpctl */
18856 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18857 	optp->level = MIB2_IP;
18858 	optp->name = MIB2_IP_ROUTE;
18859 	optp->len = msgdsize(ird.ird_route.lp_head);
18860 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18861 	    (int)optp->level, (int)optp->name, (int)optp->len));
18862 	qreply(q, mpctl);
18863 
18864 	/* ipNetToMediaEntryTable in mp3ctl */
18865 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18866 	optp->level = MIB2_IP;
18867 	optp->name = MIB2_IP_MEDIA;
18868 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18869 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18870 	    (int)optp->level, (int)optp->name, (int)optp->len));
18871 	qreply(q, mp3ctl);
18872 
18873 	/* ipRouteAttributeTable in mp4ctl */
18874 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18875 	optp->level = MIB2_IP;
18876 	optp->name = EXPER_IP_RTATTR;
18877 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18878 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18879 	    (int)optp->level, (int)optp->name, (int)optp->len));
18880 	if (optp->len == 0)
18881 		freemsg(mp4ctl);
18882 	else
18883 		qreply(q, mp4ctl);
18884 
18885 	return (mp2ctl);
18886 }
18887 
18888 /*
18889  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18890  * ipv6NetToMediaEntryTable in an NDP walk.
18891  */
18892 static mblk_t *
18893 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18894 {
18895 	struct opthdr	*optp;
18896 	mblk_t		*mp2ctl;	/* Returned */
18897 	mblk_t		*mp3ctl;	/* nettomedia */
18898 	mblk_t		*mp4ctl;	/* routeattrs */
18899 	iproutedata_t	ird;
18900 	zoneid_t	zoneid;
18901 
18902 	/*
18903 	 * make copies of the original message
18904 	 *	- mp2ctl is returned unchanged to the caller for his use
18905 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18906 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18907 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18908 	 */
18909 	mp2ctl = copymsg(mpctl);
18910 	mp3ctl = copymsg(mpctl);
18911 	mp4ctl = copymsg(mpctl);
18912 	if (mp3ctl == NULL || mp4ctl == NULL) {
18913 		freemsg(mp4ctl);
18914 		freemsg(mp3ctl);
18915 		freemsg(mp2ctl);
18916 		freemsg(mpctl);
18917 		return (NULL);
18918 	}
18919 
18920 	bzero(&ird, sizeof (ird));
18921 
18922 	ird.ird_route.lp_head = mpctl->b_cont;
18923 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18924 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18925 
18926 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18927 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18928 
18929 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18930 	optp->level = MIB2_IP6;
18931 	optp->name = MIB2_IP6_ROUTE;
18932 	optp->len = msgdsize(ird.ird_route.lp_head);
18933 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18934 	    (int)optp->level, (int)optp->name, (int)optp->len));
18935 	qreply(q, mpctl);
18936 
18937 	/* ipv6NetToMediaEntryTable in mp3ctl */
18938 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18939 
18940 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18941 	optp->level = MIB2_IP6;
18942 	optp->name = MIB2_IP6_MEDIA;
18943 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18944 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18945 	    (int)optp->level, (int)optp->name, (int)optp->len));
18946 	qreply(q, mp3ctl);
18947 
18948 	/* ipv6RouteAttributeTable in mp4ctl */
18949 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18950 	optp->level = MIB2_IP6;
18951 	optp->name = EXPER_IP_RTATTR;
18952 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18953 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18954 	    (int)optp->level, (int)optp->name, (int)optp->len));
18955 	if (optp->len == 0)
18956 		freemsg(mp4ctl);
18957 	else
18958 		qreply(q, mp4ctl);
18959 
18960 	return (mp2ctl);
18961 }
18962 
18963 /*
18964  * IPv6 mib: One per ill
18965  */
18966 static mblk_t *
18967 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18968 {
18969 	struct opthdr		*optp;
18970 	mblk_t			*mp2ctl;
18971 	ill_t			*ill;
18972 	ill_walk_context_t	ctx;
18973 	mblk_t			*mp_tail = NULL;
18974 
18975 	/*
18976 	 * Make a copy of the original message
18977 	 */
18978 	mp2ctl = copymsg(mpctl);
18979 
18980 	/* fixed length IPv6 structure ... */
18981 
18982 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18983 	optp->level = MIB2_IP6;
18984 	optp->name = 0;
18985 	/* Include "unknown interface" ip6_mib */
18986 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
18987 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
18988 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18989 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
18990 	    ipst->ips_ipv6_forward ? 1 : 2);
18991 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
18992 	    ipst->ips_ipv6_def_hops);
18993 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
18994 	    sizeof (mib2_ipIfStatsEntry_t));
18995 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
18996 	    sizeof (mib2_ipv6AddrEntry_t));
18997 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
18998 	    sizeof (mib2_ipv6RouteEntry_t));
18999 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19000 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19001 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19002 	    sizeof (ipv6_member_t));
19003 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19004 	    sizeof (ipv6_grpsrc_t));
19005 
19006 	/*
19007 	 * Synchronize 64- and 32-bit counters
19008 	 */
19009 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19010 	    ipIfStatsHCInReceives);
19011 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19012 	    ipIfStatsHCInDelivers);
19013 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19014 	    ipIfStatsHCOutRequests);
19015 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19016 	    ipIfStatsHCOutForwDatagrams);
19017 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19018 	    ipIfStatsHCOutMcastPkts);
19019 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19020 	    ipIfStatsHCInMcastPkts);
19021 
19022 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19023 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19024 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19025 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19026 	}
19027 
19028 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19029 	ill = ILL_START_WALK_V6(&ctx, ipst);
19030 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19031 		ill->ill_ip_mib->ipIfStatsIfIndex =
19032 		    ill->ill_phyint->phyint_ifindex;
19033 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19034 		    ipst->ips_ipv6_forward ? 1 : 2);
19035 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19036 		    ill->ill_max_hops);
19037 
19038 		/*
19039 		 * Synchronize 64- and 32-bit counters
19040 		 */
19041 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19042 		    ipIfStatsHCInReceives);
19043 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19044 		    ipIfStatsHCInDelivers);
19045 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19046 		    ipIfStatsHCOutRequests);
19047 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19048 		    ipIfStatsHCOutForwDatagrams);
19049 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19050 		    ipIfStatsHCOutMcastPkts);
19051 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19052 		    ipIfStatsHCInMcastPkts);
19053 
19054 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19055 		    (char *)ill->ill_ip_mib,
19056 		    (int)sizeof (*ill->ill_ip_mib))) {
19057 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19058 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19059 		}
19060 	}
19061 	rw_exit(&ipst->ips_ill_g_lock);
19062 
19063 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19064 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19065 	    (int)optp->level, (int)optp->name, (int)optp->len));
19066 	qreply(q, mpctl);
19067 	return (mp2ctl);
19068 }
19069 
19070 /*
19071  * ICMPv6 mib: One per ill
19072  */
19073 static mblk_t *
19074 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19075 {
19076 	struct opthdr		*optp;
19077 	mblk_t			*mp2ctl;
19078 	ill_t			*ill;
19079 	ill_walk_context_t	ctx;
19080 	mblk_t			*mp_tail = NULL;
19081 	/*
19082 	 * Make a copy of the original message
19083 	 */
19084 	mp2ctl = copymsg(mpctl);
19085 
19086 	/* fixed length ICMPv6 structure ... */
19087 
19088 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19089 	optp->level = MIB2_ICMP6;
19090 	optp->name = 0;
19091 	/* Include "unknown interface" icmp6_mib */
19092 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19093 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19094 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19095 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19096 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19097 	    (char *)&ipst->ips_icmp6_mib,
19098 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19099 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19100 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19101 	}
19102 
19103 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19104 	ill = ILL_START_WALK_V6(&ctx, ipst);
19105 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19106 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19107 		    ill->ill_phyint->phyint_ifindex;
19108 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19109 		    (char *)ill->ill_icmp6_mib,
19110 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19111 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19112 			    "%u bytes\n",
19113 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19114 		}
19115 	}
19116 	rw_exit(&ipst->ips_ill_g_lock);
19117 
19118 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19119 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19120 	    (int)optp->level, (int)optp->name, (int)optp->len));
19121 	qreply(q, mpctl);
19122 	return (mp2ctl);
19123 }
19124 
19125 /*
19126  * ire_walk routine to create both ipRouteEntryTable and
19127  * ipRouteAttributeTable in one IRE walk
19128  */
19129 static void
19130 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19131 {
19132 	ill_t				*ill;
19133 	ipif_t				*ipif;
19134 	mib2_ipRouteEntry_t		*re;
19135 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19136 	ipaddr_t			gw_addr;
19137 	tsol_ire_gw_secattr_t		*attrp;
19138 	tsol_gc_t			*gc = NULL;
19139 	tsol_gcgrp_t			*gcgrp = NULL;
19140 	uint_t				sacnt = 0;
19141 	int				i;
19142 
19143 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19144 
19145 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19146 		return;
19147 
19148 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19149 		mutex_enter(&attrp->igsa_lock);
19150 		if ((gc = attrp->igsa_gc) != NULL) {
19151 			gcgrp = gc->gc_grp;
19152 			ASSERT(gcgrp != NULL);
19153 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19154 			sacnt = 1;
19155 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19156 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19157 			gc = gcgrp->gcgrp_head;
19158 			sacnt = gcgrp->gcgrp_count;
19159 		}
19160 		mutex_exit(&attrp->igsa_lock);
19161 
19162 		/* do nothing if there's no gc to report */
19163 		if (gc == NULL) {
19164 			ASSERT(sacnt == 0);
19165 			if (gcgrp != NULL) {
19166 				/* we might as well drop the lock now */
19167 				rw_exit(&gcgrp->gcgrp_rwlock);
19168 				gcgrp = NULL;
19169 			}
19170 			attrp = NULL;
19171 		}
19172 
19173 		ASSERT(gc == NULL || (gcgrp != NULL &&
19174 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19175 	}
19176 	ASSERT(sacnt == 0 || gc != NULL);
19177 
19178 	if (sacnt != 0 &&
19179 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19180 		kmem_free(re, sizeof (*re));
19181 		rw_exit(&gcgrp->gcgrp_rwlock);
19182 		return;
19183 	}
19184 
19185 	/*
19186 	 * Return all IRE types for route table... let caller pick and choose
19187 	 */
19188 	re->ipRouteDest = ire->ire_addr;
19189 	ipif = ire->ire_ipif;
19190 	re->ipRouteIfIndex.o_length = 0;
19191 	if (ire->ire_type == IRE_CACHE) {
19192 		ill = (ill_t *)ire->ire_stq->q_ptr;
19193 		re->ipRouteIfIndex.o_length =
19194 		    ill->ill_name_length == 0 ? 0 :
19195 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19196 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19197 		    re->ipRouteIfIndex.o_length);
19198 	} else if (ipif != NULL) {
19199 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19200 		re->ipRouteIfIndex.o_length =
19201 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19202 	}
19203 	re->ipRouteMetric1 = -1;
19204 	re->ipRouteMetric2 = -1;
19205 	re->ipRouteMetric3 = -1;
19206 	re->ipRouteMetric4 = -1;
19207 
19208 	gw_addr = ire->ire_gateway_addr;
19209 
19210 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19211 		re->ipRouteNextHop = ire->ire_src_addr;
19212 	else
19213 		re->ipRouteNextHop = gw_addr;
19214 	/* indirect(4), direct(3), or invalid(2) */
19215 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19216 		re->ipRouteType = 2;
19217 	else
19218 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19219 	re->ipRouteProto = -1;
19220 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19221 	re->ipRouteMask = ire->ire_mask;
19222 	re->ipRouteMetric5 = -1;
19223 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19224 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19225 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19226 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19227 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19228 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19229 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19230 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19231 
19232 	if (ire->ire_flags & RTF_DYNAMIC) {
19233 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19234 	} else {
19235 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19236 	}
19237 
19238 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19239 	    (char *)re, (int)sizeof (*re))) {
19240 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19241 		    (uint_t)sizeof (*re)));
19242 	}
19243 
19244 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19245 		iaeptr->iae_routeidx = ird->ird_idx;
19246 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19247 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19248 	}
19249 
19250 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19251 	    (char *)iae, sacnt * sizeof (*iae))) {
19252 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19253 		    (unsigned)(sacnt * sizeof (*iae))));
19254 	}
19255 
19256 	/* bump route index for next pass */
19257 	ird->ird_idx++;
19258 
19259 	kmem_free(re, sizeof (*re));
19260 	if (sacnt != 0)
19261 		kmem_free(iae, sacnt * sizeof (*iae));
19262 
19263 	if (gcgrp != NULL)
19264 		rw_exit(&gcgrp->gcgrp_rwlock);
19265 }
19266 
19267 /*
19268  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19269  */
19270 static void
19271 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19272 {
19273 	ill_t				*ill;
19274 	ipif_t				*ipif;
19275 	mib2_ipv6RouteEntry_t		*re;
19276 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19277 	in6_addr_t			gw_addr_v6;
19278 	tsol_ire_gw_secattr_t		*attrp;
19279 	tsol_gc_t			*gc = NULL;
19280 	tsol_gcgrp_t			*gcgrp = NULL;
19281 	uint_t				sacnt = 0;
19282 	int				i;
19283 
19284 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19285 
19286 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19287 		return;
19288 
19289 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19290 		mutex_enter(&attrp->igsa_lock);
19291 		if ((gc = attrp->igsa_gc) != NULL) {
19292 			gcgrp = gc->gc_grp;
19293 			ASSERT(gcgrp != NULL);
19294 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19295 			sacnt = 1;
19296 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19297 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19298 			gc = gcgrp->gcgrp_head;
19299 			sacnt = gcgrp->gcgrp_count;
19300 		}
19301 		mutex_exit(&attrp->igsa_lock);
19302 
19303 		/* do nothing if there's no gc to report */
19304 		if (gc == NULL) {
19305 			ASSERT(sacnt == 0);
19306 			if (gcgrp != NULL) {
19307 				/* we might as well drop the lock now */
19308 				rw_exit(&gcgrp->gcgrp_rwlock);
19309 				gcgrp = NULL;
19310 			}
19311 			attrp = NULL;
19312 		}
19313 
19314 		ASSERT(gc == NULL || (gcgrp != NULL &&
19315 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19316 	}
19317 	ASSERT(sacnt == 0 || gc != NULL);
19318 
19319 	if (sacnt != 0 &&
19320 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19321 		kmem_free(re, sizeof (*re));
19322 		rw_exit(&gcgrp->gcgrp_rwlock);
19323 		return;
19324 	}
19325 
19326 	/*
19327 	 * Return all IRE types for route table... let caller pick and choose
19328 	 */
19329 	re->ipv6RouteDest = ire->ire_addr_v6;
19330 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19331 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19332 	re->ipv6RouteIfIndex.o_length = 0;
19333 	ipif = ire->ire_ipif;
19334 	if (ire->ire_type == IRE_CACHE) {
19335 		ill = (ill_t *)ire->ire_stq->q_ptr;
19336 		re->ipv6RouteIfIndex.o_length =
19337 		    ill->ill_name_length == 0 ? 0 :
19338 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19339 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19340 		    re->ipv6RouteIfIndex.o_length);
19341 	} else if (ipif != NULL) {
19342 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19343 		re->ipv6RouteIfIndex.o_length =
19344 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19345 	}
19346 
19347 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19348 
19349 	mutex_enter(&ire->ire_lock);
19350 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19351 	mutex_exit(&ire->ire_lock);
19352 
19353 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19354 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19355 	else
19356 		re->ipv6RouteNextHop = gw_addr_v6;
19357 
19358 	/* remote(4), local(3), or discard(2) */
19359 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19360 		re->ipv6RouteType = 2;
19361 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19362 		re->ipv6RouteType = 3;
19363 	else
19364 		re->ipv6RouteType = 4;
19365 
19366 	re->ipv6RouteProtocol	= -1;
19367 	re->ipv6RoutePolicy	= 0;
19368 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19369 	re->ipv6RouteNextHopRDI	= 0;
19370 	re->ipv6RouteWeight	= 0;
19371 	re->ipv6RouteMetric	= 0;
19372 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19373 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19374 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19375 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19376 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19377 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19378 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19379 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19380 
19381 	if (ire->ire_flags & RTF_DYNAMIC) {
19382 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19383 	} else {
19384 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19385 	}
19386 
19387 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19388 	    (char *)re, (int)sizeof (*re))) {
19389 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19390 		    (uint_t)sizeof (*re)));
19391 	}
19392 
19393 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19394 		iaeptr->iae_routeidx = ird->ird_idx;
19395 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19396 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19397 	}
19398 
19399 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19400 	    (char *)iae, sacnt * sizeof (*iae))) {
19401 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19402 		    (unsigned)(sacnt * sizeof (*iae))));
19403 	}
19404 
19405 	/* bump route index for next pass */
19406 	ird->ird_idx++;
19407 
19408 	kmem_free(re, sizeof (*re));
19409 	if (sacnt != 0)
19410 		kmem_free(iae, sacnt * sizeof (*iae));
19411 
19412 	if (gcgrp != NULL)
19413 		rw_exit(&gcgrp->gcgrp_rwlock);
19414 }
19415 
19416 /*
19417  * ndp_walk routine to create ipv6NetToMediaEntryTable
19418  */
19419 static int
19420 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19421 {
19422 	ill_t				*ill;
19423 	mib2_ipv6NetToMediaEntry_t	ntme;
19424 	dl_unitdata_req_t		*dl;
19425 
19426 	ill = nce->nce_ill;
19427 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19428 		return (0);
19429 
19430 	/*
19431 	 * Neighbor cache entry attached to IRE with on-link
19432 	 * destination.
19433 	 */
19434 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19435 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19436 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19437 	    (nce->nce_res_mp != NULL)) {
19438 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19439 		ntme.ipv6NetToMediaPhysAddress.o_length =
19440 		    dl->dl_dest_addr_length;
19441 	} else {
19442 		ntme.ipv6NetToMediaPhysAddress.o_length =
19443 		    ill->ill_phys_addr_length;
19444 	}
19445 	if (nce->nce_res_mp != NULL) {
19446 		bcopy((char *)nce->nce_res_mp->b_rptr +
19447 		    NCE_LL_ADDR_OFFSET(ill),
19448 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19449 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19450 	} else {
19451 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19452 		    ill->ill_phys_addr_length);
19453 	}
19454 	/*
19455 	 * Note: Returns ND_* states. Should be:
19456 	 * reachable(1), stale(2), delay(3), probe(4),
19457 	 * invalid(5), unknown(6)
19458 	 */
19459 	ntme.ipv6NetToMediaState = nce->nce_state;
19460 	ntme.ipv6NetToMediaLastUpdated = 0;
19461 
19462 	/* other(1), dynamic(2), static(3), local(4) */
19463 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19464 		ntme.ipv6NetToMediaType = 4;
19465 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19466 		ntme.ipv6NetToMediaType = 1;
19467 	} else {
19468 		ntme.ipv6NetToMediaType = 2;
19469 	}
19470 
19471 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19472 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19473 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19474 		    (uint_t)sizeof (ntme)));
19475 	}
19476 	return (0);
19477 }
19478 
19479 /*
19480  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19481  */
19482 /* ARGSUSED */
19483 int
19484 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19485 {
19486 	switch (level) {
19487 	case MIB2_IP:
19488 	case MIB2_ICMP:
19489 		switch (name) {
19490 		default:
19491 			break;
19492 		}
19493 		return (1);
19494 	default:
19495 		return (1);
19496 	}
19497 }
19498 
19499 /*
19500  * When there exists both a 64- and 32-bit counter of a particular type
19501  * (i.e., InReceives), only the 64-bit counters are added.
19502  */
19503 void
19504 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19505 {
19506 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19507 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19508 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19509 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19510 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19511 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19512 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19513 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19514 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19515 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19516 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19517 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19518 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19519 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19520 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19521 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19522 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19523 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19524 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19525 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19526 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19527 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19528 	    o2->ipIfStatsInWrongIPVersion);
19529 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19530 	    o2->ipIfStatsInWrongIPVersion);
19531 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19532 	    o2->ipIfStatsOutSwitchIPVersion);
19533 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19534 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19535 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19536 	    o2->ipIfStatsHCInForwDatagrams);
19537 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19538 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19539 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19540 	    o2->ipIfStatsHCOutForwDatagrams);
19541 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19542 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19543 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19544 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19545 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19546 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19547 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19548 	    o2->ipIfStatsHCOutMcastOctets);
19549 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19550 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19551 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19552 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19553 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19554 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19555 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19556 }
19557 
19558 void
19559 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19560 {
19561 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19562 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19563 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19564 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19565 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19566 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19567 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19568 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19569 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19570 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19571 	    o2->ipv6IfIcmpInRouterSolicits);
19572 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19573 	    o2->ipv6IfIcmpInRouterAdvertisements);
19574 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19575 	    o2->ipv6IfIcmpInNeighborSolicits);
19576 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19577 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19578 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19579 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19580 	    o2->ipv6IfIcmpInGroupMembQueries);
19581 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19582 	    o2->ipv6IfIcmpInGroupMembResponses);
19583 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19584 	    o2->ipv6IfIcmpInGroupMembReductions);
19585 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19586 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19587 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19588 	    o2->ipv6IfIcmpOutDestUnreachs);
19589 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19590 	    o2->ipv6IfIcmpOutAdminProhibs);
19591 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19592 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19593 	    o2->ipv6IfIcmpOutParmProblems);
19594 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19595 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19596 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19597 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19598 	    o2->ipv6IfIcmpOutRouterSolicits);
19599 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19600 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19601 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19602 	    o2->ipv6IfIcmpOutNeighborSolicits);
19603 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19604 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19605 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19606 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19607 	    o2->ipv6IfIcmpOutGroupMembQueries);
19608 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19609 	    o2->ipv6IfIcmpOutGroupMembResponses);
19610 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19611 	    o2->ipv6IfIcmpOutGroupMembReductions);
19612 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19613 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19614 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19615 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19616 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19617 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19618 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19619 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19620 	    o2->ipv6IfIcmpInGroupMembTotal);
19621 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19622 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19623 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19624 	    o2->ipv6IfIcmpInGroupMembBadReports);
19625 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19626 	    o2->ipv6IfIcmpInGroupMembOurReports);
19627 }
19628 
19629 /*
19630  * Called before the options are updated to check if this packet will
19631  * be source routed from here.
19632  * This routine assumes that the options are well formed i.e. that they
19633  * have already been checked.
19634  */
19635 static boolean_t
19636 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19637 {
19638 	ipoptp_t	opts;
19639 	uchar_t		*opt;
19640 	uint8_t		optval;
19641 	uint8_t		optlen;
19642 	ipaddr_t	dst;
19643 	ire_t		*ire;
19644 
19645 	if (IS_SIMPLE_IPH(ipha)) {
19646 		ip2dbg(("not source routed\n"));
19647 		return (B_FALSE);
19648 	}
19649 	dst = ipha->ipha_dst;
19650 	for (optval = ipoptp_first(&opts, ipha);
19651 	    optval != IPOPT_EOL;
19652 	    optval = ipoptp_next(&opts)) {
19653 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19654 		opt = opts.ipoptp_cur;
19655 		optlen = opts.ipoptp_len;
19656 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19657 		    optval, optlen));
19658 		switch (optval) {
19659 			uint32_t off;
19660 		case IPOPT_SSRR:
19661 		case IPOPT_LSRR:
19662 			/*
19663 			 * If dst is one of our addresses and there are some
19664 			 * entries left in the source route return (true).
19665 			 */
19666 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19667 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19668 			if (ire == NULL) {
19669 				ip2dbg(("ip_source_routed: not next"
19670 				    " source route 0x%x\n",
19671 				    ntohl(dst)));
19672 				return (B_FALSE);
19673 			}
19674 			ire_refrele(ire);
19675 			off = opt[IPOPT_OFFSET];
19676 			off--;
19677 			if (optlen < IP_ADDR_LEN ||
19678 			    off > optlen - IP_ADDR_LEN) {
19679 				/* End of source route */
19680 				ip1dbg(("ip_source_routed: end of SR\n"));
19681 				return (B_FALSE);
19682 			}
19683 			return (B_TRUE);
19684 		}
19685 	}
19686 	ip2dbg(("not source routed\n"));
19687 	return (B_FALSE);
19688 }
19689 
19690 /*
19691  * Check if the packet contains any source route.
19692  */
19693 static boolean_t
19694 ip_source_route_included(ipha_t *ipha)
19695 {
19696 	ipoptp_t	opts;
19697 	uint8_t		optval;
19698 
19699 	if (IS_SIMPLE_IPH(ipha))
19700 		return (B_FALSE);
19701 	for (optval = ipoptp_first(&opts, ipha);
19702 	    optval != IPOPT_EOL;
19703 	    optval = ipoptp_next(&opts)) {
19704 		switch (optval) {
19705 		case IPOPT_SSRR:
19706 		case IPOPT_LSRR:
19707 			return (B_TRUE);
19708 		}
19709 	}
19710 	return (B_FALSE);
19711 }
19712 
19713 /*
19714  * Called when the IRE expiration timer fires.
19715  */
19716 void
19717 ip_trash_timer_expire(void *args)
19718 {
19719 	int			flush_flag = 0;
19720 	ire_expire_arg_t	iea;
19721 	ip_stack_t		*ipst = (ip_stack_t *)args;
19722 
19723 	iea.iea_ipst = ipst;	/* No netstack_hold */
19724 
19725 	/*
19726 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19727 	 * This lock makes sure that a new invocation of this function
19728 	 * that occurs due to an almost immediate timer firing will not
19729 	 * progress beyond this point until the current invocation is done
19730 	 */
19731 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19732 	ipst->ips_ip_ire_expire_id = 0;
19733 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19734 
19735 	/* Periodic timer */
19736 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19737 	    ipst->ips_ip_ire_arp_interval) {
19738 		/*
19739 		 * Remove all IRE_CACHE entries since they might
19740 		 * contain arp information.
19741 		 */
19742 		flush_flag |= FLUSH_ARP_TIME;
19743 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19744 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19745 	}
19746 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19747 	    ipst->ips_ip_ire_redir_interval) {
19748 		/* Remove all redirects */
19749 		flush_flag |= FLUSH_REDIRECT_TIME;
19750 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19751 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19752 	}
19753 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19754 	    ipst->ips_ip_ire_pathmtu_interval) {
19755 		/* Increase path mtu */
19756 		flush_flag |= FLUSH_MTU_TIME;
19757 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19758 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19759 	}
19760 
19761 	/*
19762 	 * Optimize for the case when there are no redirects in the
19763 	 * ftable, that is, no need to walk the ftable in that case.
19764 	 */
19765 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19766 		iea.iea_flush_flag = flush_flag;
19767 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19768 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19769 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19770 		    NULL, ALL_ZONES, ipst);
19771 	}
19772 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19773 	    ipst->ips_ip_redirect_cnt > 0) {
19774 		iea.iea_flush_flag = flush_flag;
19775 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19776 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19777 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19778 	}
19779 	if (flush_flag & FLUSH_MTU_TIME) {
19780 		/*
19781 		 * Walk all IPv6 IRE's and update them
19782 		 * Note that ARP and redirect timers are not
19783 		 * needed since NUD handles stale entries.
19784 		 */
19785 		flush_flag = FLUSH_MTU_TIME;
19786 		iea.iea_flush_flag = flush_flag;
19787 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19788 		    ALL_ZONES, ipst);
19789 	}
19790 
19791 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19792 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19793 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19794 
19795 	/*
19796 	 * Hold the lock to serialize timeout calls and prevent
19797 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19798 	 * for the timer to fire and a new invocation of this function
19799 	 * to start before the return value of timeout has been stored
19800 	 * in ip_ire_expire_id by the current invocation.
19801 	 */
19802 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19803 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19804 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19805 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19806 }
19807 
19808 /*
19809  * Called by the memory allocator subsystem directly, when the system
19810  * is running low on memory.
19811  */
19812 /* ARGSUSED */
19813 void
19814 ip_trash_ire_reclaim(void *args)
19815 {
19816 	netstack_handle_t nh;
19817 	netstack_t *ns;
19818 
19819 	netstack_next_init(&nh);
19820 	while ((ns = netstack_next(&nh)) != NULL) {
19821 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19822 		netstack_rele(ns);
19823 	}
19824 	netstack_next_fini(&nh);
19825 }
19826 
19827 static void
19828 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19829 {
19830 	ire_cache_count_t icc;
19831 	ire_cache_reclaim_t icr;
19832 	ncc_cache_count_t ncc;
19833 	nce_cache_reclaim_t ncr;
19834 	uint_t delete_cnt;
19835 	/*
19836 	 * Memory reclaim call back.
19837 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19838 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19839 	 * entries, determine what fraction to free for
19840 	 * each category of IRE_CACHE entries giving absolute priority
19841 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19842 	 * entry will be freed unless all offlink entries are freed).
19843 	 */
19844 	icc.icc_total = 0;
19845 	icc.icc_unused = 0;
19846 	icc.icc_offlink = 0;
19847 	icc.icc_pmtu = 0;
19848 	icc.icc_onlink = 0;
19849 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19850 
19851 	/*
19852 	 * Free NCEs for IPv6 like the onlink ires.
19853 	 */
19854 	ncc.ncc_total = 0;
19855 	ncc.ncc_host = 0;
19856 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19857 
19858 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19859 	    icc.icc_pmtu + icc.icc_onlink);
19860 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19861 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19862 	if (delete_cnt == 0)
19863 		return;
19864 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19865 	/* Always delete all unused offlink entries */
19866 	icr.icr_ipst = ipst;
19867 	icr.icr_unused = 1;
19868 	if (delete_cnt <= icc.icc_unused) {
19869 		/*
19870 		 * Only need to free unused entries.  In other words,
19871 		 * there are enough unused entries to free to meet our
19872 		 * target number of freed ire cache entries.
19873 		 */
19874 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19875 		ncr.ncr_host = 0;
19876 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19877 		/*
19878 		 * Only need to free unused entries, plus a fraction of offlink
19879 		 * entries.  It follows from the first if statement that
19880 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19881 		 */
19882 		delete_cnt -= icc.icc_unused;
19883 		/* Round up # deleted by truncating fraction */
19884 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19885 		icr.icr_pmtu = icr.icr_onlink = 0;
19886 		ncr.ncr_host = 0;
19887 	} else if (delete_cnt <=
19888 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19889 		/*
19890 		 * Free all unused and offlink entries, plus a fraction of
19891 		 * pmtu entries.  It follows from the previous if statement
19892 		 * that icc_pmtu is non-zero, and that
19893 		 * delete_cnt != icc_unused + icc_offlink.
19894 		 */
19895 		icr.icr_offlink = 1;
19896 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19897 		/* Round up # deleted by truncating fraction */
19898 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19899 		icr.icr_onlink = 0;
19900 		ncr.ncr_host = 0;
19901 	} else {
19902 		/*
19903 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19904 		 * of onlink entries.  If we're here, then we know that
19905 		 * icc_onlink is non-zero, and that
19906 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19907 		 */
19908 		icr.icr_offlink = icr.icr_pmtu = 1;
19909 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19910 		    icc.icc_pmtu;
19911 		/* Round up # deleted by truncating fraction */
19912 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19913 		/* Using the same delete fraction as for onlink IREs */
19914 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19915 	}
19916 #ifdef DEBUG
19917 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19918 	    "fractions %d/%d/%d/%d\n",
19919 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19920 	    icc.icc_unused, icc.icc_offlink,
19921 	    icc.icc_pmtu, icc.icc_onlink,
19922 	    icr.icr_unused, icr.icr_offlink,
19923 	    icr.icr_pmtu, icr.icr_onlink));
19924 #endif
19925 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19926 	if (ncr.ncr_host != 0)
19927 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19928 		    (uchar_t *)&ncr, ipst);
19929 #ifdef DEBUG
19930 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19931 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19932 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19933 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19934 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19935 	    icc.icc_pmtu, icc.icc_onlink));
19936 #endif
19937 }
19938 
19939 /*
19940  * ip_unbind is called when a copy of an unbind request is received from the
19941  * upper level protocol.  We remove this conn from any fanout hash list it is
19942  * on, and zero out the bind information.  No reply is expected up above.
19943  */
19944 mblk_t *
19945 ip_unbind(queue_t *q, mblk_t *mp)
19946 {
19947 	conn_t	*connp = Q_TO_CONN(q);
19948 
19949 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19950 
19951 	if (is_system_labeled() && connp->conn_anon_port) {
19952 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19953 		    connp->conn_mlp_type, connp->conn_ulp,
19954 		    ntohs(connp->conn_lport), B_FALSE);
19955 		connp->conn_anon_port = 0;
19956 	}
19957 	connp->conn_mlp_type = mlptSingle;
19958 
19959 	ipcl_hash_remove(connp);
19960 
19961 	ASSERT(mp->b_cont == NULL);
19962 	/*
19963 	 * Convert mp into a T_OK_ACK
19964 	 */
19965 	mp = mi_tpi_ok_ack_alloc(mp);
19966 
19967 	/*
19968 	 * should not happen in practice... T_OK_ACK is smaller than the
19969 	 * original message.
19970 	 */
19971 	if (mp == NULL)
19972 		return (NULL);
19973 
19974 	/*
19975 	 * Don't bzero the ports if its TCP since TCP still needs the
19976 	 * lport to remove it from its own bind hash. TCP will do the
19977 	 * cleanup.
19978 	 */
19979 	if (!IPCL_IS_TCP(connp))
19980 		bzero(&connp->u_port, sizeof (connp->u_port));
19981 
19982 	return (mp);
19983 }
19984 
19985 /*
19986  * Write side put procedure.  Outbound data, IOCTLs, responses from
19987  * resolvers, etc, come down through here.
19988  *
19989  * arg2 is always a queue_t *.
19990  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19991  * the zoneid.
19992  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19993  */
19994 void
19995 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19996 {
19997 	ip_output_options(arg, mp, arg2, caller, &zero_info);
19998 }
19999 
20000 void
20001 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20002     ip_opt_info_t *infop)
20003 {
20004 	conn_t		*connp = NULL;
20005 	queue_t		*q = (queue_t *)arg2;
20006 	ipha_t		*ipha;
20007 #define	rptr	((uchar_t *)ipha)
20008 	ire_t		*ire = NULL;
20009 	ire_t		*sctp_ire = NULL;
20010 	uint32_t	v_hlen_tos_len;
20011 	ipaddr_t	dst;
20012 	mblk_t		*first_mp = NULL;
20013 	boolean_t	mctl_present;
20014 	ipsec_out_t	*io;
20015 	int		match_flags;
20016 	ill_t		*attach_ill = NULL;
20017 					/* Bind to IPIF_NOFAILOVER ill etc. */
20018 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20019 	ipif_t		*dst_ipif;
20020 	boolean_t	multirt_need_resolve = B_FALSE;
20021 	mblk_t		*copy_mp = NULL;
20022 	int		err;
20023 	zoneid_t	zoneid;
20024 	int	adjust;
20025 	uint16_t iplen;
20026 	boolean_t	need_decref = B_FALSE;
20027 	boolean_t	ignore_dontroute = B_FALSE;
20028 	boolean_t	ignore_nexthop = B_FALSE;
20029 	boolean_t	ip_nexthop = B_FALSE;
20030 	ipaddr_t	nexthop_addr;
20031 	ip_stack_t	*ipst;
20032 
20033 #ifdef	_BIG_ENDIAN
20034 #define	V_HLEN	(v_hlen_tos_len >> 24)
20035 #else
20036 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20037 #endif
20038 
20039 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20040 	    "ip_wput_start: q %p", q);
20041 
20042 	/*
20043 	 * ip_wput fast path
20044 	 */
20045 
20046 	/* is packet from ARP ? */
20047 	if (q->q_next != NULL) {
20048 		zoneid = (zoneid_t)(uintptr_t)arg;
20049 		goto qnext;
20050 	}
20051 
20052 	connp = (conn_t *)arg;
20053 	ASSERT(connp != NULL);
20054 	zoneid = connp->conn_zoneid;
20055 	ipst = connp->conn_netstack->netstack_ip;
20056 
20057 	/* is queue flow controlled? */
20058 	if ((q->q_first != NULL || connp->conn_draining) &&
20059 	    (caller == IP_WPUT)) {
20060 		ASSERT(!need_decref);
20061 		(void) putq(q, mp);
20062 		return;
20063 	}
20064 
20065 	/* Multidata transmit? */
20066 	if (DB_TYPE(mp) == M_MULTIDATA) {
20067 		/*
20068 		 * We should never get here, since all Multidata messages
20069 		 * originating from tcp should have been directed over to
20070 		 * tcp_multisend() in the first place.
20071 		 */
20072 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20073 		freemsg(mp);
20074 		return;
20075 	} else if (DB_TYPE(mp) != M_DATA)
20076 		goto notdata;
20077 
20078 	if (mp->b_flag & MSGHASREF) {
20079 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20080 		mp->b_flag &= ~MSGHASREF;
20081 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20082 		need_decref = B_TRUE;
20083 	}
20084 	ipha = (ipha_t *)mp->b_rptr;
20085 
20086 	/* is IP header non-aligned or mblk smaller than basic IP header */
20087 #ifndef SAFETY_BEFORE_SPEED
20088 	if (!OK_32PTR(rptr) ||
20089 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20090 		goto hdrtoosmall;
20091 #endif
20092 
20093 	ASSERT(OK_32PTR(ipha));
20094 
20095 	/*
20096 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20097 	 * wrong version, we'll catch it again in ip_output_v6.
20098 	 *
20099 	 * Note that this is *only* locally-generated output here, and never
20100 	 * forwarded data, and that we need to deal only with transports that
20101 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20102 	 * label.)
20103 	 */
20104 	if (is_system_labeled() &&
20105 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20106 	    !connp->conn_ulp_labeled) {
20107 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20108 		    connp->conn_mac_exempt, ipst);
20109 		ipha = (ipha_t *)mp->b_rptr;
20110 		if (err != 0) {
20111 			first_mp = mp;
20112 			if (err == EINVAL)
20113 				goto icmp_parameter_problem;
20114 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20115 			goto discard_pkt;
20116 		}
20117 		iplen = ntohs(ipha->ipha_length) + adjust;
20118 		ipha->ipha_length = htons(iplen);
20119 	}
20120 
20121 	ASSERT(infop != NULL);
20122 
20123 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20124 		/*
20125 		 * IP_PKTINFO ancillary option is present.
20126 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20127 		 * allows using address of any zone as the source address.
20128 		 */
20129 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20130 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20131 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20132 		if (ire == NULL)
20133 			goto drop_pkt;
20134 		ire_refrele(ire);
20135 		ire = NULL;
20136 	}
20137 
20138 	/*
20139 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20140 	 * ill index passed in IP_PKTINFO.
20141 	 */
20142 	if (infop->ip_opt_ill_index != 0 &&
20143 	    connp->conn_xmit_if_ill == NULL &&
20144 	    connp->conn_nofailover_ill == NULL) {
20145 
20146 		xmit_ill = ill_lookup_on_ifindex(
20147 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20148 		    ipst);
20149 
20150 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20151 			goto drop_pkt;
20152 		/*
20153 		 * check that there is an ipif belonging
20154 		 * to our zone. IPCL_ZONEID is not used because
20155 		 * IP_ALLZONES option is valid only when the ill is
20156 		 * accessible from all zones i.e has a valid ipif in
20157 		 * all zones.
20158 		 */
20159 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20160 			goto drop_pkt;
20161 		}
20162 	}
20163 
20164 	/*
20165 	 * If there is a policy, try to attach an ipsec_out in
20166 	 * the front. At the end, first_mp either points to a
20167 	 * M_DATA message or IPSEC_OUT message linked to a
20168 	 * M_DATA message. We have to do it now as we might
20169 	 * lose the "conn" if we go through ip_newroute.
20170 	 */
20171 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20172 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20173 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20174 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20175 			if (need_decref)
20176 				CONN_DEC_REF(connp);
20177 			return;
20178 		} else {
20179 			ASSERT(mp->b_datap->db_type == M_CTL);
20180 			first_mp = mp;
20181 			mp = mp->b_cont;
20182 			mctl_present = B_TRUE;
20183 		}
20184 	} else {
20185 		first_mp = mp;
20186 		mctl_present = B_FALSE;
20187 	}
20188 
20189 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20190 
20191 	/* is wrong version or IP options present */
20192 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20193 		goto version_hdrlen_check;
20194 	dst = ipha->ipha_dst;
20195 
20196 	if (connp->conn_nofailover_ill != NULL) {
20197 		attach_ill = conn_get_held_ill(connp,
20198 		    &connp->conn_nofailover_ill, &err);
20199 		if (err == ILL_LOOKUP_FAILED) {
20200 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20201 			if (need_decref)
20202 				CONN_DEC_REF(connp);
20203 			freemsg(first_mp);
20204 			return;
20205 		}
20206 	}
20207 
20208 
20209 	/* is packet multicast? */
20210 	if (CLASSD(dst))
20211 		goto multicast;
20212 
20213 	/*
20214 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20215 	 * takes precedence over conn_dontroute and conn_nexthop_set
20216 	 */
20217 	if (xmit_ill != NULL) {
20218 		goto send_from_ill;
20219 	}
20220 
20221 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20222 	    (connp->conn_nexthop_set)) {
20223 		/*
20224 		 * If the destination is a broadcast or a loopback
20225 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20226 		 * through the standard path. But in the case of local
20227 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20228 		 * the standard path not IP_XMIT_IF.
20229 		 */
20230 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20231 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20232 		    (ire->ire_type != IRE_LOOPBACK))) {
20233 			if ((connp->conn_dontroute ||
20234 			    connp->conn_nexthop_set) && (ire != NULL) &&
20235 			    (ire->ire_type == IRE_LOCAL))
20236 				goto standard_path;
20237 
20238 			if (ire != NULL) {
20239 				ire_refrele(ire);
20240 				/* No more access to ire */
20241 				ire = NULL;
20242 			}
20243 			/*
20244 			 * bypass routing checks and go directly to
20245 			 * interface.
20246 			 */
20247 			if (connp->conn_dontroute) {
20248 				goto dontroute;
20249 			} else if (connp->conn_nexthop_set) {
20250 				ip_nexthop = B_TRUE;
20251 				nexthop_addr = connp->conn_nexthop_v4;
20252 				goto send_from_ill;
20253 			}
20254 
20255 			/*
20256 			 * If IP_XMIT_IF socket option is set,
20257 			 * then we allow unicast and multicast
20258 			 * packets to go through the ill. It is
20259 			 * quite possible that the destination
20260 			 * is not in the ire cache table and we
20261 			 * do not want to go to ip_newroute()
20262 			 * instead we call ip_newroute_ipif.
20263 			 */
20264 			xmit_ill = conn_get_held_ill(connp,
20265 			    &connp->conn_xmit_if_ill, &err);
20266 			if (err == ILL_LOOKUP_FAILED) {
20267 				BUMP_MIB(&ipst->ips_ip_mib,
20268 				    ipIfStatsOutDiscards);
20269 				if (attach_ill != NULL)
20270 					ill_refrele(attach_ill);
20271 				if (need_decref)
20272 					CONN_DEC_REF(connp);
20273 				freemsg(first_mp);
20274 				return;
20275 			}
20276 			goto send_from_ill;
20277 		}
20278 standard_path:
20279 		/* Must be a broadcast, a loopback or a local ire */
20280 		if (ire != NULL) {
20281 			ire_refrele(ire);
20282 			/* No more access to ire */
20283 			ire = NULL;
20284 		}
20285 	}
20286 
20287 	if (attach_ill != NULL)
20288 		goto send_from_ill;
20289 
20290 	/*
20291 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20292 	 * this for the tcp global queue and listen end point
20293 	 * as it does not really have a real destination to
20294 	 * talk to.  This is also true for SCTP.
20295 	 */
20296 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20297 	    !connp->conn_fully_bound) {
20298 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20299 		if (ire == NULL)
20300 			goto noirefound;
20301 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20302 		    "ip_wput_end: q %p (%S)", q, "end");
20303 
20304 		/*
20305 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20306 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20307 		 */
20308 		if (ire->ire_flags & RTF_MULTIRT) {
20309 
20310 			/*
20311 			 * Force the TTL of multirouted packets if required.
20312 			 * The TTL of such packets is bounded by the
20313 			 * ip_multirt_ttl ndd variable.
20314 			 */
20315 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20316 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20317 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20318 				    "(was %d), dst 0x%08x\n",
20319 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20320 				    ntohl(ire->ire_addr)));
20321 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20322 			}
20323 			/*
20324 			 * We look at this point if there are pending
20325 			 * unresolved routes. ire_multirt_resolvable()
20326 			 * checks in O(n) that all IRE_OFFSUBNET ire
20327 			 * entries for the packet's destination and
20328 			 * flagged RTF_MULTIRT are currently resolved.
20329 			 * If some remain unresolved, we make a copy
20330 			 * of the current message. It will be used
20331 			 * to initiate additional route resolutions.
20332 			 */
20333 			multirt_need_resolve =
20334 			    ire_multirt_need_resolve(ire->ire_addr,
20335 			    MBLK_GETLABEL(first_mp), ipst);
20336 			ip2dbg(("ip_wput[TCP]: ire %p, "
20337 			    "multirt_need_resolve %d, first_mp %p\n",
20338 			    (void *)ire, multirt_need_resolve,
20339 			    (void *)first_mp));
20340 			if (multirt_need_resolve) {
20341 				copy_mp = copymsg(first_mp);
20342 				if (copy_mp != NULL) {
20343 					MULTIRT_DEBUG_TAG(copy_mp);
20344 				}
20345 			}
20346 		}
20347 
20348 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20349 
20350 		/*
20351 		 * Try to resolve another multiroute if
20352 		 * ire_multirt_need_resolve() deemed it necessary.
20353 		 */
20354 		if (copy_mp != NULL)
20355 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20356 		if (need_decref)
20357 			CONN_DEC_REF(connp);
20358 		return;
20359 	}
20360 
20361 	/*
20362 	 * Access to conn_ire_cache. (protected by conn_lock)
20363 	 *
20364 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20365 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20366 	 * send a packet or two with the IRE_CACHE that is going away.
20367 	 * Access to the ire requires an ire refhold on the ire prior to
20368 	 * its use since an interface unplumb thread may delete the cached
20369 	 * ire and release the refhold at any time.
20370 	 *
20371 	 * Caching an ire in the conn_ire_cache
20372 	 *
20373 	 * o Caching an ire pointer in the conn requires a strict check for
20374 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20375 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20376 	 * in the conn is done after making sure under the bucket lock that the
20377 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20378 	 * caching an ire after the unplumb thread has cleaned up the conn.
20379 	 * If the conn does not send a packet subsequently the unplumb thread
20380 	 * will be hanging waiting for the ire count to drop to zero.
20381 	 *
20382 	 * o We also need to atomically test for a null conn_ire_cache and
20383 	 * set the conn_ire_cache under the the protection of the conn_lock
20384 	 * to avoid races among concurrent threads trying to simultaneously
20385 	 * cache an ire in the conn_ire_cache.
20386 	 */
20387 	mutex_enter(&connp->conn_lock);
20388 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20389 
20390 	if (ire != NULL && ire->ire_addr == dst &&
20391 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20392 
20393 		IRE_REFHOLD(ire);
20394 		mutex_exit(&connp->conn_lock);
20395 
20396 	} else {
20397 		boolean_t cached = B_FALSE;
20398 		connp->conn_ire_cache = NULL;
20399 		mutex_exit(&connp->conn_lock);
20400 		/* Release the old ire */
20401 		if (ire != NULL && sctp_ire == NULL)
20402 			IRE_REFRELE_NOTR(ire);
20403 
20404 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20405 		if (ire == NULL)
20406 			goto noirefound;
20407 		IRE_REFHOLD_NOTR(ire);
20408 
20409 		mutex_enter(&connp->conn_lock);
20410 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20411 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20412 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20413 				if (connp->conn_ulp == IPPROTO_TCP)
20414 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20415 				connp->conn_ire_cache = ire;
20416 				cached = B_TRUE;
20417 			}
20418 			rw_exit(&ire->ire_bucket->irb_lock);
20419 		}
20420 		mutex_exit(&connp->conn_lock);
20421 
20422 		/*
20423 		 * We can continue to use the ire but since it was
20424 		 * not cached, we should drop the extra reference.
20425 		 */
20426 		if (!cached)
20427 			IRE_REFRELE_NOTR(ire);
20428 	}
20429 
20430 
20431 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20432 	    "ip_wput_end: q %p (%S)", q, "end");
20433 
20434 	/*
20435 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20436 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20437 	 */
20438 	if (ire->ire_flags & RTF_MULTIRT) {
20439 
20440 		/*
20441 		 * Force the TTL of multirouted packets if required.
20442 		 * The TTL of such packets is bounded by the
20443 		 * ip_multirt_ttl ndd variable.
20444 		 */
20445 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20446 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20447 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20448 			    "(was %d), dst 0x%08x\n",
20449 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20450 			    ntohl(ire->ire_addr)));
20451 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20452 		}
20453 
20454 		/*
20455 		 * At this point, we check to see if there are any pending
20456 		 * unresolved routes. ire_multirt_resolvable()
20457 		 * checks in O(n) that all IRE_OFFSUBNET ire
20458 		 * entries for the packet's destination and
20459 		 * flagged RTF_MULTIRT are currently resolved.
20460 		 * If some remain unresolved, we make a copy
20461 		 * of the current message. It will be used
20462 		 * to initiate additional route resolutions.
20463 		 */
20464 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20465 		    MBLK_GETLABEL(first_mp), ipst);
20466 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20467 		    "multirt_need_resolve %d, first_mp %p\n",
20468 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20469 		if (multirt_need_resolve) {
20470 			copy_mp = copymsg(first_mp);
20471 			if (copy_mp != NULL) {
20472 				MULTIRT_DEBUG_TAG(copy_mp);
20473 			}
20474 		}
20475 	}
20476 
20477 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20478 
20479 	/*
20480 	 * Try to resolve another multiroute if
20481 	 * ire_multirt_resolvable() deemed it necessary
20482 	 */
20483 	if (copy_mp != NULL)
20484 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20485 	if (need_decref)
20486 		CONN_DEC_REF(connp);
20487 	return;
20488 
20489 qnext:
20490 	/*
20491 	 * Upper Level Protocols pass down complete IP datagrams
20492 	 * as M_DATA messages.	Everything else is a sideshow.
20493 	 *
20494 	 * 1) We could be re-entering ip_wput because of ip_neworute
20495 	 *    in which case we could have a IPSEC_OUT message. We
20496 	 *    need to pass through ip_wput like other datagrams and
20497 	 *    hence cannot branch to ip_wput_nondata.
20498 	 *
20499 	 * 2) ARP, AH, ESP, and other clients who are on the module
20500 	 *    instance of IP stream, give us something to deal with.
20501 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20502 	 *
20503 	 * 3) ICMP replies also could come here.
20504 	 */
20505 	ipst = ILLQ_TO_IPST(q);
20506 
20507 	if (DB_TYPE(mp) != M_DATA) {
20508 notdata:
20509 		if (DB_TYPE(mp) == M_CTL) {
20510 			/*
20511 			 * M_CTL messages are used by ARP, AH and ESP to
20512 			 * communicate with IP. We deal with IPSEC_IN and
20513 			 * IPSEC_OUT here. ip_wput_nondata handles other
20514 			 * cases.
20515 			 */
20516 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20517 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20518 				first_mp = mp->b_cont;
20519 				first_mp->b_flag &= ~MSGHASREF;
20520 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20521 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20522 				CONN_DEC_REF(connp);
20523 				connp = NULL;
20524 			}
20525 			if (ii->ipsec_info_type == IPSEC_IN) {
20526 				/*
20527 				 * Either this message goes back to
20528 				 * IPsec for further processing or to
20529 				 * ULP after policy checks.
20530 				 */
20531 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20532 				return;
20533 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20534 				io = (ipsec_out_t *)ii;
20535 				if (io->ipsec_out_proc_begin) {
20536 					/*
20537 					 * IPsec processing has already started.
20538 					 * Complete it.
20539 					 * IPQoS notes: We don't care what is
20540 					 * in ipsec_out_ill_index since this
20541 					 * won't be processed for IPQoS policies
20542 					 * in ipsec_out_process.
20543 					 */
20544 					ipsec_out_process(q, mp, NULL,
20545 					    io->ipsec_out_ill_index);
20546 					return;
20547 				} else {
20548 					connp = (q->q_next != NULL) ?
20549 					    NULL : Q_TO_CONN(q);
20550 					first_mp = mp;
20551 					mp = mp->b_cont;
20552 					mctl_present = B_TRUE;
20553 				}
20554 				zoneid = io->ipsec_out_zoneid;
20555 				ASSERT(zoneid != ALL_ZONES);
20556 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20557 				/*
20558 				 * It's an IPsec control message requesting
20559 				 * an SADB update to be sent to the IPsec
20560 				 * hardware acceleration capable ills.
20561 				 */
20562 				ipsec_ctl_t *ipsec_ctl =
20563 				    (ipsec_ctl_t *)mp->b_rptr;
20564 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20565 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20566 				mblk_t *cmp = mp->b_cont;
20567 
20568 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20569 				ASSERT(cmp != NULL);
20570 
20571 				freeb(mp);
20572 				ill_ipsec_capab_send_all(satype, cmp, sa,
20573 				    ipst->ips_netstack);
20574 				return;
20575 			} else {
20576 				/*
20577 				 * This must be ARP or special TSOL signaling.
20578 				 */
20579 				ip_wput_nondata(NULL, q, mp, NULL);
20580 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20581 				    "ip_wput_end: q %p (%S)", q, "nondata");
20582 				return;
20583 			}
20584 		} else {
20585 			/*
20586 			 * This must be non-(ARP/AH/ESP) messages.
20587 			 */
20588 			ASSERT(!need_decref);
20589 			ip_wput_nondata(NULL, q, mp, NULL);
20590 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20591 			    "ip_wput_end: q %p (%S)", q, "nondata");
20592 			return;
20593 		}
20594 	} else {
20595 		first_mp = mp;
20596 		mctl_present = B_FALSE;
20597 	}
20598 
20599 	ASSERT(first_mp != NULL);
20600 	/*
20601 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20602 	 * to make sure that this packet goes out on the same interface it
20603 	 * came in. We handle that here.
20604 	 */
20605 	if (mctl_present) {
20606 		uint_t ifindex;
20607 
20608 		io = (ipsec_out_t *)first_mp->b_rptr;
20609 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20610 			/*
20611 			 * We may have lost the conn context if we are
20612 			 * coming here from ip_newroute(). Copy the
20613 			 * nexthop information.
20614 			 */
20615 			if (io->ipsec_out_ip_nexthop) {
20616 				ip_nexthop = B_TRUE;
20617 				nexthop_addr = io->ipsec_out_nexthop_addr;
20618 
20619 				ipha = (ipha_t *)mp->b_rptr;
20620 				dst = ipha->ipha_dst;
20621 				goto send_from_ill;
20622 			} else {
20623 				ASSERT(io->ipsec_out_ill_index != 0);
20624 				ifindex = io->ipsec_out_ill_index;
20625 				attach_ill = ill_lookup_on_ifindex(ifindex,
20626 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20627 				if (attach_ill == NULL) {
20628 					ASSERT(xmit_ill == NULL);
20629 					ip1dbg(("ip_output: bad ifindex for "
20630 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20631 					    ifindex));
20632 					freemsg(first_mp);
20633 					BUMP_MIB(&ipst->ips_ip_mib,
20634 					    ipIfStatsOutDiscards);
20635 					ASSERT(!need_decref);
20636 					return;
20637 				}
20638 			}
20639 		}
20640 	}
20641 
20642 	ASSERT(xmit_ill == NULL);
20643 
20644 	/* We have a complete IP datagram heading outbound. */
20645 	ipha = (ipha_t *)mp->b_rptr;
20646 
20647 #ifndef SPEED_BEFORE_SAFETY
20648 	/*
20649 	 * Make sure we have a full-word aligned message and that at least
20650 	 * a simple IP header is accessible in the first message.  If not,
20651 	 * try a pullup.
20652 	 */
20653 	if (!OK_32PTR(rptr) ||
20654 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20655 hdrtoosmall:
20656 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20657 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20658 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20659 			if (first_mp == NULL)
20660 				first_mp = mp;
20661 			goto discard_pkt;
20662 		}
20663 
20664 		/* This function assumes that mp points to an IPv4 packet. */
20665 		if (is_system_labeled() && q->q_next == NULL &&
20666 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20667 		    !connp->conn_ulp_labeled) {
20668 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20669 			    &adjust, connp->conn_mac_exempt, ipst);
20670 			ipha = (ipha_t *)mp->b_rptr;
20671 			if (first_mp != NULL)
20672 				first_mp->b_cont = mp;
20673 			if (err != 0) {
20674 				if (first_mp == NULL)
20675 					first_mp = mp;
20676 				if (err == EINVAL)
20677 					goto icmp_parameter_problem;
20678 				ip2dbg(("ip_wput: label check failed (%d)\n",
20679 				    err));
20680 				goto discard_pkt;
20681 			}
20682 			iplen = ntohs(ipha->ipha_length) + adjust;
20683 			ipha->ipha_length = htons(iplen);
20684 		}
20685 
20686 		ipha = (ipha_t *)mp->b_rptr;
20687 		if (first_mp == NULL) {
20688 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20689 			/*
20690 			 * If we got here because of "goto hdrtoosmall"
20691 			 * We need to attach a IPSEC_OUT.
20692 			 */
20693 			if (connp->conn_out_enforce_policy) {
20694 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20695 				    NULL, ipha->ipha_protocol,
20696 				    ipst->ips_netstack)) == NULL)) {
20697 					BUMP_MIB(&ipst->ips_ip_mib,
20698 					    ipIfStatsOutDiscards);
20699 					if (need_decref)
20700 						CONN_DEC_REF(connp);
20701 					return;
20702 				} else {
20703 					ASSERT(mp->b_datap->db_type == M_CTL);
20704 					first_mp = mp;
20705 					mp = mp->b_cont;
20706 					mctl_present = B_TRUE;
20707 				}
20708 			} else {
20709 				first_mp = mp;
20710 				mctl_present = B_FALSE;
20711 			}
20712 		}
20713 	}
20714 #endif
20715 
20716 	/* Most of the code below is written for speed, not readability */
20717 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20718 
20719 	/*
20720 	 * If ip_newroute() fails, we're going to need a full
20721 	 * header for the icmp wraparound.
20722 	 */
20723 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20724 		uint_t	v_hlen;
20725 version_hdrlen_check:
20726 		ASSERT(first_mp != NULL);
20727 		v_hlen = V_HLEN;
20728 		/*
20729 		 * siphon off IPv6 packets coming down from transport
20730 		 * layer modules here.
20731 		 * Note: high-order bit carries NUD reachability confirmation
20732 		 */
20733 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20734 			/*
20735 			 * XXX implement a IPv4 and IPv6 packet counter per
20736 			 * conn and switch when ratio exceeds e.g. 10:1
20737 			 */
20738 #ifdef notyet
20739 			if (q->q_next == NULL) /* Avoid ill queue */
20740 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
20741 #endif
20742 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20743 			ASSERT(xmit_ill == NULL);
20744 			if (attach_ill != NULL)
20745 				ill_refrele(attach_ill);
20746 			if (need_decref)
20747 				mp->b_flag |= MSGHASREF;
20748 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20749 			return;
20750 		}
20751 
20752 		if ((v_hlen >> 4) != IP_VERSION) {
20753 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20754 			    "ip_wput_end: q %p (%S)", q, "badvers");
20755 			goto discard_pkt;
20756 		}
20757 		/*
20758 		 * Is the header length at least 20 bytes?
20759 		 *
20760 		 * Are there enough bytes accessible in the header?  If
20761 		 * not, try a pullup.
20762 		 */
20763 		v_hlen &= 0xF;
20764 		v_hlen <<= 2;
20765 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20766 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20767 			    "ip_wput_end: q %p (%S)", q, "badlen");
20768 			goto discard_pkt;
20769 		}
20770 		if (v_hlen > (mp->b_wptr - rptr)) {
20771 			if (!pullupmsg(mp, v_hlen)) {
20772 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20773 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20774 				goto discard_pkt;
20775 			}
20776 			ipha = (ipha_t *)mp->b_rptr;
20777 		}
20778 		/*
20779 		 * Move first entry from any source route into ipha_dst and
20780 		 * verify the options
20781 		 */
20782 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20783 		    zoneid, ipst)) {
20784 			ASSERT(xmit_ill == NULL);
20785 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20786 			if (attach_ill != NULL)
20787 				ill_refrele(attach_ill);
20788 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20789 			    "ip_wput_end: q %p (%S)", q, "badopts");
20790 			if (need_decref)
20791 				CONN_DEC_REF(connp);
20792 			return;
20793 		}
20794 	}
20795 	dst = ipha->ipha_dst;
20796 
20797 	/*
20798 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20799 	 * we have to run the packet through ip_newroute which will take
20800 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20801 	 * a resolver, or assigning a default gateway, etc.
20802 	 */
20803 	if (CLASSD(dst)) {
20804 		ipif_t	*ipif;
20805 		uint32_t setsrc = 0;
20806 
20807 multicast:
20808 		ASSERT(first_mp != NULL);
20809 		ip2dbg(("ip_wput: CLASSD\n"));
20810 		if (connp == NULL) {
20811 			/*
20812 			 * Use the first good ipif on the ill.
20813 			 * XXX Should this ever happen? (Appears
20814 			 * to show up with just ppp and no ethernet due
20815 			 * to in.rdisc.)
20816 			 * However, ire_send should be able to
20817 			 * call ip_wput_ire directly.
20818 			 *
20819 			 * XXX Also, this can happen for ICMP and other packets
20820 			 * with multicast source addresses.  Perhaps we should
20821 			 * fix things so that we drop the packet in question,
20822 			 * but for now, just run with it.
20823 			 */
20824 			ill_t *ill = (ill_t *)q->q_ptr;
20825 
20826 			/*
20827 			 * Don't honor attach_if for this case. If ill
20828 			 * is part of the group, ipif could belong to
20829 			 * any ill and we cannot maintain attach_ill
20830 			 * and ipif_ill same anymore and the assert
20831 			 * below would fail.
20832 			 */
20833 			if (mctl_present && io->ipsec_out_attach_if) {
20834 				io->ipsec_out_ill_index = 0;
20835 				io->ipsec_out_attach_if = B_FALSE;
20836 				ASSERT(attach_ill != NULL);
20837 				ill_refrele(attach_ill);
20838 				attach_ill = NULL;
20839 			}
20840 
20841 			ASSERT(attach_ill == NULL);
20842 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20843 			if (ipif == NULL) {
20844 				if (need_decref)
20845 					CONN_DEC_REF(connp);
20846 				freemsg(first_mp);
20847 				return;
20848 			}
20849 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20850 			    ntohl(dst), ill->ill_name));
20851 		} else {
20852 			/*
20853 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
20854 			 * and IP_MULTICAST_IF.
20855 			 * Block comment above this function explains the
20856 			 * locking mechanism used here
20857 			 */
20858 			if (xmit_ill == NULL) {
20859 				xmit_ill = conn_get_held_ill(connp,
20860 				    &connp->conn_xmit_if_ill, &err);
20861 				if (err == ILL_LOOKUP_FAILED) {
20862 					ip1dbg(("ip_wput: No ill for "
20863 					    "IP_XMIT_IF\n"));
20864 					BUMP_MIB(&ipst->ips_ip_mib,
20865 					    ipIfStatsOutNoRoutes);
20866 					goto drop_pkt;
20867 				}
20868 			}
20869 
20870 			if (xmit_ill == NULL) {
20871 				ipif = conn_get_held_ipif(connp,
20872 				    &connp->conn_multicast_ipif, &err);
20873 				if (err == IPIF_LOOKUP_FAILED) {
20874 					ip1dbg(("ip_wput: No ipif for "
20875 					    "multicast\n"));
20876 					BUMP_MIB(&ipst->ips_ip_mib,
20877 					    ipIfStatsOutNoRoutes);
20878 					goto drop_pkt;
20879 				}
20880 			}
20881 			if (xmit_ill != NULL) {
20882 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20883 				if (ipif == NULL) {
20884 					ip1dbg(("ip_wput: No ipif for "
20885 					    "IP_XMIT_IF\n"));
20886 					BUMP_MIB(&ipst->ips_ip_mib,
20887 					    ipIfStatsOutNoRoutes);
20888 					goto drop_pkt;
20889 				}
20890 			} else if (ipif == NULL || ipif->ipif_isv6) {
20891 				/*
20892 				 * We must do this ipif determination here
20893 				 * else we could pass through ip_newroute
20894 				 * and come back here without the conn context.
20895 				 *
20896 				 * Note: we do late binding i.e. we bind to
20897 				 * the interface when the first packet is sent.
20898 				 * For performance reasons we do not rebind on
20899 				 * each packet but keep the binding until the
20900 				 * next IP_MULTICAST_IF option.
20901 				 *
20902 				 * conn_multicast_{ipif,ill} are shared between
20903 				 * IPv4 and IPv6 and AF_INET6 sockets can
20904 				 * send both IPv4 and IPv6 packets. Hence
20905 				 * we have to check that "isv6" matches above.
20906 				 */
20907 				if (ipif != NULL)
20908 					ipif_refrele(ipif);
20909 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20910 				if (ipif == NULL) {
20911 					ip1dbg(("ip_wput: No ipif for "
20912 					    "multicast\n"));
20913 					BUMP_MIB(&ipst->ips_ip_mib,
20914 					    ipIfStatsOutNoRoutes);
20915 					goto drop_pkt;
20916 				}
20917 				err = conn_set_held_ipif(connp,
20918 				    &connp->conn_multicast_ipif, ipif);
20919 				if (err == IPIF_LOOKUP_FAILED) {
20920 					ipif_refrele(ipif);
20921 					ip1dbg(("ip_wput: No ipif for "
20922 					    "multicast\n"));
20923 					BUMP_MIB(&ipst->ips_ip_mib,
20924 					    ipIfStatsOutNoRoutes);
20925 					goto drop_pkt;
20926 				}
20927 			}
20928 		}
20929 		ASSERT(!ipif->ipif_isv6);
20930 		/*
20931 		 * As we may lose the conn by the time we reach ip_wput_ire,
20932 		 * we copy conn_multicast_loop and conn_dontroute on to an
20933 		 * ipsec_out. In case if this datagram goes out secure,
20934 		 * we need the ill_index also. Copy that also into the
20935 		 * ipsec_out.
20936 		 */
20937 		if (mctl_present) {
20938 			io = (ipsec_out_t *)first_mp->b_rptr;
20939 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20940 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20941 		} else {
20942 			ASSERT(mp == first_mp);
20943 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20944 			    BPRI_HI)) == NULL) {
20945 				ipif_refrele(ipif);
20946 				first_mp = mp;
20947 				goto discard_pkt;
20948 			}
20949 			first_mp->b_datap->db_type = M_CTL;
20950 			first_mp->b_wptr += sizeof (ipsec_info_t);
20951 			/* ipsec_out_secure is B_FALSE now */
20952 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20953 			io = (ipsec_out_t *)first_mp->b_rptr;
20954 			io->ipsec_out_type = IPSEC_OUT;
20955 			io->ipsec_out_len = sizeof (ipsec_out_t);
20956 			io->ipsec_out_use_global_policy = B_TRUE;
20957 			io->ipsec_out_ns = ipst->ips_netstack;
20958 			first_mp->b_cont = mp;
20959 			mctl_present = B_TRUE;
20960 		}
20961 		if (attach_ill != NULL) {
20962 			ASSERT(attach_ill == ipif->ipif_ill);
20963 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20964 
20965 			/*
20966 			 * Check if we need an ire that will not be
20967 			 * looked up by anybody else i.e. HIDDEN.
20968 			 */
20969 			if (ill_is_probeonly(attach_ill)) {
20970 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20971 			}
20972 			io->ipsec_out_ill_index =
20973 			    attach_ill->ill_phyint->phyint_ifindex;
20974 			io->ipsec_out_attach_if = B_TRUE;
20975 		} else {
20976 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20977 			io->ipsec_out_ill_index =
20978 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20979 		}
20980 		if (connp != NULL) {
20981 			io->ipsec_out_multicast_loop =
20982 			    connp->conn_multicast_loop;
20983 			io->ipsec_out_dontroute = connp->conn_dontroute;
20984 			io->ipsec_out_zoneid = connp->conn_zoneid;
20985 		}
20986 		/*
20987 		 * If the application uses IP_MULTICAST_IF with
20988 		 * different logical addresses of the same ILL, we
20989 		 * need to make sure that the soruce address of
20990 		 * the packet matches the logical IP address used
20991 		 * in the option. We do it by initializing ipha_src
20992 		 * here. This should keep IPsec also happy as
20993 		 * when we return from IPsec processing, we don't
20994 		 * have to worry about getting the right address on
20995 		 * the packet. Thus it is sufficient to look for
20996 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20997 		 * MATCH_IRE_IPIF.
20998 		 *
20999 		 * NOTE : We need to do it for non-secure case also as
21000 		 * this might go out secure if there is a global policy
21001 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21002 		 * address, the source should be initialized already and
21003 		 * hence we won't be initializing here.
21004 		 *
21005 		 * As we do not have the ire yet, it is possible that
21006 		 * we set the source address here and then later discover
21007 		 * that the ire implies the source address to be assigned
21008 		 * through the RTF_SETSRC flag.
21009 		 * In that case, the setsrc variable will remind us
21010 		 * that overwritting the source address by the one
21011 		 * of the RTF_SETSRC-flagged ire is allowed.
21012 		 */
21013 		if (ipha->ipha_src == INADDR_ANY &&
21014 		    (connp == NULL || !connp->conn_unspec_src)) {
21015 			ipha->ipha_src = ipif->ipif_src_addr;
21016 			setsrc = RTF_SETSRC;
21017 		}
21018 		/*
21019 		 * Find an IRE which matches the destination and the outgoing
21020 		 * queue (i.e. the outgoing interface.)
21021 		 * For loopback use a unicast IP address for
21022 		 * the ire lookup.
21023 		 */
21024 		if (IS_LOOPBACK(ipif->ipif_ill))
21025 			dst = ipif->ipif_lcl_addr;
21026 
21027 		/*
21028 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21029 		 * We don't need to lookup ire in ctable as the packet
21030 		 * needs to be sent to the destination through the specified
21031 		 * ill irrespective of ires in the cache table.
21032 		 */
21033 		ire = NULL;
21034 		if (xmit_ill == NULL) {
21035 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21036 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21037 		}
21038 
21039 		/*
21040 		 * refrele attach_ill as its not needed anymore.
21041 		 */
21042 		if (attach_ill != NULL) {
21043 			ill_refrele(attach_ill);
21044 			attach_ill = NULL;
21045 		}
21046 
21047 		if (ire == NULL) {
21048 			/*
21049 			 * Multicast loopback and multicast forwarding is
21050 			 * done in ip_wput_ire.
21051 			 *
21052 			 * Mark this packet to make it be delivered to
21053 			 * ip_wput_ire after the new ire has been
21054 			 * created.
21055 			 *
21056 			 * The call to ip_newroute_ipif takes into account
21057 			 * the setsrc reminder. In any case, we take care
21058 			 * of the RTF_MULTIRT flag.
21059 			 */
21060 			mp->b_prev = mp->b_next = NULL;
21061 			if (xmit_ill == NULL ||
21062 			    xmit_ill->ill_ipif_up_count > 0) {
21063 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21064 				    setsrc | RTF_MULTIRT, zoneid, infop);
21065 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21066 				    "ip_wput_end: q %p (%S)", q, "noire");
21067 			} else {
21068 				freemsg(first_mp);
21069 			}
21070 			ipif_refrele(ipif);
21071 			if (xmit_ill != NULL)
21072 				ill_refrele(xmit_ill);
21073 			if (need_decref)
21074 				CONN_DEC_REF(connp);
21075 			return;
21076 		}
21077 
21078 		ipif_refrele(ipif);
21079 		ipif = NULL;
21080 		ASSERT(xmit_ill == NULL);
21081 
21082 		/*
21083 		 * Honor the RTF_SETSRC flag for multicast packets,
21084 		 * if allowed by the setsrc reminder.
21085 		 */
21086 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21087 			ipha->ipha_src = ire->ire_src_addr;
21088 		}
21089 
21090 		/*
21091 		 * Unconditionally force the TTL to 1 for
21092 		 * multirouted multicast packets:
21093 		 * multirouted multicast should not cross
21094 		 * multicast routers.
21095 		 */
21096 		if (ire->ire_flags & RTF_MULTIRT) {
21097 			if (ipha->ipha_ttl > 1) {
21098 				ip2dbg(("ip_wput: forcing multicast "
21099 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21100 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21101 				ipha->ipha_ttl = 1;
21102 			}
21103 		}
21104 	} else {
21105 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21106 		if ((ire != NULL) && (ire->ire_type &
21107 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21108 			ignore_dontroute = B_TRUE;
21109 			ignore_nexthop = B_TRUE;
21110 		}
21111 		if (ire != NULL) {
21112 			ire_refrele(ire);
21113 			ire = NULL;
21114 		}
21115 		/*
21116 		 * Guard against coming in from arp in which case conn is NULL.
21117 		 * Also guard against non M_DATA with dontroute set but
21118 		 * destined to local, loopback or broadcast addresses.
21119 		 */
21120 		if (connp != NULL && connp->conn_dontroute &&
21121 		    !ignore_dontroute) {
21122 dontroute:
21123 			/*
21124 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21125 			 * routing protocols from seeing false direct
21126 			 * connectivity.
21127 			 */
21128 			ipha->ipha_ttl = 1;
21129 			/*
21130 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21131 			 * along with SO_DONTROUTE, higher precedence is
21132 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21133 			 */
21134 			if (connp->conn_xmit_if_ill == NULL) {
21135 				/* If suitable ipif not found, drop packet */
21136 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21137 				    ipst);
21138 				if (dst_ipif == NULL) {
21139 					ip1dbg(("ip_wput: no route for "
21140 					    "dst using SO_DONTROUTE\n"));
21141 					BUMP_MIB(&ipst->ips_ip_mib,
21142 					    ipIfStatsOutNoRoutes);
21143 					mp->b_prev = mp->b_next = NULL;
21144 					if (first_mp == NULL)
21145 						first_mp = mp;
21146 					goto drop_pkt;
21147 				} else {
21148 					/*
21149 					 * If suitable ipif has been found, set
21150 					 * xmit_ill to the corresponding
21151 					 * ipif_ill because we'll be following
21152 					 * the IP_XMIT_IF logic.
21153 					 */
21154 					ASSERT(xmit_ill == NULL);
21155 					xmit_ill = dst_ipif->ipif_ill;
21156 					mutex_enter(&xmit_ill->ill_lock);
21157 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21158 						mutex_exit(&xmit_ill->ill_lock);
21159 						xmit_ill = NULL;
21160 						ipif_refrele(dst_ipif);
21161 						ip1dbg(("ip_wput: no route for"
21162 						    " dst using"
21163 						    " SO_DONTROUTE\n"));
21164 						BUMP_MIB(&ipst->ips_ip_mib,
21165 						    ipIfStatsOutNoRoutes);
21166 						mp->b_prev = mp->b_next = NULL;
21167 						if (first_mp == NULL)
21168 							first_mp = mp;
21169 						goto drop_pkt;
21170 					}
21171 					ill_refhold_locked(xmit_ill);
21172 					mutex_exit(&xmit_ill->ill_lock);
21173 					ipif_refrele(dst_ipif);
21174 				}
21175 			}
21176 
21177 		}
21178 		/*
21179 		 * If we are bound to IPIF_NOFAILOVER address, look for
21180 		 * an IRE_CACHE matching the ill.
21181 		 */
21182 send_from_ill:
21183 		if (attach_ill != NULL) {
21184 			ipif_t	*attach_ipif;
21185 
21186 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21187 
21188 			/*
21189 			 * Check if we need an ire that will not be
21190 			 * looked up by anybody else i.e. HIDDEN.
21191 			 */
21192 			if (ill_is_probeonly(attach_ill)) {
21193 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21194 			}
21195 
21196 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21197 			if (attach_ipif == NULL) {
21198 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21199 				goto discard_pkt;
21200 			}
21201 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21202 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21203 			ipif_refrele(attach_ipif);
21204 		} else if (xmit_ill != NULL || (connp != NULL &&
21205 		    connp->conn_xmit_if_ill != NULL)) {
21206 			/*
21207 			 * Mark this packet as originated locally
21208 			 */
21209 			mp->b_prev = mp->b_next = NULL;
21210 			/*
21211 			 * xmit_ill could be NULL if SO_DONTROUTE
21212 			 * is also set.
21213 			 */
21214 			if (xmit_ill == NULL) {
21215 				xmit_ill = conn_get_held_ill(connp,
21216 				    &connp->conn_xmit_if_ill, &err);
21217 				if (err == ILL_LOOKUP_FAILED) {
21218 					BUMP_MIB(&ipst->ips_ip_mib,
21219 					    ipIfStatsOutDiscards);
21220 					if (need_decref)
21221 						CONN_DEC_REF(connp);
21222 					freemsg(first_mp);
21223 					return;
21224 				}
21225 				if (xmit_ill == NULL) {
21226 					if (connp->conn_dontroute)
21227 						goto dontroute;
21228 					goto send_from_ill;
21229 				}
21230 			}
21231 			/*
21232 			 * Could be SO_DONTROUTE case also.
21233 			 * check at least one interface is UP as
21234 			 * specified by this ILL
21235 			 */
21236 			if (xmit_ill->ill_ipif_up_count > 0) {
21237 				ipif_t *ipif;
21238 
21239 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21240 				if (ipif == NULL) {
21241 					ip1dbg(("ip_output: "
21242 					    "xmit_ill NULL ipif\n"));
21243 					goto drop_pkt;
21244 				}
21245 				/*
21246 				 * Look for a ire that is part of the group,
21247 				 * if found use it else call ip_newroute_ipif.
21248 				 * IPCL_ZONEID is not used for matching because
21249 				 * IP_ALLZONES option is valid only when the
21250 				 * ill is accessible from all zones i.e has a
21251 				 * valid ipif in all zones.
21252 				 */
21253 				match_flags = MATCH_IRE_ILL_GROUP |
21254 				    MATCH_IRE_SECATTR;
21255 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21256 				    MBLK_GETLABEL(mp), match_flags, ipst);
21257 				/*
21258 				 * If an ire exists use it or else create
21259 				 * an ire but don't add it to the cache.
21260 				 * Adding an ire may cause issues with
21261 				 * asymmetric routing.
21262 				 * In case of multiroute always act as if
21263 				 * ire does not exist.
21264 				 */
21265 				if (ire == NULL ||
21266 				    ire->ire_flags & RTF_MULTIRT) {
21267 					if (ire != NULL)
21268 						ire_refrele(ire);
21269 					ip_newroute_ipif(q, first_mp, ipif,
21270 					    dst, connp, 0, zoneid, infop);
21271 					ipif_refrele(ipif);
21272 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21273 					ill_refrele(xmit_ill);
21274 					if (need_decref)
21275 						CONN_DEC_REF(connp);
21276 					return;
21277 				}
21278 				ipif_refrele(ipif);
21279 			} else {
21280 				goto drop_pkt;
21281 			}
21282 		} else if (ip_nexthop || (connp != NULL &&
21283 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21284 			if (!ip_nexthop) {
21285 				ip_nexthop = B_TRUE;
21286 				nexthop_addr = connp->conn_nexthop_v4;
21287 			}
21288 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21289 			    MATCH_IRE_GW;
21290 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21291 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21292 		} else {
21293 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21294 			    ipst);
21295 		}
21296 		if (!ire) {
21297 			/*
21298 			 * Make sure we don't load spread if this
21299 			 * is IPIF_NOFAILOVER case.
21300 			 */
21301 			if ((attach_ill != NULL) ||
21302 			    (ip_nexthop && !ignore_nexthop)) {
21303 				if (mctl_present) {
21304 					io = (ipsec_out_t *)first_mp->b_rptr;
21305 					ASSERT(first_mp->b_datap->db_type ==
21306 					    M_CTL);
21307 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21308 				} else {
21309 					ASSERT(mp == first_mp);
21310 					first_mp = allocb(
21311 					    sizeof (ipsec_info_t), BPRI_HI);
21312 					if (first_mp == NULL) {
21313 						first_mp = mp;
21314 						goto discard_pkt;
21315 					}
21316 					first_mp->b_datap->db_type = M_CTL;
21317 					first_mp->b_wptr +=
21318 					    sizeof (ipsec_info_t);
21319 					/* ipsec_out_secure is B_FALSE now */
21320 					bzero(first_mp->b_rptr,
21321 					    sizeof (ipsec_info_t));
21322 					io = (ipsec_out_t *)first_mp->b_rptr;
21323 					io->ipsec_out_type = IPSEC_OUT;
21324 					io->ipsec_out_len =
21325 					    sizeof (ipsec_out_t);
21326 					io->ipsec_out_use_global_policy =
21327 					    B_TRUE;
21328 					io->ipsec_out_ns = ipst->ips_netstack;
21329 					first_mp->b_cont = mp;
21330 					mctl_present = B_TRUE;
21331 				}
21332 				if (attach_ill != NULL) {
21333 					io->ipsec_out_ill_index = attach_ill->
21334 					    ill_phyint->phyint_ifindex;
21335 					io->ipsec_out_attach_if = B_TRUE;
21336 				} else {
21337 					io->ipsec_out_ip_nexthop = ip_nexthop;
21338 					io->ipsec_out_nexthop_addr =
21339 					    nexthop_addr;
21340 				}
21341 			}
21342 noirefound:
21343 			/*
21344 			 * Mark this packet as having originated on
21345 			 * this machine.  This will be noted in
21346 			 * ire_add_then_send, which needs to know
21347 			 * whether to run it back through ip_wput or
21348 			 * ip_rput following successful resolution.
21349 			 */
21350 			mp->b_prev = NULL;
21351 			mp->b_next = NULL;
21352 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21353 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21354 			    "ip_wput_end: q %p (%S)", q, "newroute");
21355 			if (attach_ill != NULL)
21356 				ill_refrele(attach_ill);
21357 			if (xmit_ill != NULL)
21358 				ill_refrele(xmit_ill);
21359 			if (need_decref)
21360 				CONN_DEC_REF(connp);
21361 			return;
21362 		}
21363 	}
21364 
21365 	/* We now know where we are going with it. */
21366 
21367 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21368 	    "ip_wput_end: q %p (%S)", q, "end");
21369 
21370 	/*
21371 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21372 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21373 	 */
21374 	if (ire->ire_flags & RTF_MULTIRT) {
21375 		/*
21376 		 * Force the TTL of multirouted packets if required.
21377 		 * The TTL of such packets is bounded by the
21378 		 * ip_multirt_ttl ndd variable.
21379 		 */
21380 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21381 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21382 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21383 			    "(was %d), dst 0x%08x\n",
21384 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21385 			    ntohl(ire->ire_addr)));
21386 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21387 		}
21388 		/*
21389 		 * At this point, we check to see if there are any pending
21390 		 * unresolved routes. ire_multirt_resolvable()
21391 		 * checks in O(n) that all IRE_OFFSUBNET ire
21392 		 * entries for the packet's destination and
21393 		 * flagged RTF_MULTIRT are currently resolved.
21394 		 * If some remain unresolved, we make a copy
21395 		 * of the current message. It will be used
21396 		 * to initiate additional route resolutions.
21397 		 */
21398 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21399 		    MBLK_GETLABEL(first_mp), ipst);
21400 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21401 		    "multirt_need_resolve %d, first_mp %p\n",
21402 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21403 		if (multirt_need_resolve) {
21404 			copy_mp = copymsg(first_mp);
21405 			if (copy_mp != NULL) {
21406 				MULTIRT_DEBUG_TAG(copy_mp);
21407 			}
21408 		}
21409 	}
21410 
21411 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21412 	/*
21413 	 * Try to resolve another multiroute if
21414 	 * ire_multirt_resolvable() deemed it necessary.
21415 	 * At this point, we need to distinguish
21416 	 * multicasts from other packets. For multicasts,
21417 	 * we call ip_newroute_ipif() and request that both
21418 	 * multirouting and setsrc flags are checked.
21419 	 */
21420 	if (copy_mp != NULL) {
21421 		if (CLASSD(dst)) {
21422 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21423 			if (ipif) {
21424 				ASSERT(infop->ip_opt_ill_index == 0);
21425 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21426 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21427 				ipif_refrele(ipif);
21428 			} else {
21429 				MULTIRT_DEBUG_UNTAG(copy_mp);
21430 				freemsg(copy_mp);
21431 				copy_mp = NULL;
21432 			}
21433 		} else {
21434 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21435 		}
21436 	}
21437 	if (attach_ill != NULL)
21438 		ill_refrele(attach_ill);
21439 	if (xmit_ill != NULL)
21440 		ill_refrele(xmit_ill);
21441 	if (need_decref)
21442 		CONN_DEC_REF(connp);
21443 	return;
21444 
21445 icmp_parameter_problem:
21446 	/* could not have originated externally */
21447 	ASSERT(mp->b_prev == NULL);
21448 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21449 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21450 		/* it's the IP header length that's in trouble */
21451 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21452 		first_mp = NULL;
21453 	}
21454 
21455 discard_pkt:
21456 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21457 drop_pkt:
21458 	ip1dbg(("ip_wput: dropped packet\n"));
21459 	if (ire != NULL)
21460 		ire_refrele(ire);
21461 	if (need_decref)
21462 		CONN_DEC_REF(connp);
21463 	freemsg(first_mp);
21464 	if (attach_ill != NULL)
21465 		ill_refrele(attach_ill);
21466 	if (xmit_ill != NULL)
21467 		ill_refrele(xmit_ill);
21468 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21469 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21470 }
21471 
21472 /*
21473  * If this is a conn_t queue, then we pass in the conn. This includes the
21474  * zoneid.
21475  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21476  * in which case we use the global zoneid since those are all part of
21477  * the global zone.
21478  */
21479 void
21480 ip_wput(queue_t *q, mblk_t *mp)
21481 {
21482 	if (CONN_Q(q))
21483 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21484 	else
21485 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21486 }
21487 
21488 /*
21489  *
21490  * The following rules must be observed when accessing any ipif or ill
21491  * that has been cached in the conn. Typically conn_nofailover_ill,
21492  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21493  *
21494  * Access: The ipif or ill pointed to from the conn can be accessed under
21495  * the protection of the conn_lock or after it has been refheld under the
21496  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21497  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21498  * The reason for this is that a concurrent unplumb could actually be
21499  * cleaning up these cached pointers by walking the conns and might have
21500  * finished cleaning up the conn in question. The macros check that an
21501  * unplumb has not yet started on the ipif or ill.
21502  *
21503  * Caching: An ipif or ill pointer may be cached in the conn only after
21504  * making sure that an unplumb has not started. So the caching is done
21505  * while holding both the conn_lock and the ill_lock and after using the
21506  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21507  * flag before starting the cleanup of conns.
21508  *
21509  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21510  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21511  * or a reference to the ipif or a reference to an ire that references the
21512  * ipif. An ipif does not change its ill except for failover/failback. Since
21513  * failover/failback happens only after bringing down the ipif and making sure
21514  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21515  * the above holds.
21516  */
21517 ipif_t *
21518 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21519 {
21520 	ipif_t	*ipif;
21521 	ill_t	*ill;
21522 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21523 
21524 	*err = 0;
21525 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21526 	mutex_enter(&connp->conn_lock);
21527 	ipif = *ipifp;
21528 	if (ipif != NULL) {
21529 		ill = ipif->ipif_ill;
21530 		mutex_enter(&ill->ill_lock);
21531 		if (IPIF_CAN_LOOKUP(ipif)) {
21532 			ipif_refhold_locked(ipif);
21533 			mutex_exit(&ill->ill_lock);
21534 			mutex_exit(&connp->conn_lock);
21535 			rw_exit(&ipst->ips_ill_g_lock);
21536 			return (ipif);
21537 		} else {
21538 			*err = IPIF_LOOKUP_FAILED;
21539 		}
21540 		mutex_exit(&ill->ill_lock);
21541 	}
21542 	mutex_exit(&connp->conn_lock);
21543 	rw_exit(&ipst->ips_ill_g_lock);
21544 	return (NULL);
21545 }
21546 
21547 ill_t *
21548 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21549 {
21550 	ill_t	*ill;
21551 
21552 	*err = 0;
21553 	mutex_enter(&connp->conn_lock);
21554 	ill = *illp;
21555 	if (ill != NULL) {
21556 		mutex_enter(&ill->ill_lock);
21557 		if (ILL_CAN_LOOKUP(ill)) {
21558 			ill_refhold_locked(ill);
21559 			mutex_exit(&ill->ill_lock);
21560 			mutex_exit(&connp->conn_lock);
21561 			return (ill);
21562 		} else {
21563 			*err = ILL_LOOKUP_FAILED;
21564 		}
21565 		mutex_exit(&ill->ill_lock);
21566 	}
21567 	mutex_exit(&connp->conn_lock);
21568 	return (NULL);
21569 }
21570 
21571 static int
21572 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21573 {
21574 	ill_t	*ill;
21575 
21576 	ill = ipif->ipif_ill;
21577 	mutex_enter(&connp->conn_lock);
21578 	mutex_enter(&ill->ill_lock);
21579 	if (IPIF_CAN_LOOKUP(ipif)) {
21580 		*ipifp = ipif;
21581 		mutex_exit(&ill->ill_lock);
21582 		mutex_exit(&connp->conn_lock);
21583 		return (0);
21584 	}
21585 	mutex_exit(&ill->ill_lock);
21586 	mutex_exit(&connp->conn_lock);
21587 	return (IPIF_LOOKUP_FAILED);
21588 }
21589 
21590 /*
21591  * This is called if the outbound datagram needs fragmentation.
21592  *
21593  * NOTE : This function does not ire_refrele the ire argument passed in.
21594  */
21595 static void
21596 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21597     ip_stack_t *ipst)
21598 {
21599 	ipha_t		*ipha;
21600 	mblk_t		*mp;
21601 	uint32_t	v_hlen_tos_len;
21602 	uint32_t	max_frag;
21603 	uint32_t	frag_flag;
21604 	boolean_t	dont_use;
21605 
21606 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21607 		mp = ipsec_mp->b_cont;
21608 	} else {
21609 		mp = ipsec_mp;
21610 	}
21611 
21612 	ipha = (ipha_t *)mp->b_rptr;
21613 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21614 
21615 #ifdef	_BIG_ENDIAN
21616 #define	V_HLEN	(v_hlen_tos_len >> 24)
21617 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21618 #else
21619 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21620 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21621 #endif
21622 
21623 #ifndef SPEED_BEFORE_SAFETY
21624 	/*
21625 	 * Check that ipha_length is consistent with
21626 	 * the mblk length
21627 	 */
21628 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21629 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21630 		    LENGTH, msgdsize(mp)));
21631 		freemsg(ipsec_mp);
21632 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21633 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21634 		    "packet length mismatch");
21635 		return;
21636 	}
21637 #endif
21638 	/*
21639 	 * Don't use frag_flag if pre-built packet or source
21640 	 * routed or if multicast (since multicast packets do not solicit
21641 	 * ICMP "packet too big" messages). Get the values of
21642 	 * max_frag and frag_flag atomically by acquiring the
21643 	 * ire_lock.
21644 	 */
21645 	mutex_enter(&ire->ire_lock);
21646 	max_frag = ire->ire_max_frag;
21647 	frag_flag = ire->ire_frag_flag;
21648 	mutex_exit(&ire->ire_lock);
21649 
21650 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21651 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21652 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21653 
21654 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21655 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21656 }
21657 
21658 /*
21659  * Used for deciding the MSS size for the upper layer. Thus
21660  * we need to check the outbound policy values in the conn.
21661  */
21662 int
21663 conn_ipsec_length(conn_t *connp)
21664 {
21665 	ipsec_latch_t *ipl;
21666 
21667 	ipl = connp->conn_latch;
21668 	if (ipl == NULL)
21669 		return (0);
21670 
21671 	if (ipl->ipl_out_policy == NULL)
21672 		return (0);
21673 
21674 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21675 }
21676 
21677 /*
21678  * Returns an estimate of the IPsec headers size. This is used if
21679  * we don't want to call into IPsec to get the exact size.
21680  */
21681 int
21682 ipsec_out_extra_length(mblk_t *ipsec_mp)
21683 {
21684 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21685 	ipsec_action_t *a;
21686 
21687 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21688 	if (!io->ipsec_out_secure)
21689 		return (0);
21690 
21691 	a = io->ipsec_out_act;
21692 
21693 	if (a == NULL) {
21694 		ASSERT(io->ipsec_out_policy != NULL);
21695 		a = io->ipsec_out_policy->ipsp_act;
21696 	}
21697 	ASSERT(a != NULL);
21698 
21699 	return (a->ipa_ovhd);
21700 }
21701 
21702 /*
21703  * Returns an estimate of the IPsec headers size. This is used if
21704  * we don't want to call into IPsec to get the exact size.
21705  */
21706 int
21707 ipsec_in_extra_length(mblk_t *ipsec_mp)
21708 {
21709 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21710 	ipsec_action_t *a;
21711 
21712 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21713 
21714 	a = ii->ipsec_in_action;
21715 	return (a == NULL ? 0 : a->ipa_ovhd);
21716 }
21717 
21718 /*
21719  * If there are any source route options, return the true final
21720  * destination. Otherwise, return the destination.
21721  */
21722 ipaddr_t
21723 ip_get_dst(ipha_t *ipha)
21724 {
21725 	ipoptp_t	opts;
21726 	uchar_t		*opt;
21727 	uint8_t		optval;
21728 	uint8_t		optlen;
21729 	ipaddr_t	dst;
21730 	uint32_t off;
21731 
21732 	dst = ipha->ipha_dst;
21733 
21734 	if (IS_SIMPLE_IPH(ipha))
21735 		return (dst);
21736 
21737 	for (optval = ipoptp_first(&opts, ipha);
21738 	    optval != IPOPT_EOL;
21739 	    optval = ipoptp_next(&opts)) {
21740 		opt = opts.ipoptp_cur;
21741 		optlen = opts.ipoptp_len;
21742 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21743 		switch (optval) {
21744 		case IPOPT_SSRR:
21745 		case IPOPT_LSRR:
21746 			off = opt[IPOPT_OFFSET];
21747 			/*
21748 			 * If one of the conditions is true, it means
21749 			 * end of options and dst already has the right
21750 			 * value.
21751 			 */
21752 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21753 				off = optlen - IP_ADDR_LEN;
21754 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21755 			}
21756 			return (dst);
21757 		default:
21758 			break;
21759 		}
21760 	}
21761 
21762 	return (dst);
21763 }
21764 
21765 mblk_t *
21766 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21767     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21768 {
21769 	ipsec_out_t	*io;
21770 	mblk_t		*first_mp;
21771 	boolean_t policy_present;
21772 	ip_stack_t	*ipst;
21773 	ipsec_stack_t	*ipss;
21774 
21775 	ASSERT(ire != NULL);
21776 	ipst = ire->ire_ipst;
21777 	ipss = ipst->ips_netstack->netstack_ipsec;
21778 
21779 	first_mp = mp;
21780 	if (mp->b_datap->db_type == M_CTL) {
21781 		io = (ipsec_out_t *)first_mp->b_rptr;
21782 		/*
21783 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21784 		 *
21785 		 * 1) There is per-socket policy (including cached global
21786 		 *    policy) or a policy on the IP-in-IP tunnel.
21787 		 * 2) There is no per-socket policy, but it is
21788 		 *    a multicast packet that needs to go out
21789 		 *    on a specific interface. This is the case
21790 		 *    where (ip_wput and ip_wput_multicast) attaches
21791 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21792 		 *
21793 		 * In case (2) we check with global policy to
21794 		 * see if there is a match and set the ill_index
21795 		 * appropriately so that we can lookup the ire
21796 		 * properly in ip_wput_ipsec_out.
21797 		 */
21798 
21799 		/*
21800 		 * ipsec_out_use_global_policy is set to B_FALSE
21801 		 * in ipsec_in_to_out(). Refer to that function for
21802 		 * details.
21803 		 */
21804 		if ((io->ipsec_out_latch == NULL) &&
21805 		    (io->ipsec_out_use_global_policy)) {
21806 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21807 			    ire, connp, unspec_src, zoneid));
21808 		}
21809 		if (!io->ipsec_out_secure) {
21810 			/*
21811 			 * If this is not a secure packet, drop
21812 			 * the IPSEC_OUT mp and treat it as a clear
21813 			 * packet. This happens when we are sending
21814 			 * a ICMP reply back to a clear packet. See
21815 			 * ipsec_in_to_out() for details.
21816 			 */
21817 			mp = first_mp->b_cont;
21818 			freeb(first_mp);
21819 		}
21820 		return (mp);
21821 	}
21822 	/*
21823 	 * See whether we need to attach a global policy here. We
21824 	 * don't depend on the conn (as it could be null) for deciding
21825 	 * what policy this datagram should go through because it
21826 	 * should have happened in ip_wput if there was some
21827 	 * policy. This normally happens for connections which are not
21828 	 * fully bound preventing us from caching policies in
21829 	 * ip_bind. Packets coming from the TCP listener/global queue
21830 	 * - which are non-hard_bound - could also be affected by
21831 	 * applying policy here.
21832 	 *
21833 	 * If this packet is coming from tcp global queue or listener,
21834 	 * we will be applying policy here.  This may not be *right*
21835 	 * if these packets are coming from the detached connection as
21836 	 * it could have gone in clear before. This happens only if a
21837 	 * TCP connection started when there is no policy and somebody
21838 	 * added policy before it became detached. Thus packets of the
21839 	 * detached connection could go out secure and the other end
21840 	 * would drop it because it will be expecting in clear. The
21841 	 * converse is not true i.e if somebody starts a TCP
21842 	 * connection and deletes the policy, all the packets will
21843 	 * still go out with the policy that existed before deleting
21844 	 * because ip_unbind sends up policy information which is used
21845 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21846 	 * TCP to attach a dummy IPSEC_OUT and set
21847 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21848 	 * affect performance for normal cases, we are not doing it.
21849 	 * Thus, set policy before starting any TCP connections.
21850 	 *
21851 	 * NOTE - We might apply policy even for a hard bound connection
21852 	 * - for which we cached policy in ip_bind - if somebody added
21853 	 * global policy after we inherited the policy in ip_bind.
21854 	 * This means that the packets that were going out in clear
21855 	 * previously would start going secure and hence get dropped
21856 	 * on the other side. To fix this, TCP attaches a dummy
21857 	 * ipsec_out and make sure that we don't apply global policy.
21858 	 */
21859 	if (ipha != NULL)
21860 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21861 	else
21862 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21863 	if (!policy_present)
21864 		return (mp);
21865 
21866 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21867 	    zoneid));
21868 }
21869 
21870 ire_t *
21871 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21872 {
21873 	ipaddr_t addr;
21874 	ire_t *save_ire;
21875 	irb_t *irb;
21876 	ill_group_t *illgrp;
21877 	int	err;
21878 
21879 	save_ire = ire;
21880 	addr = ire->ire_addr;
21881 
21882 	ASSERT(ire->ire_type == IRE_BROADCAST);
21883 
21884 	illgrp = connp->conn_outgoing_ill->ill_group;
21885 	if (illgrp == NULL) {
21886 		*conn_outgoing_ill = conn_get_held_ill(connp,
21887 		    &connp->conn_outgoing_ill, &err);
21888 		if (err == ILL_LOOKUP_FAILED) {
21889 			ire_refrele(save_ire);
21890 			return (NULL);
21891 		}
21892 		return (save_ire);
21893 	}
21894 	/*
21895 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21896 	 * If it is part of the group, we need to send on the ire
21897 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21898 	 * to this group. This is okay as IP_BOUND_IF really means
21899 	 * any ill in the group. We depend on the fact that the
21900 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21901 	 * if such an ire exists. This is possible only if you have
21902 	 * at least one ill in the group that has not failed.
21903 	 *
21904 	 * First get to the ire that matches the address and group.
21905 	 *
21906 	 * We don't look for an ire with a matching zoneid because a given zone
21907 	 * won't always have broadcast ires on all ills in the group.
21908 	 */
21909 	irb = ire->ire_bucket;
21910 	rw_enter(&irb->irb_lock, RW_READER);
21911 	if (ire->ire_marks & IRE_MARK_NORECV) {
21912 		/*
21913 		 * If the current zone only has an ire broadcast for this
21914 		 * address marked NORECV, the ire we want is ahead in the
21915 		 * bucket, so we look it up deliberately ignoring the zoneid.
21916 		 */
21917 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21918 			if (ire->ire_addr != addr)
21919 				continue;
21920 			/* skip over deleted ires */
21921 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21922 				continue;
21923 		}
21924 	}
21925 	while (ire != NULL) {
21926 		/*
21927 		 * If a new interface is coming up, we could end up
21928 		 * seeing the loopback ire and the non-loopback ire
21929 		 * may not have been added yet. So check for ire_stq
21930 		 */
21931 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21932 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21933 			break;
21934 		}
21935 		ire = ire->ire_next;
21936 	}
21937 	if (ire != NULL && ire->ire_addr == addr &&
21938 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21939 		IRE_REFHOLD(ire);
21940 		rw_exit(&irb->irb_lock);
21941 		ire_refrele(save_ire);
21942 		*conn_outgoing_ill = ire_to_ill(ire);
21943 		/*
21944 		 * Refhold the ill to make the conn_outgoing_ill
21945 		 * independent of the ire. ip_wput_ire goes in a loop
21946 		 * and may refrele the ire. Since we have an ire at this
21947 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21948 		 */
21949 		ill_refhold(*conn_outgoing_ill);
21950 		return (ire);
21951 	}
21952 	rw_exit(&irb->irb_lock);
21953 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21954 	/*
21955 	 * If we can't find a suitable ire, return the original ire.
21956 	 */
21957 	return (save_ire);
21958 }
21959 
21960 /*
21961  * This function does the ire_refrele of the ire passed in as the
21962  * argument. As this function looks up more ires i.e broadcast ires,
21963  * it needs to REFRELE them. Currently, for simplicity we don't
21964  * differentiate the one passed in and looked up here. We always
21965  * REFRELE.
21966  * IPQoS Notes:
21967  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21968  * IPsec packets are done in ipsec_out_process.
21969  *
21970  */
21971 void
21972 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21973     zoneid_t zoneid)
21974 {
21975 	ipha_t		*ipha;
21976 #define	rptr	((uchar_t *)ipha)
21977 	queue_t		*stq;
21978 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21979 	uint32_t	v_hlen_tos_len;
21980 	uint32_t	ttl_protocol;
21981 	ipaddr_t	src;
21982 	ipaddr_t	dst;
21983 	uint32_t	cksum;
21984 	ipaddr_t	orig_src;
21985 	ire_t		*ire1;
21986 	mblk_t		*next_mp;
21987 	uint_t		hlen;
21988 	uint16_t	*up;
21989 	uint32_t	max_frag = ire->ire_max_frag;
21990 	ill_t		*ill = ire_to_ill(ire);
21991 	int		clusterwide;
21992 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21993 	int		ipsec_len;
21994 	mblk_t		*first_mp;
21995 	ipsec_out_t	*io;
21996 	boolean_t	conn_dontroute;		/* conn value for multicast */
21997 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21998 	boolean_t	multicast_forward;	/* Should we forward ? */
21999 	boolean_t	unspec_src;
22000 	ill_t		*conn_outgoing_ill = NULL;
22001 	ill_t		*ire_ill;
22002 	ill_t		*ire1_ill;
22003 	ill_t		*out_ill;
22004 	uint32_t 	ill_index = 0;
22005 	boolean_t	multirt_send = B_FALSE;
22006 	int		err;
22007 	ipxmit_state_t	pktxmit_state;
22008 	ip_stack_t	*ipst = ire->ire_ipst;
22009 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22010 
22011 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22012 	    "ip_wput_ire_start: q %p", q);
22013 
22014 	multicast_forward = B_FALSE;
22015 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22016 
22017 	if (ire->ire_flags & RTF_MULTIRT) {
22018 		/*
22019 		 * Multirouting case. The bucket where ire is stored
22020 		 * probably holds other RTF_MULTIRT flagged ire
22021 		 * to the destination. In this call to ip_wput_ire,
22022 		 * we attempt to send the packet through all
22023 		 * those ires. Thus, we first ensure that ire is the
22024 		 * first RTF_MULTIRT ire in the bucket,
22025 		 * before walking the ire list.
22026 		 */
22027 		ire_t *first_ire;
22028 		irb_t *irb = ire->ire_bucket;
22029 		ASSERT(irb != NULL);
22030 
22031 		/* Make sure we do not omit any multiroute ire. */
22032 		IRB_REFHOLD(irb);
22033 		for (first_ire = irb->irb_ire;
22034 		    first_ire != NULL;
22035 		    first_ire = first_ire->ire_next) {
22036 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22037 			    (first_ire->ire_addr == ire->ire_addr) &&
22038 			    !(first_ire->ire_marks &
22039 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22040 				break;
22041 			}
22042 		}
22043 
22044 		if ((first_ire != NULL) && (first_ire != ire)) {
22045 			IRE_REFHOLD(first_ire);
22046 			ire_refrele(ire);
22047 			ire = first_ire;
22048 			ill = ire_to_ill(ire);
22049 		}
22050 		IRB_REFRELE(irb);
22051 	}
22052 
22053 	/*
22054 	 * conn_outgoing_ill is used only in the broadcast loop.
22055 	 * for performance we don't grab the mutexs in the fastpath
22056 	 */
22057 	if ((connp != NULL) &&
22058 	    (connp->conn_xmit_if_ill == NULL) &&
22059 	    (ire->ire_type == IRE_BROADCAST) &&
22060 	    ((connp->conn_nofailover_ill != NULL) ||
22061 	    (connp->conn_outgoing_ill != NULL))) {
22062 		/*
22063 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22064 		 * option. So, see if this endpoint is bound to a
22065 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22066 		 * that if the interface is failed, we will still send
22067 		 * the packet on the same ill which is what we want.
22068 		 */
22069 		conn_outgoing_ill = conn_get_held_ill(connp,
22070 		    &connp->conn_nofailover_ill, &err);
22071 		if (err == ILL_LOOKUP_FAILED) {
22072 			ire_refrele(ire);
22073 			freemsg(mp);
22074 			return;
22075 		}
22076 		if (conn_outgoing_ill == NULL) {
22077 			/*
22078 			 * Choose a good ill in the group to send the
22079 			 * packets on.
22080 			 */
22081 			ire = conn_set_outgoing_ill(connp, ire,
22082 			    &conn_outgoing_ill);
22083 			if (ire == NULL) {
22084 				freemsg(mp);
22085 				return;
22086 			}
22087 		}
22088 	}
22089 
22090 	if (mp->b_datap->db_type != M_CTL) {
22091 		ipha = (ipha_t *)mp->b_rptr;
22092 	} else {
22093 		io = (ipsec_out_t *)mp->b_rptr;
22094 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22095 		ASSERT(zoneid == io->ipsec_out_zoneid);
22096 		ASSERT(zoneid != ALL_ZONES);
22097 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22098 		dst = ipha->ipha_dst;
22099 		/*
22100 		 * For the multicast case, ipsec_out carries conn_dontroute and
22101 		 * conn_multicast_loop as conn may not be available here. We
22102 		 * need this for multicast loopback and forwarding which is done
22103 		 * later in the code.
22104 		 */
22105 		if (CLASSD(dst)) {
22106 			conn_dontroute = io->ipsec_out_dontroute;
22107 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22108 			/*
22109 			 * If conn_dontroute is not set or conn_multicast_loop
22110 			 * is set, we need to do forwarding/loopback. For
22111 			 * datagrams from ip_wput_multicast, conn_dontroute is
22112 			 * set to B_TRUE and conn_multicast_loop is set to
22113 			 * B_FALSE so that we neither do forwarding nor
22114 			 * loopback.
22115 			 */
22116 			if (!conn_dontroute || conn_multicast_loop)
22117 				multicast_forward = B_TRUE;
22118 		}
22119 	}
22120 
22121 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22122 	    ire->ire_zoneid != ALL_ZONES) {
22123 		/*
22124 		 * When a zone sends a packet to another zone, we try to deliver
22125 		 * the packet under the same conditions as if the destination
22126 		 * was a real node on the network. To do so, we look for a
22127 		 * matching route in the forwarding table.
22128 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22129 		 * ip_newroute() does.
22130 		 * Note that IRE_LOCAL are special, since they are used
22131 		 * when the zoneid doesn't match in some cases. This means that
22132 		 * we need to handle ipha_src differently since ire_src_addr
22133 		 * belongs to the receiving zone instead of the sending zone.
22134 		 * When ip_restrict_interzone_loopback is set, then
22135 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22136 		 * for loopback between zones when the logical "Ethernet" would
22137 		 * have looped them back.
22138 		 */
22139 		ire_t *src_ire;
22140 
22141 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22142 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22143 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22144 		if (src_ire != NULL &&
22145 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22146 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22147 		    ire_local_same_ill_group(ire, src_ire))) {
22148 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22149 				ipha->ipha_src = src_ire->ire_src_addr;
22150 			ire_refrele(src_ire);
22151 		} else {
22152 			ire_refrele(ire);
22153 			if (conn_outgoing_ill != NULL)
22154 				ill_refrele(conn_outgoing_ill);
22155 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22156 			if (src_ire != NULL) {
22157 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22158 					ire_refrele(src_ire);
22159 					freemsg(mp);
22160 					return;
22161 				}
22162 				ire_refrele(src_ire);
22163 			}
22164 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22165 				/* Failed */
22166 				freemsg(mp);
22167 				return;
22168 			}
22169 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22170 			    ipst);
22171 			return;
22172 		}
22173 	}
22174 
22175 	if (mp->b_datap->db_type == M_CTL ||
22176 	    ipss->ipsec_outbound_v4_policy_present) {
22177 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22178 		    unspec_src, zoneid);
22179 		if (mp == NULL) {
22180 			ire_refrele(ire);
22181 			if (conn_outgoing_ill != NULL)
22182 				ill_refrele(conn_outgoing_ill);
22183 			return;
22184 		}
22185 	}
22186 
22187 	first_mp = mp;
22188 	ipsec_len = 0;
22189 
22190 	if (first_mp->b_datap->db_type == M_CTL) {
22191 		io = (ipsec_out_t *)first_mp->b_rptr;
22192 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22193 		mp = first_mp->b_cont;
22194 		ipsec_len = ipsec_out_extra_length(first_mp);
22195 		ASSERT(ipsec_len >= 0);
22196 		/* We already picked up the zoneid from the M_CTL above */
22197 		ASSERT(zoneid == io->ipsec_out_zoneid);
22198 		ASSERT(zoneid != ALL_ZONES);
22199 
22200 		/*
22201 		 * Drop M_CTL here if IPsec processing is not needed.
22202 		 * (Non-IPsec use of M_CTL extracted any information it
22203 		 * needed above).
22204 		 */
22205 		if (ipsec_len == 0) {
22206 			freeb(first_mp);
22207 			first_mp = mp;
22208 		}
22209 	}
22210 
22211 	/*
22212 	 * Fast path for ip_wput_ire
22213 	 */
22214 
22215 	ipha = (ipha_t *)mp->b_rptr;
22216 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22217 	dst = ipha->ipha_dst;
22218 
22219 	/*
22220 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22221 	 * if the socket is a SOCK_RAW type. The transport checksum should
22222 	 * be provided in the pre-built packet, so we don't need to compute it.
22223 	 * Also, other application set flags, like DF, should not be altered.
22224 	 * Other transport MUST pass down zero.
22225 	 */
22226 	ip_hdr_included = ipha->ipha_ident;
22227 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22228 
22229 	if (CLASSD(dst)) {
22230 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22231 		    ntohl(dst),
22232 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22233 		    ntohl(ire->ire_addr)));
22234 	}
22235 
22236 /* Macros to extract header fields from data already in registers */
22237 #ifdef	_BIG_ENDIAN
22238 #define	V_HLEN	(v_hlen_tos_len >> 24)
22239 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22240 #define	PROTO	(ttl_protocol & 0xFF)
22241 #else
22242 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22243 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22244 #define	PROTO	(ttl_protocol >> 8)
22245 #endif
22246 
22247 
22248 	orig_src = src = ipha->ipha_src;
22249 	/* (The loop back to "another" is explained down below.) */
22250 another:;
22251 	/*
22252 	 * Assign an ident value for this packet.  We assign idents on
22253 	 * a per destination basis out of the IRE.  There could be
22254 	 * other threads targeting the same destination, so we have to
22255 	 * arrange for a atomic increment.  Note that we use a 32-bit
22256 	 * atomic add because it has better performance than its
22257 	 * 16-bit sibling.
22258 	 *
22259 	 * If running in cluster mode and if the source address
22260 	 * belongs to a replicated service then vector through
22261 	 * cl_inet_ipident vector to allocate ip identifier
22262 	 * NOTE: This is a contract private interface with the
22263 	 * clustering group.
22264 	 */
22265 	clusterwide = 0;
22266 	if (cl_inet_ipident) {
22267 		ASSERT(cl_inet_isclusterwide);
22268 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22269 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22270 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22271 			    AF_INET, (uint8_t *)(uintptr_t)src,
22272 			    (uint8_t *)(uintptr_t)dst);
22273 			clusterwide = 1;
22274 		}
22275 	}
22276 	if (!clusterwide) {
22277 		ipha->ipha_ident =
22278 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22279 	}
22280 
22281 #ifndef _BIG_ENDIAN
22282 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22283 #endif
22284 
22285 	/*
22286 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22287 	 * This is needed to obey conn_unspec_src when packets go through
22288 	 * ip_newroute + arp.
22289 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22290 	 */
22291 	if (src == INADDR_ANY && !unspec_src) {
22292 		/*
22293 		 * Assign the appropriate source address from the IRE if none
22294 		 * was specified.
22295 		 */
22296 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22297 
22298 		/*
22299 		 * With IP multipathing, broadcast packets are sent on the ire
22300 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22301 		 * the group. However, this ire might not be in the same zone so
22302 		 * we can't always use its source address. We look for a
22303 		 * broadcast ire in the same group and in the right zone.
22304 		 */
22305 		if (ire->ire_type == IRE_BROADCAST &&
22306 		    ire->ire_zoneid != zoneid) {
22307 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22308 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22309 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22310 			if (src_ire != NULL) {
22311 				src = src_ire->ire_src_addr;
22312 				ire_refrele(src_ire);
22313 			} else {
22314 				ire_refrele(ire);
22315 				if (conn_outgoing_ill != NULL)
22316 					ill_refrele(conn_outgoing_ill);
22317 				freemsg(first_mp);
22318 				if (ill != NULL) {
22319 					BUMP_MIB(ill->ill_ip_mib,
22320 					    ipIfStatsOutDiscards);
22321 				} else {
22322 					BUMP_MIB(&ipst->ips_ip_mib,
22323 					    ipIfStatsOutDiscards);
22324 				}
22325 				return;
22326 			}
22327 		} else {
22328 			src = ire->ire_src_addr;
22329 		}
22330 
22331 		if (connp == NULL) {
22332 			ip1dbg(("ip_wput_ire: no connp and no src "
22333 			    "address for dst 0x%x, using src 0x%x\n",
22334 			    ntohl(dst),
22335 			    ntohl(src)));
22336 		}
22337 		ipha->ipha_src = src;
22338 	}
22339 	stq = ire->ire_stq;
22340 
22341 	/*
22342 	 * We only allow ire chains for broadcasts since there will
22343 	 * be multiple IRE_CACHE entries for the same multicast
22344 	 * address (one per ipif).
22345 	 */
22346 	next_mp = NULL;
22347 
22348 	/* broadcast packet */
22349 	if (ire->ire_type == IRE_BROADCAST)
22350 		goto broadcast;
22351 
22352 	/* loopback ? */
22353 	if (stq == NULL)
22354 		goto nullstq;
22355 
22356 	/* The ill_index for outbound ILL */
22357 	ill_index = Q_TO_INDEX(stq);
22358 
22359 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22360 	ttl_protocol = ((uint16_t *)ipha)[4];
22361 
22362 	/* pseudo checksum (do it in parts for IP header checksum) */
22363 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22364 
22365 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22366 		queue_t *dev_q = stq->q_next;
22367 
22368 		/* flow controlled */
22369 		if ((dev_q->q_next || dev_q->q_first) &&
22370 		    !canput(dev_q))
22371 			goto blocked;
22372 		if ((PROTO == IPPROTO_UDP) &&
22373 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22374 			hlen = (V_HLEN & 0xF) << 2;
22375 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22376 			if (*up != 0) {
22377 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22378 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22379 				/* Software checksum? */
22380 				if (DB_CKSUMFLAGS(mp) == 0) {
22381 					IP_STAT(ipst, ip_out_sw_cksum);
22382 					IP_STAT_UPDATE(ipst,
22383 					    ip_udp_out_sw_cksum_bytes,
22384 					    LENGTH - hlen);
22385 				}
22386 			}
22387 		}
22388 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22389 		hlen = (V_HLEN & 0xF) << 2;
22390 		if (PROTO == IPPROTO_TCP) {
22391 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22392 			/*
22393 			 * The packet header is processed once and for all, even
22394 			 * in the multirouting case. We disable hardware
22395 			 * checksum if the packet is multirouted, as it will be
22396 			 * replicated via several interfaces, and not all of
22397 			 * them may have this capability.
22398 			 */
22399 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22400 			    LENGTH, max_frag, ipsec_len, cksum);
22401 			/* Software checksum? */
22402 			if (DB_CKSUMFLAGS(mp) == 0) {
22403 				IP_STAT(ipst, ip_out_sw_cksum);
22404 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22405 				    LENGTH - hlen);
22406 			}
22407 		} else {
22408 			sctp_hdr_t	*sctph;
22409 
22410 			ASSERT(PROTO == IPPROTO_SCTP);
22411 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22412 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22413 			/*
22414 			 * Zero out the checksum field to ensure proper
22415 			 * checksum calculation.
22416 			 */
22417 			sctph->sh_chksum = 0;
22418 #ifdef	DEBUG
22419 			if (!skip_sctp_cksum)
22420 #endif
22421 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22422 		}
22423 	}
22424 
22425 	/*
22426 	 * If this is a multicast packet and originated from ip_wput
22427 	 * we need to do loopback and forwarding checks. If it comes
22428 	 * from ip_wput_multicast, we SHOULD not do this.
22429 	 */
22430 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22431 
22432 	/* checksum */
22433 	cksum += ttl_protocol;
22434 
22435 	/* fragment the packet */
22436 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22437 		goto fragmentit;
22438 	/*
22439 	 * Don't use frag_flag if packet is pre-built or source
22440 	 * routed or if multicast (since multicast packets do
22441 	 * not solicit ICMP "packet too big" messages).
22442 	 */
22443 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22444 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22445 	    !ip_source_route_included(ipha)) &&
22446 	    !CLASSD(ipha->ipha_dst))
22447 		ipha->ipha_fragment_offset_and_flags |=
22448 		    htons(ire->ire_frag_flag);
22449 
22450 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22451 		/* calculate IP header checksum */
22452 		cksum += ipha->ipha_ident;
22453 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22454 		cksum += ipha->ipha_fragment_offset_and_flags;
22455 
22456 		/* IP options present */
22457 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22458 		if (hlen)
22459 			goto checksumoptions;
22460 
22461 		/* calculate hdr checksum */
22462 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22463 		cksum = ~(cksum + (cksum >> 16));
22464 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22465 	}
22466 	if (ipsec_len != 0) {
22467 		/*
22468 		 * We will do the rest of the processing after
22469 		 * we come back from IPsec in ip_wput_ipsec_out().
22470 		 */
22471 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22472 
22473 		io = (ipsec_out_t *)first_mp->b_rptr;
22474 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22475 		    ill_phyint->phyint_ifindex;
22476 
22477 		ipsec_out_process(q, first_mp, ire, ill_index);
22478 		ire_refrele(ire);
22479 		if (conn_outgoing_ill != NULL)
22480 			ill_refrele(conn_outgoing_ill);
22481 		return;
22482 	}
22483 
22484 	/*
22485 	 * In most cases, the emission loop below is entered only
22486 	 * once. Only in the case where the ire holds the
22487 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22488 	 * flagged ires in the bucket, and send the packet
22489 	 * through all crossed RTF_MULTIRT routes.
22490 	 */
22491 	if (ire->ire_flags & RTF_MULTIRT) {
22492 		multirt_send = B_TRUE;
22493 	}
22494 	do {
22495 		if (multirt_send) {
22496 			irb_t *irb;
22497 			/*
22498 			 * We are in a multiple send case, need to get
22499 			 * the next ire and make a duplicate of the packet.
22500 			 * ire1 holds here the next ire to process in the
22501 			 * bucket. If multirouting is expected,
22502 			 * any non-RTF_MULTIRT ire that has the
22503 			 * right destination address is ignored.
22504 			 */
22505 			irb = ire->ire_bucket;
22506 			ASSERT(irb != NULL);
22507 
22508 			IRB_REFHOLD(irb);
22509 			for (ire1 = ire->ire_next;
22510 			    ire1 != NULL;
22511 			    ire1 = ire1->ire_next) {
22512 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22513 					continue;
22514 				if (ire1->ire_addr != ire->ire_addr)
22515 					continue;
22516 				if (ire1->ire_marks &
22517 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22518 					continue;
22519 
22520 				/* Got one */
22521 				IRE_REFHOLD(ire1);
22522 				break;
22523 			}
22524 			IRB_REFRELE(irb);
22525 
22526 			if (ire1 != NULL) {
22527 				next_mp = copyb(mp);
22528 				if ((next_mp == NULL) ||
22529 				    ((mp->b_cont != NULL) &&
22530 				    ((next_mp->b_cont =
22531 				    dupmsg(mp->b_cont)) == NULL))) {
22532 					freemsg(next_mp);
22533 					next_mp = NULL;
22534 					ire_refrele(ire1);
22535 					ire1 = NULL;
22536 				}
22537 			}
22538 
22539 			/* Last multiroute ire; don't loop anymore. */
22540 			if (ire1 == NULL) {
22541 				multirt_send = B_FALSE;
22542 			}
22543 		}
22544 
22545 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22546 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22547 		    mblk_t *, mp);
22548 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22549 		    ipst->ips_ipv4firewall_physical_out,
22550 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22551 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22552 		if (mp == NULL)
22553 			goto release_ire_and_ill;
22554 
22555 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22556 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22557 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22558 		if ((pktxmit_state == SEND_FAILED) ||
22559 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22560 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22561 			    "- packet dropped\n"));
22562 release_ire_and_ill:
22563 			ire_refrele(ire);
22564 			if (next_mp != NULL) {
22565 				freemsg(next_mp);
22566 				ire_refrele(ire1);
22567 			}
22568 			if (conn_outgoing_ill != NULL)
22569 				ill_refrele(conn_outgoing_ill);
22570 			return;
22571 		}
22572 
22573 		if (CLASSD(dst)) {
22574 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22575 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22576 			    LENGTH);
22577 		}
22578 
22579 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22580 		    "ip_wput_ire_end: q %p (%S)",
22581 		    q, "last copy out");
22582 		IRE_REFRELE(ire);
22583 
22584 		if (multirt_send) {
22585 			ASSERT(ire1);
22586 			/*
22587 			 * Proceed with the next RTF_MULTIRT ire,
22588 			 * Also set up the send-to queue accordingly.
22589 			 */
22590 			ire = ire1;
22591 			ire1 = NULL;
22592 			stq = ire->ire_stq;
22593 			mp = next_mp;
22594 			next_mp = NULL;
22595 			ipha = (ipha_t *)mp->b_rptr;
22596 			ill_index = Q_TO_INDEX(stq);
22597 			ill = (ill_t *)stq->q_ptr;
22598 		}
22599 	} while (multirt_send);
22600 	if (conn_outgoing_ill != NULL)
22601 		ill_refrele(conn_outgoing_ill);
22602 	return;
22603 
22604 	/*
22605 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22606 	 */
22607 broadcast:
22608 	{
22609 		/*
22610 		 * Avoid broadcast storms by setting the ttl to 1
22611 		 * for broadcasts. This parameter can be set
22612 		 * via ndd, so make sure that for the SO_DONTROUTE
22613 		 * case that ipha_ttl is always set to 1.
22614 		 * In the event that we are replying to incoming
22615 		 * ICMP packets, conn could be NULL.
22616 		 */
22617 		if ((connp != NULL) && connp->conn_dontroute)
22618 			ipha->ipha_ttl = 1;
22619 		else
22620 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22621 
22622 		/*
22623 		 * Note that we are not doing a IRB_REFHOLD here.
22624 		 * Actually we don't care if the list changes i.e
22625 		 * if somebody deletes an IRE from the list while
22626 		 * we drop the lock, the next time we come around
22627 		 * ire_next will be NULL and hence we won't send
22628 		 * out multiple copies which is fine.
22629 		 */
22630 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22631 		ire1 = ire->ire_next;
22632 		if (conn_outgoing_ill != NULL) {
22633 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22634 				ASSERT(ire1 == ire->ire_next);
22635 				if (ire1 != NULL && ire1->ire_addr == dst) {
22636 					ire_refrele(ire);
22637 					ire = ire1;
22638 					IRE_REFHOLD(ire);
22639 					ire1 = ire->ire_next;
22640 					continue;
22641 				}
22642 				rw_exit(&ire->ire_bucket->irb_lock);
22643 				/* Did not find a matching ill */
22644 				ip1dbg(("ip_wput_ire: broadcast with no "
22645 				    "matching IP_BOUND_IF ill %s\n",
22646 				    conn_outgoing_ill->ill_name));
22647 				freemsg(first_mp);
22648 				if (ire != NULL)
22649 					ire_refrele(ire);
22650 				ill_refrele(conn_outgoing_ill);
22651 				return;
22652 			}
22653 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22654 			/*
22655 			 * If the next IRE has the same address and is not one
22656 			 * of the two copies that we need to send, try to see
22657 			 * whether this copy should be sent at all. This
22658 			 * assumes that we insert loopbacks first and then
22659 			 * non-loopbacks. This is acheived by inserting the
22660 			 * loopback always before non-loopback.
22661 			 * This is used to send a single copy of a broadcast
22662 			 * packet out all physical interfaces that have an
22663 			 * matching IRE_BROADCAST while also looping
22664 			 * back one copy (to ip_wput_local) for each
22665 			 * matching physical interface. However, we avoid
22666 			 * sending packets out different logical that match by
22667 			 * having ipif_up/ipif_down supress duplicate
22668 			 * IRE_BROADCASTS.
22669 			 *
22670 			 * This feature is currently used to get broadcasts
22671 			 * sent to multiple interfaces, when the broadcast
22672 			 * address being used applies to multiple interfaces.
22673 			 * For example, a whole net broadcast will be
22674 			 * replicated on every connected subnet of
22675 			 * the target net.
22676 			 *
22677 			 * Each zone has its own set of IRE_BROADCASTs, so that
22678 			 * we're able to distribute inbound packets to multiple
22679 			 * zones who share a broadcast address. We avoid looping
22680 			 * back outbound packets in different zones but on the
22681 			 * same ill, as the application would see duplicates.
22682 			 *
22683 			 * If the interfaces are part of the same group,
22684 			 * we would want to send only one copy out for
22685 			 * whole group.
22686 			 *
22687 			 * This logic assumes that ire_add_v4() groups the
22688 			 * IRE_BROADCAST entries so that those with the same
22689 			 * ire_addr and ill_group are kept together.
22690 			 */
22691 			ire_ill = ire->ire_ipif->ipif_ill;
22692 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22693 				if (ire_ill->ill_group != NULL &&
22694 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22695 					/*
22696 					 * If the current zone only has an ire
22697 					 * broadcast for this address marked
22698 					 * NORECV, the ire we want is ahead in
22699 					 * the bucket, so we look it up
22700 					 * deliberately ignoring the zoneid.
22701 					 */
22702 					for (ire1 = ire->ire_bucket->irb_ire;
22703 					    ire1 != NULL;
22704 					    ire1 = ire1->ire_next) {
22705 						ire1_ill =
22706 						    ire1->ire_ipif->ipif_ill;
22707 						if (ire1->ire_addr != dst)
22708 							continue;
22709 						/* skip over the current ire */
22710 						if (ire1 == ire)
22711 							continue;
22712 						/* skip over deleted ires */
22713 						if (ire1->ire_marks &
22714 						    IRE_MARK_CONDEMNED)
22715 							continue;
22716 						/*
22717 						 * non-loopback ire in our
22718 						 * group: use it for the next
22719 						 * pass in the loop
22720 						 */
22721 						if (ire1->ire_stq != NULL &&
22722 						    ire1_ill->ill_group ==
22723 						    ire_ill->ill_group)
22724 							break;
22725 					}
22726 				}
22727 			} else {
22728 				while (ire1 != NULL && ire1->ire_addr == dst) {
22729 					ire1_ill = ire1->ire_ipif->ipif_ill;
22730 					/*
22731 					 * We can have two broadcast ires on the
22732 					 * same ill in different zones; here
22733 					 * we'll send a copy of the packet on
22734 					 * each ill and the fanout code will
22735 					 * call conn_wantpacket() to check that
22736 					 * the zone has the broadcast address
22737 					 * configured on the ill. If the two
22738 					 * ires are in the same group we only
22739 					 * send one copy up.
22740 					 */
22741 					if (ire1_ill != ire_ill &&
22742 					    (ire1_ill->ill_group == NULL ||
22743 					    ire_ill->ill_group == NULL ||
22744 					    ire1_ill->ill_group !=
22745 					    ire_ill->ill_group)) {
22746 						break;
22747 					}
22748 					ire1 = ire1->ire_next;
22749 				}
22750 			}
22751 		}
22752 		ASSERT(multirt_send == B_FALSE);
22753 		if (ire1 != NULL && ire1->ire_addr == dst) {
22754 			if ((ire->ire_flags & RTF_MULTIRT) &&
22755 			    (ire1->ire_flags & RTF_MULTIRT)) {
22756 				/*
22757 				 * We are in the multirouting case.
22758 				 * The message must be sent at least
22759 				 * on both ires. These ires have been
22760 				 * inserted AFTER the standard ones
22761 				 * in ip_rt_add(). There are thus no
22762 				 * other ire entries for the destination
22763 				 * address in the rest of the bucket
22764 				 * that do not have the RTF_MULTIRT
22765 				 * flag. We don't process a copy
22766 				 * of the message here. This will be
22767 				 * done in the final sending loop.
22768 				 */
22769 				multirt_send = B_TRUE;
22770 			} else {
22771 				next_mp = ip_copymsg(first_mp);
22772 				if (next_mp != NULL)
22773 					IRE_REFHOLD(ire1);
22774 			}
22775 		}
22776 		rw_exit(&ire->ire_bucket->irb_lock);
22777 	}
22778 
22779 	if (stq) {
22780 		/*
22781 		 * A non-NULL send-to queue means this packet is going
22782 		 * out of this machine.
22783 		 */
22784 		out_ill = (ill_t *)stq->q_ptr;
22785 
22786 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22787 		ttl_protocol = ((uint16_t *)ipha)[4];
22788 		/*
22789 		 * We accumulate the pseudo header checksum in cksum.
22790 		 * This is pretty hairy code, so watch close.  One
22791 		 * thing to keep in mind is that UDP and TCP have
22792 		 * stored their respective datagram lengths in their
22793 		 * checksum fields.  This lines things up real nice.
22794 		 */
22795 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22796 		    (src >> 16) + (src & 0xFFFF);
22797 		/*
22798 		 * We assume the udp checksum field contains the
22799 		 * length, so to compute the pseudo header checksum,
22800 		 * all we need is the protocol number and src/dst.
22801 		 */
22802 		/* Provide the checksums for UDP and TCP. */
22803 		if ((PROTO == IPPROTO_TCP) &&
22804 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22805 			/* hlen gets the number of uchar_ts in the IP header */
22806 			hlen = (V_HLEN & 0xF) << 2;
22807 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22808 			IP_STAT(ipst, ip_out_sw_cksum);
22809 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22810 			    LENGTH - hlen);
22811 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22812 		} else if (PROTO == IPPROTO_SCTP &&
22813 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22814 			sctp_hdr_t	*sctph;
22815 
22816 			hlen = (V_HLEN & 0xF) << 2;
22817 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22818 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22819 			sctph->sh_chksum = 0;
22820 #ifdef	DEBUG
22821 			if (!skip_sctp_cksum)
22822 #endif
22823 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22824 		} else {
22825 			queue_t *dev_q = stq->q_next;
22826 
22827 			if ((dev_q->q_next || dev_q->q_first) &&
22828 			    !canput(dev_q)) {
22829 blocked:
22830 				ipha->ipha_ident = ip_hdr_included;
22831 				/*
22832 				 * If we don't have a conn to apply
22833 				 * backpressure, free the message.
22834 				 * In the ire_send path, we don't know
22835 				 * the position to requeue the packet. Rather
22836 				 * than reorder packets, we just drop this
22837 				 * packet.
22838 				 */
22839 				if (ipst->ips_ip_output_queue &&
22840 				    connp != NULL &&
22841 				    caller != IRE_SEND) {
22842 					if (caller == IP_WSRV) {
22843 						connp->conn_did_putbq = 1;
22844 						(void) putbq(connp->conn_wq,
22845 						    first_mp);
22846 						conn_drain_insert(connp);
22847 						/*
22848 						 * This is the service thread,
22849 						 * and the queue is already
22850 						 * noenabled. The check for
22851 						 * canput and the putbq is not
22852 						 * atomic. So we need to check
22853 						 * again.
22854 						 */
22855 						if (canput(stq->q_next))
22856 							connp->conn_did_putbq
22857 							    = 0;
22858 						IP_STAT(ipst, ip_conn_flputbq);
22859 					} else {
22860 						/*
22861 						 * We are not the service proc.
22862 						 * ip_wsrv will be scheduled or
22863 						 * is already running.
22864 						 */
22865 						(void) putq(connp->conn_wq,
22866 						    first_mp);
22867 					}
22868 				} else {
22869 					out_ill = (ill_t *)stq->q_ptr;
22870 					BUMP_MIB(out_ill->ill_ip_mib,
22871 					    ipIfStatsOutDiscards);
22872 					freemsg(first_mp);
22873 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22874 					    "ip_wput_ire_end: q %p (%S)",
22875 					    q, "discard");
22876 				}
22877 				ire_refrele(ire);
22878 				if (next_mp) {
22879 					ire_refrele(ire1);
22880 					freemsg(next_mp);
22881 				}
22882 				if (conn_outgoing_ill != NULL)
22883 					ill_refrele(conn_outgoing_ill);
22884 				return;
22885 			}
22886 			if ((PROTO == IPPROTO_UDP) &&
22887 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22888 				/*
22889 				 * hlen gets the number of uchar_ts in the
22890 				 * IP header
22891 				 */
22892 				hlen = (V_HLEN & 0xF) << 2;
22893 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22894 				max_frag = ire->ire_max_frag;
22895 				if (*up != 0) {
22896 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22897 					    up, PROTO, hlen, LENGTH, max_frag,
22898 					    ipsec_len, cksum);
22899 					/* Software checksum? */
22900 					if (DB_CKSUMFLAGS(mp) == 0) {
22901 						IP_STAT(ipst, ip_out_sw_cksum);
22902 						IP_STAT_UPDATE(ipst,
22903 						    ip_udp_out_sw_cksum_bytes,
22904 						    LENGTH - hlen);
22905 					}
22906 				}
22907 			}
22908 		}
22909 		/*
22910 		 * Need to do this even when fragmenting. The local
22911 		 * loopback can be done without computing checksums
22912 		 * but forwarding out other interface must be done
22913 		 * after the IP checksum (and ULP checksums) have been
22914 		 * computed.
22915 		 *
22916 		 * NOTE : multicast_forward is set only if this packet
22917 		 * originated from ip_wput. For packets originating from
22918 		 * ip_wput_multicast, it is not set.
22919 		 */
22920 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22921 multi_loopback:
22922 			ip2dbg(("ip_wput: multicast, loop %d\n",
22923 			    conn_multicast_loop));
22924 
22925 			/*  Forget header checksum offload */
22926 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22927 
22928 			/*
22929 			 * Local loopback of multicasts?  Check the
22930 			 * ill.
22931 			 *
22932 			 * Note that the loopback function will not come
22933 			 * in through ip_rput - it will only do the
22934 			 * client fanout thus we need to do an mforward
22935 			 * as well.  The is different from the BSD
22936 			 * logic.
22937 			 */
22938 			if (ill != NULL) {
22939 				ilm_t	*ilm;
22940 
22941 				ILM_WALKER_HOLD(ill);
22942 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22943 				    ALL_ZONES);
22944 				ILM_WALKER_RELE(ill);
22945 				if (ilm != NULL) {
22946 					/*
22947 					 * Pass along the virtual output q.
22948 					 * ip_wput_local() will distribute the
22949 					 * packet to all the matching zones,
22950 					 * except the sending zone when
22951 					 * IP_MULTICAST_LOOP is false.
22952 					 */
22953 					ip_multicast_loopback(q, ill, first_mp,
22954 					    conn_multicast_loop ? 0 :
22955 					    IP_FF_NO_MCAST_LOOP, zoneid);
22956 				}
22957 			}
22958 			if (ipha->ipha_ttl == 0) {
22959 				/*
22960 				 * 0 => only to this host i.e. we are
22961 				 * done. We are also done if this was the
22962 				 * loopback interface since it is sufficient
22963 				 * to loopback one copy of a multicast packet.
22964 				 */
22965 				freemsg(first_mp);
22966 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22967 				    "ip_wput_ire_end: q %p (%S)",
22968 				    q, "loopback");
22969 				ire_refrele(ire);
22970 				if (conn_outgoing_ill != NULL)
22971 					ill_refrele(conn_outgoing_ill);
22972 				return;
22973 			}
22974 			/*
22975 			 * ILLF_MULTICAST is checked in ip_newroute
22976 			 * i.e. we don't need to check it here since
22977 			 * all IRE_CACHEs come from ip_newroute.
22978 			 * For multicast traffic, SO_DONTROUTE is interpreted
22979 			 * to mean only send the packet out the interface
22980 			 * (optionally specified with IP_MULTICAST_IF)
22981 			 * and do not forward it out additional interfaces.
22982 			 * RSVP and the rsvp daemon is an example of a
22983 			 * protocol and user level process that
22984 			 * handles it's own routing. Hence, it uses the
22985 			 * SO_DONTROUTE option to accomplish this.
22986 			 */
22987 
22988 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22989 			    ill != NULL) {
22990 				/* Unconditionally redo the checksum */
22991 				ipha->ipha_hdr_checksum = 0;
22992 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22993 
22994 				/*
22995 				 * If this needs to go out secure, we need
22996 				 * to wait till we finish the IPsec
22997 				 * processing.
22998 				 */
22999 				if (ipsec_len == 0 &&
23000 				    ip_mforward(ill, ipha, mp)) {
23001 					freemsg(first_mp);
23002 					ip1dbg(("ip_wput: mforward failed\n"));
23003 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23004 					    "ip_wput_ire_end: q %p (%S)",
23005 					    q, "mforward failed");
23006 					ire_refrele(ire);
23007 					if (conn_outgoing_ill != NULL)
23008 						ill_refrele(conn_outgoing_ill);
23009 					return;
23010 				}
23011 			}
23012 		}
23013 		max_frag = ire->ire_max_frag;
23014 		cksum += ttl_protocol;
23015 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23016 			/* No fragmentation required for this one. */
23017 			/*
23018 			 * Don't use frag_flag if packet is pre-built or source
23019 			 * routed or if multicast (since multicast packets do
23020 			 * not solicit ICMP "packet too big" messages).
23021 			 */
23022 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23023 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23024 			    !ip_source_route_included(ipha)) &&
23025 			    !CLASSD(ipha->ipha_dst))
23026 				ipha->ipha_fragment_offset_and_flags |=
23027 				    htons(ire->ire_frag_flag);
23028 
23029 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23030 				/* Complete the IP header checksum. */
23031 				cksum += ipha->ipha_ident;
23032 				cksum += (v_hlen_tos_len >> 16)+
23033 				    (v_hlen_tos_len & 0xFFFF);
23034 				cksum += ipha->ipha_fragment_offset_and_flags;
23035 				hlen = (V_HLEN & 0xF) -
23036 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23037 				if (hlen) {
23038 checksumoptions:
23039 					/*
23040 					 * Account for the IP Options in the IP
23041 					 * header checksum.
23042 					 */
23043 					up = (uint16_t *)(rptr+
23044 					    IP_SIMPLE_HDR_LENGTH);
23045 					do {
23046 						cksum += up[0];
23047 						cksum += up[1];
23048 						up += 2;
23049 					} while (--hlen);
23050 				}
23051 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23052 				cksum = ~(cksum + (cksum >> 16));
23053 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23054 			}
23055 			if (ipsec_len != 0) {
23056 				ipsec_out_process(q, first_mp, ire, ill_index);
23057 				if (!next_mp) {
23058 					ire_refrele(ire);
23059 					if (conn_outgoing_ill != NULL)
23060 						ill_refrele(conn_outgoing_ill);
23061 					return;
23062 				}
23063 				goto next;
23064 			}
23065 
23066 			/*
23067 			 * multirt_send has already been handled
23068 			 * for broadcast, but not yet for multicast
23069 			 * or IP options.
23070 			 */
23071 			if (next_mp == NULL) {
23072 				if (ire->ire_flags & RTF_MULTIRT) {
23073 					multirt_send = B_TRUE;
23074 				}
23075 			}
23076 
23077 			/*
23078 			 * In most cases, the emission loop below is
23079 			 * entered only once. Only in the case where
23080 			 * the ire holds the RTF_MULTIRT flag, do we loop
23081 			 * to process all RTF_MULTIRT ires in the bucket,
23082 			 * and send the packet through all crossed
23083 			 * RTF_MULTIRT routes.
23084 			 */
23085 			do {
23086 				if (multirt_send) {
23087 					irb_t *irb;
23088 
23089 					irb = ire->ire_bucket;
23090 					ASSERT(irb != NULL);
23091 					/*
23092 					 * We are in a multiple send case,
23093 					 * need to get the next IRE and make
23094 					 * a duplicate of the packet.
23095 					 */
23096 					IRB_REFHOLD(irb);
23097 					for (ire1 = ire->ire_next;
23098 					    ire1 != NULL;
23099 					    ire1 = ire1->ire_next) {
23100 						if (!(ire1->ire_flags &
23101 						    RTF_MULTIRT)) {
23102 							continue;
23103 						}
23104 						if (ire1->ire_addr !=
23105 						    ire->ire_addr) {
23106 							continue;
23107 						}
23108 						if (ire1->ire_marks &
23109 						    (IRE_MARK_CONDEMNED|
23110 						    IRE_MARK_HIDDEN)) {
23111 							continue;
23112 						}
23113 
23114 						/* Got one */
23115 						IRE_REFHOLD(ire1);
23116 						break;
23117 					}
23118 					IRB_REFRELE(irb);
23119 
23120 					if (ire1 != NULL) {
23121 						next_mp = copyb(mp);
23122 						if ((next_mp == NULL) ||
23123 						    ((mp->b_cont != NULL) &&
23124 						    ((next_mp->b_cont =
23125 						    dupmsg(mp->b_cont))
23126 						    == NULL))) {
23127 							freemsg(next_mp);
23128 							next_mp = NULL;
23129 							ire_refrele(ire1);
23130 							ire1 = NULL;
23131 						}
23132 					}
23133 
23134 					/*
23135 					 * Last multiroute ire; don't loop
23136 					 * anymore. The emission is over
23137 					 * and next_mp is NULL.
23138 					 */
23139 					if (ire1 == NULL) {
23140 						multirt_send = B_FALSE;
23141 					}
23142 				}
23143 
23144 				out_ill = ire->ire_ipif->ipif_ill;
23145 				DTRACE_PROBE4(ip4__physical__out__start,
23146 				    ill_t *, NULL,
23147 				    ill_t *, out_ill,
23148 				    ipha_t *, ipha, mblk_t *, mp);
23149 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23150 				    ipst->ips_ipv4firewall_physical_out,
23151 				    NULL, out_ill, ipha, mp, mp, ipst);
23152 				DTRACE_PROBE1(ip4__physical__out__end,
23153 				    mblk_t *, mp);
23154 				if (mp == NULL)
23155 					goto release_ire_and_ill_2;
23156 
23157 				ASSERT(ipsec_len == 0);
23158 				mp->b_prev =
23159 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23160 				DTRACE_PROBE2(ip__xmit__2,
23161 				    mblk_t *, mp, ire_t *, ire);
23162 				pktxmit_state = ip_xmit_v4(mp, ire,
23163 				    NULL, B_TRUE);
23164 				if ((pktxmit_state == SEND_FAILED) ||
23165 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23166 release_ire_and_ill_2:
23167 					if (next_mp) {
23168 						freemsg(next_mp);
23169 						ire_refrele(ire1);
23170 					}
23171 					ire_refrele(ire);
23172 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23173 					    "ip_wput_ire_end: q %p (%S)",
23174 					    q, "discard MDATA");
23175 					if (conn_outgoing_ill != NULL)
23176 						ill_refrele(conn_outgoing_ill);
23177 					return;
23178 				}
23179 
23180 				if (CLASSD(dst)) {
23181 					BUMP_MIB(out_ill->ill_ip_mib,
23182 					    ipIfStatsHCOutMcastPkts);
23183 					UPDATE_MIB(out_ill->ill_ip_mib,
23184 					    ipIfStatsHCOutMcastOctets,
23185 					    LENGTH);
23186 				} else if (ire->ire_type == IRE_BROADCAST) {
23187 					BUMP_MIB(out_ill->ill_ip_mib,
23188 					    ipIfStatsHCOutBcastPkts);
23189 				}
23190 
23191 				if (multirt_send) {
23192 					/*
23193 					 * We are in a multiple send case,
23194 					 * need to re-enter the sending loop
23195 					 * using the next ire.
23196 					 */
23197 					ire_refrele(ire);
23198 					ire = ire1;
23199 					stq = ire->ire_stq;
23200 					mp = next_mp;
23201 					next_mp = NULL;
23202 					ipha = (ipha_t *)mp->b_rptr;
23203 					ill_index = Q_TO_INDEX(stq);
23204 				}
23205 			} while (multirt_send);
23206 
23207 			if (!next_mp) {
23208 				/*
23209 				 * Last copy going out (the ultra-common
23210 				 * case).  Note that we intentionally replicate
23211 				 * the putnext rather than calling it before
23212 				 * the next_mp check in hopes of a little
23213 				 * tail-call action out of the compiler.
23214 				 */
23215 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23216 				    "ip_wput_ire_end: q %p (%S)",
23217 				    q, "last copy out(1)");
23218 				ire_refrele(ire);
23219 				if (conn_outgoing_ill != NULL)
23220 					ill_refrele(conn_outgoing_ill);
23221 				return;
23222 			}
23223 			/* More copies going out below. */
23224 		} else {
23225 			int offset;
23226 fragmentit:
23227 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23228 			/*
23229 			 * If this would generate a icmp_frag_needed message,
23230 			 * we need to handle it before we do the IPsec
23231 			 * processing. Otherwise, we need to strip the IPsec
23232 			 * headers before we send up the message to the ULPs
23233 			 * which becomes messy and difficult.
23234 			 */
23235 			if (ipsec_len != 0) {
23236 				if ((max_frag < (unsigned int)(LENGTH +
23237 				    ipsec_len)) && (offset & IPH_DF)) {
23238 					out_ill = (ill_t *)stq->q_ptr;
23239 					BUMP_MIB(out_ill->ill_ip_mib,
23240 					    ipIfStatsOutFragFails);
23241 					BUMP_MIB(out_ill->ill_ip_mib,
23242 					    ipIfStatsOutFragReqds);
23243 					ipha->ipha_hdr_checksum = 0;
23244 					ipha->ipha_hdr_checksum =
23245 					    (uint16_t)ip_csum_hdr(ipha);
23246 					icmp_frag_needed(ire->ire_stq, first_mp,
23247 					    max_frag, zoneid, ipst);
23248 					if (!next_mp) {
23249 						ire_refrele(ire);
23250 						if (conn_outgoing_ill != NULL) {
23251 							ill_refrele(
23252 							    conn_outgoing_ill);
23253 						}
23254 						return;
23255 					}
23256 				} else {
23257 					/*
23258 					 * This won't cause a icmp_frag_needed
23259 					 * message. to be generated. Send it on
23260 					 * the wire. Note that this could still
23261 					 * cause fragmentation and all we
23262 					 * do is the generation of the message
23263 					 * to the ULP if needed before IPsec.
23264 					 */
23265 					if (!next_mp) {
23266 						ipsec_out_process(q, first_mp,
23267 						    ire, ill_index);
23268 						TRACE_2(TR_FAC_IP,
23269 						    TR_IP_WPUT_IRE_END,
23270 						    "ip_wput_ire_end: q %p "
23271 						    "(%S)", q,
23272 						    "last ipsec_out_process");
23273 						ire_refrele(ire);
23274 						if (conn_outgoing_ill != NULL) {
23275 							ill_refrele(
23276 							    conn_outgoing_ill);
23277 						}
23278 						return;
23279 					}
23280 					ipsec_out_process(q, first_mp,
23281 					    ire, ill_index);
23282 				}
23283 			} else {
23284 				/*
23285 				 * Initiate IPPF processing. For
23286 				 * fragmentable packets we finish
23287 				 * all QOS packet processing before
23288 				 * calling:
23289 				 * ip_wput_ire_fragmentit->ip_wput_frag
23290 				 */
23291 
23292 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23293 					ip_process(IPP_LOCAL_OUT, &mp,
23294 					    ill_index);
23295 					if (mp == NULL) {
23296 						out_ill = (ill_t *)stq->q_ptr;
23297 						BUMP_MIB(out_ill->ill_ip_mib,
23298 						    ipIfStatsOutDiscards);
23299 						if (next_mp != NULL) {
23300 							freemsg(next_mp);
23301 							ire_refrele(ire1);
23302 						}
23303 						ire_refrele(ire);
23304 						TRACE_2(TR_FAC_IP,
23305 						    TR_IP_WPUT_IRE_END,
23306 						    "ip_wput_ire: q %p (%S)",
23307 						    q, "discard MDATA");
23308 						if (conn_outgoing_ill != NULL) {
23309 							ill_refrele(
23310 							    conn_outgoing_ill);
23311 						}
23312 						return;
23313 					}
23314 				}
23315 				if (!next_mp) {
23316 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23317 					    "ip_wput_ire_end: q %p (%S)",
23318 					    q, "last fragmentation");
23319 					ip_wput_ire_fragmentit(mp, ire,
23320 					    zoneid, ipst);
23321 					ire_refrele(ire);
23322 					if (conn_outgoing_ill != NULL)
23323 						ill_refrele(conn_outgoing_ill);
23324 					return;
23325 				}
23326 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23327 			}
23328 		}
23329 	} else {
23330 nullstq:
23331 		/* A NULL stq means the destination address is local. */
23332 		UPDATE_OB_PKT_COUNT(ire);
23333 		ire->ire_last_used_time = lbolt;
23334 		ASSERT(ire->ire_ipif != NULL);
23335 		if (!next_mp) {
23336 			/*
23337 			 * Is there an "in" and "out" for traffic local
23338 			 * to a host (loopback)?  The code in Solaris doesn't
23339 			 * explicitly draw a line in its code for in vs out,
23340 			 * so we've had to draw a line in the sand: ip_wput_ire
23341 			 * is considered to be the "output" side and
23342 			 * ip_wput_local to be the "input" side.
23343 			 */
23344 			out_ill = ire->ire_ipif->ipif_ill;
23345 
23346 			DTRACE_PROBE4(ip4__loopback__out__start,
23347 			    ill_t *, NULL, ill_t *, out_ill,
23348 			    ipha_t *, ipha, mblk_t *, first_mp);
23349 
23350 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23351 			    ipst->ips_ipv4firewall_loopback_out,
23352 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23353 
23354 			DTRACE_PROBE1(ip4__loopback__out_end,
23355 			    mblk_t *, first_mp);
23356 
23357 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23358 			    "ip_wput_ire_end: q %p (%S)",
23359 			    q, "local address");
23360 
23361 			if (first_mp != NULL)
23362 				ip_wput_local(q, out_ill, ipha,
23363 				    first_mp, ire, 0, ire->ire_zoneid);
23364 			ire_refrele(ire);
23365 			if (conn_outgoing_ill != NULL)
23366 				ill_refrele(conn_outgoing_ill);
23367 			return;
23368 		}
23369 
23370 		out_ill = ire->ire_ipif->ipif_ill;
23371 
23372 		DTRACE_PROBE4(ip4__loopback__out__start,
23373 		    ill_t *, NULL, ill_t *, out_ill,
23374 		    ipha_t *, ipha, mblk_t *, first_mp);
23375 
23376 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23377 		    ipst->ips_ipv4firewall_loopback_out,
23378 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23379 
23380 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23381 
23382 		if (first_mp != NULL)
23383 			ip_wput_local(q, out_ill, ipha,
23384 			    first_mp, ire, 0, ire->ire_zoneid);
23385 	}
23386 next:
23387 	/*
23388 	 * More copies going out to additional interfaces.
23389 	 * ire1 has already been held. We don't need the
23390 	 * "ire" anymore.
23391 	 */
23392 	ire_refrele(ire);
23393 	ire = ire1;
23394 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23395 	mp = next_mp;
23396 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23397 	ill = ire_to_ill(ire);
23398 	first_mp = mp;
23399 	if (ipsec_len != 0) {
23400 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23401 		mp = mp->b_cont;
23402 	}
23403 	dst = ire->ire_addr;
23404 	ipha = (ipha_t *)mp->b_rptr;
23405 	/*
23406 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23407 	 * Restore ipha_ident "no checksum" flag.
23408 	 */
23409 	src = orig_src;
23410 	ipha->ipha_ident = ip_hdr_included;
23411 	goto another;
23412 
23413 #undef	rptr
23414 #undef	Q_TO_INDEX
23415 }
23416 
23417 /*
23418  * Routine to allocate a message that is used to notify the ULP about MDT.
23419  * The caller may provide a pointer to the link-layer MDT capabilities,
23420  * or NULL if MDT is to be disabled on the stream.
23421  */
23422 mblk_t *
23423 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23424 {
23425 	mblk_t *mp;
23426 	ip_mdt_info_t *mdti;
23427 	ill_mdt_capab_t *idst;
23428 
23429 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23430 		DB_TYPE(mp) = M_CTL;
23431 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23432 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23433 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23434 		idst = &(mdti->mdt_capab);
23435 
23436 		/*
23437 		 * If the caller provides us with the capability, copy
23438 		 * it over into our notification message; otherwise
23439 		 * we zero out the capability portion.
23440 		 */
23441 		if (isrc != NULL)
23442 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23443 		else
23444 			bzero((caddr_t)idst, sizeof (*idst));
23445 	}
23446 	return (mp);
23447 }
23448 
23449 /*
23450  * Routine which determines whether MDT can be enabled on the destination
23451  * IRE and IPC combination, and if so, allocates and returns the MDT
23452  * notification mblk that may be used by ULP.  We also check if we need to
23453  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23454  * MDT usage in the past have been lifted.  This gets called during IP
23455  * and ULP binding.
23456  */
23457 mblk_t *
23458 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23459     ill_mdt_capab_t *mdt_cap)
23460 {
23461 	mblk_t *mp;
23462 	boolean_t rc = B_FALSE;
23463 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23464 
23465 	ASSERT(dst_ire != NULL);
23466 	ASSERT(connp != NULL);
23467 	ASSERT(mdt_cap != NULL);
23468 
23469 	/*
23470 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23471 	 * Multidata, which is handled in tcp_multisend().  This
23472 	 * is the reason why we do all these checks here, to ensure
23473 	 * that we don't enable Multidata for the cases which we
23474 	 * can't handle at the moment.
23475 	 */
23476 	do {
23477 		/* Only do TCP at the moment */
23478 		if (connp->conn_ulp != IPPROTO_TCP)
23479 			break;
23480 
23481 		/*
23482 		 * IPsec outbound policy present?  Note that we get here
23483 		 * after calling ipsec_conn_cache_policy() where the global
23484 		 * policy checking is performed.  conn_latch will be
23485 		 * non-NULL as long as there's a policy defined,
23486 		 * i.e. conn_out_enforce_policy may be NULL in such case
23487 		 * when the connection is non-secure, and hence we check
23488 		 * further if the latch refers to an outbound policy.
23489 		 */
23490 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23491 			break;
23492 
23493 		/* CGTP (multiroute) is enabled? */
23494 		if (dst_ire->ire_flags & RTF_MULTIRT)
23495 			break;
23496 
23497 		/* Outbound IPQoS enabled? */
23498 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23499 			/*
23500 			 * In this case, we disable MDT for this and all
23501 			 * future connections going over the interface.
23502 			 */
23503 			mdt_cap->ill_mdt_on = 0;
23504 			break;
23505 		}
23506 
23507 		/* socket option(s) present? */
23508 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23509 			break;
23510 
23511 		rc = B_TRUE;
23512 	/* CONSTCOND */
23513 	} while (0);
23514 
23515 	/* Remember the result */
23516 	connp->conn_mdt_ok = rc;
23517 
23518 	if (!rc)
23519 		return (NULL);
23520 	else if (!mdt_cap->ill_mdt_on) {
23521 		/*
23522 		 * If MDT has been previously turned off in the past, and we
23523 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23524 		 * then enable it for this interface.
23525 		 */
23526 		mdt_cap->ill_mdt_on = 1;
23527 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23528 		    "interface %s\n", ill_name));
23529 	}
23530 
23531 	/* Allocate the MDT info mblk */
23532 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23533 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23534 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23535 		return (NULL);
23536 	}
23537 	return (mp);
23538 }
23539 
23540 /*
23541  * Routine to allocate a message that is used to notify the ULP about LSO.
23542  * The caller may provide a pointer to the link-layer LSO capabilities,
23543  * or NULL if LSO is to be disabled on the stream.
23544  */
23545 mblk_t *
23546 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23547 {
23548 	mblk_t *mp;
23549 	ip_lso_info_t *lsoi;
23550 	ill_lso_capab_t *idst;
23551 
23552 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23553 		DB_TYPE(mp) = M_CTL;
23554 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23555 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23556 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23557 		idst = &(lsoi->lso_capab);
23558 
23559 		/*
23560 		 * If the caller provides us with the capability, copy
23561 		 * it over into our notification message; otherwise
23562 		 * we zero out the capability portion.
23563 		 */
23564 		if (isrc != NULL)
23565 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23566 		else
23567 			bzero((caddr_t)idst, sizeof (*idst));
23568 	}
23569 	return (mp);
23570 }
23571 
23572 /*
23573  * Routine which determines whether LSO can be enabled on the destination
23574  * IRE and IPC combination, and if so, allocates and returns the LSO
23575  * notification mblk that may be used by ULP.  We also check if we need to
23576  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23577  * LSO usage in the past have been lifted.  This gets called during IP
23578  * and ULP binding.
23579  */
23580 mblk_t *
23581 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23582     ill_lso_capab_t *lso_cap)
23583 {
23584 	mblk_t *mp;
23585 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23586 
23587 	ASSERT(dst_ire != NULL);
23588 	ASSERT(connp != NULL);
23589 	ASSERT(lso_cap != NULL);
23590 
23591 	connp->conn_lso_ok = B_TRUE;
23592 
23593 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23594 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23595 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23596 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23597 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23598 		connp->conn_lso_ok = B_FALSE;
23599 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23600 			/*
23601 			 * Disable LSO for this and all future connections going
23602 			 * over the interface.
23603 			 */
23604 			lso_cap->ill_lso_on = 0;
23605 		}
23606 	}
23607 
23608 	if (!connp->conn_lso_ok)
23609 		return (NULL);
23610 	else if (!lso_cap->ill_lso_on) {
23611 		/*
23612 		 * If LSO has been previously turned off in the past, and we
23613 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23614 		 * then enable it for this interface.
23615 		 */
23616 		lso_cap->ill_lso_on = 1;
23617 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23618 		    ill_name));
23619 	}
23620 
23621 	/* Allocate the LSO info mblk */
23622 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23623 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23624 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23625 
23626 	return (mp);
23627 }
23628 
23629 /*
23630  * Create destination address attribute, and fill it with the physical
23631  * destination address and SAP taken from the template DL_UNITDATA_REQ
23632  * message block.
23633  */
23634 boolean_t
23635 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23636 {
23637 	dl_unitdata_req_t *dlurp;
23638 	pattr_t *pa;
23639 	pattrinfo_t pa_info;
23640 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23641 	uint_t das_len, das_off;
23642 
23643 	ASSERT(dlmp != NULL);
23644 
23645 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23646 	das_len = dlurp->dl_dest_addr_length;
23647 	das_off = dlurp->dl_dest_addr_offset;
23648 
23649 	pa_info.type = PATTR_DSTADDRSAP;
23650 	pa_info.len = sizeof (**das) + das_len - 1;
23651 
23652 	/* create and associate the attribute */
23653 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23654 	if (pa != NULL) {
23655 		ASSERT(*das != NULL);
23656 		(*das)->addr_is_group = 0;
23657 		(*das)->addr_len = (uint8_t)das_len;
23658 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23659 	}
23660 
23661 	return (pa != NULL);
23662 }
23663 
23664 /*
23665  * Create hardware checksum attribute and fill it with the values passed.
23666  */
23667 boolean_t
23668 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23669     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23670 {
23671 	pattr_t *pa;
23672 	pattrinfo_t pa_info;
23673 
23674 	ASSERT(mmd != NULL);
23675 
23676 	pa_info.type = PATTR_HCKSUM;
23677 	pa_info.len = sizeof (pattr_hcksum_t);
23678 
23679 	/* create and associate the attribute */
23680 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23681 	if (pa != NULL) {
23682 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23683 
23684 		hck->hcksum_start_offset = start_offset;
23685 		hck->hcksum_stuff_offset = stuff_offset;
23686 		hck->hcksum_end_offset = end_offset;
23687 		hck->hcksum_flags = flags;
23688 	}
23689 	return (pa != NULL);
23690 }
23691 
23692 /*
23693  * Create zerocopy attribute and fill it with the specified flags
23694  */
23695 boolean_t
23696 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23697 {
23698 	pattr_t *pa;
23699 	pattrinfo_t pa_info;
23700 
23701 	ASSERT(mmd != NULL);
23702 	pa_info.type = PATTR_ZCOPY;
23703 	pa_info.len = sizeof (pattr_zcopy_t);
23704 
23705 	/* create and associate the attribute */
23706 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23707 	if (pa != NULL) {
23708 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23709 
23710 		zcopy->zcopy_flags = flags;
23711 	}
23712 	return (pa != NULL);
23713 }
23714 
23715 /*
23716  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23717  * block chain. We could rewrite to handle arbitrary message block chains but
23718  * that would make the code complicated and slow. Right now there three
23719  * restrictions:
23720  *
23721  *   1. The first message block must contain the complete IP header and
23722  *	at least 1 byte of payload data.
23723  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23724  *	so that we can use a single Multidata message.
23725  *   3. No frag must be distributed over two or more message blocks so
23726  *	that we don't need more than two packet descriptors per frag.
23727  *
23728  * The above restrictions allow us to support userland applications (which
23729  * will send down a single message block) and NFS over UDP (which will
23730  * send down a chain of at most three message blocks).
23731  *
23732  * We also don't use MDT for payloads with less than or equal to
23733  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23734  */
23735 boolean_t
23736 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23737 {
23738 	int	blocks;
23739 	ssize_t	total, missing, size;
23740 
23741 	ASSERT(mp != NULL);
23742 	ASSERT(hdr_len > 0);
23743 
23744 	size = MBLKL(mp) - hdr_len;
23745 	if (size <= 0)
23746 		return (B_FALSE);
23747 
23748 	/* The first mblk contains the header and some payload. */
23749 	blocks = 1;
23750 	total = size;
23751 	size %= len;
23752 	missing = (size == 0) ? 0 : (len - size);
23753 	mp = mp->b_cont;
23754 
23755 	while (mp != NULL) {
23756 		/*
23757 		 * Give up if we encounter a zero length message block.
23758 		 * In practice, this should rarely happen and therefore
23759 		 * not worth the trouble of freeing and re-linking the
23760 		 * mblk from the chain to handle such case.
23761 		 */
23762 		if ((size = MBLKL(mp)) == 0)
23763 			return (B_FALSE);
23764 
23765 		/* Too many payload buffers for a single Multidata message? */
23766 		if (++blocks > MULTIDATA_MAX_PBUFS)
23767 			return (B_FALSE);
23768 
23769 		total += size;
23770 		/* Is a frag distributed over two or more message blocks? */
23771 		if (missing > size)
23772 			return (B_FALSE);
23773 		size -= missing;
23774 
23775 		size %= len;
23776 		missing = (size == 0) ? 0 : (len - size);
23777 
23778 		mp = mp->b_cont;
23779 	}
23780 
23781 	return (total > ip_wput_frag_mdt_min);
23782 }
23783 
23784 /*
23785  * Outbound IPv4 fragmentation routine using MDT.
23786  */
23787 static void
23788 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23789     uint32_t frag_flag, int offset)
23790 {
23791 	ipha_t		*ipha_orig;
23792 	int		i1, ip_data_end;
23793 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23794 	mblk_t		*hdr_mp, *md_mp = NULL;
23795 	unsigned char	*hdr_ptr, *pld_ptr;
23796 	multidata_t	*mmd;
23797 	ip_pdescinfo_t	pdi;
23798 	ill_t		*ill;
23799 	ip_stack_t	*ipst = ire->ire_ipst;
23800 
23801 	ASSERT(DB_TYPE(mp) == M_DATA);
23802 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23803 
23804 	ill = ire_to_ill(ire);
23805 	ASSERT(ill != NULL);
23806 
23807 	ipha_orig = (ipha_t *)mp->b_rptr;
23808 	mp->b_rptr += sizeof (ipha_t);
23809 
23810 	/* Calculate how many packets we will send out */
23811 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23812 	pkts = (i1 + len - 1) / len;
23813 	ASSERT(pkts > 1);
23814 
23815 	/* Allocate a message block which will hold all the IP Headers. */
23816 	wroff = ipst->ips_ip_wroff_extra;
23817 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23818 
23819 	i1 = pkts * hdr_chunk_len;
23820 	/*
23821 	 * Create the header buffer, Multidata and destination address
23822 	 * and SAP attribute that should be associated with it.
23823 	 */
23824 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23825 	    ((hdr_mp->b_wptr += i1),
23826 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23827 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23828 		freemsg(mp);
23829 		if (md_mp == NULL) {
23830 			freemsg(hdr_mp);
23831 		} else {
23832 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23833 			freemsg(md_mp);
23834 		}
23835 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23836 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23837 		return;
23838 	}
23839 	IP_STAT(ipst, ip_frag_mdt_allocd);
23840 
23841 	/*
23842 	 * Add a payload buffer to the Multidata; this operation must not
23843 	 * fail, or otherwise our logic in this routine is broken.  There
23844 	 * is no memory allocation done by the routine, so any returned
23845 	 * failure simply tells us that we've done something wrong.
23846 	 *
23847 	 * A failure tells us that either we're adding the same payload
23848 	 * buffer more than once, or we're trying to add more buffers than
23849 	 * allowed.  None of the above cases should happen, and we panic
23850 	 * because either there's horrible heap corruption, and/or
23851 	 * programming mistake.
23852 	 */
23853 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23854 		goto pbuf_panic;
23855 
23856 	hdr_ptr = hdr_mp->b_rptr;
23857 	pld_ptr = mp->b_rptr;
23858 
23859 	/* Establish the ending byte offset, based on the starting offset. */
23860 	offset <<= 3;
23861 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23862 	    IP_SIMPLE_HDR_LENGTH;
23863 
23864 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23865 
23866 	while (pld_ptr < mp->b_wptr) {
23867 		ipha_t		*ipha;
23868 		uint16_t	offset_and_flags;
23869 		uint16_t	ip_len;
23870 		int		error;
23871 
23872 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23873 		ipha = (ipha_t *)(hdr_ptr + wroff);
23874 		ASSERT(OK_32PTR(ipha));
23875 		*ipha = *ipha_orig;
23876 
23877 		if (ip_data_end - offset > len) {
23878 			offset_and_flags = IPH_MF;
23879 		} else {
23880 			/*
23881 			 * Last frag. Set len to the length of this last piece.
23882 			 */
23883 			len = ip_data_end - offset;
23884 			/* A frag of a frag might have IPH_MF non-zero */
23885 			offset_and_flags =
23886 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23887 			    IPH_MF;
23888 		}
23889 		offset_and_flags |= (uint16_t)(offset >> 3);
23890 		offset_and_flags |= (uint16_t)frag_flag;
23891 		/* Store the offset and flags in the IP header. */
23892 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23893 
23894 		/* Store the length in the IP header. */
23895 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23896 		ipha->ipha_length = htons(ip_len);
23897 
23898 		/*
23899 		 * Set the IP header checksum.  Note that mp is just
23900 		 * the header, so this is easy to pass to ip_csum.
23901 		 */
23902 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23903 
23904 		/*
23905 		 * Record offset and size of header and data of the next packet
23906 		 * in the multidata message.
23907 		 */
23908 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23909 		PDESC_PLD_INIT(&pdi);
23910 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23911 		ASSERT(i1 > 0);
23912 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23913 		if (i1 == len) {
23914 			pld_ptr += len;
23915 		} else {
23916 			i1 = len - i1;
23917 			mp = mp->b_cont;
23918 			ASSERT(mp != NULL);
23919 			ASSERT(MBLKL(mp) >= i1);
23920 			/*
23921 			 * Attach the next payload message block to the
23922 			 * multidata message.
23923 			 */
23924 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23925 				goto pbuf_panic;
23926 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23927 			pld_ptr = mp->b_rptr + i1;
23928 		}
23929 
23930 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23931 		    KM_NOSLEEP)) == NULL) {
23932 			/*
23933 			 * Any failure other than ENOMEM indicates that we
23934 			 * have passed in invalid pdesc info or parameters
23935 			 * to mmd_addpdesc, which must not happen.
23936 			 *
23937 			 * EINVAL is a result of failure on boundary checks
23938 			 * against the pdesc info contents.  It should not
23939 			 * happen, and we panic because either there's
23940 			 * horrible heap corruption, and/or programming
23941 			 * mistake.
23942 			 */
23943 			if (error != ENOMEM) {
23944 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23945 				    "pdesc logic error detected for "
23946 				    "mmd %p pinfo %p (%d)\n",
23947 				    (void *)mmd, (void *)&pdi, error);
23948 				/* NOTREACHED */
23949 			}
23950 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23951 			/* Free unattached payload message blocks as well */
23952 			md_mp->b_cont = mp->b_cont;
23953 			goto free_mmd;
23954 		}
23955 
23956 		/* Advance fragment offset. */
23957 		offset += len;
23958 
23959 		/* Advance to location for next header in the buffer. */
23960 		hdr_ptr += hdr_chunk_len;
23961 
23962 		/* Did we reach the next payload message block? */
23963 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23964 			mp = mp->b_cont;
23965 			/*
23966 			 * Attach the next message block with payload
23967 			 * data to the multidata message.
23968 			 */
23969 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23970 				goto pbuf_panic;
23971 			pld_ptr = mp->b_rptr;
23972 		}
23973 	}
23974 
23975 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23976 	ASSERT(mp->b_wptr == pld_ptr);
23977 
23978 	/* Update IP statistics */
23979 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23980 
23981 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23982 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23983 
23984 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23985 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23986 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23987 
23988 	if (pkt_type == OB_PKT) {
23989 		ire->ire_ob_pkt_count += pkts;
23990 		if (ire->ire_ipif != NULL)
23991 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23992 	} else {
23993 		/* The type is IB_PKT in the forwarding path. */
23994 		ire->ire_ib_pkt_count += pkts;
23995 		ASSERT(!IRE_IS_LOCAL(ire));
23996 		if (ire->ire_type & IRE_BROADCAST) {
23997 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23998 		} else {
23999 			UPDATE_MIB(ill->ill_ip_mib,
24000 			    ipIfStatsHCOutForwDatagrams, pkts);
24001 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24002 		}
24003 	}
24004 	ire->ire_last_used_time = lbolt;
24005 	/* Send it down */
24006 	putnext(ire->ire_stq, md_mp);
24007 	return;
24008 
24009 pbuf_panic:
24010 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24011 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24012 	    pbuf_idx);
24013 	/* NOTREACHED */
24014 }
24015 
24016 /*
24017  * Outbound IP fragmentation routine.
24018  *
24019  * NOTE : This routine does not ire_refrele the ire that is passed in
24020  * as the argument.
24021  */
24022 static void
24023 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24024     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24025 {
24026 	int		i1;
24027 	mblk_t		*ll_hdr_mp;
24028 	int 		ll_hdr_len;
24029 	int		hdr_len;
24030 	mblk_t		*hdr_mp;
24031 	ipha_t		*ipha;
24032 	int		ip_data_end;
24033 	int		len;
24034 	mblk_t		*mp = mp_orig, *mp1;
24035 	int		offset;
24036 	queue_t		*q;
24037 	uint32_t	v_hlen_tos_len;
24038 	mblk_t		*first_mp;
24039 	boolean_t	mctl_present;
24040 	ill_t		*ill;
24041 	ill_t		*out_ill;
24042 	mblk_t		*xmit_mp;
24043 	mblk_t		*carve_mp;
24044 	ire_t		*ire1 = NULL;
24045 	ire_t		*save_ire = NULL;
24046 	mblk_t  	*next_mp = NULL;
24047 	boolean_t	last_frag = B_FALSE;
24048 	boolean_t	multirt_send = B_FALSE;
24049 	ire_t		*first_ire = NULL;
24050 	irb_t		*irb = NULL;
24051 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24052 
24053 	ill = ire_to_ill(ire);
24054 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24055 
24056 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24057 
24058 	if (max_frag == 0) {
24059 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24060 		    " -  dropping packet\n"));
24061 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24062 		freemsg(mp);
24063 		return;
24064 	}
24065 
24066 	/*
24067 	 * IPsec does not allow hw accelerated packets to be fragmented
24068 	 * This check is made in ip_wput_ipsec_out prior to coming here
24069 	 * via ip_wput_ire_fragmentit.
24070 	 *
24071 	 * If at this point we have an ire whose ARP request has not
24072 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24073 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24074 	 * This packet and all fragmentable packets for this ire will
24075 	 * continue to get dropped while ire_nce->nce_state remains in
24076 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24077 	 * ND_REACHABLE, all subsquent large packets for this ire will
24078 	 * get fragemented and sent out by this function.
24079 	 */
24080 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24081 		/* If nce_state is ND_INITIAL, trigger ARP query */
24082 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24083 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24084 		    " -  dropping packet\n"));
24085 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24086 		freemsg(mp);
24087 		return;
24088 	}
24089 
24090 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24091 	    "ip_wput_frag_start:");
24092 
24093 	if (mp->b_datap->db_type == M_CTL) {
24094 		first_mp = mp;
24095 		mp_orig = mp = mp->b_cont;
24096 		mctl_present = B_TRUE;
24097 	} else {
24098 		first_mp = mp;
24099 		mctl_present = B_FALSE;
24100 	}
24101 
24102 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24103 	ipha = (ipha_t *)mp->b_rptr;
24104 
24105 	/*
24106 	 * If the Don't Fragment flag is on, generate an ICMP destination
24107 	 * unreachable, fragmentation needed.
24108 	 */
24109 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24110 	if (offset & IPH_DF) {
24111 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24112 		if (is_system_labeled()) {
24113 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24114 			    ire->ire_max_frag - max_frag, AF_INET);
24115 		}
24116 		/*
24117 		 * Need to compute hdr checksum if called from ip_wput_ire.
24118 		 * Note that ip_rput_forward verifies the checksum before
24119 		 * calling this routine so in that case this is a noop.
24120 		 */
24121 		ipha->ipha_hdr_checksum = 0;
24122 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24123 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24124 		    ipst);
24125 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24126 		    "ip_wput_frag_end:(%S)",
24127 		    "don't fragment");
24128 		return;
24129 	}
24130 	/*
24131 	 * Labeled systems adjust max_frag if they add a label
24132 	 * to send the correct path mtu.  We need the real mtu since we
24133 	 * are fragmenting the packet after label adjustment.
24134 	 */
24135 	if (is_system_labeled())
24136 		max_frag = ire->ire_max_frag;
24137 	if (mctl_present)
24138 		freeb(first_mp);
24139 	/*
24140 	 * Establish the starting offset.  May not be zero if we are fragging
24141 	 * a fragment that is being forwarded.
24142 	 */
24143 	offset = offset & IPH_OFFSET;
24144 
24145 	/* TODO why is this test needed? */
24146 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24147 	if (((max_frag - LENGTH) & ~7) < 8) {
24148 		/* TODO: notify ulp somehow */
24149 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24150 		freemsg(mp);
24151 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24152 		    "ip_wput_frag_end:(%S)",
24153 		    "len < 8");
24154 		return;
24155 	}
24156 
24157 	hdr_len = (V_HLEN & 0xF) << 2;
24158 
24159 	ipha->ipha_hdr_checksum = 0;
24160 
24161 	/*
24162 	 * Establish the number of bytes maximum per frag, after putting
24163 	 * in the header.
24164 	 */
24165 	len = (max_frag - hdr_len) & ~7;
24166 
24167 	/* Check if we can use MDT to send out the frags. */
24168 	ASSERT(!IRE_IS_LOCAL(ire));
24169 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24170 	    ipst->ips_ip_multidata_outbound &&
24171 	    !(ire->ire_flags & RTF_MULTIRT) &&
24172 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24173 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24174 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24175 		ASSERT(ill->ill_mdt_capab != NULL);
24176 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24177 			/*
24178 			 * If MDT has been previously turned off in the past,
24179 			 * and we currently can do MDT (due to IPQoS policy
24180 			 * removal, etc.) then enable it for this interface.
24181 			 */
24182 			ill->ill_mdt_capab->ill_mdt_on = 1;
24183 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24184 			    ill->ill_name));
24185 		}
24186 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24187 		    offset);
24188 		return;
24189 	}
24190 
24191 	/* Get a copy of the header for the trailing frags */
24192 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24193 	if (!hdr_mp) {
24194 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24195 		freemsg(mp);
24196 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24197 		    "ip_wput_frag_end:(%S)",
24198 		    "couldn't copy hdr");
24199 		return;
24200 	}
24201 	if (DB_CRED(mp) != NULL)
24202 		mblk_setcred(hdr_mp, DB_CRED(mp));
24203 
24204 	/* Store the starting offset, with the MoreFrags flag. */
24205 	i1 = offset | IPH_MF | frag_flag;
24206 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24207 
24208 	/* Establish the ending byte offset, based on the starting offset. */
24209 	offset <<= 3;
24210 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24211 
24212 	/* Store the length of the first fragment in the IP header. */
24213 	i1 = len + hdr_len;
24214 	ASSERT(i1 <= IP_MAXPACKET);
24215 	ipha->ipha_length = htons((uint16_t)i1);
24216 
24217 	/*
24218 	 * Compute the IP header checksum for the first frag.  We have to
24219 	 * watch out that we stop at the end of the header.
24220 	 */
24221 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24222 
24223 	/*
24224 	 * Now carve off the first frag.  Note that this will include the
24225 	 * original IP header.
24226 	 */
24227 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24228 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24229 		freeb(hdr_mp);
24230 		freemsg(mp_orig);
24231 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24232 		    "ip_wput_frag_end:(%S)",
24233 		    "couldn't carve first");
24234 		return;
24235 	}
24236 
24237 	/*
24238 	 * Multirouting case. Each fragment is replicated
24239 	 * via all non-condemned RTF_MULTIRT routes
24240 	 * currently resolved.
24241 	 * We ensure that first_ire is the first RTF_MULTIRT
24242 	 * ire in the bucket.
24243 	 */
24244 	if (ire->ire_flags & RTF_MULTIRT) {
24245 		irb = ire->ire_bucket;
24246 		ASSERT(irb != NULL);
24247 
24248 		multirt_send = B_TRUE;
24249 
24250 		/* Make sure we do not omit any multiroute ire. */
24251 		IRB_REFHOLD(irb);
24252 		for (first_ire = irb->irb_ire;
24253 		    first_ire != NULL;
24254 		    first_ire = first_ire->ire_next) {
24255 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24256 			    (first_ire->ire_addr == ire->ire_addr) &&
24257 			    !(first_ire->ire_marks &
24258 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24259 				break;
24260 			}
24261 		}
24262 
24263 		if (first_ire != NULL) {
24264 			if (first_ire != ire) {
24265 				IRE_REFHOLD(first_ire);
24266 				/*
24267 				 * Do not release the ire passed in
24268 				 * as the argument.
24269 				 */
24270 				ire = first_ire;
24271 			} else {
24272 				first_ire = NULL;
24273 			}
24274 		}
24275 		IRB_REFRELE(irb);
24276 
24277 		/*
24278 		 * Save the first ire; we will need to restore it
24279 		 * for the trailing frags.
24280 		 * We REFHOLD save_ire, as each iterated ire will be
24281 		 * REFRELEd.
24282 		 */
24283 		save_ire = ire;
24284 		IRE_REFHOLD(save_ire);
24285 	}
24286 
24287 	/*
24288 	 * First fragment emission loop.
24289 	 * In most cases, the emission loop below is entered only
24290 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24291 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24292 	 * bucket, and send the fragment through all crossed
24293 	 * RTF_MULTIRT routes.
24294 	 */
24295 	do {
24296 		if (ire->ire_flags & RTF_MULTIRT) {
24297 			/*
24298 			 * We are in a multiple send case, need to get
24299 			 * the next ire and make a copy of the packet.
24300 			 * ire1 holds here the next ire to process in the
24301 			 * bucket. If multirouting is expected,
24302 			 * any non-RTF_MULTIRT ire that has the
24303 			 * right destination address is ignored.
24304 			 *
24305 			 * We have to take into account the MTU of
24306 			 * each walked ire. max_frag is set by the
24307 			 * the caller and generally refers to
24308 			 * the primary ire entry. Here we ensure that
24309 			 * no route with a lower MTU will be used, as
24310 			 * fragments are carved once for all ires,
24311 			 * then replicated.
24312 			 */
24313 			ASSERT(irb != NULL);
24314 			IRB_REFHOLD(irb);
24315 			for (ire1 = ire->ire_next;
24316 			    ire1 != NULL;
24317 			    ire1 = ire1->ire_next) {
24318 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24319 					continue;
24320 				if (ire1->ire_addr != ire->ire_addr)
24321 					continue;
24322 				if (ire1->ire_marks &
24323 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24324 					continue;
24325 				/*
24326 				 * Ensure we do not exceed the MTU
24327 				 * of the next route.
24328 				 */
24329 				if (ire1->ire_max_frag < max_frag) {
24330 					ip_multirt_bad_mtu(ire1, max_frag);
24331 					continue;
24332 				}
24333 
24334 				/* Got one. */
24335 				IRE_REFHOLD(ire1);
24336 				break;
24337 			}
24338 			IRB_REFRELE(irb);
24339 
24340 			if (ire1 != NULL) {
24341 				next_mp = copyb(mp);
24342 				if ((next_mp == NULL) ||
24343 				    ((mp->b_cont != NULL) &&
24344 				    ((next_mp->b_cont =
24345 				    dupmsg(mp->b_cont)) == NULL))) {
24346 					freemsg(next_mp);
24347 					next_mp = NULL;
24348 					ire_refrele(ire1);
24349 					ire1 = NULL;
24350 				}
24351 			}
24352 
24353 			/* Last multiroute ire; don't loop anymore. */
24354 			if (ire1 == NULL) {
24355 				multirt_send = B_FALSE;
24356 			}
24357 		}
24358 
24359 		ll_hdr_len = 0;
24360 		LOCK_IRE_FP_MP(ire);
24361 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24362 		if (ll_hdr_mp != NULL) {
24363 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24364 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24365 		} else {
24366 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24367 		}
24368 
24369 		/* If there is a transmit header, get a copy for this frag. */
24370 		/*
24371 		 * TODO: should check db_ref before calling ip_carve_mp since
24372 		 * it might give us a dup.
24373 		 */
24374 		if (!ll_hdr_mp) {
24375 			/* No xmit header. */
24376 			xmit_mp = mp;
24377 
24378 		/* We have a link-layer header that can fit in our mblk. */
24379 		} else if (mp->b_datap->db_ref == 1 &&
24380 		    ll_hdr_len != 0 &&
24381 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24382 			/* M_DATA fastpath */
24383 			mp->b_rptr -= ll_hdr_len;
24384 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24385 			xmit_mp = mp;
24386 
24387 		/* Corner case if copyb has failed */
24388 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24389 			UNLOCK_IRE_FP_MP(ire);
24390 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24391 			freeb(hdr_mp);
24392 			freemsg(mp);
24393 			freemsg(mp_orig);
24394 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24395 			    "ip_wput_frag_end:(%S)",
24396 			    "discard");
24397 
24398 			if (multirt_send) {
24399 				ASSERT(ire1);
24400 				ASSERT(next_mp);
24401 
24402 				freemsg(next_mp);
24403 				ire_refrele(ire1);
24404 			}
24405 			if (save_ire != NULL)
24406 				IRE_REFRELE(save_ire);
24407 
24408 			if (first_ire != NULL)
24409 				ire_refrele(first_ire);
24410 			return;
24411 
24412 		/*
24413 		 * Case of res_mp OR the fastpath mp can't fit
24414 		 * in the mblk
24415 		 */
24416 		} else {
24417 			xmit_mp->b_cont = mp;
24418 			if (DB_CRED(mp) != NULL)
24419 				mblk_setcred(xmit_mp, DB_CRED(mp));
24420 			/*
24421 			 * Get priority marking, if any.
24422 			 * We propagate the CoS marking from the
24423 			 * original packet that went to QoS processing
24424 			 * in ip_wput_ire to the newly carved mp.
24425 			 */
24426 			if (DB_TYPE(xmit_mp) == M_DATA)
24427 				xmit_mp->b_band = mp->b_band;
24428 		}
24429 		UNLOCK_IRE_FP_MP(ire);
24430 
24431 		q = ire->ire_stq;
24432 		out_ill = (ill_t *)q->q_ptr;
24433 
24434 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24435 
24436 		DTRACE_PROBE4(ip4__physical__out__start,
24437 		    ill_t *, NULL, ill_t *, out_ill,
24438 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24439 
24440 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24441 		    ipst->ips_ipv4firewall_physical_out,
24442 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24443 
24444 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24445 
24446 		if (xmit_mp != NULL) {
24447 			putnext(q, xmit_mp);
24448 
24449 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24450 			UPDATE_MIB(out_ill->ill_ip_mib,
24451 			    ipIfStatsHCOutOctets, i1);
24452 
24453 			if (pkt_type != OB_PKT) {
24454 				/*
24455 				 * Update the packet count and MIB stats
24456 				 * of trailing RTF_MULTIRT ires.
24457 				 */
24458 				UPDATE_OB_PKT_COUNT(ire);
24459 				BUMP_MIB(out_ill->ill_ip_mib,
24460 				    ipIfStatsOutFragReqds);
24461 			}
24462 		}
24463 
24464 		if (multirt_send) {
24465 			/*
24466 			 * We are in a multiple send case; look for
24467 			 * the next ire and re-enter the loop.
24468 			 */
24469 			ASSERT(ire1);
24470 			ASSERT(next_mp);
24471 			/* REFRELE the current ire before looping */
24472 			ire_refrele(ire);
24473 			ire = ire1;
24474 			ire1 = NULL;
24475 			mp = next_mp;
24476 			next_mp = NULL;
24477 		}
24478 	} while (multirt_send);
24479 
24480 	ASSERT(ire1 == NULL);
24481 
24482 	/* Restore the original ire; we need it for the trailing frags */
24483 	if (save_ire != NULL) {
24484 		/* REFRELE the last iterated ire */
24485 		ire_refrele(ire);
24486 		/* save_ire has been REFHOLDed */
24487 		ire = save_ire;
24488 		save_ire = NULL;
24489 		q = ire->ire_stq;
24490 	}
24491 
24492 	if (pkt_type == OB_PKT) {
24493 		UPDATE_OB_PKT_COUNT(ire);
24494 	} else {
24495 		out_ill = (ill_t *)q->q_ptr;
24496 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24497 		UPDATE_IB_PKT_COUNT(ire);
24498 	}
24499 
24500 	/* Advance the offset to the second frag starting point. */
24501 	offset += len;
24502 	/*
24503 	 * Update hdr_len from the copied header - there might be less options
24504 	 * in the later fragments.
24505 	 */
24506 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24507 	/* Loop until done. */
24508 	for (;;) {
24509 		uint16_t	offset_and_flags;
24510 		uint16_t	ip_len;
24511 
24512 		if (ip_data_end - offset > len) {
24513 			/*
24514 			 * Carve off the appropriate amount from the original
24515 			 * datagram.
24516 			 */
24517 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24518 				mp = NULL;
24519 				break;
24520 			}
24521 			/*
24522 			 * More frags after this one.  Get another copy
24523 			 * of the header.
24524 			 */
24525 			if (carve_mp->b_datap->db_ref == 1 &&
24526 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24527 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24528 				/* Inline IP header */
24529 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24530 				    hdr_mp->b_rptr;
24531 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24532 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24533 				mp = carve_mp;
24534 			} else {
24535 				if (!(mp = copyb(hdr_mp))) {
24536 					freemsg(carve_mp);
24537 					break;
24538 				}
24539 				/* Get priority marking, if any. */
24540 				mp->b_band = carve_mp->b_band;
24541 				mp->b_cont = carve_mp;
24542 			}
24543 			ipha = (ipha_t *)mp->b_rptr;
24544 			offset_and_flags = IPH_MF;
24545 		} else {
24546 			/*
24547 			 * Last frag.  Consume the header. Set len to
24548 			 * the length of this last piece.
24549 			 */
24550 			len = ip_data_end - offset;
24551 
24552 			/*
24553 			 * Carve off the appropriate amount from the original
24554 			 * datagram.
24555 			 */
24556 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24557 				mp = NULL;
24558 				break;
24559 			}
24560 			if (carve_mp->b_datap->db_ref == 1 &&
24561 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24562 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24563 				/* Inline IP header */
24564 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24565 				    hdr_mp->b_rptr;
24566 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24567 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24568 				mp = carve_mp;
24569 				freeb(hdr_mp);
24570 				hdr_mp = mp;
24571 			} else {
24572 				mp = hdr_mp;
24573 				/* Get priority marking, if any. */
24574 				mp->b_band = carve_mp->b_band;
24575 				mp->b_cont = carve_mp;
24576 			}
24577 			ipha = (ipha_t *)mp->b_rptr;
24578 			/* A frag of a frag might have IPH_MF non-zero */
24579 			offset_and_flags =
24580 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24581 			    IPH_MF;
24582 		}
24583 		offset_and_flags |= (uint16_t)(offset >> 3);
24584 		offset_and_flags |= (uint16_t)frag_flag;
24585 		/* Store the offset and flags in the IP header. */
24586 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24587 
24588 		/* Store the length in the IP header. */
24589 		ip_len = (uint16_t)(len + hdr_len);
24590 		ipha->ipha_length = htons(ip_len);
24591 
24592 		/*
24593 		 * Set the IP header checksum.	Note that mp is just
24594 		 * the header, so this is easy to pass to ip_csum.
24595 		 */
24596 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24597 
24598 		/* Attach a transmit header, if any, and ship it. */
24599 		if (pkt_type == OB_PKT) {
24600 			UPDATE_OB_PKT_COUNT(ire);
24601 		} else {
24602 			out_ill = (ill_t *)q->q_ptr;
24603 			BUMP_MIB(out_ill->ill_ip_mib,
24604 			    ipIfStatsHCOutForwDatagrams);
24605 			UPDATE_IB_PKT_COUNT(ire);
24606 		}
24607 
24608 		if (ire->ire_flags & RTF_MULTIRT) {
24609 			irb = ire->ire_bucket;
24610 			ASSERT(irb != NULL);
24611 
24612 			multirt_send = B_TRUE;
24613 
24614 			/*
24615 			 * Save the original ire; we will need to restore it
24616 			 * for the tailing frags.
24617 			 */
24618 			save_ire = ire;
24619 			IRE_REFHOLD(save_ire);
24620 		}
24621 		/*
24622 		 * Emission loop for this fragment, similar
24623 		 * to what is done for the first fragment.
24624 		 */
24625 		do {
24626 			if (multirt_send) {
24627 				/*
24628 				 * We are in a multiple send case, need to get
24629 				 * the next ire and make a copy of the packet.
24630 				 */
24631 				ASSERT(irb != NULL);
24632 				IRB_REFHOLD(irb);
24633 				for (ire1 = ire->ire_next;
24634 				    ire1 != NULL;
24635 				    ire1 = ire1->ire_next) {
24636 					if (!(ire1->ire_flags & RTF_MULTIRT))
24637 						continue;
24638 					if (ire1->ire_addr != ire->ire_addr)
24639 						continue;
24640 					if (ire1->ire_marks &
24641 					    (IRE_MARK_CONDEMNED|
24642 					    IRE_MARK_HIDDEN)) {
24643 						continue;
24644 					}
24645 					/*
24646 					 * Ensure we do not exceed the MTU
24647 					 * of the next route.
24648 					 */
24649 					if (ire1->ire_max_frag < max_frag) {
24650 						ip_multirt_bad_mtu(ire1,
24651 						    max_frag);
24652 						continue;
24653 					}
24654 
24655 					/* Got one. */
24656 					IRE_REFHOLD(ire1);
24657 					break;
24658 				}
24659 				IRB_REFRELE(irb);
24660 
24661 				if (ire1 != NULL) {
24662 					next_mp = copyb(mp);
24663 					if ((next_mp == NULL) ||
24664 					    ((mp->b_cont != NULL) &&
24665 					    ((next_mp->b_cont =
24666 					    dupmsg(mp->b_cont)) == NULL))) {
24667 						freemsg(next_mp);
24668 						next_mp = NULL;
24669 						ire_refrele(ire1);
24670 						ire1 = NULL;
24671 					}
24672 				}
24673 
24674 				/* Last multiroute ire; don't loop anymore. */
24675 				if (ire1 == NULL) {
24676 					multirt_send = B_FALSE;
24677 				}
24678 			}
24679 
24680 			/* Update transmit header */
24681 			ll_hdr_len = 0;
24682 			LOCK_IRE_FP_MP(ire);
24683 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24684 			if (ll_hdr_mp != NULL) {
24685 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24686 				ll_hdr_len = MBLKL(ll_hdr_mp);
24687 			} else {
24688 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24689 			}
24690 
24691 			if (!ll_hdr_mp) {
24692 				xmit_mp = mp;
24693 
24694 			/*
24695 			 * We have link-layer header that can fit in
24696 			 * our mblk.
24697 			 */
24698 			} else if (mp->b_datap->db_ref == 1 &&
24699 			    ll_hdr_len != 0 &&
24700 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24701 				/* M_DATA fastpath */
24702 				mp->b_rptr -= ll_hdr_len;
24703 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24704 				    ll_hdr_len);
24705 				xmit_mp = mp;
24706 
24707 			/*
24708 			 * Case of res_mp OR the fastpath mp can't fit
24709 			 * in the mblk
24710 			 */
24711 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24712 				xmit_mp->b_cont = mp;
24713 				if (DB_CRED(mp) != NULL)
24714 					mblk_setcred(xmit_mp, DB_CRED(mp));
24715 				/* Get priority marking, if any. */
24716 				if (DB_TYPE(xmit_mp) == M_DATA)
24717 					xmit_mp->b_band = mp->b_band;
24718 
24719 			/* Corner case if copyb failed */
24720 			} else {
24721 				/*
24722 				 * Exit both the replication and
24723 				 * fragmentation loops.
24724 				 */
24725 				UNLOCK_IRE_FP_MP(ire);
24726 				goto drop_pkt;
24727 			}
24728 			UNLOCK_IRE_FP_MP(ire);
24729 
24730 			mp1 = mp;
24731 			out_ill = (ill_t *)q->q_ptr;
24732 
24733 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24734 
24735 			DTRACE_PROBE4(ip4__physical__out__start,
24736 			    ill_t *, NULL, ill_t *, out_ill,
24737 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24738 
24739 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24740 			    ipst->ips_ipv4firewall_physical_out,
24741 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24742 
24743 			DTRACE_PROBE1(ip4__physical__out__end,
24744 			    mblk_t *, xmit_mp);
24745 
24746 			if (mp != mp1 && hdr_mp == mp1)
24747 				hdr_mp = mp;
24748 			if (mp != mp1 && mp_orig == mp1)
24749 				mp_orig = mp;
24750 
24751 			if (xmit_mp != NULL) {
24752 				putnext(q, xmit_mp);
24753 
24754 				BUMP_MIB(out_ill->ill_ip_mib,
24755 				    ipIfStatsHCOutTransmits);
24756 				UPDATE_MIB(out_ill->ill_ip_mib,
24757 				    ipIfStatsHCOutOctets, ip_len);
24758 
24759 				if (pkt_type != OB_PKT) {
24760 					/*
24761 					 * Update the packet count of trailing
24762 					 * RTF_MULTIRT ires.
24763 					 */
24764 					UPDATE_OB_PKT_COUNT(ire);
24765 				}
24766 			}
24767 
24768 			/* All done if we just consumed the hdr_mp. */
24769 			if (mp == hdr_mp) {
24770 				last_frag = B_TRUE;
24771 				BUMP_MIB(out_ill->ill_ip_mib,
24772 				    ipIfStatsOutFragOKs);
24773 			}
24774 
24775 			if (multirt_send) {
24776 				/*
24777 				 * We are in a multiple send case; look for
24778 				 * the next ire and re-enter the loop.
24779 				 */
24780 				ASSERT(ire1);
24781 				ASSERT(next_mp);
24782 				/* REFRELE the current ire before looping */
24783 				ire_refrele(ire);
24784 				ire = ire1;
24785 				ire1 = NULL;
24786 				q = ire->ire_stq;
24787 				mp = next_mp;
24788 				next_mp = NULL;
24789 			}
24790 		} while (multirt_send);
24791 		/*
24792 		 * Restore the original ire; we need it for the
24793 		 * trailing frags
24794 		 */
24795 		if (save_ire != NULL) {
24796 			ASSERT(ire1 == NULL);
24797 			/* REFRELE the last iterated ire */
24798 			ire_refrele(ire);
24799 			/* save_ire has been REFHOLDed */
24800 			ire = save_ire;
24801 			q = ire->ire_stq;
24802 			save_ire = NULL;
24803 		}
24804 
24805 		if (last_frag) {
24806 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24807 			    "ip_wput_frag_end:(%S)",
24808 			    "consumed hdr_mp");
24809 
24810 			if (first_ire != NULL)
24811 				ire_refrele(first_ire);
24812 			return;
24813 		}
24814 		/* Otherwise, advance and loop. */
24815 		offset += len;
24816 	}
24817 
24818 drop_pkt:
24819 	/* Clean up following allocation failure. */
24820 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24821 	freemsg(mp);
24822 	if (mp != hdr_mp)
24823 		freeb(hdr_mp);
24824 	if (mp != mp_orig)
24825 		freemsg(mp_orig);
24826 
24827 	if (save_ire != NULL)
24828 		IRE_REFRELE(save_ire);
24829 	if (first_ire != NULL)
24830 		ire_refrele(first_ire);
24831 
24832 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24833 	    "ip_wput_frag_end:(%S)",
24834 	    "end--alloc failure");
24835 }
24836 
24837 /*
24838  * Copy the header plus those options which have the copy bit set
24839  */
24840 static mblk_t *
24841 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24842 {
24843 	mblk_t	*mp;
24844 	uchar_t	*up;
24845 
24846 	/*
24847 	 * Quick check if we need to look for options without the copy bit
24848 	 * set
24849 	 */
24850 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24851 	if (!mp)
24852 		return (mp);
24853 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24854 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24855 		bcopy(rptr, mp->b_rptr, hdr_len);
24856 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24857 		return (mp);
24858 	}
24859 	up  = mp->b_rptr;
24860 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24861 	up += IP_SIMPLE_HDR_LENGTH;
24862 	rptr += IP_SIMPLE_HDR_LENGTH;
24863 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24864 	while (hdr_len > 0) {
24865 		uint32_t optval;
24866 		uint32_t optlen;
24867 
24868 		optval = *rptr;
24869 		if (optval == IPOPT_EOL)
24870 			break;
24871 		if (optval == IPOPT_NOP)
24872 			optlen = 1;
24873 		else
24874 			optlen = rptr[1];
24875 		if (optval & IPOPT_COPY) {
24876 			bcopy(rptr, up, optlen);
24877 			up += optlen;
24878 		}
24879 		rptr += optlen;
24880 		hdr_len -= optlen;
24881 	}
24882 	/*
24883 	 * Make sure that we drop an even number of words by filling
24884 	 * with EOL to the next word boundary.
24885 	 */
24886 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24887 	    hdr_len & 0x3; hdr_len++)
24888 		*up++ = IPOPT_EOL;
24889 	mp->b_wptr = up;
24890 	/* Update header length */
24891 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24892 	return (mp);
24893 }
24894 
24895 /*
24896  * Delivery to local recipients including fanout to multiple recipients.
24897  * Does not do checksumming of UDP/TCP.
24898  * Note: q should be the read side queue for either the ill or conn.
24899  * Note: rq should be the read side q for the lower (ill) stream.
24900  * We don't send packets to IPPF processing, thus the last argument
24901  * to all the fanout calls are B_FALSE.
24902  */
24903 void
24904 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24905     int fanout_flags, zoneid_t zoneid)
24906 {
24907 	uint32_t	protocol;
24908 	mblk_t		*first_mp;
24909 	boolean_t	mctl_present;
24910 	int		ire_type;
24911 #define	rptr	((uchar_t *)ipha)
24912 	ip_stack_t	*ipst = ill->ill_ipst;
24913 
24914 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24915 	    "ip_wput_local_start: q %p", q);
24916 
24917 	if (ire != NULL) {
24918 		ire_type = ire->ire_type;
24919 	} else {
24920 		/*
24921 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24922 		 * packet is not multicast, we can't tell the ire type.
24923 		 */
24924 		ASSERT(CLASSD(ipha->ipha_dst));
24925 		ire_type = IRE_BROADCAST;
24926 	}
24927 
24928 	first_mp = mp;
24929 	if (first_mp->b_datap->db_type == M_CTL) {
24930 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24931 		if (!io->ipsec_out_secure) {
24932 			/*
24933 			 * This ipsec_out_t was allocated in ip_wput
24934 			 * for multicast packets to store the ill_index.
24935 			 * As this is being delivered locally, we don't
24936 			 * need this anymore.
24937 			 */
24938 			mp = first_mp->b_cont;
24939 			freeb(first_mp);
24940 			first_mp = mp;
24941 			mctl_present = B_FALSE;
24942 		} else {
24943 			/*
24944 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24945 			 * security properties for the looped-back packet.
24946 			 */
24947 			mctl_present = B_TRUE;
24948 			mp = first_mp->b_cont;
24949 			ASSERT(mp != NULL);
24950 			ipsec_out_to_in(first_mp);
24951 		}
24952 	} else {
24953 		mctl_present = B_FALSE;
24954 	}
24955 
24956 	DTRACE_PROBE4(ip4__loopback__in__start,
24957 	    ill_t *, ill, ill_t *, NULL,
24958 	    ipha_t *, ipha, mblk_t *, first_mp);
24959 
24960 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24961 	    ipst->ips_ipv4firewall_loopback_in,
24962 	    ill, NULL, ipha, first_mp, mp, ipst);
24963 
24964 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24965 
24966 	if (first_mp == NULL)
24967 		return;
24968 
24969 	ipst->ips_loopback_packets++;
24970 
24971 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24972 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24973 	if (!IS_SIMPLE_IPH(ipha)) {
24974 		ip_wput_local_options(ipha, ipst);
24975 	}
24976 
24977 	protocol = ipha->ipha_protocol;
24978 	switch (protocol) {
24979 	case IPPROTO_ICMP: {
24980 		ire_t		*ire_zone;
24981 		ilm_t		*ilm;
24982 		mblk_t		*mp1;
24983 		zoneid_t	last_zoneid;
24984 
24985 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24986 			ASSERT(ire_type == IRE_BROADCAST);
24987 			/*
24988 			 * In the multicast case, applications may have joined
24989 			 * the group from different zones, so we need to deliver
24990 			 * the packet to each of them. Loop through the
24991 			 * multicast memberships structures (ilm) on the receive
24992 			 * ill and send a copy of the packet up each matching
24993 			 * one. However, we don't do this for multicasts sent on
24994 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24995 			 * they must stay in the sender's zone.
24996 			 *
24997 			 * ilm_add_v6() ensures that ilms in the same zone are
24998 			 * contiguous in the ill_ilm list. We use this property
24999 			 * to avoid sending duplicates needed when two
25000 			 * applications in the same zone join the same group on
25001 			 * different logical interfaces: we ignore the ilm if
25002 			 * it's zoneid is the same as the last matching one.
25003 			 * In addition, the sending of the packet for
25004 			 * ire_zoneid is delayed until all of the other ilms
25005 			 * have been exhausted.
25006 			 */
25007 			last_zoneid = -1;
25008 			ILM_WALKER_HOLD(ill);
25009 			for (ilm = ill->ill_ilm; ilm != NULL;
25010 			    ilm = ilm->ilm_next) {
25011 				if ((ilm->ilm_flags & ILM_DELETED) ||
25012 				    ipha->ipha_dst != ilm->ilm_addr ||
25013 				    ilm->ilm_zoneid == last_zoneid ||
25014 				    ilm->ilm_zoneid == zoneid ||
25015 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25016 					continue;
25017 				mp1 = ip_copymsg(first_mp);
25018 				if (mp1 == NULL)
25019 					continue;
25020 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25021 				    mctl_present, B_FALSE, ill,
25022 				    ilm->ilm_zoneid);
25023 				last_zoneid = ilm->ilm_zoneid;
25024 			}
25025 			ILM_WALKER_RELE(ill);
25026 			/*
25027 			 * Loopback case: the sending endpoint has
25028 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25029 			 * dispatch the multicast packet to the sending zone.
25030 			 */
25031 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25032 				freemsg(first_mp);
25033 				return;
25034 			}
25035 		} else if (ire_type == IRE_BROADCAST) {
25036 			/*
25037 			 * In the broadcast case, there may be many zones
25038 			 * which need a copy of the packet delivered to them.
25039 			 * There is one IRE_BROADCAST per broadcast address
25040 			 * and per zone; we walk those using a helper function.
25041 			 * In addition, the sending of the packet for zoneid is
25042 			 * delayed until all of the other ires have been
25043 			 * processed.
25044 			 */
25045 			IRB_REFHOLD(ire->ire_bucket);
25046 			ire_zone = NULL;
25047 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25048 			    ire)) != NULL) {
25049 				mp1 = ip_copymsg(first_mp);
25050 				if (mp1 == NULL)
25051 					continue;
25052 
25053 				UPDATE_IB_PKT_COUNT(ire_zone);
25054 				ire_zone->ire_last_used_time = lbolt;
25055 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25056 				    mctl_present, B_FALSE, ill,
25057 				    ire_zone->ire_zoneid);
25058 			}
25059 			IRB_REFRELE(ire->ire_bucket);
25060 		}
25061 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25062 		    0, mctl_present, B_FALSE, ill, zoneid);
25063 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25064 		    "ip_wput_local_end: q %p (%S)",
25065 		    q, "icmp");
25066 		return;
25067 	}
25068 	case IPPROTO_IGMP:
25069 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25070 			/* Bad packet - discarded by igmp_input */
25071 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25072 			    "ip_wput_local_end: q %p (%S)",
25073 			    q, "igmp_input--bad packet");
25074 			if (mctl_present)
25075 				freeb(first_mp);
25076 			return;
25077 		}
25078 		/*
25079 		 * igmp_input() may have returned the pulled up message.
25080 		 * So first_mp and ipha need to be reinitialized.
25081 		 */
25082 		ipha = (ipha_t *)mp->b_rptr;
25083 		if (mctl_present)
25084 			first_mp->b_cont = mp;
25085 		else
25086 			first_mp = mp;
25087 		/* deliver to local raw users */
25088 		break;
25089 	case IPPROTO_ENCAP:
25090 		/*
25091 		 * This case is covered by either ip_fanout_proto, or by
25092 		 * the above security processing for self-tunneled packets.
25093 		 */
25094 		break;
25095 	case IPPROTO_UDP: {
25096 		uint16_t	*up;
25097 		uint32_t	ports;
25098 
25099 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25100 		    UDP_PORTS_OFFSET);
25101 		/* Force a 'valid' checksum. */
25102 		up[3] = 0;
25103 
25104 		ports = *(uint32_t *)up;
25105 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25106 		    (ire_type == IRE_BROADCAST),
25107 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25108 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25109 		    ill, zoneid);
25110 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25111 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25112 		return;
25113 	}
25114 	case IPPROTO_TCP: {
25115 
25116 		/*
25117 		 * For TCP, discard broadcast packets.
25118 		 */
25119 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25120 			freemsg(first_mp);
25121 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25122 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25123 			return;
25124 		}
25125 
25126 		if (mp->b_datap->db_type == M_DATA) {
25127 			/*
25128 			 * M_DATA mblk, so init mblk (chain) for no struio().
25129 			 */
25130 			mblk_t	*mp1 = mp;
25131 
25132 			do {
25133 				mp1->b_datap->db_struioflag = 0;
25134 			} while ((mp1 = mp1->b_cont) != NULL);
25135 		}
25136 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25137 		    <= mp->b_wptr);
25138 		ip_fanout_tcp(q, first_mp, ill, ipha,
25139 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25140 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25141 		    mctl_present, B_FALSE, zoneid);
25142 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25143 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25144 		return;
25145 	}
25146 	case IPPROTO_SCTP:
25147 	{
25148 		uint32_t	ports;
25149 
25150 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25151 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25152 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25153 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25154 		return;
25155 	}
25156 
25157 	default:
25158 		break;
25159 	}
25160 	/*
25161 	 * Find a client for some other protocol.  We give
25162 	 * copies to multiple clients, if more than one is
25163 	 * bound.
25164 	 */
25165 	ip_fanout_proto(q, first_mp, ill, ipha,
25166 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25167 	    mctl_present, B_FALSE, ill, zoneid);
25168 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25169 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25170 #undef	rptr
25171 }
25172 
25173 /*
25174  * Update any source route, record route, or timestamp options.
25175  * Check that we are at end of strict source route.
25176  * The options have been sanity checked by ip_wput_options().
25177  */
25178 static void
25179 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25180 {
25181 	ipoptp_t	opts;
25182 	uchar_t		*opt;
25183 	uint8_t		optval;
25184 	uint8_t		optlen;
25185 	ipaddr_t	dst;
25186 	uint32_t	ts;
25187 	ire_t		*ire;
25188 	timestruc_t	now;
25189 
25190 	ip2dbg(("ip_wput_local_options\n"));
25191 	for (optval = ipoptp_first(&opts, ipha);
25192 	    optval != IPOPT_EOL;
25193 	    optval = ipoptp_next(&opts)) {
25194 		opt = opts.ipoptp_cur;
25195 		optlen = opts.ipoptp_len;
25196 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25197 		switch (optval) {
25198 			uint32_t off;
25199 		case IPOPT_SSRR:
25200 		case IPOPT_LSRR:
25201 			off = opt[IPOPT_OFFSET];
25202 			off--;
25203 			if (optlen < IP_ADDR_LEN ||
25204 			    off > optlen - IP_ADDR_LEN) {
25205 				/* End of source route */
25206 				break;
25207 			}
25208 			/*
25209 			 * This will only happen if two consecutive entries
25210 			 * in the source route contains our address or if
25211 			 * it is a packet with a loose source route which
25212 			 * reaches us before consuming the whole source route
25213 			 */
25214 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25215 			if (optval == IPOPT_SSRR) {
25216 				return;
25217 			}
25218 			/*
25219 			 * Hack: instead of dropping the packet truncate the
25220 			 * source route to what has been used by filling the
25221 			 * rest with IPOPT_NOP.
25222 			 */
25223 			opt[IPOPT_OLEN] = (uint8_t)off;
25224 			while (off < optlen) {
25225 				opt[off++] = IPOPT_NOP;
25226 			}
25227 			break;
25228 		case IPOPT_RR:
25229 			off = opt[IPOPT_OFFSET];
25230 			off--;
25231 			if (optlen < IP_ADDR_LEN ||
25232 			    off > optlen - IP_ADDR_LEN) {
25233 				/* No more room - ignore */
25234 				ip1dbg((
25235 				    "ip_wput_forward_options: end of RR\n"));
25236 				break;
25237 			}
25238 			dst = htonl(INADDR_LOOPBACK);
25239 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25240 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25241 			break;
25242 		case IPOPT_TS:
25243 			/* Insert timestamp if there is romm */
25244 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25245 			case IPOPT_TS_TSONLY:
25246 				off = IPOPT_TS_TIMELEN;
25247 				break;
25248 			case IPOPT_TS_PRESPEC:
25249 			case IPOPT_TS_PRESPEC_RFC791:
25250 				/* Verify that the address matched */
25251 				off = opt[IPOPT_OFFSET] - 1;
25252 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25253 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25254 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25255 				    ipst);
25256 				if (ire == NULL) {
25257 					/* Not for us */
25258 					break;
25259 				}
25260 				ire_refrele(ire);
25261 				/* FALLTHRU */
25262 			case IPOPT_TS_TSANDADDR:
25263 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25264 				break;
25265 			default:
25266 				/*
25267 				 * ip_*put_options should have already
25268 				 * dropped this packet.
25269 				 */
25270 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25271 				    "unknown IT - bug in ip_wput_options?\n");
25272 				return;	/* Keep "lint" happy */
25273 			}
25274 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25275 				/* Increase overflow counter */
25276 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25277 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25278 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25279 				    (off << 4);
25280 				break;
25281 			}
25282 			off = opt[IPOPT_OFFSET] - 1;
25283 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25284 			case IPOPT_TS_PRESPEC:
25285 			case IPOPT_TS_PRESPEC_RFC791:
25286 			case IPOPT_TS_TSANDADDR:
25287 				dst = htonl(INADDR_LOOPBACK);
25288 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25289 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25290 				/* FALLTHRU */
25291 			case IPOPT_TS_TSONLY:
25292 				off = opt[IPOPT_OFFSET] - 1;
25293 				/* Compute # of milliseconds since midnight */
25294 				gethrestime(&now);
25295 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25296 				    now.tv_nsec / (NANOSEC / MILLISEC);
25297 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25298 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25299 				break;
25300 			}
25301 			break;
25302 		}
25303 	}
25304 }
25305 
25306 /*
25307  * Send out a multicast packet on interface ipif.
25308  * The sender does not have an conn.
25309  * Caller verifies that this isn't a PHYI_LOOPBACK.
25310  */
25311 void
25312 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25313 {
25314 	ipha_t	*ipha;
25315 	ire_t	*ire;
25316 	ipaddr_t	dst;
25317 	mblk_t		*first_mp;
25318 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25319 
25320 	/* igmp_sendpkt always allocates a ipsec_out_t */
25321 	ASSERT(mp->b_datap->db_type == M_CTL);
25322 	ASSERT(!ipif->ipif_isv6);
25323 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25324 
25325 	first_mp = mp;
25326 	mp = first_mp->b_cont;
25327 	ASSERT(mp->b_datap->db_type == M_DATA);
25328 	ipha = (ipha_t *)mp->b_rptr;
25329 
25330 	/*
25331 	 * Find an IRE which matches the destination and the outgoing
25332 	 * queue (i.e. the outgoing interface.)
25333 	 */
25334 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25335 		dst = ipif->ipif_pp_dst_addr;
25336 	else
25337 		dst = ipha->ipha_dst;
25338 	/*
25339 	 * The source address has already been initialized by the
25340 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25341 	 * be sufficient rather than MATCH_IRE_IPIF.
25342 	 *
25343 	 * This function is used for sending IGMP packets. We need
25344 	 * to make sure that we send the packet out of the interface
25345 	 * (ipif->ipif_ill) where we joined the group. This is to
25346 	 * prevent from switches doing IGMP snooping to send us multicast
25347 	 * packets for a given group on the interface we have joined.
25348 	 * If we can't find an ire, igmp_sendpkt has already initialized
25349 	 * ipsec_out_attach_if so that this will not be load spread in
25350 	 * ip_newroute_ipif.
25351 	 */
25352 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25353 	    MATCH_IRE_ILL, ipst);
25354 	if (!ire) {
25355 		/*
25356 		 * Mark this packet to make it be delivered to
25357 		 * ip_wput_ire after the new ire has been
25358 		 * created.
25359 		 */
25360 		mp->b_prev = NULL;
25361 		mp->b_next = NULL;
25362 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25363 		    zoneid, &zero_info);
25364 		return;
25365 	}
25366 
25367 	/*
25368 	 * Honor the RTF_SETSRC flag; this is the only case
25369 	 * where we force this addr whatever the current src addr is,
25370 	 * because this address is set by igmp_sendpkt(), and
25371 	 * cannot be specified by any user.
25372 	 */
25373 	if (ire->ire_flags & RTF_SETSRC) {
25374 		ipha->ipha_src = ire->ire_src_addr;
25375 	}
25376 
25377 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25378 }
25379 
25380 /*
25381  * NOTE : This function does not ire_refrele the ire argument passed in.
25382  *
25383  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25384  * failure. The nce_fp_mp can vanish any time in the case of
25385  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25386  * the ire_lock to access the nce_fp_mp in this case.
25387  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25388  * prepending a fastpath message IPQoS processing must precede it, we also set
25389  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25390  * (IPQoS might have set the b_band for CoS marking).
25391  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25392  * must follow it so that IPQoS can mark the dl_priority field for CoS
25393  * marking, if needed.
25394  */
25395 static mblk_t *
25396 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25397 {
25398 	uint_t	hlen;
25399 	ipha_t *ipha;
25400 	mblk_t *mp1;
25401 	boolean_t qos_done = B_FALSE;
25402 	uchar_t	*ll_hdr;
25403 	ip_stack_t	*ipst = ire->ire_ipst;
25404 
25405 #define	rptr	((uchar_t *)ipha)
25406 
25407 	ipha = (ipha_t *)mp->b_rptr;
25408 	hlen = 0;
25409 	LOCK_IRE_FP_MP(ire);
25410 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25411 		ASSERT(DB_TYPE(mp1) == M_DATA);
25412 		/* Initiate IPPF processing */
25413 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25414 			UNLOCK_IRE_FP_MP(ire);
25415 			ip_process(proc, &mp, ill_index);
25416 			if (mp == NULL)
25417 				return (NULL);
25418 
25419 			ipha = (ipha_t *)mp->b_rptr;
25420 			LOCK_IRE_FP_MP(ire);
25421 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25422 				qos_done = B_TRUE;
25423 				goto no_fp_mp;
25424 			}
25425 			ASSERT(DB_TYPE(mp1) == M_DATA);
25426 		}
25427 		hlen = MBLKL(mp1);
25428 		/*
25429 		 * Check if we have enough room to prepend fastpath
25430 		 * header
25431 		 */
25432 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25433 			ll_hdr = rptr - hlen;
25434 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25435 			/*
25436 			 * Set the b_rptr to the start of the link layer
25437 			 * header
25438 			 */
25439 			mp->b_rptr = ll_hdr;
25440 			mp1 = mp;
25441 		} else {
25442 			mp1 = copyb(mp1);
25443 			if (mp1 == NULL)
25444 				goto unlock_err;
25445 			mp1->b_band = mp->b_band;
25446 			mp1->b_cont = mp;
25447 			/*
25448 			 * certain system generated traffic may not
25449 			 * have cred/label in ip header block. This
25450 			 * is true even for a labeled system. But for
25451 			 * labeled traffic, inherit the label in the
25452 			 * new header.
25453 			 */
25454 			if (DB_CRED(mp) != NULL)
25455 				mblk_setcred(mp1, DB_CRED(mp));
25456 			/*
25457 			 * XXX disable ICK_VALID and compute checksum
25458 			 * here; can happen if nce_fp_mp changes and
25459 			 * it can't be copied now due to insufficient
25460 			 * space. (unlikely, fp mp can change, but it
25461 			 * does not increase in length)
25462 			 */
25463 		}
25464 		UNLOCK_IRE_FP_MP(ire);
25465 	} else {
25466 no_fp_mp:
25467 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25468 		if (mp1 == NULL) {
25469 unlock_err:
25470 			UNLOCK_IRE_FP_MP(ire);
25471 			freemsg(mp);
25472 			return (NULL);
25473 		}
25474 		UNLOCK_IRE_FP_MP(ire);
25475 		mp1->b_cont = mp;
25476 		/*
25477 		 * certain system generated traffic may not
25478 		 * have cred/label in ip header block. This
25479 		 * is true even for a labeled system. But for
25480 		 * labeled traffic, inherit the label in the
25481 		 * new header.
25482 		 */
25483 		if (DB_CRED(mp) != NULL)
25484 			mblk_setcred(mp1, DB_CRED(mp));
25485 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25486 			ip_process(proc, &mp1, ill_index);
25487 			if (mp1 == NULL)
25488 				return (NULL);
25489 		}
25490 	}
25491 	return (mp1);
25492 #undef rptr
25493 }
25494 
25495 /*
25496  * Finish the outbound IPsec processing for an IPv6 packet. This function
25497  * is called from ipsec_out_process() if the IPsec packet was processed
25498  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25499  * asynchronously.
25500  */
25501 void
25502 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25503     ire_t *ire_arg)
25504 {
25505 	in6_addr_t *v6dstp;
25506 	ire_t *ire;
25507 	mblk_t *mp;
25508 	ip6_t *ip6h1;
25509 	uint_t	ill_index;
25510 	ipsec_out_t *io;
25511 	boolean_t attach_if, hwaccel;
25512 	uint32_t flags = IP6_NO_IPPOLICY;
25513 	int match_flags;
25514 	zoneid_t zoneid;
25515 	boolean_t ill_need_rele = B_FALSE;
25516 	boolean_t ire_need_rele = B_FALSE;
25517 	ip_stack_t	*ipst;
25518 
25519 	mp = ipsec_mp->b_cont;
25520 	ip6h1 = (ip6_t *)mp->b_rptr;
25521 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25522 	ASSERT(io->ipsec_out_ns != NULL);
25523 	ipst = io->ipsec_out_ns->netstack_ip;
25524 	ill_index = io->ipsec_out_ill_index;
25525 	if (io->ipsec_out_reachable) {
25526 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25527 	}
25528 	attach_if = io->ipsec_out_attach_if;
25529 	hwaccel = io->ipsec_out_accelerated;
25530 	zoneid = io->ipsec_out_zoneid;
25531 	ASSERT(zoneid != ALL_ZONES);
25532 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25533 	/* Multicast addresses should have non-zero ill_index. */
25534 	v6dstp = &ip6h->ip6_dst;
25535 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25536 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25537 	ASSERT(!attach_if || ill_index != 0);
25538 	if (ill_index != 0) {
25539 		if (ill == NULL) {
25540 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25541 			    B_TRUE, ipst);
25542 
25543 			/* Failure case frees things for us. */
25544 			if (ill == NULL)
25545 				return;
25546 
25547 			ill_need_rele = B_TRUE;
25548 		}
25549 		/*
25550 		 * If this packet needs to go out on a particular interface
25551 		 * honor it.
25552 		 */
25553 		if (attach_if) {
25554 			match_flags = MATCH_IRE_ILL;
25555 
25556 			/*
25557 			 * Check if we need an ire that will not be
25558 			 * looked up by anybody else i.e. HIDDEN.
25559 			 */
25560 			if (ill_is_probeonly(ill)) {
25561 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25562 			}
25563 		}
25564 	}
25565 	ASSERT(mp != NULL);
25566 
25567 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25568 		boolean_t unspec_src;
25569 		ipif_t	*ipif;
25570 
25571 		/*
25572 		 * Use the ill_index to get the right ill.
25573 		 */
25574 		unspec_src = io->ipsec_out_unspec_src;
25575 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25576 		if (ipif == NULL) {
25577 			if (ill_need_rele)
25578 				ill_refrele(ill);
25579 			freemsg(ipsec_mp);
25580 			return;
25581 		}
25582 
25583 		if (ire_arg != NULL) {
25584 			ire = ire_arg;
25585 		} else {
25586 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25587 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25588 			ire_need_rele = B_TRUE;
25589 		}
25590 		if (ire != NULL) {
25591 			ipif_refrele(ipif);
25592 			/*
25593 			 * XXX Do the multicast forwarding now, as the IPsec
25594 			 * processing has been done.
25595 			 */
25596 			goto send;
25597 		}
25598 
25599 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25600 		mp->b_prev = NULL;
25601 		mp->b_next = NULL;
25602 
25603 		/*
25604 		 * If the IPsec packet was processed asynchronously,
25605 		 * drop it now.
25606 		 */
25607 		if (q == NULL) {
25608 			if (ill_need_rele)
25609 				ill_refrele(ill);
25610 			freemsg(ipsec_mp);
25611 			return;
25612 		}
25613 
25614 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25615 		    unspec_src, zoneid);
25616 		ipif_refrele(ipif);
25617 	} else {
25618 		if (attach_if) {
25619 			ipif_t	*ipif;
25620 
25621 			ipif = ipif_get_next_ipif(NULL, ill);
25622 			if (ipif == NULL) {
25623 				if (ill_need_rele)
25624 					ill_refrele(ill);
25625 				freemsg(ipsec_mp);
25626 				return;
25627 			}
25628 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25629 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25630 			ire_need_rele = B_TRUE;
25631 			ipif_refrele(ipif);
25632 		} else {
25633 			if (ire_arg != NULL) {
25634 				ire = ire_arg;
25635 			} else {
25636 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25637 				    ipst);
25638 				ire_need_rele = B_TRUE;
25639 			}
25640 		}
25641 		if (ire != NULL)
25642 			goto send;
25643 		/*
25644 		 * ire disappeared underneath.
25645 		 *
25646 		 * What we need to do here is the ip_newroute
25647 		 * logic to get the ire without doing the IPsec
25648 		 * processing. Follow the same old path. But this
25649 		 * time, ip_wput or ire_add_then_send will call us
25650 		 * directly as all the IPsec operations are done.
25651 		 */
25652 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25653 		mp->b_prev = NULL;
25654 		mp->b_next = NULL;
25655 
25656 		/*
25657 		 * If the IPsec packet was processed asynchronously,
25658 		 * drop it now.
25659 		 */
25660 		if (q == NULL) {
25661 			if (ill_need_rele)
25662 				ill_refrele(ill);
25663 			freemsg(ipsec_mp);
25664 			return;
25665 		}
25666 
25667 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25668 		    zoneid, ipst);
25669 	}
25670 	if (ill != NULL && ill_need_rele)
25671 		ill_refrele(ill);
25672 	return;
25673 send:
25674 	if (ill != NULL && ill_need_rele)
25675 		ill_refrele(ill);
25676 
25677 	/* Local delivery */
25678 	if (ire->ire_stq == NULL) {
25679 		ill_t	*out_ill;
25680 		ASSERT(q != NULL);
25681 
25682 		/* PFHooks: LOOPBACK_OUT */
25683 		out_ill = ire->ire_ipif->ipif_ill;
25684 
25685 		DTRACE_PROBE4(ip6__loopback__out__start,
25686 		    ill_t *, NULL, ill_t *, out_ill,
25687 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25688 
25689 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25690 		    ipst->ips_ipv6firewall_loopback_out,
25691 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25692 
25693 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25694 
25695 		if (ipsec_mp != NULL)
25696 			ip_wput_local_v6(RD(q), out_ill,
25697 			    ip6h, ipsec_mp, ire, 0);
25698 		if (ire_need_rele)
25699 			ire_refrele(ire);
25700 		return;
25701 	}
25702 	/*
25703 	 * Everything is done. Send it out on the wire.
25704 	 * We force the insertion of a fragment header using the
25705 	 * IPH_FRAG_HDR flag in two cases:
25706 	 * - after reception of an ICMPv6 "packet too big" message
25707 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25708 	 * - for multirouted IPv6 packets, so that the receiver can
25709 	 *   discard duplicates according to their fragment identifier
25710 	 */
25711 	/* XXX fix flow control problems. */
25712 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25713 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25714 		if (hwaccel) {
25715 			/*
25716 			 * hardware acceleration does not handle these
25717 			 * "slow path" cases.
25718 			 */
25719 			/* IPsec KSTATS: should bump bean counter here. */
25720 			if (ire_need_rele)
25721 				ire_refrele(ire);
25722 			freemsg(ipsec_mp);
25723 			return;
25724 		}
25725 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25726 		    (mp->b_cont ? msgdsize(mp) :
25727 		    mp->b_wptr - (uchar_t *)ip6h)) {
25728 			/* IPsec KSTATS: should bump bean counter here. */
25729 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25730 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25731 			    msgdsize(mp)));
25732 			if (ire_need_rele)
25733 				ire_refrele(ire);
25734 			freemsg(ipsec_mp);
25735 			return;
25736 		}
25737 		ASSERT(mp->b_prev == NULL);
25738 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25739 		    ntohs(ip6h->ip6_plen) +
25740 		    IPV6_HDR_LEN, ire->ire_max_frag));
25741 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25742 		    ire->ire_max_frag);
25743 	} else {
25744 		UPDATE_OB_PKT_COUNT(ire);
25745 		ire->ire_last_used_time = lbolt;
25746 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25747 	}
25748 	if (ire_need_rele)
25749 		ire_refrele(ire);
25750 	freeb(ipsec_mp);
25751 }
25752 
25753 void
25754 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25755 {
25756 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25757 	da_ipsec_t *hada;	/* data attributes */
25758 	ill_t *ill = (ill_t *)q->q_ptr;
25759 
25760 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25761 
25762 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25763 		/* IPsec KSTATS: Bump lose counter here! */
25764 		freemsg(mp);
25765 		return;
25766 	}
25767 
25768 	/*
25769 	 * It's an IPsec packet that must be
25770 	 * accelerated by the Provider, and the
25771 	 * outbound ill is IPsec acceleration capable.
25772 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25773 	 * to the ill.
25774 	 * IPsec KSTATS: should bump packet counter here.
25775 	 */
25776 
25777 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25778 	if (hada_mp == NULL) {
25779 		/* IPsec KSTATS: should bump packet counter here. */
25780 		freemsg(mp);
25781 		return;
25782 	}
25783 
25784 	hada_mp->b_datap->db_type = M_CTL;
25785 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25786 	hada_mp->b_cont = mp;
25787 
25788 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25789 	bzero(hada, sizeof (da_ipsec_t));
25790 	hada->da_type = IPHADA_M_CTL;
25791 
25792 	putnext(q, hada_mp);
25793 }
25794 
25795 /*
25796  * Finish the outbound IPsec processing. This function is called from
25797  * ipsec_out_process() if the IPsec packet was processed
25798  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25799  * asynchronously.
25800  */
25801 void
25802 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25803     ire_t *ire_arg)
25804 {
25805 	uint32_t v_hlen_tos_len;
25806 	ipaddr_t	dst;
25807 	ipif_t	*ipif = NULL;
25808 	ire_t *ire;
25809 	ire_t *ire1 = NULL;
25810 	mblk_t *next_mp = NULL;
25811 	uint32_t max_frag;
25812 	boolean_t multirt_send = B_FALSE;
25813 	mblk_t *mp;
25814 	ipha_t *ipha1;
25815 	uint_t	ill_index;
25816 	ipsec_out_t *io;
25817 	boolean_t attach_if;
25818 	int match_flags;
25819 	irb_t *irb = NULL;
25820 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25821 	zoneid_t zoneid;
25822 	ipxmit_state_t	pktxmit_state;
25823 	ip_stack_t	*ipst;
25824 
25825 #ifdef	_BIG_ENDIAN
25826 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25827 #else
25828 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25829 #endif
25830 
25831 	mp = ipsec_mp->b_cont;
25832 	ipha1 = (ipha_t *)mp->b_rptr;
25833 	ASSERT(mp != NULL);
25834 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25835 	dst = ipha->ipha_dst;
25836 
25837 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25838 	ill_index = io->ipsec_out_ill_index;
25839 	attach_if = io->ipsec_out_attach_if;
25840 	zoneid = io->ipsec_out_zoneid;
25841 	ASSERT(zoneid != ALL_ZONES);
25842 	ipst = io->ipsec_out_ns->netstack_ip;
25843 	ASSERT(io->ipsec_out_ns != NULL);
25844 
25845 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25846 	if (ill_index != 0) {
25847 		if (ill == NULL) {
25848 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25849 			    ill_index, B_FALSE, ipst);
25850 
25851 			/* Failure case frees things for us. */
25852 			if (ill == NULL)
25853 				return;
25854 
25855 			ill_need_rele = B_TRUE;
25856 		}
25857 		/*
25858 		 * If this packet needs to go out on a particular interface
25859 		 * honor it.
25860 		 */
25861 		if (attach_if) {
25862 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25863 
25864 			/*
25865 			 * Check if we need an ire that will not be
25866 			 * looked up by anybody else i.e. HIDDEN.
25867 			 */
25868 			if (ill_is_probeonly(ill)) {
25869 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25870 			}
25871 		}
25872 	}
25873 
25874 	if (CLASSD(dst)) {
25875 		boolean_t conn_dontroute;
25876 		/*
25877 		 * Use the ill_index to get the right ipif.
25878 		 */
25879 		conn_dontroute = io->ipsec_out_dontroute;
25880 		if (ill_index == 0)
25881 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25882 		else
25883 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25884 		if (ipif == NULL) {
25885 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25886 			    " multicast\n"));
25887 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25888 			freemsg(ipsec_mp);
25889 			goto done;
25890 		}
25891 		/*
25892 		 * ipha_src has already been intialized with the
25893 		 * value of the ipif in ip_wput. All we need now is
25894 		 * an ire to send this downstream.
25895 		 */
25896 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25897 		    MBLK_GETLABEL(mp), match_flags, ipst);
25898 		if (ire != NULL) {
25899 			ill_t *ill1;
25900 			/*
25901 			 * Do the multicast forwarding now, as the IPsec
25902 			 * processing has been done.
25903 			 */
25904 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25905 			    (ill1 = ire_to_ill(ire))) {
25906 				if (ip_mforward(ill1, ipha, mp)) {
25907 					freemsg(ipsec_mp);
25908 					ip1dbg(("ip_wput_ipsec_out: mforward "
25909 					    "failed\n"));
25910 					ire_refrele(ire);
25911 					goto done;
25912 				}
25913 			}
25914 			goto send;
25915 		}
25916 
25917 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25918 		mp->b_prev = NULL;
25919 		mp->b_next = NULL;
25920 
25921 		/*
25922 		 * If the IPsec packet was processed asynchronously,
25923 		 * drop it now.
25924 		 */
25925 		if (q == NULL) {
25926 			freemsg(ipsec_mp);
25927 			goto done;
25928 		}
25929 
25930 		/*
25931 		 * We may be using a wrong ipif to create the ire.
25932 		 * But it is okay as the source address is assigned
25933 		 * for the packet already. Next outbound packet would
25934 		 * create the IRE with the right IPIF in ip_wput.
25935 		 *
25936 		 * Also handle RTF_MULTIRT routes.
25937 		 */
25938 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25939 		    zoneid, &zero_info);
25940 	} else {
25941 		if (attach_if) {
25942 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25943 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25944 		} else {
25945 			if (ire_arg != NULL) {
25946 				ire = ire_arg;
25947 				ire_need_rele = B_FALSE;
25948 			} else {
25949 				ire = ire_cache_lookup(dst, zoneid,
25950 				    MBLK_GETLABEL(mp), ipst);
25951 			}
25952 		}
25953 		if (ire != NULL) {
25954 			goto send;
25955 		}
25956 
25957 		/*
25958 		 * ire disappeared underneath.
25959 		 *
25960 		 * What we need to do here is the ip_newroute
25961 		 * logic to get the ire without doing the IPsec
25962 		 * processing. Follow the same old path. But this
25963 		 * time, ip_wput or ire_add_then_put will call us
25964 		 * directly as all the IPsec operations are done.
25965 		 */
25966 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25967 		mp->b_prev = NULL;
25968 		mp->b_next = NULL;
25969 
25970 		/*
25971 		 * If the IPsec packet was processed asynchronously,
25972 		 * drop it now.
25973 		 */
25974 		if (q == NULL) {
25975 			freemsg(ipsec_mp);
25976 			goto done;
25977 		}
25978 
25979 		/*
25980 		 * Since we're going through ip_newroute() again, we
25981 		 * need to make sure we don't:
25982 		 *
25983 		 *	1.) Trigger the ASSERT() with the ipha_ident
25984 		 *	    overloading.
25985 		 *	2.) Redo transport-layer checksumming, since we've
25986 		 *	    already done all that to get this far.
25987 		 *
25988 		 * The easiest way not do either of the above is to set
25989 		 * the ipha_ident field to IP_HDR_INCLUDED.
25990 		 */
25991 		ipha->ipha_ident = IP_HDR_INCLUDED;
25992 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25993 		    zoneid, ipst);
25994 	}
25995 	goto done;
25996 send:
25997 	if (ire->ire_stq == NULL) {
25998 		ill_t	*out_ill;
25999 		/*
26000 		 * Loopbacks go through ip_wput_local except for one case.
26001 		 * We come here if we generate a icmp_frag_needed message
26002 		 * after IPsec processing is over. When this function calls
26003 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26004 		 * icmp_frag_needed. The message generated comes back here
26005 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26006 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26007 		 * source address as it is usually set in ip_wput_ire. As
26008 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26009 		 * and we end up here. We can't enter ip_wput_ire once the
26010 		 * IPsec processing is over and hence we need to do it here.
26011 		 */
26012 		ASSERT(q != NULL);
26013 		UPDATE_OB_PKT_COUNT(ire);
26014 		ire->ire_last_used_time = lbolt;
26015 		if (ipha->ipha_src == 0)
26016 			ipha->ipha_src = ire->ire_src_addr;
26017 
26018 		/* PFHooks: LOOPBACK_OUT */
26019 		out_ill = ire->ire_ipif->ipif_ill;
26020 
26021 		DTRACE_PROBE4(ip4__loopback__out__start,
26022 		    ill_t *, NULL, ill_t *, out_ill,
26023 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26024 
26025 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26026 		    ipst->ips_ipv4firewall_loopback_out,
26027 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26028 
26029 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26030 
26031 		if (ipsec_mp != NULL)
26032 			ip_wput_local(RD(q), out_ill,
26033 			    ipha, ipsec_mp, ire, 0, zoneid);
26034 		if (ire_need_rele)
26035 			ire_refrele(ire);
26036 		goto done;
26037 	}
26038 
26039 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26040 		/*
26041 		 * We are through with IPsec processing.
26042 		 * Fragment this and send it on the wire.
26043 		 */
26044 		if (io->ipsec_out_accelerated) {
26045 			/*
26046 			 * The packet has been accelerated but must
26047 			 * be fragmented. This should not happen
26048 			 * since AH and ESP must not accelerate
26049 			 * packets that need fragmentation, however
26050 			 * the configuration could have changed
26051 			 * since the AH or ESP processing.
26052 			 * Drop packet.
26053 			 * IPsec KSTATS: bump bean counter here.
26054 			 */
26055 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26056 			    "fragmented accelerated packet!\n"));
26057 			freemsg(ipsec_mp);
26058 		} else {
26059 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26060 		}
26061 		if (ire_need_rele)
26062 			ire_refrele(ire);
26063 		goto done;
26064 	}
26065 
26066 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26067 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26068 	    (void *)ire->ire_ipif, (void *)ipif));
26069 
26070 	/*
26071 	 * Multiroute the secured packet, unless IPsec really
26072 	 * requires the packet to go out only through a particular
26073 	 * interface.
26074 	 */
26075 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26076 		ire_t *first_ire;
26077 		irb = ire->ire_bucket;
26078 		ASSERT(irb != NULL);
26079 		/*
26080 		 * This ire has been looked up as the one that
26081 		 * goes through the given ipif;
26082 		 * make sure we do not omit any other multiroute ire
26083 		 * that may be present in the bucket before this one.
26084 		 */
26085 		IRB_REFHOLD(irb);
26086 		for (first_ire = irb->irb_ire;
26087 		    first_ire != NULL;
26088 		    first_ire = first_ire->ire_next) {
26089 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26090 			    (first_ire->ire_addr == ire->ire_addr) &&
26091 			    !(first_ire->ire_marks &
26092 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26093 				break;
26094 			}
26095 		}
26096 
26097 		if ((first_ire != NULL) && (first_ire != ire)) {
26098 			/*
26099 			 * Don't change the ire if the packet must
26100 			 * be fragmented if sent via this new one.
26101 			 */
26102 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26103 				IRE_REFHOLD(first_ire);
26104 				if (ire_need_rele)
26105 					ire_refrele(ire);
26106 				else
26107 					ire_need_rele = B_TRUE;
26108 				ire = first_ire;
26109 			}
26110 		}
26111 		IRB_REFRELE(irb);
26112 
26113 		multirt_send = B_TRUE;
26114 		max_frag = ire->ire_max_frag;
26115 	} else {
26116 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26117 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26118 			    "flag, attach_if %d\n", attach_if));
26119 		}
26120 	}
26121 
26122 	/*
26123 	 * In most cases, the emission loop below is entered only once.
26124 	 * Only in the case where the ire holds the RTF_MULTIRT
26125 	 * flag, we loop to process all RTF_MULTIRT ires in the
26126 	 * bucket, and send the packet through all crossed
26127 	 * RTF_MULTIRT routes.
26128 	 */
26129 	do {
26130 		if (multirt_send) {
26131 			/*
26132 			 * ire1 holds here the next ire to process in the
26133 			 * bucket. If multirouting is expected,
26134 			 * any non-RTF_MULTIRT ire that has the
26135 			 * right destination address is ignored.
26136 			 */
26137 			ASSERT(irb != NULL);
26138 			IRB_REFHOLD(irb);
26139 			for (ire1 = ire->ire_next;
26140 			    ire1 != NULL;
26141 			    ire1 = ire1->ire_next) {
26142 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26143 					continue;
26144 				if (ire1->ire_addr != ire->ire_addr)
26145 					continue;
26146 				if (ire1->ire_marks &
26147 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26148 					continue;
26149 				/* No loopback here */
26150 				if (ire1->ire_stq == NULL)
26151 					continue;
26152 				/*
26153 				 * Ensure we do not exceed the MTU
26154 				 * of the next route.
26155 				 */
26156 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26157 					ip_multirt_bad_mtu(ire1, max_frag);
26158 					continue;
26159 				}
26160 
26161 				IRE_REFHOLD(ire1);
26162 				break;
26163 			}
26164 			IRB_REFRELE(irb);
26165 			if (ire1 != NULL) {
26166 				/*
26167 				 * We are in a multiple send case, need to
26168 				 * make a copy of the packet.
26169 				 */
26170 				next_mp = copymsg(ipsec_mp);
26171 				if (next_mp == NULL) {
26172 					ire_refrele(ire1);
26173 					ire1 = NULL;
26174 				}
26175 			}
26176 		}
26177 		/*
26178 		 * Everything is done. Send it out on the wire
26179 		 *
26180 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26181 		 * either send it on the wire or, in the case of
26182 		 * HW acceleration, call ipsec_hw_putnext.
26183 		 */
26184 		if (ire->ire_nce &&
26185 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26186 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26187 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26188 			/*
26189 			 * If ire's link-layer is unresolved (this
26190 			 * would only happen if the incomplete ire
26191 			 * was added to cachetable via forwarding path)
26192 			 * don't bother going to ip_xmit_v4. Just drop the
26193 			 * packet.
26194 			 * There is a slight risk here, in that, if we
26195 			 * have the forwarding path create an incomplete
26196 			 * IRE, then until the IRE is completed, any
26197 			 * transmitted IPsec packets will be dropped
26198 			 * instead of being queued waiting for resolution.
26199 			 *
26200 			 * But the likelihood of a forwarding packet and a wput
26201 			 * packet sending to the same dst at the same time
26202 			 * and there not yet be an ARP entry for it is small.
26203 			 * Furthermore, if this actually happens, it might
26204 			 * be likely that wput would generate multiple
26205 			 * packets (and forwarding would also have a train
26206 			 * of packets) for that destination. If this is
26207 			 * the case, some of them would have been dropped
26208 			 * anyway, since ARP only queues a few packets while
26209 			 * waiting for resolution
26210 			 *
26211 			 * NOTE: We should really call ip_xmit_v4,
26212 			 * and let it queue the packet and send the
26213 			 * ARP query and have ARP come back thus:
26214 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26215 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26216 			 * hw accel work. But it's too complex to get
26217 			 * the IPsec hw  acceleration approach to fit
26218 			 * well with ip_xmit_v4 doing ARP without
26219 			 * doing IPsec simplification. For now, we just
26220 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26221 			 * that we can continue with the send on the next
26222 			 * attempt.
26223 			 *
26224 			 * XXX THis should be revisited, when
26225 			 * the IPsec/IP interaction is cleaned up
26226 			 */
26227 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26228 			    " - dropping packet\n"));
26229 			freemsg(ipsec_mp);
26230 			/*
26231 			 * Call ip_xmit_v4() to trigger ARP query
26232 			 * in case the nce_state is ND_INITIAL
26233 			 */
26234 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26235 			goto drop_pkt;
26236 		}
26237 
26238 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26239 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26240 		    mblk_t *, ipsec_mp);
26241 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26242 		    ipst->ips_ipv4firewall_physical_out,
26243 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26244 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26245 		if (ipsec_mp == NULL)
26246 			goto drop_pkt;
26247 
26248 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26249 		pktxmit_state = ip_xmit_v4(mp, ire,
26250 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26251 
26252 		if ((pktxmit_state ==  SEND_FAILED) ||
26253 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26254 
26255 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26256 drop_pkt:
26257 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26258 			    ipIfStatsOutDiscards);
26259 			if (ire_need_rele)
26260 				ire_refrele(ire);
26261 			if (ire1 != NULL) {
26262 				ire_refrele(ire1);
26263 				freemsg(next_mp);
26264 			}
26265 			goto done;
26266 		}
26267 
26268 		freeb(ipsec_mp);
26269 		if (ire_need_rele)
26270 			ire_refrele(ire);
26271 
26272 		if (ire1 != NULL) {
26273 			ire = ire1;
26274 			ire_need_rele = B_TRUE;
26275 			ASSERT(next_mp);
26276 			ipsec_mp = next_mp;
26277 			mp = ipsec_mp->b_cont;
26278 			ire1 = NULL;
26279 			next_mp = NULL;
26280 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26281 		} else {
26282 			multirt_send = B_FALSE;
26283 		}
26284 	} while (multirt_send);
26285 done:
26286 	if (ill != NULL && ill_need_rele)
26287 		ill_refrele(ill);
26288 	if (ipif != NULL)
26289 		ipif_refrele(ipif);
26290 }
26291 
26292 /*
26293  * Get the ill corresponding to the specified ire, and compare its
26294  * capabilities with the protocol and algorithms specified by the
26295  * the SA obtained from ipsec_out. If they match, annotate the
26296  * ipsec_out structure to indicate that the packet needs acceleration.
26297  *
26298  *
26299  * A packet is eligible for outbound hardware acceleration if the
26300  * following conditions are satisfied:
26301  *
26302  * 1. the packet will not be fragmented
26303  * 2. the provider supports the algorithm
26304  * 3. there is no pending control message being exchanged
26305  * 4. snoop is not attached
26306  * 5. the destination address is not a broadcast or multicast address.
26307  *
26308  * Rationale:
26309  *	- Hardware drivers do not support fragmentation with
26310  *	  the current interface.
26311  *	- snoop, multicast, and broadcast may result in exposure of
26312  *	  a cleartext datagram.
26313  * We check all five of these conditions here.
26314  *
26315  * XXX would like to nuke "ire_t *" parameter here; problem is that
26316  * IRE is only way to figure out if a v4 address is a broadcast and
26317  * thus ineligible for acceleration...
26318  */
26319 static void
26320 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26321 {
26322 	ipsec_out_t *io;
26323 	mblk_t *data_mp;
26324 	uint_t plen, overhead;
26325 	ip_stack_t	*ipst;
26326 
26327 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26328 		return;
26329 
26330 	if (ill == NULL)
26331 		return;
26332 	ipst = ill->ill_ipst;
26333 	/*
26334 	 * Destination address is a broadcast or multicast.  Punt.
26335 	 */
26336 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26337 	    IRE_LOCAL)))
26338 		return;
26339 
26340 	data_mp = ipsec_mp->b_cont;
26341 
26342 	if (ill->ill_isv6) {
26343 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26344 
26345 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26346 			return;
26347 
26348 		plen = ip6h->ip6_plen;
26349 	} else {
26350 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26351 
26352 		if (CLASSD(ipha->ipha_dst))
26353 			return;
26354 
26355 		plen = ipha->ipha_length;
26356 	}
26357 	/*
26358 	 * Is there a pending DLPI control message being exchanged
26359 	 * between IP/IPsec and the DLS Provider? If there is, it
26360 	 * could be a SADB update, and the state of the DLS Provider
26361 	 * SADB might not be in sync with the SADB maintained by
26362 	 * IPsec. To avoid dropping packets or using the wrong keying
26363 	 * material, we do not accelerate this packet.
26364 	 */
26365 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26366 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26367 		    "ill_dlpi_pending! don't accelerate packet\n"));
26368 		return;
26369 	}
26370 
26371 	/*
26372 	 * Is the Provider in promiscous mode? If it does, we don't
26373 	 * accelerate the packet since it will bounce back up to the
26374 	 * listeners in the clear.
26375 	 */
26376 	if (ill->ill_promisc_on_phys) {
26377 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26378 		    "ill in promiscous mode, don't accelerate packet\n"));
26379 		return;
26380 	}
26381 
26382 	/*
26383 	 * Will the packet require fragmentation?
26384 	 */
26385 
26386 	/*
26387 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26388 	 * as is used elsewhere.
26389 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26390 	 *	+ 2-byte trailer
26391 	 */
26392 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26393 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26394 
26395 	if ((plen + overhead) > ill->ill_max_mtu)
26396 		return;
26397 
26398 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26399 
26400 	/*
26401 	 * Can the ill accelerate this IPsec protocol and algorithm
26402 	 * specified by the SA?
26403 	 */
26404 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26405 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26406 		return;
26407 	}
26408 
26409 	/*
26410 	 * Tell AH or ESP that the outbound ill is capable of
26411 	 * accelerating this packet.
26412 	 */
26413 	io->ipsec_out_is_capab_ill = B_TRUE;
26414 }
26415 
26416 /*
26417  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26418  *
26419  * If this function returns B_TRUE, the requested SA's have been filled
26420  * into the ipsec_out_*_sa pointers.
26421  *
26422  * If the function returns B_FALSE, the packet has been "consumed", most
26423  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26424  *
26425  * The SA references created by the protocol-specific "select"
26426  * function will be released when the ipsec_mp is freed, thanks to the
26427  * ipsec_out_free destructor -- see spd.c.
26428  */
26429 static boolean_t
26430 ipsec_out_select_sa(mblk_t *ipsec_mp)
26431 {
26432 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26433 	ipsec_out_t *io;
26434 	ipsec_policy_t *pp;
26435 	ipsec_action_t *ap;
26436 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26437 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26438 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26439 
26440 	if (!io->ipsec_out_secure) {
26441 		/*
26442 		 * We came here by mistake.
26443 		 * Don't bother with ipsec processing
26444 		 * We should "discourage" this path in the future.
26445 		 */
26446 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26447 		return (B_FALSE);
26448 	}
26449 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26450 	ASSERT((io->ipsec_out_policy != NULL) ||
26451 	    (io->ipsec_out_act != NULL));
26452 
26453 	ASSERT(io->ipsec_out_failed == B_FALSE);
26454 
26455 	/*
26456 	 * IPsec processing has started.
26457 	 */
26458 	io->ipsec_out_proc_begin = B_TRUE;
26459 	ap = io->ipsec_out_act;
26460 	if (ap == NULL) {
26461 		pp = io->ipsec_out_policy;
26462 		ASSERT(pp != NULL);
26463 		ap = pp->ipsp_act;
26464 		ASSERT(ap != NULL);
26465 	}
26466 
26467 	/*
26468 	 * We have an action.  now, let's select SA's.
26469 	 * (In the future, we can cache this in the conn_t..)
26470 	 */
26471 	if (ap->ipa_want_esp) {
26472 		if (io->ipsec_out_esp_sa == NULL) {
26473 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26474 			    IPPROTO_ESP);
26475 		}
26476 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26477 	}
26478 
26479 	if (ap->ipa_want_ah) {
26480 		if (io->ipsec_out_ah_sa == NULL) {
26481 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26482 			    IPPROTO_AH);
26483 		}
26484 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26485 		/*
26486 		 * The ESP and AH processing order needs to be preserved
26487 		 * when both protocols are required (ESP should be applied
26488 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26489 		 * when both ESP and AH are required, and an AH ACQUIRE
26490 		 * is needed.
26491 		 */
26492 		if (ap->ipa_want_esp && need_ah_acquire)
26493 			need_esp_acquire = B_TRUE;
26494 	}
26495 
26496 	/*
26497 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26498 	 * Release SAs that got referenced, but will not be used until we
26499 	 * acquire _all_ of the SAs we need.
26500 	 */
26501 	if (need_ah_acquire || need_esp_acquire) {
26502 		if (io->ipsec_out_ah_sa != NULL) {
26503 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26504 			io->ipsec_out_ah_sa = NULL;
26505 		}
26506 		if (io->ipsec_out_esp_sa != NULL) {
26507 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26508 			io->ipsec_out_esp_sa = NULL;
26509 		}
26510 
26511 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26512 		return (B_FALSE);
26513 	}
26514 
26515 	return (B_TRUE);
26516 }
26517 
26518 /*
26519  * Process an IPSEC_OUT message and see what you can
26520  * do with it.
26521  * IPQoS Notes:
26522  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26523  * IPsec.
26524  * XXX would like to nuke ire_t.
26525  * XXX ill_index better be "real"
26526  */
26527 void
26528 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26529 {
26530 	ipsec_out_t *io;
26531 	ipsec_policy_t *pp;
26532 	ipsec_action_t *ap;
26533 	ipha_t *ipha;
26534 	ip6_t *ip6h;
26535 	mblk_t *mp;
26536 	ill_t *ill;
26537 	zoneid_t zoneid;
26538 	ipsec_status_t ipsec_rc;
26539 	boolean_t ill_need_rele = B_FALSE;
26540 	ip_stack_t	*ipst;
26541 	ipsec_stack_t	*ipss;
26542 
26543 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26544 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26545 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26546 	ipst = io->ipsec_out_ns->netstack_ip;
26547 	mp = ipsec_mp->b_cont;
26548 
26549 	/*
26550 	 * Initiate IPPF processing. We do it here to account for packets
26551 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26552 	 * We can check for ipsec_out_proc_begin even for such packets, as
26553 	 * they will always be false (asserted below).
26554 	 */
26555 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26556 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26557 		    io->ipsec_out_ill_index : ill_index);
26558 		if (mp == NULL) {
26559 			ip2dbg(("ipsec_out_process: packet dropped "\
26560 			    "during IPPF processing\n"));
26561 			freeb(ipsec_mp);
26562 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26563 			return;
26564 		}
26565 	}
26566 
26567 	if (!io->ipsec_out_secure) {
26568 		/*
26569 		 * We came here by mistake.
26570 		 * Don't bother with ipsec processing
26571 		 * Should "discourage" this path in the future.
26572 		 */
26573 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26574 		goto done;
26575 	}
26576 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26577 	ASSERT((io->ipsec_out_policy != NULL) ||
26578 	    (io->ipsec_out_act != NULL));
26579 	ASSERT(io->ipsec_out_failed == B_FALSE);
26580 
26581 	ipss = ipst->ips_netstack->netstack_ipsec;
26582 	if (!ipsec_loaded(ipss)) {
26583 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26584 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26585 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26586 		} else {
26587 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26588 		}
26589 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26590 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26591 		    &ipss->ipsec_dropper);
26592 		return;
26593 	}
26594 
26595 	/*
26596 	 * IPsec processing has started.
26597 	 */
26598 	io->ipsec_out_proc_begin = B_TRUE;
26599 	ap = io->ipsec_out_act;
26600 	if (ap == NULL) {
26601 		pp = io->ipsec_out_policy;
26602 		ASSERT(pp != NULL);
26603 		ap = pp->ipsp_act;
26604 		ASSERT(ap != NULL);
26605 	}
26606 
26607 	/*
26608 	 * Save the outbound ill index. When the packet comes back
26609 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26610 	 * before sending it the accelerated packet.
26611 	 */
26612 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26613 		int ifindex;
26614 		ill = ire_to_ill(ire);
26615 		ifindex = ill->ill_phyint->phyint_ifindex;
26616 		io->ipsec_out_capab_ill_index = ifindex;
26617 	}
26618 
26619 	/*
26620 	 * The order of processing is first insert a IP header if needed.
26621 	 * Then insert the ESP header and then the AH header.
26622 	 */
26623 	if ((io->ipsec_out_se_done == B_FALSE) &&
26624 	    (ap->ipa_want_se)) {
26625 		/*
26626 		 * First get the outer IP header before sending
26627 		 * it to ESP.
26628 		 */
26629 		ipha_t *oipha, *iipha;
26630 		mblk_t *outer_mp, *inner_mp;
26631 
26632 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26633 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26634 			    "ipsec_out_process: "
26635 			    "Self-Encapsulation failed: Out of memory\n");
26636 			freemsg(ipsec_mp);
26637 			if (ill != NULL) {
26638 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26639 			} else {
26640 				BUMP_MIB(&ipst->ips_ip_mib,
26641 				    ipIfStatsOutDiscards);
26642 			}
26643 			return;
26644 		}
26645 		inner_mp = ipsec_mp->b_cont;
26646 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26647 		oipha = (ipha_t *)outer_mp->b_rptr;
26648 		iipha = (ipha_t *)inner_mp->b_rptr;
26649 		*oipha = *iipha;
26650 		outer_mp->b_wptr += sizeof (ipha_t);
26651 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26652 		    sizeof (ipha_t));
26653 		oipha->ipha_protocol = IPPROTO_ENCAP;
26654 		oipha->ipha_version_and_hdr_length =
26655 		    IP_SIMPLE_HDR_VERSION;
26656 		oipha->ipha_hdr_checksum = 0;
26657 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26658 		outer_mp->b_cont = inner_mp;
26659 		ipsec_mp->b_cont = outer_mp;
26660 
26661 		io->ipsec_out_se_done = B_TRUE;
26662 		io->ipsec_out_tunnel = B_TRUE;
26663 	}
26664 
26665 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26666 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26667 	    !ipsec_out_select_sa(ipsec_mp))
26668 		return;
26669 
26670 	/*
26671 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26672 	 * to do the heavy lifting.
26673 	 */
26674 	zoneid = io->ipsec_out_zoneid;
26675 	ASSERT(zoneid != ALL_ZONES);
26676 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26677 		ASSERT(io->ipsec_out_esp_sa != NULL);
26678 		io->ipsec_out_esp_done = B_TRUE;
26679 		/*
26680 		 * Note that since hw accel can only apply one transform,
26681 		 * not two, we skip hw accel for ESP if we also have AH
26682 		 * This is an design limitation of the interface
26683 		 * which should be revisited.
26684 		 */
26685 		ASSERT(ire != NULL);
26686 		if (io->ipsec_out_ah_sa == NULL) {
26687 			ill = (ill_t *)ire->ire_stq->q_ptr;
26688 			ipsec_out_is_accelerated(ipsec_mp,
26689 			    io->ipsec_out_esp_sa, ill, ire);
26690 		}
26691 
26692 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26693 		switch (ipsec_rc) {
26694 		case IPSEC_STATUS_SUCCESS:
26695 			break;
26696 		case IPSEC_STATUS_FAILED:
26697 			if (ill != NULL) {
26698 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26699 			} else {
26700 				BUMP_MIB(&ipst->ips_ip_mib,
26701 				    ipIfStatsOutDiscards);
26702 			}
26703 			/* FALLTHRU */
26704 		case IPSEC_STATUS_PENDING:
26705 			return;
26706 		}
26707 	}
26708 
26709 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26710 		ASSERT(io->ipsec_out_ah_sa != NULL);
26711 		io->ipsec_out_ah_done = B_TRUE;
26712 		if (ire == NULL) {
26713 			int idx = io->ipsec_out_capab_ill_index;
26714 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26715 			    NULL, NULL, NULL, NULL, ipst);
26716 			ill_need_rele = B_TRUE;
26717 		} else {
26718 			ill = (ill_t *)ire->ire_stq->q_ptr;
26719 		}
26720 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26721 		    ire);
26722 
26723 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26724 		switch (ipsec_rc) {
26725 		case IPSEC_STATUS_SUCCESS:
26726 			break;
26727 		case IPSEC_STATUS_FAILED:
26728 			if (ill != NULL) {
26729 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26730 			} else {
26731 				BUMP_MIB(&ipst->ips_ip_mib,
26732 				    ipIfStatsOutDiscards);
26733 			}
26734 			/* FALLTHRU */
26735 		case IPSEC_STATUS_PENDING:
26736 			if (ill != NULL && ill_need_rele)
26737 				ill_refrele(ill);
26738 			return;
26739 		}
26740 	}
26741 	/*
26742 	 * We are done with IPsec processing. Send it over
26743 	 * the wire.
26744 	 */
26745 done:
26746 	mp = ipsec_mp->b_cont;
26747 	ipha = (ipha_t *)mp->b_rptr;
26748 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26749 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26750 	} else {
26751 		ip6h = (ip6_t *)ipha;
26752 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26753 	}
26754 	if (ill != NULL && ill_need_rele)
26755 		ill_refrele(ill);
26756 }
26757 
26758 /* ARGSUSED */
26759 void
26760 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26761 {
26762 	opt_restart_t	*or;
26763 	int	err;
26764 	conn_t	*connp;
26765 
26766 	ASSERT(CONN_Q(q));
26767 	connp = Q_TO_CONN(q);
26768 
26769 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26770 	or = (opt_restart_t *)first_mp->b_rptr;
26771 	/*
26772 	 * We don't need to pass any credentials here since this is just
26773 	 * a restart. The credentials are passed in when svr4_optcom_req
26774 	 * is called the first time (from ip_wput_nondata).
26775 	 */
26776 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26777 		err = svr4_optcom_req(q, first_mp, NULL,
26778 		    &ip_opt_obj);
26779 	} else {
26780 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26781 		err = tpi_optcom_req(q, first_mp, NULL,
26782 		    &ip_opt_obj);
26783 	}
26784 	if (err != EINPROGRESS) {
26785 		/* operation is done */
26786 		CONN_OPER_PENDING_DONE(connp);
26787 	}
26788 }
26789 
26790 /*
26791  * ioctls that go through a down/up sequence may need to wait for the down
26792  * to complete. This involves waiting for the ire and ipif refcnts to go down
26793  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26794  */
26795 /* ARGSUSED */
26796 void
26797 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26798 {
26799 	struct iocblk *iocp;
26800 	mblk_t *mp1;
26801 	ip_ioctl_cmd_t *ipip;
26802 	int err;
26803 	sin_t	*sin;
26804 	struct lifreq *lifr;
26805 	struct ifreq *ifr;
26806 
26807 	iocp = (struct iocblk *)mp->b_rptr;
26808 	ASSERT(ipsq != NULL);
26809 	/* Existence of mp1 verified in ip_wput_nondata */
26810 	mp1 = mp->b_cont->b_cont;
26811 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26812 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26813 		/*
26814 		 * Special case where ipsq_current_ipif is not set:
26815 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26816 		 * ill could also have become part of a ipmp group in the
26817 		 * process, we are here as were not able to complete the
26818 		 * operation in ipif_set_values because we could not become
26819 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26820 		 * will not be set so we need to set it.
26821 		 */
26822 		ill_t *ill = q->q_ptr;
26823 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26824 	}
26825 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26826 
26827 	if (ipip->ipi_cmd_type == IF_CMD) {
26828 		/* This a old style SIOC[GS]IF* command */
26829 		ifr = (struct ifreq *)mp1->b_rptr;
26830 		sin = (sin_t *)&ifr->ifr_addr;
26831 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26832 		/* This a new style SIOC[GS]LIF* command */
26833 		lifr = (struct lifreq *)mp1->b_rptr;
26834 		sin = (sin_t *)&lifr->lifr_addr;
26835 	} else {
26836 		sin = NULL;
26837 	}
26838 
26839 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26840 	    ipip, mp1->b_rptr);
26841 
26842 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26843 }
26844 
26845 /*
26846  * ioctl processing
26847  *
26848  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26849  * the ioctl command in the ioctl tables, determines the copyin data size
26850  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26851  *
26852  * ioctl processing then continues when the M_IOCDATA makes its way down to
26853  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26854  * associated 'conn' is refheld till the end of the ioctl and the general
26855  * ioctl processing function ip_process_ioctl() is called to extract the
26856  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26857  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26858  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26859  * is used to extract the ioctl's arguments.
26860  *
26861  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26862  * so goes thru the serialization primitive ipsq_try_enter. Then the
26863  * appropriate function to handle the ioctl is called based on the entry in
26864  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26865  * which also refreleases the 'conn' that was refheld at the start of the
26866  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26867  *
26868  * Many exclusive ioctls go thru an internal down up sequence as part of
26869  * the operation. For example an attempt to change the IP address of an
26870  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26871  * does all the cleanup such as deleting all ires that use this address.
26872  * Then we need to wait till all references to the interface go away.
26873  */
26874 void
26875 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26876 {
26877 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26878 	ip_ioctl_cmd_t *ipip = arg;
26879 	ip_extract_func_t *extract_funcp;
26880 	cmd_info_t ci;
26881 	int err;
26882 	boolean_t entered_ipsq = B_FALSE;
26883 
26884 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26885 
26886 	if (ipip == NULL)
26887 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26888 
26889 	/*
26890 	 * SIOCLIFADDIF needs to go thru a special path since the
26891 	 * ill may not exist yet. This happens in the case of lo0
26892 	 * which is created using this ioctl.
26893 	 */
26894 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26895 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26896 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26897 		return;
26898 	}
26899 
26900 	ci.ci_ipif = NULL;
26901 	if (ipip->ipi_cmd_type == MISC_CMD) {
26902 		/*
26903 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26904 		 */
26905 		if (ipip->ipi_cmd == IF_UNITSEL) {
26906 			/* ioctl comes down the ill */
26907 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26908 			ipif_refhold(ci.ci_ipif);
26909 		}
26910 		err = 0;
26911 		ci.ci_sin = NULL;
26912 		ci.ci_sin6 = NULL;
26913 		ci.ci_lifr = NULL;
26914 	} else {
26915 		switch (ipip->ipi_cmd_type) {
26916 		case IF_CMD:
26917 		case LIF_CMD:
26918 			extract_funcp = ip_extract_lifreq;
26919 			break;
26920 
26921 		case ARP_CMD:
26922 		case XARP_CMD:
26923 			extract_funcp = ip_extract_arpreq;
26924 			break;
26925 
26926 		case TUN_CMD:
26927 			extract_funcp = ip_extract_tunreq;
26928 			break;
26929 
26930 		case MSFILT_CMD:
26931 			extract_funcp = ip_extract_msfilter;
26932 			break;
26933 
26934 		default:
26935 			ASSERT(0);
26936 		}
26937 
26938 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26939 		if (err != 0) {
26940 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26941 			return;
26942 		}
26943 
26944 		/*
26945 		 * All of the extraction functions return a refheld ipif.
26946 		 */
26947 		ASSERT(ci.ci_ipif != NULL);
26948 	}
26949 
26950 	/*
26951 	 * If ipsq is non-null, we are already being called exclusively
26952 	 */
26953 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26954 	if (!(ipip->ipi_flags & IPI_WR)) {
26955 		/*
26956 		 * A return value of EINPROGRESS means the ioctl is
26957 		 * either queued and waiting for some reason or has
26958 		 * already completed.
26959 		 */
26960 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26961 		    ci.ci_lifr);
26962 		if (ci.ci_ipif != NULL)
26963 			ipif_refrele(ci.ci_ipif);
26964 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26965 		return;
26966 	}
26967 
26968 	ASSERT(ci.ci_ipif != NULL);
26969 
26970 	if (ipsq == NULL) {
26971 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26972 		    ip_process_ioctl, NEW_OP, B_TRUE);
26973 		entered_ipsq = B_TRUE;
26974 	}
26975 	/*
26976 	 * Release the ipif so that ipif_down and friends that wait for
26977 	 * references to go away are not misled about the current ipif_refcnt
26978 	 * values. We are writer so we can access the ipif even after releasing
26979 	 * the ipif.
26980 	 */
26981 	ipif_refrele(ci.ci_ipif);
26982 	if (ipsq == NULL)
26983 		return;
26984 
26985 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26986 
26987 	/*
26988 	 * For most set ioctls that come here, this serves as a single point
26989 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26990 	 * be any new references to the ipif. This helps functions that go
26991 	 * through this path and end up trying to wait for the refcnts
26992 	 * associated with the ipif to go down to zero. Some exceptions are
26993 	 * Failover, Failback, and Groupname commands that operate on more than
26994 	 * just the ci.ci_ipif. These commands internally determine the
26995 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26996 	 * flags on that set. Another exception is the Removeif command that
26997 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26998 	 * ipif to operate on.
26999 	 */
27000 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27001 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27002 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27003 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27004 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27005 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27006 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27007 
27008 	/*
27009 	 * A return value of EINPROGRESS means the ioctl is
27010 	 * either queued and waiting for some reason or has
27011 	 * already completed.
27012 	 */
27013 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27014 
27015 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27016 
27017 	if (entered_ipsq)
27018 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27019 }
27020 
27021 /*
27022  * Complete the ioctl. Typically ioctls use the mi package and need to
27023  * do mi_copyout/mi_copy_done.
27024  */
27025 void
27026 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27027 {
27028 	conn_t	*connp = NULL;
27029 
27030 	if (err == EINPROGRESS)
27031 		return;
27032 
27033 	if (CONN_Q(q)) {
27034 		connp = Q_TO_CONN(q);
27035 		ASSERT(connp->conn_ref >= 2);
27036 	}
27037 
27038 	switch (mode) {
27039 	case COPYOUT:
27040 		if (err == 0)
27041 			mi_copyout(q, mp);
27042 		else
27043 			mi_copy_done(q, mp, err);
27044 		break;
27045 
27046 	case NO_COPYOUT:
27047 		mi_copy_done(q, mp, err);
27048 		break;
27049 
27050 	default:
27051 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27052 		break;
27053 	}
27054 
27055 	/*
27056 	 * The refhold placed at the start of the ioctl is released here.
27057 	 */
27058 	if (connp != NULL)
27059 		CONN_OPER_PENDING_DONE(connp);
27060 
27061 	if (ipsq != NULL)
27062 		ipsq_current_finish(ipsq);
27063 }
27064 
27065 /*
27066  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27067  */
27068 /* ARGSUSED */
27069 void
27070 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27071 {
27072 	conn_t *connp = arg;
27073 	tcp_t	*tcp;
27074 
27075 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27076 	tcp = connp->conn_tcp;
27077 
27078 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27079 		freemsg(mp);
27080 	else
27081 		tcp_rput_other(tcp, mp);
27082 	CONN_OPER_PENDING_DONE(connp);
27083 }
27084 
27085 /* Called from ip_wput for all non data messages */
27086 /* ARGSUSED */
27087 void
27088 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27089 {
27090 	mblk_t		*mp1;
27091 	ire_t		*ire, *fake_ire;
27092 	ill_t		*ill;
27093 	struct iocblk	*iocp;
27094 	ip_ioctl_cmd_t	*ipip;
27095 	cred_t		*cr;
27096 	conn_t		*connp;
27097 	int		err;
27098 	nce_t		*nce;
27099 	ipif_t		*ipif;
27100 	ip_stack_t	*ipst;
27101 	char		*proto_str;
27102 
27103 	if (CONN_Q(q)) {
27104 		connp = Q_TO_CONN(q);
27105 		ipst = connp->conn_netstack->netstack_ip;
27106 	} else {
27107 		connp = NULL;
27108 		ipst = ILLQ_TO_IPST(q);
27109 	}
27110 
27111 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27112 
27113 	/* Check if it is a queue to /dev/sctp. */
27114 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27115 	    connp->conn_rq == NULL) {
27116 		sctp_wput(q, mp);
27117 		return;
27118 	}
27119 
27120 	switch (DB_TYPE(mp)) {
27121 	case M_IOCTL:
27122 		/*
27123 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27124 		 * will arrange to copy in associated control structures.
27125 		 */
27126 		ip_sioctl_copyin_setup(q, mp);
27127 		return;
27128 	case M_IOCDATA:
27129 		/*
27130 		 * Ensure that this is associated with one of our trans-
27131 		 * parent ioctls.  If it's not ours, discard it if we're
27132 		 * running as a driver, or pass it on if we're a module.
27133 		 */
27134 		iocp = (struct iocblk *)mp->b_rptr;
27135 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27136 		if (ipip == NULL) {
27137 			if (q->q_next == NULL) {
27138 				goto nak;
27139 			} else {
27140 				putnext(q, mp);
27141 			}
27142 			return;
27143 		}
27144 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27145 			/*
27146 			 * the ioctl is one we recognise, but is not
27147 			 * consumed by IP as a module, pass M_IOCDATA
27148 			 * for processing downstream, but only for
27149 			 * common Streams ioctls.
27150 			 */
27151 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27152 				putnext(q, mp);
27153 				return;
27154 			} else {
27155 				goto nak;
27156 			}
27157 		}
27158 
27159 		/* IOCTL continuation following copyin or copyout. */
27160 		if (mi_copy_state(q, mp, NULL) == -1) {
27161 			/*
27162 			 * The copy operation failed.  mi_copy_state already
27163 			 * cleaned up, so we're out of here.
27164 			 */
27165 			return;
27166 		}
27167 		/*
27168 		 * If we just completed a copy in, we become writer and
27169 		 * continue processing in ip_sioctl_copyin_done.  If it
27170 		 * was a copy out, we call mi_copyout again.  If there is
27171 		 * nothing more to copy out, it will complete the IOCTL.
27172 		 */
27173 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27174 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27175 				mi_copy_done(q, mp, EPROTO);
27176 				return;
27177 			}
27178 			/*
27179 			 * Check for cases that need more copying.  A return
27180 			 * value of 0 means a second copyin has been started,
27181 			 * so we return; a return value of 1 means no more
27182 			 * copying is needed, so we continue.
27183 			 */
27184 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27185 			    MI_COPY_COUNT(mp) == 1) {
27186 				if (ip_copyin_msfilter(q, mp) == 0)
27187 					return;
27188 			}
27189 			/*
27190 			 * Refhold the conn, till the ioctl completes. This is
27191 			 * needed in case the ioctl ends up in the pending mp
27192 			 * list. Every mp in the ill_pending_mp list and
27193 			 * the ipsq_pending_mp must have a refhold on the conn
27194 			 * to resume processing. The refhold is released when
27195 			 * the ioctl completes. (normally or abnormally)
27196 			 * In all cases ip_ioctl_finish is called to finish
27197 			 * the ioctl.
27198 			 */
27199 			if (connp != NULL) {
27200 				/* This is not a reentry */
27201 				ASSERT(ipsq == NULL);
27202 				CONN_INC_REF(connp);
27203 			} else {
27204 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27205 					mi_copy_done(q, mp, EINVAL);
27206 					return;
27207 				}
27208 			}
27209 
27210 			ip_process_ioctl(ipsq, q, mp, ipip);
27211 
27212 		} else {
27213 			mi_copyout(q, mp);
27214 		}
27215 		return;
27216 nak:
27217 		iocp->ioc_error = EINVAL;
27218 		mp->b_datap->db_type = M_IOCNAK;
27219 		iocp->ioc_count = 0;
27220 		qreply(q, mp);
27221 		return;
27222 
27223 	case M_IOCNAK:
27224 		/*
27225 		 * The only way we could get here is if a resolver didn't like
27226 		 * an IOCTL we sent it.	 This shouldn't happen.
27227 		 */
27228 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27229 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27230 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27231 		freemsg(mp);
27232 		return;
27233 	case M_IOCACK:
27234 		/* /dev/ip shouldn't see this */
27235 		if (CONN_Q(q))
27236 			goto nak;
27237 
27238 		/* Finish socket ioctls passed through to ARP. */
27239 		ip_sioctl_iocack(q, mp);
27240 		return;
27241 	case M_FLUSH:
27242 		if (*mp->b_rptr & FLUSHW)
27243 			flushq(q, FLUSHALL);
27244 		if (q->q_next) {
27245 			putnext(q, mp);
27246 			return;
27247 		}
27248 		if (*mp->b_rptr & FLUSHR) {
27249 			*mp->b_rptr &= ~FLUSHW;
27250 			qreply(q, mp);
27251 			return;
27252 		}
27253 		freemsg(mp);
27254 		return;
27255 	case IRE_DB_REQ_TYPE:
27256 		if (connp == NULL) {
27257 			proto_str = "IRE_DB_REQ_TYPE";
27258 			goto protonak;
27259 		}
27260 		/* An Upper Level Protocol wants a copy of an IRE. */
27261 		ip_ire_req(q, mp);
27262 		return;
27263 	case M_CTL:
27264 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27265 			break;
27266 
27267 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27268 		    TUN_HELLO) {
27269 			ASSERT(connp != NULL);
27270 			connp->conn_flags |= IPCL_IPTUN;
27271 			freeb(mp);
27272 			return;
27273 		}
27274 
27275 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27276 		    IP_ULP_OUT_LABELED) {
27277 			out_labeled_t *olp;
27278 
27279 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27280 				break;
27281 			olp = (out_labeled_t *)mp->b_rptr;
27282 			connp->conn_ulp_labeled = olp->out_qnext == q;
27283 			freemsg(mp);
27284 			return;
27285 		}
27286 
27287 		/* M_CTL messages are used by ARP to tell us things. */
27288 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27289 			break;
27290 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27291 		case AR_ENTRY_SQUERY:
27292 			ip_wput_ctl(q, mp);
27293 			return;
27294 		case AR_CLIENT_NOTIFY:
27295 			ip_arp_news(q, mp);
27296 			return;
27297 		case AR_DLPIOP_DONE:
27298 			ASSERT(q->q_next != NULL);
27299 			ill = (ill_t *)q->q_ptr;
27300 			/* qwriter_ip releases the refhold */
27301 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27302 			ill_refhold(ill);
27303 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27304 			return;
27305 		case AR_ARP_CLOSING:
27306 			/*
27307 			 * ARP (above us) is closing. If no ARP bringup is
27308 			 * currently pending, ack the message so that ARP
27309 			 * can complete its close. Also mark ill_arp_closing
27310 			 * so that new ARP bringups will fail. If any
27311 			 * ARP bringup is currently in progress, we will
27312 			 * ack this when the current ARP bringup completes.
27313 			 */
27314 			ASSERT(q->q_next != NULL);
27315 			ill = (ill_t *)q->q_ptr;
27316 			mutex_enter(&ill->ill_lock);
27317 			ill->ill_arp_closing = 1;
27318 			if (!ill->ill_arp_bringup_pending) {
27319 				mutex_exit(&ill->ill_lock);
27320 				qreply(q, mp);
27321 			} else {
27322 				mutex_exit(&ill->ill_lock);
27323 				freemsg(mp);
27324 			}
27325 			return;
27326 		case AR_ARP_EXTEND:
27327 			/*
27328 			 * The ARP module above us is capable of duplicate
27329 			 * address detection.  Old ATM drivers will not send
27330 			 * this message.
27331 			 */
27332 			ASSERT(q->q_next != NULL);
27333 			ill = (ill_t *)q->q_ptr;
27334 			ill->ill_arp_extend = B_TRUE;
27335 			freemsg(mp);
27336 			return;
27337 		default:
27338 			break;
27339 		}
27340 		break;
27341 	case M_PROTO:
27342 	case M_PCPROTO:
27343 		/*
27344 		 * The only PROTO messages we expect are ULP binds and
27345 		 * copies of option negotiation acknowledgements.
27346 		 */
27347 		switch (((union T_primitives *)mp->b_rptr)->type) {
27348 		case O_T_BIND_REQ:
27349 		case T_BIND_REQ: {
27350 			/* Request can get queued in bind */
27351 			if (connp == NULL) {
27352 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27353 				goto protonak;
27354 			}
27355 			/*
27356 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27357 			 * instead of going through this path.  We only get
27358 			 * here in the following cases:
27359 			 *
27360 			 * a. Bind retries, where ipsq is non-NULL.
27361 			 * b. T_BIND_REQ is issued from non TCP/UDP
27362 			 *    transport, e.g. icmp for raw socket,
27363 			 *    in which case ipsq will be NULL.
27364 			 */
27365 			ASSERT(ipsq != NULL ||
27366 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27367 
27368 			/* Don't increment refcnt if this is a re-entry */
27369 			if (ipsq == NULL)
27370 				CONN_INC_REF(connp);
27371 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27372 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27373 			if (mp == NULL)
27374 				return;
27375 			if (IPCL_IS_TCP(connp)) {
27376 				/*
27377 				 * In the case of TCP endpoint we
27378 				 * come here only for bind retries
27379 				 */
27380 				ASSERT(ipsq != NULL);
27381 				CONN_INC_REF(connp);
27382 				squeue_fill(connp->conn_sqp, mp,
27383 				    ip_resume_tcp_bind, connp,
27384 				    SQTAG_BIND_RETRY);
27385 				return;
27386 			} else if (IPCL_IS_UDP(connp)) {
27387 				/*
27388 				 * In the case of UDP endpoint we
27389 				 * come here only for bind retries
27390 				 */
27391 				ASSERT(ipsq != NULL);
27392 				udp_resume_bind(connp, mp);
27393 				return;
27394 			}
27395 			qreply(q, mp);
27396 			CONN_OPER_PENDING_DONE(connp);
27397 			return;
27398 		}
27399 		case T_SVR4_OPTMGMT_REQ:
27400 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27401 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27402 
27403 			if (connp == NULL) {
27404 				proto_str = "T_SVR4_OPTMGMT_REQ";
27405 				goto protonak;
27406 			}
27407 
27408 			if (!snmpcom_req(q, mp, ip_snmp_set,
27409 			    ip_snmp_get, cr)) {
27410 				/*
27411 				 * Call svr4_optcom_req so that it can
27412 				 * generate the ack. We don't come here
27413 				 * if this operation is being restarted.
27414 				 * ip_restart_optmgmt will drop the conn ref.
27415 				 * In the case of ipsec option after the ipsec
27416 				 * load is complete conn_restart_ipsec_waiter
27417 				 * drops the conn ref.
27418 				 */
27419 				ASSERT(ipsq == NULL);
27420 				CONN_INC_REF(connp);
27421 				if (ip_check_for_ipsec_opt(q, mp))
27422 					return;
27423 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27424 				if (err != EINPROGRESS) {
27425 					/* Operation is done */
27426 					CONN_OPER_PENDING_DONE(connp);
27427 				}
27428 			}
27429 			return;
27430 		case T_OPTMGMT_REQ:
27431 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27432 			/*
27433 			 * Note: No snmpcom_req support through new
27434 			 * T_OPTMGMT_REQ.
27435 			 * Call tpi_optcom_req so that it can
27436 			 * generate the ack.
27437 			 */
27438 			if (connp == NULL) {
27439 				proto_str = "T_OPTMGMT_REQ";
27440 				goto protonak;
27441 			}
27442 
27443 			ASSERT(ipsq == NULL);
27444 			/*
27445 			 * We don't come here for restart. ip_restart_optmgmt
27446 			 * will drop the conn ref. In the case of ipsec option
27447 			 * after the ipsec load is complete
27448 			 * conn_restart_ipsec_waiter drops the conn ref.
27449 			 */
27450 			CONN_INC_REF(connp);
27451 			if (ip_check_for_ipsec_opt(q, mp))
27452 				return;
27453 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27454 			if (err != EINPROGRESS) {
27455 				/* Operation is done */
27456 				CONN_OPER_PENDING_DONE(connp);
27457 			}
27458 			return;
27459 		case T_UNBIND_REQ:
27460 			if (connp == NULL) {
27461 				proto_str = "T_UNBIND_REQ";
27462 				goto protonak;
27463 			}
27464 			mp = ip_unbind(q, mp);
27465 			qreply(q, mp);
27466 			return;
27467 		default:
27468 			/*
27469 			 * Have to drop any DLPI messages coming down from
27470 			 * arp (such as an info_req which would cause ip
27471 			 * to receive an extra info_ack if it was passed
27472 			 * through.
27473 			 */
27474 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27475 			    (int)*(uint_t *)mp->b_rptr));
27476 			freemsg(mp);
27477 			return;
27478 		}
27479 		/* NOTREACHED */
27480 	case IRE_DB_TYPE: {
27481 		nce_t		*nce;
27482 		ill_t		*ill;
27483 		in6_addr_t	gw_addr_v6;
27484 
27485 
27486 		/*
27487 		 * This is a response back from a resolver.  It
27488 		 * consists of a message chain containing:
27489 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27490 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27491 		 * The LL_HDR_MBLK is the DLPI header to use to get
27492 		 * the attached packet, and subsequent ones for the
27493 		 * same destination, transmitted.
27494 		 */
27495 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27496 			break;
27497 		/*
27498 		 * First, check to make sure the resolution succeeded.
27499 		 * If it failed, the second mblk will be empty.
27500 		 * If it is, free the chain, dropping the packet.
27501 		 * (We must ire_delete the ire; that frees the ire mblk)
27502 		 * We're doing this now to support PVCs for ATM; it's
27503 		 * a partial xresolv implementation. When we fully implement
27504 		 * xresolv interfaces, instead of freeing everything here
27505 		 * we'll initiate neighbor discovery.
27506 		 *
27507 		 * For v4 (ARP and other external resolvers) the resolver
27508 		 * frees the message, so no check is needed. This check
27509 		 * is required, though, for a full xresolve implementation.
27510 		 * Including this code here now both shows how external
27511 		 * resolvers can NACK a resolution request using an
27512 		 * existing design that has no specific provisions for NACKs,
27513 		 * and also takes into account that the current non-ARP
27514 		 * external resolver has been coded to use this method of
27515 		 * NACKing for all IPv6 (xresolv) cases,
27516 		 * whether our xresolv implementation is complete or not.
27517 		 *
27518 		 */
27519 		ire = (ire_t *)mp->b_rptr;
27520 		ill = ire_to_ill(ire);
27521 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27522 		if (mp1->b_rptr == mp1->b_wptr) {
27523 			if (ire->ire_ipversion == IPV6_VERSION) {
27524 				/*
27525 				 * XRESOLV interface.
27526 				 */
27527 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27528 				mutex_enter(&ire->ire_lock);
27529 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27530 				mutex_exit(&ire->ire_lock);
27531 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27532 					nce = ndp_lookup_v6(ill,
27533 					    &ire->ire_addr_v6, B_FALSE);
27534 				} else {
27535 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27536 					    B_FALSE);
27537 				}
27538 				if (nce != NULL) {
27539 					nce_resolv_failed(nce);
27540 					ndp_delete(nce);
27541 					NCE_REFRELE(nce);
27542 				}
27543 			}
27544 			mp->b_cont = NULL;
27545 			freemsg(mp1);		/* frees the pkt as well */
27546 			ASSERT(ire->ire_nce == NULL);
27547 			ire_delete((ire_t *)mp->b_rptr);
27548 			return;
27549 		}
27550 
27551 		/*
27552 		 * Split them into IRE_MBLK and pkt and feed it into
27553 		 * ire_add_then_send. Then in ire_add_then_send
27554 		 * the IRE will be added, and then the packet will be
27555 		 * run back through ip_wput. This time it will make
27556 		 * it to the wire.
27557 		 */
27558 		mp->b_cont = NULL;
27559 		mp = mp1->b_cont;		/* now, mp points to pkt */
27560 		mp1->b_cont = NULL;
27561 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27562 		if (ire->ire_ipversion == IPV6_VERSION) {
27563 			/*
27564 			 * XRESOLV interface. Find the nce and put a copy
27565 			 * of the dl_unitdata_req in nce_res_mp
27566 			 */
27567 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27568 			mutex_enter(&ire->ire_lock);
27569 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27570 			mutex_exit(&ire->ire_lock);
27571 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27572 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27573 				    B_FALSE);
27574 			} else {
27575 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27576 			}
27577 			if (nce != NULL) {
27578 				/*
27579 				 * We have to protect nce_res_mp here
27580 				 * from being accessed by other threads
27581 				 * while we change the mblk pointer.
27582 				 * Other functions will also lock the nce when
27583 				 * accessing nce_res_mp.
27584 				 *
27585 				 * The reason we change the mblk pointer
27586 				 * here rather than copying the resolved address
27587 				 * into the template is that, unlike with
27588 				 * ethernet, we have no guarantee that the
27589 				 * resolved address length will be
27590 				 * smaller than or equal to the lla length
27591 				 * with which the template was allocated,
27592 				 * (for ethernet, they're equal)
27593 				 * so we have to use the actual resolved
27594 				 * address mblk - which holds the real
27595 				 * dl_unitdata_req with the resolved address.
27596 				 *
27597 				 * Doing this is the same behavior as was
27598 				 * previously used in the v4 ARP case.
27599 				 */
27600 				mutex_enter(&nce->nce_lock);
27601 				if (nce->nce_res_mp != NULL)
27602 					freemsg(nce->nce_res_mp);
27603 				nce->nce_res_mp = mp1;
27604 				mutex_exit(&nce->nce_lock);
27605 				/*
27606 				 * We do a fastpath probe here because
27607 				 * we have resolved the address without
27608 				 * using Neighbor Discovery.
27609 				 * In the non-XRESOLV v6 case, the fastpath
27610 				 * probe is done right after neighbor
27611 				 * discovery completes.
27612 				 */
27613 				if (nce->nce_res_mp != NULL) {
27614 					int res;
27615 					nce_fastpath_list_add(nce);
27616 					res = ill_fastpath_probe(ill,
27617 					    nce->nce_res_mp);
27618 					if (res != 0 && res != EAGAIN)
27619 						nce_fastpath_list_delete(nce);
27620 				}
27621 
27622 				ire_add_then_send(q, ire, mp);
27623 				/*
27624 				 * Now we have to clean out any packets
27625 				 * that may have been queued on the nce
27626 				 * while it was waiting for address resolution
27627 				 * to complete.
27628 				 */
27629 				mutex_enter(&nce->nce_lock);
27630 				mp1 = nce->nce_qd_mp;
27631 				nce->nce_qd_mp = NULL;
27632 				mutex_exit(&nce->nce_lock);
27633 				while (mp1 != NULL) {
27634 					mblk_t *nxt_mp;
27635 					queue_t *fwdq = NULL;
27636 					ill_t   *inbound_ill;
27637 					uint_t ifindex;
27638 
27639 					nxt_mp = mp1->b_next;
27640 					mp1->b_next = NULL;
27641 					/*
27642 					 * Retrieve ifindex stored in
27643 					 * ip_rput_data_v6()
27644 					 */
27645 					ifindex =
27646 					    (uint_t)(uintptr_t)mp1->b_prev;
27647 					inbound_ill =
27648 					    ill_lookup_on_ifindex(ifindex,
27649 					    B_TRUE, NULL, NULL, NULL,
27650 					    NULL, ipst);
27651 					mp1->b_prev = NULL;
27652 					if (inbound_ill != NULL)
27653 						fwdq = inbound_ill->ill_rq;
27654 
27655 					if (fwdq != NULL) {
27656 						put(fwdq, mp1);
27657 						ill_refrele(inbound_ill);
27658 					} else
27659 						put(WR(ill->ill_rq), mp1);
27660 					mp1 = nxt_mp;
27661 				}
27662 				NCE_REFRELE(nce);
27663 			} else {	/* nce is NULL; clean up */
27664 				ire_delete(ire);
27665 				freemsg(mp);
27666 				freemsg(mp1);
27667 				return;
27668 			}
27669 		} else {
27670 			nce_t *arpce;
27671 			/*
27672 			 * Link layer resolution succeeded. Recompute the
27673 			 * ire_nce.
27674 			 */
27675 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27676 			if ((arpce = ndp_lookup_v4(ill,
27677 			    (ire->ire_gateway_addr != INADDR_ANY ?
27678 			    &ire->ire_gateway_addr : &ire->ire_addr),
27679 			    B_FALSE)) == NULL) {
27680 				freeb(ire->ire_mp);
27681 				freeb(mp1);
27682 				freemsg(mp);
27683 				return;
27684 			}
27685 			mutex_enter(&arpce->nce_lock);
27686 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27687 			if (arpce->nce_state == ND_REACHABLE) {
27688 				/*
27689 				 * Someone resolved this before us;
27690 				 * cleanup the res_mp. Since ire has
27691 				 * not been added yet, the call to ire_add_v4
27692 				 * from ire_add_then_send (when a dup is
27693 				 * detected) will clean up the ire.
27694 				 */
27695 				freeb(mp1);
27696 			} else {
27697 				ASSERT(arpce->nce_res_mp == NULL);
27698 				arpce->nce_res_mp = mp1;
27699 				arpce->nce_state = ND_REACHABLE;
27700 			}
27701 			mutex_exit(&arpce->nce_lock);
27702 			if (ire->ire_marks & IRE_MARK_NOADD) {
27703 				/*
27704 				 * this ire will not be added to the ire
27705 				 * cache table, so we can set the ire_nce
27706 				 * here, as there are no atomicity constraints.
27707 				 */
27708 				ire->ire_nce = arpce;
27709 				/*
27710 				 * We are associating this nce with the ire
27711 				 * so change the nce ref taken in
27712 				 * ndp_lookup_v4() from
27713 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27714 				 */
27715 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27716 			} else {
27717 				NCE_REFRELE(arpce);
27718 			}
27719 			ire_add_then_send(q, ire, mp);
27720 		}
27721 		return;	/* All is well, the packet has been sent. */
27722 	}
27723 	case IRE_ARPRESOLVE_TYPE: {
27724 
27725 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27726 			break;
27727 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27728 		mp->b_cont = NULL;
27729 		/*
27730 		 * First, check to make sure the resolution succeeded.
27731 		 * If it failed, the second mblk will be empty.
27732 		 */
27733 		if (mp1->b_rptr == mp1->b_wptr) {
27734 			/* cleanup  the incomplete ire, free queued packets */
27735 			freemsg(mp); /* fake ire */
27736 			freeb(mp1);  /* dl_unitdata response */
27737 			return;
27738 		}
27739 
27740 		/*
27741 		 * update any incomplete nce_t found. we lookup the ctable
27742 		 * and find the nce from the ire->ire_nce because we need
27743 		 * to pass the ire to ip_xmit_v4 later, and can find both
27744 		 * ire and nce in one lookup from the ctable.
27745 		 */
27746 		fake_ire = (ire_t *)mp->b_rptr;
27747 		/*
27748 		 * By the time we come back here from ARP
27749 		 * the logical outgoing interface  of the incomplete ire
27750 		 * we added in ire_forward could have disappeared,
27751 		 * causing the incomplete ire to also have
27752 		 * dissapeared. So we need to retreive the
27753 		 * proper ipif for the ire  before looking
27754 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27755 		 */
27756 		ill = q->q_ptr;
27757 
27758 		/* Get the outgoing ipif */
27759 		mutex_enter(&ill->ill_lock);
27760 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27761 			mutex_exit(&ill->ill_lock);
27762 			freemsg(mp); /* fake ire */
27763 			freeb(mp1);  /* dl_unitdata response */
27764 			return;
27765 		}
27766 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27767 
27768 		if (ipif == NULL) {
27769 			mutex_exit(&ill->ill_lock);
27770 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27771 			freemsg(mp);
27772 			freeb(mp1);
27773 			return;
27774 		}
27775 		ipif_refhold_locked(ipif);
27776 		mutex_exit(&ill->ill_lock);
27777 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27778 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27779 		    ipif, fake_ire->ire_zoneid, NULL,
27780 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27781 		ipif_refrele(ipif);
27782 		if (ire == NULL) {
27783 			/*
27784 			 * no ire was found; check if there is an nce
27785 			 * for this lookup; if it has no ire's pointing at it
27786 			 * cleanup.
27787 			 */
27788 			if ((nce = ndp_lookup_v4(ill,
27789 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27790 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27791 			    B_FALSE)) != NULL) {
27792 				/*
27793 				 * cleanup:
27794 				 * We check for refcnt 2 (one for the nce
27795 				 * hash list + 1 for the ref taken by
27796 				 * ndp_lookup_v4) to check that there are
27797 				 * no ire's pointing at the nce.
27798 				 */
27799 				if (nce->nce_refcnt == 2)
27800 					ndp_delete(nce);
27801 				NCE_REFRELE(nce);
27802 			}
27803 			freeb(mp1);  /* dl_unitdata response */
27804 			freemsg(mp); /* fake ire */
27805 			return;
27806 		}
27807 		nce = ire->ire_nce;
27808 		DTRACE_PROBE2(ire__arpresolve__type,
27809 		    ire_t *, ire, nce_t *, nce);
27810 		ASSERT(nce->nce_state != ND_INITIAL);
27811 		mutex_enter(&nce->nce_lock);
27812 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27813 		if (nce->nce_state == ND_REACHABLE) {
27814 			/*
27815 			 * Someone resolved this before us;
27816 			 * our response is not needed any more.
27817 			 */
27818 			mutex_exit(&nce->nce_lock);
27819 			freeb(mp1);  /* dl_unitdata response */
27820 		} else {
27821 			ASSERT(nce->nce_res_mp == NULL);
27822 			nce->nce_res_mp = mp1;
27823 			nce->nce_state = ND_REACHABLE;
27824 			mutex_exit(&nce->nce_lock);
27825 			nce_fastpath(nce);
27826 		}
27827 		/*
27828 		 * The cached nce_t has been updated to be reachable;
27829 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27830 		 */
27831 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27832 		freemsg(mp);
27833 		/*
27834 		 * send out queued packets.
27835 		 */
27836 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27837 
27838 		IRE_REFRELE(ire);
27839 		return;
27840 	}
27841 	default:
27842 		break;
27843 	}
27844 	if (q->q_next) {
27845 		putnext(q, mp);
27846 	} else
27847 		freemsg(mp);
27848 	return;
27849 
27850 protonak:
27851 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27852 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27853 		qreply(q, mp);
27854 }
27855 
27856 /*
27857  * Process IP options in an outbound packet.  Modify the destination if there
27858  * is a source route option.
27859  * Returns non-zero if something fails in which case an ICMP error has been
27860  * sent and mp freed.
27861  */
27862 static int
27863 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27864     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27865 {
27866 	ipoptp_t	opts;
27867 	uchar_t		*opt;
27868 	uint8_t		optval;
27869 	uint8_t		optlen;
27870 	ipaddr_t	dst;
27871 	intptr_t	code = 0;
27872 	mblk_t		*mp;
27873 	ire_t		*ire = NULL;
27874 
27875 	ip2dbg(("ip_wput_options\n"));
27876 	mp = ipsec_mp;
27877 	if (mctl_present) {
27878 		mp = ipsec_mp->b_cont;
27879 	}
27880 
27881 	dst = ipha->ipha_dst;
27882 	for (optval = ipoptp_first(&opts, ipha);
27883 	    optval != IPOPT_EOL;
27884 	    optval = ipoptp_next(&opts)) {
27885 		opt = opts.ipoptp_cur;
27886 		optlen = opts.ipoptp_len;
27887 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27888 		    optval, optlen));
27889 		switch (optval) {
27890 			uint32_t off;
27891 		case IPOPT_SSRR:
27892 		case IPOPT_LSRR:
27893 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27894 				ip1dbg((
27895 				    "ip_wput_options: bad option offset\n"));
27896 				code = (char *)&opt[IPOPT_OLEN] -
27897 				    (char *)ipha;
27898 				goto param_prob;
27899 			}
27900 			off = opt[IPOPT_OFFSET];
27901 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27902 			    ntohl(dst)));
27903 			/*
27904 			 * For strict: verify that dst is directly
27905 			 * reachable.
27906 			 */
27907 			if (optval == IPOPT_SSRR) {
27908 				ire = ire_ftable_lookup(dst, 0, 0,
27909 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27910 				    MBLK_GETLABEL(mp),
27911 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27912 				if (ire == NULL) {
27913 					ip1dbg(("ip_wput_options: SSRR not"
27914 					    " directly reachable: 0x%x\n",
27915 					    ntohl(dst)));
27916 					goto bad_src_route;
27917 				}
27918 				ire_refrele(ire);
27919 			}
27920 			break;
27921 		case IPOPT_RR:
27922 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27923 				ip1dbg((
27924 				    "ip_wput_options: bad option offset\n"));
27925 				code = (char *)&opt[IPOPT_OLEN] -
27926 				    (char *)ipha;
27927 				goto param_prob;
27928 			}
27929 			break;
27930 		case IPOPT_TS:
27931 			/*
27932 			 * Verify that length >=5 and that there is either
27933 			 * room for another timestamp or that the overflow
27934 			 * counter is not maxed out.
27935 			 */
27936 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27937 			if (optlen < IPOPT_MINLEN_IT) {
27938 				goto param_prob;
27939 			}
27940 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27941 				ip1dbg((
27942 				    "ip_wput_options: bad option offset\n"));
27943 				code = (char *)&opt[IPOPT_OFFSET] -
27944 				    (char *)ipha;
27945 				goto param_prob;
27946 			}
27947 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27948 			case IPOPT_TS_TSONLY:
27949 				off = IPOPT_TS_TIMELEN;
27950 				break;
27951 			case IPOPT_TS_TSANDADDR:
27952 			case IPOPT_TS_PRESPEC:
27953 			case IPOPT_TS_PRESPEC_RFC791:
27954 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27955 				break;
27956 			default:
27957 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27958 				    (char *)ipha;
27959 				goto param_prob;
27960 			}
27961 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27962 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27963 				/*
27964 				 * No room and the overflow counter is 15
27965 				 * already.
27966 				 */
27967 				goto param_prob;
27968 			}
27969 			break;
27970 		}
27971 	}
27972 
27973 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27974 		return (0);
27975 
27976 	ip1dbg(("ip_wput_options: error processing IP options."));
27977 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27978 
27979 param_prob:
27980 	/*
27981 	 * Since ip_wput() isn't close to finished, we fill
27982 	 * in enough of the header for credible error reporting.
27983 	 */
27984 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27985 		/* Failed */
27986 		freemsg(ipsec_mp);
27987 		return (-1);
27988 	}
27989 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27990 	return (-1);
27991 
27992 bad_src_route:
27993 	/*
27994 	 * Since ip_wput() isn't close to finished, we fill
27995 	 * in enough of the header for credible error reporting.
27996 	 */
27997 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27998 		/* Failed */
27999 		freemsg(ipsec_mp);
28000 		return (-1);
28001 	}
28002 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28003 	return (-1);
28004 }
28005 
28006 /*
28007  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28008  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28009  * thru /etc/system.
28010  */
28011 #define	CONN_MAXDRAINCNT	64
28012 
28013 static void
28014 conn_drain_init(ip_stack_t *ipst)
28015 {
28016 	int i;
28017 
28018 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28019 
28020 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28021 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28022 		/*
28023 		 * Default value of the number of drainers is the
28024 		 * number of cpus, subject to maximum of 8 drainers.
28025 		 */
28026 		if (boot_max_ncpus != -1)
28027 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28028 		else
28029 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28030 	}
28031 
28032 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28033 	    sizeof (idl_t), KM_SLEEP);
28034 
28035 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28036 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28037 		    MUTEX_DEFAULT, NULL);
28038 	}
28039 }
28040 
28041 static void
28042 conn_drain_fini(ip_stack_t *ipst)
28043 {
28044 	int i;
28045 
28046 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28047 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28048 	kmem_free(ipst->ips_conn_drain_list,
28049 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28050 	ipst->ips_conn_drain_list = NULL;
28051 }
28052 
28053 /*
28054  * Note: For an overview of how flowcontrol is handled in IP please see the
28055  * IP Flowcontrol notes at the top of this file.
28056  *
28057  * Flow control has blocked us from proceeding. Insert the given conn in one
28058  * of the conn drain lists. These conn wq's will be qenabled later on when
28059  * STREAMS flow control does a backenable. conn_walk_drain will enable
28060  * the first conn in each of these drain lists. Each of these qenabled conns
28061  * in turn enables the next in the list, after it runs, or when it closes,
28062  * thus sustaining the drain process.
28063  *
28064  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28065  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28066  * running at any time, on a given conn, since there can be only 1 service proc
28067  * running on a queue at any time.
28068  */
28069 void
28070 conn_drain_insert(conn_t *connp)
28071 {
28072 	idl_t	*idl;
28073 	uint_t	index;
28074 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28075 
28076 	mutex_enter(&connp->conn_lock);
28077 	if (connp->conn_state_flags & CONN_CLOSING) {
28078 		/*
28079 		 * The conn is closing as a result of which CONN_CLOSING
28080 		 * is set. Return.
28081 		 */
28082 		mutex_exit(&connp->conn_lock);
28083 		return;
28084 	} else if (connp->conn_idl == NULL) {
28085 		/*
28086 		 * Assign the next drain list round robin. We dont' use
28087 		 * a lock, and thus it may not be strictly round robin.
28088 		 * Atomicity of load/stores is enough to make sure that
28089 		 * conn_drain_list_index is always within bounds.
28090 		 */
28091 		index = ipst->ips_conn_drain_list_index;
28092 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28093 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28094 		index++;
28095 		if (index == ipst->ips_conn_drain_list_cnt)
28096 			index = 0;
28097 		ipst->ips_conn_drain_list_index = index;
28098 	}
28099 	mutex_exit(&connp->conn_lock);
28100 
28101 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28102 	if ((connp->conn_drain_prev != NULL) ||
28103 	    (connp->conn_state_flags & CONN_CLOSING)) {
28104 		/*
28105 		 * The conn is already in the drain list, OR
28106 		 * the conn is closing. We need to check again for
28107 		 * the closing case again since close can happen
28108 		 * after we drop the conn_lock, and before we
28109 		 * acquire the CONN_DRAIN_LIST_LOCK.
28110 		 */
28111 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28112 		return;
28113 	} else {
28114 		idl = connp->conn_idl;
28115 	}
28116 
28117 	/*
28118 	 * The conn is not in the drain list. Insert it at the
28119 	 * tail of the drain list. The drain list is circular
28120 	 * and doubly linked. idl_conn points to the 1st element
28121 	 * in the list.
28122 	 */
28123 	if (idl->idl_conn == NULL) {
28124 		idl->idl_conn = connp;
28125 		connp->conn_drain_next = connp;
28126 		connp->conn_drain_prev = connp;
28127 	} else {
28128 		conn_t *head = idl->idl_conn;
28129 
28130 		connp->conn_drain_next = head;
28131 		connp->conn_drain_prev = head->conn_drain_prev;
28132 		head->conn_drain_prev->conn_drain_next = connp;
28133 		head->conn_drain_prev = connp;
28134 	}
28135 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28136 }
28137 
28138 /*
28139  * This conn is closing, and we are called from ip_close. OR
28140  * This conn has been serviced by ip_wsrv, and we need to do the tail
28141  * processing.
28142  * If this conn is part of the drain list, we may need to sustain the drain
28143  * process by qenabling the next conn in the drain list. We may also need to
28144  * remove this conn from the list, if it is done.
28145  */
28146 static void
28147 conn_drain_tail(conn_t *connp, boolean_t closing)
28148 {
28149 	idl_t *idl;
28150 
28151 	/*
28152 	 * connp->conn_idl is stable at this point, and no lock is needed
28153 	 * to check it. If we are called from ip_close, close has already
28154 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28155 	 * called us only because conn_idl is non-null. If we are called thru
28156 	 * service, conn_idl could be null, but it cannot change because
28157 	 * service is single-threaded per queue, and there cannot be another
28158 	 * instance of service trying to call conn_drain_insert on this conn
28159 	 * now.
28160 	 */
28161 	ASSERT(!closing || (connp->conn_idl != NULL));
28162 
28163 	/*
28164 	 * If connp->conn_idl is null, the conn has not been inserted into any
28165 	 * drain list even once since creation of the conn. Just return.
28166 	 */
28167 	if (connp->conn_idl == NULL)
28168 		return;
28169 
28170 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28171 
28172 	if (connp->conn_drain_prev == NULL) {
28173 		/* This conn is currently not in the drain list.  */
28174 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28175 		return;
28176 	}
28177 	idl = connp->conn_idl;
28178 	if (idl->idl_conn_draining == connp) {
28179 		/*
28180 		 * This conn is the current drainer. If this is the last conn
28181 		 * in the drain list, we need to do more checks, in the 'if'
28182 		 * below. Otherwwise we need to just qenable the next conn,
28183 		 * to sustain the draining, and is handled in the 'else'
28184 		 * below.
28185 		 */
28186 		if (connp->conn_drain_next == idl->idl_conn) {
28187 			/*
28188 			 * This conn is the last in this list. This round
28189 			 * of draining is complete. If idl_repeat is set,
28190 			 * it means another flow enabling has happened from
28191 			 * the driver/streams and we need to another round
28192 			 * of draining.
28193 			 * If there are more than 2 conns in the drain list,
28194 			 * do a left rotate by 1, so that all conns except the
28195 			 * conn at the head move towards the head by 1, and the
28196 			 * the conn at the head goes to the tail. This attempts
28197 			 * a more even share for all queues that are being
28198 			 * drained.
28199 			 */
28200 			if ((connp->conn_drain_next != connp) &&
28201 			    (idl->idl_conn->conn_drain_next != connp)) {
28202 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28203 			}
28204 			if (idl->idl_repeat) {
28205 				qenable(idl->idl_conn->conn_wq);
28206 				idl->idl_conn_draining = idl->idl_conn;
28207 				idl->idl_repeat = 0;
28208 			} else {
28209 				idl->idl_conn_draining = NULL;
28210 			}
28211 		} else {
28212 			/*
28213 			 * If the next queue that we are now qenable'ing,
28214 			 * is closing, it will remove itself from this list
28215 			 * and qenable the subsequent queue in ip_close().
28216 			 * Serialization is acheived thru idl_lock.
28217 			 */
28218 			qenable(connp->conn_drain_next->conn_wq);
28219 			idl->idl_conn_draining = connp->conn_drain_next;
28220 		}
28221 	}
28222 	if (!connp->conn_did_putbq || closing) {
28223 		/*
28224 		 * Remove ourself from the drain list, if we did not do
28225 		 * a putbq, or if the conn is closing.
28226 		 * Note: It is possible that q->q_first is non-null. It means
28227 		 * that these messages landed after we did a enableok() in
28228 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28229 		 * service them.
28230 		 */
28231 		if (connp->conn_drain_next == connp) {
28232 			/* Singleton in the list */
28233 			ASSERT(connp->conn_drain_prev == connp);
28234 			idl->idl_conn = NULL;
28235 			idl->idl_conn_draining = NULL;
28236 		} else {
28237 			connp->conn_drain_prev->conn_drain_next =
28238 			    connp->conn_drain_next;
28239 			connp->conn_drain_next->conn_drain_prev =
28240 			    connp->conn_drain_prev;
28241 			if (idl->idl_conn == connp)
28242 				idl->idl_conn = connp->conn_drain_next;
28243 			ASSERT(idl->idl_conn_draining != connp);
28244 
28245 		}
28246 		connp->conn_drain_next = NULL;
28247 		connp->conn_drain_prev = NULL;
28248 	}
28249 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28250 }
28251 
28252 /*
28253  * Write service routine. Shared perimeter entry point.
28254  * ip_wsrv can be called in any of the following ways.
28255  * 1. The device queue's messages has fallen below the low water mark
28256  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28257  *    the drain lists and backenable the first conn in each list.
28258  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28259  *    qenabled non-tcp upper layers. We start dequeing messages and call
28260  *    ip_wput for each message.
28261  */
28262 
28263 void
28264 ip_wsrv(queue_t *q)
28265 {
28266 	conn_t	*connp;
28267 	ill_t	*ill;
28268 	mblk_t	*mp;
28269 
28270 	if (q->q_next) {
28271 		ill = (ill_t *)q->q_ptr;
28272 		if (ill->ill_state_flags == 0) {
28273 			/*
28274 			 * The device flow control has opened up.
28275 			 * Walk through conn drain lists and qenable the
28276 			 * first conn in each list. This makes sense only
28277 			 * if the stream is fully plumbed and setup.
28278 			 * Hence the if check above.
28279 			 */
28280 			ip1dbg(("ip_wsrv: walking\n"));
28281 			conn_walk_drain(ill->ill_ipst);
28282 		}
28283 		return;
28284 	}
28285 
28286 	connp = Q_TO_CONN(q);
28287 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28288 
28289 	/*
28290 	 * 1. Set conn_draining flag to signal that service is active.
28291 	 *
28292 	 * 2. ip_output determines whether it has been called from service,
28293 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28294 	 *    has been called from service.
28295 	 *
28296 	 * 3. Message ordering is preserved by the following logic.
28297 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28298 	 *    the message at the tail, if conn_draining is set (i.e. service
28299 	 *    is running) or if q->q_first is non-null.
28300 	 *
28301 	 *    ii. If ip_output is called from service, and if ip_output cannot
28302 	 *    putnext due to flow control, it does a putbq.
28303 	 *
28304 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28305 	 *    (causing an infinite loop).
28306 	 */
28307 	ASSERT(!connp->conn_did_putbq);
28308 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28309 		connp->conn_draining = 1;
28310 		noenable(q);
28311 		while ((mp = getq(q)) != NULL) {
28312 			ASSERT(CONN_Q(q));
28313 
28314 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28315 			if (connp->conn_did_putbq) {
28316 				/* ip_wput did a putbq */
28317 				break;
28318 			}
28319 		}
28320 		/*
28321 		 * At this point, a thread coming down from top, calling
28322 		 * ip_wput, may end up queueing the message. We have not yet
28323 		 * enabled the queue, so ip_wsrv won't be called again.
28324 		 * To avoid this race, check q->q_first again (in the loop)
28325 		 * If the other thread queued the message before we call
28326 		 * enableok(), we will catch it in the q->q_first check.
28327 		 * If the other thread queues the message after we call
28328 		 * enableok(), ip_wsrv will be called again by STREAMS.
28329 		 */
28330 		connp->conn_draining = 0;
28331 		enableok(q);
28332 	}
28333 
28334 	/* Enable the next conn for draining */
28335 	conn_drain_tail(connp, B_FALSE);
28336 
28337 	connp->conn_did_putbq = 0;
28338 }
28339 
28340 /*
28341  * Walk the list of all conn's calling the function provided with the
28342  * specified argument for each.	 Note that this only walks conn's that
28343  * have been bound.
28344  * Applies to both IPv4 and IPv6.
28345  */
28346 static void
28347 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28348 {
28349 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28350 	    ipst->ips_ipcl_udp_fanout_size,
28351 	    func, arg, zoneid);
28352 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28353 	    ipst->ips_ipcl_conn_fanout_size,
28354 	    func, arg, zoneid);
28355 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28356 	    ipst->ips_ipcl_bind_fanout_size,
28357 	    func, arg, zoneid);
28358 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28359 	    IPPROTO_MAX, func, arg, zoneid);
28360 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28361 	    IPPROTO_MAX, func, arg, zoneid);
28362 }
28363 
28364 /*
28365  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28366  * of conns that need to be drained, check if drain is already in progress.
28367  * If so set the idl_repeat bit, indicating that the last conn in the list
28368  * needs to reinitiate the drain once again, for the list. If drain is not
28369  * in progress for the list, initiate the draining, by qenabling the 1st
28370  * conn in the list. The drain is self-sustaining, each qenabled conn will
28371  * in turn qenable the next conn, when it is done/blocked/closing.
28372  */
28373 static void
28374 conn_walk_drain(ip_stack_t *ipst)
28375 {
28376 	int i;
28377 	idl_t *idl;
28378 
28379 	IP_STAT(ipst, ip_conn_walk_drain);
28380 
28381 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28382 		idl = &ipst->ips_conn_drain_list[i];
28383 		mutex_enter(&idl->idl_lock);
28384 		if (idl->idl_conn == NULL) {
28385 			mutex_exit(&idl->idl_lock);
28386 			continue;
28387 		}
28388 		/*
28389 		 * If this list is not being drained currently by
28390 		 * an ip_wsrv thread, start the process.
28391 		 */
28392 		if (idl->idl_conn_draining == NULL) {
28393 			ASSERT(idl->idl_repeat == 0);
28394 			qenable(idl->idl_conn->conn_wq);
28395 			idl->idl_conn_draining = idl->idl_conn;
28396 		} else {
28397 			idl->idl_repeat = 1;
28398 		}
28399 		mutex_exit(&idl->idl_lock);
28400 	}
28401 }
28402 
28403 /*
28404  * Walk an conn hash table of `count' buckets, calling func for each entry.
28405  */
28406 static void
28407 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28408     zoneid_t zoneid)
28409 {
28410 	conn_t	*connp;
28411 
28412 	while (count-- > 0) {
28413 		mutex_enter(&connfp->connf_lock);
28414 		for (connp = connfp->connf_head; connp != NULL;
28415 		    connp = connp->conn_next) {
28416 			if (zoneid == GLOBAL_ZONEID ||
28417 			    zoneid == connp->conn_zoneid) {
28418 				CONN_INC_REF(connp);
28419 				mutex_exit(&connfp->connf_lock);
28420 				(*func)(connp, arg);
28421 				mutex_enter(&connfp->connf_lock);
28422 				CONN_DEC_REF(connp);
28423 			}
28424 		}
28425 		mutex_exit(&connfp->connf_lock);
28426 		connfp++;
28427 	}
28428 }
28429 
28430 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28431 static void
28432 conn_report1(conn_t *connp, void *mp)
28433 {
28434 	char	buf1[INET6_ADDRSTRLEN];
28435 	char	buf2[INET6_ADDRSTRLEN];
28436 	uint_t	print_len, buf_len;
28437 
28438 	ASSERT(connp != NULL);
28439 
28440 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28441 	if (buf_len <= 0)
28442 		return;
28443 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28444 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28445 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28446 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28447 	    "%5d %s/%05d %s/%05d\n",
28448 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28449 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28450 	    buf1, connp->conn_lport,
28451 	    buf2, connp->conn_fport);
28452 	if (print_len < buf_len) {
28453 		((mblk_t *)mp)->b_wptr += print_len;
28454 	} else {
28455 		((mblk_t *)mp)->b_wptr += buf_len;
28456 	}
28457 }
28458 
28459 /*
28460  * Named Dispatch routine to produce a formatted report on all conns
28461  * that are listed in one of the fanout tables.
28462  * This report is accessed by using the ndd utility to "get" ND variable
28463  * "ip_conn_status".
28464  */
28465 /* ARGSUSED */
28466 static int
28467 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28468 {
28469 	conn_t *connp = Q_TO_CONN(q);
28470 
28471 	(void) mi_mpprintf(mp,
28472 	    "CONN      " MI_COL_HDRPAD_STR
28473 	    "rfq      " MI_COL_HDRPAD_STR
28474 	    "stq      " MI_COL_HDRPAD_STR
28475 	    " zone local                 remote");
28476 
28477 	/*
28478 	 * Because of the ndd constraint, at most we can have 64K buffer
28479 	 * to put in all conn info.  So to be more efficient, just
28480 	 * allocate a 64K buffer here, assuming we need that large buffer.
28481 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28482 	 */
28483 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28484 		/* The following may work even if we cannot get a large buf. */
28485 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28486 		return (0);
28487 	}
28488 
28489 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28490 	    connp->conn_netstack->netstack_ip);
28491 	return (0);
28492 }
28493 
28494 /*
28495  * Determine if the ill and multicast aspects of that packets
28496  * "matches" the conn.
28497  */
28498 boolean_t
28499 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28500     zoneid_t zoneid)
28501 {
28502 	ill_t *in_ill;
28503 	boolean_t found;
28504 	ipif_t *ipif;
28505 	ire_t *ire;
28506 	ipaddr_t dst, src;
28507 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28508 
28509 	dst = ipha->ipha_dst;
28510 	src = ipha->ipha_src;
28511 
28512 	/*
28513 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28514 	 * unicast, broadcast and multicast reception to
28515 	 * conn_incoming_ill. conn_wantpacket itself is called
28516 	 * only for BROADCAST and multicast.
28517 	 *
28518 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28519 	 *    is part of a group. Hence, we should be receiving
28520 	 *    just one copy of broadcast for the whole group.
28521 	 *    Thus, if it is part of the group the packet could
28522 	 *    come on any ill of the group and hence we need a
28523 	 *    match on the group. Otherwise, match on ill should
28524 	 *    be sufficient.
28525 	 *
28526 	 * 2) ip_rput does not suppress duplicate multicast packets.
28527 	 *    If there are two interfaces in a ill group and we have
28528 	 *    2 applications (conns) joined a multicast group G on
28529 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28530 	 *    will give us two packets because we join G on both the
28531 	 *    interfaces rather than nominating just one interface
28532 	 *    for receiving multicast like broadcast above. So,
28533 	 *    we have to call ilg_lookup_ill to filter out duplicate
28534 	 *    copies, if ill is part of a group.
28535 	 */
28536 	in_ill = connp->conn_incoming_ill;
28537 	if (in_ill != NULL) {
28538 		if (in_ill->ill_group == NULL) {
28539 			if (in_ill != ill)
28540 				return (B_FALSE);
28541 		} else if (in_ill->ill_group != ill->ill_group) {
28542 			return (B_FALSE);
28543 		}
28544 	}
28545 
28546 	if (!CLASSD(dst)) {
28547 		if (IPCL_ZONE_MATCH(connp, zoneid))
28548 			return (B_TRUE);
28549 		/*
28550 		 * The conn is in a different zone; we need to check that this
28551 		 * broadcast address is configured in the application's zone and
28552 		 * on one ill in the group.
28553 		 */
28554 		ipif = ipif_get_next_ipif(NULL, ill);
28555 		if (ipif == NULL)
28556 			return (B_FALSE);
28557 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28558 		    connp->conn_zoneid, NULL,
28559 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28560 		ipif_refrele(ipif);
28561 		if (ire != NULL) {
28562 			ire_refrele(ire);
28563 			return (B_TRUE);
28564 		} else {
28565 			return (B_FALSE);
28566 		}
28567 	}
28568 
28569 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28570 	    connp->conn_zoneid == zoneid) {
28571 		/*
28572 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28573 		 * disabled, therefore we don't dispatch the multicast packet to
28574 		 * the sending zone.
28575 		 */
28576 		return (B_FALSE);
28577 	}
28578 
28579 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28580 		/*
28581 		 * Multicast packet on the loopback interface: we only match
28582 		 * conns who joined the group in the specified zone.
28583 		 */
28584 		return (B_FALSE);
28585 	}
28586 
28587 	if (connp->conn_multi_router) {
28588 		/* multicast packet and multicast router socket: send up */
28589 		return (B_TRUE);
28590 	}
28591 
28592 	mutex_enter(&connp->conn_lock);
28593 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28594 	mutex_exit(&connp->conn_lock);
28595 	return (found);
28596 }
28597 
28598 /*
28599  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28600  */
28601 /* ARGSUSED */
28602 static void
28603 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28604 {
28605 	ill_t *ill = (ill_t *)q->q_ptr;
28606 	mblk_t	*mp1, *mp2;
28607 	ipif_t  *ipif;
28608 	int err = 0;
28609 	conn_t *connp = NULL;
28610 	ipsq_t	*ipsq;
28611 	arc_t	*arc;
28612 
28613 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28614 
28615 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28616 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28617 
28618 	ASSERT(IAM_WRITER_ILL(ill));
28619 	mp2 = mp->b_cont;
28620 	mp->b_cont = NULL;
28621 
28622 	/*
28623 	 * We have now received the arp bringup completion message
28624 	 * from ARP. Mark the arp bringup as done. Also if the arp
28625 	 * stream has already started closing, send up the AR_ARP_CLOSING
28626 	 * ack now since ARP is waiting in close for this ack.
28627 	 */
28628 	mutex_enter(&ill->ill_lock);
28629 	ill->ill_arp_bringup_pending = 0;
28630 	if (ill->ill_arp_closing) {
28631 		mutex_exit(&ill->ill_lock);
28632 		/* Let's reuse the mp for sending the ack */
28633 		arc = (arc_t *)mp->b_rptr;
28634 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28635 		arc->arc_cmd = AR_ARP_CLOSING;
28636 		qreply(q, mp);
28637 	} else {
28638 		mutex_exit(&ill->ill_lock);
28639 		freeb(mp);
28640 	}
28641 
28642 	ipsq = ill->ill_phyint->phyint_ipsq;
28643 	ipif = ipsq->ipsq_pending_ipif;
28644 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28645 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28646 	if (mp1 == NULL) {
28647 		/* bringup was aborted by the user */
28648 		freemsg(mp2);
28649 		return;
28650 	}
28651 
28652 	/*
28653 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28654 	 * must have an associated conn_t.  Otherwise, we're bringing this
28655 	 * interface back up as part of handling an asynchronous event (e.g.,
28656 	 * physical address change).
28657 	 */
28658 	if (ipsq->ipsq_current_ioctl != 0) {
28659 		ASSERT(connp != NULL);
28660 		q = CONNP_TO_WQ(connp);
28661 	} else {
28662 		ASSERT(connp == NULL);
28663 		q = ill->ill_rq;
28664 	}
28665 
28666 	/*
28667 	 * If the DL_BIND_REQ fails, it is noted
28668 	 * in arc_name_offset.
28669 	 */
28670 	err = *((int *)mp2->b_rptr);
28671 	if (err == 0) {
28672 		if (ipif->ipif_isv6) {
28673 			if ((err = ipif_up_done_v6(ipif)) != 0)
28674 				ip0dbg(("ip_arp_done: init failed\n"));
28675 		} else {
28676 			if ((err = ipif_up_done(ipif)) != 0)
28677 				ip0dbg(("ip_arp_done: init failed\n"));
28678 		}
28679 	} else {
28680 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28681 	}
28682 
28683 	freemsg(mp2);
28684 
28685 	if ((err == 0) && (ill->ill_up_ipifs)) {
28686 		err = ill_up_ipifs(ill, q, mp1);
28687 		if (err == EINPROGRESS)
28688 			return;
28689 	}
28690 
28691 	if (ill->ill_up_ipifs)
28692 		ill_group_cleanup(ill);
28693 
28694 	/*
28695 	 * The operation must complete without EINPROGRESS since
28696 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28697 	 * Otherwise, the operation will be stuck forever in the ipsq.
28698 	 */
28699 	ASSERT(err != EINPROGRESS);
28700 	if (ipsq->ipsq_current_ioctl != 0)
28701 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28702 	else
28703 		ipsq_current_finish(ipsq);
28704 }
28705 
28706 /* Allocate the private structure */
28707 static int
28708 ip_priv_alloc(void **bufp)
28709 {
28710 	void	*buf;
28711 
28712 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28713 		return (ENOMEM);
28714 
28715 	*bufp = buf;
28716 	return (0);
28717 }
28718 
28719 /* Function to delete the private structure */
28720 void
28721 ip_priv_free(void *buf)
28722 {
28723 	ASSERT(buf != NULL);
28724 	kmem_free(buf, sizeof (ip_priv_t));
28725 }
28726 
28727 /*
28728  * The entry point for IPPF processing.
28729  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28730  * routine just returns.
28731  *
28732  * When called, ip_process generates an ipp_packet_t structure
28733  * which holds the state information for this packet and invokes the
28734  * the classifier (via ipp_packet_process). The classification, depending on
28735  * configured filters, results in a list of actions for this packet. Invoking
28736  * an action may cause the packet to be dropped, in which case the resulting
28737  * mblk (*mpp) is NULL. proc indicates the callout position for
28738  * this packet and ill_index is the interface this packet on or will leave
28739  * on (inbound and outbound resp.).
28740  */
28741 void
28742 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28743 {
28744 	mblk_t		*mp;
28745 	ip_priv_t	*priv;
28746 	ipp_action_id_t	aid;
28747 	int		rc = 0;
28748 	ipp_packet_t	*pp;
28749 #define	IP_CLASS	"ip"
28750 
28751 	/* If the classifier is not loaded, return  */
28752 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28753 		return;
28754 	}
28755 
28756 	mp = *mpp;
28757 	ASSERT(mp != NULL);
28758 
28759 	/* Allocate the packet structure */
28760 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28761 	if (rc != 0) {
28762 		*mpp = NULL;
28763 		freemsg(mp);
28764 		return;
28765 	}
28766 
28767 	/* Allocate the private structure */
28768 	rc = ip_priv_alloc((void **)&priv);
28769 	if (rc != 0) {
28770 		*mpp = NULL;
28771 		freemsg(mp);
28772 		ipp_packet_free(pp);
28773 		return;
28774 	}
28775 	priv->proc = proc;
28776 	priv->ill_index = ill_index;
28777 	ipp_packet_set_private(pp, priv, ip_priv_free);
28778 	ipp_packet_set_data(pp, mp);
28779 
28780 	/* Invoke the classifier */
28781 	rc = ipp_packet_process(&pp);
28782 	if (pp != NULL) {
28783 		mp = ipp_packet_get_data(pp);
28784 		ipp_packet_free(pp);
28785 		if (rc != 0) {
28786 			freemsg(mp);
28787 			*mpp = NULL;
28788 		}
28789 	} else {
28790 		*mpp = NULL;
28791 	}
28792 #undef	IP_CLASS
28793 }
28794 
28795 /*
28796  * Propagate a multicast group membership operation (add/drop) on
28797  * all the interfaces crossed by the related multirt routes.
28798  * The call is considered successful if the operation succeeds
28799  * on at least one interface.
28800  */
28801 static int
28802 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28803     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28804     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28805     mblk_t *first_mp)
28806 {
28807 	ire_t		*ire_gw;
28808 	irb_t		*irb;
28809 	int		error = 0;
28810 	opt_restart_t	*or;
28811 	ip_stack_t	*ipst = ire->ire_ipst;
28812 
28813 	irb = ire->ire_bucket;
28814 	ASSERT(irb != NULL);
28815 
28816 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28817 
28818 	or = (opt_restart_t *)first_mp->b_rptr;
28819 	IRB_REFHOLD(irb);
28820 	for (; ire != NULL; ire = ire->ire_next) {
28821 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28822 			continue;
28823 		if (ire->ire_addr != group)
28824 			continue;
28825 
28826 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28827 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28828 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28829 		/* No resolver exists for the gateway; skip this ire. */
28830 		if (ire_gw == NULL)
28831 			continue;
28832 
28833 		/*
28834 		 * This function can return EINPROGRESS. If so the operation
28835 		 * will be restarted from ip_restart_optmgmt which will
28836 		 * call ip_opt_set and option processing will restart for
28837 		 * this option. So we may end up calling 'fn' more than once.
28838 		 * This requires that 'fn' is idempotent except for the
28839 		 * return value. The operation is considered a success if
28840 		 * it succeeds at least once on any one interface.
28841 		 */
28842 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28843 		    NULL, fmode, src, first_mp);
28844 		if (error == 0)
28845 			or->or_private = CGTP_MCAST_SUCCESS;
28846 
28847 		if (ip_debug > 0) {
28848 			ulong_t	off;
28849 			char	*ksym;
28850 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28851 			ip2dbg(("ip_multirt_apply_membership: "
28852 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28853 			    "error %d [success %u]\n",
28854 			    ksym ? ksym : "?",
28855 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28856 			    error, or->or_private));
28857 		}
28858 
28859 		ire_refrele(ire_gw);
28860 		if (error == EINPROGRESS) {
28861 			IRB_REFRELE(irb);
28862 			return (error);
28863 		}
28864 	}
28865 	IRB_REFRELE(irb);
28866 	/*
28867 	 * Consider the call as successful if we succeeded on at least
28868 	 * one interface. Otherwise, return the last encountered error.
28869 	 */
28870 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28871 }
28872 
28873 
28874 /*
28875  * Issue a warning regarding a route crossing an interface with an
28876  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28877  * amount of time is logged.
28878  */
28879 static void
28880 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28881 {
28882 	hrtime_t	current = gethrtime();
28883 	char		buf[INET_ADDRSTRLEN];
28884 	ip_stack_t	*ipst = ire->ire_ipst;
28885 
28886 	/* Convert interval in ms to hrtime in ns */
28887 	if (ipst->ips_multirt_bad_mtu_last_time +
28888 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28889 	    current) {
28890 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28891 		    "to %s, incorrect MTU %u (expected %u)\n",
28892 		    ip_dot_addr(ire->ire_addr, buf),
28893 		    ire->ire_max_frag, max_frag);
28894 
28895 		ipst->ips_multirt_bad_mtu_last_time = current;
28896 	}
28897 }
28898 
28899 
28900 /*
28901  * Get the CGTP (multirouting) filtering status.
28902  * If 0, the CGTP hooks are transparent.
28903  */
28904 /* ARGSUSED */
28905 static int
28906 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28907 {
28908 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28909 
28910 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28911 	return (0);
28912 }
28913 
28914 
28915 /*
28916  * Set the CGTP (multirouting) filtering status.
28917  * If the status is changed from active to transparent
28918  * or from transparent to active, forward the new status
28919  * to the filtering module (if loaded).
28920  */
28921 /* ARGSUSED */
28922 static int
28923 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28924     cred_t *ioc_cr)
28925 {
28926 	long		new_value;
28927 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28928 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28929 
28930 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28931 		return (EPERM);
28932 
28933 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28934 	    new_value < 0 || new_value > 1) {
28935 		return (EINVAL);
28936 	}
28937 
28938 	if ((!*ip_cgtp_filter_value) && new_value) {
28939 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28940 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28941 		    " (module not loaded)" : "");
28942 	}
28943 	if (*ip_cgtp_filter_value && (!new_value)) {
28944 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28945 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28946 		    " (module not loaded)" : "");
28947 	}
28948 
28949 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28950 		int	res;
28951 		netstackid_t stackid;
28952 
28953 		stackid = ipst->ips_netstack->netstack_stackid;
28954 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28955 		    new_value);
28956 		if (res)
28957 			return (res);
28958 	}
28959 
28960 	*ip_cgtp_filter_value = (boolean_t)new_value;
28961 
28962 	return (0);
28963 }
28964 
28965 
28966 /*
28967  * Return the expected CGTP hooks version number.
28968  */
28969 int
28970 ip_cgtp_filter_supported(void)
28971 {
28972 	return (ip_cgtp_filter_rev);
28973 }
28974 
28975 
28976 /*
28977  * CGTP hooks can be registered by invoking this function.
28978  * Checks that the version number matches.
28979  */
28980 int
28981 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28982 {
28983 	netstack_t *ns;
28984 	ip_stack_t *ipst;
28985 
28986 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28987 		return (ENOTSUP);
28988 
28989 	ns = netstack_find_by_stackid(stackid);
28990 	if (ns == NULL)
28991 		return (EINVAL);
28992 	ipst = ns->netstack_ip;
28993 	ASSERT(ipst != NULL);
28994 
28995 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28996 		netstack_rele(ns);
28997 		return (EALREADY);
28998 	}
28999 
29000 	ipst->ips_ip_cgtp_filter_ops = ops;
29001 	netstack_rele(ns);
29002 	return (0);
29003 }
29004 
29005 /*
29006  * CGTP hooks can be unregistered by invoking this function.
29007  * Returns ENXIO if there was no registration.
29008  * Returns EBUSY if the ndd variable has not been turned off.
29009  */
29010 int
29011 ip_cgtp_filter_unregister(netstackid_t stackid)
29012 {
29013 	netstack_t *ns;
29014 	ip_stack_t *ipst;
29015 
29016 	ns = netstack_find_by_stackid(stackid);
29017 	if (ns == NULL)
29018 		return (EINVAL);
29019 	ipst = ns->netstack_ip;
29020 	ASSERT(ipst != NULL);
29021 
29022 	if (ipst->ips_ip_cgtp_filter) {
29023 		netstack_rele(ns);
29024 		return (EBUSY);
29025 	}
29026 
29027 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29028 		netstack_rele(ns);
29029 		return (ENXIO);
29030 	}
29031 	ipst->ips_ip_cgtp_filter_ops = NULL;
29032 	netstack_rele(ns);
29033 	return (0);
29034 }
29035 
29036 /*
29037  * Check whether there is a CGTP filter registration.
29038  * Returns non-zero if there is a registration, otherwise returns zero.
29039  * Note: returns zero if bad stackid.
29040  */
29041 int
29042 ip_cgtp_filter_is_registered(netstackid_t stackid)
29043 {
29044 	netstack_t *ns;
29045 	ip_stack_t *ipst;
29046 	int ret;
29047 
29048 	ns = netstack_find_by_stackid(stackid);
29049 	if (ns == NULL)
29050 		return (0);
29051 	ipst = ns->netstack_ip;
29052 	ASSERT(ipst != NULL);
29053 
29054 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29055 		ret = 1;
29056 	else
29057 		ret = 0;
29058 
29059 	netstack_rele(ns);
29060 	return (ret);
29061 }
29062 
29063 static squeue_func_t
29064 ip_squeue_switch(int val)
29065 {
29066 	squeue_func_t rval = squeue_fill;
29067 
29068 	switch (val) {
29069 	case IP_SQUEUE_ENTER_NODRAIN:
29070 		rval = squeue_enter_nodrain;
29071 		break;
29072 	case IP_SQUEUE_ENTER:
29073 		rval = squeue_enter;
29074 		break;
29075 	default:
29076 		break;
29077 	}
29078 	return (rval);
29079 }
29080 
29081 /* ARGSUSED */
29082 static int
29083 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29084     caddr_t addr, cred_t *cr)
29085 {
29086 	int *v = (int *)addr;
29087 	long new_value;
29088 
29089 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29090 		return (EPERM);
29091 
29092 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29093 		return (EINVAL);
29094 
29095 	ip_input_proc = ip_squeue_switch(new_value);
29096 	*v = new_value;
29097 	return (0);
29098 }
29099 
29100 /* ARGSUSED */
29101 static int
29102 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29103     caddr_t addr, cred_t *cr)
29104 {
29105 	int *v = (int *)addr;
29106 	long new_value;
29107 
29108 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29109 		return (EPERM);
29110 
29111 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29112 		return (EINVAL);
29113 
29114 	*v = new_value;
29115 	return (0);
29116 }
29117 
29118 /*
29119  * Handle changes to ipmp_hook_emulation ndd variable.
29120  * Need to update phyint_hook_ifindex.
29121  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29122  */
29123 static void
29124 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29125 {
29126 	phyint_t *phyi;
29127 	phyint_t *phyi_tmp;
29128 	char *groupname;
29129 	int namelen;
29130 	ill_t	*ill;
29131 	boolean_t new_group;
29132 
29133 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29134 	/*
29135 	 * Group indicies are stored in the phyint - a common structure
29136 	 * to both IPv4 and IPv6.
29137 	 */
29138 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29139 	for (; phyi != NULL;
29140 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29141 	    phyi, AVL_AFTER)) {
29142 		/* Ignore the ones that do not have a group */
29143 		if (phyi->phyint_groupname_len == 0)
29144 			continue;
29145 
29146 		/*
29147 		 * Look for other phyint in group.
29148 		 * Clear name/namelen so the lookup doesn't find ourselves.
29149 		 */
29150 		namelen = phyi->phyint_groupname_len;
29151 		groupname = phyi->phyint_groupname;
29152 		phyi->phyint_groupname_len = 0;
29153 		phyi->phyint_groupname = NULL;
29154 
29155 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29156 		/* Restore */
29157 		phyi->phyint_groupname_len = namelen;
29158 		phyi->phyint_groupname = groupname;
29159 
29160 		new_group = B_FALSE;
29161 		if (ipst->ips_ipmp_hook_emulation) {
29162 			/*
29163 			 * If the group already exists and has already
29164 			 * been assigned a group ifindex, we use the existing
29165 			 * group_ifindex, otherwise we pick a new group_ifindex
29166 			 * here.
29167 			 */
29168 			if (phyi_tmp != NULL &&
29169 			    phyi_tmp->phyint_group_ifindex != 0) {
29170 				phyi->phyint_group_ifindex =
29171 				    phyi_tmp->phyint_group_ifindex;
29172 			} else {
29173 				/* XXX We need a recovery strategy here. */
29174 				if (!ip_assign_ifindex(
29175 				    &phyi->phyint_group_ifindex, ipst))
29176 					cmn_err(CE_PANIC,
29177 					    "ip_assign_ifindex() failed");
29178 				new_group = B_TRUE;
29179 			}
29180 		} else {
29181 			phyi->phyint_group_ifindex = 0;
29182 		}
29183 		if (ipst->ips_ipmp_hook_emulation)
29184 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29185 		else
29186 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29187 
29188 		/*
29189 		 * For IP Filter to find out the relationship between
29190 		 * names and interface indicies, we need to generate
29191 		 * a NE_PLUMB event when a new group can appear.
29192 		 * We always generate events when a new interface appears
29193 		 * (even when ipmp_hook_emulation is set) so there
29194 		 * is no need to generate NE_PLUMB events when
29195 		 * ipmp_hook_emulation is turned off.
29196 		 * And since it isn't critical for IP Filter to get
29197 		 * the NE_UNPLUMB events we skip those here.
29198 		 */
29199 		if (new_group) {
29200 			/*
29201 			 * First phyint in group - generate group PLUMB event.
29202 			 * Since we are not running inside the ipsq we do
29203 			 * the dispatch immediately.
29204 			 */
29205 			if (phyi->phyint_illv4 != NULL)
29206 				ill = phyi->phyint_illv4;
29207 			else
29208 				ill = phyi->phyint_illv6;
29209 
29210 			if (ill != NULL) {
29211 				mutex_enter(&ill->ill_lock);
29212 				ill_nic_info_plumb(ill, B_TRUE);
29213 				ill_nic_info_dispatch(ill);
29214 				mutex_exit(&ill->ill_lock);
29215 			}
29216 		}
29217 	}
29218 	rw_exit(&ipst->ips_ill_g_lock);
29219 }
29220 
29221 /* ARGSUSED */
29222 static int
29223 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29224     caddr_t addr, cred_t *cr)
29225 {
29226 	int *v = (int *)addr;
29227 	long new_value;
29228 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29229 
29230 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29231 		return (EINVAL);
29232 
29233 	if (*v != new_value) {
29234 		*v = new_value;
29235 		ipmp_hook_emulation_changed(ipst);
29236 	}
29237 	return (0);
29238 }
29239 
29240 static void *
29241 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29242 {
29243 	kstat_t *ksp;
29244 
29245 	ip_stat_t template = {
29246 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29247 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29248 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29249 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29250 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29251 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29252 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29253 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29254 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29255 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29256 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29257 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29258 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29259 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29260 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29261 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29262 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29263 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29264 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29265 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29266 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29267 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29268 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29269 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29270 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29271 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29272 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29273 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29274 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29275 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29276 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29277 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29278 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29279 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29280 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29281 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29282 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29283 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29284 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29285 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29286 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29287 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29288 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29289 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29290 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29291 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29292 	};
29293 
29294 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29295 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29296 	    KSTAT_FLAG_VIRTUAL, stackid);
29297 
29298 	if (ksp == NULL)
29299 		return (NULL);
29300 
29301 	bcopy(&template, ip_statisticsp, sizeof (template));
29302 	ksp->ks_data = (void *)ip_statisticsp;
29303 	ksp->ks_private = (void *)(uintptr_t)stackid;
29304 
29305 	kstat_install(ksp);
29306 	return (ksp);
29307 }
29308 
29309 static void
29310 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29311 {
29312 	if (ksp != NULL) {
29313 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29314 		kstat_delete_netstack(ksp, stackid);
29315 	}
29316 }
29317 
29318 static void *
29319 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29320 {
29321 	kstat_t	*ksp;
29322 
29323 	ip_named_kstat_t template = {
29324 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29325 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29326 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29327 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29328 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29329 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29330 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29331 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29332 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29333 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29334 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29335 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29336 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29337 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29338 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29339 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29340 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29341 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29342 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29343 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29344 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29345 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29346 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29347 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29348 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29349 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29350 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29351 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29352 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29353 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29354 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29355 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29356 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29357 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29358 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29359 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29360 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29361 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29362 	};
29363 
29364 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29365 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29366 	if (ksp == NULL || ksp->ks_data == NULL)
29367 		return (NULL);
29368 
29369 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29370 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29371 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29372 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29373 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29374 
29375 	template.netToMediaEntrySize.value.i32 =
29376 	    sizeof (mib2_ipNetToMediaEntry_t);
29377 
29378 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29379 
29380 	bcopy(&template, ksp->ks_data, sizeof (template));
29381 	ksp->ks_update = ip_kstat_update;
29382 	ksp->ks_private = (void *)(uintptr_t)stackid;
29383 
29384 	kstat_install(ksp);
29385 	return (ksp);
29386 }
29387 
29388 static void
29389 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29390 {
29391 	if (ksp != NULL) {
29392 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29393 		kstat_delete_netstack(ksp, stackid);
29394 	}
29395 }
29396 
29397 static int
29398 ip_kstat_update(kstat_t *kp, int rw)
29399 {
29400 	ip_named_kstat_t *ipkp;
29401 	mib2_ipIfStatsEntry_t ipmib;
29402 	ill_walk_context_t ctx;
29403 	ill_t *ill;
29404 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29405 	netstack_t	*ns;
29406 	ip_stack_t	*ipst;
29407 
29408 	if (kp == NULL || kp->ks_data == NULL)
29409 		return (EIO);
29410 
29411 	if (rw == KSTAT_WRITE)
29412 		return (EACCES);
29413 
29414 	ns = netstack_find_by_stackid(stackid);
29415 	if (ns == NULL)
29416 		return (-1);
29417 	ipst = ns->netstack_ip;
29418 	if (ipst == NULL) {
29419 		netstack_rele(ns);
29420 		return (-1);
29421 	}
29422 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29423 
29424 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29425 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29426 	ill = ILL_START_WALK_V4(&ctx, ipst);
29427 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29428 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29429 	rw_exit(&ipst->ips_ill_g_lock);
29430 
29431 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29432 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29433 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29434 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29435 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29436 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29437 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29438 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29439 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29440 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29441 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29442 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29443 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29444 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29445 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29446 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29447 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29448 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29449 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29450 
29451 	ipkp->routingDiscards.value.ui32 =	0;
29452 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29453 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29454 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29455 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29456 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29457 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29458 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29459 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29460 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29461 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29462 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29463 
29464 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29465 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29466 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29467 
29468 	netstack_rele(ns);
29469 
29470 	return (0);
29471 }
29472 
29473 static void *
29474 icmp_kstat_init(netstackid_t stackid)
29475 {
29476 	kstat_t	*ksp;
29477 
29478 	icmp_named_kstat_t template = {
29479 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29480 		{ "inErrors",		KSTAT_DATA_UINT32 },
29481 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29482 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29483 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29484 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29485 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29486 		{ "inEchos",		KSTAT_DATA_UINT32 },
29487 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29488 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29489 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29490 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29491 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29492 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29493 		{ "outErrors",		KSTAT_DATA_UINT32 },
29494 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29495 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29496 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29497 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29498 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29499 		{ "outEchos",		KSTAT_DATA_UINT32 },
29500 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29501 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29502 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29503 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29504 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29505 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29506 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29507 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29508 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29509 		{ "outDrops",		KSTAT_DATA_UINT32 },
29510 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29511 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29512 	};
29513 
29514 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29515 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29516 	if (ksp == NULL || ksp->ks_data == NULL)
29517 		return (NULL);
29518 
29519 	bcopy(&template, ksp->ks_data, sizeof (template));
29520 
29521 	ksp->ks_update = icmp_kstat_update;
29522 	ksp->ks_private = (void *)(uintptr_t)stackid;
29523 
29524 	kstat_install(ksp);
29525 	return (ksp);
29526 }
29527 
29528 static void
29529 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29530 {
29531 	if (ksp != NULL) {
29532 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29533 		kstat_delete_netstack(ksp, stackid);
29534 	}
29535 }
29536 
29537 static int
29538 icmp_kstat_update(kstat_t *kp, int rw)
29539 {
29540 	icmp_named_kstat_t *icmpkp;
29541 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29542 	netstack_t	*ns;
29543 	ip_stack_t	*ipst;
29544 
29545 	if ((kp == NULL) || (kp->ks_data == NULL))
29546 		return (EIO);
29547 
29548 	if (rw == KSTAT_WRITE)
29549 		return (EACCES);
29550 
29551 	ns = netstack_find_by_stackid(stackid);
29552 	if (ns == NULL)
29553 		return (-1);
29554 	ipst = ns->netstack_ip;
29555 	if (ipst == NULL) {
29556 		netstack_rele(ns);
29557 		return (-1);
29558 	}
29559 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29560 
29561 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29562 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29563 	icmpkp->inDestUnreachs.value.ui32 =
29564 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29565 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29566 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29567 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29568 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29569 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29570 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29571 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29572 	icmpkp->inTimestampReps.value.ui32 =
29573 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29574 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29575 	icmpkp->inAddrMaskReps.value.ui32 =
29576 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29577 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29578 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29579 	icmpkp->outDestUnreachs.value.ui32 =
29580 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29581 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29582 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29583 	icmpkp->outSrcQuenchs.value.ui32 =
29584 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29585 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29586 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29587 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29588 	icmpkp->outTimestamps.value.ui32 =
29589 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29590 	icmpkp->outTimestampReps.value.ui32 =
29591 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29592 	icmpkp->outAddrMasks.value.ui32 =
29593 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29594 	icmpkp->outAddrMaskReps.value.ui32 =
29595 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29596 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29597 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29598 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29599 	icmpkp->outFragNeeded.value.ui32 =
29600 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29601 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29602 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29603 	icmpkp->inBadRedirects.value.ui32 =
29604 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29605 
29606 	netstack_rele(ns);
29607 	return (0);
29608 }
29609 
29610 /*
29611  * This is the fanout function for raw socket opened for SCTP.  Note
29612  * that it is called after SCTP checks that there is no socket which
29613  * wants a packet.  Then before SCTP handles this out of the blue packet,
29614  * this function is called to see if there is any raw socket for SCTP.
29615  * If there is and it is bound to the correct address, the packet will
29616  * be sent to that socket.  Note that only one raw socket can be bound to
29617  * a port.  This is assured in ipcl_sctp_hash_insert();
29618  */
29619 void
29620 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29621     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29622     zoneid_t zoneid)
29623 {
29624 	conn_t		*connp;
29625 	queue_t		*rq;
29626 	mblk_t		*first_mp;
29627 	boolean_t	secure;
29628 	ip6_t		*ip6h;
29629 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29630 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29631 
29632 	first_mp = mp;
29633 	if (mctl_present) {
29634 		mp = first_mp->b_cont;
29635 		secure = ipsec_in_is_secure(first_mp);
29636 		ASSERT(mp != NULL);
29637 	} else {
29638 		secure = B_FALSE;
29639 	}
29640 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29641 
29642 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29643 	if (connp == NULL) {
29644 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29645 		return;
29646 	}
29647 	rq = connp->conn_rq;
29648 	if (!canputnext(rq)) {
29649 		CONN_DEC_REF(connp);
29650 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29651 		freemsg(first_mp);
29652 		return;
29653 	}
29654 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29655 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29656 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29657 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29658 		if (first_mp == NULL) {
29659 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29660 			CONN_DEC_REF(connp);
29661 			return;
29662 		}
29663 	}
29664 	/*
29665 	 * We probably should not send M_CTL message up to
29666 	 * raw socket.
29667 	 */
29668 	if (mctl_present)
29669 		freeb(first_mp);
29670 
29671 	/* Initiate IPPF processing here if needed. */
29672 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29673 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29674 		ip_process(IPP_LOCAL_IN, &mp,
29675 		    recv_ill->ill_phyint->phyint_ifindex);
29676 		if (mp == NULL) {
29677 			CONN_DEC_REF(connp);
29678 			return;
29679 		}
29680 	}
29681 
29682 	if (connp->conn_recvif || connp->conn_recvslla ||
29683 	    ((connp->conn_ip_recvpktinfo ||
29684 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29685 	    (flags & IP_FF_IPINFO))) {
29686 		int in_flags = 0;
29687 
29688 		/*
29689 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29690 		 * IPF_RECVIF.
29691 		 */
29692 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29693 			in_flags = IPF_RECVIF;
29694 		}
29695 		if (connp->conn_recvslla) {
29696 			in_flags |= IPF_RECVSLLA;
29697 		}
29698 		if (isv4) {
29699 			mp = ip_add_info(mp, recv_ill, in_flags,
29700 			    IPCL_ZONEID(connp), ipst);
29701 		} else {
29702 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29703 			if (mp == NULL) {
29704 				BUMP_MIB(recv_ill->ill_ip_mib,
29705 				    ipIfStatsInDiscards);
29706 				CONN_DEC_REF(connp);
29707 				return;
29708 			}
29709 		}
29710 	}
29711 
29712 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29713 	/*
29714 	 * We are sending the IPSEC_IN message also up. Refer
29715 	 * to comments above this function.
29716 	 */
29717 	putnext(rq, mp);
29718 	CONN_DEC_REF(connp);
29719 }
29720 
29721 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29722 {									\
29723 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29724 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29725 }
29726 /*
29727  * This function should be called only if all packet processing
29728  * including fragmentation is complete. Callers of this function
29729  * must set mp->b_prev to one of these values:
29730  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29731  * prior to handing over the mp as first argument to this function.
29732  *
29733  * If the ire passed by caller is incomplete, this function
29734  * queues the packet and if necessary, sends ARP request and bails.
29735  * If the ire passed is fully resolved, we simply prepend
29736  * the link-layer header to the packet, do ipsec hw acceleration
29737  * work if necessary, and send the packet out on the wire.
29738  *
29739  * NOTE: IPsec will only call this function with fully resolved
29740  * ires if hw acceleration is involved.
29741  * TODO list :
29742  * 	a Handle M_MULTIDATA so that
29743  *	  tcp_multisend->tcp_multisend_data can
29744  *	  call ip_xmit_v4 directly
29745  *	b Handle post-ARP work for fragments so that
29746  *	  ip_wput_frag can call this function.
29747  */
29748 ipxmit_state_t
29749 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29750 {
29751 	nce_t		*arpce;
29752 	queue_t		*q;
29753 	int		ill_index;
29754 	mblk_t		*nxt_mp, *first_mp;
29755 	boolean_t	xmit_drop = B_FALSE;
29756 	ip_proc_t	proc;
29757 	ill_t		*out_ill;
29758 	int		pkt_len;
29759 
29760 	arpce = ire->ire_nce;
29761 	ASSERT(arpce != NULL);
29762 
29763 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29764 
29765 	mutex_enter(&arpce->nce_lock);
29766 	switch (arpce->nce_state) {
29767 	case ND_REACHABLE:
29768 		/* If there are other queued packets, queue this packet */
29769 		if (arpce->nce_qd_mp != NULL) {
29770 			if (mp != NULL)
29771 				nce_queue_mp_common(arpce, mp, B_FALSE);
29772 			mp = arpce->nce_qd_mp;
29773 		}
29774 		arpce->nce_qd_mp = NULL;
29775 		mutex_exit(&arpce->nce_lock);
29776 
29777 		/*
29778 		 * Flush the queue.  In the common case, where the
29779 		 * ARP is already resolved,  it will go through the
29780 		 * while loop only once.
29781 		 */
29782 		while (mp != NULL) {
29783 
29784 			nxt_mp = mp->b_next;
29785 			mp->b_next = NULL;
29786 			ASSERT(mp->b_datap->db_type != M_CTL);
29787 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29788 			/*
29789 			 * This info is needed for IPQOS to do COS marking
29790 			 * in ip_wput_attach_llhdr->ip_process.
29791 			 */
29792 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29793 			mp->b_prev = NULL;
29794 
29795 			/* set up ill index for outbound qos processing */
29796 			out_ill = ire->ire_ipif->ipif_ill;
29797 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29798 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29799 			    ill_index);
29800 			if (first_mp == NULL) {
29801 				xmit_drop = B_TRUE;
29802 				BUMP_MIB(out_ill->ill_ip_mib,
29803 				    ipIfStatsOutDiscards);
29804 				goto next_mp;
29805 			}
29806 			/* non-ipsec hw accel case */
29807 			if (io == NULL || !io->ipsec_out_accelerated) {
29808 				/* send it */
29809 				q = ire->ire_stq;
29810 				if (proc == IPP_FWD_OUT) {
29811 					UPDATE_IB_PKT_COUNT(ire);
29812 				} else {
29813 					UPDATE_OB_PKT_COUNT(ire);
29814 				}
29815 				ire->ire_last_used_time = lbolt;
29816 
29817 				if (flow_ctl_enabled || canputnext(q)) {
29818 					if (proc == IPP_FWD_OUT) {
29819 
29820 					BUMP_MIB(out_ill->ill_ip_mib,
29821 					    ipIfStatsHCOutForwDatagrams);
29822 
29823 					}
29824 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29825 					    pkt_len);
29826 
29827 					putnext(q, first_mp);
29828 				} else {
29829 					BUMP_MIB(out_ill->ill_ip_mib,
29830 					    ipIfStatsOutDiscards);
29831 					xmit_drop = B_TRUE;
29832 					freemsg(first_mp);
29833 				}
29834 			} else {
29835 				/*
29836 				 * Safety Pup says: make sure this
29837 				 *  is going to the right interface!
29838 				 */
29839 				ill_t *ill1 =
29840 				    (ill_t *)ire->ire_stq->q_ptr;
29841 				int ifindex =
29842 				    ill1->ill_phyint->phyint_ifindex;
29843 				if (ifindex !=
29844 				    io->ipsec_out_capab_ill_index) {
29845 					xmit_drop = B_TRUE;
29846 					freemsg(mp);
29847 				} else {
29848 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29849 					    pkt_len);
29850 					ipsec_hw_putnext(ire->ire_stq, mp);
29851 				}
29852 			}
29853 next_mp:
29854 			mp = nxt_mp;
29855 		} /* while (mp != NULL) */
29856 		if (xmit_drop)
29857 			return (SEND_FAILED);
29858 		else
29859 			return (SEND_PASSED);
29860 
29861 	case ND_INITIAL:
29862 	case ND_INCOMPLETE:
29863 
29864 		/*
29865 		 * While we do send off packets to dests that
29866 		 * use fully-resolved CGTP routes, we do not
29867 		 * handle unresolved CGTP routes.
29868 		 */
29869 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29870 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29871 
29872 		if (mp != NULL) {
29873 			/* queue the packet */
29874 			nce_queue_mp_common(arpce, mp, B_FALSE);
29875 		}
29876 
29877 		if (arpce->nce_state == ND_INCOMPLETE) {
29878 			mutex_exit(&arpce->nce_lock);
29879 			DTRACE_PROBE3(ip__xmit__incomplete,
29880 			    (ire_t *), ire, (mblk_t *), mp,
29881 			    (ipsec_out_t *), io);
29882 			return (LOOKUP_IN_PROGRESS);
29883 		}
29884 
29885 		arpce->nce_state = ND_INCOMPLETE;
29886 		mutex_exit(&arpce->nce_lock);
29887 		/*
29888 		 * Note that ire_add() (called from ire_forward())
29889 		 * holds a ref on the ire until ARP is completed.
29890 		 */
29891 
29892 		ire_arpresolve(ire, ire_to_ill(ire));
29893 		return (LOOKUP_IN_PROGRESS);
29894 	default:
29895 		ASSERT(0);
29896 		mutex_exit(&arpce->nce_lock);
29897 		return (LLHDR_RESLV_FAILED);
29898 	}
29899 }
29900 
29901 #undef	UPDATE_IP_MIB_OB_COUNTERS
29902 
29903 /*
29904  * Return B_TRUE if the buffers differ in length or content.
29905  * This is used for comparing extension header buffers.
29906  * Note that an extension header would be declared different
29907  * even if all that changed was the next header value in that header i.e.
29908  * what really changed is the next extension header.
29909  */
29910 boolean_t
29911 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29912     uint_t blen)
29913 {
29914 	if (!b_valid)
29915 		blen = 0;
29916 
29917 	if (alen != blen)
29918 		return (B_TRUE);
29919 	if (alen == 0)
29920 		return (B_FALSE);	/* Both zero length */
29921 	return (bcmp(abuf, bbuf, alen));
29922 }
29923 
29924 /*
29925  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29926  * Return B_FALSE if memory allocation fails - don't change any state!
29927  */
29928 boolean_t
29929 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29930     const void *src, uint_t srclen)
29931 {
29932 	void *dst;
29933 
29934 	if (!src_valid)
29935 		srclen = 0;
29936 
29937 	ASSERT(*dstlenp == 0);
29938 	if (src != NULL && srclen != 0) {
29939 		dst = mi_alloc(srclen, BPRI_MED);
29940 		if (dst == NULL)
29941 			return (B_FALSE);
29942 	} else {
29943 		dst = NULL;
29944 	}
29945 	if (*dstp != NULL)
29946 		mi_free(*dstp);
29947 	*dstp = dst;
29948 	*dstlenp = dst == NULL ? 0 : srclen;
29949 	return (B_TRUE);
29950 }
29951 
29952 /*
29953  * Replace what is in *dst, *dstlen with the source.
29954  * Assumes ip_allocbuf has already been called.
29955  */
29956 void
29957 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29958     const void *src, uint_t srclen)
29959 {
29960 	if (!src_valid)
29961 		srclen = 0;
29962 
29963 	ASSERT(*dstlenp == srclen);
29964 	if (src != NULL && srclen != 0)
29965 		bcopy(src, *dstp, srclen);
29966 }
29967 
29968 /*
29969  * Free the storage pointed to by the members of an ip6_pkt_t.
29970  */
29971 void
29972 ip6_pkt_free(ip6_pkt_t *ipp)
29973 {
29974 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29975 
29976 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29977 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29978 		ipp->ipp_hopopts = NULL;
29979 		ipp->ipp_hopoptslen = 0;
29980 	}
29981 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29982 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29983 		ipp->ipp_rtdstopts = NULL;
29984 		ipp->ipp_rtdstoptslen = 0;
29985 	}
29986 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29987 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29988 		ipp->ipp_dstopts = NULL;
29989 		ipp->ipp_dstoptslen = 0;
29990 	}
29991 	if (ipp->ipp_fields & IPPF_RTHDR) {
29992 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29993 		ipp->ipp_rthdr = NULL;
29994 		ipp->ipp_rthdrlen = 0;
29995 	}
29996 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29997 	    IPPF_RTHDR);
29998 }
29999