xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 437220cd296f6d8b6654d6d52508b40b1e2d1ac7)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/optcom.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <sys/sunddi.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
131  * IP_SQUEUE_ENTER: squeue_enter
132  * IP_SQUEUE_FILL: squeue_fill
133  */
134 int ip_squeue_enter = 2;	/* Setable in /etc/system */
135 
136 squeue_func_t ip_input_proc;
137 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
138 
139 #define	TCP6 "tcp6"
140 #define	TCP "tcp"
141 #define	SCTP "sctp"
142 #define	SCTP6 "sctp6"
143 
144 major_t TCP6_MAJ;
145 major_t TCP_MAJ;
146 major_t SCTP_MAJ;
147 major_t SCTP6_MAJ;
148 
149 /*
150  * Setable in /etc/system
151  */
152 int ip_poll_normal_ms = 100;
153 int ip_poll_normal_ticks = 0;
154 int ip_modclose_ackwait_ms = 3000;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	listptr_t	ird_route;	/* ipRouteEntryTable */
174 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
175 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
176 } iproutedata_t;
177 
178 /*
179  * Cluster specific hooks. These should be NULL when booted as a non-cluster
180  */
181 
182 /*
183  * Hook functions to enable cluster networking
184  * On non-clustered systems these vectors must always be NULL.
185  *
186  * Hook function to Check ip specified ip address is a shared ip address
187  * in the cluster
188  *
189  */
190 int (*cl_inet_isclusterwide)(uint8_t protocol,
191     sa_family_t addr_family, uint8_t *laddrp) = NULL;
192 
193 /*
194  * Hook function to generate cluster wide ip fragment identifier
195  */
196 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
197     uint8_t *laddrp, uint8_t *faddrp) = NULL;
198 
199 /*
200  * Synchronization notes:
201  *
202  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
203  * MT level protection given by STREAMS. IP uses a combination of its own
204  * internal serialization mechanism and standard Solaris locking techniques.
205  * The internal serialization is per phyint (no IPMP) or per IPMP group.
206  * This is used to serialize plumbing operations, IPMP operations, certain
207  * multicast operations, most set ioctls, igmp/mld timers etc.
208  *
209  * Plumbing is a long sequence of operations involving message
210  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
211  * involved in plumbing operations. A natural model is to serialize these
212  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
213  * parallel without any interference. But various set ioctls on hme0 are best
214  * serialized. However if the system uses IPMP, the operations are easier if
215  * they are serialized on a per IPMP group basis since IPMP operations
216  * happen across ill's of a group. Thus the lowest common denominator is to
217  * serialize most set ioctls, multicast join/leave operations, IPMP operations
218  * igmp/mld timer operations, and processing of DLPI control messages received
219  * from drivers on a per IPMP group basis. If the system does not employ
220  * IPMP the serialization is on a per phyint basis. This serialization is
221  * provided by the ipsq_t and primitives operating on this. Details can
222  * be found in ip_if.c above the core primitives operating on ipsq_t.
223  *
224  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
225  * Simiarly lookup of an ire by a thread also returns a refheld ire.
226  * In addition ipif's and ill's referenced by the ire are also indirectly
227  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
228  * the ipif's address or netmask change as long as an ipif is refheld
229  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
230  * address of an ipif has to go through the ipsq_t. This ensures that only
231  * 1 such exclusive operation proceeds at any time on the ipif. It then
232  * deletes all ires associated with this ipif, and waits for all refcnts
233  * associated with this ipif to come down to zero. The address is changed
234  * only after the ipif has been quiesced. Then the ipif is brought up again.
235  * More details are described above the comment in ip_sioctl_flags.
236  *
237  * Packet processing is based mostly on IREs and are fully multi-threaded
238  * using standard Solaris MT techniques.
239  *
240  * There are explicit locks in IP to handle:
241  * - The ip_g_head list maintained by mi_open_link() and friends.
242  *
243  * - The reassembly data structures (one lock per hash bucket)
244  *
245  * - conn_lock is meant to protect conn_t fields. The fields actually
246  *   protected by conn_lock are documented in the conn_t definition.
247  *
248  * - ire_lock to protect some of the fields of the ire, IRE tables
249  *   (one lock per hash bucket). Refer to ip_ire.c for details.
250  *
251  * - ndp_g_lock and nce_lock for protecting NCEs.
252  *
253  * - ill_lock protects fields of the ill and ipif. Details in ip.h
254  *
255  * - ill_g_lock: This is a global reader/writer lock. Protects the following
256  *	* The AVL tree based global multi list of all ills.
257  *	* The linked list of all ipifs of an ill
258  *	* The <ill-ipsq> mapping
259  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
260  *	* The illgroup list threaded by ill_group_next.
261  *	* <ill-phyint> association
262  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
263  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
264  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
265  *   will all have to hold the ill_g_lock as writer for the actual duration
266  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
267  *   may be found in the IPMP section.
268  *
269  * - ill_lock:  This is a per ill mutex.
270  *   It protects some members of the ill and is documented below.
271  *   It also protects the <ill-ipsq> mapping
272  *   It also protects the illgroup list threaded by ill_group_next.
273  *   It also protects the <ill-phyint> assoc.
274  *   It also protects the list of ipifs hanging off the ill.
275  *
276  * - ipsq_lock: This is a per ipsq_t mutex lock.
277  *   This protects all the other members of the ipsq struct except
278  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
279  *
280  * - illgrp_lock: This is a per ill_group mutex lock.
281  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
282  *   which dictates which is the next ill in an ill_group that is to be chosen
283  *   for sending outgoing packets, through creation of an IRE_CACHE that
284  *   references this ill.
285  *
286  * - phyint_lock: This is a per phyint mutex lock. Protects just the
287  *   phyint_flags
288  *
289  * - ip_g_nd_lock: This is a global reader/writer lock.
290  *   Any call to nd_load to load a new parameter to the ND table must hold the
291  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
292  *   as reader.
293  *
294  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
295  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
296  *   uniqueness check also done atomically.
297  *
298  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
299  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
300  *   as a writer when adding or deleting elements from these lists, and
301  *   as a reader when walking these lists to send a SADB update to the
302  *   IPsec capable ills.
303  *
304  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
305  *   group list linked by ill_usesrc_grp_next. It also protects the
306  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
307  *   group is being added or deleted.  This lock is taken as a reader when
308  *   walking the list/group(eg: to get the number of members in a usesrc group).
309  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
310  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
311  *   example, it is not necessary to take this lock in the initial portion
312  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
313  *   ip_sioctl_flags since the these operations are executed exclusively and
314  *   that ensures that the "usesrc group state" cannot change. The "usesrc
315  *   group state" change can happen only in the latter part of
316  *   ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
325  * and the ill_lock of the ill in question must be held.
326  *
327  * To change the <ill-illgroup> association the ill_g_lock must be held as
328  * writer and the ill_lock of the ill in question must be held.
329  *
330  * To add or delete an ipif from the list of ipifs hanging off the ill,
331  * ill_g_lock (writer) and ill_lock must be held and the thread must be
332  * a writer on the associated ipsq,.
333  *
334  * To add or delete an ill to the system, the ill_g_lock must be held as
335  * writer and the thread must be a writer on the associated ipsq.
336  *
337  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
338  * must be a writer on the associated ipsq.
339  *
340  * Lock hierarchy
341  *
342  * Some lock hierarchy scenarios are listed below.
343  *
344  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
345  * ill_g_lock -> illgrp_lock -> ill_lock
346  * ill_g_lock -> ill_lock(s) -> phyint_lock
347  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
348  * ill_g_lock -> ip_addr_avail_lock
349  * conn_lock -> irb_lock -> ill_lock -> ire_lock
350  * ill_g_lock -> ip_g_nd_lock
351  *
352  * When more than 1 ill lock is needed to be held, all ill lock addresses
353  * are sorted on address and locked starting from highest addressed lock
354  * downward.
355  *
356  * IPsec scenarios
357  *
358  * ipsa_lock -> ill_g_lock -> ill_lock
359  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
360  * ipsec_capab_ills_lock -> ipsa_lock
361  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
362  *
363  * Trusted Solaris scenarios
364  *
365  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
366  * igsa_lock -> gcdb_lock
367  * gcgrp_rwlock -> ire_lock
368  * gcgrp_rwlock -> gcdb_lock
369  *
370  *
371  * Routing/forwarding table locking notes:
372  *
373  * Lock acquisition order: Radix tree lock, irb_lock.
374  * Requirements:
375  * i.  Walker must not hold any locks during the walker callback.
376  * ii  Walker must not see a truncated tree during the walk because of any node
377  *     deletion.
378  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
379  *     in many places in the code to walk the irb list. Thus even if all the
380  *     ires in a bucket have been deleted, we still can't free the radix node
381  *     until the ires have actually been inactive'd (freed).
382  *
383  * Tree traversal - Need to hold the global tree lock in read mode.
384  * Before dropping the global tree lock, need to either increment the ire_refcnt
385  * to ensure that the radix node can't be deleted.
386  *
387  * Tree add - Need to hold the global tree lock in write mode to add a
388  * radix node. To prevent the node from being deleted, increment the
389  * irb_refcnt, after the node is added to the tree. The ire itself is
390  * added later while holding the irb_lock, but not the tree lock.
391  *
392  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
393  * All associated ires must be inactive (i.e. freed), and irb_refcnt
394  * must be zero.
395  *
396  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
397  * global tree lock (read mode) for traversal.
398  *
399  * IPsec notes :
400  *
401  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
402  * in front of the actual packet. For outbound datagrams, the M_CTL
403  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
404  * information used by the IPsec code for applying the right level of
405  * protection. The information initialized by IP in the ipsec_out_t
406  * is determined by the per-socket policy or global policy in the system.
407  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
408  * ipsec_info.h) which starts out with nothing in it. It gets filled
409  * with the right information if it goes through the AH/ESP code, which
410  * happens if the incoming packet is secure. The information initialized
411  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
412  * the policy requirements needed by per-socket policy or global policy
413  * is met or not.
414  *
415  * If there is both per-socket policy (set using setsockopt) and there
416  * is also global policy match for the 5 tuples of the socket,
417  * ipsec_override_policy() makes the decision of which one to use.
418  *
419  * For fully connected sockets i.e dst, src [addr, port] is known,
420  * conn_policy_cached is set indicating that policy has been cached.
421  * conn_in_enforce_policy may or may not be set depending on whether
422  * there is a global policy match or per-socket policy match.
423  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
424  * Once the right policy is set on the conn_t, policy cannot change for
425  * this socket. This makes life simpler for TCP (UDP ?) where
426  * re-transmissions go out with the same policy. For symmetry, policy
427  * is cached for fully connected UDP sockets also. Thus if policy is cached,
428  * it also implies that policy is latched i.e policy cannot change
429  * on these sockets. As we have the right policy on the conn, we don't
430  * have to lookup global policy for every outbound and inbound datagram
431  * and thus serving as an optimization. Note that a global policy change
432  * does not affect fully connected sockets if they have policy. If fully
433  * connected sockets did not have any policy associated with it, global
434  * policy change may affect them.
435  *
436  * IP Flow control notes:
437  *
438  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
439  * cannot be sent down to the driver by IP, because of a canput failure, IP
440  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
441  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
442  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
443  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
444  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
445  * the queued messages, and removes the conn from the drain list, if all
446  * messages were drained. It also qenables the next conn in the drain list to
447  * continue the drain process.
448  *
449  * In reality the drain list is not a single list, but a configurable number
450  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
451  * list. If the ip_wsrv of the next qenabled conn does not run, because the
452  * stream closes, ip_close takes responsibility to qenable the next conn in
453  * the drain list. The directly called ip_wput path always does a putq, if
454  * it cannot putnext. Thus synchronization problems are handled between
455  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
456  * functions that manipulate this drain list. Furthermore conn_drain_insert
457  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
458  * running on a queue at any time. conn_drain_tail can be simultaneously called
459  * from both ip_wsrv and ip_close.
460  *
461  * IPQOS notes:
462  *
463  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
464  * and IPQoS modules. IPPF includes hooks in IP at different control points
465  * (callout positions) which direct packets to IPQoS modules for policy
466  * processing. Policies, if present, are global.
467  *
468  * The callout positions are located in the following paths:
469  *		o local_in (packets destined for this host)
470  *		o local_out (packets orginating from this host )
471  *		o fwd_in  (packets forwarded by this m/c - inbound)
472  *		o fwd_out (packets forwarded by this m/c - outbound)
473  * Hooks at these callout points can be enabled/disabled using the ndd variable
474  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
475  * By default all the callout positions are enabled.
476  *
477  * Outbound (local_out)
478  * Hooks are placed in ip_wput_ire and ipsec_out_process.
479  *
480  * Inbound (local_in)
481  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
482  * TCP and UDP fanout routines.
483  *
484  * Forwarding (in and out)
485  * Hooks are placed in ip_rput_forward.
486  *
487  * IP Policy Framework processing (IPPF processing)
488  * Policy processing for a packet is initiated by ip_process, which ascertains
489  * that the classifier (ipgpc) is loaded and configured, failing which the
490  * packet resumes normal processing in IP. If the clasifier is present, the
491  * packet is acted upon by one or more IPQoS modules (action instances), per
492  * filters configured in ipgpc and resumes normal IP processing thereafter.
493  * An action instance can drop a packet in course of its processing.
494  *
495  * A boolean variable, ip_policy, is used in all the fanout routines that can
496  * invoke ip_process for a packet. This variable indicates if the packet should
497  * to be sent for policy processing. The variable is set to B_TRUE by default,
498  * i.e. when the routines are invoked in the normal ip procesing path for a
499  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
500  * ip_policy is set to B_FALSE for all the routines called in these two
501  * functions because, in the former case,  we don't process loopback traffic
502  * currently while in the latter, the packets have already been processed in
503  * icmp_inbound.
504  *
505  * Zones notes:
506  *
507  * The partitioning rules for networking are as follows:
508  * 1) Packets coming from a zone must have a source address belonging to that
509  * zone.
510  * 2) Packets coming from a zone can only be sent on a physical interface on
511  * which the zone has an IP address.
512  * 3) Between two zones on the same machine, packet delivery is only allowed if
513  * there's a matching route for the destination and zone in the forwarding
514  * table.
515  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
516  * different zones can bind to the same port with the wildcard address
517  * (INADDR_ANY).
518  *
519  * The granularity of interface partitioning is at the logical interface level.
520  * Therefore, every zone has its own IP addresses, and incoming packets can be
521  * attributed to a zone unambiguously. A logical interface is placed into a zone
522  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
523  * structure. Rule (1) is implemented by modifying the source address selection
524  * algorithm so that the list of eligible addresses is filtered based on the
525  * sending process zone.
526  *
527  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
528  * across all zones, depending on their type. Here is the break-up:
529  *
530  * IRE type				Shared/exclusive
531  * --------				----------------
532  * IRE_BROADCAST			Exclusive
533  * IRE_DEFAULT (default routes)		Shared (*)
534  * IRE_LOCAL				Exclusive (x)
535  * IRE_LOOPBACK				Exclusive
536  * IRE_PREFIX (net routes)		Shared (*)
537  * IRE_CACHE				Exclusive
538  * IRE_IF_NORESOLVER (interface routes)	Exclusive
539  * IRE_IF_RESOLVER (interface routes)	Exclusive
540  * IRE_HOST (host routes)		Shared (*)
541  *
542  * (*) A zone can only use a default or off-subnet route if the gateway is
543  * directly reachable from the zone, that is, if the gateway's address matches
544  * one of the zone's logical interfaces.
545  *
546  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
547  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
548  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
549  * address of the zone itself (the destination). Since IRE_LOCAL is used
550  * for communication between zones, ip_wput_ire has special logic to set
551  * the right source address when sending using an IRE_LOCAL.
552  *
553  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
554  * ire_cache_lookup restricts loopback using an IRE_LOCAL
555  * between zone to the case when L2 would have conceptually looped the packet
556  * back, i.e. the loopback which is required since neither Ethernet drivers
557  * nor Ethernet hardware loops them back. This is the case when the normal
558  * routes (ignoring IREs with different zoneids) would send out the packet on
559  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
560  * associated.
561  *
562  * Multiple zones can share a common broadcast address; typically all zones
563  * share the 255.255.255.255 address. Incoming as well as locally originated
564  * broadcast packets must be dispatched to all the zones on the broadcast
565  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
566  * since some zones may not be on the 10.16.72/24 network. To handle this, each
567  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
568  * sent to every zone that has an IRE_BROADCAST entry for the destination
569  * address on the input ill, see conn_wantpacket().
570  *
571  * Applications in different zones can join the same multicast group address.
572  * For IPv4, group memberships are per-logical interface, so they're already
573  * inherently part of a zone. For IPv6, group memberships are per-physical
574  * interface, so we distinguish IPv6 group memberships based on group address,
575  * interface and zoneid. In both cases, received multicast packets are sent to
576  * every zone for which a group membership entry exists. On IPv6 we need to
577  * check that the target zone still has an address on the receiving physical
578  * interface; it could have been removed since the application issued the
579  * IPV6_JOIN_GROUP.
580  */
581 
582 /*
583  * Squeue Fanout flags:
584  *	0: No fanout.
585  *	1: Fanout across all squeues
586  */
587 boolean_t	ip_squeue_fanout = 0;
588 
589 /*
590  * Maximum dups allowed per packet.
591  */
592 uint_t ip_max_frag_dups = 10;
593 
594 #define	IS_SIMPLE_IPH(ipha)						\
595 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
596 
597 /* RFC1122 Conformance */
598 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
599 
600 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
601 
602 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
603 
604 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
605 
606 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
607 		    ip_stack_t *);
608 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
609 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
610 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
611 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
612 		    mblk_t *, int, ip_stack_t *);
613 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
614 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
615 		    ill_t *, zoneid_t);
616 static void	icmp_options_update(ipha_t *);
617 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
618 		    ip_stack_t *);
619 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
620 		    zoneid_t zoneid, ip_stack_t *);
621 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
622 static void	icmp_redirect(ill_t *, mblk_t *);
623 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
624 		    ip_stack_t *);
625 
626 static void	ip_arp_news(queue_t *, mblk_t *);
627 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
628 		    ip_stack_t *);
629 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
630 char		*ip_dot_addr(ipaddr_t, char *);
631 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
632 int		ip_close(queue_t *, int);
633 static char	*ip_dot_saddr(uchar_t *, char *);
634 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
635 		    boolean_t, boolean_t, ill_t *, zoneid_t);
636 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
637 		    boolean_t, boolean_t, zoneid_t);
638 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
639 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
640 static void	ip_lrput(queue_t *, mblk_t *);
641 ipaddr_t	ip_net_mask(ipaddr_t);
642 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
643 		    ip_stack_t *);
644 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
645 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
646 char		*ip_nv_lookup(nv_t *, int);
647 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
648 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
649 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
650 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
651     ipndp_t *, size_t);
652 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
653 void	ip_rput(queue_t *, mblk_t *);
654 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
655 		    void *dummy_arg);
656 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
657 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
658     ip_stack_t *);
659 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
660 			    ire_t *, ip_stack_t *);
661 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
662 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
663 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
664     ip_stack_t *);
665 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
666 		    uint16_t *);
667 int		ip_snmp_get(queue_t *, mblk_t *);
668 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
669 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
670 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
671 		    ip_stack_t *);
672 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
673 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
674 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
675 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
676 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
677 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
678 		    ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
680 		    ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
682 		    ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
684 		    ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
686 		    ip_stack_t *ipst);
687 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
688 		    ip_stack_t *ipst);
689 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst);
691 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
698 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
699 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
700 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
701 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
702 static boolean_t	ip_source_route_included(ipha_t *);
703 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
704 
705 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
706 		    zoneid_t, ip_stack_t *);
707 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
708 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
709 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
710 		    zoneid_t, ip_stack_t *);
711 
712 static void	conn_drain_init(ip_stack_t *);
713 static void	conn_drain_fini(ip_stack_t *);
714 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
715 
716 static void	conn_walk_drain(ip_stack_t *);
717 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
718     zoneid_t);
719 
720 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
721 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
722 static void	ip_stack_fini(netstackid_t stackid, void *arg);
723 
724 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
725     zoneid_t);
726 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
727     void *dummy_arg);
728 
729 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
730 
731 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
732     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
733     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
734 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
735 
736 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
737 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
738     caddr_t, cred_t *);
739 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
740     caddr_t cp, cred_t *cr);
741 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
742     cred_t *);
743 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
744     caddr_t cp, cred_t *cr);
745 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
746     cred_t *);
747 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
748     cred_t *);
749 static squeue_func_t ip_squeue_switch(int);
750 
751 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
752 static void	ip_kstat_fini(netstackid_t, kstat_t *);
753 static int	ip_kstat_update(kstat_t *kp, int rw);
754 static void	*icmp_kstat_init(netstackid_t);
755 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
756 static int	icmp_kstat_update(kstat_t *kp, int rw);
757 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
758 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
759 
760 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
761 
762 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
763     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
764 
765 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
766     ipha_t *, ill_t *, boolean_t);
767 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
768 
769 /* How long, in seconds, we allow frags to hang around. */
770 #define	IP_FRAG_TIMEOUT	60
771 
772 /*
773  * Threshold which determines whether MDT should be used when
774  * generating IP fragments; payload size must be greater than
775  * this threshold for MDT to take place.
776  */
777 #define	IP_WPUT_FRAG_MDT_MIN	32768
778 
779 /* Setable in /etc/system only */
780 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
781 
782 static long ip_rput_pullups;
783 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
784 
785 vmem_t *ip_minor_arena;
786 
787 int	ip_debug;
788 
789 #ifdef DEBUG
790 uint32_t ipsechw_debug = 0;
791 #endif
792 
793 /*
794  * Multirouting/CGTP stuff
795  */
796 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
797 
798 /*
799  * XXX following really should only be in a header. Would need more
800  * header and .c clean up first.
801  */
802 extern optdb_obj_t	ip_opt_obj;
803 
804 ulong_t ip_squeue_enter_unbound = 0;
805 
806 /*
807  * Named Dispatch Parameter Table.
808  * All of these are alterable, within the min/max values given, at run time.
809  */
810 static ipparam_t	lcl_param_arr[] = {
811 	/* min	max	value	name */
812 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
813 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
814 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
815 	{  0,	1,	0,	"ip_respond_to_timestamp"},
816 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
817 	{  0,	1,	1,	"ip_send_redirects"},
818 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
819 	{  0,	10,	0,	"ip_debug"},
820 	{  0,	10,	0,	"ip_mrtdebug"},
821 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
822 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
823 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
824 	{  1,	255,	255,	"ip_def_ttl" },
825 	{  0,	1,	0,	"ip_forward_src_routed"},
826 	{  0,	256,	32,	"ip_wroff_extra" },
827 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
828 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
829 	{  0,	1,	1,	"ip_path_mtu_discovery" },
830 	{  0,	240,	30,	"ip_ignore_delete_time" },
831 	{  0,	1,	0,	"ip_ignore_redirect" },
832 	{  0,	1,	1,	"ip_output_queue" },
833 	{  1,	254,	1,	"ip_broadcast_ttl" },
834 	{  0,	99999,	100,	"ip_icmp_err_interval" },
835 	{  1,	99999,	10,	"ip_icmp_err_burst" },
836 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
837 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
838 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
839 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
840 	{  0,	1,	1,	"icmp_accept_clear_messages" },
841 	{  0,	1,	1,	"igmp_accept_clear_messages" },
842 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
843 				"ip_ndp_delay_first_probe_time"},
844 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
845 				"ip_ndp_max_unicast_solicit"},
846 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
847 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
848 	{  0,	1,	0,	"ip6_forward_src_routed"},
849 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
850 	{  0,	1,	1,	"ip6_send_redirects"},
851 	{  0,	1,	0,	"ip6_ignore_redirect" },
852 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
853 
854 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
855 
856 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
857 
858 	{  0,	1,	1,	"pim_accept_clear_messages" },
859 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
860 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
861 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
862 	{  0,	15,	0,	"ip_policy_mask" },
863 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
864 	{  0,	255,	1,	"ip_multirt_ttl" },
865 	{  0,	1,	1,	"ip_multidata_outbound" },
866 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
867 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
868 	{  0,	1000,	1,	"ip_max_temp_defend" },
869 	{  0,	1000,	3,	"ip_max_defend" },
870 	{  0,	999999,	30,	"ip_defend_interval" },
871 	{  0,	3600000, 300000, "ip_dup_recovery" },
872 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
873 	{  0,	1,	1,	"ip_lso_outbound" },
874 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
875 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
876 #ifdef DEBUG
877 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
878 #else
879 	{  0,	0,	0,	"" },
880 #endif
881 };
882 
883 /*
884  * Extended NDP table
885  * The addresses for the first two are filled in to be ips_ip_g_forward
886  * and ips_ipv6_forward at init time.
887  */
888 static ipndp_t	lcl_ndp_arr[] = {
889 	/* getf			setf		data			name */
890 #define	IPNDP_IP_FORWARDING_OFFSET	0
891 	{  ip_param_generic_get,	ip_forward_set,	NULL,
892 	    "ip_forwarding" },
893 #define	IPNDP_IP6_FORWARDING_OFFSET	1
894 	{  ip_param_generic_get,	ip_forward_set,	NULL,
895 	    "ip6_forwarding" },
896 	{  ip_ill_report,	NULL,		NULL,
897 	    "ip_ill_status" },
898 	{  ip_ipif_report,	NULL,		NULL,
899 	    "ip_ipif_status" },
900 	{  ip_ire_report,	NULL,		NULL,
901 	    "ipv4_ire_status" },
902 	{  ip_ire_report_v6,	NULL,		NULL,
903 	    "ipv6_ire_status" },
904 	{  ip_conn_report,	NULL,		NULL,
905 	    "ip_conn_status" },
906 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
907 	    "ip_rput_pullups" },
908 	{  ndp_report,		NULL,		NULL,
909 	    "ip_ndp_cache_report" },
910 	{  ip_srcid_report,	NULL,		NULL,
911 	    "ip_srcid_status" },
912 	{ ip_param_generic_get, ip_squeue_profile_set,
913 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
914 	{ ip_param_generic_get, ip_squeue_bind_set,
915 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
916 	{ ip_param_generic_get, ip_input_proc_set,
917 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
918 	{ ip_param_generic_get, ip_int_set,
919 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
920 #define	IPNDP_CGTP_FILTER_OFFSET	14
921 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
922 	    "ip_cgtp_filter" },
923 	{ ip_param_generic_get, ip_int_set,
924 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
925 #define	IPNDP_IPMP_HOOK_OFFSET	16
926 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
927 	    "ipmp_hook_emulation" },
928 };
929 
930 /*
931  * Table of IP ioctls encoding the various properties of the ioctl and
932  * indexed based on the last byte of the ioctl command. Occasionally there
933  * is a clash, and there is more than 1 ioctl with the same last byte.
934  * In such a case 1 ioctl is encoded in the ndx table and the remaining
935  * ioctls are encoded in the misc table. An entry in the ndx table is
936  * retrieved by indexing on the last byte of the ioctl command and comparing
937  * the ioctl command with the value in the ndx table. In the event of a
938  * mismatch the misc table is then searched sequentially for the desired
939  * ioctl command.
940  *
941  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
942  */
943 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
944 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
945 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
946 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
947 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
948 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 
955 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
956 			MISC_CMD, ip_siocaddrt, NULL },
957 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
958 			MISC_CMD, ip_siocdelrt, NULL },
959 
960 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
961 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
962 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
963 			IF_CMD, ip_sioctl_get_addr, NULL },
964 
965 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
966 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
967 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
968 			IPI_GET_CMD | IPI_REPL,
969 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
970 
971 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
972 			IPI_PRIV | IPI_WR | IPI_REPL,
973 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
974 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
975 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
976 			IF_CMD, ip_sioctl_get_flags, NULL },
977 
978 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
979 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
980 
981 	/* copyin size cannot be coded for SIOCGIFCONF */
982 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
983 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
984 
985 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
986 			IF_CMD, ip_sioctl_mtu, NULL },
987 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
988 			IF_CMD, ip_sioctl_get_mtu, NULL },
989 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
990 			IPI_GET_CMD | IPI_REPL,
991 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
992 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
993 			IF_CMD, ip_sioctl_brdaddr, NULL },
994 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
995 			IPI_GET_CMD | IPI_REPL,
996 			IF_CMD, ip_sioctl_get_netmask, NULL },
997 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
998 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
999 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1000 			IPI_GET_CMD | IPI_REPL,
1001 			IF_CMD, ip_sioctl_get_metric, NULL },
1002 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1003 			IF_CMD, ip_sioctl_metric, NULL },
1004 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1005 
1006 	/* See 166-168 below for extended SIOC*XARP ioctls */
1007 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1008 			ARP_CMD, ip_sioctl_arp, NULL },
1009 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1010 			ARP_CMD, ip_sioctl_arp, NULL },
1011 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1012 			ARP_CMD, ip_sioctl_arp, NULL },
1013 
1014 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1015 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1017 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1037 			MISC_CMD, if_unitsel, if_unitsel_restart },
1038 
1039 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 
1058 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1059 			IPI_PRIV | IPI_WR | IPI_MODOK,
1060 			IF_CMD, ip_sioctl_sifname, NULL },
1061 
1062 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 
1076 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1077 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1078 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1079 			IF_CMD, ip_sioctl_get_muxid, NULL },
1080 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1081 			IPI_PRIV | IPI_WR | IPI_REPL,
1082 			IF_CMD, ip_sioctl_muxid, NULL },
1083 
1084 	/* Both if and lif variants share same func */
1085 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1086 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1087 	/* Both if and lif variants share same func */
1088 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1089 			IPI_PRIV | IPI_WR | IPI_REPL,
1090 			IF_CMD, ip_sioctl_slifindex, NULL },
1091 
1092 	/* copyin size cannot be coded for SIOCGIFCONF */
1093 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1094 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1095 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1114 			IPI_PRIV | IPI_WR | IPI_REPL,
1115 			LIF_CMD, ip_sioctl_removeif,
1116 			ip_sioctl_removeif_restart },
1117 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1118 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1119 			LIF_CMD, ip_sioctl_addif, NULL },
1120 #define	SIOCLIFADDR_NDX 112
1121 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1122 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1123 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1124 			IPI_GET_CMD | IPI_REPL,
1125 			LIF_CMD, ip_sioctl_get_addr, NULL },
1126 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1127 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1128 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1129 			IPI_GET_CMD | IPI_REPL,
1130 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1131 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1132 			IPI_PRIV | IPI_WR | IPI_REPL,
1133 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1134 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1135 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_get_flags, NULL },
1137 
1138 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 
1141 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1142 			ip_sioctl_get_lifconf, NULL },
1143 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1144 			LIF_CMD, ip_sioctl_mtu, NULL },
1145 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1146 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1147 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1148 			IPI_GET_CMD | IPI_REPL,
1149 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1150 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1151 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1152 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1153 			IPI_GET_CMD | IPI_REPL,
1154 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1155 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1156 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1157 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1158 			IPI_GET_CMD | IPI_REPL,
1159 			LIF_CMD, ip_sioctl_get_metric, NULL },
1160 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1161 			LIF_CMD, ip_sioctl_metric, NULL },
1162 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1163 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1164 			LIF_CMD, ip_sioctl_slifname,
1165 			ip_sioctl_slifname_restart },
1166 
1167 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1168 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1169 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1170 			IPI_GET_CMD | IPI_REPL,
1171 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1172 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1173 			IPI_PRIV | IPI_WR | IPI_REPL,
1174 			LIF_CMD, ip_sioctl_muxid, NULL },
1175 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1176 			IPI_GET_CMD | IPI_REPL,
1177 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1178 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1179 			IPI_PRIV | IPI_WR | IPI_REPL,
1180 			LIF_CMD, ip_sioctl_slifindex, 0 },
1181 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1182 			LIF_CMD, ip_sioctl_token, NULL },
1183 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1184 			IPI_GET_CMD | IPI_REPL,
1185 			LIF_CMD, ip_sioctl_get_token, NULL },
1186 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1187 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1188 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1189 			IPI_GET_CMD | IPI_REPL,
1190 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1191 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1192 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1193 
1194 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1195 			IPI_GET_CMD | IPI_REPL,
1196 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1197 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1198 			LIF_CMD, ip_siocdelndp_v6, NULL },
1199 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1200 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1201 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1202 			LIF_CMD, ip_siocsetndp_v6, NULL },
1203 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1204 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1205 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1206 			MISC_CMD, ip_sioctl_tonlink, NULL },
1207 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1208 			MISC_CMD, ip_sioctl_tmysite, NULL },
1209 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1210 			TUN_CMD, ip_sioctl_tunparam, NULL },
1211 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1212 			IPI_PRIV | IPI_WR,
1213 			TUN_CMD, ip_sioctl_tunparam, NULL },
1214 
1215 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1216 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1217 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1218 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1219 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1220 
1221 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1222 			IPI_PRIV | IPI_WR | IPI_REPL,
1223 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1224 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1225 			IPI_PRIV | IPI_WR | IPI_REPL,
1226 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1227 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1228 			IPI_PRIV | IPI_WR,
1229 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1230 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1231 			IPI_GET_CMD | IPI_REPL,
1232 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1233 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1234 			IPI_GET_CMD | IPI_REPL,
1235 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1236 
1237 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1238 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1239 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1240 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1241 
1242 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1243 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1244 
1245 	/* These are handled in ip_sioctl_copyin_setup itself */
1246 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1247 			MISC_CMD, NULL, NULL },
1248 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1249 			MISC_CMD, NULL, NULL },
1250 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1251 
1252 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1253 			ip_sioctl_get_lifconf, NULL },
1254 
1255 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1256 			XARP_CMD, ip_sioctl_arp, NULL },
1257 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1258 			XARP_CMD, ip_sioctl_arp, NULL },
1259 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1260 			XARP_CMD, ip_sioctl_arp, NULL },
1261 
1262 	/* SIOCPOPSOCKFS is not handled by IP */
1263 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1264 
1265 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1266 			IPI_GET_CMD | IPI_REPL,
1267 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1268 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1269 			IPI_PRIV | IPI_WR | IPI_REPL,
1270 			LIF_CMD, ip_sioctl_slifzone,
1271 			ip_sioctl_slifzone_restart },
1272 	/* 172-174 are SCTP ioctls and not handled by IP */
1273 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1274 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1275 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1276 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1277 			IPI_GET_CMD, LIF_CMD,
1278 			ip_sioctl_get_lifusesrc, 0 },
1279 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1280 			IPI_PRIV | IPI_WR,
1281 			LIF_CMD, ip_sioctl_slifusesrc,
1282 			NULL },
1283 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1284 			ip_sioctl_get_lifsrcof, NULL },
1285 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1286 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1287 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1288 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1289 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1290 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1291 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1292 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1293 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1294 			ip_sioctl_set_ipmpfailback, NULL }
1295 };
1296 
1297 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1298 
1299 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1300 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1301 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1302 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1303 		TUN_CMD, ip_sioctl_tunparam, NULL },
1304 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1305 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1306 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1307 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1308 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1309 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1310 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1311 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1312 		MISC_CMD, mrt_ioctl},
1313 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1314 		MISC_CMD, mrt_ioctl},
1315 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1316 		MISC_CMD, mrt_ioctl}
1317 };
1318 
1319 int ip_misc_ioctl_count =
1320     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1321 
1322 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1323 					/* Settable in /etc/system */
1324 /* Defined in ip_ire.c */
1325 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1326 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1327 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1328 
1329 static nv_t	ire_nv_arr[] = {
1330 	{ IRE_BROADCAST, "BROADCAST" },
1331 	{ IRE_LOCAL, "LOCAL" },
1332 	{ IRE_LOOPBACK, "LOOPBACK" },
1333 	{ IRE_CACHE, "CACHE" },
1334 	{ IRE_DEFAULT, "DEFAULT" },
1335 	{ IRE_PREFIX, "PREFIX" },
1336 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1337 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1338 	{ IRE_HOST, "HOST" },
1339 	{ 0 }
1340 };
1341 
1342 nv_t	*ire_nv_tbl = ire_nv_arr;
1343 
1344 /* Defined in ip_netinfo.c */
1345 extern ddi_taskq_t	*eventq_queue_nic;
1346 
1347 /* Simple ICMP IP Header Template */
1348 static ipha_t icmp_ipha = {
1349 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1350 };
1351 
1352 struct module_info ip_mod_info = {
1353 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1354 };
1355 
1356 /*
1357  * Duplicate static symbols within a module confuses mdb; so we avoid the
1358  * problem by making the symbols here distinct from those in udp.c.
1359  */
1360 
1361 static struct qinit iprinit = {
1362 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1363 	&ip_mod_info
1364 };
1365 
1366 static struct qinit ipwinit = {
1367 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1368 	&ip_mod_info
1369 };
1370 
1371 static struct qinit iplrinit = {
1372 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1373 	&ip_mod_info
1374 };
1375 
1376 static struct qinit iplwinit = {
1377 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1378 	&ip_mod_info
1379 };
1380 
1381 struct streamtab ipinfo = {
1382 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1383 };
1384 
1385 #ifdef	DEBUG
1386 static boolean_t skip_sctp_cksum = B_FALSE;
1387 #endif
1388 
1389 /*
1390  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1391  * ip_rput_v6(), ip_output(), etc.  If the message
1392  * block already has a M_CTL at the front of it, then simply set the zoneid
1393  * appropriately.
1394  */
1395 mblk_t *
1396 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1397 {
1398 	mblk_t		*first_mp;
1399 	ipsec_out_t	*io;
1400 
1401 	ASSERT(zoneid != ALL_ZONES);
1402 	if (mp->b_datap->db_type == M_CTL) {
1403 		io = (ipsec_out_t *)mp->b_rptr;
1404 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1405 		io->ipsec_out_zoneid = zoneid;
1406 		return (mp);
1407 	}
1408 
1409 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1410 	if (first_mp == NULL)
1411 		return (NULL);
1412 	io = (ipsec_out_t *)first_mp->b_rptr;
1413 	/* This is not a secure packet */
1414 	io->ipsec_out_secure = B_FALSE;
1415 	io->ipsec_out_zoneid = zoneid;
1416 	first_mp->b_cont = mp;
1417 	return (first_mp);
1418 }
1419 
1420 /*
1421  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1422  */
1423 mblk_t *
1424 ip_copymsg(mblk_t *mp)
1425 {
1426 	mblk_t *nmp;
1427 	ipsec_info_t *in;
1428 
1429 	if (mp->b_datap->db_type != M_CTL)
1430 		return (copymsg(mp));
1431 
1432 	in = (ipsec_info_t *)mp->b_rptr;
1433 
1434 	/*
1435 	 * Note that M_CTL is also used for delivering ICMP error messages
1436 	 * upstream to transport layers.
1437 	 */
1438 	if (in->ipsec_info_type != IPSEC_OUT &&
1439 	    in->ipsec_info_type != IPSEC_IN)
1440 		return (copymsg(mp));
1441 
1442 	nmp = copymsg(mp->b_cont);
1443 
1444 	if (in->ipsec_info_type == IPSEC_OUT) {
1445 		return (ipsec_out_tag(mp, nmp,
1446 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1447 	} else {
1448 		return (ipsec_in_tag(mp, nmp,
1449 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1450 	}
1451 }
1452 
1453 /* Generate an ICMP fragmentation needed message. */
1454 static void
1455 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1456     ip_stack_t *ipst)
1457 {
1458 	icmph_t	icmph;
1459 	mblk_t *first_mp;
1460 	boolean_t mctl_present;
1461 
1462 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1463 
1464 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1465 		if (mctl_present)
1466 			freeb(first_mp);
1467 		return;
1468 	}
1469 
1470 	bzero(&icmph, sizeof (icmph_t));
1471 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1472 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1473 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1474 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1475 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1476 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1477 	    ipst);
1478 }
1479 
1480 /*
1481  * icmp_inbound deals with ICMP messages in the following ways.
1482  *
1483  * 1) It needs to send a reply back and possibly delivering it
1484  *    to the "interested" upper clients.
1485  * 2) It needs to send it to the upper clients only.
1486  * 3) It needs to change some values in IP only.
1487  * 4) It needs to change some values in IP and upper layers e.g TCP.
1488  *
1489  * We need to accomodate icmp messages coming in clear until we get
1490  * everything secure from the wire. If icmp_accept_clear_messages
1491  * is zero we check with the global policy and act accordingly. If
1492  * it is non-zero, we accept the message without any checks. But
1493  * *this does not mean* that this will be delivered to the upper
1494  * clients. By accepting we might send replies back, change our MTU
1495  * value etc. but delivery to the ULP/clients depends on their policy
1496  * dispositions.
1497  *
1498  * We handle the above 4 cases in the context of IPsec in the
1499  * following way :
1500  *
1501  * 1) Send the reply back in the same way as the request came in.
1502  *    If it came in encrypted, it goes out encrypted. If it came in
1503  *    clear, it goes out in clear. Thus, this will prevent chosen
1504  *    plain text attack.
1505  * 2) The client may or may not expect things to come in secure.
1506  *    If it comes in secure, the policy constraints are checked
1507  *    before delivering it to the upper layers. If it comes in
1508  *    clear, ipsec_inbound_accept_clear will decide whether to
1509  *    accept this in clear or not. In both the cases, if the returned
1510  *    message (IP header + 8 bytes) that caused the icmp message has
1511  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1512  *    sending up. If there are only 8 bytes of returned message, then
1513  *    upper client will not be notified.
1514  * 3) Check with global policy to see whether it matches the constaints.
1515  *    But this will be done only if icmp_accept_messages_in_clear is
1516  *    zero.
1517  * 4) If we need to change both in IP and ULP, then the decision taken
1518  *    while affecting the values in IP and while delivering up to TCP
1519  *    should be the same.
1520  *
1521  * 	There are two cases.
1522  *
1523  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1524  *	   failed), we will not deliver it to the ULP, even though they
1525  *	   are *willing* to accept in *clear*. This is fine as our global
1526  *	   disposition to icmp messages asks us reject the datagram.
1527  *
1528  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1529  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1530  *	   to deliver it to ULP (policy failed), it can lead to
1531  *	   consistency problems. The cases known at this time are
1532  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1533  *	   values :
1534  *
1535  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1536  *	     and Upper layer rejects. Then the communication will
1537  *	     come to a stop. This is solved by making similar decisions
1538  *	     at both levels. Currently, when we are unable to deliver
1539  *	     to the Upper Layer (due to policy failures) while IP has
1540  *	     adjusted ire_max_frag, the next outbound datagram would
1541  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1542  *	     will be with the right level of protection. Thus the right
1543  *	     value will be communicated even if we are not able to
1544  *	     communicate when we get from the wire initially. But this
1545  *	     assumes there would be at least one outbound datagram after
1546  *	     IP has adjusted its ire_max_frag value. To make things
1547  *	     simpler, we accept in clear after the validation of
1548  *	     AH/ESP headers.
1549  *
1550  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1551  *	     upper layer depending on the level of protection the upper
1552  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1553  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1554  *	     should be accepted in clear when the Upper layer expects secure.
1555  *	     Thus the communication may get aborted by some bad ICMP
1556  *	     packets.
1557  *
1558  * IPQoS Notes:
1559  * The only instance when a packet is sent for processing is when there
1560  * isn't an ICMP client and if we are interested in it.
1561  * If there is a client, IPPF processing will take place in the
1562  * ip_fanout_proto routine.
1563  *
1564  * Zones notes:
1565  * The packet is only processed in the context of the specified zone: typically
1566  * only this zone will reply to an echo request, and only interested clients in
1567  * this zone will receive a copy of the packet. This means that the caller must
1568  * call icmp_inbound() for each relevant zone.
1569  */
1570 static void
1571 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1572     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1573     ill_t *recv_ill, zoneid_t zoneid)
1574 {
1575 	icmph_t	*icmph;
1576 	ipha_t	*ipha;
1577 	int	iph_hdr_length;
1578 	int	hdr_length;
1579 	boolean_t	interested;
1580 	uint32_t	ts;
1581 	uchar_t	*wptr;
1582 	ipif_t	*ipif;
1583 	mblk_t *first_mp;
1584 	ipsec_in_t *ii;
1585 	ire_t *src_ire;
1586 	boolean_t onlink;
1587 	timestruc_t now;
1588 	uint32_t ill_index;
1589 	ip_stack_t *ipst;
1590 
1591 	ASSERT(ill != NULL);
1592 	ipst = ill->ill_ipst;
1593 
1594 	first_mp = mp;
1595 	if (mctl_present) {
1596 		mp = first_mp->b_cont;
1597 		ASSERT(mp != NULL);
1598 	}
1599 
1600 	ipha = (ipha_t *)mp->b_rptr;
1601 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1602 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1603 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1604 		if (first_mp == NULL)
1605 			return;
1606 	}
1607 
1608 	/*
1609 	 * On a labeled system, we have to check whether the zone itself is
1610 	 * permitted to receive raw traffic.
1611 	 */
1612 	if (is_system_labeled()) {
1613 		if (zoneid == ALL_ZONES)
1614 			zoneid = tsol_packet_to_zoneid(mp);
1615 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1616 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1617 			    zoneid));
1618 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1619 			freemsg(first_mp);
1620 			return;
1621 		}
1622 	}
1623 
1624 	/*
1625 	 * We have accepted the ICMP message. It means that we will
1626 	 * respond to the packet if needed. It may not be delivered
1627 	 * to the upper client depending on the policy constraints
1628 	 * and the disposition in ipsec_inbound_accept_clear.
1629 	 */
1630 
1631 	ASSERT(ill != NULL);
1632 
1633 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1634 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1635 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1636 		/* Last chance to get real. */
1637 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1638 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1639 			freemsg(first_mp);
1640 			return;
1641 		}
1642 		/* Refresh iph following the pullup. */
1643 		ipha = (ipha_t *)mp->b_rptr;
1644 	}
1645 	/* ICMP header checksum, including checksum field, should be zero. */
1646 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1647 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1648 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1649 		freemsg(first_mp);
1650 		return;
1651 	}
1652 	/* The IP header will always be a multiple of four bytes */
1653 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1654 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1655 	    icmph->icmph_code));
1656 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1657 	/* We will set "interested" to "true" if we want a copy */
1658 	interested = B_FALSE;
1659 	switch (icmph->icmph_type) {
1660 	case ICMP_ECHO_REPLY:
1661 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1662 		break;
1663 	case ICMP_DEST_UNREACHABLE:
1664 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1665 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1666 		interested = B_TRUE;	/* Pass up to transport */
1667 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1668 		break;
1669 	case ICMP_SOURCE_QUENCH:
1670 		interested = B_TRUE;	/* Pass up to transport */
1671 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1672 		break;
1673 	case ICMP_REDIRECT:
1674 		if (!ipst->ips_ip_ignore_redirect)
1675 			interested = B_TRUE;
1676 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1677 		break;
1678 	case ICMP_ECHO_REQUEST:
1679 		/*
1680 		 * Whether to respond to echo requests that come in as IP
1681 		 * broadcasts or as IP multicast is subject to debate
1682 		 * (what isn't?).  We aim to please, you pick it.
1683 		 * Default is do it.
1684 		 */
1685 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1686 			/* unicast: always respond */
1687 			interested = B_TRUE;
1688 		} else if (CLASSD(ipha->ipha_dst)) {
1689 			/* multicast: respond based on tunable */
1690 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1691 		} else if (broadcast) {
1692 			/* broadcast: respond based on tunable */
1693 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1694 		}
1695 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1696 		break;
1697 	case ICMP_ROUTER_ADVERTISEMENT:
1698 	case ICMP_ROUTER_SOLICITATION:
1699 		break;
1700 	case ICMP_TIME_EXCEEDED:
1701 		interested = B_TRUE;	/* Pass up to transport */
1702 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1703 		break;
1704 	case ICMP_PARAM_PROBLEM:
1705 		interested = B_TRUE;	/* Pass up to transport */
1706 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1707 		break;
1708 	case ICMP_TIME_STAMP_REQUEST:
1709 		/* Response to Time Stamp Requests is local policy. */
1710 		if (ipst->ips_ip_g_resp_to_timestamp &&
1711 		    /* So is whether to respond if it was an IP broadcast. */
1712 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1713 			int tstamp_len = 3 * sizeof (uint32_t);
1714 
1715 			if (wptr +  tstamp_len > mp->b_wptr) {
1716 				if (!pullupmsg(mp, wptr + tstamp_len -
1717 				    mp->b_rptr)) {
1718 					BUMP_MIB(ill->ill_ip_mib,
1719 					    ipIfStatsInDiscards);
1720 					freemsg(first_mp);
1721 					return;
1722 				}
1723 				/* Refresh ipha following the pullup. */
1724 				ipha = (ipha_t *)mp->b_rptr;
1725 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1726 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1727 			}
1728 			interested = B_TRUE;
1729 		}
1730 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1731 		break;
1732 	case ICMP_TIME_STAMP_REPLY:
1733 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1734 		break;
1735 	case ICMP_INFO_REQUEST:
1736 		/* Per RFC 1122 3.2.2.7, ignore this. */
1737 	case ICMP_INFO_REPLY:
1738 		break;
1739 	case ICMP_ADDRESS_MASK_REQUEST:
1740 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1741 		    !broadcast) &&
1742 		    /* TODO m_pullup of complete header? */
1743 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1744 			interested = B_TRUE;
1745 		}
1746 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1747 		break;
1748 	case ICMP_ADDRESS_MASK_REPLY:
1749 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1750 		break;
1751 	default:
1752 		interested = B_TRUE;	/* Pass up to transport */
1753 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1754 		break;
1755 	}
1756 	/* See if there is an ICMP client. */
1757 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1758 		/* If there is an ICMP client and we want one too, copy it. */
1759 		mblk_t *first_mp1;
1760 
1761 		if (!interested) {
1762 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1763 			    ip_policy, recv_ill, zoneid);
1764 			return;
1765 		}
1766 		first_mp1 = ip_copymsg(first_mp);
1767 		if (first_mp1 != NULL) {
1768 			ip_fanout_proto(q, first_mp1, ill, ipha,
1769 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1770 		}
1771 	} else if (!interested) {
1772 		freemsg(first_mp);
1773 		return;
1774 	} else {
1775 		/*
1776 		 * Initiate policy processing for this packet if ip_policy
1777 		 * is true.
1778 		 */
1779 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1780 			ill_index = ill->ill_phyint->phyint_ifindex;
1781 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1782 			if (mp == NULL) {
1783 				if (mctl_present) {
1784 					freeb(first_mp);
1785 				}
1786 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1787 				return;
1788 			}
1789 		}
1790 	}
1791 	/* We want to do something with it. */
1792 	/* Check db_ref to make sure we can modify the packet. */
1793 	if (mp->b_datap->db_ref > 1) {
1794 		mblk_t	*first_mp1;
1795 
1796 		first_mp1 = ip_copymsg(first_mp);
1797 		freemsg(first_mp);
1798 		if (!first_mp1) {
1799 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1800 			return;
1801 		}
1802 		first_mp = first_mp1;
1803 		if (mctl_present) {
1804 			mp = first_mp->b_cont;
1805 			ASSERT(mp != NULL);
1806 		} else {
1807 			mp = first_mp;
1808 		}
1809 		ipha = (ipha_t *)mp->b_rptr;
1810 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1811 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1812 	}
1813 	switch (icmph->icmph_type) {
1814 	case ICMP_ADDRESS_MASK_REQUEST:
1815 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1816 		if (ipif == NULL) {
1817 			freemsg(first_mp);
1818 			return;
1819 		}
1820 		/*
1821 		 * outging interface must be IPv4
1822 		 */
1823 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1824 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1825 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1826 		ipif_refrele(ipif);
1827 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1828 		break;
1829 	case ICMP_ECHO_REQUEST:
1830 		icmph->icmph_type = ICMP_ECHO_REPLY;
1831 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1832 		break;
1833 	case ICMP_TIME_STAMP_REQUEST: {
1834 		uint32_t *tsp;
1835 
1836 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1837 		tsp = (uint32_t *)wptr;
1838 		tsp++;		/* Skip past 'originate time' */
1839 		/* Compute # of milliseconds since midnight */
1840 		gethrestime(&now);
1841 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1842 		    now.tv_nsec / (NANOSEC / MILLISEC);
1843 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1844 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1845 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1846 		break;
1847 	}
1848 	default:
1849 		ipha = (ipha_t *)&icmph[1];
1850 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1851 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1852 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1853 				freemsg(first_mp);
1854 				return;
1855 			}
1856 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1857 			ipha = (ipha_t *)&icmph[1];
1858 		}
1859 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1860 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1861 			freemsg(first_mp);
1862 			return;
1863 		}
1864 		hdr_length = IPH_HDR_LENGTH(ipha);
1865 		if (hdr_length < sizeof (ipha_t)) {
1866 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1867 			freemsg(first_mp);
1868 			return;
1869 		}
1870 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1871 			if (!pullupmsg(mp,
1872 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1873 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1874 				freemsg(first_mp);
1875 				return;
1876 			}
1877 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1878 			ipha = (ipha_t *)&icmph[1];
1879 		}
1880 		switch (icmph->icmph_type) {
1881 		case ICMP_REDIRECT:
1882 			/*
1883 			 * As there is no upper client to deliver, we don't
1884 			 * need the first_mp any more.
1885 			 */
1886 			if (mctl_present) {
1887 				freeb(first_mp);
1888 			}
1889 			icmp_redirect(ill, mp);
1890 			return;
1891 		case ICMP_DEST_UNREACHABLE:
1892 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1893 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1894 				    zoneid, mp, iph_hdr_length, ipst)) {
1895 					freemsg(first_mp);
1896 					return;
1897 				}
1898 				/*
1899 				 * icmp_inbound_too_big() may alter mp.
1900 				 * Resynch ipha and icmph accordingly.
1901 				 */
1902 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1903 				ipha = (ipha_t *)&icmph[1];
1904 			}
1905 			/* FALLTHRU */
1906 		default :
1907 			/*
1908 			 * IPQoS notes: Since we have already done IPQoS
1909 			 * processing we don't want to do it again in
1910 			 * the fanout routines called by
1911 			 * icmp_inbound_error_fanout, hence the last
1912 			 * argument, ip_policy, is B_FALSE.
1913 			 */
1914 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1915 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1916 			    B_FALSE, recv_ill, zoneid);
1917 		}
1918 		return;
1919 	}
1920 	/* Send out an ICMP packet */
1921 	icmph->icmph_checksum = 0;
1922 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1923 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1924 		ipif_t	*ipif_chosen;
1925 		/*
1926 		 * Make it look like it was directed to us, so we don't look
1927 		 * like a fool with a broadcast or multicast source address.
1928 		 */
1929 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1930 		/*
1931 		 * Make sure that we haven't grabbed an interface that's DOWN.
1932 		 */
1933 		if (ipif != NULL) {
1934 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1935 			    ipha->ipha_src, zoneid);
1936 			if (ipif_chosen != NULL) {
1937 				ipif_refrele(ipif);
1938 				ipif = ipif_chosen;
1939 			}
1940 		}
1941 		if (ipif == NULL) {
1942 			ip0dbg(("icmp_inbound: "
1943 			    "No source for broadcast/multicast:\n"
1944 			    "\tsrc 0x%x dst 0x%x ill %p "
1945 			    "ipif_lcl_addr 0x%x\n",
1946 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1947 			    (void *)ill,
1948 			    ill->ill_ipif->ipif_lcl_addr));
1949 			freemsg(first_mp);
1950 			return;
1951 		}
1952 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1953 		ipha->ipha_dst = ipif->ipif_src_addr;
1954 		ipif_refrele(ipif);
1955 	}
1956 	/* Reset time to live. */
1957 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1958 	{
1959 		/* Swap source and destination addresses */
1960 		ipaddr_t tmp;
1961 
1962 		tmp = ipha->ipha_src;
1963 		ipha->ipha_src = ipha->ipha_dst;
1964 		ipha->ipha_dst = tmp;
1965 	}
1966 	ipha->ipha_ident = 0;
1967 	if (!IS_SIMPLE_IPH(ipha))
1968 		icmp_options_update(ipha);
1969 
1970 	/*
1971 	 * ICMP echo replies should go out on the same interface
1972 	 * the request came on as probes used by in.mpathd for detecting
1973 	 * NIC failures are ECHO packets. We turn-off load spreading
1974 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1975 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1976 	 * function. This is in turn handled by ip_wput and ip_newroute
1977 	 * to make sure that the packet goes out on the interface it came
1978 	 * in on. If we don't turnoff load spreading, the packets might get
1979 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1980 	 * to go out and in.mpathd would wrongly detect a failure or
1981 	 * mis-detect a NIC failure for link failure. As load spreading
1982 	 * can happen only if ill_group is not NULL, we do only for
1983 	 * that case and this does not affect the normal case.
1984 	 *
1985 	 * We turn off load spreading only on echo packets that came from
1986 	 * on-link hosts. If the interface route has been deleted, this will
1987 	 * not be enforced as we can't do much. For off-link hosts, as the
1988 	 * default routes in IPv4 does not typically have an ire_ipif
1989 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
1990 	 * Moreover, expecting a default route through this interface may
1991 	 * not be correct. We use ipha_dst because of the swap above.
1992 	 */
1993 	onlink = B_FALSE;
1994 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
1995 		/*
1996 		 * First, we need to make sure that it is not one of our
1997 		 * local addresses. If we set onlink when it is one of
1998 		 * our local addresses, we will end up creating IRE_CACHES
1999 		 * for one of our local addresses. Then, we will never
2000 		 * accept packets for them afterwards.
2001 		 */
2002 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2003 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2004 		if (src_ire == NULL) {
2005 			ipif = ipif_get_next_ipif(NULL, ill);
2006 			if (ipif == NULL) {
2007 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2008 				freemsg(mp);
2009 				return;
2010 			}
2011 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2012 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2013 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2014 			ipif_refrele(ipif);
2015 			if (src_ire != NULL) {
2016 				onlink = B_TRUE;
2017 				ire_refrele(src_ire);
2018 			}
2019 		} else {
2020 			ire_refrele(src_ire);
2021 		}
2022 	}
2023 	if (!mctl_present) {
2024 		/*
2025 		 * This packet should go out the same way as it
2026 		 * came in i.e in clear. To make sure that global
2027 		 * policy will not be applied to this in ip_wput_ire,
2028 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2029 		 */
2030 		ASSERT(first_mp == mp);
2031 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2032 		if (first_mp == NULL) {
2033 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2034 			freemsg(mp);
2035 			return;
2036 		}
2037 		ii = (ipsec_in_t *)first_mp->b_rptr;
2038 
2039 		/* This is not a secure packet */
2040 		ii->ipsec_in_secure = B_FALSE;
2041 		if (onlink) {
2042 			ii->ipsec_in_attach_if = B_TRUE;
2043 			ii->ipsec_in_ill_index =
2044 			    ill->ill_phyint->phyint_ifindex;
2045 			ii->ipsec_in_rill_index =
2046 			    recv_ill->ill_phyint->phyint_ifindex;
2047 		}
2048 		first_mp->b_cont = mp;
2049 	} else if (onlink) {
2050 		ii = (ipsec_in_t *)first_mp->b_rptr;
2051 		ii->ipsec_in_attach_if = B_TRUE;
2052 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2053 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2054 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2055 	} else {
2056 		ii = (ipsec_in_t *)first_mp->b_rptr;
2057 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2058 	}
2059 	ii->ipsec_in_zoneid = zoneid;
2060 	ASSERT(zoneid != ALL_ZONES);
2061 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2062 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2063 		return;
2064 	}
2065 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2066 	put(WR(q), first_mp);
2067 }
2068 
2069 static ipaddr_t
2070 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2071 {
2072 	conn_t *connp;
2073 	connf_t *connfp;
2074 	ipaddr_t nexthop_addr = INADDR_ANY;
2075 	int hdr_length = IPH_HDR_LENGTH(ipha);
2076 	uint16_t *up;
2077 	uint32_t ports;
2078 	ip_stack_t *ipst = ill->ill_ipst;
2079 
2080 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2081 	switch (ipha->ipha_protocol) {
2082 		case IPPROTO_TCP:
2083 		{
2084 			tcph_t *tcph;
2085 
2086 			/* do a reverse lookup */
2087 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2088 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2089 			    TCPS_LISTEN, ipst);
2090 			break;
2091 		}
2092 		case IPPROTO_UDP:
2093 		{
2094 			uint32_t dstport, srcport;
2095 
2096 			((uint16_t *)&ports)[0] = up[1];
2097 			((uint16_t *)&ports)[1] = up[0];
2098 
2099 			/* Extract ports in net byte order */
2100 			dstport = htons(ntohl(ports) & 0xFFFF);
2101 			srcport = htons(ntohl(ports) >> 16);
2102 
2103 			connfp = &ipst->ips_ipcl_udp_fanout[
2104 			    IPCL_UDP_HASH(dstport, ipst)];
2105 			mutex_enter(&connfp->connf_lock);
2106 			connp = connfp->connf_head;
2107 
2108 			/* do a reverse lookup */
2109 			while ((connp != NULL) &&
2110 			    (!IPCL_UDP_MATCH(connp, dstport,
2111 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2112 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2113 				connp = connp->conn_next;
2114 			}
2115 			if (connp != NULL)
2116 				CONN_INC_REF(connp);
2117 			mutex_exit(&connfp->connf_lock);
2118 			break;
2119 		}
2120 		case IPPROTO_SCTP:
2121 		{
2122 			in6_addr_t map_src, map_dst;
2123 
2124 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2125 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2126 			((uint16_t *)&ports)[0] = up[1];
2127 			((uint16_t *)&ports)[1] = up[0];
2128 
2129 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2130 			    zoneid, ipst->ips_netstack->netstack_sctp);
2131 			if (connp == NULL) {
2132 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2133 				    zoneid, ports, ipha, ipst);
2134 			} else {
2135 				CONN_INC_REF(connp);
2136 				SCTP_REFRELE(CONN2SCTP(connp));
2137 			}
2138 			break;
2139 		}
2140 		default:
2141 		{
2142 			ipha_t ripha;
2143 
2144 			ripha.ipha_src = ipha->ipha_dst;
2145 			ripha.ipha_dst = ipha->ipha_src;
2146 			ripha.ipha_protocol = ipha->ipha_protocol;
2147 
2148 			connfp = &ipst->ips_ipcl_proto_fanout[
2149 			    ipha->ipha_protocol];
2150 			mutex_enter(&connfp->connf_lock);
2151 			connp = connfp->connf_head;
2152 			for (connp = connfp->connf_head; connp != NULL;
2153 			    connp = connp->conn_next) {
2154 				if (IPCL_PROTO_MATCH(connp,
2155 				    ipha->ipha_protocol, &ripha, ill,
2156 				    0, zoneid)) {
2157 					CONN_INC_REF(connp);
2158 					break;
2159 				}
2160 			}
2161 			mutex_exit(&connfp->connf_lock);
2162 		}
2163 	}
2164 	if (connp != NULL) {
2165 		if (connp->conn_nexthop_set)
2166 			nexthop_addr = connp->conn_nexthop_v4;
2167 		CONN_DEC_REF(connp);
2168 	}
2169 	return (nexthop_addr);
2170 }
2171 
2172 /* Table from RFC 1191 */
2173 static int icmp_frag_size_table[] =
2174 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2175 
2176 /*
2177  * Process received ICMP Packet too big.
2178  * After updating any IRE it does the fanout to any matching transport streams.
2179  * Assumes the message has been pulled up till the IP header that caused
2180  * the error.
2181  *
2182  * Returns B_FALSE on failure and B_TRUE on success.
2183  */
2184 static boolean_t
2185 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2186     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2187     ip_stack_t *ipst)
2188 {
2189 	ire_t	*ire, *first_ire;
2190 	int	mtu;
2191 	int	hdr_length;
2192 	ipaddr_t nexthop_addr;
2193 
2194 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2195 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2196 	ASSERT(ill != NULL);
2197 
2198 	hdr_length = IPH_HDR_LENGTH(ipha);
2199 
2200 	/* Drop if the original packet contained a source route */
2201 	if (ip_source_route_included(ipha)) {
2202 		return (B_FALSE);
2203 	}
2204 	/*
2205 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2206 	 * header.
2207 	 */
2208 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2209 	    mp->b_wptr) {
2210 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2211 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2212 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2213 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2214 			return (B_FALSE);
2215 		}
2216 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2217 		ipha = (ipha_t *)&icmph[1];
2218 	}
2219 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2220 	if (nexthop_addr != INADDR_ANY) {
2221 		/* nexthop set */
2222 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2223 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2224 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2225 	} else {
2226 		/* nexthop not set */
2227 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2228 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2229 	}
2230 
2231 	if (!first_ire) {
2232 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2233 		    ntohl(ipha->ipha_dst)));
2234 		return (B_FALSE);
2235 	}
2236 	/* Check for MTU discovery advice as described in RFC 1191 */
2237 	mtu = ntohs(icmph->icmph_du_mtu);
2238 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2239 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2240 	    ire = ire->ire_next) {
2241 		/*
2242 		 * Look for the connection to which this ICMP message is
2243 		 * directed. If it has the IP_NEXTHOP option set, then the
2244 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2245 		 * option. Else the search is limited to regular IREs.
2246 		 */
2247 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2248 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2249 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2250 		    (nexthop_addr != INADDR_ANY)))
2251 			continue;
2252 
2253 		mutex_enter(&ire->ire_lock);
2254 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2255 			/* Reduce the IRE max frag value as advised. */
2256 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2257 			    mtu, ire->ire_max_frag));
2258 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2259 		} else {
2260 			uint32_t length;
2261 			int	i;
2262 
2263 			/*
2264 			 * Use the table from RFC 1191 to figure out
2265 			 * the next "plateau" based on the length in
2266 			 * the original IP packet.
2267 			 */
2268 			length = ntohs(ipha->ipha_length);
2269 			if (ire->ire_max_frag <= length &&
2270 			    ire->ire_max_frag >= length - hdr_length) {
2271 				/*
2272 				 * Handle broken BSD 4.2 systems that
2273 				 * return the wrong iph_length in ICMP
2274 				 * errors.
2275 				 */
2276 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2277 				    length, ire->ire_max_frag));
2278 				length -= hdr_length;
2279 			}
2280 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2281 				if (length > icmp_frag_size_table[i])
2282 					break;
2283 			}
2284 			if (i == A_CNT(icmp_frag_size_table)) {
2285 				/* Smaller than 68! */
2286 				ip1dbg(("Too big for packet size %d\n",
2287 				    length));
2288 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2289 				ire->ire_frag_flag = 0;
2290 			} else {
2291 				mtu = icmp_frag_size_table[i];
2292 				ip1dbg(("Calculated mtu %d, packet size %d, "
2293 				    "before %d", mtu, length,
2294 				    ire->ire_max_frag));
2295 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2296 				ip1dbg((", after %d\n", ire->ire_max_frag));
2297 			}
2298 			/* Record the new max frag size for the ULP. */
2299 			icmph->icmph_du_zero = 0;
2300 			icmph->icmph_du_mtu =
2301 			    htons((uint16_t)ire->ire_max_frag);
2302 		}
2303 		mutex_exit(&ire->ire_lock);
2304 	}
2305 	rw_exit(&first_ire->ire_bucket->irb_lock);
2306 	ire_refrele(first_ire);
2307 	return (B_TRUE);
2308 }
2309 
2310 /*
2311  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2312  * calls this function.
2313  */
2314 static mblk_t *
2315 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2316 {
2317 	ipha_t *ipha;
2318 	icmph_t *icmph;
2319 	ipha_t *in_ipha;
2320 	int length;
2321 
2322 	ASSERT(mp->b_datap->db_type == M_DATA);
2323 
2324 	/*
2325 	 * For Self-encapsulated packets, we added an extra IP header
2326 	 * without the options. Inner IP header is the one from which
2327 	 * the outer IP header was formed. Thus, we need to remove the
2328 	 * outer IP header. To do this, we pullup the whole message
2329 	 * and overlay whatever follows the outer IP header over the
2330 	 * outer IP header.
2331 	 */
2332 
2333 	if (!pullupmsg(mp, -1))
2334 		return (NULL);
2335 
2336 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2337 	ipha = (ipha_t *)&icmph[1];
2338 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2339 
2340 	/*
2341 	 * The length that we want to overlay is following the inner
2342 	 * IP header. Subtracting the IP header + icmp header + outer
2343 	 * IP header's length should give us the length that we want to
2344 	 * overlay.
2345 	 */
2346 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2347 	    hdr_length;
2348 	/*
2349 	 * Overlay whatever follows the inner header over the
2350 	 * outer header.
2351 	 */
2352 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2353 
2354 	/* Set the wptr to account for the outer header */
2355 	mp->b_wptr -= hdr_length;
2356 	return (mp);
2357 }
2358 
2359 /*
2360  * Try to pass the ICMP message upstream in case the ULP cares.
2361  *
2362  * If the packet that caused the ICMP error is secure, we send
2363  * it to AH/ESP to make sure that the attached packet has a
2364  * valid association. ipha in the code below points to the
2365  * IP header of the packet that caused the error.
2366  *
2367  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2368  * in the context of IPsec. Normally we tell the upper layer
2369  * whenever we send the ire (including ip_bind), the IPsec header
2370  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2371  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2372  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2373  * same thing. As TCP has the IPsec options size that needs to be
2374  * adjusted, we just pass the MTU unchanged.
2375  *
2376  * IFN could have been generated locally or by some router.
2377  *
2378  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2379  *	    This happens because IP adjusted its value of MTU on an
2380  *	    earlier IFN message and could not tell the upper layer,
2381  *	    the new adjusted value of MTU e.g. Packet was encrypted
2382  *	    or there was not enough information to fanout to upper
2383  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2384  *	    generates the IFN, where IPsec processing has *not* been
2385  *	    done.
2386  *
2387  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2388  *	    could have generated this. This happens because ire_max_frag
2389  *	    value in IP was set to a new value, while the IPsec processing
2390  *	    was being done and after we made the fragmentation check in
2391  *	    ip_wput_ire. Thus on return from IPsec processing,
2392  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2393  *	    and generates the IFN. As IPsec processing is over, we fanout
2394  *	    to AH/ESP to remove the header.
2395  *
2396  *	    In both these cases, ipsec_in_loopback will be set indicating
2397  *	    that IFN was generated locally.
2398  *
2399  * ROUTER : IFN could be secure or non-secure.
2400  *
2401  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2402  *	      packet in error has AH/ESP headers to validate the AH/ESP
2403  *	      headers. AH/ESP will verify whether there is a valid SA or
2404  *	      not and send it back. We will fanout again if we have more
2405  *	      data in the packet.
2406  *
2407  *	      If the packet in error does not have AH/ESP, we handle it
2408  *	      like any other case.
2409  *
2410  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2411  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2412  *	      for validation. AH/ESP will verify whether there is a
2413  *	      valid SA or not and send it back. We will fanout again if
2414  *	      we have more 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 static void
2420 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2421     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2422     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2423     zoneid_t zoneid)
2424 {
2425 	uint16_t *up;	/* Pointer to ports in ULP header */
2426 	uint32_t ports;	/* reversed ports for fanout */
2427 	ipha_t ripha;	/* With reversed addresses */
2428 	mblk_t *first_mp;
2429 	ipsec_in_t *ii;
2430 	tcph_t	*tcph;
2431 	conn_t	*connp;
2432 	ip_stack_t *ipst;
2433 
2434 	ASSERT(ill != NULL);
2435 
2436 	ASSERT(recv_ill != NULL);
2437 	ipst = recv_ill->ill_ipst;
2438 
2439 	first_mp = mp;
2440 	if (mctl_present) {
2441 		mp = first_mp->b_cont;
2442 		ASSERT(mp != NULL);
2443 
2444 		ii = (ipsec_in_t *)first_mp->b_rptr;
2445 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2446 	} else {
2447 		ii = NULL;
2448 	}
2449 
2450 	switch (ipha->ipha_protocol) {
2451 	case IPPROTO_UDP:
2452 		/*
2453 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2454 		 * transport header.
2455 		 */
2456 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2457 		    mp->b_wptr) {
2458 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2459 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2460 				goto discard_pkt;
2461 			}
2462 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2463 			ipha = (ipha_t *)&icmph[1];
2464 		}
2465 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2466 
2467 		/*
2468 		 * Attempt to find a client stream based on port.
2469 		 * Note that we do a reverse lookup since the header is
2470 		 * in the form we sent it out.
2471 		 * The ripha header is only used for the IP_UDP_MATCH and we
2472 		 * only set the src and dst addresses and protocol.
2473 		 */
2474 		ripha.ipha_src = ipha->ipha_dst;
2475 		ripha.ipha_dst = ipha->ipha_src;
2476 		ripha.ipha_protocol = ipha->ipha_protocol;
2477 		((uint16_t *)&ports)[0] = up[1];
2478 		((uint16_t *)&ports)[1] = up[0];
2479 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2480 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2481 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2482 		    icmph->icmph_type, icmph->icmph_code));
2483 
2484 		/* Have to change db_type after any pullupmsg */
2485 		DB_TYPE(mp) = M_CTL;
2486 
2487 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2488 		    mctl_present, ip_policy, recv_ill, zoneid);
2489 		return;
2490 
2491 	case IPPROTO_TCP:
2492 		/*
2493 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2494 		 * transport header.
2495 		 */
2496 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2497 		    mp->b_wptr) {
2498 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2499 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2500 				goto discard_pkt;
2501 			}
2502 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2503 			ipha = (ipha_t *)&icmph[1];
2504 		}
2505 		/*
2506 		 * Find a TCP client stream for this packet.
2507 		 * Note that we do a reverse lookup since the header is
2508 		 * in the form we sent it out.
2509 		 */
2510 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2511 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2512 		    ipst);
2513 		if (connp == NULL)
2514 			goto discard_pkt;
2515 
2516 		/* Have to change db_type after any pullupmsg */
2517 		DB_TYPE(mp) = M_CTL;
2518 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2519 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2520 		return;
2521 
2522 	case IPPROTO_SCTP:
2523 		/*
2524 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2525 		 * transport header.
2526 		 */
2527 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2528 		    mp->b_wptr) {
2529 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2530 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2531 				goto discard_pkt;
2532 			}
2533 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2534 			ipha = (ipha_t *)&icmph[1];
2535 		}
2536 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2537 		/*
2538 		 * Find a SCTP client stream for this packet.
2539 		 * Note that we do a reverse lookup since the header is
2540 		 * in the form we sent it out.
2541 		 * The ripha header is only used for the matching and we
2542 		 * only set the src and dst addresses, protocol, and version.
2543 		 */
2544 		ripha.ipha_src = ipha->ipha_dst;
2545 		ripha.ipha_dst = ipha->ipha_src;
2546 		ripha.ipha_protocol = ipha->ipha_protocol;
2547 		ripha.ipha_version_and_hdr_length =
2548 		    ipha->ipha_version_and_hdr_length;
2549 		((uint16_t *)&ports)[0] = up[1];
2550 		((uint16_t *)&ports)[1] = up[0];
2551 
2552 		/* Have to change db_type after any pullupmsg */
2553 		DB_TYPE(mp) = M_CTL;
2554 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2555 		    mctl_present, ip_policy, zoneid);
2556 		return;
2557 
2558 	case IPPROTO_ESP:
2559 	case IPPROTO_AH: {
2560 		int ipsec_rc;
2561 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2562 
2563 		/*
2564 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2565 		 * We will re-use the IPSEC_IN if it is already present as
2566 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2567 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2568 		 * one and attach it in the front.
2569 		 */
2570 		if (ii != NULL) {
2571 			/*
2572 			 * ip_fanout_proto_again converts the ICMP errors
2573 			 * that come back from AH/ESP to M_DATA so that
2574 			 * if it is non-AH/ESP and we do a pullupmsg in
2575 			 * this function, it would work. Convert it back
2576 			 * to M_CTL before we send up as this is a ICMP
2577 			 * error. This could have been generated locally or
2578 			 * by some router. Validate the inner IPsec
2579 			 * headers.
2580 			 *
2581 			 * NOTE : ill_index is used by ip_fanout_proto_again
2582 			 * to locate the ill.
2583 			 */
2584 			ASSERT(ill != NULL);
2585 			ii->ipsec_in_ill_index =
2586 			    ill->ill_phyint->phyint_ifindex;
2587 			ii->ipsec_in_rill_index =
2588 			    recv_ill->ill_phyint->phyint_ifindex;
2589 			DB_TYPE(first_mp->b_cont) = M_CTL;
2590 		} else {
2591 			/*
2592 			 * IPSEC_IN is not present. We attach a ipsec_in
2593 			 * message and send up to IPsec for validating
2594 			 * and removing the IPsec headers. Clear
2595 			 * ipsec_in_secure so that when we return
2596 			 * from IPsec, we don't mistakenly think that this
2597 			 * is a secure packet came from the network.
2598 			 *
2599 			 * NOTE : ill_index is used by ip_fanout_proto_again
2600 			 * to locate the ill.
2601 			 */
2602 			ASSERT(first_mp == mp);
2603 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2604 			if (first_mp == NULL) {
2605 				freemsg(mp);
2606 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2607 				return;
2608 			}
2609 			ii = (ipsec_in_t *)first_mp->b_rptr;
2610 
2611 			/* This is not a secure packet */
2612 			ii->ipsec_in_secure = B_FALSE;
2613 			first_mp->b_cont = mp;
2614 			DB_TYPE(mp) = M_CTL;
2615 			ASSERT(ill != NULL);
2616 			ii->ipsec_in_ill_index =
2617 			    ill->ill_phyint->phyint_ifindex;
2618 			ii->ipsec_in_rill_index =
2619 			    recv_ill->ill_phyint->phyint_ifindex;
2620 		}
2621 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2622 
2623 		if (!ipsec_loaded(ipss)) {
2624 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2625 			return;
2626 		}
2627 
2628 		if (ipha->ipha_protocol == IPPROTO_ESP)
2629 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2630 		else
2631 			ipsec_rc = ipsecah_icmp_error(first_mp);
2632 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2633 			return;
2634 
2635 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2636 		return;
2637 	}
2638 	default:
2639 		/*
2640 		 * The ripha header is only used for the lookup and we
2641 		 * only set the src and dst addresses and protocol.
2642 		 */
2643 		ripha.ipha_src = ipha->ipha_dst;
2644 		ripha.ipha_dst = ipha->ipha_src;
2645 		ripha.ipha_protocol = ipha->ipha_protocol;
2646 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2647 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2648 		    ntohl(ipha->ipha_dst),
2649 		    icmph->icmph_type, icmph->icmph_code));
2650 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2651 			ipha_t *in_ipha;
2652 
2653 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2654 			    mp->b_wptr) {
2655 				if (!pullupmsg(mp, (uchar_t *)ipha +
2656 				    hdr_length + sizeof (ipha_t) -
2657 				    mp->b_rptr)) {
2658 					goto discard_pkt;
2659 				}
2660 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2661 				ipha = (ipha_t *)&icmph[1];
2662 			}
2663 			/*
2664 			 * Caller has verified that length has to be
2665 			 * at least the size of IP header.
2666 			 */
2667 			ASSERT(hdr_length >= sizeof (ipha_t));
2668 			/*
2669 			 * Check the sanity of the inner IP header like
2670 			 * we did for the outer header.
2671 			 */
2672 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2673 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2674 				goto discard_pkt;
2675 			}
2676 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2677 				goto discard_pkt;
2678 			}
2679 			/* Check for Self-encapsulated tunnels */
2680 			if (in_ipha->ipha_src == ipha->ipha_src &&
2681 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2682 
2683 				mp = icmp_inbound_self_encap_error(mp,
2684 				    iph_hdr_length, hdr_length);
2685 				if (mp == NULL)
2686 					goto discard_pkt;
2687 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2688 				ipha = (ipha_t *)&icmph[1];
2689 				hdr_length = IPH_HDR_LENGTH(ipha);
2690 				/*
2691 				 * The packet in error is self-encapsualted.
2692 				 * And we are finding it further encapsulated
2693 				 * which we could not have possibly generated.
2694 				 */
2695 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2696 					goto discard_pkt;
2697 				}
2698 				icmp_inbound_error_fanout(q, ill, first_mp,
2699 				    icmph, ipha, iph_hdr_length, hdr_length,
2700 				    mctl_present, ip_policy, recv_ill, zoneid);
2701 				return;
2702 			}
2703 		}
2704 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2705 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2706 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2707 		    ii != NULL &&
2708 		    ii->ipsec_in_loopback &&
2709 		    ii->ipsec_in_secure) {
2710 			/*
2711 			 * For IP tunnels that get a looped-back
2712 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2713 			 * reported new MTU to take into account the IPsec
2714 			 * headers protecting this configured tunnel.
2715 			 *
2716 			 * This allows the tunnel module (tun.c) to blindly
2717 			 * accept the MTU reported in an ICMP "too big"
2718 			 * message.
2719 			 *
2720 			 * Non-looped back ICMP messages will just be
2721 			 * handled by the security protocols (if needed),
2722 			 * and the first subsequent packet will hit this
2723 			 * path.
2724 			 */
2725 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2726 			    ipsec_in_extra_length(first_mp));
2727 		}
2728 		/* Have to change db_type after any pullupmsg */
2729 		DB_TYPE(mp) = M_CTL;
2730 
2731 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2732 		    ip_policy, recv_ill, zoneid);
2733 		return;
2734 	}
2735 	/* NOTREACHED */
2736 discard_pkt:
2737 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2738 drop_pkt:;
2739 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2740 	freemsg(first_mp);
2741 }
2742 
2743 /*
2744  * Common IP options parser.
2745  *
2746  * Setup routine: fill in *optp with options-parsing state, then
2747  * tail-call ipoptp_next to return the first option.
2748  */
2749 uint8_t
2750 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2751 {
2752 	uint32_t totallen; /* total length of all options */
2753 
2754 	totallen = ipha->ipha_version_and_hdr_length -
2755 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2756 	totallen <<= 2;
2757 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2758 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2759 	optp->ipoptp_flags = 0;
2760 	return (ipoptp_next(optp));
2761 }
2762 
2763 /*
2764  * Common IP options parser: extract next option.
2765  */
2766 uint8_t
2767 ipoptp_next(ipoptp_t *optp)
2768 {
2769 	uint8_t *end = optp->ipoptp_end;
2770 	uint8_t *cur = optp->ipoptp_next;
2771 	uint8_t opt, len, pointer;
2772 
2773 	/*
2774 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2775 	 * has been corrupted.
2776 	 */
2777 	ASSERT(cur <= end);
2778 
2779 	if (cur == end)
2780 		return (IPOPT_EOL);
2781 
2782 	opt = cur[IPOPT_OPTVAL];
2783 
2784 	/*
2785 	 * Skip any NOP options.
2786 	 */
2787 	while (opt == IPOPT_NOP) {
2788 		cur++;
2789 		if (cur == end)
2790 			return (IPOPT_EOL);
2791 		opt = cur[IPOPT_OPTVAL];
2792 	}
2793 
2794 	if (opt == IPOPT_EOL)
2795 		return (IPOPT_EOL);
2796 
2797 	/*
2798 	 * Option requiring a length.
2799 	 */
2800 	if ((cur + 1) >= end) {
2801 		optp->ipoptp_flags |= IPOPTP_ERROR;
2802 		return (IPOPT_EOL);
2803 	}
2804 	len = cur[IPOPT_OLEN];
2805 	if (len < 2) {
2806 		optp->ipoptp_flags |= IPOPTP_ERROR;
2807 		return (IPOPT_EOL);
2808 	}
2809 	optp->ipoptp_cur = cur;
2810 	optp->ipoptp_len = len;
2811 	optp->ipoptp_next = cur + len;
2812 	if (cur + len > end) {
2813 		optp->ipoptp_flags |= IPOPTP_ERROR;
2814 		return (IPOPT_EOL);
2815 	}
2816 
2817 	/*
2818 	 * For the options which require a pointer field, make sure
2819 	 * its there, and make sure it points to either something
2820 	 * inside this option, or the end of the option.
2821 	 */
2822 	switch (opt) {
2823 	case IPOPT_RR:
2824 	case IPOPT_TS:
2825 	case IPOPT_LSRR:
2826 	case IPOPT_SSRR:
2827 		if (len <= IPOPT_OFFSET) {
2828 			optp->ipoptp_flags |= IPOPTP_ERROR;
2829 			return (opt);
2830 		}
2831 		pointer = cur[IPOPT_OFFSET];
2832 		if (pointer - 1 > len) {
2833 			optp->ipoptp_flags |= IPOPTP_ERROR;
2834 			return (opt);
2835 		}
2836 		break;
2837 	}
2838 
2839 	/*
2840 	 * Sanity check the pointer field based on the type of the
2841 	 * option.
2842 	 */
2843 	switch (opt) {
2844 	case IPOPT_RR:
2845 	case IPOPT_SSRR:
2846 	case IPOPT_LSRR:
2847 		if (pointer < IPOPT_MINOFF_SR)
2848 			optp->ipoptp_flags |= IPOPTP_ERROR;
2849 		break;
2850 	case IPOPT_TS:
2851 		if (pointer < IPOPT_MINOFF_IT)
2852 			optp->ipoptp_flags |= IPOPTP_ERROR;
2853 		/*
2854 		 * Note that the Internet Timestamp option also
2855 		 * contains two four bit fields (the Overflow field,
2856 		 * and the Flag field), which follow the pointer
2857 		 * field.  We don't need to check that these fields
2858 		 * fall within the length of the option because this
2859 		 * was implicitely done above.  We've checked that the
2860 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2861 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2862 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2863 		 */
2864 		ASSERT(len > IPOPT_POS_OV_FLG);
2865 		break;
2866 	}
2867 
2868 	return (opt);
2869 }
2870 
2871 /*
2872  * Use the outgoing IP header to create an IP_OPTIONS option the way
2873  * it was passed down from the application.
2874  */
2875 int
2876 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2877 {
2878 	ipoptp_t	opts;
2879 	const uchar_t	*opt;
2880 	uint8_t		optval;
2881 	uint8_t		optlen;
2882 	uint32_t	len = 0;
2883 	uchar_t	*buf1 = buf;
2884 
2885 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2886 	len += IP_ADDR_LEN;
2887 	bzero(buf1, IP_ADDR_LEN);
2888 
2889 	/*
2890 	 * OK to cast away const here, as we don't store through the returned
2891 	 * opts.ipoptp_cur pointer.
2892 	 */
2893 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2894 	    optval != IPOPT_EOL;
2895 	    optval = ipoptp_next(&opts)) {
2896 		int	off;
2897 
2898 		opt = opts.ipoptp_cur;
2899 		optlen = opts.ipoptp_len;
2900 		switch (optval) {
2901 		case IPOPT_SSRR:
2902 		case IPOPT_LSRR:
2903 
2904 			/*
2905 			 * Insert ipha_dst as the first entry in the source
2906 			 * route and move down the entries on step.
2907 			 * The last entry gets placed at buf1.
2908 			 */
2909 			buf[IPOPT_OPTVAL] = optval;
2910 			buf[IPOPT_OLEN] = optlen;
2911 			buf[IPOPT_OFFSET] = optlen;
2912 
2913 			off = optlen - IP_ADDR_LEN;
2914 			if (off < 0) {
2915 				/* No entries in source route */
2916 				break;
2917 			}
2918 			/* Last entry in source route */
2919 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2920 			off -= IP_ADDR_LEN;
2921 
2922 			while (off > 0) {
2923 				bcopy(opt + off,
2924 				    buf + off + IP_ADDR_LEN,
2925 				    IP_ADDR_LEN);
2926 				off -= IP_ADDR_LEN;
2927 			}
2928 			/* ipha_dst into first slot */
2929 			bcopy(&ipha->ipha_dst,
2930 			    buf + off + IP_ADDR_LEN,
2931 			    IP_ADDR_LEN);
2932 			buf += optlen;
2933 			len += optlen;
2934 			break;
2935 
2936 		case IPOPT_COMSEC:
2937 		case IPOPT_SECURITY:
2938 			/* if passing up a label is not ok, then remove */
2939 			if (is_system_labeled())
2940 				break;
2941 			/* FALLTHROUGH */
2942 		default:
2943 			bcopy(opt, buf, optlen);
2944 			buf += optlen;
2945 			len += optlen;
2946 			break;
2947 		}
2948 	}
2949 done:
2950 	/* Pad the resulting options */
2951 	while (len & 0x3) {
2952 		*buf++ = IPOPT_EOL;
2953 		len++;
2954 	}
2955 	return (len);
2956 }
2957 
2958 /*
2959  * Update any record route or timestamp options to include this host.
2960  * Reverse any source route option.
2961  * This routine assumes that the options are well formed i.e. that they
2962  * have already been checked.
2963  */
2964 static void
2965 icmp_options_update(ipha_t *ipha)
2966 {
2967 	ipoptp_t	opts;
2968 	uchar_t		*opt;
2969 	uint8_t		optval;
2970 	ipaddr_t	src;		/* Our local address */
2971 	ipaddr_t	dst;
2972 
2973 	ip2dbg(("icmp_options_update\n"));
2974 	src = ipha->ipha_src;
2975 	dst = ipha->ipha_dst;
2976 
2977 	for (optval = ipoptp_first(&opts, ipha);
2978 	    optval != IPOPT_EOL;
2979 	    optval = ipoptp_next(&opts)) {
2980 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2981 		opt = opts.ipoptp_cur;
2982 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2983 		    optval, opts.ipoptp_len));
2984 		switch (optval) {
2985 			int off1, off2;
2986 		case IPOPT_SSRR:
2987 		case IPOPT_LSRR:
2988 			/*
2989 			 * Reverse the source route.  The first entry
2990 			 * should be the next to last one in the current
2991 			 * source route (the last entry is our address).
2992 			 * The last entry should be the final destination.
2993 			 */
2994 			off1 = IPOPT_MINOFF_SR - 1;
2995 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2996 			if (off2 < 0) {
2997 				/* No entries in source route */
2998 				ip1dbg((
2999 				    "icmp_options_update: bad src route\n"));
3000 				break;
3001 			}
3002 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3003 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3004 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3005 			off2 -= IP_ADDR_LEN;
3006 
3007 			while (off1 < off2) {
3008 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3009 				bcopy((char *)opt + off2, (char *)opt + off1,
3010 				    IP_ADDR_LEN);
3011 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3012 				off1 += IP_ADDR_LEN;
3013 				off2 -= IP_ADDR_LEN;
3014 			}
3015 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3016 			break;
3017 		}
3018 	}
3019 }
3020 
3021 /*
3022  * Process received ICMP Redirect messages.
3023  */
3024 static void
3025 icmp_redirect(ill_t *ill, mblk_t *mp)
3026 {
3027 	ipha_t	*ipha;
3028 	int	iph_hdr_length;
3029 	icmph_t	*icmph;
3030 	ipha_t	*ipha_err;
3031 	ire_t	*ire;
3032 	ire_t	*prev_ire;
3033 	ire_t	*save_ire;
3034 	ipaddr_t  src, dst, gateway;
3035 	iulp_t	ulp_info = { 0 };
3036 	int	error;
3037 	ip_stack_t *ipst;
3038 
3039 	ASSERT(ill != NULL);
3040 	ipst = ill->ill_ipst;
3041 
3042 	ipha = (ipha_t *)mp->b_rptr;
3043 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3044 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3045 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3046 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3047 		freemsg(mp);
3048 		return;
3049 	}
3050 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3051 	ipha_err = (ipha_t *)&icmph[1];
3052 	src = ipha->ipha_src;
3053 	dst = ipha_err->ipha_dst;
3054 	gateway = icmph->icmph_rd_gateway;
3055 	/* Make sure the new gateway is reachable somehow. */
3056 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3057 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3058 	/*
3059 	 * Make sure we had a route for the dest in question and that
3060 	 * that route was pointing to the old gateway (the source of the
3061 	 * redirect packet.)
3062 	 */
3063 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3064 	    NULL, MATCH_IRE_GW, ipst);
3065 	/*
3066 	 * Check that
3067 	 *	the redirect was not from ourselves
3068 	 *	the new gateway and the old gateway are directly reachable
3069 	 */
3070 	if (!prev_ire ||
3071 	    !ire ||
3072 	    ire->ire_type == IRE_LOCAL) {
3073 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3074 		freemsg(mp);
3075 		if (ire != NULL)
3076 			ire_refrele(ire);
3077 		if (prev_ire != NULL)
3078 			ire_refrele(prev_ire);
3079 		return;
3080 	}
3081 
3082 	/*
3083 	 * Should we use the old ULP info to create the new gateway?  From
3084 	 * a user's perspective, we should inherit the info so that it
3085 	 * is a "smooth" transition.  If we do not do that, then new
3086 	 * connections going thru the new gateway will have no route metrics,
3087 	 * which is counter-intuitive to user.  From a network point of
3088 	 * view, this may or may not make sense even though the new gateway
3089 	 * is still directly connected to us so the route metrics should not
3090 	 * change much.
3091 	 *
3092 	 * But if the old ire_uinfo is not initialized, we do another
3093 	 * recursive lookup on the dest using the new gateway.  There may
3094 	 * be a route to that.  If so, use it to initialize the redirect
3095 	 * route.
3096 	 */
3097 	if (prev_ire->ire_uinfo.iulp_set) {
3098 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3099 	} else {
3100 		ire_t *tmp_ire;
3101 		ire_t *sire;
3102 
3103 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3104 		    ALL_ZONES, 0, NULL,
3105 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3106 		    ipst);
3107 		if (sire != NULL) {
3108 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3109 			/*
3110 			 * If sire != NULL, ire_ftable_lookup() should not
3111 			 * return a NULL value.
3112 			 */
3113 			ASSERT(tmp_ire != NULL);
3114 			ire_refrele(tmp_ire);
3115 			ire_refrele(sire);
3116 		} else if (tmp_ire != NULL) {
3117 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3118 			    sizeof (iulp_t));
3119 			ire_refrele(tmp_ire);
3120 		}
3121 	}
3122 	if (prev_ire->ire_type == IRE_CACHE)
3123 		ire_delete(prev_ire);
3124 	ire_refrele(prev_ire);
3125 	/*
3126 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3127 	 * require TOS routing
3128 	 */
3129 	switch (icmph->icmph_code) {
3130 	case 0:
3131 	case 1:
3132 		/* TODO: TOS specificity for cases 2 and 3 */
3133 	case 2:
3134 	case 3:
3135 		break;
3136 	default:
3137 		freemsg(mp);
3138 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3139 		ire_refrele(ire);
3140 		return;
3141 	}
3142 	/*
3143 	 * Create a Route Association.  This will allow us to remember that
3144 	 * someone we believe told us to use the particular gateway.
3145 	 */
3146 	save_ire = ire;
3147 	ire = ire_create(
3148 	    (uchar_t *)&dst,			/* dest addr */
3149 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3150 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3151 	    (uchar_t *)&gateway,		/* gateway addr */
3152 	    &save_ire->ire_max_frag,		/* max frag */
3153 	    NULL,				/* no src nce */
3154 	    NULL,				/* no rfq */
3155 	    NULL,				/* no stq */
3156 	    IRE_HOST,
3157 	    NULL,				/* ipif */
3158 	    0,					/* cmask */
3159 	    0,					/* phandle */
3160 	    0,					/* ihandle */
3161 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3162 	    &ulp_info,
3163 	    NULL,				/* tsol_gc_t */
3164 	    NULL,				/* gcgrp */
3165 	    ipst);
3166 
3167 	if (ire == NULL) {
3168 		freemsg(mp);
3169 		ire_refrele(save_ire);
3170 		return;
3171 	}
3172 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3173 	ire_refrele(save_ire);
3174 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3175 
3176 	if (error == 0) {
3177 		ire_refrele(ire);		/* Held in ire_add_v4 */
3178 		/* tell routing sockets that we received a redirect */
3179 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3180 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3181 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3182 	}
3183 
3184 	/*
3185 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3186 	 * This together with the added IRE has the effect of
3187 	 * modifying an existing redirect.
3188 	 */
3189 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3190 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3191 	if (prev_ire != NULL) {
3192 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3193 			ire_delete(prev_ire);
3194 		ire_refrele(prev_ire);
3195 	}
3196 
3197 	freemsg(mp);
3198 }
3199 
3200 /*
3201  * Generate an ICMP parameter problem message.
3202  */
3203 static void
3204 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3205 	ip_stack_t *ipst)
3206 {
3207 	icmph_t	icmph;
3208 	boolean_t mctl_present;
3209 	mblk_t *first_mp;
3210 
3211 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3212 
3213 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3214 		if (mctl_present)
3215 			freeb(first_mp);
3216 		return;
3217 	}
3218 
3219 	bzero(&icmph, sizeof (icmph_t));
3220 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3221 	icmph.icmph_pp_ptr = ptr;
3222 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3223 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3224 	    ipst);
3225 }
3226 
3227 /*
3228  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3229  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3230  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3231  * an icmp error packet can be sent.
3232  * Assigns an appropriate source address to the packet. If ipha_dst is
3233  * one of our addresses use it for source. Otherwise pick a source based
3234  * on a route lookup back to ipha_src.
3235  * Note that ipha_src must be set here since the
3236  * packet is likely to arrive on an ill queue in ip_wput() which will
3237  * not set a source address.
3238  */
3239 static void
3240 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3241     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3242 {
3243 	ipaddr_t dst;
3244 	icmph_t	*icmph;
3245 	ipha_t	*ipha;
3246 	uint_t	len_needed;
3247 	size_t	msg_len;
3248 	mblk_t	*mp1;
3249 	ipaddr_t src;
3250 	ire_t	*ire;
3251 	mblk_t *ipsec_mp;
3252 	ipsec_out_t	*io = NULL;
3253 
3254 	if (mctl_present) {
3255 		/*
3256 		 * If it is :
3257 		 *
3258 		 * 1) a IPSEC_OUT, then this is caused by outbound
3259 		 *    datagram originating on this host. IPsec processing
3260 		 *    may or may not have been done. Refer to comments above
3261 		 *    icmp_inbound_error_fanout for details.
3262 		 *
3263 		 * 2) a IPSEC_IN if we are generating a icmp_message
3264 		 *    for an incoming datagram destined for us i.e called
3265 		 *    from ip_fanout_send_icmp.
3266 		 */
3267 		ipsec_info_t *in;
3268 		ipsec_mp = mp;
3269 		mp = ipsec_mp->b_cont;
3270 
3271 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3272 		ipha = (ipha_t *)mp->b_rptr;
3273 
3274 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3275 		    in->ipsec_info_type == IPSEC_IN);
3276 
3277 		if (in->ipsec_info_type == IPSEC_IN) {
3278 			/*
3279 			 * Convert the IPSEC_IN to IPSEC_OUT.
3280 			 */
3281 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3282 				BUMP_MIB(&ipst->ips_ip_mib,
3283 				    ipIfStatsOutDiscards);
3284 				return;
3285 			}
3286 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3287 		} else {
3288 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3289 			io = (ipsec_out_t *)in;
3290 			/*
3291 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3292 			 * ire lookup.
3293 			 */
3294 			io->ipsec_out_proc_begin = B_FALSE;
3295 		}
3296 		ASSERT(zoneid == io->ipsec_out_zoneid);
3297 		ASSERT(zoneid != ALL_ZONES);
3298 	} else {
3299 		/*
3300 		 * This is in clear. The icmp message we are building
3301 		 * here should go out in clear.
3302 		 *
3303 		 * Pardon the convolution of it all, but it's easier to
3304 		 * allocate a "use cleartext" IPSEC_IN message and convert
3305 		 * it than it is to allocate a new one.
3306 		 */
3307 		ipsec_in_t *ii;
3308 		ASSERT(DB_TYPE(mp) == M_DATA);
3309 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3310 		if (ipsec_mp == NULL) {
3311 			freemsg(mp);
3312 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3313 			return;
3314 		}
3315 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3316 
3317 		/* This is not a secure packet */
3318 		ii->ipsec_in_secure = B_FALSE;
3319 		/*
3320 		 * For trusted extensions using a shared IP address we can
3321 		 * send using any zoneid.
3322 		 */
3323 		if (zoneid == ALL_ZONES)
3324 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3325 		else
3326 			ii->ipsec_in_zoneid = zoneid;
3327 		ipsec_mp->b_cont = mp;
3328 		ipha = (ipha_t *)mp->b_rptr;
3329 		/*
3330 		 * Convert the IPSEC_IN to IPSEC_OUT.
3331 		 */
3332 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3333 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3334 			return;
3335 		}
3336 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3337 	}
3338 
3339 	/* Remember our eventual destination */
3340 	dst = ipha->ipha_src;
3341 
3342 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3343 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3344 	if (ire != NULL &&
3345 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3346 		src = ipha->ipha_dst;
3347 	} else {
3348 		if (ire != NULL)
3349 			ire_refrele(ire);
3350 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3351 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3352 		    ipst);
3353 		if (ire == NULL) {
3354 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3355 			freemsg(ipsec_mp);
3356 			return;
3357 		}
3358 		src = ire->ire_src_addr;
3359 	}
3360 
3361 	if (ire != NULL)
3362 		ire_refrele(ire);
3363 
3364 	/*
3365 	 * Check if we can send back more then 8 bytes in addition to
3366 	 * the IP header.  We try to send 64 bytes of data and the internal
3367 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3368 	 */
3369 	len_needed = IPH_HDR_LENGTH(ipha);
3370 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3371 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3372 
3373 		if (!pullupmsg(mp, -1)) {
3374 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3375 			freemsg(ipsec_mp);
3376 			return;
3377 		}
3378 		ipha = (ipha_t *)mp->b_rptr;
3379 
3380 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3381 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3382 			    len_needed));
3383 		} else {
3384 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3385 
3386 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3387 			len_needed += ip_hdr_length_v6(mp, ip6h);
3388 		}
3389 	}
3390 	len_needed += ipst->ips_ip_icmp_return;
3391 	msg_len = msgdsize(mp);
3392 	if (msg_len > len_needed) {
3393 		(void) adjmsg(mp, len_needed - msg_len);
3394 		msg_len = len_needed;
3395 	}
3396 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3397 	if (mp1 == NULL) {
3398 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3399 		freemsg(ipsec_mp);
3400 		return;
3401 	}
3402 	mp1->b_cont = mp;
3403 	mp = mp1;
3404 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3405 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3406 	    io->ipsec_out_type == IPSEC_OUT);
3407 	ipsec_mp->b_cont = mp;
3408 
3409 	/*
3410 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3411 	 * node generates be accepted in peace by all on-host destinations.
3412 	 * If we do NOT assume that all on-host destinations trust
3413 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3414 	 * (Look for ipsec_out_icmp_loopback).
3415 	 */
3416 	io->ipsec_out_icmp_loopback = B_TRUE;
3417 
3418 	ipha = (ipha_t *)mp->b_rptr;
3419 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3420 	*ipha = icmp_ipha;
3421 	ipha->ipha_src = src;
3422 	ipha->ipha_dst = dst;
3423 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3424 	msg_len += sizeof (icmp_ipha) + len;
3425 	if (msg_len > IP_MAXPACKET) {
3426 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3427 		msg_len = IP_MAXPACKET;
3428 	}
3429 	ipha->ipha_length = htons((uint16_t)msg_len);
3430 	icmph = (icmph_t *)&ipha[1];
3431 	bcopy(stuff, icmph, len);
3432 	icmph->icmph_checksum = 0;
3433 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3434 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3435 	put(q, ipsec_mp);
3436 }
3437 
3438 /*
3439  * Determine if an ICMP error packet can be sent given the rate limit.
3440  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3441  * in milliseconds) and a burst size. Burst size number of packets can
3442  * be sent arbitrarely closely spaced.
3443  * The state is tracked using two variables to implement an approximate
3444  * token bucket filter:
3445  *	icmp_pkt_err_last - lbolt value when the last burst started
3446  *	icmp_pkt_err_sent - number of packets sent in current burst
3447  */
3448 boolean_t
3449 icmp_err_rate_limit(ip_stack_t *ipst)
3450 {
3451 	clock_t now = TICK_TO_MSEC(lbolt);
3452 	uint_t refilled; /* Number of packets refilled in tbf since last */
3453 	/* Guard against changes by loading into local variable */
3454 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3455 
3456 	if (err_interval == 0)
3457 		return (B_FALSE);
3458 
3459 	if (ipst->ips_icmp_pkt_err_last > now) {
3460 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3461 		ipst->ips_icmp_pkt_err_last = 0;
3462 		ipst->ips_icmp_pkt_err_sent = 0;
3463 	}
3464 	/*
3465 	 * If we are in a burst update the token bucket filter.
3466 	 * Update the "last" time to be close to "now" but make sure
3467 	 * we don't loose precision.
3468 	 */
3469 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3470 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3471 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3472 			ipst->ips_icmp_pkt_err_sent = 0;
3473 		} else {
3474 			ipst->ips_icmp_pkt_err_sent -= refilled;
3475 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3476 		}
3477 	}
3478 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3479 		/* Start of new burst */
3480 		ipst->ips_icmp_pkt_err_last = now;
3481 	}
3482 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3483 		ipst->ips_icmp_pkt_err_sent++;
3484 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3485 		    ipst->ips_icmp_pkt_err_sent));
3486 		return (B_FALSE);
3487 	}
3488 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3489 	return (B_TRUE);
3490 }
3491 
3492 /*
3493  * Check if it is ok to send an IPv4 ICMP error packet in
3494  * response to the IPv4 packet in mp.
3495  * Free the message and return null if no
3496  * ICMP error packet should be sent.
3497  */
3498 static mblk_t *
3499 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3500 {
3501 	icmph_t	*icmph;
3502 	ipha_t	*ipha;
3503 	uint_t	len_needed;
3504 	ire_t	*src_ire;
3505 	ire_t	*dst_ire;
3506 
3507 	if (!mp)
3508 		return (NULL);
3509 	ipha = (ipha_t *)mp->b_rptr;
3510 	if (ip_csum_hdr(ipha)) {
3511 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3512 		freemsg(mp);
3513 		return (NULL);
3514 	}
3515 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3516 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3517 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3518 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3519 	if (src_ire != NULL || dst_ire != NULL ||
3520 	    CLASSD(ipha->ipha_dst) ||
3521 	    CLASSD(ipha->ipha_src) ||
3522 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3523 		/* Note: only errors to the fragment with offset 0 */
3524 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3525 		freemsg(mp);
3526 		if (src_ire != NULL)
3527 			ire_refrele(src_ire);
3528 		if (dst_ire != NULL)
3529 			ire_refrele(dst_ire);
3530 		return (NULL);
3531 	}
3532 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3533 		/*
3534 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3535 		 * errors in response to any ICMP errors.
3536 		 */
3537 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3538 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3539 			if (!pullupmsg(mp, len_needed)) {
3540 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3541 				freemsg(mp);
3542 				return (NULL);
3543 			}
3544 			ipha = (ipha_t *)mp->b_rptr;
3545 		}
3546 		icmph = (icmph_t *)
3547 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3548 		switch (icmph->icmph_type) {
3549 		case ICMP_DEST_UNREACHABLE:
3550 		case ICMP_SOURCE_QUENCH:
3551 		case ICMP_TIME_EXCEEDED:
3552 		case ICMP_PARAM_PROBLEM:
3553 		case ICMP_REDIRECT:
3554 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3555 			freemsg(mp);
3556 			return (NULL);
3557 		default:
3558 			break;
3559 		}
3560 	}
3561 	/*
3562 	 * If this is a labeled system, then check to see if we're allowed to
3563 	 * send a response to this particular sender.  If not, then just drop.
3564 	 */
3565 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3566 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3567 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3568 		freemsg(mp);
3569 		return (NULL);
3570 	}
3571 	if (icmp_err_rate_limit(ipst)) {
3572 		/*
3573 		 * Only send ICMP error packets every so often.
3574 		 * This should be done on a per port/source basis,
3575 		 * but for now this will suffice.
3576 		 */
3577 		freemsg(mp);
3578 		return (NULL);
3579 	}
3580 	return (mp);
3581 }
3582 
3583 /*
3584  * Generate an ICMP redirect message.
3585  */
3586 static void
3587 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3588 {
3589 	icmph_t	icmph;
3590 
3591 	/*
3592 	 * We are called from ip_rput where we could
3593 	 * not have attached an IPSEC_IN.
3594 	 */
3595 	ASSERT(mp->b_datap->db_type == M_DATA);
3596 
3597 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3598 		return;
3599 	}
3600 
3601 	bzero(&icmph, sizeof (icmph_t));
3602 	icmph.icmph_type = ICMP_REDIRECT;
3603 	icmph.icmph_code = 1;
3604 	icmph.icmph_rd_gateway = gateway;
3605 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3606 	/* Redirects sent by router, and router is global zone */
3607 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3608 }
3609 
3610 /*
3611  * Generate an ICMP time exceeded message.
3612  */
3613 void
3614 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3615     ip_stack_t *ipst)
3616 {
3617 	icmph_t	icmph;
3618 	boolean_t mctl_present;
3619 	mblk_t *first_mp;
3620 
3621 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3622 
3623 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3624 		if (mctl_present)
3625 			freeb(first_mp);
3626 		return;
3627 	}
3628 
3629 	bzero(&icmph, sizeof (icmph_t));
3630 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3631 	icmph.icmph_code = code;
3632 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3633 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3634 	    ipst);
3635 }
3636 
3637 /*
3638  * Generate an ICMP unreachable message.
3639  */
3640 void
3641 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3642     ip_stack_t *ipst)
3643 {
3644 	icmph_t	icmph;
3645 	mblk_t *first_mp;
3646 	boolean_t mctl_present;
3647 
3648 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3649 
3650 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3651 		if (mctl_present)
3652 			freeb(first_mp);
3653 		return;
3654 	}
3655 
3656 	bzero(&icmph, sizeof (icmph_t));
3657 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3658 	icmph.icmph_code = code;
3659 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3660 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3661 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3662 	    zoneid, ipst);
3663 }
3664 
3665 /*
3666  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3667  * duplicate.  As long as someone else holds the address, the interface will
3668  * stay down.  When that conflict goes away, the interface is brought back up.
3669  * This is done so that accidental shutdowns of addresses aren't made
3670  * permanent.  Your server will recover from a failure.
3671  *
3672  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3673  * user space process (dhcpagent).
3674  *
3675  * Recovery completes if ARP reports that the address is now ours (via
3676  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3677  *
3678  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3679  */
3680 static void
3681 ipif_dup_recovery(void *arg)
3682 {
3683 	ipif_t *ipif = arg;
3684 	ill_t *ill = ipif->ipif_ill;
3685 	mblk_t *arp_add_mp;
3686 	mblk_t *arp_del_mp;
3687 	area_t *area;
3688 	ip_stack_t *ipst = ill->ill_ipst;
3689 
3690 	ipif->ipif_recovery_id = 0;
3691 
3692 	/*
3693 	 * No lock needed for moving or condemned check, as this is just an
3694 	 * optimization.
3695 	 */
3696 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3697 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3698 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3699 		/* No reason to try to bring this address back. */
3700 		return;
3701 	}
3702 
3703 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3704 		goto alloc_fail;
3705 
3706 	if (ipif->ipif_arp_del_mp == NULL) {
3707 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3708 			goto alloc_fail;
3709 		ipif->ipif_arp_del_mp = arp_del_mp;
3710 	}
3711 
3712 	/* Setting the 'unverified' flag restarts DAD */
3713 	area = (area_t *)arp_add_mp->b_rptr;
3714 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3715 	    ACE_F_UNVERIFIED;
3716 	putnext(ill->ill_rq, arp_add_mp);
3717 	return;
3718 
3719 alloc_fail:
3720 	/*
3721 	 * On allocation failure, just restart the timer.  Note that the ipif
3722 	 * is down here, so no other thread could be trying to start a recovery
3723 	 * timer.  The ill_lock protects the condemned flag and the recovery
3724 	 * timer ID.
3725 	 */
3726 	freemsg(arp_add_mp);
3727 	mutex_enter(&ill->ill_lock);
3728 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3729 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3730 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3731 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3732 	}
3733 	mutex_exit(&ill->ill_lock);
3734 }
3735 
3736 /*
3737  * This is for exclusive changes due to ARP.  Either tear down an interface due
3738  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3739  */
3740 /* ARGSUSED */
3741 static void
3742 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3743 {
3744 	ill_t	*ill = rq->q_ptr;
3745 	arh_t *arh;
3746 	ipaddr_t src;
3747 	ipif_t	*ipif;
3748 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3749 	char hbuf[MAC_STR_LEN];
3750 	char sbuf[INET_ADDRSTRLEN];
3751 	const char *failtype;
3752 	boolean_t bring_up;
3753 	ip_stack_t *ipst = ill->ill_ipst;
3754 
3755 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3756 	case AR_CN_READY:
3757 		failtype = NULL;
3758 		bring_up = B_TRUE;
3759 		break;
3760 	case AR_CN_FAILED:
3761 		failtype = "in use";
3762 		bring_up = B_FALSE;
3763 		break;
3764 	default:
3765 		failtype = "claimed";
3766 		bring_up = B_FALSE;
3767 		break;
3768 	}
3769 
3770 	arh = (arh_t *)mp->b_cont->b_rptr;
3771 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3772 
3773 	/* Handle failures due to probes */
3774 	if (src == 0) {
3775 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3776 		    IP_ADDR_LEN);
3777 	}
3778 
3779 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3780 	    sizeof (hbuf));
3781 	(void) ip_dot_addr(src, sbuf);
3782 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3783 
3784 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3785 		    ipif->ipif_lcl_addr != src) {
3786 			continue;
3787 		}
3788 
3789 		/*
3790 		 * If we failed on a recovery probe, then restart the timer to
3791 		 * try again later.
3792 		 */
3793 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3794 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3795 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3796 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3797 		    ipst->ips_ip_dup_recovery > 0 &&
3798 		    ipif->ipif_recovery_id == 0) {
3799 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3800 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3801 			continue;
3802 		}
3803 
3804 		/*
3805 		 * If what we're trying to do has already been done, then do
3806 		 * nothing.
3807 		 */
3808 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3809 			continue;
3810 
3811 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3812 
3813 		if (failtype == NULL) {
3814 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3815 			    ibuf);
3816 		} else {
3817 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3818 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3819 		}
3820 
3821 		if (bring_up) {
3822 			ASSERT(ill->ill_dl_up);
3823 			/*
3824 			 * Free up the ARP delete message so we can allocate
3825 			 * a fresh one through the normal path.
3826 			 */
3827 			freemsg(ipif->ipif_arp_del_mp);
3828 			ipif->ipif_arp_del_mp = NULL;
3829 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3830 			    EINPROGRESS) {
3831 				ipif->ipif_addr_ready = 1;
3832 				(void) ipif_up_done(ipif);
3833 			}
3834 			continue;
3835 		}
3836 
3837 		mutex_enter(&ill->ill_lock);
3838 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3839 		ipif->ipif_flags |= IPIF_DUPLICATE;
3840 		ill->ill_ipif_dup_count++;
3841 		mutex_exit(&ill->ill_lock);
3842 		/*
3843 		 * Already exclusive on the ill; no need to handle deferred
3844 		 * processing here.
3845 		 */
3846 		(void) ipif_down(ipif, NULL, NULL);
3847 		ipif_down_tail(ipif);
3848 		mutex_enter(&ill->ill_lock);
3849 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3850 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3851 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3852 		    ipst->ips_ip_dup_recovery > 0) {
3853 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3854 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3855 		}
3856 		mutex_exit(&ill->ill_lock);
3857 	}
3858 	freemsg(mp);
3859 }
3860 
3861 /* ARGSUSED */
3862 static void
3863 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3864 {
3865 	ill_t	*ill = rq->q_ptr;
3866 	arh_t *arh;
3867 	ipaddr_t src;
3868 	ipif_t	*ipif;
3869 
3870 	arh = (arh_t *)mp->b_cont->b_rptr;
3871 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3872 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3873 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3874 			(void) ipif_resolver_up(ipif, Res_act_defend);
3875 	}
3876 	freemsg(mp);
3877 }
3878 
3879 /*
3880  * News from ARP.  ARP sends notification of interesting events down
3881  * to its clients using M_CTL messages with the interesting ARP packet
3882  * attached via b_cont.
3883  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3884  * queue as opposed to ARP sending the message to all the clients, i.e. all
3885  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3886  * table if a cache IRE is found to delete all the entries for the address in
3887  * the packet.
3888  */
3889 static void
3890 ip_arp_news(queue_t *q, mblk_t *mp)
3891 {
3892 	arcn_t		*arcn;
3893 	arh_t		*arh;
3894 	ire_t		*ire = NULL;
3895 	char		hbuf[MAC_STR_LEN];
3896 	char		sbuf[INET_ADDRSTRLEN];
3897 	ipaddr_t	src;
3898 	in6_addr_t	v6src;
3899 	boolean_t	isv6 = B_FALSE;
3900 	ipif_t		*ipif;
3901 	ill_t		*ill;
3902 	ip_stack_t	*ipst;
3903 
3904 	if (CONN_Q(q)) {
3905 		conn_t *connp = Q_TO_CONN(q);
3906 
3907 		ipst = connp->conn_netstack->netstack_ip;
3908 	} else {
3909 		ill_t *ill = (ill_t *)q->q_ptr;
3910 
3911 		ipst = ill->ill_ipst;
3912 	}
3913 
3914 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3915 		if (q->q_next) {
3916 			putnext(q, mp);
3917 		} else
3918 			freemsg(mp);
3919 		return;
3920 	}
3921 	arh = (arh_t *)mp->b_cont->b_rptr;
3922 	/* Is it one we are interested in? */
3923 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3924 		isv6 = B_TRUE;
3925 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3926 		    IPV6_ADDR_LEN);
3927 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3928 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3929 		    IP_ADDR_LEN);
3930 	} else {
3931 		freemsg(mp);
3932 		return;
3933 	}
3934 
3935 	ill = q->q_ptr;
3936 
3937 	arcn = (arcn_t *)mp->b_rptr;
3938 	switch (arcn->arcn_code) {
3939 	case AR_CN_BOGON:
3940 		/*
3941 		 * Someone is sending ARP packets with a source protocol
3942 		 * address that we have published and for which we believe our
3943 		 * entry is authoritative and (when ill_arp_extend is set)
3944 		 * verified to be unique on the network.
3945 		 *
3946 		 * The ARP module internally handles the cases where the sender
3947 		 * is just probing (for DAD) and where the hardware address of
3948 		 * a non-authoritative entry has changed.  Thus, these are the
3949 		 * real conflicts, and we have to do resolution.
3950 		 *
3951 		 * We back away quickly from the address if it's from DHCP or
3952 		 * otherwise temporary and hasn't been used recently (or at
3953 		 * all).  We'd like to include "deprecated" addresses here as
3954 		 * well (as there's no real reason to defend something we're
3955 		 * discarding), but IPMP "reuses" this flag to mean something
3956 		 * other than the standard meaning.
3957 		 *
3958 		 * If the ARP module above is not extended (meaning that it
3959 		 * doesn't know how to defend the address), then we just log
3960 		 * the problem as we always did and continue on.  It's not
3961 		 * right, but there's little else we can do, and those old ATM
3962 		 * users are going away anyway.
3963 		 */
3964 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3965 		    hbuf, sizeof (hbuf));
3966 		(void) ip_dot_addr(src, sbuf);
3967 		if (isv6) {
3968 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3969 			    ipst);
3970 		} else {
3971 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3972 		}
3973 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3974 			uint32_t now;
3975 			uint32_t maxage;
3976 			clock_t lused;
3977 			uint_t maxdefense;
3978 			uint_t defs;
3979 
3980 			/*
3981 			 * First, figure out if this address hasn't been used
3982 			 * in a while.  If it hasn't, then it's a better
3983 			 * candidate for abandoning.
3984 			 */
3985 			ipif = ire->ire_ipif;
3986 			ASSERT(ipif != NULL);
3987 			now = gethrestime_sec();
3988 			maxage = now - ire->ire_create_time;
3989 			if (maxage > ipst->ips_ip_max_temp_idle)
3990 				maxage = ipst->ips_ip_max_temp_idle;
3991 			lused = drv_hztousec(ddi_get_lbolt() -
3992 			    ire->ire_last_used_time) / MICROSEC + 1;
3993 			if (lused >= maxage && (ipif->ipif_flags &
3994 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3995 				maxdefense = ipst->ips_ip_max_temp_defend;
3996 			else
3997 				maxdefense = ipst->ips_ip_max_defend;
3998 
3999 			/*
4000 			 * Now figure out how many times we've defended
4001 			 * ourselves.  Ignore defenses that happened long in
4002 			 * the past.
4003 			 */
4004 			mutex_enter(&ire->ire_lock);
4005 			if ((defs = ire->ire_defense_count) > 0 &&
4006 			    now - ire->ire_defense_time >
4007 			    ipst->ips_ip_defend_interval) {
4008 				ire->ire_defense_count = defs = 0;
4009 			}
4010 			ire->ire_defense_count++;
4011 			ire->ire_defense_time = now;
4012 			mutex_exit(&ire->ire_lock);
4013 			ill_refhold(ill);
4014 			ire_refrele(ire);
4015 
4016 			/*
4017 			 * If we've defended ourselves too many times already,
4018 			 * then give up and tear down the interface(s) using
4019 			 * this address.  Otherwise, defend by sending out a
4020 			 * gratuitous ARP.
4021 			 */
4022 			if (defs >= maxdefense && ill->ill_arp_extend) {
4023 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4024 				    B_FALSE);
4025 			} else {
4026 				cmn_err(CE_WARN,
4027 				    "node %s is using our IP address %s on %s",
4028 				    hbuf, sbuf, ill->ill_name);
4029 				/*
4030 				 * If this is an old (ATM) ARP module, then
4031 				 * don't try to defend the address.  Remain
4032 				 * compatible with the old behavior.  Defend
4033 				 * only with new ARP.
4034 				 */
4035 				if (ill->ill_arp_extend) {
4036 					qwriter_ip(ill, q, mp, ip_arp_defend,
4037 					    NEW_OP, B_FALSE);
4038 				} else {
4039 					ill_refrele(ill);
4040 				}
4041 			}
4042 			return;
4043 		}
4044 		cmn_err(CE_WARN,
4045 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4046 		    hbuf, sbuf, ill->ill_name);
4047 		if (ire != NULL)
4048 			ire_refrele(ire);
4049 		break;
4050 	case AR_CN_ANNOUNCE:
4051 		if (isv6) {
4052 			/*
4053 			 * For XRESOLV interfaces.
4054 			 * Delete the IRE cache entry and NCE for this
4055 			 * v6 address
4056 			 */
4057 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4058 			/*
4059 			 * If v6src is a non-zero, it's a router address
4060 			 * as below. Do the same sort of thing to clean
4061 			 * out off-net IRE_CACHE entries that go through
4062 			 * the router.
4063 			 */
4064 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4065 				ire_walk_v6(ire_delete_cache_gw_v6,
4066 				    (char *)&v6src, ALL_ZONES, ipst);
4067 			}
4068 		} else {
4069 			nce_hw_map_t hwm;
4070 
4071 			/*
4072 			 * ARP gives us a copy of any packet where it thinks
4073 			 * the address has changed, so that we can update our
4074 			 * caches.  We're responsible for caching known answers
4075 			 * in the current design.  We check whether the
4076 			 * hardware address really has changed in all of our
4077 			 * entries that have cached this mapping, and if so, we
4078 			 * blow them away.  This way we will immediately pick
4079 			 * up the rare case of a host changing hardware
4080 			 * address.
4081 			 */
4082 			if (src == 0)
4083 				break;
4084 			hwm.hwm_addr = src;
4085 			hwm.hwm_hwlen = arh->arh_hlen;
4086 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4087 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4088 			ndp_walk_common(ipst->ips_ndp4, NULL,
4089 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4090 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4091 		}
4092 		break;
4093 	case AR_CN_READY:
4094 		/* No external v6 resolver has a contract to use this */
4095 		if (isv6)
4096 			break;
4097 		/* If the link is down, we'll retry this later */
4098 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4099 			break;
4100 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4101 		    NULL, NULL, ipst);
4102 		if (ipif != NULL) {
4103 			/*
4104 			 * If this is a duplicate recovery, then we now need to
4105 			 * go exclusive to bring this thing back up.
4106 			 */
4107 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4108 			    IPIF_DUPLICATE) {
4109 				ipif_refrele(ipif);
4110 				ill_refhold(ill);
4111 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4112 				    B_FALSE);
4113 				return;
4114 			}
4115 			/*
4116 			 * If this is the first notice that this address is
4117 			 * ready, then let the user know now.
4118 			 */
4119 			if ((ipif->ipif_flags & IPIF_UP) &&
4120 			    !ipif->ipif_addr_ready) {
4121 				ipif_mask_reply(ipif);
4122 				ip_rts_ifmsg(ipif);
4123 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4124 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4125 			}
4126 			ipif->ipif_addr_ready = 1;
4127 			ipif_refrele(ipif);
4128 		}
4129 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4130 		if (ire != NULL) {
4131 			ire->ire_defense_count = 0;
4132 			ire_refrele(ire);
4133 		}
4134 		break;
4135 	case AR_CN_FAILED:
4136 		/* No external v6 resolver has a contract to use this */
4137 		if (isv6)
4138 			break;
4139 		ill_refhold(ill);
4140 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4141 		return;
4142 	}
4143 	freemsg(mp);
4144 }
4145 
4146 /*
4147  * Create a mblk suitable for carrying the interface index and/or source link
4148  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4149  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4150  * application.
4151  */
4152 mblk_t *
4153 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4154     ip_stack_t *ipst)
4155 {
4156 	mblk_t		*mp;
4157 	ip_pktinfo_t	*pinfo;
4158 	ipha_t *ipha;
4159 	struct ether_header *pether;
4160 
4161 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4162 	if (mp == NULL) {
4163 		ip1dbg(("ip_add_info: allocation failure.\n"));
4164 		return (data_mp);
4165 	}
4166 
4167 	ipha	= (ipha_t *)data_mp->b_rptr;
4168 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4169 	bzero(pinfo, sizeof (ip_pktinfo_t));
4170 	pinfo->ip_pkt_flags = (uchar_t)flags;
4171 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4172 
4173 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4174 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4175 	if (flags & IPF_RECVADDR) {
4176 		ipif_t	*ipif;
4177 		ire_t	*ire;
4178 
4179 		/*
4180 		 * Only valid for V4
4181 		 */
4182 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4183 		    (IPV4_VERSION << 4));
4184 
4185 		ipif = ipif_get_next_ipif(NULL, ill);
4186 		if (ipif != NULL) {
4187 			/*
4188 			 * Since a decision has already been made to deliver the
4189 			 * packet, there is no need to test for SECATTR and
4190 			 * ZONEONLY.
4191 			 * When a multicast packet is transmitted
4192 			 * a cache entry is created for the multicast address.
4193 			 * When delivering a copy of the packet or when new
4194 			 * packets are received we do not want to match on the
4195 			 * cached entry so explicitly match on
4196 			 * IRE_LOCAL and IRE_LOOPBACK
4197 			 */
4198 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4199 			    IRE_LOCAL | IRE_LOOPBACK,
4200 			    ipif, zoneid, NULL,
4201 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4202 			if (ire == NULL) {
4203 				/*
4204 				 * packet must have come on a different
4205 				 * interface.
4206 				 * Since a decision has already been made to
4207 				 * deliver the packet, there is no need to test
4208 				 * for SECATTR and ZONEONLY.
4209 				 * Only match on local and broadcast ire's.
4210 				 * See detailed comment above.
4211 				 */
4212 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4213 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4214 				    NULL, MATCH_IRE_TYPE, ipst);
4215 			}
4216 
4217 			if (ire == NULL) {
4218 				/*
4219 				 * This is either a multicast packet or
4220 				 * the address has been removed since
4221 				 * the packet was received.
4222 				 * Return INADDR_ANY so that normal source
4223 				 * selection occurs for the response.
4224 				 */
4225 
4226 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4227 			} else {
4228 				pinfo->ip_pkt_match_addr.s_addr =
4229 				    ire->ire_src_addr;
4230 				ire_refrele(ire);
4231 			}
4232 			ipif_refrele(ipif);
4233 		} else {
4234 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4235 		}
4236 	}
4237 
4238 	pether = (struct ether_header *)((char *)ipha
4239 	    - sizeof (struct ether_header));
4240 	/*
4241 	 * Make sure the interface is an ethernet type, since this option
4242 	 * is currently supported only on this type of interface. Also make
4243 	 * sure we are pointing correctly above db_base.
4244 	 */
4245 
4246 	if ((flags & IPF_RECVSLLA) &&
4247 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4248 	    (ill->ill_type == IFT_ETHER) &&
4249 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4250 
4251 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4252 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4253 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4254 	} else {
4255 		/*
4256 		 * Clear the bit. Indicate to upper layer that IP is not
4257 		 * sending this ancillary info.
4258 		 */
4259 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4260 	}
4261 
4262 	mp->b_datap->db_type = M_CTL;
4263 	mp->b_wptr += sizeof (ip_pktinfo_t);
4264 	mp->b_cont = data_mp;
4265 
4266 	return (mp);
4267 }
4268 
4269 /*
4270  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4271  * part of the bind request.
4272  */
4273 
4274 boolean_t
4275 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4276 {
4277 	ipsec_in_t *ii;
4278 
4279 	ASSERT(policy_mp != NULL);
4280 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4281 
4282 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4283 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4284 
4285 	connp->conn_policy = ii->ipsec_in_policy;
4286 	ii->ipsec_in_policy = NULL;
4287 
4288 	if (ii->ipsec_in_action != NULL) {
4289 		if (connp->conn_latch == NULL) {
4290 			connp->conn_latch = iplatch_create();
4291 			if (connp->conn_latch == NULL)
4292 				return (B_FALSE);
4293 		}
4294 		ipsec_latch_inbound(connp->conn_latch, ii);
4295 	}
4296 	return (B_TRUE);
4297 }
4298 
4299 /*
4300  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4301  * and to arrange for power-fanout assist.  The ULP is identified by
4302  * adding a single byte at the end of the original bind message.
4303  * A ULP other than UDP or TCP that wishes to be recognized passes
4304  * down a bind with a zero length address.
4305  *
4306  * The binding works as follows:
4307  * - A zero byte address means just bind to the protocol.
4308  * - A four byte address is treated as a request to validate
4309  *   that the address is a valid local address, appropriate for
4310  *   an application to bind to. This does not affect any fanout
4311  *   information in IP.
4312  * - A sizeof sin_t byte address is used to bind to only the local address
4313  *   and port.
4314  * - A sizeof ipa_conn_t byte address contains complete fanout information
4315  *   consisting of local and remote addresses and ports.  In
4316  *   this case, the addresses are both validated as appropriate
4317  *   for this operation, and, if so, the information is retained
4318  *   for use in the inbound fanout.
4319  *
4320  * The ULP (except in the zero-length bind) can append an
4321  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4322  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4323  * a copy of the source or destination IRE (source for local bind;
4324  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4325  * policy information contained should be copied on to the conn.
4326  *
4327  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4328  */
4329 mblk_t *
4330 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4331 {
4332 	ssize_t		len;
4333 	struct T_bind_req	*tbr;
4334 	sin_t		*sin;
4335 	ipa_conn_t	*ac;
4336 	uchar_t		*ucp;
4337 	mblk_t		*mp1;
4338 	boolean_t	ire_requested;
4339 	boolean_t	ipsec_policy_set = B_FALSE;
4340 	int		error = 0;
4341 	int		protocol;
4342 	ipa_conn_x_t	*acx;
4343 
4344 	ASSERT(!connp->conn_af_isv6);
4345 	connp->conn_pkt_isv6 = B_FALSE;
4346 
4347 	len = MBLKL(mp);
4348 	if (len < (sizeof (*tbr) + 1)) {
4349 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4350 		    "ip_bind: bogus msg, len %ld", len);
4351 		/* XXX: Need to return something better */
4352 		goto bad_addr;
4353 	}
4354 	/* Back up and extract the protocol identifier. */
4355 	mp->b_wptr--;
4356 	protocol = *mp->b_wptr & 0xFF;
4357 	tbr = (struct T_bind_req *)mp->b_rptr;
4358 	/* Reset the message type in preparation for shipping it back. */
4359 	DB_TYPE(mp) = M_PCPROTO;
4360 
4361 	connp->conn_ulp = (uint8_t)protocol;
4362 
4363 	/*
4364 	 * Check for a zero length address.  This is from a protocol that
4365 	 * wants to register to receive all packets of its type.
4366 	 */
4367 	if (tbr->ADDR_length == 0) {
4368 		/*
4369 		 * These protocols are now intercepted in ip_bind_v6().
4370 		 * Reject protocol-level binds here for now.
4371 		 *
4372 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4373 		 * so that the protocol type cannot be SCTP.
4374 		 */
4375 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4376 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4377 			goto bad_addr;
4378 		}
4379 
4380 		/*
4381 		 *
4382 		 * The udp module never sends down a zero-length address,
4383 		 * and allowing this on a labeled system will break MLP
4384 		 * functionality.
4385 		 */
4386 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4387 			goto bad_addr;
4388 
4389 		if (connp->conn_mac_exempt)
4390 			goto bad_addr;
4391 
4392 		/* No hash here really.  The table is big enough. */
4393 		connp->conn_srcv6 = ipv6_all_zeros;
4394 
4395 		ipcl_proto_insert(connp, protocol);
4396 
4397 		tbr->PRIM_type = T_BIND_ACK;
4398 		return (mp);
4399 	}
4400 
4401 	/* Extract the address pointer from the message. */
4402 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4403 	    tbr->ADDR_length);
4404 	if (ucp == NULL) {
4405 		ip1dbg(("ip_bind: no address\n"));
4406 		goto bad_addr;
4407 	}
4408 	if (!OK_32PTR(ucp)) {
4409 		ip1dbg(("ip_bind: unaligned address\n"));
4410 		goto bad_addr;
4411 	}
4412 	/*
4413 	 * Check for trailing mps.
4414 	 */
4415 
4416 	mp1 = mp->b_cont;
4417 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4418 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4419 
4420 	switch (tbr->ADDR_length) {
4421 	default:
4422 		ip1dbg(("ip_bind: bad address length %d\n",
4423 		    (int)tbr->ADDR_length));
4424 		goto bad_addr;
4425 
4426 	case IP_ADDR_LEN:
4427 		/* Verification of local address only */
4428 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4429 		    ire_requested, ipsec_policy_set, B_FALSE);
4430 		break;
4431 
4432 	case sizeof (sin_t):
4433 		sin = (sin_t *)ucp;
4434 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4435 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4436 		break;
4437 
4438 	case sizeof (ipa_conn_t):
4439 		ac = (ipa_conn_t *)ucp;
4440 		/* For raw socket, the local port is not set. */
4441 		if (ac->ac_lport == 0)
4442 			ac->ac_lport = connp->conn_lport;
4443 		/* Always verify destination reachability. */
4444 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4445 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4446 		    ipsec_policy_set, B_TRUE, B_TRUE);
4447 		break;
4448 
4449 	case sizeof (ipa_conn_x_t):
4450 		acx = (ipa_conn_x_t *)ucp;
4451 		/*
4452 		 * Whether or not to verify destination reachability depends
4453 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4454 		 */
4455 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4456 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4457 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4458 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4459 		break;
4460 	}
4461 	if (error == EINPROGRESS)
4462 		return (NULL);
4463 	else if (error != 0)
4464 		goto bad_addr;
4465 	/*
4466 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4467 	 * We can't do this in ip_bind_insert_ire because the policy
4468 	 * may not have been inherited at that point in time and hence
4469 	 * conn_out_enforce_policy may not be set.
4470 	 */
4471 	mp1 = mp->b_cont;
4472 	if (ire_requested && connp->conn_out_enforce_policy &&
4473 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4474 		ire_t *ire = (ire_t *)mp1->b_rptr;
4475 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4476 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4477 	}
4478 
4479 	/* Send it home. */
4480 	mp->b_datap->db_type = M_PCPROTO;
4481 	tbr->PRIM_type = T_BIND_ACK;
4482 	return (mp);
4483 
4484 bad_addr:
4485 	/*
4486 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4487 	 * a unix errno.
4488 	 */
4489 	if (error > 0)
4490 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4491 	else
4492 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4493 	return (mp);
4494 }
4495 
4496 /*
4497  * Here address is verified to be a valid local address.
4498  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4499  * address is also considered a valid local address.
4500  * In the case of a broadcast/multicast address, however, the
4501  * upper protocol is expected to reset the src address
4502  * to 0 if it sees a IRE_BROADCAST type returned so that
4503  * no packets are emitted with broadcast/multicast address as
4504  * source address (that violates hosts requirements RFC1122)
4505  * The addresses valid for bind are:
4506  *	(1) - INADDR_ANY (0)
4507  *	(2) - IP address of an UP interface
4508  *	(3) - IP address of a DOWN interface
4509  *	(4) - valid local IP broadcast addresses. In this case
4510  *	the conn will only receive packets destined to
4511  *	the specified broadcast address.
4512  *	(5) - a multicast address. In this case
4513  *	the conn will only receive packets destined to
4514  *	the specified multicast address. Note: the
4515  *	application still has to issue an
4516  *	IP_ADD_MEMBERSHIP socket option.
4517  *
4518  * On error, return -1 for TBADADDR otherwise pass the
4519  * errno with TSYSERR reply.
4520  *
4521  * In all the above cases, the bound address must be valid in the current zone.
4522  * When the address is loopback, multicast or broadcast, there might be many
4523  * matching IREs so bind has to look up based on the zone.
4524  *
4525  * Note: lport is in network byte order.
4526  */
4527 int
4528 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4529     boolean_t ire_requested, boolean_t ipsec_policy_set,
4530     boolean_t fanout_insert)
4531 {
4532 	int		error = 0;
4533 	ire_t		*src_ire;
4534 	mblk_t		*policy_mp;
4535 	ipif_t		*ipif;
4536 	zoneid_t	zoneid;
4537 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4538 
4539 	if (ipsec_policy_set) {
4540 		policy_mp = mp->b_cont;
4541 	}
4542 
4543 	/*
4544 	 * If it was previously connected, conn_fully_bound would have
4545 	 * been set.
4546 	 */
4547 	connp->conn_fully_bound = B_FALSE;
4548 
4549 	src_ire = NULL;
4550 	ipif = NULL;
4551 
4552 	zoneid = IPCL_ZONEID(connp);
4553 
4554 	if (src_addr) {
4555 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4556 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4557 		/*
4558 		 * If an address other than 0.0.0.0 is requested,
4559 		 * we verify that it is a valid address for bind
4560 		 * Note: Following code is in if-else-if form for
4561 		 * readability compared to a condition check.
4562 		 */
4563 		/* LINTED - statement has no consequent */
4564 		if (IRE_IS_LOCAL(src_ire)) {
4565 			/*
4566 			 * (2) Bind to address of local UP interface
4567 			 */
4568 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4569 			/*
4570 			 * (4) Bind to broadcast address
4571 			 * Note: permitted only from transports that
4572 			 * request IRE
4573 			 */
4574 			if (!ire_requested)
4575 				error = EADDRNOTAVAIL;
4576 		} else {
4577 			/*
4578 			 * (3) Bind to address of local DOWN interface
4579 			 * (ipif_lookup_addr() looks up all interfaces
4580 			 * but we do not get here for UP interfaces
4581 			 * - case (2) above)
4582 			 * We put the protocol byte back into the mblk
4583 			 * since we may come back via ip_wput_nondata()
4584 			 * later with this mblk if ipif_lookup_addr chooses
4585 			 * to defer processing.
4586 			 */
4587 			*mp->b_wptr++ = (char)connp->conn_ulp;
4588 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4589 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4590 			    &error, ipst)) != NULL) {
4591 				ipif_refrele(ipif);
4592 			} else if (error == EINPROGRESS) {
4593 				if (src_ire != NULL)
4594 					ire_refrele(src_ire);
4595 				return (EINPROGRESS);
4596 			} else if (CLASSD(src_addr)) {
4597 				error = 0;
4598 				if (src_ire != NULL)
4599 					ire_refrele(src_ire);
4600 				/*
4601 				 * (5) bind to multicast address.
4602 				 * Fake out the IRE returned to upper
4603 				 * layer to be a broadcast IRE.
4604 				 */
4605 				src_ire = ire_ctable_lookup(
4606 				    INADDR_BROADCAST, INADDR_ANY,
4607 				    IRE_BROADCAST, NULL, zoneid, NULL,
4608 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4609 				    ipst);
4610 				if (src_ire == NULL || !ire_requested)
4611 					error = EADDRNOTAVAIL;
4612 			} else {
4613 				/*
4614 				 * Not a valid address for bind
4615 				 */
4616 				error = EADDRNOTAVAIL;
4617 			}
4618 			/*
4619 			 * Just to keep it consistent with the processing in
4620 			 * ip_bind_v4()
4621 			 */
4622 			mp->b_wptr--;
4623 		}
4624 		if (error) {
4625 			/* Red Alert!  Attempting to be a bogon! */
4626 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4627 			    ntohl(src_addr)));
4628 			goto bad_addr;
4629 		}
4630 	}
4631 
4632 	/*
4633 	 * Allow setting new policies. For example, disconnects come
4634 	 * down as ipa_t bind. As we would have set conn_policy_cached
4635 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4636 	 * can change after the disconnect.
4637 	 */
4638 	connp->conn_policy_cached = B_FALSE;
4639 
4640 	/*
4641 	 * If not fanout_insert this was just an address verification
4642 	 */
4643 	if (fanout_insert) {
4644 		/*
4645 		 * The addresses have been verified. Time to insert in
4646 		 * the correct fanout list.
4647 		 */
4648 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4649 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4650 		connp->conn_lport = lport;
4651 		connp->conn_fport = 0;
4652 		/*
4653 		 * Do we need to add a check to reject Multicast packets
4654 		 *
4655 		 * We need to make sure that the conn_recv is set to a non-null
4656 		 * value before we insert the conn into the classifier table.
4657 		 * This is to avoid a race with an incoming packet which does an
4658 		 * ipcl_classify().
4659 		 */
4660 		if (*mp->b_wptr == IPPROTO_TCP)
4661 			connp->conn_recv = tcp_conn_request;
4662 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4663 	}
4664 
4665 	if (error == 0) {
4666 		if (ire_requested) {
4667 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4668 				error = -1;
4669 				/* Falls through to bad_addr */
4670 			}
4671 		} else if (ipsec_policy_set) {
4672 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4673 				error = -1;
4674 				/* Falls through to bad_addr */
4675 			}
4676 		}
4677 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4678 		connp->conn_recv = tcp_input;
4679 	}
4680 bad_addr:
4681 	if (error != 0) {
4682 		if (connp->conn_anon_port) {
4683 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4684 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4685 			    B_FALSE);
4686 		}
4687 		connp->conn_mlp_type = mlptSingle;
4688 	}
4689 	if (src_ire != NULL)
4690 		IRE_REFRELE(src_ire);
4691 	if (ipsec_policy_set) {
4692 		ASSERT(policy_mp == mp->b_cont);
4693 		ASSERT(policy_mp != NULL);
4694 		freeb(policy_mp);
4695 		/*
4696 		 * As of now assume that nothing else accompanies
4697 		 * IPSEC_POLICY_SET.
4698 		 */
4699 		mp->b_cont = NULL;
4700 	}
4701 	return (error);
4702 }
4703 
4704 /*
4705  * Verify that both the source and destination addresses
4706  * are valid.  If verify_dst is false, then the destination address may be
4707  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4708  * destination reachability, while tunnels do not.
4709  * Note that we allow connect to broadcast and multicast
4710  * addresses when ire_requested is set. Thus the ULP
4711  * has to check for IRE_BROADCAST and multicast.
4712  *
4713  * Returns zero if ok.
4714  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4715  * (for use with TSYSERR reply).
4716  *
4717  * Note: lport and fport are in network byte order.
4718  */
4719 int
4720 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4721     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4722     boolean_t ire_requested, boolean_t ipsec_policy_set,
4723     boolean_t fanout_insert, boolean_t verify_dst)
4724 {
4725 	ire_t		*src_ire;
4726 	ire_t		*dst_ire;
4727 	int		error = 0;
4728 	int 		protocol;
4729 	mblk_t		*policy_mp;
4730 	ire_t		*sire = NULL;
4731 	ire_t		*md_dst_ire = NULL;
4732 	ire_t		*lso_dst_ire = NULL;
4733 	ill_t		*ill = NULL;
4734 	zoneid_t	zoneid;
4735 	ipaddr_t	src_addr = *src_addrp;
4736 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4737 
4738 	src_ire = dst_ire = NULL;
4739 	protocol = *mp->b_wptr & 0xFF;
4740 
4741 	/*
4742 	 * If we never got a disconnect before, clear it now.
4743 	 */
4744 	connp->conn_fully_bound = B_FALSE;
4745 
4746 	if (ipsec_policy_set) {
4747 		policy_mp = mp->b_cont;
4748 	}
4749 
4750 	zoneid = IPCL_ZONEID(connp);
4751 
4752 	if (CLASSD(dst_addr)) {
4753 		/* Pick up an IRE_BROADCAST */
4754 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4755 		    NULL, zoneid, MBLK_GETLABEL(mp),
4756 		    (MATCH_IRE_RECURSIVE |
4757 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4758 		    MATCH_IRE_SECATTR), ipst);
4759 	} else {
4760 		/*
4761 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4762 		 * and onlink ipif is not found set ENETUNREACH error.
4763 		 */
4764 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4765 			ipif_t *ipif;
4766 
4767 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4768 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4769 			if (ipif == NULL) {
4770 				error = ENETUNREACH;
4771 				goto bad_addr;
4772 			}
4773 			ipif_refrele(ipif);
4774 		}
4775 
4776 		if (connp->conn_nexthop_set) {
4777 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4778 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4779 			    MATCH_IRE_SECATTR, ipst);
4780 		} else {
4781 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4782 			    &sire, zoneid, MBLK_GETLABEL(mp),
4783 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4784 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4785 			    MATCH_IRE_SECATTR), ipst);
4786 		}
4787 	}
4788 	/*
4789 	 * dst_ire can't be a broadcast when not ire_requested.
4790 	 * We also prevent ire's with src address INADDR_ANY to
4791 	 * be used, which are created temporarily for
4792 	 * sending out packets from endpoints that have
4793 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4794 	 * reachable.  If verify_dst is false, the destination needn't be
4795 	 * reachable.
4796 	 *
4797 	 * If we match on a reject or black hole, then we've got a
4798 	 * local failure.  May as well fail out the connect() attempt,
4799 	 * since it's never going to succeed.
4800 	 */
4801 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4802 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4803 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4804 		/*
4805 		 * If we're verifying destination reachability, we always want
4806 		 * to complain here.
4807 		 *
4808 		 * If we're not verifying destination reachability but the
4809 		 * destination has a route, we still want to fail on the
4810 		 * temporary address and broadcast address tests.
4811 		 */
4812 		if (verify_dst || (dst_ire != NULL)) {
4813 			if (ip_debug > 2) {
4814 				pr_addr_dbg("ip_bind_connected: bad connected "
4815 				    "dst %s\n", AF_INET, &dst_addr);
4816 			}
4817 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4818 				error = ENETUNREACH;
4819 			else
4820 				error = EHOSTUNREACH;
4821 			goto bad_addr;
4822 		}
4823 	}
4824 
4825 	/*
4826 	 * We now know that routing will allow us to reach the destination.
4827 	 * Check whether Trusted Solaris policy allows communication with this
4828 	 * host, and pretend that the destination is unreachable if not.
4829 	 *
4830 	 * This is never a problem for TCP, since that transport is known to
4831 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4832 	 * handling.  If the remote is unreachable, it will be detected at that
4833 	 * point, so there's no reason to check it here.
4834 	 *
4835 	 * Note that for sendto (and other datagram-oriented friends), this
4836 	 * check is done as part of the data path label computation instead.
4837 	 * The check here is just to make non-TCP connect() report the right
4838 	 * error.
4839 	 */
4840 	if (dst_ire != NULL && is_system_labeled() &&
4841 	    !IPCL_IS_TCP(connp) &&
4842 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4843 	    connp->conn_mac_exempt, ipst) != 0) {
4844 		error = EHOSTUNREACH;
4845 		if (ip_debug > 2) {
4846 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4847 			    AF_INET, &dst_addr);
4848 		}
4849 		goto bad_addr;
4850 	}
4851 
4852 	/*
4853 	 * If the app does a connect(), it means that it will most likely
4854 	 * send more than 1 packet to the destination.  It makes sense
4855 	 * to clear the temporary flag.
4856 	 */
4857 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4858 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4859 		irb_t *irb = dst_ire->ire_bucket;
4860 
4861 		rw_enter(&irb->irb_lock, RW_WRITER);
4862 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4863 		irb->irb_tmp_ire_cnt--;
4864 		rw_exit(&irb->irb_lock);
4865 	}
4866 
4867 	/*
4868 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4869 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4870 	 * eligibility tests for passive connects are handled separately
4871 	 * through tcp_adapt_ire().  We do this before the source address
4872 	 * selection, because dst_ire may change after a call to
4873 	 * ipif_select_source().  This is a best-effort check, as the
4874 	 * packet for this connection may not actually go through
4875 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4876 	 * calling ip_newroute().  This is why we further check on the
4877 	 * IRE during LSO/Multidata packet transmission in
4878 	 * tcp_lsosend()/tcp_multisend().
4879 	 */
4880 	if (!ipsec_policy_set && dst_ire != NULL &&
4881 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4882 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4883 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4884 			lso_dst_ire = dst_ire;
4885 			IRE_REFHOLD(lso_dst_ire);
4886 		} else if (ipst->ips_ip_multidata_outbound &&
4887 		    ILL_MDT_CAPABLE(ill)) {
4888 			md_dst_ire = dst_ire;
4889 			IRE_REFHOLD(md_dst_ire);
4890 		}
4891 	}
4892 
4893 	if (dst_ire != NULL &&
4894 	    dst_ire->ire_type == IRE_LOCAL &&
4895 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4896 		/*
4897 		 * If the IRE belongs to a different zone, look for a matching
4898 		 * route in the forwarding table and use the source address from
4899 		 * that route.
4900 		 */
4901 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4902 		    zoneid, 0, NULL,
4903 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4904 		    MATCH_IRE_RJ_BHOLE, ipst);
4905 		if (src_ire == NULL) {
4906 			error = EHOSTUNREACH;
4907 			goto bad_addr;
4908 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4909 			if (!(src_ire->ire_type & IRE_HOST))
4910 				error = ENETUNREACH;
4911 			else
4912 				error = EHOSTUNREACH;
4913 			goto bad_addr;
4914 		}
4915 		if (src_addr == INADDR_ANY)
4916 			src_addr = src_ire->ire_src_addr;
4917 		ire_refrele(src_ire);
4918 		src_ire = NULL;
4919 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4920 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4921 			src_addr = sire->ire_src_addr;
4922 			ire_refrele(dst_ire);
4923 			dst_ire = sire;
4924 			sire = NULL;
4925 		} else {
4926 			/*
4927 			 * Pick a source address so that a proper inbound
4928 			 * load spreading would happen.
4929 			 */
4930 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4931 			ipif_t *src_ipif = NULL;
4932 			ire_t *ipif_ire;
4933 
4934 			/*
4935 			 * Supply a local source address such that inbound
4936 			 * load spreading happens.
4937 			 *
4938 			 * Determine the best source address on this ill for
4939 			 * the destination.
4940 			 *
4941 			 * 1) For broadcast, we should return a broadcast ire
4942 			 *    found above so that upper layers know that the
4943 			 *    destination address is a broadcast address.
4944 			 *
4945 			 * 2) If this is part of a group, select a better
4946 			 *    source address so that better inbound load
4947 			 *    balancing happens. Do the same if the ipif
4948 			 *    is DEPRECATED.
4949 			 *
4950 			 * 3) If the outgoing interface is part of a usesrc
4951 			 *    group, then try selecting a source address from
4952 			 *    the usesrc ILL.
4953 			 */
4954 			if ((dst_ire->ire_zoneid != zoneid &&
4955 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4956 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4957 			    ((dst_ill->ill_group != NULL) ||
4958 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4959 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4960 				/*
4961 				 * If the destination is reachable via a
4962 				 * given gateway, the selected source address
4963 				 * should be in the same subnet as the gateway.
4964 				 * Otherwise, the destination is not reachable.
4965 				 *
4966 				 * If there are no interfaces on the same subnet
4967 				 * as the destination, ipif_select_source gives
4968 				 * first non-deprecated interface which might be
4969 				 * on a different subnet than the gateway.
4970 				 * This is not desirable. Hence pass the dst_ire
4971 				 * source address to ipif_select_source.
4972 				 * It is sure that the destination is reachable
4973 				 * with the dst_ire source address subnet.
4974 				 * So passing dst_ire source address to
4975 				 * ipif_select_source will make sure that the
4976 				 * selected source will be on the same subnet
4977 				 * as dst_ire source address.
4978 				 */
4979 				ipaddr_t saddr =
4980 				    dst_ire->ire_ipif->ipif_src_addr;
4981 				src_ipif = ipif_select_source(dst_ill,
4982 				    saddr, zoneid);
4983 				if (src_ipif != NULL) {
4984 					if (IS_VNI(src_ipif->ipif_ill)) {
4985 						/*
4986 						 * For VNI there is no
4987 						 * interface route
4988 						 */
4989 						src_addr =
4990 						    src_ipif->ipif_src_addr;
4991 					} else {
4992 						ipif_ire =
4993 						    ipif_to_ire(src_ipif);
4994 						if (ipif_ire != NULL) {
4995 							IRE_REFRELE(dst_ire);
4996 							dst_ire = ipif_ire;
4997 						}
4998 						src_addr =
4999 						    dst_ire->ire_src_addr;
5000 					}
5001 					ipif_refrele(src_ipif);
5002 				} else {
5003 					src_addr = dst_ire->ire_src_addr;
5004 				}
5005 			} else {
5006 				src_addr = dst_ire->ire_src_addr;
5007 			}
5008 		}
5009 	}
5010 
5011 	/*
5012 	 * We do ire_route_lookup() here (and not
5013 	 * interface lookup as we assert that
5014 	 * src_addr should only come from an
5015 	 * UP interface for hard binding.
5016 	 */
5017 	ASSERT(src_ire == NULL);
5018 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5019 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5020 	/* src_ire must be a local|loopback */
5021 	if (!IRE_IS_LOCAL(src_ire)) {
5022 		if (ip_debug > 2) {
5023 			pr_addr_dbg("ip_bind_connected: bad connected "
5024 			    "src %s\n", AF_INET, &src_addr);
5025 		}
5026 		error = EADDRNOTAVAIL;
5027 		goto bad_addr;
5028 	}
5029 
5030 	/*
5031 	 * If the source address is a loopback address, the
5032 	 * destination had best be local or multicast.
5033 	 * The transports that can't handle multicast will reject
5034 	 * those addresses.
5035 	 */
5036 	if (src_ire->ire_type == IRE_LOOPBACK &&
5037 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5038 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5039 		error = -1;
5040 		goto bad_addr;
5041 	}
5042 
5043 	/*
5044 	 * Allow setting new policies. For example, disconnects come
5045 	 * down as ipa_t bind. As we would have set conn_policy_cached
5046 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5047 	 * can change after the disconnect.
5048 	 */
5049 	connp->conn_policy_cached = B_FALSE;
5050 
5051 	/*
5052 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5053 	 * can handle their passed-in conn's.
5054 	 */
5055 
5056 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5057 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5058 	connp->conn_lport = lport;
5059 	connp->conn_fport = fport;
5060 	*src_addrp = src_addr;
5061 
5062 	ASSERT(!(ipsec_policy_set && ire_requested));
5063 	if (ire_requested) {
5064 		iulp_t *ulp_info = NULL;
5065 
5066 		/*
5067 		 * Note that sire will not be NULL if this is an off-link
5068 		 * connection and there is not cache for that dest yet.
5069 		 *
5070 		 * XXX Because of an existing bug, if there are multiple
5071 		 * default routes, the IRE returned now may not be the actual
5072 		 * default route used (default routes are chosen in a
5073 		 * round robin fashion).  So if the metrics for different
5074 		 * default routes are different, we may return the wrong
5075 		 * metrics.  This will not be a problem if the existing
5076 		 * bug is fixed.
5077 		 */
5078 		if (sire != NULL) {
5079 			ulp_info = &(sire->ire_uinfo);
5080 		}
5081 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5082 			error = -1;
5083 			goto bad_addr;
5084 		}
5085 	} else if (ipsec_policy_set) {
5086 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5087 			error = -1;
5088 			goto bad_addr;
5089 		}
5090 	}
5091 
5092 	/*
5093 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5094 	 * we'll cache that.  If we don't, we'll inherit global policy.
5095 	 *
5096 	 * We can't insert until the conn reflects the policy. Note that
5097 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5098 	 * connections where we don't have a policy. This is to prevent
5099 	 * global policy lookups in the inbound path.
5100 	 *
5101 	 * If we insert before we set conn_policy_cached,
5102 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5103 	 * because global policy cound be non-empty. We normally call
5104 	 * ipsec_check_policy() for conn_policy_cached connections only if
5105 	 * ipc_in_enforce_policy is set. But in this case,
5106 	 * conn_policy_cached can get set anytime since we made the
5107 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5108 	 * called, which will make the above assumption false.  Thus, we
5109 	 * need to insert after we set conn_policy_cached.
5110 	 */
5111 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5112 		goto bad_addr;
5113 
5114 	if (fanout_insert) {
5115 		/*
5116 		 * The addresses have been verified. Time to insert in
5117 		 * the correct fanout list.
5118 		 * We need to make sure that the conn_recv is set to a non-null
5119 		 * value before we insert into the classifier table to avoid a
5120 		 * race with an incoming packet which does an ipcl_classify().
5121 		 */
5122 		if (protocol == IPPROTO_TCP)
5123 			connp->conn_recv = tcp_input;
5124 		error = ipcl_conn_insert(connp, protocol, src_addr,
5125 		    dst_addr, connp->conn_ports);
5126 	}
5127 
5128 	if (error == 0) {
5129 		connp->conn_fully_bound = B_TRUE;
5130 		/*
5131 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5132 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5133 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5134 		 * ip_xxinfo_return(), which performs further checks
5135 		 * against them and upon success, returns the LSO/MDT info
5136 		 * mblk which we will attach to the bind acknowledgment.
5137 		 */
5138 		if (lso_dst_ire != NULL) {
5139 			mblk_t *lsoinfo_mp;
5140 
5141 			ASSERT(ill->ill_lso_capab != NULL);
5142 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5143 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5144 				linkb(mp, lsoinfo_mp);
5145 		} else if (md_dst_ire != NULL) {
5146 			mblk_t *mdinfo_mp;
5147 
5148 			ASSERT(ill->ill_mdt_capab != NULL);
5149 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5150 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5151 				linkb(mp, mdinfo_mp);
5152 		}
5153 	}
5154 bad_addr:
5155 	if (ipsec_policy_set) {
5156 		ASSERT(policy_mp == mp->b_cont);
5157 		ASSERT(policy_mp != NULL);
5158 		freeb(policy_mp);
5159 		/*
5160 		 * As of now assume that nothing else accompanies
5161 		 * IPSEC_POLICY_SET.
5162 		 */
5163 		mp->b_cont = NULL;
5164 	}
5165 	if (src_ire != NULL)
5166 		IRE_REFRELE(src_ire);
5167 	if (dst_ire != NULL)
5168 		IRE_REFRELE(dst_ire);
5169 	if (sire != NULL)
5170 		IRE_REFRELE(sire);
5171 	if (md_dst_ire != NULL)
5172 		IRE_REFRELE(md_dst_ire);
5173 	if (lso_dst_ire != NULL)
5174 		IRE_REFRELE(lso_dst_ire);
5175 	return (error);
5176 }
5177 
5178 /*
5179  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5180  * Prefers dst_ire over src_ire.
5181  */
5182 static boolean_t
5183 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5184 {
5185 	mblk_t	*mp1;
5186 	ire_t *ret_ire = NULL;
5187 
5188 	mp1 = mp->b_cont;
5189 	ASSERT(mp1 != NULL);
5190 
5191 	if (ire != NULL) {
5192 		/*
5193 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5194 		 * appended mblk. Its <upper protocol>'s
5195 		 * job to make sure there is room.
5196 		 */
5197 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5198 			return (0);
5199 
5200 		mp1->b_datap->db_type = IRE_DB_TYPE;
5201 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5202 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5203 		ret_ire = (ire_t *)mp1->b_rptr;
5204 		/*
5205 		 * Pass the latest setting of the ip_path_mtu_discovery and
5206 		 * copy the ulp info if any.
5207 		 */
5208 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5209 		    IPH_DF : 0;
5210 		if (ulp_info != NULL) {
5211 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5212 			    sizeof (iulp_t));
5213 		}
5214 		ret_ire->ire_mp = mp1;
5215 	} else {
5216 		/*
5217 		 * No IRE was found. Remove IRE mblk.
5218 		 */
5219 		mp->b_cont = mp1->b_cont;
5220 		freeb(mp1);
5221 	}
5222 
5223 	return (1);
5224 }
5225 
5226 /*
5227  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5228  * the final piece where we don't.  Return a pointer to the first mblk in the
5229  * result, and update the pointer to the next mblk to chew on.  If anything
5230  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5231  * NULL pointer.
5232  */
5233 mblk_t *
5234 ip_carve_mp(mblk_t **mpp, ssize_t len)
5235 {
5236 	mblk_t	*mp0;
5237 	mblk_t	*mp1;
5238 	mblk_t	*mp2;
5239 
5240 	if (!len || !mpp || !(mp0 = *mpp))
5241 		return (NULL);
5242 	/* If we aren't going to consume the first mblk, we need a dup. */
5243 	if (mp0->b_wptr - mp0->b_rptr > len) {
5244 		mp1 = dupb(mp0);
5245 		if (mp1) {
5246 			/* Partition the data between the two mblks. */
5247 			mp1->b_wptr = mp1->b_rptr + len;
5248 			mp0->b_rptr = mp1->b_wptr;
5249 			/*
5250 			 * after adjustments if mblk not consumed is now
5251 			 * unaligned, try to align it. If this fails free
5252 			 * all messages and let upper layer recover.
5253 			 */
5254 			if (!OK_32PTR(mp0->b_rptr)) {
5255 				if (!pullupmsg(mp0, -1)) {
5256 					freemsg(mp0);
5257 					freemsg(mp1);
5258 					*mpp = NULL;
5259 					return (NULL);
5260 				}
5261 			}
5262 		}
5263 		return (mp1);
5264 	}
5265 	/* Eat through as many mblks as we need to get len bytes. */
5266 	len -= mp0->b_wptr - mp0->b_rptr;
5267 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5268 		if (mp2->b_wptr - mp2->b_rptr > len) {
5269 			/*
5270 			 * We won't consume the entire last mblk.  Like
5271 			 * above, dup and partition it.
5272 			 */
5273 			mp1->b_cont = dupb(mp2);
5274 			mp1 = mp1->b_cont;
5275 			if (!mp1) {
5276 				/*
5277 				 * Trouble.  Rather than go to a lot of
5278 				 * trouble to clean up, we free the messages.
5279 				 * This won't be any worse than losing it on
5280 				 * the wire.
5281 				 */
5282 				freemsg(mp0);
5283 				freemsg(mp2);
5284 				*mpp = NULL;
5285 				return (NULL);
5286 			}
5287 			mp1->b_wptr = mp1->b_rptr + len;
5288 			mp2->b_rptr = mp1->b_wptr;
5289 			/*
5290 			 * after adjustments if mblk not consumed is now
5291 			 * unaligned, try to align it. If this fails free
5292 			 * all messages and let upper layer recover.
5293 			 */
5294 			if (!OK_32PTR(mp2->b_rptr)) {
5295 				if (!pullupmsg(mp2, -1)) {
5296 					freemsg(mp0);
5297 					freemsg(mp2);
5298 					*mpp = NULL;
5299 					return (NULL);
5300 				}
5301 			}
5302 			*mpp = mp2;
5303 			return (mp0);
5304 		}
5305 		/* Decrement len by the amount we just got. */
5306 		len -= mp2->b_wptr - mp2->b_rptr;
5307 	}
5308 	/*
5309 	 * len should be reduced to zero now.  If not our caller has
5310 	 * screwed up.
5311 	 */
5312 	if (len) {
5313 		/* Shouldn't happen! */
5314 		freemsg(mp0);
5315 		*mpp = NULL;
5316 		return (NULL);
5317 	}
5318 	/*
5319 	 * We consumed up to exactly the end of an mblk.  Detach the part
5320 	 * we are returning from the rest of the chain.
5321 	 */
5322 	mp1->b_cont = NULL;
5323 	*mpp = mp2;
5324 	return (mp0);
5325 }
5326 
5327 /* The ill stream is being unplumbed. Called from ip_close */
5328 int
5329 ip_modclose(ill_t *ill)
5330 {
5331 	boolean_t success;
5332 	ipsq_t	*ipsq;
5333 	ipif_t	*ipif;
5334 	queue_t	*q = ill->ill_rq;
5335 	ip_stack_t	*ipst = ill->ill_ipst;
5336 	clock_t timeout;
5337 
5338 	/*
5339 	 * Wait for the ACKs of all deferred control messages to be processed.
5340 	 * In particular, we wait for a potential capability reset initiated
5341 	 * in ip_sioctl_plink() to complete before proceeding.
5342 	 *
5343 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5344 	 * in case the driver never replies.
5345 	 */
5346 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5347 	mutex_enter(&ill->ill_lock);
5348 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5349 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5350 			/* Timeout */
5351 			break;
5352 		}
5353 	}
5354 	mutex_exit(&ill->ill_lock);
5355 
5356 	/*
5357 	 * Forcibly enter the ipsq after some delay. This is to take
5358 	 * care of the case when some ioctl does not complete because
5359 	 * we sent a control message to the driver and it did not
5360 	 * send us a reply. We want to be able to at least unplumb
5361 	 * and replumb rather than force the user to reboot the system.
5362 	 */
5363 	success = ipsq_enter(ill, B_FALSE);
5364 
5365 	/*
5366 	 * Open/close/push/pop is guaranteed to be single threaded
5367 	 * per stream by STREAMS. FS guarantees that all references
5368 	 * from top are gone before close is called. So there can't
5369 	 * be another close thread that has set CONDEMNED on this ill.
5370 	 * and cause ipsq_enter to return failure.
5371 	 */
5372 	ASSERT(success);
5373 	ipsq = ill->ill_phyint->phyint_ipsq;
5374 
5375 	/*
5376 	 * Mark it condemned. No new reference will be made to this ill.
5377 	 * Lookup functions will return an error. Threads that try to
5378 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5379 	 * that the refcnt will drop down to zero.
5380 	 */
5381 	mutex_enter(&ill->ill_lock);
5382 	ill->ill_state_flags |= ILL_CONDEMNED;
5383 	for (ipif = ill->ill_ipif; ipif != NULL;
5384 	    ipif = ipif->ipif_next) {
5385 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5386 	}
5387 	/*
5388 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5389 	 * returns  error if ILL_CONDEMNED is set
5390 	 */
5391 	cv_broadcast(&ill->ill_cv);
5392 	mutex_exit(&ill->ill_lock);
5393 
5394 	/*
5395 	 * Send all the deferred DLPI messages downstream which came in
5396 	 * during the small window right before ipsq_enter(). We do this
5397 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5398 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5399 	 */
5400 	ill_dlpi_send_deferred(ill);
5401 
5402 	/*
5403 	 * Shut down fragmentation reassembly.
5404 	 * ill_frag_timer won't start a timer again.
5405 	 * Now cancel any existing timer
5406 	 */
5407 	(void) untimeout(ill->ill_frag_timer_id);
5408 	(void) ill_frag_timeout(ill, 0);
5409 
5410 	/*
5411 	 * If MOVE was in progress, clear the
5412 	 * move_in_progress fields also.
5413 	 */
5414 	if (ill->ill_move_in_progress) {
5415 		ILL_CLEAR_MOVE(ill);
5416 	}
5417 
5418 	/*
5419 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5420 	 * this ill. Then wait for the refcnts to drop to zero.
5421 	 * ill_is_quiescent checks whether the ill is really quiescent.
5422 	 * Then make sure that threads that are waiting to enter the
5423 	 * ipsq have seen the error returned by ipsq_enter and have
5424 	 * gone away. Then we call ill_delete_tail which does the
5425 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5426 	 */
5427 	ill_delete(ill);
5428 	mutex_enter(&ill->ill_lock);
5429 	while (!ill_is_quiescent(ill))
5430 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5431 	while (ill->ill_waiters)
5432 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5433 
5434 	mutex_exit(&ill->ill_lock);
5435 
5436 	/*
5437 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5438 	 * it held until the end of the function since the cleanup
5439 	 * below needs to be able to use the ip_stack_t.
5440 	 */
5441 	netstack_hold(ipst->ips_netstack);
5442 
5443 	/* qprocsoff is called in ill_delete_tail */
5444 	ill_delete_tail(ill);
5445 	ASSERT(ill->ill_ipst == NULL);
5446 
5447 	/*
5448 	 * Walk through all upper (conn) streams and qenable
5449 	 * those that have queued data.
5450 	 * close synchronization needs this to
5451 	 * be done to ensure that all upper layers blocked
5452 	 * due to flow control to the closing device
5453 	 * get unblocked.
5454 	 */
5455 	ip1dbg(("ip_wsrv: walking\n"));
5456 	conn_walk_drain(ipst);
5457 
5458 	mutex_enter(&ipst->ips_ip_mi_lock);
5459 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5460 	mutex_exit(&ipst->ips_ip_mi_lock);
5461 
5462 	/*
5463 	 * credp could be null if the open didn't succeed and ip_modopen
5464 	 * itself calls ip_close.
5465 	 */
5466 	if (ill->ill_credp != NULL)
5467 		crfree(ill->ill_credp);
5468 
5469 	mutex_enter(&ill->ill_lock);
5470 	ill_nic_info_dispatch(ill);
5471 	mutex_exit(&ill->ill_lock);
5472 
5473 	/*
5474 	 * Now we are done with the module close pieces that
5475 	 * need the netstack_t.
5476 	 */
5477 	netstack_rele(ipst->ips_netstack);
5478 
5479 	mi_close_free((IDP)ill);
5480 	q->q_ptr = WR(q)->q_ptr = NULL;
5481 
5482 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5483 
5484 	return (0);
5485 }
5486 
5487 /*
5488  * This is called as part of close() for both IP and UDP
5489  * in order to quiesce the conn.
5490  */
5491 void
5492 ip_quiesce_conn(conn_t *connp)
5493 {
5494 	boolean_t	drain_cleanup_reqd = B_FALSE;
5495 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5496 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5497 	ip_stack_t	*ipst;
5498 
5499 	ASSERT(!IPCL_IS_TCP(connp));
5500 	ipst = connp->conn_netstack->netstack_ip;
5501 
5502 	/*
5503 	 * Mark the conn as closing, and this conn must not be
5504 	 * inserted in future into any list. Eg. conn_drain_insert(),
5505 	 * won't insert this conn into the conn_drain_list.
5506 	 * Similarly ill_pending_mp_add() will not add any mp to
5507 	 * the pending mp list, after this conn has started closing.
5508 	 *
5509 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5510 	 * cannot get set henceforth.
5511 	 */
5512 	mutex_enter(&connp->conn_lock);
5513 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5514 	connp->conn_state_flags |= CONN_CLOSING;
5515 	if (connp->conn_idl != NULL)
5516 		drain_cleanup_reqd = B_TRUE;
5517 	if (connp->conn_oper_pending_ill != NULL)
5518 		conn_ioctl_cleanup_reqd = B_TRUE;
5519 	if (connp->conn_ilg_inuse != 0)
5520 		ilg_cleanup_reqd = B_TRUE;
5521 	mutex_exit(&connp->conn_lock);
5522 
5523 	if (IPCL_IS_UDP(connp))
5524 		udp_quiesce_conn(connp);
5525 
5526 	if (conn_ioctl_cleanup_reqd)
5527 		conn_ioctl_cleanup(connp);
5528 
5529 	if (is_system_labeled() && connp->conn_anon_port) {
5530 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5531 		    connp->conn_mlp_type, connp->conn_ulp,
5532 		    ntohs(connp->conn_lport), B_FALSE);
5533 		connp->conn_anon_port = 0;
5534 	}
5535 	connp->conn_mlp_type = mlptSingle;
5536 
5537 	/*
5538 	 * Remove this conn from any fanout list it is on.
5539 	 * and then wait for any threads currently operating
5540 	 * on this endpoint to finish
5541 	 */
5542 	ipcl_hash_remove(connp);
5543 
5544 	/*
5545 	 * Remove this conn from the drain list, and do
5546 	 * any other cleanup that may be required.
5547 	 * (Only non-tcp streams may have a non-null conn_idl.
5548 	 * TCP streams are never flow controlled, and
5549 	 * conn_idl will be null)
5550 	 */
5551 	if (drain_cleanup_reqd)
5552 		conn_drain_tail(connp, B_TRUE);
5553 
5554 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5555 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5556 		(void) ip_mrouter_done(NULL, ipst);
5557 
5558 	if (ilg_cleanup_reqd)
5559 		ilg_delete_all(connp);
5560 
5561 	conn_delete_ire(connp, NULL);
5562 
5563 	/*
5564 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5565 	 * callers from write side can't be there now because close
5566 	 * is in progress. The only other caller is ipcl_walk
5567 	 * which checks for the condemned flag.
5568 	 */
5569 	mutex_enter(&connp->conn_lock);
5570 	connp->conn_state_flags |= CONN_CONDEMNED;
5571 	while (connp->conn_ref != 1)
5572 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5573 	connp->conn_state_flags |= CONN_QUIESCED;
5574 	mutex_exit(&connp->conn_lock);
5575 }
5576 
5577 /* ARGSUSED */
5578 int
5579 ip_close(queue_t *q, int flags)
5580 {
5581 	conn_t		*connp;
5582 
5583 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5584 
5585 	/*
5586 	 * Call the appropriate delete routine depending on whether this is
5587 	 * a module or device.
5588 	 */
5589 	if (WR(q)->q_next != NULL) {
5590 		/* This is a module close */
5591 		return (ip_modclose((ill_t *)q->q_ptr));
5592 	}
5593 
5594 	connp = q->q_ptr;
5595 	ip_quiesce_conn(connp);
5596 
5597 	qprocsoff(q);
5598 
5599 	/*
5600 	 * Now we are truly single threaded on this stream, and can
5601 	 * delete the things hanging off the connp, and finally the connp.
5602 	 * We removed this connp from the fanout list, it cannot be
5603 	 * accessed thru the fanouts, and we already waited for the
5604 	 * conn_ref to drop to 0. We are already in close, so
5605 	 * there cannot be any other thread from the top. qprocsoff
5606 	 * has completed, and service has completed or won't run in
5607 	 * future.
5608 	 */
5609 	ASSERT(connp->conn_ref == 1);
5610 
5611 	/*
5612 	 * A conn which was previously marked as IPCL_UDP cannot
5613 	 * retain the flag because it would have been cleared by
5614 	 * udp_close().
5615 	 */
5616 	ASSERT(!IPCL_IS_UDP(connp));
5617 
5618 	if (connp->conn_latch != NULL) {
5619 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5620 		connp->conn_latch = NULL;
5621 	}
5622 	if (connp->conn_policy != NULL) {
5623 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5624 		connp->conn_policy = NULL;
5625 	}
5626 	if (connp->conn_ipsec_opt_mp != NULL) {
5627 		freemsg(connp->conn_ipsec_opt_mp);
5628 		connp->conn_ipsec_opt_mp = NULL;
5629 	}
5630 
5631 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5632 
5633 	connp->conn_ref--;
5634 	ipcl_conn_destroy(connp);
5635 
5636 	q->q_ptr = WR(q)->q_ptr = NULL;
5637 	return (0);
5638 }
5639 
5640 int
5641 ip_snmpmod_close(queue_t *q)
5642 {
5643 	conn_t *connp = Q_TO_CONN(q);
5644 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5645 
5646 	qprocsoff(q);
5647 
5648 	if (connp->conn_flags & IPCL_UDPMOD)
5649 		udp_close_free(connp);
5650 
5651 	if (connp->conn_cred != NULL) {
5652 		crfree(connp->conn_cred);
5653 		connp->conn_cred = NULL;
5654 	}
5655 	CONN_DEC_REF(connp);
5656 	q->q_ptr = WR(q)->q_ptr = NULL;
5657 	return (0);
5658 }
5659 
5660 /*
5661  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5662  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5663  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5664  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5665  * queues as we never enqueue messages there and we don't handle any ioctls.
5666  * Everything else is freed.
5667  */
5668 void
5669 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5670 {
5671 	conn_t	*connp = q->q_ptr;
5672 	pfi_t	setfn;
5673 	pfi_t	getfn;
5674 
5675 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5676 
5677 	switch (DB_TYPE(mp)) {
5678 	case M_PROTO:
5679 	case M_PCPROTO:
5680 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5681 		    ((((union T_primitives *)mp->b_rptr)->type ==
5682 		    T_SVR4_OPTMGMT_REQ) ||
5683 		    (((union T_primitives *)mp->b_rptr)->type ==
5684 		    T_OPTMGMT_REQ))) {
5685 			/*
5686 			 * This is the only TPI primitive supported. Its
5687 			 * handling does not require tcp_t, but it does require
5688 			 * conn_t to check permissions.
5689 			 */
5690 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5691 
5692 			if (connp->conn_flags & IPCL_TCPMOD) {
5693 				setfn = tcp_snmp_set;
5694 				getfn = tcp_snmp_get;
5695 			} else {
5696 				setfn = udp_snmp_set;
5697 				getfn = udp_snmp_get;
5698 			}
5699 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5700 				freemsg(mp);
5701 				return;
5702 			}
5703 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5704 		    != NULL)
5705 			qreply(q, mp);
5706 		break;
5707 	case M_FLUSH:
5708 	case M_IOCTL:
5709 		putnext(q, mp);
5710 		break;
5711 	default:
5712 		freemsg(mp);
5713 		break;
5714 	}
5715 }
5716 
5717 /* Return the IP checksum for the IP header at "iph". */
5718 uint16_t
5719 ip_csum_hdr(ipha_t *ipha)
5720 {
5721 	uint16_t	*uph;
5722 	uint32_t	sum;
5723 	int		opt_len;
5724 
5725 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5726 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5727 	uph = (uint16_t *)ipha;
5728 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5729 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5730 	if (opt_len > 0) {
5731 		do {
5732 			sum += uph[10];
5733 			sum += uph[11];
5734 			uph += 2;
5735 		} while (--opt_len);
5736 	}
5737 	sum = (sum & 0xFFFF) + (sum >> 16);
5738 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5739 	if (sum == 0xffff)
5740 		sum = 0;
5741 	return ((uint16_t)sum);
5742 }
5743 
5744 /*
5745  * Called when the module is about to be unloaded
5746  */
5747 void
5748 ip_ddi_destroy(void)
5749 {
5750 	tnet_fini();
5751 
5752 	sctp_ddi_g_destroy();
5753 	tcp_ddi_g_destroy();
5754 	ipsec_policy_g_destroy();
5755 	ipcl_g_destroy();
5756 	ip_net_g_destroy();
5757 	ip_ire_g_fini();
5758 	inet_minor_destroy(ip_minor_arena);
5759 
5760 	netstack_unregister(NS_IP);
5761 }
5762 
5763 /*
5764  * First step in cleanup.
5765  */
5766 /* ARGSUSED */
5767 static void
5768 ip_stack_shutdown(netstackid_t stackid, void *arg)
5769 {
5770 	ip_stack_t *ipst = (ip_stack_t *)arg;
5771 
5772 #ifdef NS_DEBUG
5773 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5774 #endif
5775 
5776 	/* Get rid of loopback interfaces and their IREs */
5777 	ip_loopback_cleanup(ipst);
5778 }
5779 
5780 /*
5781  * Free the IP stack instance.
5782  */
5783 static void
5784 ip_stack_fini(netstackid_t stackid, void *arg)
5785 {
5786 	ip_stack_t *ipst = (ip_stack_t *)arg;
5787 	int ret;
5788 
5789 #ifdef NS_DEBUG
5790 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5791 #endif
5792 	ipv4_hook_destroy(ipst);
5793 	ipv6_hook_destroy(ipst);
5794 	ip_net_destroy(ipst);
5795 
5796 	rw_destroy(&ipst->ips_srcid_lock);
5797 
5798 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5799 	ipst->ips_ip_mibkp = NULL;
5800 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5801 	ipst->ips_icmp_mibkp = NULL;
5802 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5803 	ipst->ips_ip_kstat = NULL;
5804 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5805 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5806 	ipst->ips_ip6_kstat = NULL;
5807 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5808 
5809 	nd_free(&ipst->ips_ip_g_nd);
5810 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5811 	ipst->ips_param_arr = NULL;
5812 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5813 	ipst->ips_ndp_arr = NULL;
5814 
5815 	ip_mrouter_stack_destroy(ipst);
5816 
5817 	mutex_destroy(&ipst->ips_ip_mi_lock);
5818 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5819 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5820 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5821 
5822 	ret = untimeout(ipst->ips_igmp_timeout_id);
5823 	if (ret == -1) {
5824 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5825 	} else {
5826 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5827 		ipst->ips_igmp_timeout_id = 0;
5828 	}
5829 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5830 	if (ret == -1) {
5831 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5832 	} else {
5833 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5834 		ipst->ips_igmp_slowtimeout_id = 0;
5835 	}
5836 	ret = untimeout(ipst->ips_mld_timeout_id);
5837 	if (ret == -1) {
5838 		ASSERT(ipst->ips_mld_timeout_id == 0);
5839 	} else {
5840 		ASSERT(ipst->ips_mld_timeout_id != 0);
5841 		ipst->ips_mld_timeout_id = 0;
5842 	}
5843 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5844 	if (ret == -1) {
5845 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5846 	} else {
5847 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5848 		ipst->ips_mld_slowtimeout_id = 0;
5849 	}
5850 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5851 	if (ret == -1) {
5852 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5853 	} else {
5854 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5855 		ipst->ips_ip_ire_expire_id = 0;
5856 	}
5857 
5858 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5859 	mutex_destroy(&ipst->ips_mld_timer_lock);
5860 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5861 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5862 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5863 	rw_destroy(&ipst->ips_ill_g_lock);
5864 
5865 	ip_ire_fini(ipst);
5866 	ip6_asp_free(ipst);
5867 	conn_drain_fini(ipst);
5868 	ipcl_destroy(ipst);
5869 
5870 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5871 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5872 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5873 	ipst->ips_ndp4 = NULL;
5874 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5875 	ipst->ips_ndp6 = NULL;
5876 
5877 	if (ipst->ips_loopback_ksp != NULL) {
5878 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5879 		ipst->ips_loopback_ksp = NULL;
5880 	}
5881 
5882 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5883 	ipst->ips_phyint_g_list = NULL;
5884 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5885 	ipst->ips_ill_g_heads = NULL;
5886 
5887 	kmem_free(ipst, sizeof (*ipst));
5888 }
5889 
5890 /*
5891  * Called when the IP kernel module is loaded into the kernel
5892  */
5893 void
5894 ip_ddi_init(void)
5895 {
5896 	TCP6_MAJ = ddi_name_to_major(TCP6);
5897 	TCP_MAJ	= ddi_name_to_major(TCP);
5898 	SCTP_MAJ = ddi_name_to_major(SCTP);
5899 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5900 
5901 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5902 
5903 	/*
5904 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5905 	 * initial devices: ip, ip6, tcp, tcp6.
5906 	 */
5907 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5908 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5909 		cmn_err(CE_PANIC,
5910 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5911 	}
5912 
5913 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5914 
5915 	ipcl_g_init();
5916 	ip_ire_g_init();
5917 	ip_net_g_init();
5918 
5919 #ifdef ILL_DEBUG
5920 	/* Default cleanup function */
5921 	ip_cleanup_func = ip_thread_exit;
5922 #endif
5923 
5924 	/*
5925 	 * We want to be informed each time a stack is created or
5926 	 * destroyed in the kernel, so we can maintain the
5927 	 * set of udp_stack_t's.
5928 	 */
5929 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5930 	    ip_stack_fini);
5931 
5932 	ipsec_policy_g_init();
5933 	tcp_ddi_g_init();
5934 	sctp_ddi_g_init();
5935 
5936 	tnet_init();
5937 }
5938 
5939 /*
5940  * Initialize the IP stack instance.
5941  */
5942 static void *
5943 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5944 {
5945 	ip_stack_t	*ipst;
5946 	ipparam_t	*pa;
5947 	ipndp_t		*na;
5948 
5949 #ifdef NS_DEBUG
5950 	printf("ip_stack_init(stack %d)\n", stackid);
5951 #endif
5952 
5953 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5954 	ipst->ips_netstack = ns;
5955 
5956 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5957 	    KM_SLEEP);
5958 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5959 	    KM_SLEEP);
5960 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5961 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5962 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5963 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5964 
5965 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5966 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5967 	ipst->ips_igmp_deferred_next = INFINITY;
5968 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5969 	ipst->ips_mld_deferred_next = INFINITY;
5970 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5971 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5972 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5973 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5974 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5975 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5976 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5977 
5978 	ipcl_init(ipst);
5979 	ip_ire_init(ipst);
5980 	ip6_asp_init(ipst);
5981 	ipif_init(ipst);
5982 	conn_drain_init(ipst);
5983 	ip_mrouter_stack_init(ipst);
5984 
5985 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5986 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5987 
5988 	ipst->ips_ip_multirt_log_interval = 1000;
5989 
5990 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5991 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5992 	ipst->ips_ill_index = 1;
5993 
5994 	ipst->ips_saved_ip_g_forward = -1;
5995 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5996 
5997 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5998 	ipst->ips_param_arr = pa;
5999 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6000 
6001 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6002 	ipst->ips_ndp_arr = na;
6003 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6004 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6005 	    (caddr_t)&ipst->ips_ip_g_forward;
6006 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6007 	    (caddr_t)&ipst->ips_ipv6_forward;
6008 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6009 	    "ip_cgtp_filter") == 0);
6010 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6011 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6012 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6013 	    "ipmp_hook_emulation") == 0);
6014 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6015 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6016 
6017 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6018 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6019 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6020 
6021 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6022 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6023 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6024 	ipst->ips_ip6_kstat =
6025 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6026 
6027 	ipst->ips_ipmp_enable_failback = B_TRUE;
6028 
6029 	ipst->ips_ip_src_id = 1;
6030 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6031 
6032 	ip_net_init(ipst, ns);
6033 	ipv4_hook_init(ipst);
6034 	ipv6_hook_init(ipst);
6035 
6036 	return (ipst);
6037 }
6038 
6039 /*
6040  * Allocate and initialize a DLPI template of the specified length.  (May be
6041  * called as writer.)
6042  */
6043 mblk_t *
6044 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6045 {
6046 	mblk_t	*mp;
6047 
6048 	mp = allocb(len, BPRI_MED);
6049 	if (!mp)
6050 		return (NULL);
6051 
6052 	/*
6053 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6054 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6055 	 * that other DLPI are M_PROTO.
6056 	 */
6057 	if (prim == DL_INFO_REQ) {
6058 		mp->b_datap->db_type = M_PCPROTO;
6059 	} else {
6060 		mp->b_datap->db_type = M_PROTO;
6061 	}
6062 
6063 	mp->b_wptr = mp->b_rptr + len;
6064 	bzero(mp->b_rptr, len);
6065 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6066 	return (mp);
6067 }
6068 
6069 const char *
6070 dlpi_prim_str(int prim)
6071 {
6072 	switch (prim) {
6073 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6074 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6075 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6076 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6077 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6078 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6079 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6080 	case DL_OK_ACK:		return ("DL_OK_ACK");
6081 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6082 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6083 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6084 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6085 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6086 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6087 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6088 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6089 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6090 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6091 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6092 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6093 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6094 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6095 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6096 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6097 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6098 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6099 	default:		return ("<unknown primitive>");
6100 	}
6101 }
6102 
6103 const char *
6104 dlpi_err_str(int err)
6105 {
6106 	switch (err) {
6107 	case DL_ACCESS:		return ("DL_ACCESS");
6108 	case DL_BADADDR:	return ("DL_BADADDR");
6109 	case DL_BADCORR:	return ("DL_BADCORR");
6110 	case DL_BADDATA:	return ("DL_BADDATA");
6111 	case DL_BADPPA:		return ("DL_BADPPA");
6112 	case DL_BADPRIM:	return ("DL_BADPRIM");
6113 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6114 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6115 	case DL_BADSAP:		return ("DL_BADSAP");
6116 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6117 	case DL_BOUND:		return ("DL_BOUND");
6118 	case DL_INITFAILED:	return ("DL_INITFAILED");
6119 	case DL_NOADDR:		return ("DL_NOADDR");
6120 	case DL_NOTINIT:	return ("DL_NOTINIT");
6121 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6122 	case DL_SYSERR:		return ("DL_SYSERR");
6123 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6124 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6125 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6126 	case DL_TOOMANY:	return ("DL_TOOMANY");
6127 	case DL_NOTENAB:	return ("DL_NOTENAB");
6128 	case DL_BUSY:		return ("DL_BUSY");
6129 	case DL_NOAUTO:		return ("DL_NOAUTO");
6130 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6131 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6132 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6133 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6134 	case DL_PENDING:	return ("DL_PENDING");
6135 	default:		return ("<unknown error>");
6136 	}
6137 }
6138 
6139 /*
6140  * Debug formatting routine.  Returns a character string representation of the
6141  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6142  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6143  *
6144  * Once the ndd table-printing interfaces are removed, this can be changed to
6145  * standard dotted-decimal form.
6146  */
6147 char *
6148 ip_dot_addr(ipaddr_t addr, char *buf)
6149 {
6150 	uint8_t *ap = (uint8_t *)&addr;
6151 
6152 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6153 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6154 	return (buf);
6155 }
6156 
6157 /*
6158  * Write the given MAC address as a printable string in the usual colon-
6159  * separated format.
6160  */
6161 const char *
6162 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6163 {
6164 	char *bp;
6165 
6166 	if (alen == 0 || buflen < 4)
6167 		return ("?");
6168 	bp = buf;
6169 	for (;;) {
6170 		/*
6171 		 * If there are more MAC address bytes available, but we won't
6172 		 * have any room to print them, then add "..." to the string
6173 		 * instead.  See below for the 'magic number' explanation.
6174 		 */
6175 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6176 			(void) strcpy(bp, "...");
6177 			break;
6178 		}
6179 		(void) sprintf(bp, "%02x", *addr++);
6180 		bp += 2;
6181 		if (--alen == 0)
6182 			break;
6183 		*bp++ = ':';
6184 		buflen -= 3;
6185 		/*
6186 		 * At this point, based on the first 'if' statement above,
6187 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6188 		 * buflen >= 4.  The first case leaves room for the final "xx"
6189 		 * number and trailing NUL byte.  The second leaves room for at
6190 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6191 		 * that statement.
6192 		 */
6193 	}
6194 	return (buf);
6195 }
6196 
6197 /*
6198  * Send an ICMP error after patching up the packet appropriately.  Returns
6199  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6200  */
6201 static boolean_t
6202 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6203     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6204     zoneid_t zoneid, ip_stack_t *ipst)
6205 {
6206 	ipha_t *ipha;
6207 	mblk_t *first_mp;
6208 	boolean_t secure;
6209 	unsigned char db_type;
6210 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6211 
6212 	first_mp = mp;
6213 	if (mctl_present) {
6214 		mp = mp->b_cont;
6215 		secure = ipsec_in_is_secure(first_mp);
6216 		ASSERT(mp != NULL);
6217 	} else {
6218 		/*
6219 		 * If this is an ICMP error being reported - which goes
6220 		 * up as M_CTLs, we need to convert them to M_DATA till
6221 		 * we finish checking with global policy because
6222 		 * ipsec_check_global_policy() assumes M_DATA as clear
6223 		 * and M_CTL as secure.
6224 		 */
6225 		db_type = DB_TYPE(mp);
6226 		DB_TYPE(mp) = M_DATA;
6227 		secure = B_FALSE;
6228 	}
6229 	/*
6230 	 * We are generating an icmp error for some inbound packet.
6231 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6232 	 * Before we generate an error, check with global policy
6233 	 * to see whether this is allowed to enter the system. As
6234 	 * there is no "conn", we are checking with global policy.
6235 	 */
6236 	ipha = (ipha_t *)mp->b_rptr;
6237 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6238 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6239 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6240 		if (first_mp == NULL)
6241 			return (B_FALSE);
6242 	}
6243 
6244 	if (!mctl_present)
6245 		DB_TYPE(mp) = db_type;
6246 
6247 	if (flags & IP_FF_SEND_ICMP) {
6248 		if (flags & IP_FF_HDR_COMPLETE) {
6249 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6250 				freemsg(first_mp);
6251 				return (B_TRUE);
6252 			}
6253 		}
6254 		if (flags & IP_FF_CKSUM) {
6255 			/*
6256 			 * Have to correct checksum since
6257 			 * the packet might have been
6258 			 * fragmented and the reassembly code in ip_rput
6259 			 * does not restore the IP checksum.
6260 			 */
6261 			ipha->ipha_hdr_checksum = 0;
6262 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6263 		}
6264 		switch (icmp_type) {
6265 		case ICMP_DEST_UNREACHABLE:
6266 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6267 			    ipst);
6268 			break;
6269 		default:
6270 			freemsg(first_mp);
6271 			break;
6272 		}
6273 	} else {
6274 		freemsg(first_mp);
6275 		return (B_FALSE);
6276 	}
6277 
6278 	return (B_TRUE);
6279 }
6280 
6281 /*
6282  * Used to send an ICMP error message when a packet is received for
6283  * a protocol that is not supported. The mblk passed as argument
6284  * is consumed by this function.
6285  */
6286 void
6287 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6288     ip_stack_t *ipst)
6289 {
6290 	mblk_t *mp;
6291 	ipha_t *ipha;
6292 	ill_t *ill;
6293 	ipsec_in_t *ii;
6294 
6295 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6296 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6297 
6298 	mp = ipsec_mp->b_cont;
6299 	ipsec_mp->b_cont = NULL;
6300 	ipha = (ipha_t *)mp->b_rptr;
6301 	/* Get ill from index in ipsec_in_t. */
6302 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6303 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6304 	    ipst);
6305 	if (ill != NULL) {
6306 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6307 			if (ip_fanout_send_icmp(q, mp, flags,
6308 			    ICMP_DEST_UNREACHABLE,
6309 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6310 				BUMP_MIB(ill->ill_ip_mib,
6311 				    ipIfStatsInUnknownProtos);
6312 			}
6313 		} else {
6314 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6315 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6316 			    0, B_FALSE, zoneid, ipst)) {
6317 				BUMP_MIB(ill->ill_ip_mib,
6318 				    ipIfStatsInUnknownProtos);
6319 			}
6320 		}
6321 		ill_refrele(ill);
6322 	} else { /* re-link for the freemsg() below. */
6323 		ipsec_mp->b_cont = mp;
6324 	}
6325 
6326 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6327 	freemsg(ipsec_mp);
6328 }
6329 
6330 /*
6331  * See if the inbound datagram has had IPsec processing applied to it.
6332  */
6333 boolean_t
6334 ipsec_in_is_secure(mblk_t *ipsec_mp)
6335 {
6336 	ipsec_in_t *ii;
6337 
6338 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6339 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6340 
6341 	if (ii->ipsec_in_loopback) {
6342 		return (ii->ipsec_in_secure);
6343 	} else {
6344 		return (ii->ipsec_in_ah_sa != NULL ||
6345 		    ii->ipsec_in_esp_sa != NULL ||
6346 		    ii->ipsec_in_decaps);
6347 	}
6348 }
6349 
6350 /*
6351  * Handle protocols with which IP is less intimate.  There
6352  * can be more than one stream bound to a particular
6353  * protocol.  When this is the case, normally each one gets a copy
6354  * of any incoming packets.
6355  *
6356  * IPsec NOTE :
6357  *
6358  * Don't allow a secure packet going up a non-secure connection.
6359  * We don't allow this because
6360  *
6361  * 1) Reply might go out in clear which will be dropped at
6362  *    the sending side.
6363  * 2) If the reply goes out in clear it will give the
6364  *    adversary enough information for getting the key in
6365  *    most of the cases.
6366  *
6367  * Moreover getting a secure packet when we expect clear
6368  * implies that SA's were added without checking for
6369  * policy on both ends. This should not happen once ISAKMP
6370  * is used to negotiate SAs as SAs will be added only after
6371  * verifying the policy.
6372  *
6373  * NOTE : If the packet was tunneled and not multicast we only send
6374  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6375  * back to delivering packets to AF_INET6 raw sockets.
6376  *
6377  * IPQoS Notes:
6378  * Once we have determined the client, invoke IPPF processing.
6379  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6380  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6381  * ip_policy will be false.
6382  *
6383  * Zones notes:
6384  * Currently only applications in the global zone can create raw sockets for
6385  * protocols other than ICMP. So unlike the broadcast / multicast case of
6386  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6387  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6388  */
6389 static void
6390 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6391     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6392     zoneid_t zoneid)
6393 {
6394 	queue_t	*rq;
6395 	mblk_t	*mp1, *first_mp1;
6396 	uint_t	protocol = ipha->ipha_protocol;
6397 	ipaddr_t dst;
6398 	boolean_t one_only;
6399 	mblk_t *first_mp = mp;
6400 	boolean_t secure;
6401 	uint32_t ill_index;
6402 	conn_t	*connp, *first_connp, *next_connp;
6403 	connf_t	*connfp;
6404 	boolean_t shared_addr;
6405 	mib2_ipIfStatsEntry_t *mibptr;
6406 	ip_stack_t *ipst = recv_ill->ill_ipst;
6407 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6408 
6409 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6410 	if (mctl_present) {
6411 		mp = first_mp->b_cont;
6412 		secure = ipsec_in_is_secure(first_mp);
6413 		ASSERT(mp != NULL);
6414 	} else {
6415 		secure = B_FALSE;
6416 	}
6417 	dst = ipha->ipha_dst;
6418 	/*
6419 	 * If the packet was tunneled and not multicast we only send to it
6420 	 * the first match.
6421 	 */
6422 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6423 	    !CLASSD(dst));
6424 
6425 	shared_addr = (zoneid == ALL_ZONES);
6426 	if (shared_addr) {
6427 		/*
6428 		 * We don't allow multilevel ports for raw IP, so no need to
6429 		 * check for that here.
6430 		 */
6431 		zoneid = tsol_packet_to_zoneid(mp);
6432 	}
6433 
6434 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6435 	mutex_enter(&connfp->connf_lock);
6436 	connp = connfp->connf_head;
6437 	for (connp = connfp->connf_head; connp != NULL;
6438 	    connp = connp->conn_next) {
6439 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6440 		    zoneid) &&
6441 		    (!is_system_labeled() ||
6442 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6443 		    connp))) {
6444 			break;
6445 		}
6446 	}
6447 
6448 	if (connp == NULL || connp->conn_upq == NULL) {
6449 		/*
6450 		 * No one bound to these addresses.  Is
6451 		 * there a client that wants all
6452 		 * unclaimed datagrams?
6453 		 */
6454 		mutex_exit(&connfp->connf_lock);
6455 		/*
6456 		 * Check for IPPROTO_ENCAP...
6457 		 */
6458 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6459 			/*
6460 			 * If an IPsec mblk is here on a multicast
6461 			 * tunnel (using ip_mroute stuff), check policy here,
6462 			 * THEN ship off to ip_mroute_decap().
6463 			 *
6464 			 * BTW,  If I match a configured IP-in-IP
6465 			 * tunnel, this path will not be reached, and
6466 			 * ip_mroute_decap will never be called.
6467 			 */
6468 			first_mp = ipsec_check_global_policy(first_mp, connp,
6469 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6470 			if (first_mp != NULL) {
6471 				if (mctl_present)
6472 					freeb(first_mp);
6473 				ip_mroute_decap(q, mp, ill);
6474 			} /* Else we already freed everything! */
6475 		} else {
6476 			/*
6477 			 * Otherwise send an ICMP protocol unreachable.
6478 			 */
6479 			if (ip_fanout_send_icmp(q, first_mp, flags,
6480 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6481 			    mctl_present, zoneid, ipst)) {
6482 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6483 			}
6484 		}
6485 		return;
6486 	}
6487 	CONN_INC_REF(connp);
6488 	first_connp = connp;
6489 
6490 	/*
6491 	 * Only send message to one tunnel driver by immediately
6492 	 * terminating the loop.
6493 	 */
6494 	connp = one_only ? NULL : connp->conn_next;
6495 
6496 	for (;;) {
6497 		while (connp != NULL) {
6498 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6499 			    flags, zoneid) &&
6500 			    (!is_system_labeled() ||
6501 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6502 			    shared_addr, connp)))
6503 				break;
6504 			connp = connp->conn_next;
6505 		}
6506 
6507 		/*
6508 		 * Copy the packet.
6509 		 */
6510 		if (connp == NULL || connp->conn_upq == NULL ||
6511 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6512 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6513 			/*
6514 			 * No more interested clients or memory
6515 			 * allocation failed
6516 			 */
6517 			connp = first_connp;
6518 			break;
6519 		}
6520 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6521 		CONN_INC_REF(connp);
6522 		mutex_exit(&connfp->connf_lock);
6523 		rq = connp->conn_rq;
6524 		if (!canputnext(rq)) {
6525 			if (flags & IP_FF_RAWIP) {
6526 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6527 			} else {
6528 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6529 			}
6530 
6531 			freemsg(first_mp1);
6532 		} else {
6533 			/*
6534 			 * Don't enforce here if we're an actual tunnel -
6535 			 * let "tun" do it instead.
6536 			 */
6537 			if (!IPCL_IS_IPTUN(connp) &&
6538 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6539 			    secure)) {
6540 				first_mp1 = ipsec_check_inbound_policy
6541 				    (first_mp1, connp, ipha, NULL,
6542 				    mctl_present);
6543 			}
6544 			if (first_mp1 != NULL) {
6545 				int in_flags = 0;
6546 				/*
6547 				 * ip_fanout_proto also gets called from
6548 				 * icmp_inbound_error_fanout, in which case
6549 				 * the msg type is M_CTL.  Don't add info
6550 				 * in this case for the time being. In future
6551 				 * when there is a need for knowing the
6552 				 * inbound iface index for ICMP error msgs,
6553 				 * then this can be changed.
6554 				 */
6555 				if (connp->conn_recvif)
6556 					in_flags = IPF_RECVIF;
6557 				/*
6558 				 * The ULP may support IP_RECVPKTINFO for both
6559 				 * IP v4 and v6 so pass the appropriate argument
6560 				 * based on conn IP version.
6561 				 */
6562 				if (connp->conn_ip_recvpktinfo) {
6563 					if (connp->conn_af_isv6) {
6564 						/*
6565 						 * V6 only needs index
6566 						 */
6567 						in_flags |= IPF_RECVIF;
6568 					} else {
6569 						/*
6570 						 * V4 needs index +
6571 						 * matching address.
6572 						 */
6573 						in_flags |= IPF_RECVADDR;
6574 					}
6575 				}
6576 				if ((in_flags != 0) &&
6577 				    (mp->b_datap->db_type != M_CTL)) {
6578 					/*
6579 					 * the actual data will be
6580 					 * contained in b_cont upon
6581 					 * successful return of the
6582 					 * following call else
6583 					 * original mblk is returned
6584 					 */
6585 					ASSERT(recv_ill != NULL);
6586 					mp1 = ip_add_info(mp1, recv_ill,
6587 					    in_flags, IPCL_ZONEID(connp), ipst);
6588 				}
6589 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6590 				if (mctl_present)
6591 					freeb(first_mp1);
6592 				putnext(rq, mp1);
6593 			}
6594 		}
6595 		mutex_enter(&connfp->connf_lock);
6596 		/* Follow the next pointer before releasing the conn. */
6597 		next_connp = connp->conn_next;
6598 		CONN_DEC_REF(connp);
6599 		connp = next_connp;
6600 	}
6601 
6602 	/* Last one.  Send it upstream. */
6603 	mutex_exit(&connfp->connf_lock);
6604 
6605 	/*
6606 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6607 	 * will be set to false.
6608 	 */
6609 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6610 		ill_index = ill->ill_phyint->phyint_ifindex;
6611 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6612 		if (mp == NULL) {
6613 			CONN_DEC_REF(connp);
6614 			if (mctl_present) {
6615 				freeb(first_mp);
6616 			}
6617 			return;
6618 		}
6619 	}
6620 
6621 	rq = connp->conn_rq;
6622 	if (!canputnext(rq)) {
6623 		if (flags & IP_FF_RAWIP) {
6624 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6625 		} else {
6626 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6627 		}
6628 
6629 		freemsg(first_mp);
6630 	} else {
6631 		if (IPCL_IS_IPTUN(connp)) {
6632 			/*
6633 			 * Tunneled packet.  We enforce policy in the tunnel
6634 			 * module itself.
6635 			 *
6636 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6637 			 * a policy check.
6638 			 */
6639 			putnext(rq, first_mp);
6640 			CONN_DEC_REF(connp);
6641 			return;
6642 		}
6643 
6644 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6645 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6646 			    ipha, NULL, mctl_present);
6647 		}
6648 
6649 		if (first_mp != NULL) {
6650 			int in_flags = 0;
6651 
6652 			/*
6653 			 * ip_fanout_proto also gets called
6654 			 * from icmp_inbound_error_fanout, in
6655 			 * which case the msg type is M_CTL.
6656 			 * Don't add info in this case for time
6657 			 * being. In future when there is a
6658 			 * need for knowing the inbound iface
6659 			 * index for ICMP error msgs, then this
6660 			 * can be changed
6661 			 */
6662 			if (connp->conn_recvif)
6663 				in_flags = IPF_RECVIF;
6664 			if (connp->conn_ip_recvpktinfo) {
6665 				if (connp->conn_af_isv6) {
6666 					/*
6667 					 * V6 only needs index
6668 					 */
6669 					in_flags |= IPF_RECVIF;
6670 				} else {
6671 					/*
6672 					 * V4 needs index +
6673 					 * matching address.
6674 					 */
6675 					in_flags |= IPF_RECVADDR;
6676 				}
6677 			}
6678 			if ((in_flags != 0) &&
6679 			    (mp->b_datap->db_type != M_CTL)) {
6680 
6681 				/*
6682 				 * the actual data will be contained in
6683 				 * b_cont upon successful return
6684 				 * of the following call else original
6685 				 * mblk is returned
6686 				 */
6687 				ASSERT(recv_ill != NULL);
6688 				mp = ip_add_info(mp, recv_ill,
6689 				    in_flags, IPCL_ZONEID(connp), ipst);
6690 			}
6691 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6692 			putnext(rq, mp);
6693 			if (mctl_present)
6694 				freeb(first_mp);
6695 		}
6696 	}
6697 	CONN_DEC_REF(connp);
6698 }
6699 
6700 /*
6701  * Fanout for TCP packets
6702  * The caller puts <fport, lport> in the ports parameter.
6703  *
6704  * IPQoS Notes
6705  * Before sending it to the client, invoke IPPF processing.
6706  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6707  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6708  * ip_policy is false.
6709  */
6710 static void
6711 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6712     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6713 {
6714 	mblk_t  *first_mp;
6715 	boolean_t secure;
6716 	uint32_t ill_index;
6717 	int	ip_hdr_len;
6718 	tcph_t	*tcph;
6719 	boolean_t syn_present = B_FALSE;
6720 	conn_t	*connp;
6721 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6722 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6723 
6724 	ASSERT(recv_ill != NULL);
6725 
6726 	first_mp = mp;
6727 	if (mctl_present) {
6728 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6729 		mp = first_mp->b_cont;
6730 		secure = ipsec_in_is_secure(first_mp);
6731 		ASSERT(mp != NULL);
6732 	} else {
6733 		secure = B_FALSE;
6734 	}
6735 
6736 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6737 
6738 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6739 	    zoneid, ipst)) == NULL) {
6740 		/*
6741 		 * No connected connection or listener. Send a
6742 		 * TH_RST via tcp_xmit_listeners_reset.
6743 		 */
6744 
6745 		/* Initiate IPPf processing, if needed. */
6746 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6747 			uint32_t ill_index;
6748 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6749 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6750 			if (first_mp == NULL)
6751 				return;
6752 		}
6753 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6754 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6755 		    zoneid));
6756 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6757 		    ipst->ips_netstack->netstack_tcp);
6758 		return;
6759 	}
6760 
6761 	/*
6762 	 * Allocate the SYN for the TCP connection here itself
6763 	 */
6764 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6765 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6766 		if (IPCL_IS_TCP(connp)) {
6767 			squeue_t *sqp;
6768 
6769 			/*
6770 			 * For fused tcp loopback, assign the eager's
6771 			 * squeue to be that of the active connect's.
6772 			 * Note that we don't check for IP_FF_LOOPBACK
6773 			 * here since this routine gets called only
6774 			 * for loopback (unlike the IPv6 counterpart).
6775 			 */
6776 			ASSERT(Q_TO_CONN(q) != NULL);
6777 			if (do_tcp_fusion &&
6778 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6779 			    !secure &&
6780 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6781 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6782 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6783 				sqp = Q_TO_CONN(q)->conn_sqp;
6784 			} else {
6785 				sqp = IP_SQUEUE_GET(lbolt);
6786 			}
6787 
6788 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6789 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6790 			syn_present = B_TRUE;
6791 		}
6792 	}
6793 
6794 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6795 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6796 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6797 		if ((flags & TH_RST) || (flags & TH_URG)) {
6798 			CONN_DEC_REF(connp);
6799 			freemsg(first_mp);
6800 			return;
6801 		}
6802 		if (flags & TH_ACK) {
6803 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6804 			    ipst->ips_netstack->netstack_tcp);
6805 			CONN_DEC_REF(connp);
6806 			return;
6807 		}
6808 
6809 		CONN_DEC_REF(connp);
6810 		freemsg(first_mp);
6811 		return;
6812 	}
6813 
6814 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6815 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6816 		    NULL, mctl_present);
6817 		if (first_mp == NULL) {
6818 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6819 			CONN_DEC_REF(connp);
6820 			return;
6821 		}
6822 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6823 			ASSERT(syn_present);
6824 			if (mctl_present) {
6825 				ASSERT(first_mp != mp);
6826 				first_mp->b_datap->db_struioflag |=
6827 				    STRUIO_POLICY;
6828 			} else {
6829 				ASSERT(first_mp == mp);
6830 				mp->b_datap->db_struioflag &=
6831 				    ~STRUIO_EAGER;
6832 				mp->b_datap->db_struioflag |=
6833 				    STRUIO_POLICY;
6834 			}
6835 		} else {
6836 			/*
6837 			 * Discard first_mp early since we're dealing with a
6838 			 * fully-connected conn_t and tcp doesn't do policy in
6839 			 * this case.
6840 			 */
6841 			if (mctl_present) {
6842 				freeb(first_mp);
6843 				mctl_present = B_FALSE;
6844 			}
6845 			first_mp = mp;
6846 		}
6847 	}
6848 
6849 	/*
6850 	 * Initiate policy processing here if needed. If we get here from
6851 	 * icmp_inbound_error_fanout, ip_policy is false.
6852 	 */
6853 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6854 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6855 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6856 		if (mp == NULL) {
6857 			CONN_DEC_REF(connp);
6858 			if (mctl_present)
6859 				freeb(first_mp);
6860 			return;
6861 		} else if (mctl_present) {
6862 			ASSERT(first_mp != mp);
6863 			first_mp->b_cont = mp;
6864 		} else {
6865 			first_mp = mp;
6866 		}
6867 	}
6868 
6869 
6870 
6871 	/* Handle socket options. */
6872 	if (!syn_present &&
6873 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6874 		/* Add header */
6875 		ASSERT(recv_ill != NULL);
6876 		/*
6877 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6878 		 * IPF_RECVIF.
6879 		 */
6880 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6881 		    ipst);
6882 		if (mp == NULL) {
6883 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6884 			CONN_DEC_REF(connp);
6885 			if (mctl_present)
6886 				freeb(first_mp);
6887 			return;
6888 		} else if (mctl_present) {
6889 			/*
6890 			 * ip_add_info might return a new mp.
6891 			 */
6892 			ASSERT(first_mp != mp);
6893 			first_mp->b_cont = mp;
6894 		} else {
6895 			first_mp = mp;
6896 		}
6897 	}
6898 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6899 	if (IPCL_IS_TCP(connp)) {
6900 		/* do not drain, certain use cases can blow the stack */
6901 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6902 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6903 	} else {
6904 		putnext(connp->conn_rq, first_mp);
6905 		CONN_DEC_REF(connp);
6906 	}
6907 }
6908 
6909 /*
6910  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6911  * pass it along to ESP if the SPI is non-zero.
6912  *
6913  * One of three things can happen, all of which affect the passed-in mblk:
6914  *
6915  * 1.) The packet is stock UDP and has had its zero-SPI stripped.  Return TRUE.
6916  *     (NOTE:  ICMP messages that go through here just get returned.)
6917  *
6918  * 2.) The packet is ESP-in-UDP, has been transformed into an equivalent
6919  *     ESP packet, and is passed along to ESP.  Return FALSE.
6920  *
6921  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6922  */
6923 static boolean_t
6924 zero_spi_check(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
6925     ill_t *recv_ill, ipsec_stack_t *ipss)
6926 {
6927 	int shift, plen, iph_len = IPH_HDR_LENGTH(ipha);
6928 	udpha_t *udpha;
6929 	uint32_t *spi;
6930 	uint8_t *orptr;
6931 	boolean_t udp_pkt, free_ire;
6932 
6933 	if (DB_TYPE(mp) == M_CTL) {
6934 		/*
6935 		 * ICMP message with UDP inside.  Don't bother stripping, just
6936 		 * send it up.
6937 		 *
6938 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6939 		 * to ignore errors set by ICMP anyway ('cause they might be
6940 		 * forged), but that's the app's decision, not ours.
6941 		 */
6942 
6943 		/* Bunch of reality checks for DEBUG kernels... */
6944 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6945 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6946 		ASSERT((uint8_t *)ipha != mp->b_rptr);
6947 
6948 		return (B_TRUE);
6949 	}
6950 
6951 	ASSERT((uint8_t *)ipha == mp->b_rptr);
6952 	plen = ntohs(ipha->ipha_length);
6953 
6954 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6955 		/*
6956 		 * Most likely a keepalive for the benefit of an intervening
6957 		 * NAT.  These aren't for us, per se, so drop it.
6958 		 *
6959 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6960 		 * byte packets (keepalives are 1-byte), but we'll drop them
6961 		 * also.
6962 		 */
6963 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6964 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6965 		return (B_FALSE);
6966 	}
6967 
6968 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6969 		mblk_t *tmp = msgpullup(mp, -1);
6970 
6971 		/* might as well pull it all up - it might be ESP. */
6972 		if (tmp == NULL) {
6973 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6974 			    DROPPER(ipss, ipds_esp_nomem),
6975 			    &ipss->ipsec_dropper);
6976 			return (B_FALSE);
6977 		}
6978 		freemsg(mp);
6979 		mp = tmp;
6980 	}
6981 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6982 	if (*spi == 0) {
6983 		/* UDP packet - remove 0-spi. */
6984 		shift = sizeof (uint32_t);
6985 	} else {
6986 		/* ESP-in-UDP packet - reduce to ESP. */
6987 		ipha->ipha_protocol = IPPROTO_ESP;
6988 		shift = sizeof (udpha_t);
6989 	}
6990 
6991 	/* Fix IP header */
6992 	ipha->ipha_length = htons(plen - shift);
6993 	ipha->ipha_hdr_checksum = 0;
6994 
6995 	orptr = mp->b_rptr;
6996 	mp->b_rptr += shift;
6997 
6998 	if (*spi == 0) {
6999 		ASSERT((uint8_t *)ipha == orptr);
7000 		udpha = (udpha_t *)(orptr + iph_len);
7001 		udpha->uha_length = htons(plen - shift - iph_len);
7002 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7003 		udp_pkt = B_TRUE;
7004 	} else {
7005 		udp_pkt = B_FALSE;
7006 	}
7007 	ovbcopy(orptr, orptr + shift, iph_len);
7008 	if (!udp_pkt) /* Punt up for ESP processing. */ {
7009 		ipha = (ipha_t *)(orptr + shift);
7010 
7011 		free_ire = (ire == NULL);
7012 		if (free_ire) {
7013 			/* Re-acquire ire. */
7014 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7015 			    ipss->ipsec_netstack->netstack_ip);
7016 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7017 				if (ire != NULL)
7018 					ire_refrele(ire);
7019 				/*
7020 				 * Do a regular freemsg(), as this is an IP
7021 				 * error (no local route) not an IPsec one.
7022 				 */
7023 				freemsg(mp);
7024 			}
7025 		}
7026 
7027 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
7028 		if (free_ire)
7029 			ire_refrele(ire);
7030 	}
7031 
7032 	return (udp_pkt);
7033 }
7034 
7035 /*
7036  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7037  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7038  * Caller is responsible for dropping references to the conn, and freeing
7039  * first_mp.
7040  *
7041  * IPQoS Notes
7042  * Before sending it to the client, invoke IPPF processing. Policy processing
7043  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7044  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7045  * ip_wput_local, ip_policy is false.
7046  */
7047 static void
7048 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7049     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7050     boolean_t ip_policy)
7051 {
7052 	boolean_t	mctl_present = (first_mp != NULL);
7053 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7054 	uint32_t	ill_index;
7055 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7056 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7057 
7058 	ASSERT(ill != NULL);
7059 
7060 	if (mctl_present)
7061 		first_mp->b_cont = mp;
7062 	else
7063 		first_mp = mp;
7064 
7065 	if (CONN_UDP_FLOWCTLD(connp)) {
7066 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7067 		freemsg(first_mp);
7068 		return;
7069 	}
7070 
7071 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7072 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7073 		    NULL, mctl_present);
7074 		if (first_mp == NULL) {
7075 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7076 			return;	/* Freed by ipsec_check_inbound_policy(). */
7077 		}
7078 	}
7079 	if (mctl_present)
7080 		freeb(first_mp);
7081 
7082 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7083 	if (connp->conn_udp->udp_nat_t_endpoint) {
7084 		if (mctl_present) {
7085 			/* mctl_present *shouldn't* happen. */
7086 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7087 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7088 			    &ipss->ipsec_dropper);
7089 			return;
7090 		}
7091 
7092 		if (!zero_spi_check(ill->ill_rq, mp, ipha, NULL, recv_ill,
7093 		    ipss)) {
7094 			return;
7095 		}
7096 	}
7097 
7098 	/* Handle options. */
7099 	if (connp->conn_recvif)
7100 		in_flags = IPF_RECVIF;
7101 	/*
7102 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7103 	 * passed to ip_add_info is based on IP version of connp.
7104 	 */
7105 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7106 		if (connp->conn_af_isv6) {
7107 			/*
7108 			 * V6 only needs index
7109 			 */
7110 			in_flags |= IPF_RECVIF;
7111 		} else {
7112 			/*
7113 			 * V4 needs index + matching address.
7114 			 */
7115 			in_flags |= IPF_RECVADDR;
7116 		}
7117 	}
7118 
7119 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7120 		in_flags |= IPF_RECVSLLA;
7121 
7122 	/*
7123 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7124 	 * freed if the packet is dropped. The caller will do so.
7125 	 */
7126 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7127 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7128 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7129 		if (mp == NULL) {
7130 			return;
7131 		}
7132 	}
7133 	if ((in_flags != 0) &&
7134 	    (mp->b_datap->db_type != M_CTL)) {
7135 		/*
7136 		 * The actual data will be contained in b_cont
7137 		 * upon successful return of the following call
7138 		 * else original mblk is returned
7139 		 */
7140 		ASSERT(recv_ill != NULL);
7141 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7142 		    ipst);
7143 	}
7144 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7145 	/* Send it upstream */
7146 	CONN_UDP_RECV(connp, mp);
7147 }
7148 
7149 /*
7150  * Fanout for UDP packets.
7151  * The caller puts <fport, lport> in the ports parameter.
7152  *
7153  * If SO_REUSEADDR is set all multicast and broadcast packets
7154  * will be delivered to all streams bound to the same port.
7155  *
7156  * Zones notes:
7157  * Multicast and broadcast packets will be distributed to streams in all zones.
7158  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7159  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7160  * packets. To maintain this behavior with multiple zones, the conns are grouped
7161  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7162  * each zone. If unset, all the following conns in the same zone are skipped.
7163  */
7164 static void
7165 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7166     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7167     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7168 {
7169 	uint32_t	dstport, srcport;
7170 	ipaddr_t	dst;
7171 	mblk_t		*first_mp;
7172 	boolean_t	secure;
7173 	in6_addr_t	v6src;
7174 	conn_t		*connp;
7175 	connf_t		*connfp;
7176 	conn_t		*first_connp;
7177 	conn_t		*next_connp;
7178 	mblk_t		*mp1, *first_mp1;
7179 	ipaddr_t	src;
7180 	zoneid_t	last_zoneid;
7181 	boolean_t	reuseaddr;
7182 	boolean_t	shared_addr;
7183 	ip_stack_t	*ipst;
7184 
7185 	ASSERT(recv_ill != NULL);
7186 	ipst = recv_ill->ill_ipst;
7187 
7188 	first_mp = mp;
7189 	if (mctl_present) {
7190 		mp = first_mp->b_cont;
7191 		first_mp->b_cont = NULL;
7192 		secure = ipsec_in_is_secure(first_mp);
7193 		ASSERT(mp != NULL);
7194 	} else {
7195 		first_mp = NULL;
7196 		secure = B_FALSE;
7197 	}
7198 
7199 	/* Extract ports in net byte order */
7200 	dstport = htons(ntohl(ports) & 0xFFFF);
7201 	srcport = htons(ntohl(ports) >> 16);
7202 	dst = ipha->ipha_dst;
7203 	src = ipha->ipha_src;
7204 
7205 	shared_addr = (zoneid == ALL_ZONES);
7206 	if (shared_addr) {
7207 		/*
7208 		 * No need to handle exclusive-stack zones since ALL_ZONES
7209 		 * only applies to the shared stack.
7210 		 */
7211 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7212 		if (zoneid == ALL_ZONES)
7213 			zoneid = tsol_packet_to_zoneid(mp);
7214 	}
7215 
7216 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7217 	mutex_enter(&connfp->connf_lock);
7218 	connp = connfp->connf_head;
7219 	if (!broadcast && !CLASSD(dst)) {
7220 		/*
7221 		 * Not broadcast or multicast. Send to the one (first)
7222 		 * client we find. No need to check conn_wantpacket()
7223 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7224 		 * IPv4 unicast packets.
7225 		 */
7226 		while ((connp != NULL) &&
7227 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7228 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7229 			connp = connp->conn_next;
7230 		}
7231 
7232 		if (connp == NULL || connp->conn_upq == NULL)
7233 			goto notfound;
7234 
7235 		if (is_system_labeled() &&
7236 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7237 		    connp))
7238 			goto notfound;
7239 
7240 		CONN_INC_REF(connp);
7241 		mutex_exit(&connfp->connf_lock);
7242 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7243 		    flags, recv_ill, ip_policy);
7244 		IP_STAT(ipst, ip_udp_fannorm);
7245 		CONN_DEC_REF(connp);
7246 		return;
7247 	}
7248 
7249 	/*
7250 	 * Broadcast and multicast case
7251 	 *
7252 	 * Need to check conn_wantpacket().
7253 	 * If SO_REUSEADDR has been set on the first we send the
7254 	 * packet to all clients that have joined the group and
7255 	 * match the port.
7256 	 */
7257 
7258 	while (connp != NULL) {
7259 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7260 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7261 		    (!is_system_labeled() ||
7262 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7263 		    connp)))
7264 			break;
7265 		connp = connp->conn_next;
7266 	}
7267 
7268 	if (connp == NULL || connp->conn_upq == NULL)
7269 		goto notfound;
7270 
7271 	first_connp = connp;
7272 	/*
7273 	 * When SO_REUSEADDR is not set, send the packet only to the first
7274 	 * matching connection in its zone by keeping track of the zoneid.
7275 	 */
7276 	reuseaddr = first_connp->conn_reuseaddr;
7277 	last_zoneid = first_connp->conn_zoneid;
7278 
7279 	CONN_INC_REF(connp);
7280 	connp = connp->conn_next;
7281 	for (;;) {
7282 		while (connp != NULL) {
7283 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7284 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7285 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7286 			    (!is_system_labeled() ||
7287 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7288 			    shared_addr, connp)))
7289 				break;
7290 			connp = connp->conn_next;
7291 		}
7292 		/*
7293 		 * Just copy the data part alone. The mctl part is
7294 		 * needed just for verifying policy and it is never
7295 		 * sent up.
7296 		 */
7297 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7298 		    ((mp1 = copymsg(mp)) == NULL))) {
7299 			/*
7300 			 * No more interested clients or memory
7301 			 * allocation failed
7302 			 */
7303 			connp = first_connp;
7304 			break;
7305 		}
7306 		if (connp->conn_zoneid != last_zoneid) {
7307 			/*
7308 			 * Update the zoneid so that the packet isn't sent to
7309 			 * any more conns in the same zone unless SO_REUSEADDR
7310 			 * is set.
7311 			 */
7312 			reuseaddr = connp->conn_reuseaddr;
7313 			last_zoneid = connp->conn_zoneid;
7314 		}
7315 		if (first_mp != NULL) {
7316 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7317 			    ipsec_info_type == IPSEC_IN);
7318 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7319 			    ipst->ips_netstack);
7320 			if (first_mp1 == NULL) {
7321 				freemsg(mp1);
7322 				connp = first_connp;
7323 				break;
7324 			}
7325 		} else {
7326 			first_mp1 = NULL;
7327 		}
7328 		CONN_INC_REF(connp);
7329 		mutex_exit(&connfp->connf_lock);
7330 		/*
7331 		 * IPQoS notes: We don't send the packet for policy
7332 		 * processing here, will do it for the last one (below).
7333 		 * i.e. we do it per-packet now, but if we do policy
7334 		 * processing per-conn, then we would need to do it
7335 		 * here too.
7336 		 */
7337 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7338 		    ipha, flags, recv_ill, B_FALSE);
7339 		mutex_enter(&connfp->connf_lock);
7340 		/* Follow the next pointer before releasing the conn. */
7341 		next_connp = connp->conn_next;
7342 		IP_STAT(ipst, ip_udp_fanmb);
7343 		CONN_DEC_REF(connp);
7344 		connp = next_connp;
7345 	}
7346 
7347 	/* Last one.  Send it upstream. */
7348 	mutex_exit(&connfp->connf_lock);
7349 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7350 	    recv_ill, ip_policy);
7351 	IP_STAT(ipst, ip_udp_fanmb);
7352 	CONN_DEC_REF(connp);
7353 	return;
7354 
7355 notfound:
7356 
7357 	mutex_exit(&connfp->connf_lock);
7358 	IP_STAT(ipst, ip_udp_fanothers);
7359 	/*
7360 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7361 	 * have already been matched above, since they live in the IPv4
7362 	 * fanout tables. This implies we only need to
7363 	 * check for IPv6 in6addr_any endpoints here.
7364 	 * Thus we compare using ipv6_all_zeros instead of the destination
7365 	 * address, except for the multicast group membership lookup which
7366 	 * uses the IPv4 destination.
7367 	 */
7368 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7369 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7370 	mutex_enter(&connfp->connf_lock);
7371 	connp = connfp->connf_head;
7372 	if (!broadcast && !CLASSD(dst)) {
7373 		while (connp != NULL) {
7374 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7375 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7376 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7377 			    !connp->conn_ipv6_v6only)
7378 				break;
7379 			connp = connp->conn_next;
7380 		}
7381 
7382 		if (connp != NULL && is_system_labeled() &&
7383 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7384 		    connp))
7385 			connp = NULL;
7386 
7387 		if (connp == NULL || connp->conn_upq == NULL) {
7388 			/*
7389 			 * No one bound to this port.  Is
7390 			 * there a client that wants all
7391 			 * unclaimed datagrams?
7392 			 */
7393 			mutex_exit(&connfp->connf_lock);
7394 
7395 			if (mctl_present)
7396 				first_mp->b_cont = mp;
7397 			else
7398 				first_mp = mp;
7399 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7400 			    connf_head != NULL) {
7401 				ip_fanout_proto(q, first_mp, ill, ipha,
7402 				    flags | IP_FF_RAWIP, mctl_present,
7403 				    ip_policy, recv_ill, zoneid);
7404 			} else {
7405 				if (ip_fanout_send_icmp(q, first_mp, flags,
7406 				    ICMP_DEST_UNREACHABLE,
7407 				    ICMP_PORT_UNREACHABLE,
7408 				    mctl_present, zoneid, ipst)) {
7409 					BUMP_MIB(ill->ill_ip_mib,
7410 					    udpIfStatsNoPorts);
7411 				}
7412 			}
7413 			return;
7414 		}
7415 
7416 		CONN_INC_REF(connp);
7417 		mutex_exit(&connfp->connf_lock);
7418 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7419 		    flags, recv_ill, ip_policy);
7420 		CONN_DEC_REF(connp);
7421 		return;
7422 	}
7423 	/*
7424 	 * IPv4 multicast packet being delivered to an AF_INET6
7425 	 * in6addr_any endpoint.
7426 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7427 	 * and not conn_wantpacket_v6() since any multicast membership is
7428 	 * for an IPv4-mapped multicast address.
7429 	 * The packet is sent to all clients in all zones that have joined the
7430 	 * group and match the port.
7431 	 */
7432 	while (connp != NULL) {
7433 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7434 		    srcport, v6src) &&
7435 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7436 		    (!is_system_labeled() ||
7437 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7438 		    connp)))
7439 			break;
7440 		connp = connp->conn_next;
7441 	}
7442 
7443 	if (connp == NULL || connp->conn_upq == NULL) {
7444 		/*
7445 		 * No one bound to this port.  Is
7446 		 * there a client that wants all
7447 		 * unclaimed datagrams?
7448 		 */
7449 		mutex_exit(&connfp->connf_lock);
7450 
7451 		if (mctl_present)
7452 			first_mp->b_cont = mp;
7453 		else
7454 			first_mp = mp;
7455 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7456 		    NULL) {
7457 			ip_fanout_proto(q, first_mp, ill, ipha,
7458 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7459 			    recv_ill, zoneid);
7460 		} else {
7461 			/*
7462 			 * We used to attempt to send an icmp error here, but
7463 			 * since this is known to be a multicast packet
7464 			 * and we don't send icmp errors in response to
7465 			 * multicast, just drop the packet and give up sooner.
7466 			 */
7467 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7468 			freemsg(first_mp);
7469 		}
7470 		return;
7471 	}
7472 
7473 	first_connp = connp;
7474 
7475 	CONN_INC_REF(connp);
7476 	connp = connp->conn_next;
7477 	for (;;) {
7478 		while (connp != NULL) {
7479 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7480 			    ipv6_all_zeros, srcport, v6src) &&
7481 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7482 			    (!is_system_labeled() ||
7483 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7484 			    shared_addr, connp)))
7485 				break;
7486 			connp = connp->conn_next;
7487 		}
7488 		/*
7489 		 * Just copy the data part alone. The mctl part is
7490 		 * needed just for verifying policy and it is never
7491 		 * sent up.
7492 		 */
7493 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7494 		    ((mp1 = copymsg(mp)) == NULL))) {
7495 			/*
7496 			 * No more intested clients or memory
7497 			 * allocation failed
7498 			 */
7499 			connp = first_connp;
7500 			break;
7501 		}
7502 		if (first_mp != NULL) {
7503 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7504 			    ipsec_info_type == IPSEC_IN);
7505 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7506 			    ipst->ips_netstack);
7507 			if (first_mp1 == NULL) {
7508 				freemsg(mp1);
7509 				connp = first_connp;
7510 				break;
7511 			}
7512 		} else {
7513 			first_mp1 = NULL;
7514 		}
7515 		CONN_INC_REF(connp);
7516 		mutex_exit(&connfp->connf_lock);
7517 		/*
7518 		 * IPQoS notes: We don't send the packet for policy
7519 		 * processing here, will do it for the last one (below).
7520 		 * i.e. we do it per-packet now, but if we do policy
7521 		 * processing per-conn, then we would need to do it
7522 		 * here too.
7523 		 */
7524 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7525 		    ipha, flags, recv_ill, B_FALSE);
7526 		mutex_enter(&connfp->connf_lock);
7527 		/* Follow the next pointer before releasing the conn. */
7528 		next_connp = connp->conn_next;
7529 		CONN_DEC_REF(connp);
7530 		connp = next_connp;
7531 	}
7532 
7533 	/* Last one.  Send it upstream. */
7534 	mutex_exit(&connfp->connf_lock);
7535 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7536 	    recv_ill, ip_policy);
7537 	CONN_DEC_REF(connp);
7538 }
7539 
7540 /*
7541  * Complete the ip_wput header so that it
7542  * is possible to generate ICMP
7543  * errors.
7544  */
7545 int
7546 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7547 {
7548 	ire_t *ire;
7549 
7550 	if (ipha->ipha_src == INADDR_ANY) {
7551 		ire = ire_lookup_local(zoneid, ipst);
7552 		if (ire == NULL) {
7553 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7554 			return (1);
7555 		}
7556 		ipha->ipha_src = ire->ire_addr;
7557 		ire_refrele(ire);
7558 	}
7559 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7560 	ipha->ipha_hdr_checksum = 0;
7561 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7562 	return (0);
7563 }
7564 
7565 /*
7566  * Nobody should be sending
7567  * packets up this stream
7568  */
7569 static void
7570 ip_lrput(queue_t *q, mblk_t *mp)
7571 {
7572 	mblk_t *mp1;
7573 
7574 	switch (mp->b_datap->db_type) {
7575 	case M_FLUSH:
7576 		/* Turn around */
7577 		if (*mp->b_rptr & FLUSHW) {
7578 			*mp->b_rptr &= ~FLUSHR;
7579 			qreply(q, mp);
7580 			return;
7581 		}
7582 		break;
7583 	}
7584 	/* Could receive messages that passed through ar_rput */
7585 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7586 		mp1->b_prev = mp1->b_next = NULL;
7587 	freemsg(mp);
7588 }
7589 
7590 /* Nobody should be sending packets down this stream */
7591 /* ARGSUSED */
7592 void
7593 ip_lwput(queue_t *q, mblk_t *mp)
7594 {
7595 	freemsg(mp);
7596 }
7597 
7598 /*
7599  * Move the first hop in any source route to ipha_dst and remove that part of
7600  * the source route.  Called by other protocols.  Errors in option formatting
7601  * are ignored - will be handled by ip_wput_options Return the final
7602  * destination (either ipha_dst or the last entry in a source route.)
7603  */
7604 ipaddr_t
7605 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7606 {
7607 	ipoptp_t	opts;
7608 	uchar_t		*opt;
7609 	uint8_t		optval;
7610 	uint8_t		optlen;
7611 	ipaddr_t	dst;
7612 	int		i;
7613 	ire_t		*ire;
7614 	ip_stack_t	*ipst = ns->netstack_ip;
7615 
7616 	ip2dbg(("ip_massage_options\n"));
7617 	dst = ipha->ipha_dst;
7618 	for (optval = ipoptp_first(&opts, ipha);
7619 	    optval != IPOPT_EOL;
7620 	    optval = ipoptp_next(&opts)) {
7621 		opt = opts.ipoptp_cur;
7622 		switch (optval) {
7623 			uint8_t off;
7624 		case IPOPT_SSRR:
7625 		case IPOPT_LSRR:
7626 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7627 				ip1dbg(("ip_massage_options: bad src route\n"));
7628 				break;
7629 			}
7630 			optlen = opts.ipoptp_len;
7631 			off = opt[IPOPT_OFFSET];
7632 			off--;
7633 		redo_srr:
7634 			if (optlen < IP_ADDR_LEN ||
7635 			    off > optlen - IP_ADDR_LEN) {
7636 				/* End of source route */
7637 				ip1dbg(("ip_massage_options: end of SR\n"));
7638 				break;
7639 			}
7640 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7641 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7642 			    ntohl(dst)));
7643 			/*
7644 			 * Check if our address is present more than
7645 			 * once as consecutive hops in source route.
7646 			 * XXX verify per-interface ip_forwarding
7647 			 * for source route?
7648 			 */
7649 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7650 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7651 			if (ire != NULL) {
7652 				ire_refrele(ire);
7653 				off += IP_ADDR_LEN;
7654 				goto redo_srr;
7655 			}
7656 			if (dst == htonl(INADDR_LOOPBACK)) {
7657 				ip1dbg(("ip_massage_options: loopback addr in "
7658 				    "source route!\n"));
7659 				break;
7660 			}
7661 			/*
7662 			 * Update ipha_dst to be the first hop and remove the
7663 			 * first hop from the source route (by overwriting
7664 			 * part of the option with NOP options).
7665 			 */
7666 			ipha->ipha_dst = dst;
7667 			/* Put the last entry in dst */
7668 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7669 			    3;
7670 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7671 
7672 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7673 			    ntohl(dst)));
7674 			/* Move down and overwrite */
7675 			opt[IP_ADDR_LEN] = opt[0];
7676 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7677 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7678 			for (i = 0; i < IP_ADDR_LEN; i++)
7679 				opt[i] = IPOPT_NOP;
7680 			break;
7681 		}
7682 	}
7683 	return (dst);
7684 }
7685 
7686 /*
7687  * Return the network mask
7688  * associated with the specified address.
7689  */
7690 ipaddr_t
7691 ip_net_mask(ipaddr_t addr)
7692 {
7693 	uchar_t	*up = (uchar_t *)&addr;
7694 	ipaddr_t mask = 0;
7695 	uchar_t	*maskp = (uchar_t *)&mask;
7696 
7697 #if defined(__i386) || defined(__amd64)
7698 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7699 #endif
7700 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7701 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7702 #endif
7703 	if (CLASSD(addr)) {
7704 		maskp[0] = 0xF0;
7705 		return (mask);
7706 	}
7707 	if (addr == 0)
7708 		return (0);
7709 	maskp[0] = 0xFF;
7710 	if ((up[0] & 0x80) == 0)
7711 		return (mask);
7712 
7713 	maskp[1] = 0xFF;
7714 	if ((up[0] & 0xC0) == 0x80)
7715 		return (mask);
7716 
7717 	maskp[2] = 0xFF;
7718 	if ((up[0] & 0xE0) == 0xC0)
7719 		return (mask);
7720 
7721 	/* Must be experimental or multicast, indicate as much */
7722 	return ((ipaddr_t)0);
7723 }
7724 
7725 /*
7726  * Select an ill for the packet by considering load spreading across
7727  * a different ill in the group if dst_ill is part of some group.
7728  */
7729 ill_t *
7730 ip_newroute_get_dst_ill(ill_t *dst_ill)
7731 {
7732 	ill_t *ill;
7733 
7734 	/*
7735 	 * We schedule irrespective of whether the source address is
7736 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7737 	 */
7738 	ill = illgrp_scheduler(dst_ill);
7739 	if (ill == NULL)
7740 		return (NULL);
7741 
7742 	/*
7743 	 * For groups with names ip_sioctl_groupname ensures that all
7744 	 * ills are of same type. For groups without names, ifgrp_insert
7745 	 * ensures this.
7746 	 */
7747 	ASSERT(dst_ill->ill_type == ill->ill_type);
7748 
7749 	return (ill);
7750 }
7751 
7752 /*
7753  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7754  */
7755 ill_t *
7756 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7757     ip_stack_t *ipst)
7758 {
7759 	ill_t *ret_ill;
7760 
7761 	ASSERT(ifindex != 0);
7762 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7763 	    ipst);
7764 	if (ret_ill == NULL ||
7765 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7766 		if (isv6) {
7767 			if (ill != NULL) {
7768 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7769 			} else {
7770 				BUMP_MIB(&ipst->ips_ip6_mib,
7771 				    ipIfStatsOutDiscards);
7772 			}
7773 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7774 			    "bad ifindex %d.\n", ifindex));
7775 		} else {
7776 			if (ill != NULL) {
7777 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7778 			} else {
7779 				BUMP_MIB(&ipst->ips_ip_mib,
7780 				    ipIfStatsOutDiscards);
7781 			}
7782 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7783 			    "bad ifindex %d.\n", ifindex));
7784 		}
7785 		if (ret_ill != NULL)
7786 			ill_refrele(ret_ill);
7787 		freemsg(first_mp);
7788 		return (NULL);
7789 	}
7790 
7791 	return (ret_ill);
7792 }
7793 
7794 /*
7795  * IPv4 -
7796  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7797  * out a packet to a destination address for which we do not have specific
7798  * (or sufficient) routing information.
7799  *
7800  * NOTE : These are the scopes of some of the variables that point at IRE,
7801  *	  which needs to be followed while making any future modifications
7802  *	  to avoid memory leaks.
7803  *
7804  *	- ire and sire are the entries looked up initially by
7805  *	  ire_ftable_lookup.
7806  *	- ipif_ire is used to hold the interface ire associated with
7807  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7808  *	  it before branching out to error paths.
7809  *	- save_ire is initialized before ire_create, so that ire returned
7810  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7811  *	  before breaking out of the switch.
7812  *
7813  *	Thus on failures, we have to REFRELE only ire and sire, if they
7814  *	are not NULL.
7815  */
7816 void
7817 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7818     zoneid_t zoneid, ip_stack_t *ipst)
7819 {
7820 	areq_t	*areq;
7821 	ipaddr_t gw = 0;
7822 	ire_t	*ire = NULL;
7823 	mblk_t	*res_mp;
7824 	ipaddr_t *addrp;
7825 	ipaddr_t nexthop_addr;
7826 	ipif_t  *src_ipif = NULL;
7827 	ill_t	*dst_ill = NULL;
7828 	ipha_t  *ipha;
7829 	ire_t	*sire = NULL;
7830 	mblk_t	*first_mp;
7831 	ire_t	*save_ire;
7832 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7833 	ushort_t ire_marks = 0;
7834 	boolean_t mctl_present;
7835 	ipsec_out_t *io;
7836 	mblk_t	*saved_mp;
7837 	ire_t	*first_sire = NULL;
7838 	mblk_t	*copy_mp = NULL;
7839 	mblk_t	*xmit_mp = NULL;
7840 	ipaddr_t save_dst;
7841 	uint32_t multirt_flags =
7842 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7843 	boolean_t multirt_is_resolvable;
7844 	boolean_t multirt_resolve_next;
7845 	boolean_t do_attach_ill = B_FALSE;
7846 	boolean_t ip_nexthop = B_FALSE;
7847 	tsol_ire_gw_secattr_t *attrp = NULL;
7848 	tsol_gcgrp_t *gcgrp = NULL;
7849 	tsol_gcgrp_addr_t ga;
7850 
7851 	if (ip_debug > 2) {
7852 		/* ip1dbg */
7853 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7854 	}
7855 
7856 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7857 	if (mctl_present) {
7858 		io = (ipsec_out_t *)first_mp->b_rptr;
7859 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7860 		ASSERT(zoneid == io->ipsec_out_zoneid);
7861 		ASSERT(zoneid != ALL_ZONES);
7862 	}
7863 
7864 	ipha = (ipha_t *)mp->b_rptr;
7865 
7866 	/* All multicast lookups come through ip_newroute_ipif() */
7867 	if (CLASSD(dst)) {
7868 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7869 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7870 		freemsg(first_mp);
7871 		return;
7872 	}
7873 
7874 	if (mctl_present && io->ipsec_out_attach_if) {
7875 		/* ip_grab_attach_ill returns a held ill */
7876 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7877 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7878 
7879 		/* Failure case frees things for us. */
7880 		if (attach_ill == NULL)
7881 			return;
7882 
7883 		/*
7884 		 * Check if we need an ire that will not be
7885 		 * looked up by anybody else i.e. HIDDEN.
7886 		 */
7887 		if (ill_is_probeonly(attach_ill))
7888 			ire_marks = IRE_MARK_HIDDEN;
7889 	}
7890 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7891 		ip_nexthop = B_TRUE;
7892 		nexthop_addr = io->ipsec_out_nexthop_addr;
7893 	}
7894 	/*
7895 	 * If this IRE is created for forwarding or it is not for
7896 	 * traffic for congestion controlled protocols, mark it as temporary.
7897 	 */
7898 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7899 		ire_marks |= IRE_MARK_TEMPORARY;
7900 
7901 	/*
7902 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7903 	 * chain until it gets the most specific information available.
7904 	 * For example, we know that there is no IRE_CACHE for this dest,
7905 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7906 	 * ire_ftable_lookup will look up the gateway, etc.
7907 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7908 	 * to the destination, of equal netmask length in the forward table,
7909 	 * will be recursively explored. If no information is available
7910 	 * for the final gateway of that route, we force the returned ire
7911 	 * to be equal to sire using MATCH_IRE_PARENT.
7912 	 * At least, in this case we have a starting point (in the buckets)
7913 	 * to look for other routes to the destination in the forward table.
7914 	 * This is actually used only for multirouting, where a list
7915 	 * of routes has to be processed in sequence.
7916 	 *
7917 	 * In the process of coming up with the most specific information,
7918 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7919 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7920 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7921 	 * Two caveats when handling incomplete ire's in ip_newroute:
7922 	 * - we should be careful when accessing its ire_nce (specifically
7923 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7924 	 * - not all legacy code path callers are prepared to handle
7925 	 *   incomplete ire's, so we should not create/add incomplete
7926 	 *   ire_cache entries here. (See discussion about temporary solution
7927 	 *   further below).
7928 	 *
7929 	 * In order to minimize packet dropping, and to preserve existing
7930 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7931 	 * gateway, and instead use the IF_RESOLVER ire to send out
7932 	 * another request to ARP (this is achieved by passing the
7933 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7934 	 * arp response comes back in ip_wput_nondata, we will create
7935 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7936 	 *
7937 	 * Note that this is a temporary solution; the correct solution is
7938 	 * to create an incomplete  per-dst ire_cache entry, and send the
7939 	 * packet out when the gw's nce is resolved. In order to achieve this,
7940 	 * all packet processing must have been completed prior to calling
7941 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7942 	 * to be modified to accomodate this solution.
7943 	 */
7944 	if (ip_nexthop) {
7945 		/*
7946 		 * The first time we come here, we look for an IRE_INTERFACE
7947 		 * entry for the specified nexthop, set the dst to be the
7948 		 * nexthop address and create an IRE_CACHE entry for the
7949 		 * nexthop. The next time around, we are able to find an
7950 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7951 		 * nexthop address and create an IRE_CACHE entry for the
7952 		 * destination address via the specified nexthop.
7953 		 */
7954 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7955 		    MBLK_GETLABEL(mp), ipst);
7956 		if (ire != NULL) {
7957 			gw = nexthop_addr;
7958 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7959 		} else {
7960 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7961 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7962 			    MBLK_GETLABEL(mp),
7963 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7964 			    ipst);
7965 			if (ire != NULL) {
7966 				dst = nexthop_addr;
7967 			}
7968 		}
7969 	} else if (attach_ill == NULL) {
7970 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7971 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7972 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7973 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7974 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7975 		    ipst);
7976 	} else {
7977 		/*
7978 		 * attach_ill is set only for communicating with
7979 		 * on-link hosts. So, don't look for DEFAULT.
7980 		 */
7981 		ipif_t	*attach_ipif;
7982 
7983 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7984 		if (attach_ipif == NULL) {
7985 			ill_refrele(attach_ill);
7986 			goto icmp_err_ret;
7987 		}
7988 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7989 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7990 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7991 		    MATCH_IRE_SECATTR, ipst);
7992 		ipif_refrele(attach_ipif);
7993 	}
7994 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7995 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7996 
7997 	/*
7998 	 * This loop is run only once in most cases.
7999 	 * We loop to resolve further routes only when the destination
8000 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8001 	 */
8002 	do {
8003 		/* Clear the previous iteration's values */
8004 		if (src_ipif != NULL) {
8005 			ipif_refrele(src_ipif);
8006 			src_ipif = NULL;
8007 		}
8008 		if (dst_ill != NULL) {
8009 			ill_refrele(dst_ill);
8010 			dst_ill = NULL;
8011 		}
8012 
8013 		multirt_resolve_next = B_FALSE;
8014 		/*
8015 		 * We check if packets have to be multirouted.
8016 		 * In this case, given the current <ire, sire> couple,
8017 		 * we look for the next suitable <ire, sire>.
8018 		 * This check is done in ire_multirt_lookup(),
8019 		 * which applies various criteria to find the next route
8020 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8021 		 * unchanged if it detects it has not been tried yet.
8022 		 */
8023 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8024 			ip3dbg(("ip_newroute: starting next_resolution "
8025 			    "with first_mp %p, tag %d\n",
8026 			    (void *)first_mp,
8027 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8028 
8029 			ASSERT(sire != NULL);
8030 			multirt_is_resolvable =
8031 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8032 			    MBLK_GETLABEL(mp), ipst);
8033 
8034 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8035 			    "ire %p, sire %p\n",
8036 			    multirt_is_resolvable,
8037 			    (void *)ire, (void *)sire));
8038 
8039 			if (!multirt_is_resolvable) {
8040 				/*
8041 				 * No more multirt route to resolve; give up
8042 				 * (all routes resolved or no more
8043 				 * resolvable routes).
8044 				 */
8045 				if (ire != NULL) {
8046 					ire_refrele(ire);
8047 					ire = NULL;
8048 				}
8049 			} else {
8050 				ASSERT(sire != NULL);
8051 				ASSERT(ire != NULL);
8052 				/*
8053 				 * We simply use first_sire as a flag that
8054 				 * indicates if a resolvable multirt route
8055 				 * has already been found.
8056 				 * If it is not the case, we may have to send
8057 				 * an ICMP error to report that the
8058 				 * destination is unreachable.
8059 				 * We do not IRE_REFHOLD first_sire.
8060 				 */
8061 				if (first_sire == NULL) {
8062 					first_sire = sire;
8063 				}
8064 			}
8065 		}
8066 		if (ire == NULL) {
8067 			if (ip_debug > 3) {
8068 				/* ip2dbg */
8069 				pr_addr_dbg("ip_newroute: "
8070 				    "can't resolve %s\n", AF_INET, &dst);
8071 			}
8072 			ip3dbg(("ip_newroute: "
8073 			    "ire %p, sire %p, first_sire %p\n",
8074 			    (void *)ire, (void *)sire, (void *)first_sire));
8075 
8076 			if (sire != NULL) {
8077 				ire_refrele(sire);
8078 				sire = NULL;
8079 			}
8080 
8081 			if (first_sire != NULL) {
8082 				/*
8083 				 * At least one multirt route has been found
8084 				 * in the same call to ip_newroute();
8085 				 * there is no need to report an ICMP error.
8086 				 * first_sire was not IRE_REFHOLDed.
8087 				 */
8088 				MULTIRT_DEBUG_UNTAG(first_mp);
8089 				freemsg(first_mp);
8090 				return;
8091 			}
8092 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8093 			    RTA_DST, ipst);
8094 			if (attach_ill != NULL)
8095 				ill_refrele(attach_ill);
8096 			goto icmp_err_ret;
8097 		}
8098 
8099 		/*
8100 		 * Verify that the returned IRE does not have either
8101 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8102 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8103 		 */
8104 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8105 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8106 			if (attach_ill != NULL)
8107 				ill_refrele(attach_ill);
8108 			goto icmp_err_ret;
8109 		}
8110 		/*
8111 		 * Increment the ire_ob_pkt_count field for ire if it is an
8112 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8113 		 * increment the same for the parent IRE, sire, if it is some
8114 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8115 		 */
8116 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8117 			UPDATE_OB_PKT_COUNT(ire);
8118 			ire->ire_last_used_time = lbolt;
8119 		}
8120 
8121 		if (sire != NULL) {
8122 			gw = sire->ire_gateway_addr;
8123 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8124 			    IRE_INTERFACE)) == 0);
8125 			UPDATE_OB_PKT_COUNT(sire);
8126 			sire->ire_last_used_time = lbolt;
8127 		}
8128 		/*
8129 		 * We have a route to reach the destination.
8130 		 *
8131 		 * 1) If the interface is part of ill group, try to get a new
8132 		 *    ill taking load spreading into account.
8133 		 *
8134 		 * 2) After selecting the ill, get a source address that
8135 		 *    might create good inbound load spreading.
8136 		 *    ipif_select_source does this for us.
8137 		 *
8138 		 * If the application specified the ill (ifindex), we still
8139 		 * load spread. Only if the packets needs to go out
8140 		 * specifically on a given ill e.g. binding to
8141 		 * IPIF_NOFAILOVER address, then we don't try to use a
8142 		 * different ill for load spreading.
8143 		 */
8144 		if (attach_ill == NULL) {
8145 			/*
8146 			 * Don't perform outbound load spreading in the
8147 			 * case of an RTF_MULTIRT route, as we actually
8148 			 * typically want to replicate outgoing packets
8149 			 * through particular interfaces.
8150 			 */
8151 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8152 				dst_ill = ire->ire_ipif->ipif_ill;
8153 				/* for uniformity */
8154 				ill_refhold(dst_ill);
8155 			} else {
8156 				/*
8157 				 * If we are here trying to create an IRE_CACHE
8158 				 * for an offlink destination and have the
8159 				 * IRE_CACHE for the next hop and the latter is
8160 				 * using virtual IP source address selection i.e
8161 				 * it's ire->ire_ipif is pointing to a virtual
8162 				 * network interface (vni) then
8163 				 * ip_newroute_get_dst_ll() will return the vni
8164 				 * interface as the dst_ill. Since the vni is
8165 				 * virtual i.e not associated with any physical
8166 				 * interface, it cannot be the dst_ill, hence
8167 				 * in such a case call ip_newroute_get_dst_ll()
8168 				 * with the stq_ill instead of the ire_ipif ILL.
8169 				 * The function returns a refheld ill.
8170 				 */
8171 				if ((ire->ire_type == IRE_CACHE) &&
8172 				    IS_VNI(ire->ire_ipif->ipif_ill))
8173 					dst_ill = ip_newroute_get_dst_ill(
8174 					    ire->ire_stq->q_ptr);
8175 				else
8176 					dst_ill = ip_newroute_get_dst_ill(
8177 					    ire->ire_ipif->ipif_ill);
8178 			}
8179 			if (dst_ill == NULL) {
8180 				if (ip_debug > 2) {
8181 					pr_addr_dbg("ip_newroute: "
8182 					    "no dst ill for dst"
8183 					    " %s\n", AF_INET, &dst);
8184 				}
8185 				goto icmp_err_ret;
8186 			}
8187 		} else {
8188 			dst_ill = ire->ire_ipif->ipif_ill;
8189 			/* for uniformity */
8190 			ill_refhold(dst_ill);
8191 			/*
8192 			 * We should have found a route matching ill as we
8193 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8194 			 * Rather than asserting, when there is a mismatch,
8195 			 * we just drop the packet.
8196 			 */
8197 			if (dst_ill != attach_ill) {
8198 				ip0dbg(("ip_newroute: Packet dropped as "
8199 				    "IPIF_NOFAILOVER ill is %s, "
8200 				    "ire->ire_ipif->ipif_ill is %s\n",
8201 				    attach_ill->ill_name,
8202 				    dst_ill->ill_name));
8203 				ill_refrele(attach_ill);
8204 				goto icmp_err_ret;
8205 			}
8206 		}
8207 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8208 		if (attach_ill != NULL) {
8209 			ill_refrele(attach_ill);
8210 			attach_ill = NULL;
8211 			do_attach_ill = B_TRUE;
8212 		}
8213 		ASSERT(dst_ill != NULL);
8214 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8215 
8216 		/*
8217 		 * Pick the best source address from dst_ill.
8218 		 *
8219 		 * 1) If it is part of a multipathing group, we would
8220 		 *    like to spread the inbound packets across different
8221 		 *    interfaces. ipif_select_source picks a random source
8222 		 *    across the different ills in the group.
8223 		 *
8224 		 * 2) If it is not part of a multipathing group, we try
8225 		 *    to pick the source address from the destination
8226 		 *    route. Clustering assumes that when we have multiple
8227 		 *    prefixes hosted on an interface, the prefix of the
8228 		 *    source address matches the prefix of the destination
8229 		 *    route. We do this only if the address is not
8230 		 *    DEPRECATED.
8231 		 *
8232 		 * 3) If the conn is in a different zone than the ire, we
8233 		 *    need to pick a source address from the right zone.
8234 		 *
8235 		 * NOTE : If we hit case (1) above, the prefix of the source
8236 		 *	  address picked may not match the prefix of the
8237 		 *	  destination routes prefix as ipif_select_source
8238 		 *	  does not look at "dst" while picking a source
8239 		 *	  address.
8240 		 *	  If we want the same behavior as (2), we will need
8241 		 *	  to change the behavior of ipif_select_source.
8242 		 */
8243 		ASSERT(src_ipif == NULL);
8244 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8245 			/*
8246 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8247 			 * Check that the ipif matching the requested source
8248 			 * address still exists.
8249 			 */
8250 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8251 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8252 		}
8253 		if (src_ipif == NULL) {
8254 			ire_marks |= IRE_MARK_USESRC_CHECK;
8255 			if ((dst_ill->ill_group != NULL) ||
8256 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8257 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8258 			    ire->ire_zoneid != ALL_ZONES) ||
8259 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8260 				/*
8261 				 * If the destination is reachable via a
8262 				 * given gateway, the selected source address
8263 				 * should be in the same subnet as the gateway.
8264 				 * Otherwise, the destination is not reachable.
8265 				 *
8266 				 * If there are no interfaces on the same subnet
8267 				 * as the destination, ipif_select_source gives
8268 				 * first non-deprecated interface which might be
8269 				 * on a different subnet than the gateway.
8270 				 * This is not desirable. Hence pass the dst_ire
8271 				 * source address to ipif_select_source.
8272 				 * It is sure that the destination is reachable
8273 				 * with the dst_ire source address subnet.
8274 				 * So passing dst_ire source address to
8275 				 * ipif_select_source will make sure that the
8276 				 * selected source will be on the same subnet
8277 				 * as dst_ire source address.
8278 				 */
8279 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8280 				src_ipif = ipif_select_source(dst_ill, saddr,
8281 				    zoneid);
8282 				if (src_ipif == NULL) {
8283 					if (ip_debug > 2) {
8284 						pr_addr_dbg("ip_newroute: "
8285 						    "no src for dst %s ",
8286 						    AF_INET, &dst);
8287 						printf("through interface %s\n",
8288 						    dst_ill->ill_name);
8289 					}
8290 					goto icmp_err_ret;
8291 				}
8292 			} else {
8293 				src_ipif = ire->ire_ipif;
8294 				ASSERT(src_ipif != NULL);
8295 				/* hold src_ipif for uniformity */
8296 				ipif_refhold(src_ipif);
8297 			}
8298 		}
8299 
8300 		/*
8301 		 * Assign a source address while we have the conn.
8302 		 * We can't have ip_wput_ire pick a source address when the
8303 		 * packet returns from arp since we need to look at
8304 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8305 		 * going through arp.
8306 		 *
8307 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8308 		 *	  it uses ip6i to store this information.
8309 		 */
8310 		if (ipha->ipha_src == INADDR_ANY &&
8311 		    (connp == NULL || !connp->conn_unspec_src)) {
8312 			ipha->ipha_src = src_ipif->ipif_src_addr;
8313 		}
8314 		if (ip_debug > 3) {
8315 			/* ip2dbg */
8316 			pr_addr_dbg("ip_newroute: first hop %s\n",
8317 			    AF_INET, &gw);
8318 		}
8319 		ip2dbg(("\tire type %s (%d)\n",
8320 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8321 
8322 		/*
8323 		 * The TTL of multirouted packets is bounded by the
8324 		 * ip_multirt_ttl ndd variable.
8325 		 */
8326 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8327 			/* Force TTL of multirouted packets */
8328 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8329 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8330 				ip2dbg(("ip_newroute: forcing multirt TTL "
8331 				    "to %d (was %d), dst 0x%08x\n",
8332 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8333 				    ntohl(sire->ire_addr)));
8334 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8335 			}
8336 		}
8337 		/*
8338 		 * At this point in ip_newroute(), ire is either the
8339 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8340 		 * destination or an IRE_INTERFACE type that should be used
8341 		 * to resolve an on-subnet destination or an on-subnet
8342 		 * next-hop gateway.
8343 		 *
8344 		 * In the IRE_CACHE case, we have the following :
8345 		 *
8346 		 * 1) src_ipif - used for getting a source address.
8347 		 *
8348 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8349 		 *    means packets using this IRE_CACHE will go out on
8350 		 *    dst_ill.
8351 		 *
8352 		 * 3) The IRE sire will point to the prefix that is the
8353 		 *    longest  matching route for the destination. These
8354 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8355 		 *
8356 		 *    The newly created IRE_CACHE entry for the off-subnet
8357 		 *    destination is tied to both the prefix route and the
8358 		 *    interface route used to resolve the next-hop gateway
8359 		 *    via the ire_phandle and ire_ihandle fields,
8360 		 *    respectively.
8361 		 *
8362 		 * In the IRE_INTERFACE case, we have the following :
8363 		 *
8364 		 * 1) src_ipif - used for getting a source address.
8365 		 *
8366 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8367 		 *    means packets using the IRE_CACHE that we will build
8368 		 *    here will go out on dst_ill.
8369 		 *
8370 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8371 		 *    to be created will only be tied to the IRE_INTERFACE
8372 		 *    that was derived from the ire_ihandle field.
8373 		 *
8374 		 *    If sire is non-NULL, it means the destination is
8375 		 *    off-link and we will first create the IRE_CACHE for the
8376 		 *    gateway. Next time through ip_newroute, we will create
8377 		 *    the IRE_CACHE for the final destination as described
8378 		 *    above.
8379 		 *
8380 		 * In both cases, after the current resolution has been
8381 		 * completed (or possibly initialised, in the IRE_INTERFACE
8382 		 * case), the loop may be re-entered to attempt the resolution
8383 		 * of another RTF_MULTIRT route.
8384 		 *
8385 		 * When an IRE_CACHE entry for the off-subnet destination is
8386 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8387 		 * for further processing in emission loops.
8388 		 */
8389 		save_ire = ire;
8390 		switch (ire->ire_type) {
8391 		case IRE_CACHE: {
8392 			ire_t	*ipif_ire;
8393 
8394 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8395 			if (gw == 0)
8396 				gw = ire->ire_gateway_addr;
8397 			/*
8398 			 * We need 3 ire's to create a new cache ire for an
8399 			 * off-link destination from the cache ire of the
8400 			 * gateway.
8401 			 *
8402 			 *	1. The prefix ire 'sire' (Note that this does
8403 			 *	   not apply to the conn_nexthop_set case)
8404 			 *	2. The cache ire of the gateway 'ire'
8405 			 *	3. The interface ire 'ipif_ire'
8406 			 *
8407 			 * We have (1) and (2). We lookup (3) below.
8408 			 *
8409 			 * If there is no interface route to the gateway,
8410 			 * it is a race condition, where we found the cache
8411 			 * but the interface route has been deleted.
8412 			 */
8413 			if (ip_nexthop) {
8414 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8415 			} else {
8416 				ipif_ire =
8417 				    ire_ihandle_lookup_offlink(ire, sire);
8418 			}
8419 			if (ipif_ire == NULL) {
8420 				ip1dbg(("ip_newroute: "
8421 				    "ire_ihandle_lookup_offlink failed\n"));
8422 				goto icmp_err_ret;
8423 			}
8424 
8425 			/*
8426 			 * Check cached gateway IRE for any security
8427 			 * attributes; if found, associate the gateway
8428 			 * credentials group to the destination IRE.
8429 			 */
8430 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8431 				mutex_enter(&attrp->igsa_lock);
8432 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8433 					GCGRP_REFHOLD(gcgrp);
8434 				mutex_exit(&attrp->igsa_lock);
8435 			}
8436 
8437 			/*
8438 			 * XXX For the source of the resolver mp,
8439 			 * we are using the same DL_UNITDATA_REQ
8440 			 * (from save_ire->ire_nce->nce_res_mp)
8441 			 * though the save_ire is not pointing at the same ill.
8442 			 * This is incorrect. We need to send it up to the
8443 			 * resolver to get the right res_mp. For ethernets
8444 			 * this may be okay (ill_type == DL_ETHER).
8445 			 */
8446 
8447 			ire = ire_create(
8448 			    (uchar_t *)&dst,		/* dest address */
8449 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8450 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8451 			    (uchar_t *)&gw,		/* gateway address */
8452 			    &save_ire->ire_max_frag,
8453 			    save_ire->ire_nce,		/* src nce */
8454 			    dst_ill->ill_rq,		/* recv-from queue */
8455 			    dst_ill->ill_wq,		/* send-to queue */
8456 			    IRE_CACHE,			/* IRE type */
8457 			    src_ipif,
8458 			    (sire != NULL) ?
8459 			    sire->ire_mask : 0, 	/* Parent mask */
8460 			    (sire != NULL) ?
8461 			    sire->ire_phandle : 0,	/* Parent handle */
8462 			    ipif_ire->ire_ihandle,	/* Interface handle */
8463 			    (sire != NULL) ? (sire->ire_flags &
8464 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8465 			    (sire != NULL) ?
8466 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8467 			    NULL,
8468 			    gcgrp,
8469 			    ipst);
8470 
8471 			if (ire == NULL) {
8472 				if (gcgrp != NULL) {
8473 					GCGRP_REFRELE(gcgrp);
8474 					gcgrp = NULL;
8475 				}
8476 				ire_refrele(ipif_ire);
8477 				ire_refrele(save_ire);
8478 				break;
8479 			}
8480 
8481 			/* reference now held by IRE */
8482 			gcgrp = NULL;
8483 
8484 			ire->ire_marks |= ire_marks;
8485 
8486 			/*
8487 			 * Prevent sire and ipif_ire from getting deleted.
8488 			 * The newly created ire is tied to both of them via
8489 			 * the phandle and ihandle respectively.
8490 			 */
8491 			if (sire != NULL) {
8492 				IRB_REFHOLD(sire->ire_bucket);
8493 				/* Has it been removed already ? */
8494 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8495 					IRB_REFRELE(sire->ire_bucket);
8496 					ire_refrele(ipif_ire);
8497 					ire_refrele(save_ire);
8498 					break;
8499 				}
8500 			}
8501 
8502 			IRB_REFHOLD(ipif_ire->ire_bucket);
8503 			/* Has it been removed already ? */
8504 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8505 				IRB_REFRELE(ipif_ire->ire_bucket);
8506 				if (sire != NULL)
8507 					IRB_REFRELE(sire->ire_bucket);
8508 				ire_refrele(ipif_ire);
8509 				ire_refrele(save_ire);
8510 				break;
8511 			}
8512 
8513 			xmit_mp = first_mp;
8514 			/*
8515 			 * In the case of multirouting, a copy
8516 			 * of the packet is done before its sending.
8517 			 * The copy is used to attempt another
8518 			 * route resolution, in a next loop.
8519 			 */
8520 			if (ire->ire_flags & RTF_MULTIRT) {
8521 				copy_mp = copymsg(first_mp);
8522 				if (copy_mp != NULL) {
8523 					xmit_mp = copy_mp;
8524 					MULTIRT_DEBUG_TAG(first_mp);
8525 				}
8526 			}
8527 			ire_add_then_send(q, ire, xmit_mp);
8528 			ire_refrele(save_ire);
8529 
8530 			/* Assert that sire is not deleted yet. */
8531 			if (sire != NULL) {
8532 				ASSERT(sire->ire_ptpn != NULL);
8533 				IRB_REFRELE(sire->ire_bucket);
8534 			}
8535 
8536 			/* Assert that ipif_ire is not deleted yet. */
8537 			ASSERT(ipif_ire->ire_ptpn != NULL);
8538 			IRB_REFRELE(ipif_ire->ire_bucket);
8539 			ire_refrele(ipif_ire);
8540 
8541 			/*
8542 			 * If copy_mp is not NULL, multirouting was
8543 			 * requested. We loop to initiate a next
8544 			 * route resolution attempt, starting from sire.
8545 			 */
8546 			if (copy_mp != NULL) {
8547 				/*
8548 				 * Search for the next unresolved
8549 				 * multirt route.
8550 				 */
8551 				copy_mp = NULL;
8552 				ipif_ire = NULL;
8553 				ire = NULL;
8554 				multirt_resolve_next = B_TRUE;
8555 				continue;
8556 			}
8557 			if (sire != NULL)
8558 				ire_refrele(sire);
8559 			ipif_refrele(src_ipif);
8560 			ill_refrele(dst_ill);
8561 			return;
8562 		}
8563 		case IRE_IF_NORESOLVER: {
8564 
8565 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8566 			    dst_ill->ill_resolver_mp == NULL) {
8567 				ip1dbg(("ip_newroute: dst_ill %p "
8568 				    "for IRE_IF_NORESOLVER ire %p has "
8569 				    "no ill_resolver_mp\n",
8570 				    (void *)dst_ill, (void *)ire));
8571 				break;
8572 			}
8573 
8574 			/*
8575 			 * TSol note: We are creating the ire cache for the
8576 			 * destination 'dst'. If 'dst' is offlink, going
8577 			 * through the first hop 'gw', the security attributes
8578 			 * of 'dst' must be set to point to the gateway
8579 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8580 			 * is possible that 'dst' is a potential gateway that is
8581 			 * referenced by some route that has some security
8582 			 * attributes. Thus in the former case, we need to do a
8583 			 * gcgrp_lookup of 'gw' while in the latter case we
8584 			 * need to do gcgrp_lookup of 'dst' itself.
8585 			 */
8586 			ga.ga_af = AF_INET;
8587 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8588 			    &ga.ga_addr);
8589 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8590 
8591 			ire = ire_create(
8592 			    (uchar_t *)&dst,		/* dest address */
8593 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8594 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8595 			    (uchar_t *)&gw,		/* gateway address */
8596 			    &save_ire->ire_max_frag,
8597 			    NULL,			/* no src nce */
8598 			    dst_ill->ill_rq,		/* recv-from queue */
8599 			    dst_ill->ill_wq,		/* send-to queue */
8600 			    IRE_CACHE,
8601 			    src_ipif,
8602 			    save_ire->ire_mask,		/* Parent mask */
8603 			    (sire != NULL) ?		/* Parent handle */
8604 			    sire->ire_phandle : 0,
8605 			    save_ire->ire_ihandle,	/* Interface handle */
8606 			    (sire != NULL) ? sire->ire_flags &
8607 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8608 			    &(save_ire->ire_uinfo),
8609 			    NULL,
8610 			    gcgrp,
8611 			    ipst);
8612 
8613 			if (ire == NULL) {
8614 				if (gcgrp != NULL) {
8615 					GCGRP_REFRELE(gcgrp);
8616 					gcgrp = NULL;
8617 				}
8618 				ire_refrele(save_ire);
8619 				break;
8620 			}
8621 
8622 			/* reference now held by IRE */
8623 			gcgrp = NULL;
8624 
8625 			ire->ire_marks |= ire_marks;
8626 
8627 			/* Prevent save_ire from getting deleted */
8628 			IRB_REFHOLD(save_ire->ire_bucket);
8629 			/* Has it been removed already ? */
8630 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8631 				IRB_REFRELE(save_ire->ire_bucket);
8632 				ire_refrele(save_ire);
8633 				break;
8634 			}
8635 
8636 			/*
8637 			 * In the case of multirouting, a copy
8638 			 * of the packet is made before it is sent.
8639 			 * The copy is used in the next
8640 			 * loop to attempt another resolution.
8641 			 */
8642 			xmit_mp = first_mp;
8643 			if ((sire != NULL) &&
8644 			    (sire->ire_flags & RTF_MULTIRT)) {
8645 				copy_mp = copymsg(first_mp);
8646 				if (copy_mp != NULL) {
8647 					xmit_mp = copy_mp;
8648 					MULTIRT_DEBUG_TAG(first_mp);
8649 				}
8650 			}
8651 			ire_add_then_send(q, ire, xmit_mp);
8652 
8653 			/* Assert that it is not deleted yet. */
8654 			ASSERT(save_ire->ire_ptpn != NULL);
8655 			IRB_REFRELE(save_ire->ire_bucket);
8656 			ire_refrele(save_ire);
8657 
8658 			if (copy_mp != NULL) {
8659 				/*
8660 				 * If we found a (no)resolver, we ignore any
8661 				 * trailing top priority IRE_CACHE in further
8662 				 * loops. This ensures that we do not omit any
8663 				 * (no)resolver.
8664 				 * This IRE_CACHE, if any, will be processed
8665 				 * by another thread entering ip_newroute().
8666 				 * IRE_CACHE entries, if any, will be processed
8667 				 * by another thread entering ip_newroute(),
8668 				 * (upon resolver response, for instance).
8669 				 * This aims to force parallel multirt
8670 				 * resolutions as soon as a packet must be sent.
8671 				 * In the best case, after the tx of only one
8672 				 * packet, all reachable routes are resolved.
8673 				 * Otherwise, the resolution of all RTF_MULTIRT
8674 				 * routes would require several emissions.
8675 				 */
8676 				multirt_flags &= ~MULTIRT_CACHEGW;
8677 
8678 				/*
8679 				 * Search for the next unresolved multirt
8680 				 * route.
8681 				 */
8682 				copy_mp = NULL;
8683 				save_ire = NULL;
8684 				ire = NULL;
8685 				multirt_resolve_next = B_TRUE;
8686 				continue;
8687 			}
8688 
8689 			/*
8690 			 * Don't need sire anymore
8691 			 */
8692 			if (sire != NULL)
8693 				ire_refrele(sire);
8694 
8695 			ipif_refrele(src_ipif);
8696 			ill_refrele(dst_ill);
8697 			return;
8698 		}
8699 		case IRE_IF_RESOLVER:
8700 			/*
8701 			 * We can't build an IRE_CACHE yet, but at least we
8702 			 * found a resolver that can help.
8703 			 */
8704 			res_mp = dst_ill->ill_resolver_mp;
8705 			if (!OK_RESOLVER_MP(res_mp))
8706 				break;
8707 
8708 			/*
8709 			 * To be at this point in the code with a non-zero gw
8710 			 * means that dst is reachable through a gateway that
8711 			 * we have never resolved.  By changing dst to the gw
8712 			 * addr we resolve the gateway first.
8713 			 * When ire_add_then_send() tries to put the IP dg
8714 			 * to dst, it will reenter ip_newroute() at which
8715 			 * time we will find the IRE_CACHE for the gw and
8716 			 * create another IRE_CACHE in case IRE_CACHE above.
8717 			 */
8718 			if (gw != INADDR_ANY) {
8719 				/*
8720 				 * The source ipif that was determined above was
8721 				 * relative to the destination address, not the
8722 				 * gateway's. If src_ipif was not taken out of
8723 				 * the IRE_IF_RESOLVER entry, we'll need to call
8724 				 * ipif_select_source() again.
8725 				 */
8726 				if (src_ipif != ire->ire_ipif) {
8727 					ipif_refrele(src_ipif);
8728 					src_ipif = ipif_select_source(dst_ill,
8729 					    gw, zoneid);
8730 					if (src_ipif == NULL) {
8731 						if (ip_debug > 2) {
8732 							pr_addr_dbg(
8733 							    "ip_newroute: no "
8734 							    "src for gw %s ",
8735 							    AF_INET, &gw);
8736 							printf("through "
8737 							    "interface %s\n",
8738 							    dst_ill->ill_name);
8739 						}
8740 						goto icmp_err_ret;
8741 					}
8742 				}
8743 				save_dst = dst;
8744 				dst = gw;
8745 				gw = INADDR_ANY;
8746 			}
8747 
8748 			/*
8749 			 * We obtain a partial IRE_CACHE which we will pass
8750 			 * along with the resolver query.  When the response
8751 			 * comes back it will be there ready for us to add.
8752 			 * The ire_max_frag is atomically set under the
8753 			 * irebucket lock in ire_add_v[46].
8754 			 */
8755 
8756 			ire = ire_create_mp(
8757 			    (uchar_t *)&dst,		/* dest address */
8758 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8759 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8760 			    (uchar_t *)&gw,		/* gateway address */
8761 			    NULL,			/* ire_max_frag */
8762 			    NULL,			/* no src nce */
8763 			    dst_ill->ill_rq,		/* recv-from queue */
8764 			    dst_ill->ill_wq,		/* send-to queue */
8765 			    IRE_CACHE,
8766 			    src_ipif,			/* Interface ipif */
8767 			    save_ire->ire_mask,		/* Parent mask */
8768 			    0,
8769 			    save_ire->ire_ihandle,	/* Interface handle */
8770 			    0,				/* flags if any */
8771 			    &(save_ire->ire_uinfo),
8772 			    NULL,
8773 			    NULL,
8774 			    ipst);
8775 
8776 			if (ire == NULL) {
8777 				ire_refrele(save_ire);
8778 				break;
8779 			}
8780 
8781 			if ((sire != NULL) &&
8782 			    (sire->ire_flags & RTF_MULTIRT)) {
8783 				copy_mp = copymsg(first_mp);
8784 				if (copy_mp != NULL)
8785 					MULTIRT_DEBUG_TAG(copy_mp);
8786 			}
8787 
8788 			ire->ire_marks |= ire_marks;
8789 
8790 			/*
8791 			 * Construct message chain for the resolver
8792 			 * of the form:
8793 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8794 			 * Packet could contain a IPSEC_OUT mp.
8795 			 *
8796 			 * NOTE : ire will be added later when the response
8797 			 * comes back from ARP. If the response does not
8798 			 * come back, ARP frees the packet. For this reason,
8799 			 * we can't REFHOLD the bucket of save_ire to prevent
8800 			 * deletions. We may not be able to REFRELE the bucket
8801 			 * if the response never comes back. Thus, before
8802 			 * adding the ire, ire_add_v4 will make sure that the
8803 			 * interface route does not get deleted. This is the
8804 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8805 			 * where we can always prevent deletions because of
8806 			 * the synchronous nature of adding IRES i.e
8807 			 * ire_add_then_send is called after creating the IRE.
8808 			 */
8809 			ASSERT(ire->ire_mp != NULL);
8810 			ire->ire_mp->b_cont = first_mp;
8811 			/* Have saved_mp handy, for cleanup if canput fails */
8812 			saved_mp = mp;
8813 			mp = copyb(res_mp);
8814 			if (mp == NULL) {
8815 				/* Prepare for cleanup */
8816 				mp = saved_mp; /* pkt */
8817 				ire_delete(ire); /* ire_mp */
8818 				ire = NULL;
8819 				ire_refrele(save_ire);
8820 				if (copy_mp != NULL) {
8821 					MULTIRT_DEBUG_UNTAG(copy_mp);
8822 					freemsg(copy_mp);
8823 					copy_mp = NULL;
8824 				}
8825 				break;
8826 			}
8827 			linkb(mp, ire->ire_mp);
8828 
8829 			/*
8830 			 * Fill in the source and dest addrs for the resolver.
8831 			 * NOTE: this depends on memory layouts imposed by
8832 			 * ill_init().
8833 			 */
8834 			areq = (areq_t *)mp->b_rptr;
8835 			addrp = (ipaddr_t *)((char *)areq +
8836 			    areq->areq_sender_addr_offset);
8837 			if (do_attach_ill) {
8838 				/*
8839 				 * This is bind to no failover case.
8840 				 * arp packet also must go out on attach_ill.
8841 				 */
8842 				ASSERT(ipha->ipha_src != NULL);
8843 				*addrp = ipha->ipha_src;
8844 			} else {
8845 				*addrp = save_ire->ire_src_addr;
8846 			}
8847 
8848 			ire_refrele(save_ire);
8849 			addrp = (ipaddr_t *)((char *)areq +
8850 			    areq->areq_target_addr_offset);
8851 			*addrp = dst;
8852 			/* Up to the resolver. */
8853 			if (canputnext(dst_ill->ill_rq) &&
8854 			    !(dst_ill->ill_arp_closing)) {
8855 				putnext(dst_ill->ill_rq, mp);
8856 				ire = NULL;
8857 				if (copy_mp != NULL) {
8858 					/*
8859 					 * If we found a resolver, we ignore
8860 					 * any trailing top priority IRE_CACHE
8861 					 * in the further loops. This ensures
8862 					 * that we do not omit any resolver.
8863 					 * IRE_CACHE entries, if any, will be
8864 					 * processed next time we enter
8865 					 * ip_newroute().
8866 					 */
8867 					multirt_flags &= ~MULTIRT_CACHEGW;
8868 					/*
8869 					 * Search for the next unresolved
8870 					 * multirt route.
8871 					 */
8872 					first_mp = copy_mp;
8873 					copy_mp = NULL;
8874 					/* Prepare the next resolution loop. */
8875 					mp = first_mp;
8876 					EXTRACT_PKT_MP(mp, first_mp,
8877 					    mctl_present);
8878 					if (mctl_present)
8879 						io = (ipsec_out_t *)
8880 						    first_mp->b_rptr;
8881 					ipha = (ipha_t *)mp->b_rptr;
8882 
8883 					ASSERT(sire != NULL);
8884 
8885 					dst = save_dst;
8886 					multirt_resolve_next = B_TRUE;
8887 					continue;
8888 				}
8889 
8890 				if (sire != NULL)
8891 					ire_refrele(sire);
8892 
8893 				/*
8894 				 * The response will come back in ip_wput
8895 				 * with db_type IRE_DB_TYPE.
8896 				 */
8897 				ipif_refrele(src_ipif);
8898 				ill_refrele(dst_ill);
8899 				return;
8900 			} else {
8901 				/* Prepare for cleanup */
8902 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8903 				    mp);
8904 				mp->b_cont = NULL;
8905 				freeb(mp); /* areq */
8906 				/*
8907 				 * this is an ire that is not added to the
8908 				 * cache. ire_freemblk will handle the release
8909 				 * of any resources associated with the ire.
8910 				 */
8911 				ire_delete(ire); /* ire_mp */
8912 				mp = saved_mp; /* pkt */
8913 				ire = NULL;
8914 				if (copy_mp != NULL) {
8915 					MULTIRT_DEBUG_UNTAG(copy_mp);
8916 					freemsg(copy_mp);
8917 					copy_mp = NULL;
8918 				}
8919 				break;
8920 			}
8921 		default:
8922 			break;
8923 		}
8924 	} while (multirt_resolve_next);
8925 
8926 	ip1dbg(("ip_newroute: dropped\n"));
8927 	/* Did this packet originate externally? */
8928 	if (mp->b_prev) {
8929 		mp->b_next = NULL;
8930 		mp->b_prev = NULL;
8931 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8932 	} else {
8933 		if (dst_ill != NULL) {
8934 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8935 		} else {
8936 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8937 		}
8938 	}
8939 	ASSERT(copy_mp == NULL);
8940 	MULTIRT_DEBUG_UNTAG(first_mp);
8941 	freemsg(first_mp);
8942 	if (ire != NULL)
8943 		ire_refrele(ire);
8944 	if (sire != NULL)
8945 		ire_refrele(sire);
8946 	if (src_ipif != NULL)
8947 		ipif_refrele(src_ipif);
8948 	if (dst_ill != NULL)
8949 		ill_refrele(dst_ill);
8950 	return;
8951 
8952 icmp_err_ret:
8953 	ip1dbg(("ip_newroute: no route\n"));
8954 	if (src_ipif != NULL)
8955 		ipif_refrele(src_ipif);
8956 	if (dst_ill != NULL)
8957 		ill_refrele(dst_ill);
8958 	if (sire != NULL)
8959 		ire_refrele(sire);
8960 	/* Did this packet originate externally? */
8961 	if (mp->b_prev) {
8962 		mp->b_next = NULL;
8963 		mp->b_prev = NULL;
8964 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8965 		q = WR(q);
8966 	} else {
8967 		/*
8968 		 * There is no outgoing ill, so just increment the
8969 		 * system MIB.
8970 		 */
8971 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8972 		/*
8973 		 * Since ip_wput() isn't close to finished, we fill
8974 		 * in enough of the header for credible error reporting.
8975 		 */
8976 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8977 			/* Failed */
8978 			MULTIRT_DEBUG_UNTAG(first_mp);
8979 			freemsg(first_mp);
8980 			if (ire != NULL)
8981 				ire_refrele(ire);
8982 			return;
8983 		}
8984 	}
8985 
8986 	/*
8987 	 * At this point we will have ire only if RTF_BLACKHOLE
8988 	 * or RTF_REJECT flags are set on the IRE. It will not
8989 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8990 	 */
8991 	if (ire != NULL) {
8992 		if (ire->ire_flags & RTF_BLACKHOLE) {
8993 			ire_refrele(ire);
8994 			MULTIRT_DEBUG_UNTAG(first_mp);
8995 			freemsg(first_mp);
8996 			return;
8997 		}
8998 		ire_refrele(ire);
8999 	}
9000 	if (ip_source_routed(ipha, ipst)) {
9001 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9002 		    zoneid, ipst);
9003 		return;
9004 	}
9005 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9006 }
9007 
9008 ip_opt_info_t zero_info;
9009 
9010 /*
9011  * IPv4 -
9012  * ip_newroute_ipif is called by ip_wput_multicast and
9013  * ip_rput_forward_multicast whenever we need to send
9014  * out a packet to a destination address for which we do not have specific
9015  * routing information. It is used when the packet will be sent out
9016  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9017  * socket option is set or icmp error message wants to go out on a particular
9018  * interface for a unicast packet.
9019  *
9020  * In most cases, the destination address is resolved thanks to the ipif
9021  * intrinsic resolver. However, there are some cases where the call to
9022  * ip_newroute_ipif must take into account the potential presence of
9023  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9024  * that uses the interface. This is specified through flags,
9025  * which can be a combination of:
9026  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9027  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9028  *   and flags. Additionally, the packet source address has to be set to
9029  *   the specified address. The caller is thus expected to set this flag
9030  *   if the packet has no specific source address yet.
9031  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9032  *   flag, the resulting ire will inherit the flag. All unresolved routes
9033  *   to the destination must be explored in the same call to
9034  *   ip_newroute_ipif().
9035  */
9036 static void
9037 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9038     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9039 {
9040 	areq_t	*areq;
9041 	ire_t	*ire = NULL;
9042 	mblk_t	*res_mp;
9043 	ipaddr_t *addrp;
9044 	mblk_t *first_mp;
9045 	ire_t	*save_ire = NULL;
9046 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9047 	ipif_t	*src_ipif = NULL;
9048 	ushort_t ire_marks = 0;
9049 	ill_t	*dst_ill = NULL;
9050 	boolean_t mctl_present;
9051 	ipsec_out_t *io;
9052 	ipha_t *ipha;
9053 	int	ihandle = 0;
9054 	mblk_t	*saved_mp;
9055 	ire_t   *fire = NULL;
9056 	mblk_t  *copy_mp = NULL;
9057 	boolean_t multirt_resolve_next;
9058 	ipaddr_t ipha_dst;
9059 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9060 
9061 	/*
9062 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9063 	 * here for uniformity
9064 	 */
9065 	ipif_refhold(ipif);
9066 
9067 	/*
9068 	 * This loop is run only once in most cases.
9069 	 * We loop to resolve further routes only when the destination
9070 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9071 	 */
9072 	do {
9073 		if (dst_ill != NULL) {
9074 			ill_refrele(dst_ill);
9075 			dst_ill = NULL;
9076 		}
9077 		if (src_ipif != NULL) {
9078 			ipif_refrele(src_ipif);
9079 			src_ipif = NULL;
9080 		}
9081 		multirt_resolve_next = B_FALSE;
9082 
9083 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9084 		    ipif->ipif_ill->ill_name));
9085 
9086 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9087 		if (mctl_present)
9088 			io = (ipsec_out_t *)first_mp->b_rptr;
9089 
9090 		ipha = (ipha_t *)mp->b_rptr;
9091 
9092 		/*
9093 		 * Save the packet destination address, we may need it after
9094 		 * the packet has been consumed.
9095 		 */
9096 		ipha_dst = ipha->ipha_dst;
9097 
9098 		/*
9099 		 * If the interface is a pt-pt interface we look for an
9100 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9101 		 * local_address and the pt-pt destination address. Otherwise
9102 		 * we just match the local address.
9103 		 * NOTE: dst could be different than ipha->ipha_dst in case
9104 		 * of sending igmp multicast packets over a point-to-point
9105 		 * connection.
9106 		 * Thus we must be careful enough to check ipha_dst to be a
9107 		 * multicast address, otherwise it will take xmit_if path for
9108 		 * multicast packets resulting into kernel stack overflow by
9109 		 * repeated calls to ip_newroute_ipif from ire_send().
9110 		 */
9111 		if (CLASSD(ipha_dst) &&
9112 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9113 			goto err_ret;
9114 		}
9115 
9116 		/*
9117 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9118 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9119 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9120 		 * propagate its flags to the new ire.
9121 		 */
9122 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9123 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9124 			ip2dbg(("ip_newroute_ipif: "
9125 			    "ipif_lookup_multi_ire("
9126 			    "ipif %p, dst %08x) = fire %p\n",
9127 			    (void *)ipif, ntohl(dst), (void *)fire));
9128 		}
9129 
9130 		if (mctl_present && io->ipsec_out_attach_if) {
9131 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9132 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9133 
9134 			/* Failure case frees things for us. */
9135 			if (attach_ill == NULL) {
9136 				ipif_refrele(ipif);
9137 				if (fire != NULL)
9138 					ire_refrele(fire);
9139 				return;
9140 			}
9141 
9142 			/*
9143 			 * Check if we need an ire that will not be
9144 			 * looked up by anybody else i.e. HIDDEN.
9145 			 */
9146 			if (ill_is_probeonly(attach_ill)) {
9147 				ire_marks = IRE_MARK_HIDDEN;
9148 			}
9149 			/*
9150 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9151 			 * case.
9152 			 */
9153 			dst_ill = ipif->ipif_ill;
9154 			/* attach_ill has been refheld by ip_grab_attach_ill */
9155 			ASSERT(dst_ill == attach_ill);
9156 		} else {
9157 			/*
9158 			 * If this is set by IP_XMIT_IF, then make sure that
9159 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9160 			 * specified ill.
9161 			 */
9162 			ASSERT((connp == NULL) ||
9163 			    (connp->conn_xmit_if_ill == NULL) ||
9164 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9165 			/*
9166 			 * If the interface belongs to an interface group,
9167 			 * make sure the next possible interface in the group
9168 			 * is used.  This encourages load spreading among
9169 			 * peers in an interface group.
9170 			 * Note: load spreading is disabled for RTF_MULTIRT
9171 			 * routes.
9172 			 */
9173 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9174 			    (fire->ire_flags & RTF_MULTIRT)) {
9175 				/*
9176 				 * Don't perform outbound load spreading
9177 				 * in the case of an RTF_MULTIRT issued route,
9178 				 * we actually typically want to replicate
9179 				 * outgoing packets through particular
9180 				 * interfaces.
9181 				 */
9182 				dst_ill = ipif->ipif_ill;
9183 				ill_refhold(dst_ill);
9184 			} else {
9185 				dst_ill = ip_newroute_get_dst_ill(
9186 				    ipif->ipif_ill);
9187 			}
9188 			if (dst_ill == NULL) {
9189 				if (ip_debug > 2) {
9190 					pr_addr_dbg("ip_newroute_ipif: "
9191 					    "no dst ill for dst %s\n",
9192 					    AF_INET, &dst);
9193 				}
9194 				goto err_ret;
9195 			}
9196 		}
9197 
9198 		/*
9199 		 * Pick a source address preferring non-deprecated ones.
9200 		 * Unlike ip_newroute, we don't do any source address
9201 		 * selection here since for multicast it really does not help
9202 		 * in inbound load spreading as in the unicast case.
9203 		 */
9204 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9205 		    (fire->ire_flags & RTF_SETSRC)) {
9206 			/*
9207 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9208 			 * on that interface. This ire has RTF_SETSRC flag, so
9209 			 * the source address of the packet must be changed.
9210 			 * Check that the ipif matching the requested source
9211 			 * address still exists.
9212 			 */
9213 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9214 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9215 		}
9216 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9217 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9218 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9219 		    (src_ipif == NULL)) {
9220 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9221 			if (src_ipif == NULL) {
9222 				if (ip_debug > 2) {
9223 					/* ip1dbg */
9224 					pr_addr_dbg("ip_newroute_ipif: "
9225 					    "no src for dst %s",
9226 					    AF_INET, &dst);
9227 				}
9228 				ip1dbg((" through interface %s\n",
9229 				    dst_ill->ill_name));
9230 				goto err_ret;
9231 			}
9232 			ipif_refrele(ipif);
9233 			ipif = src_ipif;
9234 			ipif_refhold(ipif);
9235 		}
9236 		if (src_ipif == NULL) {
9237 			src_ipif = ipif;
9238 			ipif_refhold(src_ipif);
9239 		}
9240 
9241 		/*
9242 		 * Assign a source address while we have the conn.
9243 		 * We can't have ip_wput_ire pick a source address when the
9244 		 * packet returns from arp since conn_unspec_src might be set
9245 		 * and we loose the conn when going through arp.
9246 		 */
9247 		if (ipha->ipha_src == INADDR_ANY &&
9248 		    (connp == NULL || !connp->conn_unspec_src)) {
9249 			ipha->ipha_src = src_ipif->ipif_src_addr;
9250 		}
9251 
9252 		/*
9253 		 * In the case of IP_XMIT_IF, it is possible that the
9254 		 * outgoing interface does not have an interface ire.
9255 		 */
9256 		if (CLASSD(ipha_dst) && (connp == NULL ||
9257 		    connp->conn_xmit_if_ill == NULL) &&
9258 		    infop->ip_opt_ill_index == 0) {
9259 			/* ipif_to_ire returns an held ire */
9260 			ire = ipif_to_ire(ipif);
9261 			if (ire == NULL)
9262 				goto err_ret;
9263 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9264 				goto err_ret;
9265 			/*
9266 			 * ihandle is needed when the ire is added to
9267 			 * cache table.
9268 			 */
9269 			save_ire = ire;
9270 			ihandle = save_ire->ire_ihandle;
9271 
9272 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9273 			    "flags %04x\n",
9274 			    (void *)ire, (void *)ipif, flags));
9275 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9276 			    (fire->ire_flags & RTF_MULTIRT)) {
9277 				/*
9278 				 * As requested by flags, an IRE_OFFSUBNET was
9279 				 * looked up on that interface. This ire has
9280 				 * RTF_MULTIRT flag, so the resolution loop will
9281 				 * be re-entered to resolve additional routes on
9282 				 * other interfaces. For that purpose, a copy of
9283 				 * the packet is performed at this point.
9284 				 */
9285 				fire->ire_last_used_time = lbolt;
9286 				copy_mp = copymsg(first_mp);
9287 				if (copy_mp) {
9288 					MULTIRT_DEBUG_TAG(copy_mp);
9289 				}
9290 			}
9291 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9292 			    (fire->ire_flags & RTF_SETSRC)) {
9293 				/*
9294 				 * As requested by flags, an IRE_OFFSUBET was
9295 				 * looked up on that interface. This ire has
9296 				 * RTF_SETSRC flag, so the source address of the
9297 				 * packet must be changed.
9298 				 */
9299 				ipha->ipha_src = fire->ire_src_addr;
9300 			}
9301 		} else {
9302 			ASSERT((connp == NULL) ||
9303 			    (connp->conn_xmit_if_ill != NULL) ||
9304 			    (connp->conn_dontroute) ||
9305 			    infop->ip_opt_ill_index != 0);
9306 			/*
9307 			 * The only ways we can come here are:
9308 			 * 1) IP_XMIT_IF socket option is set
9309 			 * 2) SO_DONTROUTE socket option is set
9310 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9311 			 * In all cases, the new ire will not be added
9312 			 * into cache table.
9313 			 */
9314 			ire_marks |= IRE_MARK_NOADD;
9315 		}
9316 
9317 		switch (ipif->ipif_net_type) {
9318 		case IRE_IF_NORESOLVER: {
9319 			/* We have what we need to build an IRE_CACHE. */
9320 
9321 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9322 			    (dst_ill->ill_resolver_mp == NULL)) {
9323 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9324 				    "for IRE_IF_NORESOLVER ire %p has "
9325 				    "no ill_resolver_mp\n",
9326 				    (void *)dst_ill, (void *)ire));
9327 				break;
9328 			}
9329 
9330 			/*
9331 			 * The new ire inherits the IRE_OFFSUBNET flags
9332 			 * and source address, if this was requested.
9333 			 */
9334 			ire = ire_create(
9335 			    (uchar_t *)&dst,		/* dest address */
9336 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9337 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9338 			    NULL,			/* gateway address */
9339 			    &ipif->ipif_mtu,
9340 			    NULL,			/* no src nce */
9341 			    dst_ill->ill_rq,		/* recv-from queue */
9342 			    dst_ill->ill_wq,		/* send-to queue */
9343 			    IRE_CACHE,
9344 			    src_ipif,
9345 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9346 			    (fire != NULL) ?		/* Parent handle */
9347 			    fire->ire_phandle : 0,
9348 			    ihandle,			/* Interface handle */
9349 			    (fire != NULL) ?
9350 			    (fire->ire_flags &
9351 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9352 			    (save_ire == NULL ? &ire_uinfo_null :
9353 			    &save_ire->ire_uinfo),
9354 			    NULL,
9355 			    NULL,
9356 			    ipst);
9357 
9358 			if (ire == NULL) {
9359 				if (save_ire != NULL)
9360 					ire_refrele(save_ire);
9361 				break;
9362 			}
9363 
9364 			ire->ire_marks |= ire_marks;
9365 
9366 			/*
9367 			 * If IRE_MARK_NOADD is set then we need to convert
9368 			 * the max_fragp to a useable value now. This is
9369 			 * normally done in ire_add_v[46]. We also need to
9370 			 * associate the ire with an nce (normally would be
9371 			 * done in ip_wput_nondata()).
9372 			 *
9373 			 * Note that IRE_MARK_NOADD packets created here
9374 			 * do not have a non-null ire_mp pointer. The null
9375 			 * value of ire_bucket indicates that they were
9376 			 * never added.
9377 			 */
9378 			if (ire->ire_marks & IRE_MARK_NOADD) {
9379 				uint_t  max_frag;
9380 
9381 				max_frag = *ire->ire_max_fragp;
9382 				ire->ire_max_fragp = NULL;
9383 				ire->ire_max_frag = max_frag;
9384 
9385 				if ((ire->ire_nce = ndp_lookup_v4(
9386 				    ire_to_ill(ire),
9387 				    (ire->ire_gateway_addr != INADDR_ANY ?
9388 				    &ire->ire_gateway_addr : &ire->ire_addr),
9389 				    B_FALSE)) == NULL) {
9390 					if (save_ire != NULL)
9391 						ire_refrele(save_ire);
9392 					break;
9393 				}
9394 				ASSERT(ire->ire_nce->nce_state ==
9395 				    ND_REACHABLE);
9396 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9397 			}
9398 
9399 			/* Prevent save_ire from getting deleted */
9400 			if (save_ire != NULL) {
9401 				IRB_REFHOLD(save_ire->ire_bucket);
9402 				/* Has it been removed already ? */
9403 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9404 					IRB_REFRELE(save_ire->ire_bucket);
9405 					ire_refrele(save_ire);
9406 					break;
9407 				}
9408 			}
9409 
9410 			ire_add_then_send(q, ire, first_mp);
9411 
9412 			/* Assert that save_ire is not deleted yet. */
9413 			if (save_ire != NULL) {
9414 				ASSERT(save_ire->ire_ptpn != NULL);
9415 				IRB_REFRELE(save_ire->ire_bucket);
9416 				ire_refrele(save_ire);
9417 				save_ire = NULL;
9418 			}
9419 			if (fire != NULL) {
9420 				ire_refrele(fire);
9421 				fire = NULL;
9422 			}
9423 
9424 			/*
9425 			 * the resolution loop is re-entered if this
9426 			 * was requested through flags and if we
9427 			 * actually are in a multirouting case.
9428 			 */
9429 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9430 				boolean_t need_resolve =
9431 				    ire_multirt_need_resolve(ipha_dst,
9432 				    MBLK_GETLABEL(copy_mp), ipst);
9433 				if (!need_resolve) {
9434 					MULTIRT_DEBUG_UNTAG(copy_mp);
9435 					freemsg(copy_mp);
9436 					copy_mp = NULL;
9437 				} else {
9438 					/*
9439 					 * ipif_lookup_group() calls
9440 					 * ire_lookup_multi() that uses
9441 					 * ire_ftable_lookup() to find
9442 					 * an IRE_INTERFACE for the group.
9443 					 * In the multirt case,
9444 					 * ire_lookup_multi() then invokes
9445 					 * ire_multirt_lookup() to find
9446 					 * the next resolvable ire.
9447 					 * As a result, we obtain an new
9448 					 * interface, derived from the
9449 					 * next ire.
9450 					 */
9451 					ipif_refrele(ipif);
9452 					ipif = ipif_lookup_group(ipha_dst,
9453 					    zoneid, ipst);
9454 					ip2dbg(("ip_newroute_ipif: "
9455 					    "multirt dst %08x, ipif %p\n",
9456 					    htonl(dst), (void *)ipif));
9457 					if (ipif != NULL) {
9458 						mp = copy_mp;
9459 						copy_mp = NULL;
9460 						multirt_resolve_next = B_TRUE;
9461 						continue;
9462 					} else {
9463 						freemsg(copy_mp);
9464 					}
9465 				}
9466 			}
9467 			if (ipif != NULL)
9468 				ipif_refrele(ipif);
9469 			ill_refrele(dst_ill);
9470 			ipif_refrele(src_ipif);
9471 			return;
9472 		}
9473 		case IRE_IF_RESOLVER:
9474 			/*
9475 			 * We can't build an IRE_CACHE yet, but at least
9476 			 * we found a resolver that can help.
9477 			 */
9478 			res_mp = dst_ill->ill_resolver_mp;
9479 			if (!OK_RESOLVER_MP(res_mp))
9480 				break;
9481 
9482 			/*
9483 			 * We obtain a partial IRE_CACHE which we will pass
9484 			 * along with the resolver query.  When the response
9485 			 * comes back it will be there ready for us to add.
9486 			 * The new ire inherits the IRE_OFFSUBNET flags
9487 			 * and source address, if this was requested.
9488 			 * The ire_max_frag is atomically set under the
9489 			 * irebucket lock in ire_add_v[46]. Only in the
9490 			 * case of IRE_MARK_NOADD, we set it here itself.
9491 			 */
9492 			ire = ire_create_mp(
9493 			    (uchar_t *)&dst,		/* dest address */
9494 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9495 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9496 			    NULL,			/* gateway address */
9497 			    (ire_marks & IRE_MARK_NOADD) ?
9498 			    ipif->ipif_mtu : 0,		/* max_frag */
9499 			    NULL,			/* no src nce */
9500 			    dst_ill->ill_rq,		/* recv-from queue */
9501 			    dst_ill->ill_wq,		/* send-to queue */
9502 			    IRE_CACHE,
9503 			    src_ipif,
9504 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9505 			    (fire != NULL) ?		/* Parent handle */
9506 			    fire->ire_phandle : 0,
9507 			    ihandle,			/* Interface handle */
9508 			    (fire != NULL) ?		/* flags if any */
9509 			    (fire->ire_flags &
9510 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9511 			    (save_ire == NULL ? &ire_uinfo_null :
9512 			    &save_ire->ire_uinfo),
9513 			    NULL,
9514 			    NULL,
9515 			    ipst);
9516 
9517 			if (save_ire != NULL) {
9518 				ire_refrele(save_ire);
9519 				save_ire = NULL;
9520 			}
9521 			if (ire == NULL)
9522 				break;
9523 
9524 			ire->ire_marks |= ire_marks;
9525 			/*
9526 			 * Construct message chain for the resolver of the
9527 			 * form:
9528 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9529 			 *
9530 			 * NOTE : ire will be added later when the response
9531 			 * comes back from ARP. If the response does not
9532 			 * come back, ARP frees the packet. For this reason,
9533 			 * we can't REFHOLD the bucket of save_ire to prevent
9534 			 * deletions. We may not be able to REFRELE the
9535 			 * bucket if the response never comes back.
9536 			 * Thus, before adding the ire, ire_add_v4 will make
9537 			 * sure that the interface route does not get deleted.
9538 			 * This is the only case unlike ip_newroute_v6,
9539 			 * ip_newroute_ipif_v6 where we can always prevent
9540 			 * deletions because ire_add_then_send is called after
9541 			 * creating the IRE.
9542 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9543 			 * does not add this IRE into the IRE CACHE.
9544 			 */
9545 			ASSERT(ire->ire_mp != NULL);
9546 			ire->ire_mp->b_cont = first_mp;
9547 			/* Have saved_mp handy, for cleanup if canput fails */
9548 			saved_mp = mp;
9549 			mp = copyb(res_mp);
9550 			if (mp == NULL) {
9551 				/* Prepare for cleanup */
9552 				mp = saved_mp; /* pkt */
9553 				ire_delete(ire); /* ire_mp */
9554 				ire = NULL;
9555 				if (copy_mp != NULL) {
9556 					MULTIRT_DEBUG_UNTAG(copy_mp);
9557 					freemsg(copy_mp);
9558 					copy_mp = NULL;
9559 				}
9560 				break;
9561 			}
9562 			linkb(mp, ire->ire_mp);
9563 
9564 			/*
9565 			 * Fill in the source and dest addrs for the resolver.
9566 			 * NOTE: this depends on memory layouts imposed by
9567 			 * ill_init().
9568 			 */
9569 			areq = (areq_t *)mp->b_rptr;
9570 			addrp = (ipaddr_t *)((char *)areq +
9571 			    areq->areq_sender_addr_offset);
9572 			*addrp = ire->ire_src_addr;
9573 			addrp = (ipaddr_t *)((char *)areq +
9574 			    areq->areq_target_addr_offset);
9575 			*addrp = dst;
9576 			/* Up to the resolver. */
9577 			if (canputnext(dst_ill->ill_rq) &&
9578 			    !(dst_ill->ill_arp_closing)) {
9579 				putnext(dst_ill->ill_rq, mp);
9580 				/*
9581 				 * The response will come back in ip_wput
9582 				 * with db_type IRE_DB_TYPE.
9583 				 */
9584 			} else {
9585 				mp->b_cont = NULL;
9586 				freeb(mp); /* areq */
9587 				ire_delete(ire); /* ire_mp */
9588 				saved_mp->b_next = NULL;
9589 				saved_mp->b_prev = NULL;
9590 				freemsg(first_mp); /* pkt */
9591 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9592 			}
9593 
9594 			if (fire != NULL) {
9595 				ire_refrele(fire);
9596 				fire = NULL;
9597 			}
9598 
9599 
9600 			/*
9601 			 * The resolution loop is re-entered if this was
9602 			 * requested through flags and we actually are
9603 			 * in a multirouting case.
9604 			 */
9605 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9606 				boolean_t need_resolve =
9607 				    ire_multirt_need_resolve(ipha_dst,
9608 				    MBLK_GETLABEL(copy_mp), ipst);
9609 				if (!need_resolve) {
9610 					MULTIRT_DEBUG_UNTAG(copy_mp);
9611 					freemsg(copy_mp);
9612 					copy_mp = NULL;
9613 				} else {
9614 					/*
9615 					 * ipif_lookup_group() calls
9616 					 * ire_lookup_multi() that uses
9617 					 * ire_ftable_lookup() to find
9618 					 * an IRE_INTERFACE for the group.
9619 					 * In the multirt case,
9620 					 * ire_lookup_multi() then invokes
9621 					 * ire_multirt_lookup() to find
9622 					 * the next resolvable ire.
9623 					 * As a result, we obtain an new
9624 					 * interface, derived from the
9625 					 * next ire.
9626 					 */
9627 					ipif_refrele(ipif);
9628 					ipif = ipif_lookup_group(ipha_dst,
9629 					    zoneid, ipst);
9630 					if (ipif != NULL) {
9631 						mp = copy_mp;
9632 						copy_mp = NULL;
9633 						multirt_resolve_next = B_TRUE;
9634 						continue;
9635 					} else {
9636 						freemsg(copy_mp);
9637 					}
9638 				}
9639 			}
9640 			if (ipif != NULL)
9641 				ipif_refrele(ipif);
9642 			ill_refrele(dst_ill);
9643 			ipif_refrele(src_ipif);
9644 			return;
9645 		default:
9646 			break;
9647 		}
9648 	} while (multirt_resolve_next);
9649 
9650 err_ret:
9651 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9652 	if (fire != NULL)
9653 		ire_refrele(fire);
9654 	ipif_refrele(ipif);
9655 	/* Did this packet originate externally? */
9656 	if (dst_ill != NULL)
9657 		ill_refrele(dst_ill);
9658 	if (src_ipif != NULL)
9659 		ipif_refrele(src_ipif);
9660 	if (mp->b_prev || mp->b_next) {
9661 		mp->b_next = NULL;
9662 		mp->b_prev = NULL;
9663 	} else {
9664 		/*
9665 		 * Since ip_wput() isn't close to finished, we fill
9666 		 * in enough of the header for credible error reporting.
9667 		 */
9668 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9669 			/* Failed */
9670 			freemsg(first_mp);
9671 			if (ire != NULL)
9672 				ire_refrele(ire);
9673 			return;
9674 		}
9675 	}
9676 	/*
9677 	 * At this point we will have ire only if RTF_BLACKHOLE
9678 	 * or RTF_REJECT flags are set on the IRE. It will not
9679 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9680 	 */
9681 	if (ire != NULL) {
9682 		if (ire->ire_flags & RTF_BLACKHOLE) {
9683 			ire_refrele(ire);
9684 			freemsg(first_mp);
9685 			return;
9686 		}
9687 		ire_refrele(ire);
9688 	}
9689 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9690 }
9691 
9692 /* Name/Value Table Lookup Routine */
9693 char *
9694 ip_nv_lookup(nv_t *nv, int value)
9695 {
9696 	if (!nv)
9697 		return (NULL);
9698 	for (; nv->nv_name; nv++) {
9699 		if (nv->nv_value == value)
9700 			return (nv->nv_name);
9701 	}
9702 	return ("unknown");
9703 }
9704 
9705 /*
9706  * This is a module open, i.e. this is a control stream for access
9707  * to a DLPI device.  We allocate an ill_t as the instance data in
9708  * this case.
9709  */
9710 int
9711 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9712 {
9713 	ill_t	*ill;
9714 	int	err;
9715 	zoneid_t zoneid;
9716 	netstack_t *ns;
9717 	ip_stack_t *ipst;
9718 
9719 	/*
9720 	 * Prevent unprivileged processes from pushing IP so that
9721 	 * they can't send raw IP.
9722 	 */
9723 	if (secpolicy_net_rawaccess(credp) != 0)
9724 		return (EPERM);
9725 
9726 	ns = netstack_find_by_cred(credp);
9727 	ASSERT(ns != NULL);
9728 	ipst = ns->netstack_ip;
9729 	ASSERT(ipst != NULL);
9730 
9731 	/*
9732 	 * For exclusive stacks we set the zoneid to zero
9733 	 * to make IP operate as if in the global zone.
9734 	 */
9735 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9736 		zoneid = GLOBAL_ZONEID;
9737 	else
9738 		zoneid = crgetzoneid(credp);
9739 
9740 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9741 	q->q_ptr = WR(q)->q_ptr = ill;
9742 	ill->ill_ipst = ipst;
9743 	ill->ill_zoneid = zoneid;
9744 
9745 	/*
9746 	 * ill_init initializes the ill fields and then sends down
9747 	 * down a DL_INFO_REQ after calling qprocson.
9748 	 */
9749 	err = ill_init(q, ill);
9750 	if (err != 0) {
9751 		mi_free(ill);
9752 		netstack_rele(ipst->ips_netstack);
9753 		q->q_ptr = NULL;
9754 		WR(q)->q_ptr = NULL;
9755 		return (err);
9756 	}
9757 
9758 	/* ill_init initializes the ipsq marking this thread as writer */
9759 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9760 	/* Wait for the DL_INFO_ACK */
9761 	mutex_enter(&ill->ill_lock);
9762 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9763 		/*
9764 		 * Return value of 0 indicates a pending signal.
9765 		 */
9766 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9767 		if (err == 0) {
9768 			mutex_exit(&ill->ill_lock);
9769 			(void) ip_close(q, 0);
9770 			return (EINTR);
9771 		}
9772 	}
9773 	mutex_exit(&ill->ill_lock);
9774 
9775 	/*
9776 	 * ip_rput_other could have set an error  in ill_error on
9777 	 * receipt of M_ERROR.
9778 	 */
9779 
9780 	err = ill->ill_error;
9781 	if (err != 0) {
9782 		(void) ip_close(q, 0);
9783 		return (err);
9784 	}
9785 
9786 	ill->ill_credp = credp;
9787 	crhold(credp);
9788 
9789 	mutex_enter(&ipst->ips_ip_mi_lock);
9790 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9791 	    credp);
9792 	mutex_exit(&ipst->ips_ip_mi_lock);
9793 	if (err) {
9794 		(void) ip_close(q, 0);
9795 		return (err);
9796 	}
9797 	return (0);
9798 }
9799 
9800 /* IP open routine. */
9801 int
9802 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9803 {
9804 	conn_t 		*connp;
9805 	major_t		maj;
9806 	zoneid_t	zoneid;
9807 	netstack_t	*ns;
9808 	ip_stack_t	*ipst;
9809 
9810 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9811 
9812 	/* Allow reopen. */
9813 	if (q->q_ptr != NULL)
9814 		return (0);
9815 
9816 	if (sflag & MODOPEN) {
9817 		/* This is a module open */
9818 		return (ip_modopen(q, devp, flag, sflag, credp));
9819 	}
9820 
9821 	ns = netstack_find_by_cred(credp);
9822 	ASSERT(ns != NULL);
9823 	ipst = ns->netstack_ip;
9824 	ASSERT(ipst != NULL);
9825 
9826 	/*
9827 	 * For exclusive stacks we set the zoneid to zero
9828 	 * to make IP operate as if in the global zone.
9829 	 */
9830 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9831 		zoneid = GLOBAL_ZONEID;
9832 	else
9833 		zoneid = crgetzoneid(credp);
9834 
9835 	/*
9836 	 * We are opening as a device. This is an IP client stream, and we
9837 	 * allocate an conn_t as the instance data.
9838 	 */
9839 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9840 
9841 	/*
9842 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9843 	 * done by netstack_find_by_cred()
9844 	 */
9845 	netstack_rele(ipst->ips_netstack);
9846 
9847 	connp->conn_zoneid = zoneid;
9848 
9849 	connp->conn_upq = q;
9850 	q->q_ptr = WR(q)->q_ptr = connp;
9851 
9852 	if (flag & SO_SOCKSTR)
9853 		connp->conn_flags |= IPCL_SOCKET;
9854 
9855 	/* Minor tells us which /dev entry was opened */
9856 	if (geteminor(*devp) == IPV6_MINOR) {
9857 		connp->conn_flags |= IPCL_ISV6;
9858 		connp->conn_af_isv6 = B_TRUE;
9859 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
9860 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9861 	} else {
9862 		connp->conn_af_isv6 = B_FALSE;
9863 		connp->conn_pkt_isv6 = B_FALSE;
9864 	}
9865 
9866 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9867 		/* CONN_DEC_REF takes care of netstack_rele() */
9868 		q->q_ptr = WR(q)->q_ptr = NULL;
9869 		CONN_DEC_REF(connp);
9870 		return (EBUSY);
9871 	}
9872 
9873 	maj = getemajor(*devp);
9874 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9875 
9876 	/*
9877 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9878 	 */
9879 	connp->conn_cred = credp;
9880 	crhold(connp->conn_cred);
9881 
9882 	/*
9883 	 * If the caller has the process-wide flag set, then default to MAC
9884 	 * exempt mode.  This allows read-down to unlabeled hosts.
9885 	 */
9886 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9887 		connp->conn_mac_exempt = B_TRUE;
9888 
9889 	/*
9890 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9891 	 * administrative ops.  In these cases, we just need a normal conn_t
9892 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9893 	 * an error will be returned.
9894 	 */
9895 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9896 		connp->conn_rq = q;
9897 		connp->conn_wq = WR(q);
9898 	} else {
9899 		connp->conn_ulp = IPPROTO_SCTP;
9900 		connp->conn_rq = connp->conn_wq = NULL;
9901 	}
9902 	/* Non-zero default values */
9903 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9904 
9905 	/*
9906 	 * Make the conn globally visible to walkers
9907 	 */
9908 	ASSERT(connp->conn_ref == 1);
9909 	mutex_enter(&connp->conn_lock);
9910 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9911 	mutex_exit(&connp->conn_lock);
9912 
9913 	qprocson(q);
9914 
9915 	return (0);
9916 }
9917 
9918 /*
9919  * Change q_qinfo based on the value of isv6.
9920  * This can not called on an ill queue.
9921  * Note that there is no race since either q_qinfo works for conn queues - it
9922  * is just an optimization to enter the best wput routine directly.
9923  */
9924 void
9925 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
9926 {
9927 	ASSERT(q->q_flag & QREADR);
9928 	ASSERT(WR(q)->q_next == NULL);
9929 	ASSERT(q->q_ptr != NULL);
9930 
9931 	if (minor == IPV6_MINOR)  {
9932 		if (bump_mib) {
9933 			BUMP_MIB(&ipst->ips_ip6_mib,
9934 			    ipIfStatsOutSwitchIPVersion);
9935 		}
9936 		q->q_qinfo = &rinit_ipv6;
9937 		WR(q)->q_qinfo = &winit_ipv6;
9938 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9939 	} else {
9940 		if (bump_mib) {
9941 			BUMP_MIB(&ipst->ips_ip_mib,
9942 			    ipIfStatsOutSwitchIPVersion);
9943 		}
9944 		q->q_qinfo = &iprinit;
9945 		WR(q)->q_qinfo = &ipwinit;
9946 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9947 	}
9948 
9949 }
9950 
9951 /*
9952  * See if IPsec needs loading because of the options in mp.
9953  */
9954 static boolean_t
9955 ipsec_opt_present(mblk_t *mp)
9956 {
9957 	uint8_t *optcp, *next_optcp, *opt_endcp;
9958 	struct opthdr *opt;
9959 	struct T_opthdr *topt;
9960 	int opthdr_len;
9961 	t_uscalar_t optname, optlevel;
9962 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9963 	ipsec_req_t *ipsr;
9964 
9965 	/*
9966 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9967 	 * return TRUE.
9968 	 */
9969 
9970 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9971 	opt_endcp = optcp + tor->OPT_length;
9972 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9973 		opthdr_len = sizeof (struct T_opthdr);
9974 	} else {		/* O_OPTMGMT_REQ */
9975 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9976 		opthdr_len = sizeof (struct opthdr);
9977 	}
9978 	for (; optcp < opt_endcp; optcp = next_optcp) {
9979 		if (optcp + opthdr_len > opt_endcp)
9980 			return (B_FALSE);	/* Not enough option header. */
9981 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9982 			topt = (struct T_opthdr *)optcp;
9983 			optlevel = topt->level;
9984 			optname = topt->name;
9985 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9986 		} else {
9987 			opt = (struct opthdr *)optcp;
9988 			optlevel = opt->level;
9989 			optname = opt->name;
9990 			next_optcp = optcp + opthdr_len +
9991 			    _TPI_ALIGN_OPT(opt->len);
9992 		}
9993 		if ((next_optcp < optcp) || /* wraparound pointer space */
9994 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9995 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9996 			return (B_FALSE); /* bad option buffer */
9997 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9998 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9999 			/*
10000 			 * Check to see if it's an all-bypass or all-zeroes
10001 			 * IPsec request.  Don't bother loading IPsec if
10002 			 * the socket doesn't want to use it.  (A good example
10003 			 * is a bypass request.)
10004 			 *
10005 			 * Basically, if any of the non-NEVER bits are set,
10006 			 * load IPsec.
10007 			 */
10008 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10009 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10010 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10011 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10012 			    != 0)
10013 				return (B_TRUE);
10014 		}
10015 	}
10016 	return (B_FALSE);
10017 }
10018 
10019 /*
10020  * If conn is is waiting for ipsec to finish loading, kick it.
10021  */
10022 /* ARGSUSED */
10023 static void
10024 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10025 {
10026 	t_scalar_t	optreq_prim;
10027 	mblk_t		*mp;
10028 	cred_t		*cr;
10029 	int		err = 0;
10030 
10031 	/*
10032 	 * This function is called, after ipsec loading is complete.
10033 	 * Since IP checks exclusively and atomically (i.e it prevents
10034 	 * ipsec load from completing until ip_optcom_req completes)
10035 	 * whether ipsec load is complete, there cannot be a race with IP
10036 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10037 	 */
10038 	mutex_enter(&connp->conn_lock);
10039 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10040 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10041 		mp = connp->conn_ipsec_opt_mp;
10042 		connp->conn_ipsec_opt_mp = NULL;
10043 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10044 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10045 		mutex_exit(&connp->conn_lock);
10046 
10047 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10048 
10049 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10050 		if (optreq_prim == T_OPTMGMT_REQ) {
10051 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10052 			    &ip_opt_obj);
10053 		} else {
10054 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10055 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10056 			    &ip_opt_obj);
10057 		}
10058 		if (err != EINPROGRESS)
10059 			CONN_OPER_PENDING_DONE(connp);
10060 		return;
10061 	}
10062 	mutex_exit(&connp->conn_lock);
10063 }
10064 
10065 /*
10066  * Called from the ipsec_loader thread, outside any perimeter, to tell
10067  * ip qenable any of the queues waiting for the ipsec loader to
10068  * complete.
10069  */
10070 void
10071 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10072 {
10073 	netstack_t *ns = ipss->ipsec_netstack;
10074 
10075 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10076 }
10077 
10078 /*
10079  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10080  * determines the grp on which it has to become exclusive, queues the mp
10081  * and sq draining restarts the optmgmt
10082  */
10083 static boolean_t
10084 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10085 {
10086 	conn_t *connp = Q_TO_CONN(q);
10087 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10088 
10089 	/*
10090 	 * Take IPsec requests and treat them special.
10091 	 */
10092 	if (ipsec_opt_present(mp)) {
10093 		/* First check if IPsec is loaded. */
10094 		mutex_enter(&ipss->ipsec_loader_lock);
10095 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10096 			mutex_exit(&ipss->ipsec_loader_lock);
10097 			return (B_FALSE);
10098 		}
10099 		mutex_enter(&connp->conn_lock);
10100 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10101 
10102 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10103 		connp->conn_ipsec_opt_mp = mp;
10104 		mutex_exit(&connp->conn_lock);
10105 		mutex_exit(&ipss->ipsec_loader_lock);
10106 
10107 		ipsec_loader_loadnow(ipss);
10108 		return (B_TRUE);
10109 	}
10110 	return (B_FALSE);
10111 }
10112 
10113 /*
10114  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10115  * all of them are copied to the conn_t. If the req is "zero", the policy is
10116  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10117  * fields.
10118  * We keep only the latest setting of the policy and thus policy setting
10119  * is not incremental/cumulative.
10120  *
10121  * Requests to set policies with multiple alternative actions will
10122  * go through a different API.
10123  */
10124 int
10125 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10126 {
10127 	uint_t ah_req = 0;
10128 	uint_t esp_req = 0;
10129 	uint_t se_req = 0;
10130 	ipsec_selkey_t sel;
10131 	ipsec_act_t *actp = NULL;
10132 	uint_t nact;
10133 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10134 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10135 	ipsec_policy_root_t *pr;
10136 	ipsec_policy_head_t *ph;
10137 	int fam;
10138 	boolean_t is_pol_reset;
10139 	int error = 0;
10140 	netstack_t	*ns = connp->conn_netstack;
10141 	ip_stack_t	*ipst = ns->netstack_ip;
10142 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10143 
10144 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10145 
10146 	/*
10147 	 * The IP_SEC_OPT option does not allow variable length parameters,
10148 	 * hence a request cannot be NULL.
10149 	 */
10150 	if (req == NULL)
10151 		return (EINVAL);
10152 
10153 	ah_req = req->ipsr_ah_req;
10154 	esp_req = req->ipsr_esp_req;
10155 	se_req = req->ipsr_self_encap_req;
10156 
10157 	/*
10158 	 * Are we dealing with a request to reset the policy (i.e.
10159 	 * zero requests).
10160 	 */
10161 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10162 	    (esp_req & REQ_MASK) == 0 &&
10163 	    (se_req & REQ_MASK) == 0);
10164 
10165 	if (!is_pol_reset) {
10166 		/*
10167 		 * If we couldn't load IPsec, fail with "protocol
10168 		 * not supported".
10169 		 * IPsec may not have been loaded for a request with zero
10170 		 * policies, so we don't fail in this case.
10171 		 */
10172 		mutex_enter(&ipss->ipsec_loader_lock);
10173 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10174 			mutex_exit(&ipss->ipsec_loader_lock);
10175 			return (EPROTONOSUPPORT);
10176 		}
10177 		mutex_exit(&ipss->ipsec_loader_lock);
10178 
10179 		/*
10180 		 * Test for valid requests. Invalid algorithms
10181 		 * need to be tested by IPsec code because new
10182 		 * algorithms can be added dynamically.
10183 		 */
10184 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10185 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10186 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10187 			return (EINVAL);
10188 		}
10189 
10190 		/*
10191 		 * Only privileged users can issue these
10192 		 * requests.
10193 		 */
10194 		if (((ah_req & IPSEC_PREF_NEVER) ||
10195 		    (esp_req & IPSEC_PREF_NEVER) ||
10196 		    (se_req & IPSEC_PREF_NEVER)) &&
10197 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10198 			return (EPERM);
10199 		}
10200 
10201 		/*
10202 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10203 		 * are mutually exclusive.
10204 		 */
10205 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10206 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10207 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10208 			/* Both of them are set */
10209 			return (EINVAL);
10210 		}
10211 	}
10212 
10213 	mutex_enter(&connp->conn_lock);
10214 
10215 	/*
10216 	 * If we have already cached policies in ip_bind_connected*(), don't
10217 	 * let them change now. We cache policies for connections
10218 	 * whose src,dst [addr, port] is known.
10219 	 */
10220 	if (connp->conn_policy_cached) {
10221 		mutex_exit(&connp->conn_lock);
10222 		return (EINVAL);
10223 	}
10224 
10225 	/*
10226 	 * We have a zero policies, reset the connection policy if already
10227 	 * set. This will cause the connection to inherit the
10228 	 * global policy, if any.
10229 	 */
10230 	if (is_pol_reset) {
10231 		if (connp->conn_policy != NULL) {
10232 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10233 			connp->conn_policy = NULL;
10234 		}
10235 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10236 		connp->conn_in_enforce_policy = B_FALSE;
10237 		connp->conn_out_enforce_policy = B_FALSE;
10238 		mutex_exit(&connp->conn_lock);
10239 		return (0);
10240 	}
10241 
10242 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10243 	    ipst->ips_netstack);
10244 	if (ph == NULL)
10245 		goto enomem;
10246 
10247 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10248 	if (actp == NULL)
10249 		goto enomem;
10250 
10251 	/*
10252 	 * Always allocate IPv4 policy entries, since they can also
10253 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10254 	 */
10255 	bzero(&sel, sizeof (sel));
10256 	sel.ipsl_valid = IPSL_IPV4;
10257 
10258 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10259 	    ipst->ips_netstack);
10260 	if (pin4 == NULL)
10261 		goto enomem;
10262 
10263 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10264 	    ipst->ips_netstack);
10265 	if (pout4 == NULL)
10266 		goto enomem;
10267 
10268 	if (connp->conn_pkt_isv6) {
10269 		/*
10270 		 * We're looking at a v6 socket, also allocate the
10271 		 * v6-specific entries...
10272 		 */
10273 		sel.ipsl_valid = IPSL_IPV6;
10274 		pin6 = ipsec_policy_create(&sel, actp, nact,
10275 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10276 		if (pin6 == NULL)
10277 			goto enomem;
10278 
10279 		pout6 = ipsec_policy_create(&sel, actp, nact,
10280 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10281 		if (pout6 == NULL)
10282 			goto enomem;
10283 
10284 		/*
10285 		 * .. and file them away in the right place.
10286 		 */
10287 		fam = IPSEC_AF_V6;
10288 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10289 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10290 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10291 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10292 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10293 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10294 	}
10295 
10296 	ipsec_actvec_free(actp, nact);
10297 
10298 	/*
10299 	 * File the v4 policies.
10300 	 */
10301 	fam = IPSEC_AF_V4;
10302 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10303 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10304 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10305 
10306 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10307 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10308 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10309 
10310 	/*
10311 	 * If the requests need security, set enforce_policy.
10312 	 * If the requests are IPSEC_PREF_NEVER, one should
10313 	 * still set conn_out_enforce_policy so that an ipsec_out
10314 	 * gets attached in ip_wput. This is needed so that
10315 	 * for connections that we don't cache policy in ip_bind,
10316 	 * if global policy matches in ip_wput_attach_policy, we
10317 	 * don't wrongly inherit global policy. Similarly, we need
10318 	 * to set conn_in_enforce_policy also so that we don't verify
10319 	 * policy wrongly.
10320 	 */
10321 	if ((ah_req & REQ_MASK) != 0 ||
10322 	    (esp_req & REQ_MASK) != 0 ||
10323 	    (se_req & REQ_MASK) != 0) {
10324 		connp->conn_in_enforce_policy = B_TRUE;
10325 		connp->conn_out_enforce_policy = B_TRUE;
10326 		connp->conn_flags |= IPCL_CHECK_POLICY;
10327 	}
10328 
10329 	mutex_exit(&connp->conn_lock);
10330 	return (error);
10331 #undef REQ_MASK
10332 
10333 	/*
10334 	 * Common memory-allocation-failure exit path.
10335 	 */
10336 enomem:
10337 	mutex_exit(&connp->conn_lock);
10338 	if (actp != NULL)
10339 		ipsec_actvec_free(actp, nact);
10340 	if (pin4 != NULL)
10341 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10342 	if (pout4 != NULL)
10343 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10344 	if (pin6 != NULL)
10345 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10346 	if (pout6 != NULL)
10347 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10348 	return (ENOMEM);
10349 }
10350 
10351 /*
10352  * Only for options that pass in an IP addr. Currently only V4 options
10353  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10354  * So this function assumes level is IPPROTO_IP
10355  */
10356 int
10357 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10358     mblk_t *first_mp)
10359 {
10360 	ipif_t *ipif = NULL;
10361 	int error;
10362 	ill_t *ill;
10363 	int zoneid;
10364 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10365 
10366 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10367 
10368 	if (addr != INADDR_ANY || checkonly) {
10369 		ASSERT(connp != NULL);
10370 		zoneid = IPCL_ZONEID(connp);
10371 		if (option == IP_NEXTHOP) {
10372 			ipif = ipif_lookup_onlink_addr(addr,
10373 			    connp->conn_zoneid, ipst);
10374 		} else {
10375 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10376 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10377 			    &error, ipst);
10378 		}
10379 		if (ipif == NULL) {
10380 			if (error == EINPROGRESS)
10381 				return (error);
10382 			else if ((option == IP_MULTICAST_IF) ||
10383 			    (option == IP_NEXTHOP))
10384 				return (EHOSTUNREACH);
10385 			else
10386 				return (EINVAL);
10387 		} else if (checkonly) {
10388 			if (option == IP_MULTICAST_IF) {
10389 				ill = ipif->ipif_ill;
10390 				/* not supported by the virtual network iface */
10391 				if (IS_VNI(ill)) {
10392 					ipif_refrele(ipif);
10393 					return (EINVAL);
10394 				}
10395 			}
10396 			ipif_refrele(ipif);
10397 			return (0);
10398 		}
10399 		ill = ipif->ipif_ill;
10400 		mutex_enter(&connp->conn_lock);
10401 		mutex_enter(&ill->ill_lock);
10402 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10403 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10404 			mutex_exit(&ill->ill_lock);
10405 			mutex_exit(&connp->conn_lock);
10406 			ipif_refrele(ipif);
10407 			return (option == IP_MULTICAST_IF ?
10408 			    EHOSTUNREACH : EINVAL);
10409 		}
10410 	} else {
10411 		mutex_enter(&connp->conn_lock);
10412 	}
10413 
10414 	/* None of the options below are supported on the VNI */
10415 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10416 		mutex_exit(&ill->ill_lock);
10417 		mutex_exit(&connp->conn_lock);
10418 		ipif_refrele(ipif);
10419 		return (EINVAL);
10420 	}
10421 
10422 	switch (option) {
10423 	case IP_DONTFAILOVER_IF:
10424 		/*
10425 		 * This option is used by in.mpathd to ensure
10426 		 * that IPMP probe packets only go out on the
10427 		 * test interfaces. in.mpathd sets this option
10428 		 * on the non-failover interfaces.
10429 		 * For backward compatibility, this option
10430 		 * implicitly sets IP_MULTICAST_IF, as used
10431 		 * be done in bind(), so that ip_wput gets
10432 		 * this ipif to send mcast packets.
10433 		 */
10434 		if (ipif != NULL) {
10435 			ASSERT(addr != INADDR_ANY);
10436 			connp->conn_nofailover_ill = ipif->ipif_ill;
10437 			connp->conn_multicast_ipif = ipif;
10438 		} else {
10439 			ASSERT(addr == INADDR_ANY);
10440 			connp->conn_nofailover_ill = NULL;
10441 			connp->conn_multicast_ipif = NULL;
10442 		}
10443 		break;
10444 
10445 	case IP_MULTICAST_IF:
10446 		connp->conn_multicast_ipif = ipif;
10447 		break;
10448 	case IP_NEXTHOP:
10449 		connp->conn_nexthop_v4 = addr;
10450 		connp->conn_nexthop_set = B_TRUE;
10451 		break;
10452 	}
10453 
10454 	if (ipif != NULL) {
10455 		mutex_exit(&ill->ill_lock);
10456 		mutex_exit(&connp->conn_lock);
10457 		ipif_refrele(ipif);
10458 		return (0);
10459 	}
10460 	mutex_exit(&connp->conn_lock);
10461 	/* We succeded in cleared the option */
10462 	return (0);
10463 }
10464 
10465 /*
10466  * For options that pass in an ifindex specifying the ill. V6 options always
10467  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10468  */
10469 int
10470 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10471     int level, int option, mblk_t *first_mp)
10472 {
10473 	ill_t *ill = NULL;
10474 	int error = 0;
10475 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10476 
10477 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10478 	if (ifindex != 0) {
10479 		ASSERT(connp != NULL);
10480 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10481 		    first_mp, ip_restart_optmgmt, &error, ipst);
10482 		if (ill != NULL) {
10483 			if (checkonly) {
10484 				/* not supported by the virtual network iface */
10485 				if (IS_VNI(ill)) {
10486 					ill_refrele(ill);
10487 					return (EINVAL);
10488 				}
10489 				ill_refrele(ill);
10490 				return (0);
10491 			}
10492 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10493 			    0, NULL)) {
10494 				ill_refrele(ill);
10495 				ill = NULL;
10496 				mutex_enter(&connp->conn_lock);
10497 				goto setit;
10498 			}
10499 			mutex_enter(&connp->conn_lock);
10500 			mutex_enter(&ill->ill_lock);
10501 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10502 				mutex_exit(&ill->ill_lock);
10503 				mutex_exit(&connp->conn_lock);
10504 				ill_refrele(ill);
10505 				ill = NULL;
10506 				mutex_enter(&connp->conn_lock);
10507 			}
10508 			goto setit;
10509 		} else if (error == EINPROGRESS) {
10510 			return (error);
10511 		} else {
10512 			error = 0;
10513 		}
10514 	}
10515 	mutex_enter(&connp->conn_lock);
10516 setit:
10517 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10518 
10519 	/*
10520 	 * The options below assume that the ILL (if any) transmits and/or
10521 	 * receives traffic. Neither of which is true for the virtual network
10522 	 * interface, so fail setting these on a VNI.
10523 	 */
10524 	if (IS_VNI(ill)) {
10525 		ASSERT(ill != NULL);
10526 		mutex_exit(&ill->ill_lock);
10527 		mutex_exit(&connp->conn_lock);
10528 		ill_refrele(ill);
10529 		return (EINVAL);
10530 	}
10531 
10532 	if (level == IPPROTO_IP) {
10533 		switch (option) {
10534 		case IP_BOUND_IF:
10535 			connp->conn_incoming_ill = ill;
10536 			connp->conn_outgoing_ill = ill;
10537 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10538 			    0 : ifindex;
10539 			break;
10540 
10541 		case IP_XMIT_IF:
10542 			/*
10543 			 * Similar to IP_BOUND_IF, but this only
10544 			 * determines the outgoing interface for
10545 			 * unicast packets. Also no IRE_CACHE entry
10546 			 * is added for the destination of the
10547 			 * outgoing packets.
10548 			 */
10549 			connp->conn_xmit_if_ill = ill;
10550 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10551 			    0 : ifindex;
10552 			break;
10553 
10554 		case IP_MULTICAST_IF:
10555 			/*
10556 			 * This option is an internal special. The socket
10557 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10558 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10559 			 * specifies an ifindex and we try first on V6 ill's.
10560 			 * If we don't find one, we they try using on v4 ill's
10561 			 * intenally and we come here.
10562 			 */
10563 			if (!checkonly && ill != NULL) {
10564 				ipif_t	*ipif;
10565 				ipif = ill->ill_ipif;
10566 
10567 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10568 					mutex_exit(&ill->ill_lock);
10569 					mutex_exit(&connp->conn_lock);
10570 					ill_refrele(ill);
10571 					ill = NULL;
10572 					mutex_enter(&connp->conn_lock);
10573 				} else {
10574 					connp->conn_multicast_ipif = ipif;
10575 				}
10576 			}
10577 			break;
10578 		}
10579 	} else {
10580 		switch (option) {
10581 		case IPV6_BOUND_IF:
10582 			connp->conn_incoming_ill = ill;
10583 			connp->conn_outgoing_ill = ill;
10584 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10585 			    0 : ifindex;
10586 			break;
10587 
10588 		case IPV6_BOUND_PIF:
10589 			/*
10590 			 * Limit all transmit to this ill.
10591 			 * Unlike IPV6_BOUND_IF, using this option
10592 			 * prevents load spreading and failover from
10593 			 * happening when the interface is part of the
10594 			 * group. That's why we don't need to remember
10595 			 * the ifindex in orig_bound_ifindex as in
10596 			 * IPV6_BOUND_IF.
10597 			 */
10598 			connp->conn_outgoing_pill = ill;
10599 			break;
10600 
10601 		case IPV6_DONTFAILOVER_IF:
10602 			/*
10603 			 * This option is used by in.mpathd to ensure
10604 			 * that IPMP probe packets only go out on the
10605 			 * test interfaces. in.mpathd sets this option
10606 			 * on the non-failover interfaces.
10607 			 */
10608 			connp->conn_nofailover_ill = ill;
10609 			/*
10610 			 * For backward compatibility, this option
10611 			 * implicitly sets ip_multicast_ill as used in
10612 			 * IP_MULTICAST_IF so that ip_wput gets
10613 			 * this ipif to send mcast packets.
10614 			 */
10615 			connp->conn_multicast_ill = ill;
10616 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10617 			    0 : ifindex;
10618 			break;
10619 
10620 		case IPV6_MULTICAST_IF:
10621 			/*
10622 			 * Set conn_multicast_ill to be the IPv6 ill.
10623 			 * Set conn_multicast_ipif to be an IPv4 ipif
10624 			 * for ifindex to make IPv4 mapped addresses
10625 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10626 			 * Even if no IPv6 ill exists for the ifindex
10627 			 * we need to check for an IPv4 ifindex in order
10628 			 * for this to work with mapped addresses. In that
10629 			 * case only set conn_multicast_ipif.
10630 			 */
10631 			if (!checkonly) {
10632 				if (ifindex == 0) {
10633 					connp->conn_multicast_ill = NULL;
10634 					connp->conn_orig_multicast_ifindex = 0;
10635 					connp->conn_multicast_ipif = NULL;
10636 				} else if (ill != NULL) {
10637 					connp->conn_multicast_ill = ill;
10638 					connp->conn_orig_multicast_ifindex =
10639 					    ifindex;
10640 				}
10641 			}
10642 			break;
10643 		}
10644 	}
10645 
10646 	if (ill != NULL) {
10647 		mutex_exit(&ill->ill_lock);
10648 		mutex_exit(&connp->conn_lock);
10649 		ill_refrele(ill);
10650 		return (0);
10651 	}
10652 	mutex_exit(&connp->conn_lock);
10653 	/*
10654 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10655 	 * locate the ill and could not set the option (ifindex != 0)
10656 	 */
10657 	return (ifindex == 0 ? 0 : EINVAL);
10658 }
10659 
10660 /* This routine sets socket options. */
10661 /* ARGSUSED */
10662 int
10663 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10664     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10665     void *dummy, cred_t *cr, mblk_t *first_mp)
10666 {
10667 	int		*i1 = (int *)invalp;
10668 	conn_t		*connp = Q_TO_CONN(q);
10669 	int		error = 0;
10670 	boolean_t	checkonly;
10671 	ire_t		*ire;
10672 	boolean_t	found;
10673 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10674 
10675 	switch (optset_context) {
10676 
10677 	case SETFN_OPTCOM_CHECKONLY:
10678 		checkonly = B_TRUE;
10679 		/*
10680 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10681 		 * inlen != 0 implies value supplied and
10682 		 * 	we have to "pretend" to set it.
10683 		 * inlen == 0 implies that there is no
10684 		 * 	value part in T_CHECK request and just validation
10685 		 * done elsewhere should be enough, we just return here.
10686 		 */
10687 		if (inlen == 0) {
10688 			*outlenp = 0;
10689 			return (0);
10690 		}
10691 		break;
10692 	case SETFN_OPTCOM_NEGOTIATE:
10693 	case SETFN_UD_NEGOTIATE:
10694 	case SETFN_CONN_NEGOTIATE:
10695 		checkonly = B_FALSE;
10696 		break;
10697 	default:
10698 		/*
10699 		 * We should never get here
10700 		 */
10701 		*outlenp = 0;
10702 		return (EINVAL);
10703 	}
10704 
10705 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10706 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10707 
10708 	/*
10709 	 * For fixed length options, no sanity check
10710 	 * of passed in length is done. It is assumed *_optcom_req()
10711 	 * routines do the right thing.
10712 	 */
10713 
10714 	switch (level) {
10715 	case SOL_SOCKET:
10716 		/*
10717 		 * conn_lock protects the bitfields, and is used to
10718 		 * set the fields atomically.
10719 		 */
10720 		switch (name) {
10721 		case SO_BROADCAST:
10722 			if (!checkonly) {
10723 				/* TODO: use value someplace? */
10724 				mutex_enter(&connp->conn_lock);
10725 				connp->conn_broadcast = *i1 ? 1 : 0;
10726 				mutex_exit(&connp->conn_lock);
10727 			}
10728 			break;	/* goto sizeof (int) option return */
10729 		case SO_USELOOPBACK:
10730 			if (!checkonly) {
10731 				/* TODO: use value someplace? */
10732 				mutex_enter(&connp->conn_lock);
10733 				connp->conn_loopback = *i1 ? 1 : 0;
10734 				mutex_exit(&connp->conn_lock);
10735 			}
10736 			break;	/* goto sizeof (int) option return */
10737 		case SO_DONTROUTE:
10738 			if (!checkonly) {
10739 				mutex_enter(&connp->conn_lock);
10740 				connp->conn_dontroute = *i1 ? 1 : 0;
10741 				mutex_exit(&connp->conn_lock);
10742 			}
10743 			break;	/* goto sizeof (int) option return */
10744 		case SO_REUSEADDR:
10745 			if (!checkonly) {
10746 				mutex_enter(&connp->conn_lock);
10747 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10748 				mutex_exit(&connp->conn_lock);
10749 			}
10750 			break;	/* goto sizeof (int) option return */
10751 		case SO_PROTOTYPE:
10752 			if (!checkonly) {
10753 				mutex_enter(&connp->conn_lock);
10754 				connp->conn_proto = *i1;
10755 				mutex_exit(&connp->conn_lock);
10756 			}
10757 			break;	/* goto sizeof (int) option return */
10758 		case SO_ALLZONES:
10759 			if (!checkonly) {
10760 				mutex_enter(&connp->conn_lock);
10761 				if (IPCL_IS_BOUND(connp)) {
10762 					mutex_exit(&connp->conn_lock);
10763 					return (EINVAL);
10764 				}
10765 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10766 				mutex_exit(&connp->conn_lock);
10767 			}
10768 			break;	/* goto sizeof (int) option return */
10769 		case SO_ANON_MLP:
10770 			if (!checkonly) {
10771 				mutex_enter(&connp->conn_lock);
10772 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10773 				mutex_exit(&connp->conn_lock);
10774 			}
10775 			break;	/* goto sizeof (int) option return */
10776 		case SO_MAC_EXEMPT:
10777 			if (secpolicy_net_mac_aware(cr) != 0 ||
10778 			    IPCL_IS_BOUND(connp))
10779 				return (EACCES);
10780 			if (!checkonly) {
10781 				mutex_enter(&connp->conn_lock);
10782 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10783 				mutex_exit(&connp->conn_lock);
10784 			}
10785 			break;	/* goto sizeof (int) option return */
10786 		default:
10787 			/*
10788 			 * "soft" error (negative)
10789 			 * option not handled at this level
10790 			 * Note: Do not modify *outlenp
10791 			 */
10792 			return (-EINVAL);
10793 		}
10794 		break;
10795 	case IPPROTO_IP:
10796 		switch (name) {
10797 		case IP_NEXTHOP:
10798 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10799 				return (EPERM);
10800 			/* FALLTHRU */
10801 		case IP_MULTICAST_IF:
10802 		case IP_DONTFAILOVER_IF: {
10803 			ipaddr_t addr = *i1;
10804 
10805 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10806 			    first_mp);
10807 			if (error != 0)
10808 				return (error);
10809 			break;	/* goto sizeof (int) option return */
10810 		}
10811 
10812 		case IP_MULTICAST_TTL:
10813 			/* Recorded in transport above IP */
10814 			*outvalp = *invalp;
10815 			*outlenp = sizeof (uchar_t);
10816 			return (0);
10817 		case IP_MULTICAST_LOOP:
10818 			if (!checkonly) {
10819 				mutex_enter(&connp->conn_lock);
10820 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10821 				mutex_exit(&connp->conn_lock);
10822 			}
10823 			*outvalp = *invalp;
10824 			*outlenp = sizeof (uchar_t);
10825 			return (0);
10826 		case IP_ADD_MEMBERSHIP:
10827 		case MCAST_JOIN_GROUP:
10828 		case IP_DROP_MEMBERSHIP:
10829 		case MCAST_LEAVE_GROUP: {
10830 			struct ip_mreq *mreqp;
10831 			struct group_req *greqp;
10832 			ire_t *ire;
10833 			boolean_t done = B_FALSE;
10834 			ipaddr_t group, ifaddr;
10835 			struct sockaddr_in *sin;
10836 			uint32_t *ifindexp;
10837 			boolean_t mcast_opt = B_TRUE;
10838 			mcast_record_t fmode;
10839 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10840 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10841 
10842 			switch (name) {
10843 			case IP_ADD_MEMBERSHIP:
10844 				mcast_opt = B_FALSE;
10845 				/* FALLTHRU */
10846 			case MCAST_JOIN_GROUP:
10847 				fmode = MODE_IS_EXCLUDE;
10848 				optfn = ip_opt_add_group;
10849 				break;
10850 
10851 			case IP_DROP_MEMBERSHIP:
10852 				mcast_opt = B_FALSE;
10853 				/* FALLTHRU */
10854 			case MCAST_LEAVE_GROUP:
10855 				fmode = MODE_IS_INCLUDE;
10856 				optfn = ip_opt_delete_group;
10857 				break;
10858 			}
10859 
10860 			if (mcast_opt) {
10861 				greqp = (struct group_req *)i1;
10862 				sin = (struct sockaddr_in *)&greqp->gr_group;
10863 				if (sin->sin_family != AF_INET) {
10864 					*outlenp = 0;
10865 					return (ENOPROTOOPT);
10866 				}
10867 				group = (ipaddr_t)sin->sin_addr.s_addr;
10868 				ifaddr = INADDR_ANY;
10869 				ifindexp = &greqp->gr_interface;
10870 			} else {
10871 				mreqp = (struct ip_mreq *)i1;
10872 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10873 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10874 				ifindexp = NULL;
10875 			}
10876 
10877 			/*
10878 			 * In the multirouting case, we need to replicate
10879 			 * the request on all interfaces that will take part
10880 			 * in replication.  We do so because multirouting is
10881 			 * reflective, thus we will probably receive multi-
10882 			 * casts on those interfaces.
10883 			 * The ip_multirt_apply_membership() succeeds if the
10884 			 * operation succeeds on at least one interface.
10885 			 */
10886 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10887 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10888 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10889 			if (ire != NULL) {
10890 				if (ire->ire_flags & RTF_MULTIRT) {
10891 					error = ip_multirt_apply_membership(
10892 					    optfn, ire, connp, checkonly, group,
10893 					    fmode, INADDR_ANY, first_mp);
10894 					done = B_TRUE;
10895 				}
10896 				ire_refrele(ire);
10897 			}
10898 			if (!done) {
10899 				error = optfn(connp, checkonly, group, ifaddr,
10900 				    ifindexp, fmode, INADDR_ANY, first_mp);
10901 			}
10902 			if (error) {
10903 				/*
10904 				 * EINPROGRESS is a soft error, needs retry
10905 				 * so don't make *outlenp zero.
10906 				 */
10907 				if (error != EINPROGRESS)
10908 					*outlenp = 0;
10909 				return (error);
10910 			}
10911 			/* OK return - copy input buffer into output buffer */
10912 			if (invalp != outvalp) {
10913 				/* don't trust bcopy for identical src/dst */
10914 				bcopy(invalp, outvalp, inlen);
10915 			}
10916 			*outlenp = inlen;
10917 			return (0);
10918 		}
10919 		case IP_BLOCK_SOURCE:
10920 		case IP_UNBLOCK_SOURCE:
10921 		case IP_ADD_SOURCE_MEMBERSHIP:
10922 		case IP_DROP_SOURCE_MEMBERSHIP:
10923 		case MCAST_BLOCK_SOURCE:
10924 		case MCAST_UNBLOCK_SOURCE:
10925 		case MCAST_JOIN_SOURCE_GROUP:
10926 		case MCAST_LEAVE_SOURCE_GROUP: {
10927 			struct ip_mreq_source *imreqp;
10928 			struct group_source_req *gsreqp;
10929 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10930 			uint32_t ifindex = 0;
10931 			mcast_record_t fmode;
10932 			struct sockaddr_in *sin;
10933 			ire_t *ire;
10934 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10935 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10936 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10937 
10938 			switch (name) {
10939 			case IP_BLOCK_SOURCE:
10940 				mcast_opt = B_FALSE;
10941 				/* FALLTHRU */
10942 			case MCAST_BLOCK_SOURCE:
10943 				fmode = MODE_IS_EXCLUDE;
10944 				optfn = ip_opt_add_group;
10945 				break;
10946 
10947 			case IP_UNBLOCK_SOURCE:
10948 				mcast_opt = B_FALSE;
10949 				/* FALLTHRU */
10950 			case MCAST_UNBLOCK_SOURCE:
10951 				fmode = MODE_IS_EXCLUDE;
10952 				optfn = ip_opt_delete_group;
10953 				break;
10954 
10955 			case IP_ADD_SOURCE_MEMBERSHIP:
10956 				mcast_opt = B_FALSE;
10957 				/* FALLTHRU */
10958 			case MCAST_JOIN_SOURCE_GROUP:
10959 				fmode = MODE_IS_INCLUDE;
10960 				optfn = ip_opt_add_group;
10961 				break;
10962 
10963 			case IP_DROP_SOURCE_MEMBERSHIP:
10964 				mcast_opt = B_FALSE;
10965 				/* FALLTHRU */
10966 			case MCAST_LEAVE_SOURCE_GROUP:
10967 				fmode = MODE_IS_INCLUDE;
10968 				optfn = ip_opt_delete_group;
10969 				break;
10970 			}
10971 
10972 			if (mcast_opt) {
10973 				gsreqp = (struct group_source_req *)i1;
10974 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10975 					*outlenp = 0;
10976 					return (ENOPROTOOPT);
10977 				}
10978 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10979 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10980 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10981 				src = (ipaddr_t)sin->sin_addr.s_addr;
10982 				ifindex = gsreqp->gsr_interface;
10983 			} else {
10984 				imreqp = (struct ip_mreq_source *)i1;
10985 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10986 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10987 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10988 			}
10989 
10990 			/*
10991 			 * In the multirouting case, we need to replicate
10992 			 * the request as noted in the mcast cases above.
10993 			 */
10994 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10995 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10996 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10997 			if (ire != NULL) {
10998 				if (ire->ire_flags & RTF_MULTIRT) {
10999 					error = ip_multirt_apply_membership(
11000 					    optfn, ire, connp, checkonly, grp,
11001 					    fmode, src, first_mp);
11002 					done = B_TRUE;
11003 				}
11004 				ire_refrele(ire);
11005 			}
11006 			if (!done) {
11007 				error = optfn(connp, checkonly, grp, ifaddr,
11008 				    &ifindex, fmode, src, first_mp);
11009 			}
11010 			if (error != 0) {
11011 				/*
11012 				 * EINPROGRESS is a soft error, needs retry
11013 				 * so don't make *outlenp zero.
11014 				 */
11015 				if (error != EINPROGRESS)
11016 					*outlenp = 0;
11017 				return (error);
11018 			}
11019 			/* OK return - copy input buffer into output buffer */
11020 			if (invalp != outvalp) {
11021 				bcopy(invalp, outvalp, inlen);
11022 			}
11023 			*outlenp = inlen;
11024 			return (0);
11025 		}
11026 		case IP_SEC_OPT:
11027 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11028 			if (error != 0) {
11029 				*outlenp = 0;
11030 				return (error);
11031 			}
11032 			break;
11033 		case IP_HDRINCL:
11034 		case IP_OPTIONS:
11035 		case T_IP_OPTIONS:
11036 		case IP_TOS:
11037 		case T_IP_TOS:
11038 		case IP_TTL:
11039 		case IP_RECVDSTADDR:
11040 		case IP_RECVOPTS:
11041 			/* OK return - copy input buffer into output buffer */
11042 			if (invalp != outvalp) {
11043 				/* don't trust bcopy for identical src/dst */
11044 				bcopy(invalp, outvalp, inlen);
11045 			}
11046 			*outlenp = inlen;
11047 			return (0);
11048 		case IP_RECVIF:
11049 			/* Retrieve the inbound interface index */
11050 			if (!checkonly) {
11051 				mutex_enter(&connp->conn_lock);
11052 				connp->conn_recvif = *i1 ? 1 : 0;
11053 				mutex_exit(&connp->conn_lock);
11054 			}
11055 			break;	/* goto sizeof (int) option return */
11056 		case IP_RECVPKTINFO:
11057 			if (!checkonly) {
11058 				mutex_enter(&connp->conn_lock);
11059 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11060 				mutex_exit(&connp->conn_lock);
11061 			}
11062 			break;	/* goto sizeof (int) option return */
11063 		case IP_RECVSLLA:
11064 			/* Retrieve the source link layer address */
11065 			if (!checkonly) {
11066 				mutex_enter(&connp->conn_lock);
11067 				connp->conn_recvslla = *i1 ? 1 : 0;
11068 				mutex_exit(&connp->conn_lock);
11069 			}
11070 			break;	/* goto sizeof (int) option return */
11071 		case MRT_INIT:
11072 		case MRT_DONE:
11073 		case MRT_ADD_VIF:
11074 		case MRT_DEL_VIF:
11075 		case MRT_ADD_MFC:
11076 		case MRT_DEL_MFC:
11077 		case MRT_ASSERT:
11078 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11079 				*outlenp = 0;
11080 				return (error);
11081 			}
11082 			error = ip_mrouter_set((int)name, q, checkonly,
11083 			    (uchar_t *)invalp, inlen, first_mp);
11084 			if (error) {
11085 				*outlenp = 0;
11086 				return (error);
11087 			}
11088 			/* OK return - copy input buffer into output buffer */
11089 			if (invalp != outvalp) {
11090 				/* don't trust bcopy for identical src/dst */
11091 				bcopy(invalp, outvalp, inlen);
11092 			}
11093 			*outlenp = inlen;
11094 			return (0);
11095 		case IP_BOUND_IF:
11096 		case IP_XMIT_IF:
11097 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11098 			    level, name, first_mp);
11099 			if (error != 0)
11100 				return (error);
11101 			break; 		/* goto sizeof (int) option return */
11102 
11103 		case IP_UNSPEC_SRC:
11104 			/* Allow sending with a zero source address */
11105 			if (!checkonly) {
11106 				mutex_enter(&connp->conn_lock);
11107 				connp->conn_unspec_src = *i1 ? 1 : 0;
11108 				mutex_exit(&connp->conn_lock);
11109 			}
11110 			break;	/* goto sizeof (int) option return */
11111 		default:
11112 			/*
11113 			 * "soft" error (negative)
11114 			 * option not handled at this level
11115 			 * Note: Do not modify *outlenp
11116 			 */
11117 			return (-EINVAL);
11118 		}
11119 		break;
11120 	case IPPROTO_IPV6:
11121 		switch (name) {
11122 		case IPV6_BOUND_IF:
11123 		case IPV6_BOUND_PIF:
11124 		case IPV6_DONTFAILOVER_IF:
11125 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11126 			    level, name, first_mp);
11127 			if (error != 0)
11128 				return (error);
11129 			break; 		/* goto sizeof (int) option return */
11130 
11131 		case IPV6_MULTICAST_IF:
11132 			/*
11133 			 * The only possible errors are EINPROGRESS and
11134 			 * EINVAL. EINPROGRESS will be restarted and is not
11135 			 * a hard error. We call this option on both V4 and V6
11136 			 * If both return EINVAL, then this call returns
11137 			 * EINVAL. If at least one of them succeeds we
11138 			 * return success.
11139 			 */
11140 			found = B_FALSE;
11141 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11142 			    level, name, first_mp);
11143 			if (error == EINPROGRESS)
11144 				return (error);
11145 			if (error == 0)
11146 				found = B_TRUE;
11147 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11148 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11149 			if (error == 0)
11150 				found = B_TRUE;
11151 			if (!found)
11152 				return (error);
11153 			break; 		/* goto sizeof (int) option return */
11154 
11155 		case IPV6_MULTICAST_HOPS:
11156 			/* Recorded in transport above IP */
11157 			break;	/* goto sizeof (int) option return */
11158 		case IPV6_MULTICAST_LOOP:
11159 			if (!checkonly) {
11160 				mutex_enter(&connp->conn_lock);
11161 				connp->conn_multicast_loop = *i1;
11162 				mutex_exit(&connp->conn_lock);
11163 			}
11164 			break;	/* goto sizeof (int) option return */
11165 		case IPV6_JOIN_GROUP:
11166 		case MCAST_JOIN_GROUP:
11167 		case IPV6_LEAVE_GROUP:
11168 		case MCAST_LEAVE_GROUP: {
11169 			struct ipv6_mreq *ip_mreqp;
11170 			struct group_req *greqp;
11171 			ire_t *ire;
11172 			boolean_t done = B_FALSE;
11173 			in6_addr_t groupv6;
11174 			uint32_t ifindex;
11175 			boolean_t mcast_opt = B_TRUE;
11176 			mcast_record_t fmode;
11177 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11178 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11179 
11180 			switch (name) {
11181 			case IPV6_JOIN_GROUP:
11182 				mcast_opt = B_FALSE;
11183 				/* FALLTHRU */
11184 			case MCAST_JOIN_GROUP:
11185 				fmode = MODE_IS_EXCLUDE;
11186 				optfn = ip_opt_add_group_v6;
11187 				break;
11188 
11189 			case IPV6_LEAVE_GROUP:
11190 				mcast_opt = B_FALSE;
11191 				/* FALLTHRU */
11192 			case MCAST_LEAVE_GROUP:
11193 				fmode = MODE_IS_INCLUDE;
11194 				optfn = ip_opt_delete_group_v6;
11195 				break;
11196 			}
11197 
11198 			if (mcast_opt) {
11199 				struct sockaddr_in *sin;
11200 				struct sockaddr_in6 *sin6;
11201 				greqp = (struct group_req *)i1;
11202 				if (greqp->gr_group.ss_family == AF_INET) {
11203 					sin = (struct sockaddr_in *)
11204 					    &(greqp->gr_group);
11205 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11206 					    &groupv6);
11207 				} else {
11208 					sin6 = (struct sockaddr_in6 *)
11209 					    &(greqp->gr_group);
11210 					groupv6 = sin6->sin6_addr;
11211 				}
11212 				ifindex = greqp->gr_interface;
11213 			} else {
11214 				ip_mreqp = (struct ipv6_mreq *)i1;
11215 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11216 				ifindex = ip_mreqp->ipv6mr_interface;
11217 			}
11218 			/*
11219 			 * In the multirouting case, we need to replicate
11220 			 * the request on all interfaces that will take part
11221 			 * in replication.  We do so because multirouting is
11222 			 * reflective, thus we will probably receive multi-
11223 			 * casts on those interfaces.
11224 			 * The ip_multirt_apply_membership_v6() succeeds if
11225 			 * the operation succeeds on at least one interface.
11226 			 */
11227 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11228 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11229 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11230 			if (ire != NULL) {
11231 				if (ire->ire_flags & RTF_MULTIRT) {
11232 					error = ip_multirt_apply_membership_v6(
11233 					    optfn, ire, connp, checkonly,
11234 					    &groupv6, fmode, &ipv6_all_zeros,
11235 					    first_mp);
11236 					done = B_TRUE;
11237 				}
11238 				ire_refrele(ire);
11239 			}
11240 			if (!done) {
11241 				error = optfn(connp, checkonly, &groupv6,
11242 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11243 			}
11244 			if (error) {
11245 				/*
11246 				 * EINPROGRESS is a soft error, needs retry
11247 				 * so don't make *outlenp zero.
11248 				 */
11249 				if (error != EINPROGRESS)
11250 					*outlenp = 0;
11251 				return (error);
11252 			}
11253 			/* OK return - copy input buffer into output buffer */
11254 			if (invalp != outvalp) {
11255 				/* don't trust bcopy for identical src/dst */
11256 				bcopy(invalp, outvalp, inlen);
11257 			}
11258 			*outlenp = inlen;
11259 			return (0);
11260 		}
11261 		case MCAST_BLOCK_SOURCE:
11262 		case MCAST_UNBLOCK_SOURCE:
11263 		case MCAST_JOIN_SOURCE_GROUP:
11264 		case MCAST_LEAVE_SOURCE_GROUP: {
11265 			struct group_source_req *gsreqp;
11266 			in6_addr_t v6grp, v6src;
11267 			uint32_t ifindex;
11268 			mcast_record_t fmode;
11269 			ire_t *ire;
11270 			boolean_t done = B_FALSE;
11271 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11272 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11273 
11274 			switch (name) {
11275 			case MCAST_BLOCK_SOURCE:
11276 				fmode = MODE_IS_EXCLUDE;
11277 				optfn = ip_opt_add_group_v6;
11278 				break;
11279 			case MCAST_UNBLOCK_SOURCE:
11280 				fmode = MODE_IS_EXCLUDE;
11281 				optfn = ip_opt_delete_group_v6;
11282 				break;
11283 			case MCAST_JOIN_SOURCE_GROUP:
11284 				fmode = MODE_IS_INCLUDE;
11285 				optfn = ip_opt_add_group_v6;
11286 				break;
11287 			case MCAST_LEAVE_SOURCE_GROUP:
11288 				fmode = MODE_IS_INCLUDE;
11289 				optfn = ip_opt_delete_group_v6;
11290 				break;
11291 			}
11292 
11293 			gsreqp = (struct group_source_req *)i1;
11294 			ifindex = gsreqp->gsr_interface;
11295 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11296 				struct sockaddr_in *s;
11297 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11298 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11299 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11300 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11301 			} else {
11302 				struct sockaddr_in6 *s6;
11303 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11304 				v6grp = s6->sin6_addr;
11305 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11306 				v6src = s6->sin6_addr;
11307 			}
11308 
11309 			/*
11310 			 * In the multirouting case, we need to replicate
11311 			 * the request as noted in the mcast cases above.
11312 			 */
11313 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11314 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11315 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11316 			if (ire != NULL) {
11317 				if (ire->ire_flags & RTF_MULTIRT) {
11318 					error = ip_multirt_apply_membership_v6(
11319 					    optfn, ire, connp, checkonly,
11320 					    &v6grp, fmode, &v6src, first_mp);
11321 					done = B_TRUE;
11322 				}
11323 				ire_refrele(ire);
11324 			}
11325 			if (!done) {
11326 				error = optfn(connp, checkonly, &v6grp,
11327 				    ifindex, fmode, &v6src, first_mp);
11328 			}
11329 			if (error != 0) {
11330 				/*
11331 				 * EINPROGRESS is a soft error, needs retry
11332 				 * so don't make *outlenp zero.
11333 				 */
11334 				if (error != EINPROGRESS)
11335 					*outlenp = 0;
11336 				return (error);
11337 			}
11338 			/* OK return - copy input buffer into output buffer */
11339 			if (invalp != outvalp) {
11340 				bcopy(invalp, outvalp, inlen);
11341 			}
11342 			*outlenp = inlen;
11343 			return (0);
11344 		}
11345 		case IPV6_UNICAST_HOPS:
11346 			/* Recorded in transport above IP */
11347 			break;	/* goto sizeof (int) option return */
11348 		case IPV6_UNSPEC_SRC:
11349 			/* Allow sending with a zero source address */
11350 			if (!checkonly) {
11351 				mutex_enter(&connp->conn_lock);
11352 				connp->conn_unspec_src = *i1 ? 1 : 0;
11353 				mutex_exit(&connp->conn_lock);
11354 			}
11355 			break;	/* goto sizeof (int) option return */
11356 		case IPV6_RECVPKTINFO:
11357 			if (!checkonly) {
11358 				mutex_enter(&connp->conn_lock);
11359 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11360 				mutex_exit(&connp->conn_lock);
11361 			}
11362 			break;	/* goto sizeof (int) option return */
11363 		case IPV6_RECVTCLASS:
11364 			if (!checkonly) {
11365 				if (*i1 < 0 || *i1 > 1) {
11366 					return (EINVAL);
11367 				}
11368 				mutex_enter(&connp->conn_lock);
11369 				connp->conn_ipv6_recvtclass = *i1;
11370 				mutex_exit(&connp->conn_lock);
11371 			}
11372 			break;
11373 		case IPV6_RECVPATHMTU:
11374 			if (!checkonly) {
11375 				if (*i1 < 0 || *i1 > 1) {
11376 					return (EINVAL);
11377 				}
11378 				mutex_enter(&connp->conn_lock);
11379 				connp->conn_ipv6_recvpathmtu = *i1;
11380 				mutex_exit(&connp->conn_lock);
11381 			}
11382 			break;
11383 		case IPV6_RECVHOPLIMIT:
11384 			if (!checkonly) {
11385 				mutex_enter(&connp->conn_lock);
11386 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11387 				mutex_exit(&connp->conn_lock);
11388 			}
11389 			break;	/* goto sizeof (int) option return */
11390 		case IPV6_RECVHOPOPTS:
11391 			if (!checkonly) {
11392 				mutex_enter(&connp->conn_lock);
11393 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11394 				mutex_exit(&connp->conn_lock);
11395 			}
11396 			break;	/* goto sizeof (int) option return */
11397 		case IPV6_RECVDSTOPTS:
11398 			if (!checkonly) {
11399 				mutex_enter(&connp->conn_lock);
11400 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11401 				mutex_exit(&connp->conn_lock);
11402 			}
11403 			break;	/* goto sizeof (int) option return */
11404 		case IPV6_RECVRTHDR:
11405 			if (!checkonly) {
11406 				mutex_enter(&connp->conn_lock);
11407 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11408 				mutex_exit(&connp->conn_lock);
11409 			}
11410 			break;	/* goto sizeof (int) option return */
11411 		case IPV6_RECVRTHDRDSTOPTS:
11412 			if (!checkonly) {
11413 				mutex_enter(&connp->conn_lock);
11414 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11415 				mutex_exit(&connp->conn_lock);
11416 			}
11417 			break;	/* goto sizeof (int) option return */
11418 		case IPV6_PKTINFO:
11419 			if (inlen == 0)
11420 				return (-EINVAL);	/* clearing option */
11421 			error = ip6_set_pktinfo(cr, connp,
11422 			    (struct in6_pktinfo *)invalp, first_mp);
11423 			if (error != 0)
11424 				*outlenp = 0;
11425 			else
11426 				*outlenp = inlen;
11427 			return (error);
11428 		case IPV6_NEXTHOP: {
11429 			struct sockaddr_in6 *sin6;
11430 
11431 			/* Verify that the nexthop is reachable */
11432 			if (inlen == 0)
11433 				return (-EINVAL);	/* clearing option */
11434 
11435 			sin6 = (struct sockaddr_in6 *)invalp;
11436 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11437 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11438 			    NULL, MATCH_IRE_DEFAULT, ipst);
11439 
11440 			if (ire == NULL) {
11441 				*outlenp = 0;
11442 				return (EHOSTUNREACH);
11443 			}
11444 			ire_refrele(ire);
11445 			return (-EINVAL);
11446 		}
11447 		case IPV6_SEC_OPT:
11448 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11449 			if (error != 0) {
11450 				*outlenp = 0;
11451 				return (error);
11452 			}
11453 			break;
11454 		case IPV6_SRC_PREFERENCES: {
11455 			/*
11456 			 * This is implemented strictly in the ip module
11457 			 * (here and in tcp_opt_*() to accomodate tcp
11458 			 * sockets).  Modules above ip pass this option
11459 			 * down here since ip is the only one that needs to
11460 			 * be aware of source address preferences.
11461 			 *
11462 			 * This socket option only affects connected
11463 			 * sockets that haven't already bound to a specific
11464 			 * IPv6 address.  In other words, sockets that
11465 			 * don't call bind() with an address other than the
11466 			 * unspecified address and that call connect().
11467 			 * ip_bind_connected_v6() passes these preferences
11468 			 * to the ipif_select_source_v6() function.
11469 			 */
11470 			if (inlen != sizeof (uint32_t))
11471 				return (EINVAL);
11472 			error = ip6_set_src_preferences(connp,
11473 			    *(uint32_t *)invalp);
11474 			if (error != 0) {
11475 				*outlenp = 0;
11476 				return (error);
11477 			} else {
11478 				*outlenp = sizeof (uint32_t);
11479 			}
11480 			break;
11481 		}
11482 		case IPV6_V6ONLY:
11483 			if (*i1 < 0 || *i1 > 1) {
11484 				return (EINVAL);
11485 			}
11486 			mutex_enter(&connp->conn_lock);
11487 			connp->conn_ipv6_v6only = *i1;
11488 			mutex_exit(&connp->conn_lock);
11489 			break;
11490 		default:
11491 			return (-EINVAL);
11492 		}
11493 		break;
11494 	default:
11495 		/*
11496 		 * "soft" error (negative)
11497 		 * option not handled at this level
11498 		 * Note: Do not modify *outlenp
11499 		 */
11500 		return (-EINVAL);
11501 	}
11502 	/*
11503 	 * Common case of return from an option that is sizeof (int)
11504 	 */
11505 	*(int *)outvalp = *i1;
11506 	*outlenp = sizeof (int);
11507 	return (0);
11508 }
11509 
11510 /*
11511  * This routine gets default values of certain options whose default
11512  * values are maintained by protocol specific code
11513  */
11514 /* ARGSUSED */
11515 int
11516 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11517 {
11518 	int *i1 = (int *)ptr;
11519 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11520 
11521 	switch (level) {
11522 	case IPPROTO_IP:
11523 		switch (name) {
11524 		case IP_MULTICAST_TTL:
11525 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11526 			return (sizeof (uchar_t));
11527 		case IP_MULTICAST_LOOP:
11528 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11529 			return (sizeof (uchar_t));
11530 		default:
11531 			return (-1);
11532 		}
11533 	case IPPROTO_IPV6:
11534 		switch (name) {
11535 		case IPV6_UNICAST_HOPS:
11536 			*i1 = ipst->ips_ipv6_def_hops;
11537 			return (sizeof (int));
11538 		case IPV6_MULTICAST_HOPS:
11539 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11540 			return (sizeof (int));
11541 		case IPV6_MULTICAST_LOOP:
11542 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11543 			return (sizeof (int));
11544 		case IPV6_V6ONLY:
11545 			*i1 = 1;
11546 			return (sizeof (int));
11547 		default:
11548 			return (-1);
11549 		}
11550 	default:
11551 		return (-1);
11552 	}
11553 	/* NOTREACHED */
11554 }
11555 
11556 /*
11557  * Given a destination address and a pointer to where to put the information
11558  * this routine fills in the mtuinfo.
11559  */
11560 int
11561 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11562     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11563 {
11564 	ire_t *ire;
11565 	ip_stack_t	*ipst = ns->netstack_ip;
11566 
11567 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11568 		return (-1);
11569 
11570 	bzero(mtuinfo, sizeof (*mtuinfo));
11571 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11572 	mtuinfo->ip6m_addr.sin6_port = port;
11573 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11574 
11575 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11576 	if (ire != NULL) {
11577 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11578 		ire_refrele(ire);
11579 	} else {
11580 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11581 	}
11582 	return (sizeof (struct ip6_mtuinfo));
11583 }
11584 
11585 /*
11586  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11587  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11588  * isn't.  This doesn't matter as the error checking is done properly for the
11589  * other MRT options coming in through ip_opt_set.
11590  */
11591 int
11592 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11593 {
11594 	conn_t		*connp = Q_TO_CONN(q);
11595 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11596 
11597 	switch (level) {
11598 	case IPPROTO_IP:
11599 		switch (name) {
11600 		case MRT_VERSION:
11601 		case MRT_ASSERT:
11602 			(void) ip_mrouter_get(name, q, ptr);
11603 			return (sizeof (int));
11604 		case IP_SEC_OPT:
11605 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11606 		case IP_NEXTHOP:
11607 			if (connp->conn_nexthop_set) {
11608 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11609 				return (sizeof (ipaddr_t));
11610 			} else
11611 				return (0);
11612 		case IP_RECVPKTINFO:
11613 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11614 			return (sizeof (int));
11615 		default:
11616 			break;
11617 		}
11618 		break;
11619 	case IPPROTO_IPV6:
11620 		switch (name) {
11621 		case IPV6_SEC_OPT:
11622 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11623 		case IPV6_SRC_PREFERENCES: {
11624 			return (ip6_get_src_preferences(connp,
11625 			    (uint32_t *)ptr));
11626 		}
11627 		case IPV6_V6ONLY:
11628 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11629 			return (sizeof (int));
11630 		case IPV6_PATHMTU:
11631 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11632 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11633 		default:
11634 			break;
11635 		}
11636 		break;
11637 	default:
11638 		break;
11639 	}
11640 	return (-1);
11641 }
11642 
11643 /* Named Dispatch routine to get a current value out of our parameter table. */
11644 /* ARGSUSED */
11645 static int
11646 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11647 {
11648 	ipparam_t *ippa = (ipparam_t *)cp;
11649 
11650 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11651 	return (0);
11652 }
11653 
11654 /* ARGSUSED */
11655 static int
11656 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11657 {
11658 
11659 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11660 	return (0);
11661 }
11662 
11663 /*
11664  * Set ip{,6}_forwarding values.  This means walking through all of the
11665  * ill's and toggling their forwarding values.
11666  */
11667 /* ARGSUSED */
11668 static int
11669 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11670 {
11671 	long new_value;
11672 	int *forwarding_value = (int *)cp;
11673 	ill_t *ill;
11674 	boolean_t isv6;
11675 	ill_walk_context_t ctx;
11676 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11677 
11678 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11679 
11680 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11681 	    new_value < 0 || new_value > 1) {
11682 		return (EINVAL);
11683 	}
11684 
11685 	*forwarding_value = new_value;
11686 
11687 	/*
11688 	 * Regardless of the current value of ip_forwarding, set all per-ill
11689 	 * values of ip_forwarding to the value being set.
11690 	 *
11691 	 * Bring all the ill's up to date with the new global value.
11692 	 */
11693 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11694 
11695 	if (isv6)
11696 		ill = ILL_START_WALK_V6(&ctx, ipst);
11697 	else
11698 		ill = ILL_START_WALK_V4(&ctx, ipst);
11699 
11700 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11701 		(void) ill_forward_set(ill, new_value != 0);
11702 
11703 	rw_exit(&ipst->ips_ill_g_lock);
11704 	return (0);
11705 }
11706 
11707 /*
11708  * Walk through the param array specified registering each element with the
11709  * Named Dispatch handler. This is called only during init. So it is ok
11710  * not to acquire any locks
11711  */
11712 static boolean_t
11713 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11714     ipndp_t *ipnd, size_t ipnd_cnt)
11715 {
11716 	for (; ippa_cnt-- > 0; ippa++) {
11717 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11718 			if (!nd_load(ndp, ippa->ip_param_name,
11719 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11720 				nd_free(ndp);
11721 				return (B_FALSE);
11722 			}
11723 		}
11724 	}
11725 
11726 	for (; ipnd_cnt-- > 0; ipnd++) {
11727 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11728 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11729 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11730 			    ipnd->ip_ndp_data)) {
11731 				nd_free(ndp);
11732 				return (B_FALSE);
11733 			}
11734 		}
11735 	}
11736 
11737 	return (B_TRUE);
11738 }
11739 
11740 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11741 /* ARGSUSED */
11742 static int
11743 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11744 {
11745 	long		new_value;
11746 	ipparam_t	*ippa = (ipparam_t *)cp;
11747 
11748 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11749 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11750 		return (EINVAL);
11751 	}
11752 	ippa->ip_param_value = new_value;
11753 	return (0);
11754 }
11755 
11756 /*
11757  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11758  * When an ipf is passed here for the first time, if
11759  * we already have in-order fragments on the queue, we convert from the fast-
11760  * path reassembly scheme to the hard-case scheme.  From then on, additional
11761  * fragments are reassembled here.  We keep track of the start and end offsets
11762  * of each piece, and the number of holes in the chain.  When the hole count
11763  * goes to zero, we are done!
11764  *
11765  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11766  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11767  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11768  * after the call to ip_reassemble().
11769  */
11770 int
11771 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11772     size_t msg_len)
11773 {
11774 	uint_t	end;
11775 	mblk_t	*next_mp;
11776 	mblk_t	*mp1;
11777 	uint_t	offset;
11778 	boolean_t incr_dups = B_TRUE;
11779 	boolean_t offset_zero_seen = B_FALSE;
11780 	boolean_t pkt_boundary_checked = B_FALSE;
11781 
11782 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11783 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11784 
11785 	/* Add in byte count */
11786 	ipf->ipf_count += msg_len;
11787 	if (ipf->ipf_end) {
11788 		/*
11789 		 * We were part way through in-order reassembly, but now there
11790 		 * is a hole.  We walk through messages already queued, and
11791 		 * mark them for hard case reassembly.  We know that up till
11792 		 * now they were in order starting from offset zero.
11793 		 */
11794 		offset = 0;
11795 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11796 			IP_REASS_SET_START(mp1, offset);
11797 			if (offset == 0) {
11798 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11799 				offset = -ipf->ipf_nf_hdr_len;
11800 			}
11801 			offset += mp1->b_wptr - mp1->b_rptr;
11802 			IP_REASS_SET_END(mp1, offset);
11803 		}
11804 		/* One hole at the end. */
11805 		ipf->ipf_hole_cnt = 1;
11806 		/* Brand it as a hard case, forever. */
11807 		ipf->ipf_end = 0;
11808 	}
11809 	/* Walk through all the new pieces. */
11810 	do {
11811 		end = start + (mp->b_wptr - mp->b_rptr);
11812 		/*
11813 		 * If start is 0, decrease 'end' only for the first mblk of
11814 		 * the fragment. Otherwise 'end' can get wrong value in the
11815 		 * second pass of the loop if first mblk is exactly the
11816 		 * size of ipf_nf_hdr_len.
11817 		 */
11818 		if (start == 0 && !offset_zero_seen) {
11819 			/* First segment */
11820 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11821 			end -= ipf->ipf_nf_hdr_len;
11822 			offset_zero_seen = B_TRUE;
11823 		}
11824 		next_mp = mp->b_cont;
11825 		/*
11826 		 * We are checking to see if there is any interesing data
11827 		 * to process.  If there isn't and the mblk isn't the
11828 		 * one which carries the unfragmentable header then we
11829 		 * drop it.  It's possible to have just the unfragmentable
11830 		 * header come through without any data.  That needs to be
11831 		 * saved.
11832 		 *
11833 		 * If the assert at the top of this function holds then the
11834 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11835 		 * is infrequently traveled enough that the test is left in
11836 		 * to protect against future code changes which break that
11837 		 * invariant.
11838 		 */
11839 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11840 			/* Empty.  Blast it. */
11841 			IP_REASS_SET_START(mp, 0);
11842 			IP_REASS_SET_END(mp, 0);
11843 			/*
11844 			 * If the ipf points to the mblk we are about to free,
11845 			 * update ipf to point to the next mblk (or NULL
11846 			 * if none).
11847 			 */
11848 			if (ipf->ipf_mp->b_cont == mp)
11849 				ipf->ipf_mp->b_cont = next_mp;
11850 			freeb(mp);
11851 			continue;
11852 		}
11853 		mp->b_cont = NULL;
11854 		IP_REASS_SET_START(mp, start);
11855 		IP_REASS_SET_END(mp, end);
11856 		if (!ipf->ipf_tail_mp) {
11857 			ipf->ipf_tail_mp = mp;
11858 			ipf->ipf_mp->b_cont = mp;
11859 			if (start == 0 || !more) {
11860 				ipf->ipf_hole_cnt = 1;
11861 				/*
11862 				 * if the first fragment comes in more than one
11863 				 * mblk, this loop will be executed for each
11864 				 * mblk. Need to adjust hole count so exiting
11865 				 * this routine will leave hole count at 1.
11866 				 */
11867 				if (next_mp)
11868 					ipf->ipf_hole_cnt++;
11869 			} else
11870 				ipf->ipf_hole_cnt = 2;
11871 			continue;
11872 		} else if (ipf->ipf_last_frag_seen && !more &&
11873 		    !pkt_boundary_checked) {
11874 			/*
11875 			 * We check datagram boundary only if this fragment
11876 			 * claims to be the last fragment and we have seen a
11877 			 * last fragment in the past too. We do this only
11878 			 * once for a given fragment.
11879 			 *
11880 			 * start cannot be 0 here as fragments with start=0
11881 			 * and MF=0 gets handled as a complete packet. These
11882 			 * fragments should not reach here.
11883 			 */
11884 
11885 			if (start + msgdsize(mp) !=
11886 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11887 				/*
11888 				 * We have two fragments both of which claim
11889 				 * to be the last fragment but gives conflicting
11890 				 * information about the whole datagram size.
11891 				 * Something fishy is going on. Drop the
11892 				 * fragment and free up the reassembly list.
11893 				 */
11894 				return (IP_REASS_FAILED);
11895 			}
11896 
11897 			/*
11898 			 * We shouldn't come to this code block again for this
11899 			 * particular fragment.
11900 			 */
11901 			pkt_boundary_checked = B_TRUE;
11902 		}
11903 
11904 		/* New stuff at or beyond tail? */
11905 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11906 		if (start >= offset) {
11907 			if (ipf->ipf_last_frag_seen) {
11908 				/* current fragment is beyond last fragment */
11909 				return (IP_REASS_FAILED);
11910 			}
11911 			/* Link it on end. */
11912 			ipf->ipf_tail_mp->b_cont = mp;
11913 			ipf->ipf_tail_mp = mp;
11914 			if (more) {
11915 				if (start != offset)
11916 					ipf->ipf_hole_cnt++;
11917 			} else if (start == offset && next_mp == NULL)
11918 					ipf->ipf_hole_cnt--;
11919 			continue;
11920 		}
11921 		mp1 = ipf->ipf_mp->b_cont;
11922 		offset = IP_REASS_START(mp1);
11923 		/* New stuff at the front? */
11924 		if (start < offset) {
11925 			if (start == 0) {
11926 				if (end >= offset) {
11927 					/* Nailed the hole at the begining. */
11928 					ipf->ipf_hole_cnt--;
11929 				}
11930 			} else if (end < offset) {
11931 				/*
11932 				 * A hole, stuff, and a hole where there used
11933 				 * to be just a hole.
11934 				 */
11935 				ipf->ipf_hole_cnt++;
11936 			}
11937 			mp->b_cont = mp1;
11938 			/* Check for overlap. */
11939 			while (end > offset) {
11940 				if (end < IP_REASS_END(mp1)) {
11941 					mp->b_wptr -= end - offset;
11942 					IP_REASS_SET_END(mp, offset);
11943 					BUMP_MIB(ill->ill_ip_mib,
11944 					    ipIfStatsReasmPartDups);
11945 					break;
11946 				}
11947 				/* Did we cover another hole? */
11948 				if ((mp1->b_cont &&
11949 				    IP_REASS_END(mp1) !=
11950 				    IP_REASS_START(mp1->b_cont) &&
11951 				    end >= IP_REASS_START(mp1->b_cont)) ||
11952 				    (!ipf->ipf_last_frag_seen && !more)) {
11953 					ipf->ipf_hole_cnt--;
11954 				}
11955 				/* Clip out mp1. */
11956 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11957 					/*
11958 					 * After clipping out mp1, this guy
11959 					 * is now hanging off the end.
11960 					 */
11961 					ipf->ipf_tail_mp = mp;
11962 				}
11963 				IP_REASS_SET_START(mp1, 0);
11964 				IP_REASS_SET_END(mp1, 0);
11965 				/* Subtract byte count */
11966 				ipf->ipf_count -= mp1->b_datap->db_lim -
11967 				    mp1->b_datap->db_base;
11968 				freeb(mp1);
11969 				BUMP_MIB(ill->ill_ip_mib,
11970 				    ipIfStatsReasmPartDups);
11971 				mp1 = mp->b_cont;
11972 				if (!mp1)
11973 					break;
11974 				offset = IP_REASS_START(mp1);
11975 			}
11976 			ipf->ipf_mp->b_cont = mp;
11977 			continue;
11978 		}
11979 		/*
11980 		 * The new piece starts somewhere between the start of the head
11981 		 * and before the end of the tail.
11982 		 */
11983 		for (; mp1; mp1 = mp1->b_cont) {
11984 			offset = IP_REASS_END(mp1);
11985 			if (start < offset) {
11986 				if (end <= offset) {
11987 					/* Nothing new. */
11988 					IP_REASS_SET_START(mp, 0);
11989 					IP_REASS_SET_END(mp, 0);
11990 					/* Subtract byte count */
11991 					ipf->ipf_count -= mp->b_datap->db_lim -
11992 					    mp->b_datap->db_base;
11993 					if (incr_dups) {
11994 						ipf->ipf_num_dups++;
11995 						incr_dups = B_FALSE;
11996 					}
11997 					freeb(mp);
11998 					BUMP_MIB(ill->ill_ip_mib,
11999 					    ipIfStatsReasmDuplicates);
12000 					break;
12001 				}
12002 				/*
12003 				 * Trim redundant stuff off beginning of new
12004 				 * piece.
12005 				 */
12006 				IP_REASS_SET_START(mp, offset);
12007 				mp->b_rptr += offset - start;
12008 				BUMP_MIB(ill->ill_ip_mib,
12009 				    ipIfStatsReasmPartDups);
12010 				start = offset;
12011 				if (!mp1->b_cont) {
12012 					/*
12013 					 * After trimming, this guy is now
12014 					 * hanging off the end.
12015 					 */
12016 					mp1->b_cont = mp;
12017 					ipf->ipf_tail_mp = mp;
12018 					if (!more) {
12019 						ipf->ipf_hole_cnt--;
12020 					}
12021 					break;
12022 				}
12023 			}
12024 			if (start >= IP_REASS_START(mp1->b_cont))
12025 				continue;
12026 			/* Fill a hole */
12027 			if (start > offset)
12028 				ipf->ipf_hole_cnt++;
12029 			mp->b_cont = mp1->b_cont;
12030 			mp1->b_cont = mp;
12031 			mp1 = mp->b_cont;
12032 			offset = IP_REASS_START(mp1);
12033 			if (end >= offset) {
12034 				ipf->ipf_hole_cnt--;
12035 				/* Check for overlap. */
12036 				while (end > offset) {
12037 					if (end < IP_REASS_END(mp1)) {
12038 						mp->b_wptr -= end - offset;
12039 						IP_REASS_SET_END(mp, offset);
12040 						/*
12041 						 * TODO we might bump
12042 						 * this up twice if there is
12043 						 * overlap at both ends.
12044 						 */
12045 						BUMP_MIB(ill->ill_ip_mib,
12046 						    ipIfStatsReasmPartDups);
12047 						break;
12048 					}
12049 					/* Did we cover another hole? */
12050 					if ((mp1->b_cont &&
12051 					    IP_REASS_END(mp1)
12052 					    != IP_REASS_START(mp1->b_cont) &&
12053 					    end >=
12054 					    IP_REASS_START(mp1->b_cont)) ||
12055 					    (!ipf->ipf_last_frag_seen &&
12056 					    !more)) {
12057 						ipf->ipf_hole_cnt--;
12058 					}
12059 					/* Clip out mp1. */
12060 					if ((mp->b_cont = mp1->b_cont) ==
12061 					    NULL) {
12062 						/*
12063 						 * After clipping out mp1,
12064 						 * this guy is now hanging
12065 						 * off the end.
12066 						 */
12067 						ipf->ipf_tail_mp = mp;
12068 					}
12069 					IP_REASS_SET_START(mp1, 0);
12070 					IP_REASS_SET_END(mp1, 0);
12071 					/* Subtract byte count */
12072 					ipf->ipf_count -=
12073 					    mp1->b_datap->db_lim -
12074 					    mp1->b_datap->db_base;
12075 					freeb(mp1);
12076 					BUMP_MIB(ill->ill_ip_mib,
12077 					    ipIfStatsReasmPartDups);
12078 					mp1 = mp->b_cont;
12079 					if (!mp1)
12080 						break;
12081 					offset = IP_REASS_START(mp1);
12082 				}
12083 			}
12084 			break;
12085 		}
12086 	} while (start = end, mp = next_mp);
12087 
12088 	/* Fragment just processed could be the last one. Remember this fact */
12089 	if (!more)
12090 		ipf->ipf_last_frag_seen = B_TRUE;
12091 
12092 	/* Still got holes? */
12093 	if (ipf->ipf_hole_cnt)
12094 		return (IP_REASS_PARTIAL);
12095 	/* Clean up overloaded fields to avoid upstream disasters. */
12096 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12097 		IP_REASS_SET_START(mp1, 0);
12098 		IP_REASS_SET_END(mp1, 0);
12099 	}
12100 	return (IP_REASS_COMPLETE);
12101 }
12102 
12103 /*
12104  * ipsec processing for the fast path, used for input UDP Packets
12105  * Returns true if ready for passup to UDP.
12106  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12107  * was an ESP-in-UDP packet, etc.).
12108  */
12109 static boolean_t
12110 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12111     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12112 {
12113 	uint32_t	ill_index;
12114 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12115 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12116 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12117 	udp_t		*udp = connp->conn_udp;
12118 
12119 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12120 	/* The ill_index of the incoming ILL */
12121 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12122 
12123 	/* pass packet up to the transport */
12124 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12125 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12126 		    NULL, mctl_present);
12127 		if (*first_mpp == NULL) {
12128 			return (B_FALSE);
12129 		}
12130 	}
12131 
12132 	/* Initiate IPPF processing for fastpath UDP */
12133 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12134 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12135 		if (*mpp == NULL) {
12136 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12137 			    "deferred/dropped during IPPF processing\n"));
12138 			return (B_FALSE);
12139 		}
12140 	}
12141 	/*
12142 	 * Remove 0-spi if it's 0, or move everything behind
12143 	 * the UDP header over it and forward to ESP via
12144 	 * ip_proto_input().
12145 	 */
12146 	if (udp->udp_nat_t_endpoint) {
12147 		if (mctl_present) {
12148 			/* mctl_present *shouldn't* happen. */
12149 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12150 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12151 			    &ipss->ipsec_dropper);
12152 			*first_mpp = NULL;
12153 			return (B_FALSE);
12154 		}
12155 
12156 		/* "ill" is "recv_ill" in actuality. */
12157 		if (!zero_spi_check(q, *mpp, ipha, ire, ill, ipss))
12158 			return (B_FALSE);
12159 
12160 		/* Else continue like a normal UDP packet. */
12161 	}
12162 
12163 	/*
12164 	 * We make the checks as below since we are in the fast path
12165 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12166 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12167 	 */
12168 	if (connp->conn_recvif || connp->conn_recvslla ||
12169 	    connp->conn_ip_recvpktinfo) {
12170 		if (connp->conn_recvif) {
12171 			in_flags = IPF_RECVIF;
12172 		}
12173 		/*
12174 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12175 		 * so the flag passed to ip_add_info is based on IP version
12176 		 * of connp.
12177 		 */
12178 		if (connp->conn_ip_recvpktinfo) {
12179 			if (connp->conn_af_isv6) {
12180 				/*
12181 				 * V6 only needs index
12182 				 */
12183 				in_flags |= IPF_RECVIF;
12184 			} else {
12185 				/*
12186 				 * V4 needs index + matching address.
12187 				 */
12188 				in_flags |= IPF_RECVADDR;
12189 			}
12190 		}
12191 		if (connp->conn_recvslla) {
12192 			in_flags |= IPF_RECVSLLA;
12193 		}
12194 		/*
12195 		 * since in_flags are being set ill will be
12196 		 * referenced in ip_add_info, so it better not
12197 		 * be NULL.
12198 		 */
12199 		/*
12200 		 * the actual data will be contained in b_cont
12201 		 * upon successful return of the following call.
12202 		 * If the call fails then the original mblk is
12203 		 * returned.
12204 		 */
12205 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12206 		    ipst);
12207 	}
12208 
12209 	return (B_TRUE);
12210 }
12211 
12212 /*
12213  * Fragmentation reassembly.  Each ILL has a hash table for
12214  * queuing packets undergoing reassembly for all IPIFs
12215  * associated with the ILL.  The hash is based on the packet
12216  * IP ident field.  The ILL frag hash table was allocated
12217  * as a timer block at the time the ILL was created.  Whenever
12218  * there is anything on the reassembly queue, the timer will
12219  * be running.  Returns B_TRUE if successful else B_FALSE;
12220  * frees mp on failure.
12221  */
12222 static boolean_t
12223 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12224     uint32_t *cksum_val, uint16_t *cksum_flags)
12225 {
12226 	uint32_t	frag_offset_flags;
12227 	ill_t		*ill = (ill_t *)q->q_ptr;
12228 	mblk_t		*mp = *mpp;
12229 	mblk_t		*t_mp;
12230 	ipaddr_t	dst;
12231 	uint8_t		proto = ipha->ipha_protocol;
12232 	uint32_t	sum_val;
12233 	uint16_t	sum_flags;
12234 	ipf_t		*ipf;
12235 	ipf_t		**ipfp;
12236 	ipfb_t		*ipfb;
12237 	uint16_t	ident;
12238 	uint32_t	offset;
12239 	ipaddr_t	src;
12240 	uint_t		hdr_length;
12241 	uint32_t	end;
12242 	mblk_t		*mp1;
12243 	mblk_t		*tail_mp;
12244 	size_t		count;
12245 	size_t		msg_len;
12246 	uint8_t		ecn_info = 0;
12247 	uint32_t	packet_size;
12248 	boolean_t	pruned = B_FALSE;
12249 	ip_stack_t *ipst = ill->ill_ipst;
12250 
12251 	if (cksum_val != NULL)
12252 		*cksum_val = 0;
12253 	if (cksum_flags != NULL)
12254 		*cksum_flags = 0;
12255 
12256 	/*
12257 	 * Drop the fragmented as early as possible, if
12258 	 * we don't have resource(s) to re-assemble.
12259 	 */
12260 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12261 		freemsg(mp);
12262 		return (B_FALSE);
12263 	}
12264 
12265 	/* Check for fragmentation offset; return if there's none */
12266 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12267 	    (IPH_MF | IPH_OFFSET)) == 0)
12268 		return (B_TRUE);
12269 
12270 	/*
12271 	 * We utilize hardware computed checksum info only for UDP since
12272 	 * IP fragmentation is a normal occurence for the protocol.  In
12273 	 * addition, checksum offload support for IP fragments carrying
12274 	 * UDP payload is commonly implemented across network adapters.
12275 	 */
12276 	ASSERT(ill != NULL);
12277 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12278 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12279 		mblk_t *mp1 = mp->b_cont;
12280 		int32_t len;
12281 
12282 		/* Record checksum information from the packet */
12283 		sum_val = (uint32_t)DB_CKSUM16(mp);
12284 		sum_flags = DB_CKSUMFLAGS(mp);
12285 
12286 		/* IP payload offset from beginning of mblk */
12287 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12288 
12289 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12290 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12291 		    offset >= DB_CKSUMSTART(mp) &&
12292 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12293 			uint32_t adj;
12294 			/*
12295 			 * Partial checksum has been calculated by hardware
12296 			 * and attached to the packet; in addition, any
12297 			 * prepended extraneous data is even byte aligned.
12298 			 * If any such data exists, we adjust the checksum;
12299 			 * this would also handle any postpended data.
12300 			 */
12301 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12302 			    mp, mp1, len, adj);
12303 
12304 			/* One's complement subtract extraneous checksum */
12305 			if (adj >= sum_val)
12306 				sum_val = ~(adj - sum_val) & 0xFFFF;
12307 			else
12308 				sum_val -= adj;
12309 		}
12310 	} else {
12311 		sum_val = 0;
12312 		sum_flags = 0;
12313 	}
12314 
12315 	/* Clear hardware checksumming flag */
12316 	DB_CKSUMFLAGS(mp) = 0;
12317 
12318 	ident = ipha->ipha_ident;
12319 	offset = (frag_offset_flags << 3) & 0xFFFF;
12320 	src = ipha->ipha_src;
12321 	dst = ipha->ipha_dst;
12322 	hdr_length = IPH_HDR_LENGTH(ipha);
12323 	end = ntohs(ipha->ipha_length) - hdr_length;
12324 
12325 	/* If end == 0 then we have a packet with no data, so just free it */
12326 	if (end == 0) {
12327 		freemsg(mp);
12328 		return (B_FALSE);
12329 	}
12330 
12331 	/* Record the ECN field info. */
12332 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12333 	if (offset != 0) {
12334 		/*
12335 		 * If this isn't the first piece, strip the header, and
12336 		 * add the offset to the end value.
12337 		 */
12338 		mp->b_rptr += hdr_length;
12339 		end += offset;
12340 	}
12341 
12342 	msg_len = MBLKSIZE(mp);
12343 	tail_mp = mp;
12344 	while (tail_mp->b_cont != NULL) {
12345 		tail_mp = tail_mp->b_cont;
12346 		msg_len += MBLKSIZE(tail_mp);
12347 	}
12348 
12349 	/* If the reassembly list for this ILL will get too big, prune it */
12350 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12351 	    ipst->ips_ip_reass_queue_bytes) {
12352 		ill_frag_prune(ill,
12353 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12354 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12355 		pruned = B_TRUE;
12356 	}
12357 
12358 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12359 	mutex_enter(&ipfb->ipfb_lock);
12360 
12361 	ipfp = &ipfb->ipfb_ipf;
12362 	/* Try to find an existing fragment queue for this packet. */
12363 	for (;;) {
12364 		ipf = ipfp[0];
12365 		if (ipf != NULL) {
12366 			/*
12367 			 * It has to match on ident and src/dst address.
12368 			 */
12369 			if (ipf->ipf_ident == ident &&
12370 			    ipf->ipf_src == src &&
12371 			    ipf->ipf_dst == dst &&
12372 			    ipf->ipf_protocol == proto) {
12373 				/*
12374 				 * If we have received too many
12375 				 * duplicate fragments for this packet
12376 				 * free it.
12377 				 */
12378 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12379 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12380 					freemsg(mp);
12381 					mutex_exit(&ipfb->ipfb_lock);
12382 					return (B_FALSE);
12383 				}
12384 				/* Found it. */
12385 				break;
12386 			}
12387 			ipfp = &ipf->ipf_hash_next;
12388 			continue;
12389 		}
12390 
12391 		/*
12392 		 * If we pruned the list, do we want to store this new
12393 		 * fragment?. We apply an optimization here based on the
12394 		 * fact that most fragments will be received in order.
12395 		 * So if the offset of this incoming fragment is zero,
12396 		 * it is the first fragment of a new packet. We will
12397 		 * keep it.  Otherwise drop the fragment, as we have
12398 		 * probably pruned the packet already (since the
12399 		 * packet cannot be found).
12400 		 */
12401 		if (pruned && offset != 0) {
12402 			mutex_exit(&ipfb->ipfb_lock);
12403 			freemsg(mp);
12404 			return (B_FALSE);
12405 		}
12406 
12407 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12408 			/*
12409 			 * Too many fragmented packets in this hash
12410 			 * bucket. Free the oldest.
12411 			 */
12412 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12413 		}
12414 
12415 		/* New guy.  Allocate a frag message. */
12416 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12417 		if (mp1 == NULL) {
12418 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12419 			freemsg(mp);
12420 reass_done:
12421 			mutex_exit(&ipfb->ipfb_lock);
12422 			return (B_FALSE);
12423 		}
12424 
12425 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12426 		mp1->b_cont = mp;
12427 
12428 		/* Initialize the fragment header. */
12429 		ipf = (ipf_t *)mp1->b_rptr;
12430 		ipf->ipf_mp = mp1;
12431 		ipf->ipf_ptphn = ipfp;
12432 		ipfp[0] = ipf;
12433 		ipf->ipf_hash_next = NULL;
12434 		ipf->ipf_ident = ident;
12435 		ipf->ipf_protocol = proto;
12436 		ipf->ipf_src = src;
12437 		ipf->ipf_dst = dst;
12438 		ipf->ipf_nf_hdr_len = 0;
12439 		/* Record reassembly start time. */
12440 		ipf->ipf_timestamp = gethrestime_sec();
12441 		/* Record ipf generation and account for frag header */
12442 		ipf->ipf_gen = ill->ill_ipf_gen++;
12443 		ipf->ipf_count = MBLKSIZE(mp1);
12444 		ipf->ipf_last_frag_seen = B_FALSE;
12445 		ipf->ipf_ecn = ecn_info;
12446 		ipf->ipf_num_dups = 0;
12447 		ipfb->ipfb_frag_pkts++;
12448 		ipf->ipf_checksum = 0;
12449 		ipf->ipf_checksum_flags = 0;
12450 
12451 		/* Store checksum value in fragment header */
12452 		if (sum_flags != 0) {
12453 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12454 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12455 			ipf->ipf_checksum = sum_val;
12456 			ipf->ipf_checksum_flags = sum_flags;
12457 		}
12458 
12459 		/*
12460 		 * We handle reassembly two ways.  In the easy case,
12461 		 * where all the fragments show up in order, we do
12462 		 * minimal bookkeeping, and just clip new pieces on
12463 		 * the end.  If we ever see a hole, then we go off
12464 		 * to ip_reassemble which has to mark the pieces and
12465 		 * keep track of the number of holes, etc.  Obviously,
12466 		 * the point of having both mechanisms is so we can
12467 		 * handle the easy case as efficiently as possible.
12468 		 */
12469 		if (offset == 0) {
12470 			/* Easy case, in-order reassembly so far. */
12471 			ipf->ipf_count += msg_len;
12472 			ipf->ipf_tail_mp = tail_mp;
12473 			/*
12474 			 * Keep track of next expected offset in
12475 			 * ipf_end.
12476 			 */
12477 			ipf->ipf_end = end;
12478 			ipf->ipf_nf_hdr_len = hdr_length;
12479 		} else {
12480 			/* Hard case, hole at the beginning. */
12481 			ipf->ipf_tail_mp = NULL;
12482 			/*
12483 			 * ipf_end == 0 means that we have given up
12484 			 * on easy reassembly.
12485 			 */
12486 			ipf->ipf_end = 0;
12487 
12488 			/* Forget checksum offload from now on */
12489 			ipf->ipf_checksum_flags = 0;
12490 
12491 			/*
12492 			 * ipf_hole_cnt is set by ip_reassemble.
12493 			 * ipf_count is updated by ip_reassemble.
12494 			 * No need to check for return value here
12495 			 * as we don't expect reassembly to complete
12496 			 * or fail for the first fragment itself.
12497 			 */
12498 			(void) ip_reassemble(mp, ipf,
12499 			    (frag_offset_flags & IPH_OFFSET) << 3,
12500 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12501 		}
12502 		/* Update per ipfb and ill byte counts */
12503 		ipfb->ipfb_count += ipf->ipf_count;
12504 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12505 		ill->ill_frag_count += ipf->ipf_count;
12506 		/* If the frag timer wasn't already going, start it. */
12507 		mutex_enter(&ill->ill_lock);
12508 		ill_frag_timer_start(ill);
12509 		mutex_exit(&ill->ill_lock);
12510 		goto reass_done;
12511 	}
12512 
12513 	/*
12514 	 * If the packet's flag has changed (it could be coming up
12515 	 * from an interface different than the previous, therefore
12516 	 * possibly different checksum capability), then forget about
12517 	 * any stored checksum states.  Otherwise add the value to
12518 	 * the existing one stored in the fragment header.
12519 	 */
12520 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12521 		sum_val += ipf->ipf_checksum;
12522 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12523 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12524 		ipf->ipf_checksum = sum_val;
12525 	} else if (ipf->ipf_checksum_flags != 0) {
12526 		/* Forget checksum offload from now on */
12527 		ipf->ipf_checksum_flags = 0;
12528 	}
12529 
12530 	/*
12531 	 * We have a new piece of a datagram which is already being
12532 	 * reassembled.  Update the ECN info if all IP fragments
12533 	 * are ECN capable.  If there is one which is not, clear
12534 	 * all the info.  If there is at least one which has CE
12535 	 * code point, IP needs to report that up to transport.
12536 	 */
12537 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12538 		if (ecn_info == IPH_ECN_CE)
12539 			ipf->ipf_ecn = IPH_ECN_CE;
12540 	} else {
12541 		ipf->ipf_ecn = IPH_ECN_NECT;
12542 	}
12543 	if (offset && ipf->ipf_end == offset) {
12544 		/* The new fragment fits at the end */
12545 		ipf->ipf_tail_mp->b_cont = mp;
12546 		/* Update the byte count */
12547 		ipf->ipf_count += msg_len;
12548 		/* Update per ipfb and ill byte counts */
12549 		ipfb->ipfb_count += msg_len;
12550 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12551 		ill->ill_frag_count += msg_len;
12552 		if (frag_offset_flags & IPH_MF) {
12553 			/* More to come. */
12554 			ipf->ipf_end = end;
12555 			ipf->ipf_tail_mp = tail_mp;
12556 			goto reass_done;
12557 		}
12558 	} else {
12559 		/* Go do the hard cases. */
12560 		int ret;
12561 
12562 		if (offset == 0)
12563 			ipf->ipf_nf_hdr_len = hdr_length;
12564 
12565 		/* Save current byte count */
12566 		count = ipf->ipf_count;
12567 		ret = ip_reassemble(mp, ipf,
12568 		    (frag_offset_flags & IPH_OFFSET) << 3,
12569 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12570 		/* Count of bytes added and subtracted (freeb()ed) */
12571 		count = ipf->ipf_count - count;
12572 		if (count) {
12573 			/* Update per ipfb and ill byte counts */
12574 			ipfb->ipfb_count += count;
12575 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12576 			ill->ill_frag_count += count;
12577 		}
12578 		if (ret == IP_REASS_PARTIAL) {
12579 			goto reass_done;
12580 		} else if (ret == IP_REASS_FAILED) {
12581 			/* Reassembly failed. Free up all resources */
12582 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12583 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12584 				IP_REASS_SET_START(t_mp, 0);
12585 				IP_REASS_SET_END(t_mp, 0);
12586 			}
12587 			freemsg(mp);
12588 			goto reass_done;
12589 		}
12590 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12591 	}
12592 	/*
12593 	 * We have completed reassembly.  Unhook the frag header from
12594 	 * the reassembly list.
12595 	 *
12596 	 * Before we free the frag header, record the ECN info
12597 	 * to report back to the transport.
12598 	 */
12599 	ecn_info = ipf->ipf_ecn;
12600 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12601 	ipfp = ipf->ipf_ptphn;
12602 
12603 	/* We need to supply these to caller */
12604 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12605 		sum_val = ipf->ipf_checksum;
12606 	else
12607 		sum_val = 0;
12608 
12609 	mp1 = ipf->ipf_mp;
12610 	count = ipf->ipf_count;
12611 	ipf = ipf->ipf_hash_next;
12612 	if (ipf != NULL)
12613 		ipf->ipf_ptphn = ipfp;
12614 	ipfp[0] = ipf;
12615 	ill->ill_frag_count -= count;
12616 	ASSERT(ipfb->ipfb_count >= count);
12617 	ipfb->ipfb_count -= count;
12618 	ipfb->ipfb_frag_pkts--;
12619 	mutex_exit(&ipfb->ipfb_lock);
12620 	/* Ditch the frag header. */
12621 	mp = mp1->b_cont;
12622 
12623 	freeb(mp1);
12624 
12625 	/* Restore original IP length in header. */
12626 	packet_size = (uint32_t)msgdsize(mp);
12627 	if (packet_size > IP_MAXPACKET) {
12628 		freemsg(mp);
12629 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12630 		return (B_FALSE);
12631 	}
12632 
12633 	if (DB_REF(mp) > 1) {
12634 		mblk_t *mp2 = copymsg(mp);
12635 
12636 		freemsg(mp);
12637 		if (mp2 == NULL) {
12638 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12639 			return (B_FALSE);
12640 		}
12641 		mp = mp2;
12642 	}
12643 	ipha = (ipha_t *)mp->b_rptr;
12644 
12645 	ipha->ipha_length = htons((uint16_t)packet_size);
12646 	/* We're now complete, zip the frag state */
12647 	ipha->ipha_fragment_offset_and_flags = 0;
12648 	/* Record the ECN info. */
12649 	ipha->ipha_type_of_service &= 0xFC;
12650 	ipha->ipha_type_of_service |= ecn_info;
12651 	*mpp = mp;
12652 
12653 	/* Reassembly is successful; return checksum information if needed */
12654 	if (cksum_val != NULL)
12655 		*cksum_val = sum_val;
12656 	if (cksum_flags != NULL)
12657 		*cksum_flags = sum_flags;
12658 
12659 	return (B_TRUE);
12660 }
12661 
12662 /*
12663  * Perform ip header check sum update local options.
12664  * return B_TRUE if all is well, else return B_FALSE and release
12665  * the mp. caller is responsible for decrementing ire ref cnt.
12666  */
12667 static boolean_t
12668 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12669     ip_stack_t *ipst)
12670 {
12671 	mblk_t		*first_mp;
12672 	boolean_t	mctl_present;
12673 	uint16_t	sum;
12674 
12675 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12676 	/*
12677 	 * Don't do the checksum if it has gone through AH/ESP
12678 	 * processing.
12679 	 */
12680 	if (!mctl_present) {
12681 		sum = ip_csum_hdr(ipha);
12682 		if (sum != 0) {
12683 			if (ill != NULL) {
12684 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12685 			} else {
12686 				BUMP_MIB(&ipst->ips_ip_mib,
12687 				    ipIfStatsInCksumErrs);
12688 			}
12689 			freemsg(first_mp);
12690 			return (B_FALSE);
12691 		}
12692 	}
12693 
12694 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12695 		if (mctl_present)
12696 			freeb(first_mp);
12697 		return (B_FALSE);
12698 	}
12699 
12700 	return (B_TRUE);
12701 }
12702 
12703 /*
12704  * All udp packet are delivered to the local host via this routine.
12705  */
12706 void
12707 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12708     ill_t *recv_ill)
12709 {
12710 	uint32_t	sum;
12711 	uint32_t	u1;
12712 	boolean_t	mctl_present;
12713 	conn_t		*connp;
12714 	mblk_t		*first_mp;
12715 	uint16_t	*up;
12716 	ill_t		*ill = (ill_t *)q->q_ptr;
12717 	uint16_t	reass_hck_flags = 0;
12718 	ip_stack_t	*ipst;
12719 
12720 	ASSERT(recv_ill != NULL);
12721 	ipst = recv_ill->ill_ipst;
12722 
12723 #define	rptr    ((uchar_t *)ipha)
12724 
12725 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12726 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12727 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12728 	ASSERT(ill != NULL);
12729 
12730 	/*
12731 	 * FAST PATH for udp packets
12732 	 */
12733 
12734 	/* u1 is # words of IP options */
12735 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12736 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12737 
12738 	/* IP options present */
12739 	if (u1 != 0)
12740 		goto ipoptions;
12741 
12742 	/* Check the IP header checksum.  */
12743 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12744 		/* Clear the IP header h/w cksum flag */
12745 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12746 	} else if (!mctl_present) {
12747 		/*
12748 		 * Don't verify header checksum if this packet is coming
12749 		 * back from AH/ESP as we already did it.
12750 		 */
12751 #define	uph	((uint16_t *)ipha)
12752 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12753 		    uph[6] + uph[7] + uph[8] + uph[9];
12754 #undef	uph
12755 		/* finish doing IP checksum */
12756 		sum = (sum & 0xFFFF) + (sum >> 16);
12757 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12758 		if (sum != 0 && sum != 0xFFFF) {
12759 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12760 			freemsg(first_mp);
12761 			return;
12762 		}
12763 	}
12764 
12765 	/*
12766 	 * Count for SNMP of inbound packets for ire.
12767 	 * if mctl is present this might be a secure packet and
12768 	 * has already been counted for in ip_proto_input().
12769 	 */
12770 	if (!mctl_present) {
12771 		UPDATE_IB_PKT_COUNT(ire);
12772 		ire->ire_last_used_time = lbolt;
12773 	}
12774 
12775 	/* packet part of fragmented IP packet? */
12776 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12777 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12778 		goto fragmented;
12779 	}
12780 
12781 	/* u1 = IP header length (20 bytes) */
12782 	u1 = IP_SIMPLE_HDR_LENGTH;
12783 
12784 	/* packet does not contain complete IP & UDP headers */
12785 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12786 		goto udppullup;
12787 
12788 	/* up points to UDP header */
12789 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12790 #define	iphs    ((uint16_t *)ipha)
12791 
12792 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12793 	if (up[3] != 0) {
12794 		mblk_t *mp1 = mp->b_cont;
12795 		boolean_t cksum_err;
12796 		uint16_t hck_flags = 0;
12797 
12798 		/* Pseudo-header checksum */
12799 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12800 		    iphs[9] + up[2];
12801 
12802 		/*
12803 		 * Revert to software checksum calculation if the interface
12804 		 * isn't capable of checksum offload or if IPsec is present.
12805 		 */
12806 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12807 			hck_flags = DB_CKSUMFLAGS(mp);
12808 
12809 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12810 			IP_STAT(ipst, ip_in_sw_cksum);
12811 
12812 		IP_CKSUM_RECV(hck_flags, u1,
12813 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12814 		    (int32_t)((uchar_t *)up - rptr),
12815 		    mp, mp1, cksum_err);
12816 
12817 		if (cksum_err) {
12818 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12819 			if (hck_flags & HCK_FULLCKSUM)
12820 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12821 			else if (hck_flags & HCK_PARTIALCKSUM)
12822 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12823 			else
12824 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12825 
12826 			freemsg(first_mp);
12827 			return;
12828 		}
12829 	}
12830 
12831 	/* Non-fragmented broadcast or multicast packet? */
12832 	if (ire->ire_type == IRE_BROADCAST)
12833 		goto udpslowpath;
12834 
12835 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12836 	    ire->ire_zoneid, ipst)) != NULL) {
12837 		ASSERT(connp->conn_upq != NULL);
12838 		IP_STAT(ipst, ip_udp_fast_path);
12839 
12840 		if (CONN_UDP_FLOWCTLD(connp)) {
12841 			freemsg(mp);
12842 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12843 		} else {
12844 			if (!mctl_present) {
12845 				BUMP_MIB(ill->ill_ip_mib,
12846 				    ipIfStatsHCInDelivers);
12847 			}
12848 			/*
12849 			 * mp and first_mp can change.
12850 			 */
12851 			if (ip_udp_check(q, connp, recv_ill,
12852 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12853 				/* Send it upstream */
12854 				CONN_UDP_RECV(connp, mp);
12855 			}
12856 		}
12857 		/*
12858 		 * freeb() cannot deal with null mblk being passed
12859 		 * in and first_mp can be set to null in the call
12860 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12861 		 */
12862 		if (mctl_present && first_mp != NULL) {
12863 			freeb(first_mp);
12864 		}
12865 		CONN_DEC_REF(connp);
12866 		return;
12867 	}
12868 
12869 	/*
12870 	 * if we got here we know the packet is not fragmented and
12871 	 * has no options. The classifier could not find a conn_t and
12872 	 * most likely its an icmp packet so send it through slow path.
12873 	 */
12874 
12875 	goto udpslowpath;
12876 
12877 ipoptions:
12878 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12879 		goto slow_done;
12880 	}
12881 
12882 	UPDATE_IB_PKT_COUNT(ire);
12883 	ire->ire_last_used_time = lbolt;
12884 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12885 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12886 fragmented:
12887 		/*
12888 		 * "sum" and "reass_hck_flags" are non-zero if the
12889 		 * reassembled packet has a valid hardware computed
12890 		 * checksum information associated with it.
12891 		 */
12892 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12893 			goto slow_done;
12894 		/*
12895 		 * Make sure that first_mp points back to mp as
12896 		 * the mp we came in with could have changed in
12897 		 * ip_rput_fragment().
12898 		 */
12899 		ASSERT(!mctl_present);
12900 		ipha = (ipha_t *)mp->b_rptr;
12901 		first_mp = mp;
12902 	}
12903 
12904 	/* Now we have a complete datagram, destined for this machine. */
12905 	u1 = IPH_HDR_LENGTH(ipha);
12906 	/* Pull up the UDP header, if necessary. */
12907 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12908 udppullup:
12909 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12910 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12911 			freemsg(first_mp);
12912 			goto slow_done;
12913 		}
12914 		ipha = (ipha_t *)mp->b_rptr;
12915 	}
12916 
12917 	/*
12918 	 * Validate the checksum for the reassembled packet; for the
12919 	 * pullup case we calculate the payload checksum in software.
12920 	 */
12921 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12922 	if (up[3] != 0) {
12923 		boolean_t cksum_err;
12924 
12925 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12926 			IP_STAT(ipst, ip_in_sw_cksum);
12927 
12928 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12929 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12930 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12931 		    iphs[9] + up[2], sum, cksum_err);
12932 
12933 		if (cksum_err) {
12934 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12935 
12936 			if (reass_hck_flags & HCK_FULLCKSUM)
12937 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12938 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12939 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12940 			else
12941 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12942 
12943 			freemsg(first_mp);
12944 			goto slow_done;
12945 		}
12946 	}
12947 udpslowpath:
12948 
12949 	/* Clear hardware checksum flag to be safe */
12950 	DB_CKSUMFLAGS(mp) = 0;
12951 
12952 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12953 	    (ire->ire_type == IRE_BROADCAST),
12954 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12955 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12956 
12957 slow_done:
12958 	IP_STAT(ipst, ip_udp_slow_path);
12959 	return;
12960 
12961 #undef  iphs
12962 #undef  rptr
12963 }
12964 
12965 /* ARGSUSED */
12966 static mblk_t *
12967 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12968     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12969     ill_rx_ring_t *ill_ring)
12970 {
12971 	conn_t		*connp;
12972 	uint32_t	sum;
12973 	uint32_t	u1;
12974 	uint16_t	*up;
12975 	int		offset;
12976 	ssize_t		len;
12977 	mblk_t		*mp1;
12978 	boolean_t	syn_present = B_FALSE;
12979 	tcph_t		*tcph;
12980 	uint_t		ip_hdr_len;
12981 	ill_t		*ill = (ill_t *)q->q_ptr;
12982 	zoneid_t	zoneid = ire->ire_zoneid;
12983 	boolean_t	cksum_err;
12984 	uint16_t	hck_flags = 0;
12985 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12986 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12987 
12988 #define	rptr	((uchar_t *)ipha)
12989 
12990 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12991 	ASSERT(ill != NULL);
12992 
12993 	/*
12994 	 * FAST PATH for tcp packets
12995 	 */
12996 
12997 	/* u1 is # words of IP options */
12998 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12999 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13000 
13001 	/* IP options present */
13002 	if (u1) {
13003 		goto ipoptions;
13004 	} else {
13005 		/* Check the IP header checksum.  */
13006 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13007 			/* Clear the IP header h/w cksum flag */
13008 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13009 		} else if (!mctl_present) {
13010 			/*
13011 			 * Don't verify header checksum if this packet
13012 			 * is coming back from AH/ESP as we already did it.
13013 			 */
13014 #define	uph	((uint16_t *)ipha)
13015 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13016 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13017 #undef	uph
13018 			/* finish doing IP checksum */
13019 			sum = (sum & 0xFFFF) + (sum >> 16);
13020 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13021 			if (sum != 0 && sum != 0xFFFF) {
13022 				BUMP_MIB(ill->ill_ip_mib,
13023 				    ipIfStatsInCksumErrs);
13024 				goto error;
13025 			}
13026 		}
13027 	}
13028 
13029 	if (!mctl_present) {
13030 		UPDATE_IB_PKT_COUNT(ire);
13031 		ire->ire_last_used_time = lbolt;
13032 	}
13033 
13034 	/* packet part of fragmented IP packet? */
13035 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13036 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13037 		goto fragmented;
13038 	}
13039 
13040 	/* u1 = IP header length (20 bytes) */
13041 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13042 
13043 	/* does packet contain IP+TCP headers? */
13044 	len = mp->b_wptr - rptr;
13045 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13046 		IP_STAT(ipst, ip_tcppullup);
13047 		goto tcppullup;
13048 	}
13049 
13050 	/* TCP options present? */
13051 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13052 
13053 	/*
13054 	 * If options need to be pulled up, then goto tcpoptions.
13055 	 * otherwise we are still in the fast path
13056 	 */
13057 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13058 		IP_STAT(ipst, ip_tcpoptions);
13059 		goto tcpoptions;
13060 	}
13061 
13062 	/* multiple mblks of tcp data? */
13063 	if ((mp1 = mp->b_cont) != NULL) {
13064 		/* more then two? */
13065 		if (mp1->b_cont != NULL) {
13066 			IP_STAT(ipst, ip_multipkttcp);
13067 			goto multipkttcp;
13068 		}
13069 		len += mp1->b_wptr - mp1->b_rptr;
13070 	}
13071 
13072 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13073 
13074 	/* part of pseudo checksum */
13075 
13076 	/* TCP datagram length */
13077 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13078 
13079 #define	iphs    ((uint16_t *)ipha)
13080 
13081 #ifdef	_BIG_ENDIAN
13082 	u1 += IPPROTO_TCP;
13083 #else
13084 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13085 #endif
13086 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13087 
13088 	/*
13089 	 * Revert to software checksum calculation if the interface
13090 	 * isn't capable of checksum offload or if IPsec is present.
13091 	 */
13092 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13093 		hck_flags = DB_CKSUMFLAGS(mp);
13094 
13095 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13096 		IP_STAT(ipst, ip_in_sw_cksum);
13097 
13098 	IP_CKSUM_RECV(hck_flags, u1,
13099 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13100 	    (int32_t)((uchar_t *)up - rptr),
13101 	    mp, mp1, cksum_err);
13102 
13103 	if (cksum_err) {
13104 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13105 
13106 		if (hck_flags & HCK_FULLCKSUM)
13107 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13108 		else if (hck_flags & HCK_PARTIALCKSUM)
13109 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13110 		else
13111 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13112 
13113 		goto error;
13114 	}
13115 
13116 try_again:
13117 
13118 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13119 	    zoneid, ipst)) == NULL) {
13120 		/* Send the TH_RST */
13121 		goto no_conn;
13122 	}
13123 
13124 	/*
13125 	 * TCP FAST PATH for AF_INET socket.
13126 	 *
13127 	 * TCP fast path to avoid extra work. An AF_INET socket type
13128 	 * does not have facility to receive extra information via
13129 	 * ip_process or ip_add_info. Also, when the connection was
13130 	 * established, we made a check if this connection is impacted
13131 	 * by any global IPsec policy or per connection policy (a
13132 	 * policy that comes in effect later will not apply to this
13133 	 * connection). Since all this can be determined at the
13134 	 * connection establishment time, a quick check of flags
13135 	 * can avoid extra work.
13136 	 */
13137 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13138 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13139 		ASSERT(first_mp == mp);
13140 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13141 		SET_SQUEUE(mp, tcp_rput_data, connp);
13142 		return (mp);
13143 	}
13144 
13145 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13146 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13147 		if (IPCL_IS_TCP(connp)) {
13148 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13149 			DB_CKSUMSTART(mp) =
13150 			    (intptr_t)ip_squeue_get(ill_ring);
13151 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13152 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13153 				BUMP_MIB(ill->ill_ip_mib,
13154 				    ipIfStatsHCInDelivers);
13155 				SET_SQUEUE(mp, connp->conn_recv, connp);
13156 				return (mp);
13157 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13158 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13159 				BUMP_MIB(ill->ill_ip_mib,
13160 				    ipIfStatsHCInDelivers);
13161 				ip_squeue_enter_unbound++;
13162 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13163 				    connp);
13164 				return (mp);
13165 			}
13166 			syn_present = B_TRUE;
13167 		}
13168 
13169 	}
13170 
13171 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13172 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13173 
13174 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13175 		/* No need to send this packet to TCP */
13176 		if ((flags & TH_RST) || (flags & TH_URG)) {
13177 			CONN_DEC_REF(connp);
13178 			freemsg(first_mp);
13179 			return (NULL);
13180 		}
13181 		if (flags & TH_ACK) {
13182 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13183 			    ipst->ips_netstack->netstack_tcp);
13184 			CONN_DEC_REF(connp);
13185 			return (NULL);
13186 		}
13187 
13188 		CONN_DEC_REF(connp);
13189 		freemsg(first_mp);
13190 		return (NULL);
13191 	}
13192 
13193 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13194 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13195 		    ipha, NULL, mctl_present);
13196 		if (first_mp == NULL) {
13197 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13198 			CONN_DEC_REF(connp);
13199 			return (NULL);
13200 		}
13201 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13202 			ASSERT(syn_present);
13203 			if (mctl_present) {
13204 				ASSERT(first_mp != mp);
13205 				first_mp->b_datap->db_struioflag |=
13206 				    STRUIO_POLICY;
13207 			} else {
13208 				ASSERT(first_mp == mp);
13209 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13210 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13211 			}
13212 		} else {
13213 			/*
13214 			 * Discard first_mp early since we're dealing with a
13215 			 * fully-connected conn_t and tcp doesn't do policy in
13216 			 * this case.
13217 			 */
13218 			if (mctl_present) {
13219 				freeb(first_mp);
13220 				mctl_present = B_FALSE;
13221 			}
13222 			first_mp = mp;
13223 		}
13224 	}
13225 
13226 	/* Initiate IPPF processing for fastpath */
13227 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13228 		uint32_t	ill_index;
13229 
13230 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13231 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13232 		if (mp == NULL) {
13233 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13234 			    "deferred/dropped during IPPF processing\n"));
13235 			CONN_DEC_REF(connp);
13236 			if (mctl_present)
13237 				freeb(first_mp);
13238 			return (NULL);
13239 		} else if (mctl_present) {
13240 			/*
13241 			 * ip_process might return a new mp.
13242 			 */
13243 			ASSERT(first_mp != mp);
13244 			first_mp->b_cont = mp;
13245 		} else {
13246 			first_mp = mp;
13247 		}
13248 
13249 	}
13250 
13251 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13252 		/*
13253 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13254 		 * make sure IPF_RECVIF is passed to ip_add_info.
13255 		 */
13256 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13257 		    IPCL_ZONEID(connp), ipst);
13258 		if (mp == NULL) {
13259 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13260 			CONN_DEC_REF(connp);
13261 			if (mctl_present)
13262 				freeb(first_mp);
13263 			return (NULL);
13264 		} else if (mctl_present) {
13265 			/*
13266 			 * ip_add_info might return a new mp.
13267 			 */
13268 			ASSERT(first_mp != mp);
13269 			first_mp->b_cont = mp;
13270 		} else {
13271 			first_mp = mp;
13272 		}
13273 	}
13274 
13275 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13276 	if (IPCL_IS_TCP(connp)) {
13277 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13278 		return (first_mp);
13279 	} else {
13280 		putnext(connp->conn_rq, first_mp);
13281 		CONN_DEC_REF(connp);
13282 		return (NULL);
13283 	}
13284 
13285 no_conn:
13286 	/* Initiate IPPf processing, if needed. */
13287 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13288 		uint32_t ill_index;
13289 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13290 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13291 		if (first_mp == NULL) {
13292 			return (NULL);
13293 		}
13294 	}
13295 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13296 
13297 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13298 	    ipst->ips_netstack->netstack_tcp);
13299 	return (NULL);
13300 ipoptions:
13301 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13302 		goto slow_done;
13303 	}
13304 
13305 	UPDATE_IB_PKT_COUNT(ire);
13306 	ire->ire_last_used_time = lbolt;
13307 
13308 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13309 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13310 fragmented:
13311 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13312 			if (mctl_present)
13313 				freeb(first_mp);
13314 			goto slow_done;
13315 		}
13316 		/*
13317 		 * Make sure that first_mp points back to mp as
13318 		 * the mp we came in with could have changed in
13319 		 * ip_rput_fragment().
13320 		 */
13321 		ASSERT(!mctl_present);
13322 		ipha = (ipha_t *)mp->b_rptr;
13323 		first_mp = mp;
13324 	}
13325 
13326 	/* Now we have a complete datagram, destined for this machine. */
13327 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13328 
13329 	len = mp->b_wptr - mp->b_rptr;
13330 	/* Pull up a minimal TCP header, if necessary. */
13331 	if (len < (u1 + 20)) {
13332 tcppullup:
13333 		if (!pullupmsg(mp, u1 + 20)) {
13334 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13335 			goto error;
13336 		}
13337 		ipha = (ipha_t *)mp->b_rptr;
13338 		len = mp->b_wptr - mp->b_rptr;
13339 	}
13340 
13341 	/*
13342 	 * Extract the offset field from the TCP header.  As usual, we
13343 	 * try to help the compiler more than the reader.
13344 	 */
13345 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13346 	if (offset != 5) {
13347 tcpoptions:
13348 		if (offset < 5) {
13349 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13350 			goto error;
13351 		}
13352 		/*
13353 		 * There must be TCP options.
13354 		 * Make sure we can grab them.
13355 		 */
13356 		offset <<= 2;
13357 		offset += u1;
13358 		if (len < offset) {
13359 			if (!pullupmsg(mp, offset)) {
13360 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13361 				goto error;
13362 			}
13363 			ipha = (ipha_t *)mp->b_rptr;
13364 			len = mp->b_wptr - rptr;
13365 		}
13366 	}
13367 
13368 	/* Get the total packet length in len, including headers. */
13369 	if (mp->b_cont) {
13370 multipkttcp:
13371 		len = msgdsize(mp);
13372 	}
13373 
13374 	/*
13375 	 * Check the TCP checksum by pulling together the pseudo-
13376 	 * header checksum, and passing it to ip_csum to be added in
13377 	 * with the TCP datagram.
13378 	 *
13379 	 * Since we are not using the hwcksum if available we must
13380 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13381 	 * If either of these fails along the way the mblk is freed.
13382 	 * If this logic ever changes and mblk is reused to say send
13383 	 * ICMP's back, then this flag may need to be cleared in
13384 	 * other places as well.
13385 	 */
13386 	DB_CKSUMFLAGS(mp) = 0;
13387 
13388 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13389 
13390 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13391 #ifdef	_BIG_ENDIAN
13392 	u1 += IPPROTO_TCP;
13393 #else
13394 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13395 #endif
13396 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13397 	/*
13398 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13399 	 */
13400 	IP_STAT(ipst, ip_in_sw_cksum);
13401 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13402 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13403 		goto error;
13404 	}
13405 
13406 	IP_STAT(ipst, ip_tcp_slow_path);
13407 	goto try_again;
13408 #undef  iphs
13409 #undef  rptr
13410 
13411 error:
13412 	freemsg(first_mp);
13413 slow_done:
13414 	return (NULL);
13415 }
13416 
13417 /* ARGSUSED */
13418 static void
13419 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13420     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13421 {
13422 	conn_t		*connp;
13423 	uint32_t	sum;
13424 	uint32_t	u1;
13425 	ssize_t		len;
13426 	sctp_hdr_t	*sctph;
13427 	zoneid_t	zoneid = ire->ire_zoneid;
13428 	uint32_t	pktsum;
13429 	uint32_t	calcsum;
13430 	uint32_t	ports;
13431 	in6_addr_t	map_src, map_dst;
13432 	ill_t		*ill = (ill_t *)q->q_ptr;
13433 	ip_stack_t	*ipst;
13434 	sctp_stack_t	*sctps;
13435 
13436 	ASSERT(recv_ill != NULL);
13437 	ipst = recv_ill->ill_ipst;
13438 	sctps = ipst->ips_netstack->netstack_sctp;
13439 
13440 #define	rptr	((uchar_t *)ipha)
13441 
13442 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13443 	ASSERT(ill != NULL);
13444 
13445 	/* u1 is # words of IP options */
13446 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13447 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13448 
13449 	/* IP options present */
13450 	if (u1 > 0) {
13451 		goto ipoptions;
13452 	} else {
13453 		/* Check the IP header checksum.  */
13454 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13455 		    !mctl_present) {
13456 #define	uph	((uint16_t *)ipha)
13457 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13458 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13459 #undef	uph
13460 			/* finish doing IP checksum */
13461 			sum = (sum & 0xFFFF) + (sum >> 16);
13462 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13463 			/*
13464 			 * Don't verify header checksum if this packet
13465 			 * is coming back from AH/ESP as we already did it.
13466 			 */
13467 			if (sum != 0 && sum != 0xFFFF) {
13468 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13469 				goto error;
13470 			}
13471 		}
13472 		/*
13473 		 * Since there is no SCTP h/w cksum support yet, just
13474 		 * clear the flag.
13475 		 */
13476 		DB_CKSUMFLAGS(mp) = 0;
13477 	}
13478 
13479 	/*
13480 	 * Don't verify header checksum if this packet is coming
13481 	 * back from AH/ESP as we already did it.
13482 	 */
13483 	if (!mctl_present) {
13484 		UPDATE_IB_PKT_COUNT(ire);
13485 		ire->ire_last_used_time = lbolt;
13486 	}
13487 
13488 	/* packet part of fragmented IP packet? */
13489 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13490 	if (u1 & (IPH_MF | IPH_OFFSET))
13491 		goto fragmented;
13492 
13493 	/* u1 = IP header length (20 bytes) */
13494 	u1 = IP_SIMPLE_HDR_LENGTH;
13495 
13496 find_sctp_client:
13497 	/* Pullup if we don't have the sctp common header. */
13498 	len = MBLKL(mp);
13499 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13500 		if (mp->b_cont == NULL ||
13501 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13502 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13503 			goto error;
13504 		}
13505 		ipha = (ipha_t *)mp->b_rptr;
13506 		len = MBLKL(mp);
13507 	}
13508 
13509 	sctph = (sctp_hdr_t *)(rptr + u1);
13510 #ifdef	DEBUG
13511 	if (!skip_sctp_cksum) {
13512 #endif
13513 		pktsum = sctph->sh_chksum;
13514 		sctph->sh_chksum = 0;
13515 		calcsum = sctp_cksum(mp, u1);
13516 		if (calcsum != pktsum) {
13517 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13518 			goto error;
13519 		}
13520 		sctph->sh_chksum = pktsum;
13521 #ifdef	DEBUG	/* skip_sctp_cksum */
13522 	}
13523 #endif
13524 	/* get the ports */
13525 	ports = *(uint32_t *)&sctph->sh_sport;
13526 
13527 	IRE_REFRELE(ire);
13528 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13529 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13530 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13531 	    sctps)) == NULL) {
13532 		/* Check for raw socket or OOTB handling */
13533 		goto no_conn;
13534 	}
13535 
13536 	/* Found a client; up it goes */
13537 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13538 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13539 	return;
13540 
13541 no_conn:
13542 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13543 	    ports, mctl_present, flags, B_TRUE, zoneid);
13544 	return;
13545 
13546 ipoptions:
13547 	DB_CKSUMFLAGS(mp) = 0;
13548 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13549 		goto slow_done;
13550 
13551 	UPDATE_IB_PKT_COUNT(ire);
13552 	ire->ire_last_used_time = lbolt;
13553 
13554 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13555 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13556 fragmented:
13557 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13558 			goto slow_done;
13559 		/*
13560 		 * Make sure that first_mp points back to mp as
13561 		 * the mp we came in with could have changed in
13562 		 * ip_rput_fragment().
13563 		 */
13564 		ASSERT(!mctl_present);
13565 		ipha = (ipha_t *)mp->b_rptr;
13566 		first_mp = mp;
13567 	}
13568 
13569 	/* Now we have a complete datagram, destined for this machine. */
13570 	u1 = IPH_HDR_LENGTH(ipha);
13571 	goto find_sctp_client;
13572 #undef  iphs
13573 #undef  rptr
13574 
13575 error:
13576 	freemsg(first_mp);
13577 slow_done:
13578 	IRE_REFRELE(ire);
13579 }
13580 
13581 #define	VER_BITS	0xF0
13582 #define	VERSION_6	0x60
13583 
13584 static boolean_t
13585 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13586     ipaddr_t *dstp, ip_stack_t *ipst)
13587 {
13588 	uint_t	opt_len;
13589 	ipha_t *ipha;
13590 	ssize_t len;
13591 	uint_t	pkt_len;
13592 
13593 	ASSERT(ill != NULL);
13594 	IP_STAT(ipst, ip_ipoptions);
13595 	ipha = *iphapp;
13596 
13597 #define	rptr    ((uchar_t *)ipha)
13598 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13599 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13600 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13601 		freemsg(mp);
13602 		return (B_FALSE);
13603 	}
13604 
13605 	/* multiple mblk or too short */
13606 	pkt_len = ntohs(ipha->ipha_length);
13607 
13608 	/* Get the number of words of IP options in the IP header. */
13609 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13610 	if (opt_len) {
13611 		/* IP Options present!  Validate and process. */
13612 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13613 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13614 			goto done;
13615 		}
13616 		/*
13617 		 * Recompute complete header length and make sure we
13618 		 * have access to all of it.
13619 		 */
13620 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13621 		if (len > (mp->b_wptr - rptr)) {
13622 			if (len > pkt_len) {
13623 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13624 				goto done;
13625 			}
13626 			if (!pullupmsg(mp, len)) {
13627 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13628 				goto done;
13629 			}
13630 			ipha = (ipha_t *)mp->b_rptr;
13631 		}
13632 		/*
13633 		 * Go off to ip_rput_options which returns the next hop
13634 		 * destination address, which may have been affected
13635 		 * by source routing.
13636 		 */
13637 		IP_STAT(ipst, ip_opt);
13638 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13639 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13640 			return (B_FALSE);
13641 		}
13642 	}
13643 	*iphapp = ipha;
13644 	return (B_TRUE);
13645 done:
13646 	/* clear b_prev - used by ip_mroute_decap */
13647 	mp->b_prev = NULL;
13648 	freemsg(mp);
13649 	return (B_FALSE);
13650 #undef  rptr
13651 }
13652 
13653 /*
13654  * Deal with the fact that there is no ire for the destination.
13655  */
13656 static ire_t *
13657 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13658 {
13659 	ipha_t	*ipha;
13660 	ill_t	*ill;
13661 	ire_t	*ire;
13662 	boolean_t	check_multirt = B_FALSE;
13663 	ip_stack_t *ipst;
13664 
13665 	ipha = (ipha_t *)mp->b_rptr;
13666 	ill = (ill_t *)q->q_ptr;
13667 
13668 	ASSERT(ill != NULL);
13669 	ipst = ill->ill_ipst;
13670 
13671 	/*
13672 	 * No IRE for this destination, so it can't be for us.
13673 	 * Unless we are forwarding, drop the packet.
13674 	 * We have to let source routed packets through
13675 	 * since we don't yet know if they are 'ping -l'
13676 	 * packets i.e. if they will go out over the
13677 	 * same interface as they came in on.
13678 	 */
13679 	if (ll_multicast) {
13680 		freemsg(mp);
13681 		return (NULL);
13682 	}
13683 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13684 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13685 		freemsg(mp);
13686 		return (NULL);
13687 	}
13688 
13689 	/*
13690 	 * Mark this packet as having originated externally.
13691 	 *
13692 	 * For non-forwarding code path, ire_send later double
13693 	 * checks this interface to see if it is still exists
13694 	 * post-ARP resolution.
13695 	 *
13696 	 * Also, IPQOS uses this to differentiate between
13697 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13698 	 * QOS packet processing in ip_wput_attach_llhdr().
13699 	 * The QoS module can mark the b_band for a fastpath message
13700 	 * or the dl_priority field in a unitdata_req header for
13701 	 * CoS marking. This info can only be found in
13702 	 * ip_wput_attach_llhdr().
13703 	 */
13704 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13705 	/*
13706 	 * Clear the indication that this may have a hardware checksum
13707 	 * as we are not using it
13708 	 */
13709 	DB_CKSUMFLAGS(mp) = 0;
13710 
13711 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13712 	    MBLK_GETLABEL(mp), ipst);
13713 
13714 	if (ire == NULL && check_multirt) {
13715 		/* Let ip_newroute handle CGTP  */
13716 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13717 		return (NULL);
13718 	}
13719 
13720 	if (ire != NULL)
13721 		return (ire);
13722 
13723 	mp->b_prev = mp->b_next = 0;
13724 	/* send icmp unreachable */
13725 	q = WR(q);
13726 	/* Sent by forwarding path, and router is global zone */
13727 	if (ip_source_routed(ipha, ipst)) {
13728 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13729 		    GLOBAL_ZONEID, ipst);
13730 	} else {
13731 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13732 		    ipst);
13733 	}
13734 
13735 	return (NULL);
13736 
13737 }
13738 
13739 /*
13740  * check ip header length and align it.
13741  */
13742 static boolean_t
13743 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13744 {
13745 	ssize_t len;
13746 	ill_t *ill;
13747 	ipha_t	*ipha;
13748 
13749 	len = MBLKL(mp);
13750 
13751 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13752 		ill = (ill_t *)q->q_ptr;
13753 
13754 		if (!OK_32PTR(mp->b_rptr))
13755 			IP_STAT(ipst, ip_notaligned1);
13756 		else
13757 			IP_STAT(ipst, ip_notaligned2);
13758 		/* Guard against bogus device drivers */
13759 		if (len < 0) {
13760 			/* clear b_prev - used by ip_mroute_decap */
13761 			mp->b_prev = NULL;
13762 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13763 			freemsg(mp);
13764 			return (B_FALSE);
13765 		}
13766 
13767 		if (ip_rput_pullups++ == 0) {
13768 			ipha = (ipha_t *)mp->b_rptr;
13769 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13770 			    "ip_check_and_align_header: %s forced us to "
13771 			    " pullup pkt, hdr len %ld, hdr addr %p",
13772 			    ill->ill_name, len, ipha);
13773 		}
13774 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13775 			/* clear b_prev - used by ip_mroute_decap */
13776 			mp->b_prev = NULL;
13777 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13778 			freemsg(mp);
13779 			return (B_FALSE);
13780 		}
13781 	}
13782 	return (B_TRUE);
13783 }
13784 
13785 ire_t *
13786 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13787 {
13788 	ire_t		*new_ire;
13789 	ill_t		*ire_ill;
13790 	uint_t		ifindex;
13791 	ip_stack_t	*ipst = ill->ill_ipst;
13792 	boolean_t	strict_check = B_FALSE;
13793 
13794 	/*
13795 	 * This packet came in on an interface other than the one associated
13796 	 * with the first ire we found for the destination address. We do
13797 	 * another ire lookup here, using the ingress ill, to see if the
13798 	 * interface is in an interface group.
13799 	 * As long as the ills belong to the same group, we don't consider
13800 	 * them to be arriving on the wrong interface. Thus, if the switch
13801 	 * is doing inbound load spreading, we won't drop packets when the
13802 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13803 	 * for 'usesrc groups' where the destination address may belong to
13804 	 * another interface to allow multipathing to happen.
13805 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13806 	 * where the local address may not be unique. In this case we were
13807 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13808 	 * actually returned. The new lookup, which is more specific, should
13809 	 * only find the IRE_LOCAL associated with the ingress ill if one
13810 	 * exists.
13811 	 */
13812 
13813 	if (ire->ire_ipversion == IPV4_VERSION) {
13814 		if (ipst->ips_ip_strict_dst_multihoming)
13815 			strict_check = B_TRUE;
13816 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13817 		    ill->ill_ipif, ALL_ZONES, NULL,
13818 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13819 	} else {
13820 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13821 		if (ipst->ips_ipv6_strict_dst_multihoming)
13822 			strict_check = B_TRUE;
13823 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13824 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13825 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13826 	}
13827 	/*
13828 	 * If the same ire that was returned in ip_input() is found then this
13829 	 * is an indication that interface groups are in use. The packet
13830 	 * arrived on a different ill in the group than the one associated with
13831 	 * the destination address.  If a different ire was found then the same
13832 	 * IP address must be hosted on multiple ills. This is possible with
13833 	 * unnumbered point2point interfaces. We switch to use this new ire in
13834 	 * order to have accurate interface statistics.
13835 	 */
13836 	if (new_ire != NULL) {
13837 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13838 			ire_refrele(ire);
13839 			ire = new_ire;
13840 		} else {
13841 			ire_refrele(new_ire);
13842 		}
13843 		return (ire);
13844 	} else if ((ire->ire_rfq == NULL) &&
13845 	    (ire->ire_ipversion == IPV4_VERSION)) {
13846 		/*
13847 		 * The best match could have been the original ire which
13848 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13849 		 * the strict multihoming checks are irrelevant as we consider
13850 		 * local addresses hosted on lo0 to be interface agnostic. We
13851 		 * only expect a null ire_rfq on IREs which are associated with
13852 		 * lo0 hence we can return now.
13853 		 */
13854 		return (ire);
13855 	}
13856 
13857 	/*
13858 	 * Chase pointers once and store locally.
13859 	 */
13860 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13861 	    (ill_t *)(ire->ire_rfq->q_ptr);
13862 	ifindex = ill->ill_usesrc_ifindex;
13863 
13864 	/*
13865 	 * Check if it's a legal address on the 'usesrc' interface.
13866 	 */
13867 	if ((ifindex != 0) && (ire_ill != NULL) &&
13868 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13869 		return (ire);
13870 	}
13871 
13872 	/*
13873 	 * If the ip*_strict_dst_multihoming switch is on then we can
13874 	 * only accept this packet if the interface is marked as routing.
13875 	 */
13876 	if (!(strict_check))
13877 		return (ire);
13878 
13879 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13880 	    ILLF_ROUTER) != 0) {
13881 		return (ire);
13882 	}
13883 
13884 	ire_refrele(ire);
13885 	return (NULL);
13886 }
13887 
13888 ire_t *
13889 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13890 {
13891 	ipha_t	*ipha;
13892 	ipaddr_t ip_dst, ip_src;
13893 	ire_t	*src_ire = NULL;
13894 	ill_t	*stq_ill;
13895 	uint_t	hlen;
13896 	uint_t	pkt_len;
13897 	uint32_t sum;
13898 	queue_t	*dev_q;
13899 	boolean_t check_multirt = B_FALSE;
13900 	ip_stack_t *ipst = ill->ill_ipst;
13901 
13902 	ipha = (ipha_t *)mp->b_rptr;
13903 
13904 	/*
13905 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13906 	 * The loopback address check for both src and dst has already
13907 	 * been checked in ip_input
13908 	 */
13909 	ip_dst = ntohl(dst);
13910 	ip_src = ntohl(ipha->ipha_src);
13911 
13912 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13913 	    IN_CLASSD(ip_src)) {
13914 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13915 		goto drop;
13916 	}
13917 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13918 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13919 
13920 	if (src_ire != NULL) {
13921 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13922 		goto drop;
13923 	}
13924 
13925 
13926 	/* No ire cache of nexthop. So first create one  */
13927 	if (ire == NULL) {
13928 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13929 		/*
13930 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13931 		 * is not set. So upon return from ire_forward
13932 		 * check_multirt should remain as false.
13933 		 */
13934 		ASSERT(!check_multirt);
13935 		if (ire == NULL) {
13936 			/* An attempt was made to forward the packet */
13937 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13938 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13939 			mp->b_prev = mp->b_next = 0;
13940 			/* send icmp unreachable */
13941 			/* Sent by forwarding path, and router is global zone */
13942 			if (ip_source_routed(ipha, ipst)) {
13943 				icmp_unreachable(ill->ill_wq, mp,
13944 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13945 				    ipst);
13946 			} else {
13947 				icmp_unreachable(ill->ill_wq, mp,
13948 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13949 				    ipst);
13950 			}
13951 			return (ire);
13952 		}
13953 	}
13954 
13955 	/*
13956 	 * Forwarding fastpath exception case:
13957 	 * If either of the follwoing case is true, we take
13958 	 * the slowpath
13959 	 *	o forwarding is not enabled
13960 	 *	o incoming and outgoing interface are the same, or the same
13961 	 *	  IPMP group
13962 	 *	o corresponding ire is in incomplete state
13963 	 *	o packet needs fragmentation
13964 	 *
13965 	 * The codeflow from here on is thus:
13966 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13967 	 */
13968 	pkt_len = ntohs(ipha->ipha_length);
13969 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13970 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13971 	    !(ill->ill_flags & ILLF_ROUTER) ||
13972 	    (ill == stq_ill) ||
13973 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13974 	    (ire->ire_nce == NULL) ||
13975 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13976 	    (pkt_len > ire->ire_max_frag) ||
13977 	    ipha->ipha_ttl <= 1) {
13978 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13979 		    ipha, ill, B_FALSE);
13980 		return (ire);
13981 	}
13982 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13983 
13984 	DTRACE_PROBE4(ip4__forwarding__start,
13985 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13986 
13987 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13988 	    ipst->ips_ipv4firewall_forwarding,
13989 	    ill, stq_ill, ipha, mp, mp, ipst);
13990 
13991 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13992 
13993 	if (mp == NULL)
13994 		goto drop;
13995 
13996 	mp->b_datap->db_struioun.cksum.flags = 0;
13997 	/* Adjust the checksum to reflect the ttl decrement. */
13998 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13999 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14000 	ipha->ipha_ttl--;
14001 
14002 	dev_q = ire->ire_stq->q_next;
14003 	if ((dev_q->q_next != NULL ||
14004 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14005 		goto indiscard;
14006 	}
14007 
14008 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14009 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14010 
14011 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14012 		mblk_t *mpip = mp;
14013 
14014 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14015 		if (mp != NULL) {
14016 			DTRACE_PROBE4(ip4__physical__out__start,
14017 			    ill_t *, NULL, ill_t *, stq_ill,
14018 			    ipha_t *, ipha, mblk_t *, mp);
14019 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14020 			    ipst->ips_ipv4firewall_physical_out,
14021 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14022 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14023 			    mp);
14024 			if (mp == NULL)
14025 				goto drop;
14026 
14027 			UPDATE_IB_PKT_COUNT(ire);
14028 			ire->ire_last_used_time = lbolt;
14029 			BUMP_MIB(stq_ill->ill_ip_mib,
14030 			    ipIfStatsHCOutForwDatagrams);
14031 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14032 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14033 			    pkt_len);
14034 			putnext(ire->ire_stq, mp);
14035 			return (ire);
14036 		}
14037 	}
14038 
14039 indiscard:
14040 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14041 drop:
14042 	if (mp != NULL)
14043 		freemsg(mp);
14044 	if (src_ire != NULL)
14045 		ire_refrele(src_ire);
14046 	return (ire);
14047 
14048 }
14049 
14050 /*
14051  * This function is called in the forwarding slowpath, when
14052  * either the ire lacks the link-layer address, or the packet needs
14053  * further processing(eg. fragmentation), before transmission.
14054  */
14055 
14056 static void
14057 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14058     ill_t *ill, boolean_t ll_multicast)
14059 {
14060 	ill_group_t	*ill_group;
14061 	ill_group_t	*ire_group;
14062 	queue_t		*dev_q;
14063 	ire_t		*src_ire;
14064 	ip_stack_t	*ipst = ill->ill_ipst;
14065 
14066 	ASSERT(ire->ire_stq != NULL);
14067 
14068 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14069 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14070 
14071 	if (ll_multicast != 0) {
14072 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14073 		goto drop_pkt;
14074 	}
14075 
14076 	/*
14077 	 * check if ipha_src is a broadcast address. Note that this
14078 	 * check is redundant when we get here from ip_fast_forward()
14079 	 * which has already done this check. However, since we can
14080 	 * also get here from ip_rput_process_broadcast() or, for
14081 	 * for the slow path through ip_fast_forward(), we perform
14082 	 * the check again for code-reusability
14083 	 */
14084 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14085 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14086 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14087 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14088 		if (src_ire != NULL)
14089 			ire_refrele(src_ire);
14090 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14091 		ip2dbg(("ip_rput_process_forward: Received packet with"
14092 		    " bad src/dst address on %s\n", ill->ill_name));
14093 		goto drop_pkt;
14094 	}
14095 
14096 	ill_group = ill->ill_group;
14097 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14098 	/*
14099 	 * Check if we want to forward this one at this time.
14100 	 * We allow source routed packets on a host provided that
14101 	 * they go out the same interface or same interface group
14102 	 * as they came in on.
14103 	 *
14104 	 * XXX To be quicker, we may wish to not chase pointers to
14105 	 * get the ILLF_ROUTER flag and instead store the
14106 	 * forwarding policy in the ire.  An unfortunate
14107 	 * side-effect of that would be requiring an ire flush
14108 	 * whenever the ILLF_ROUTER flag changes.
14109 	 */
14110 	if (((ill->ill_flags &
14111 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14112 	    ILLF_ROUTER) == 0) &&
14113 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14114 	    (ill_group != NULL && ill_group == ire_group)))) {
14115 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14116 		if (ip_source_routed(ipha, ipst)) {
14117 			q = WR(q);
14118 			/*
14119 			 * Clear the indication that this may have
14120 			 * hardware checksum as we are not using it.
14121 			 */
14122 			DB_CKSUMFLAGS(mp) = 0;
14123 			/* Sent by forwarding path, and router is global zone */
14124 			icmp_unreachable(q, mp,
14125 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14126 			return;
14127 		}
14128 		goto drop_pkt;
14129 	}
14130 
14131 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14132 
14133 	/* Packet is being forwarded. Turning off hwcksum flag. */
14134 	DB_CKSUMFLAGS(mp) = 0;
14135 	if (ipst->ips_ip_g_send_redirects) {
14136 		/*
14137 		 * Check whether the incoming interface and outgoing
14138 		 * interface is part of the same group. If so,
14139 		 * send redirects.
14140 		 *
14141 		 * Check the source address to see if it originated
14142 		 * on the same logical subnet it is going back out on.
14143 		 * If so, we should be able to send it a redirect.
14144 		 * Avoid sending a redirect if the destination
14145 		 * is directly connected (i.e., ipha_dst is the same
14146 		 * as ire_gateway_addr or the ire_addr of the
14147 		 * nexthop IRE_CACHE ), or if the packet was source
14148 		 * routed out this interface.
14149 		 */
14150 		ipaddr_t src, nhop;
14151 		mblk_t	*mp1;
14152 		ire_t	*nhop_ire = NULL;
14153 
14154 		/*
14155 		 * Check whether ire_rfq and q are from the same ill
14156 		 * or if they are not same, they at least belong
14157 		 * to the same group. If so, send redirects.
14158 		 */
14159 		if ((ire->ire_rfq == q ||
14160 		    (ill_group != NULL && ill_group == ire_group)) &&
14161 		    !ip_source_routed(ipha, ipst)) {
14162 
14163 			nhop = (ire->ire_gateway_addr != 0 ?
14164 			    ire->ire_gateway_addr : ire->ire_addr);
14165 
14166 			if (ipha->ipha_dst == nhop) {
14167 				/*
14168 				 * We avoid sending a redirect if the
14169 				 * destination is directly connected
14170 				 * because it is possible that multiple
14171 				 * IP subnets may have been configured on
14172 				 * the link, and the source may not
14173 				 * be on the same subnet as ip destination,
14174 				 * even though they are on the same
14175 				 * physical link.
14176 				 */
14177 				goto sendit;
14178 			}
14179 
14180 			src = ipha->ipha_src;
14181 
14182 			/*
14183 			 * We look up the interface ire for the nexthop,
14184 			 * to see if ipha_src is in the same subnet
14185 			 * as the nexthop.
14186 			 *
14187 			 * Note that, if, in the future, IRE_CACHE entries
14188 			 * are obsoleted,  this lookup will not be needed,
14189 			 * as the ire passed to this function will be the
14190 			 * same as the nhop_ire computed below.
14191 			 */
14192 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14193 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14194 			    0, NULL, MATCH_IRE_TYPE, ipst);
14195 
14196 			if (nhop_ire != NULL) {
14197 				if ((src & nhop_ire->ire_mask) ==
14198 				    (nhop & nhop_ire->ire_mask)) {
14199 					/*
14200 					 * The source is directly connected.
14201 					 * Just copy the ip header (which is
14202 					 * in the first mblk)
14203 					 */
14204 					mp1 = copyb(mp);
14205 					if (mp1 != NULL) {
14206 						icmp_send_redirect(WR(q), mp1,
14207 						    nhop, ipst);
14208 					}
14209 				}
14210 				ire_refrele(nhop_ire);
14211 			}
14212 		}
14213 	}
14214 sendit:
14215 	dev_q = ire->ire_stq->q_next;
14216 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14217 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14218 		freemsg(mp);
14219 		return;
14220 	}
14221 
14222 	ip_rput_forward(ire, ipha, mp, ill);
14223 	return;
14224 
14225 drop_pkt:
14226 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14227 	freemsg(mp);
14228 }
14229 
14230 ire_t *
14231 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14232     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14233 {
14234 	queue_t		*q;
14235 	uint16_t	hcksumflags;
14236 	ip_stack_t	*ipst = ill->ill_ipst;
14237 
14238 	q = *qp;
14239 
14240 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14241 
14242 	/*
14243 	 * Clear the indication that this may have hardware
14244 	 * checksum as we are not using it for forwarding.
14245 	 */
14246 	hcksumflags = DB_CKSUMFLAGS(mp);
14247 	DB_CKSUMFLAGS(mp) = 0;
14248 
14249 	/*
14250 	 * Directed broadcast forwarding: if the packet came in over a
14251 	 * different interface then it is routed out over we can forward it.
14252 	 */
14253 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14254 		ire_refrele(ire);
14255 		freemsg(mp);
14256 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14257 		return (NULL);
14258 	}
14259 	/*
14260 	 * For multicast we have set dst to be INADDR_BROADCAST
14261 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14262 	 * only for broadcast packets.
14263 	 */
14264 	if (!CLASSD(ipha->ipha_dst)) {
14265 		ire_t *new_ire;
14266 		ipif_t *ipif;
14267 		/*
14268 		 * For ill groups, as the switch duplicates broadcasts
14269 		 * across all the ports, we need to filter out and
14270 		 * send up only one copy. There is one copy for every
14271 		 * broadcast address on each ill. Thus, we look for a
14272 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14273 		 * later to see whether this ill is eligible to receive
14274 		 * them or not. ill_nominate_bcast_rcv() nominates only
14275 		 * one set of IREs for receiving.
14276 		 */
14277 
14278 		ipif = ipif_get_next_ipif(NULL, ill);
14279 		if (ipif == NULL) {
14280 			ire_refrele(ire);
14281 			freemsg(mp);
14282 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14283 			return (NULL);
14284 		}
14285 		new_ire = ire_ctable_lookup(dst, 0, 0,
14286 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14287 		ipif_refrele(ipif);
14288 
14289 		if (new_ire != NULL) {
14290 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14291 				ire_refrele(ire);
14292 				ire_refrele(new_ire);
14293 				freemsg(mp);
14294 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14295 				return (NULL);
14296 			}
14297 			/*
14298 			 * In the special case of multirouted broadcast
14299 			 * packets, we unconditionally need to "gateway"
14300 			 * them to the appropriate interface here.
14301 			 * In the normal case, this cannot happen, because
14302 			 * there is no broadcast IRE tagged with the
14303 			 * RTF_MULTIRT flag.
14304 			 */
14305 			if (new_ire->ire_flags & RTF_MULTIRT) {
14306 				ire_refrele(new_ire);
14307 				if (ire->ire_rfq != NULL) {
14308 					q = ire->ire_rfq;
14309 					*qp = q;
14310 				}
14311 			} else {
14312 				ire_refrele(ire);
14313 				ire = new_ire;
14314 			}
14315 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14316 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14317 				/*
14318 				 * Free the message if
14319 				 * ip_g_forward_directed_bcast is turned
14320 				 * off for non-local broadcast.
14321 				 */
14322 				ire_refrele(ire);
14323 				freemsg(mp);
14324 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14325 				return (NULL);
14326 			}
14327 		} else {
14328 			/*
14329 			 * This CGTP packet successfully passed the
14330 			 * CGTP filter, but the related CGTP
14331 			 * broadcast IRE has not been found,
14332 			 * meaning that the redundant ipif is
14333 			 * probably down. However, if we discarded
14334 			 * this packet, its duplicate would be
14335 			 * filtered out by the CGTP filter so none
14336 			 * of them would get through. So we keep
14337 			 * going with this one.
14338 			 */
14339 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14340 			if (ire->ire_rfq != NULL) {
14341 				q = ire->ire_rfq;
14342 				*qp = q;
14343 			}
14344 		}
14345 	}
14346 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14347 		/*
14348 		 * Verify that there are not more then one
14349 		 * IRE_BROADCAST with this broadcast address which
14350 		 * has ire_stq set.
14351 		 * TODO: simplify, loop over all IRE's
14352 		 */
14353 		ire_t	*ire1;
14354 		int	num_stq = 0;
14355 		mblk_t	*mp1;
14356 
14357 		/* Find the first one with ire_stq set */
14358 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14359 		for (ire1 = ire; ire1 &&
14360 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14361 		    ire1 = ire1->ire_next)
14362 			;
14363 		if (ire1) {
14364 			ire_refrele(ire);
14365 			ire = ire1;
14366 			IRE_REFHOLD(ire);
14367 		}
14368 
14369 		/* Check if there are additional ones with stq set */
14370 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14371 			if (ire->ire_addr != ire1->ire_addr)
14372 				break;
14373 			if (ire1->ire_stq) {
14374 				num_stq++;
14375 				break;
14376 			}
14377 		}
14378 		rw_exit(&ire->ire_bucket->irb_lock);
14379 		if (num_stq == 1 && ire->ire_stq != NULL) {
14380 			ip1dbg(("ip_rput_process_broadcast: directed "
14381 			    "broadcast to 0x%x\n",
14382 			    ntohl(ire->ire_addr)));
14383 			mp1 = copymsg(mp);
14384 			if (mp1) {
14385 				switch (ipha->ipha_protocol) {
14386 				case IPPROTO_UDP:
14387 					ip_udp_input(q, mp1, ipha, ire, ill);
14388 					break;
14389 				default:
14390 					ip_proto_input(q, mp1, ipha, ire, ill,
14391 					    B_FALSE);
14392 					break;
14393 				}
14394 			}
14395 			/*
14396 			 * Adjust ttl to 2 (1+1 - the forward engine
14397 			 * will decrement it by one.
14398 			 */
14399 			if (ip_csum_hdr(ipha)) {
14400 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14401 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14402 				freemsg(mp);
14403 				ire_refrele(ire);
14404 				return (NULL);
14405 			}
14406 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14407 			ipha->ipha_hdr_checksum = 0;
14408 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14409 			ip_rput_process_forward(q, mp, ire, ipha,
14410 			    ill, ll_multicast);
14411 			ire_refrele(ire);
14412 			return (NULL);
14413 		}
14414 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14415 		    ntohl(ire->ire_addr)));
14416 	}
14417 
14418 
14419 	/* Restore any hardware checksum flags */
14420 	DB_CKSUMFLAGS(mp) = hcksumflags;
14421 	return (ire);
14422 }
14423 
14424 /* ARGSUSED */
14425 static boolean_t
14426 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14427     int *ll_multicast, ipaddr_t *dstp)
14428 {
14429 	ip_stack_t	*ipst = ill->ill_ipst;
14430 
14431 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14432 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14433 	    ntohs(ipha->ipha_length));
14434 
14435 	/*
14436 	 * Forward packets only if we have joined the allmulti
14437 	 * group on this interface.
14438 	 */
14439 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14440 		int retval;
14441 
14442 		/*
14443 		 * Clear the indication that this may have hardware
14444 		 * checksum as we are not using it.
14445 		 */
14446 		DB_CKSUMFLAGS(mp) = 0;
14447 		retval = ip_mforward(ill, ipha, mp);
14448 		/* ip_mforward updates mib variables if needed */
14449 		/* clear b_prev - used by ip_mroute_decap */
14450 		mp->b_prev = NULL;
14451 
14452 		switch (retval) {
14453 		case 0:
14454 			/*
14455 			 * pkt is okay and arrived on phyint.
14456 			 *
14457 			 * If we are running as a multicast router
14458 			 * we need to see all IGMP and/or PIM packets.
14459 			 */
14460 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14461 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14462 				goto done;
14463 			}
14464 			break;
14465 		case -1:
14466 			/* pkt is mal-formed, toss it */
14467 			goto drop_pkt;
14468 		case 1:
14469 			/* pkt is okay and arrived on a tunnel */
14470 			/*
14471 			 * If we are running a multicast router
14472 			 *  we need to see all igmp packets.
14473 			 */
14474 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14475 				*dstp = INADDR_BROADCAST;
14476 				*ll_multicast = 1;
14477 				return (B_FALSE);
14478 			}
14479 
14480 			goto drop_pkt;
14481 		}
14482 	}
14483 
14484 	ILM_WALKER_HOLD(ill);
14485 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14486 		/*
14487 		 * This might just be caused by the fact that
14488 		 * multiple IP Multicast addresses map to the same
14489 		 * link layer multicast - no need to increment counter!
14490 		 */
14491 		ILM_WALKER_RELE(ill);
14492 		freemsg(mp);
14493 		return (B_TRUE);
14494 	}
14495 	ILM_WALKER_RELE(ill);
14496 done:
14497 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14498 	/*
14499 	 * This assumes the we deliver to all streams for multicast
14500 	 * and broadcast packets.
14501 	 */
14502 	*dstp = INADDR_BROADCAST;
14503 	*ll_multicast = 1;
14504 	return (B_FALSE);
14505 drop_pkt:
14506 	ip2dbg(("ip_rput: drop pkt\n"));
14507 	freemsg(mp);
14508 	return (B_TRUE);
14509 }
14510 
14511 static boolean_t
14512 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14513     int *ll_multicast, mblk_t **mpp)
14514 {
14515 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14516 	boolean_t must_copy = B_FALSE;
14517 	struct iocblk   *iocp;
14518 	ipha_t		*ipha;
14519 	ip_stack_t	*ipst = ill->ill_ipst;
14520 
14521 #define	rptr    ((uchar_t *)ipha)
14522 
14523 	first_mp = *first_mpp;
14524 	mp = *mpp;
14525 
14526 	ASSERT(first_mp == mp);
14527 
14528 	/*
14529 	 * if db_ref > 1 then copymsg and free original. Packet may be
14530 	 * changed and do not want other entity who has a reference to this
14531 	 * message to trip over the changes. This is a blind change because
14532 	 * trying to catch all places that might change packet is too
14533 	 * difficult (since it may be a module above this one)
14534 	 *
14535 	 * This corresponds to the non-fast path case. We walk down the full
14536 	 * chain in this case, and check the db_ref count of all the dblks,
14537 	 * and do a copymsg if required. It is possible that the db_ref counts
14538 	 * of the data blocks in the mblk chain can be different.
14539 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14540 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14541 	 * 'snoop' is running.
14542 	 */
14543 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14544 		if (mp1->b_datap->db_ref > 1) {
14545 			must_copy = B_TRUE;
14546 			break;
14547 		}
14548 	}
14549 
14550 	if (must_copy) {
14551 		mp1 = copymsg(mp);
14552 		if (mp1 == NULL) {
14553 			for (mp1 = mp; mp1 != NULL;
14554 			    mp1 = mp1->b_cont) {
14555 				mp1->b_next = NULL;
14556 				mp1->b_prev = NULL;
14557 			}
14558 			freemsg(mp);
14559 			if (ill != NULL) {
14560 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14561 			} else {
14562 				BUMP_MIB(&ipst->ips_ip_mib,
14563 				    ipIfStatsInDiscards);
14564 			}
14565 			return (B_TRUE);
14566 		}
14567 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14568 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14569 			/* Copy b_prev - used by ip_mroute_decap */
14570 			to_mp->b_prev = from_mp->b_prev;
14571 			from_mp->b_prev = NULL;
14572 		}
14573 		*first_mpp = first_mp = mp1;
14574 		freemsg(mp);
14575 		mp = mp1;
14576 		*mpp = mp1;
14577 	}
14578 
14579 	ipha = (ipha_t *)mp->b_rptr;
14580 
14581 	/*
14582 	 * previous code has a case for M_DATA.
14583 	 * We want to check how that happens.
14584 	 */
14585 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14586 	switch (first_mp->b_datap->db_type) {
14587 	case M_PROTO:
14588 	case M_PCPROTO:
14589 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14590 		    DL_UNITDATA_IND) {
14591 			/* Go handle anything other than data elsewhere. */
14592 			ip_rput_dlpi(q, mp);
14593 			return (B_TRUE);
14594 		}
14595 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14596 		/* Ditch the DLPI header. */
14597 		mp1 = mp->b_cont;
14598 		ASSERT(first_mp == mp);
14599 		*first_mpp = mp1;
14600 		freeb(mp);
14601 		*mpp = mp1;
14602 		return (B_FALSE);
14603 	case M_IOCACK:
14604 		ip1dbg(("got iocack "));
14605 		iocp = (struct iocblk *)mp->b_rptr;
14606 		switch (iocp->ioc_cmd) {
14607 		case DL_IOC_HDR_INFO:
14608 			ill = (ill_t *)q->q_ptr;
14609 			ill_fastpath_ack(ill, mp);
14610 			return (B_TRUE);
14611 		case SIOCSTUNPARAM:
14612 		case OSIOCSTUNPARAM:
14613 			/* Go through qwriter_ip */
14614 			break;
14615 		case SIOCGTUNPARAM:
14616 		case OSIOCGTUNPARAM:
14617 			ip_rput_other(NULL, q, mp, NULL);
14618 			return (B_TRUE);
14619 		default:
14620 			putnext(q, mp);
14621 			return (B_TRUE);
14622 		}
14623 		/* FALLTHRU */
14624 	case M_ERROR:
14625 	case M_HANGUP:
14626 		/*
14627 		 * Since this is on the ill stream we unconditionally
14628 		 * bump up the refcount
14629 		 */
14630 		ill_refhold(ill);
14631 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14632 		return (B_TRUE);
14633 	case M_CTL:
14634 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14635 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14636 		    IPHADA_M_CTL)) {
14637 			/*
14638 			 * It's an IPsec accelerated packet.
14639 			 * Make sure that the ill from which we received the
14640 			 * packet has enabled IPsec hardware acceleration.
14641 			 */
14642 			if (!(ill->ill_capabilities &
14643 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14644 				/* IPsec kstats: bean counter */
14645 				freemsg(mp);
14646 				return (B_TRUE);
14647 			}
14648 
14649 			/*
14650 			 * Make mp point to the mblk following the M_CTL,
14651 			 * then process according to type of mp.
14652 			 * After this processing, first_mp will point to
14653 			 * the data-attributes and mp to the pkt following
14654 			 * the M_CTL.
14655 			 */
14656 			mp = first_mp->b_cont;
14657 			if (mp == NULL) {
14658 				freemsg(first_mp);
14659 				return (B_TRUE);
14660 			}
14661 			/*
14662 			 * A Hardware Accelerated packet can only be M_DATA
14663 			 * ESP or AH packet.
14664 			 */
14665 			if (mp->b_datap->db_type != M_DATA) {
14666 				/* non-M_DATA IPsec accelerated packet */
14667 				IPSECHW_DEBUG(IPSECHW_PKT,
14668 				    ("non-M_DATA IPsec accelerated pkt\n"));
14669 				freemsg(first_mp);
14670 				return (B_TRUE);
14671 			}
14672 			ipha = (ipha_t *)mp->b_rptr;
14673 			if (ipha->ipha_protocol != IPPROTO_AH &&
14674 			    ipha->ipha_protocol != IPPROTO_ESP) {
14675 				IPSECHW_DEBUG(IPSECHW_PKT,
14676 				    ("non-M_DATA IPsec accelerated pkt\n"));
14677 				freemsg(first_mp);
14678 				return (B_TRUE);
14679 			}
14680 			*mpp = mp;
14681 			return (B_FALSE);
14682 		}
14683 		putnext(q, mp);
14684 		return (B_TRUE);
14685 	case M_IOCNAK:
14686 		ip1dbg(("got iocnak "));
14687 		iocp = (struct iocblk *)mp->b_rptr;
14688 		switch (iocp->ioc_cmd) {
14689 		case SIOCSTUNPARAM:
14690 		case OSIOCSTUNPARAM:
14691 			/*
14692 			 * Since this is on the ill stream we unconditionally
14693 			 * bump up the refcount
14694 			 */
14695 			ill_refhold(ill);
14696 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14697 			return (B_TRUE);
14698 		case DL_IOC_HDR_INFO:
14699 		case SIOCGTUNPARAM:
14700 		case OSIOCGTUNPARAM:
14701 			ip_rput_other(NULL, q, mp, NULL);
14702 			return (B_TRUE);
14703 		default:
14704 			break;
14705 		}
14706 		/* FALLTHRU */
14707 	default:
14708 		putnext(q, mp);
14709 		return (B_TRUE);
14710 	}
14711 }
14712 
14713 /* Read side put procedure.  Packets coming from the wire arrive here. */
14714 void
14715 ip_rput(queue_t *q, mblk_t *mp)
14716 {
14717 	ill_t		*ill = (ill_t *)q->q_ptr;
14718 	ip_stack_t	*ipst = ill->ill_ipst;
14719 	union DL_primitives *dl;
14720 
14721 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14722 
14723 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14724 		/*
14725 		 * If things are opening or closing, only accept high-priority
14726 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14727 		 * created; on close, things hanging off the ill may have been
14728 		 * freed already.)
14729 		 */
14730 		dl = (union DL_primitives *)mp->b_rptr;
14731 		if (DB_TYPE(mp) != M_PCPROTO ||
14732 		    dl->dl_primitive == DL_UNITDATA_IND) {
14733 			/*
14734 			 * SIOC[GS]TUNPARAM ioctls can come here.
14735 			 */
14736 			inet_freemsg(mp);
14737 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14738 			    "ip_rput_end: q %p (%S)", q, "uninit");
14739 			return;
14740 		}
14741 	}
14742 
14743 	/*
14744 	 * if db_ref > 1 then copymsg and free original. Packet may be
14745 	 * changed and we do not want the other entity who has a reference to
14746 	 * this message to trip over the changes. This is a blind change because
14747 	 * trying to catch all places that might change the packet is too
14748 	 * difficult.
14749 	 *
14750 	 * This corresponds to the fast path case, where we have a chain of
14751 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14752 	 * in the mblk chain. There doesn't seem to be a reason why a device
14753 	 * driver would send up data with varying db_ref counts in the mblk
14754 	 * chain. In any case the Fast path is a private interface, and our
14755 	 * drivers don't do such a thing. Given the above assumption, there is
14756 	 * no need to walk down the entire mblk chain (which could have a
14757 	 * potential performance problem)
14758 	 */
14759 	if (mp->b_datap->db_ref > 1) {
14760 		mblk_t  *mp1;
14761 		boolean_t adjusted = B_FALSE;
14762 		IP_STAT(ipst, ip_db_ref);
14763 
14764 		/*
14765 		 * The IP_RECVSLLA option depends on having the link layer
14766 		 * header. First check that:
14767 		 * a> the underlying device is of type ether, since this
14768 		 * option is currently supported only over ethernet.
14769 		 * b> there is enough room to copy over the link layer header.
14770 		 *
14771 		 * Once the checks are done, adjust rptr so that the link layer
14772 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14773 		 * be returned by some non-ethernet drivers but in this case the
14774 		 * second check will fail.
14775 		 */
14776 		if (ill->ill_type == IFT_ETHER &&
14777 		    (mp->b_rptr - mp->b_datap->db_base) >=
14778 		    sizeof (struct ether_header)) {
14779 			mp->b_rptr -= sizeof (struct ether_header);
14780 			adjusted = B_TRUE;
14781 		}
14782 		mp1 = copymsg(mp);
14783 		if (mp1 == NULL) {
14784 			mp->b_next = NULL;
14785 			/* clear b_prev - used by ip_mroute_decap */
14786 			mp->b_prev = NULL;
14787 			freemsg(mp);
14788 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14789 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14790 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14791 			return;
14792 		}
14793 		if (adjusted) {
14794 			/*
14795 			 * Copy is done. Restore the pointer in the _new_ mblk
14796 			 */
14797 			mp1->b_rptr += sizeof (struct ether_header);
14798 		}
14799 		/* Copy b_prev - used by ip_mroute_decap */
14800 		mp1->b_prev = mp->b_prev;
14801 		mp->b_prev = NULL;
14802 		freemsg(mp);
14803 		mp = mp1;
14804 	}
14805 
14806 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14807 	    "ip_rput_end: q %p (%S)", q, "end");
14808 
14809 	ip_input(ill, NULL, mp, NULL);
14810 }
14811 
14812 /*
14813  * Direct read side procedure capable of dealing with chains. GLDv3 based
14814  * drivers call this function directly with mblk chains while STREAMS
14815  * read side procedure ip_rput() calls this for single packet with ip_ring
14816  * set to NULL to process one packet at a time.
14817  *
14818  * The ill will always be valid if this function is called directly from
14819  * the driver.
14820  *
14821  * If ip_input() is called from GLDv3:
14822  *
14823  *   - This must be a non-VLAN IP stream.
14824  *   - 'mp' is either an untagged or a special priority-tagged packet.
14825  *   - Any VLAN tag that was in the MAC header has been stripped.
14826  *
14827  * If the IP header in packet is not 32-bit aligned, every message in the
14828  * chain will be aligned before further operations. This is required on SPARC
14829  * platform.
14830  */
14831 /* ARGSUSED */
14832 void
14833 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14834     struct mac_header_info_s *mhip)
14835 {
14836 	ipaddr_t		dst = NULL;
14837 	ipaddr_t		prev_dst;
14838 	ire_t			*ire = NULL;
14839 	ipha_t			*ipha;
14840 	uint_t			pkt_len;
14841 	ssize_t			len;
14842 	uint_t			opt_len;
14843 	int			ll_multicast;
14844 	int			cgtp_flt_pkt;
14845 	queue_t			*q = ill->ill_rq;
14846 	squeue_t		*curr_sqp = NULL;
14847 	mblk_t 			*head = NULL;
14848 	mblk_t			*tail = NULL;
14849 	mblk_t			*first_mp;
14850 	mblk_t 			*mp;
14851 	mblk_t			*dmp;
14852 	int			cnt = 0;
14853 	ip_stack_t		*ipst = ill->ill_ipst;
14854 
14855 	ASSERT(mp_chain != NULL);
14856 	ASSERT(ill != NULL);
14857 
14858 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14859 
14860 #define	rptr	((uchar_t *)ipha)
14861 
14862 	while (mp_chain != NULL) {
14863 		first_mp = mp = mp_chain;
14864 		mp_chain = mp_chain->b_next;
14865 		mp->b_next = NULL;
14866 		ll_multicast = 0;
14867 
14868 		/*
14869 		 * We do ire caching from one iteration to
14870 		 * another. In the event the packet chain contains
14871 		 * all packets from the same dst, this caching saves
14872 		 * an ire_cache_lookup for each of the succeeding
14873 		 * packets in a packet chain.
14874 		 */
14875 		prev_dst = dst;
14876 
14877 		/*
14878 		 * Check and align the IP header.
14879 		 */
14880 		if (DB_TYPE(mp) == M_DATA) {
14881 			dmp = mp;
14882 		} else if (DB_TYPE(mp) == M_PROTO &&
14883 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14884 			dmp = mp->b_cont;
14885 		} else {
14886 			dmp = NULL;
14887 		}
14888 		if (dmp != NULL) {
14889 			/*
14890 			 * IP header ptr not aligned?
14891 			 * OR IP header not complete in first mblk
14892 			 */
14893 			if (!OK_32PTR(dmp->b_rptr) ||
14894 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14895 				if (!ip_check_and_align_header(q, dmp, ipst))
14896 					continue;
14897 			}
14898 		}
14899 
14900 		/*
14901 		 * ip_input fast path
14902 		 */
14903 
14904 		/* mblk type is not M_DATA */
14905 		if (DB_TYPE(mp) != M_DATA) {
14906 			if (ip_rput_process_notdata(q, &first_mp, ill,
14907 			    &ll_multicast, &mp))
14908 				continue;
14909 		}
14910 
14911 		/* Make sure its an M_DATA and that its aligned */
14912 		ASSERT(DB_TYPE(mp) == M_DATA);
14913 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14914 
14915 		ipha = (ipha_t *)mp->b_rptr;
14916 		len = mp->b_wptr - rptr;
14917 		pkt_len = ntohs(ipha->ipha_length);
14918 
14919 		/*
14920 		 * We must count all incoming packets, even if they end
14921 		 * up being dropped later on.
14922 		 */
14923 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14924 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14925 
14926 		/* multiple mblk or too short */
14927 		len -= pkt_len;
14928 		if (len != 0) {
14929 			/*
14930 			 * Make sure we have data length consistent
14931 			 * with the IP header.
14932 			 */
14933 			if (mp->b_cont == NULL) {
14934 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14935 					BUMP_MIB(ill->ill_ip_mib,
14936 					    ipIfStatsInHdrErrors);
14937 					ip2dbg(("ip_input: drop pkt\n"));
14938 					freemsg(mp);
14939 					continue;
14940 				}
14941 				mp->b_wptr = rptr + pkt_len;
14942 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14943 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14944 					BUMP_MIB(ill->ill_ip_mib,
14945 					    ipIfStatsInHdrErrors);
14946 					ip2dbg(("ip_input: drop pkt\n"));
14947 					freemsg(mp);
14948 					continue;
14949 				}
14950 				(void) adjmsg(mp, -len);
14951 				IP_STAT(ipst, ip_multimblk3);
14952 			}
14953 		}
14954 
14955 		/* Obtain the dst of the current packet */
14956 		dst = ipha->ipha_dst;
14957 
14958 		if (IP_LOOPBACK_ADDR(dst) ||
14959 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14960 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14961 			cmn_err(CE_CONT, "dst %X src %X\n",
14962 			    dst, ipha->ipha_src);
14963 			freemsg(mp);
14964 			continue;
14965 		}
14966 
14967 		/*
14968 		 * The event for packets being received from a 'physical'
14969 		 * interface is placed after validation of the source and/or
14970 		 * destination address as being local so that packets can be
14971 		 * redirected to loopback addresses using ipnat.
14972 		 */
14973 		DTRACE_PROBE4(ip4__physical__in__start,
14974 		    ill_t *, ill, ill_t *, NULL,
14975 		    ipha_t *, ipha, mblk_t *, first_mp);
14976 
14977 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14978 		    ipst->ips_ipv4firewall_physical_in,
14979 		    ill, NULL, ipha, first_mp, mp, ipst);
14980 
14981 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14982 
14983 		if (first_mp == NULL) {
14984 			continue;
14985 		}
14986 		dst = ipha->ipha_dst;
14987 
14988 		/*
14989 		 * Attach any necessary label information to
14990 		 * this packet
14991 		 */
14992 		if (is_system_labeled() &&
14993 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14994 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14995 			freemsg(mp);
14996 			continue;
14997 		}
14998 
14999 		/*
15000 		 * Reuse the cached ire only if the ipha_dst of the previous
15001 		 * packet is the same as the current packet AND it is not
15002 		 * INADDR_ANY.
15003 		 */
15004 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15005 		    (ire != NULL)) {
15006 			ire_refrele(ire);
15007 			ire = NULL;
15008 		}
15009 		opt_len = ipha->ipha_version_and_hdr_length -
15010 		    IP_SIMPLE_HDR_VERSION;
15011 
15012 		/*
15013 		 * Check to see if we can take the fastpath.
15014 		 * That is possible if the following conditions are met
15015 		 *	o Tsol disabled
15016 		 *	o CGTP disabled
15017 		 *	o ipp_action_count is 0
15018 		 *	o no options in the packet
15019 		 *	o not a RSVP packet
15020 		 * 	o not a multicast packet
15021 		 */
15022 		if (!is_system_labeled() &&
15023 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15024 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15025 		    !ll_multicast && !CLASSD(dst)) {
15026 			if (ire == NULL)
15027 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15028 				    ipst);
15029 
15030 			/* incoming packet is for forwarding */
15031 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15032 				ire = ip_fast_forward(ire, dst, ill, mp);
15033 				continue;
15034 			}
15035 			/* incoming packet is for local consumption */
15036 			if (ire->ire_type & IRE_LOCAL)
15037 				goto local;
15038 		}
15039 
15040 		/*
15041 		 * Disable ire caching for anything more complex
15042 		 * than the simple fast path case we checked for above.
15043 		 */
15044 		if (ire != NULL) {
15045 			ire_refrele(ire);
15046 			ire = NULL;
15047 		}
15048 
15049 		/* Full-blown slow path */
15050 		if (opt_len != 0) {
15051 			if (len != 0)
15052 				IP_STAT(ipst, ip_multimblk4);
15053 			else
15054 				IP_STAT(ipst, ip_ipoptions);
15055 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15056 			    &dst, ipst))
15057 				continue;
15058 		}
15059 
15060 		/*
15061 		 * Invoke the CGTP (multirouting) filtering module to process
15062 		 * the incoming packet. Packets identified as duplicates
15063 		 * must be discarded. Filtering is active only if the
15064 		 * the ip_cgtp_filter ndd variable is non-zero.
15065 		 */
15066 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15067 		if (ipst->ips_ip_cgtp_filter &&
15068 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15069 			netstackid_t stackid;
15070 
15071 			stackid = ipst->ips_netstack->netstack_stackid;
15072 			cgtp_flt_pkt =
15073 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15074 			    ill->ill_phyint->phyint_ifindex, mp);
15075 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15076 				freemsg(first_mp);
15077 				continue;
15078 			}
15079 		}
15080 
15081 		/*
15082 		 * If rsvpd is running, let RSVP daemon handle its processing
15083 		 * and forwarding of RSVP multicast/unicast packets.
15084 		 * If rsvpd is not running but mrouted is running, RSVP
15085 		 * multicast packets are forwarded as multicast traffic
15086 		 * and RSVP unicast packets are forwarded by unicast router.
15087 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15088 		 * packets are not forwarded, but the unicast packets are
15089 		 * forwarded like unicast traffic.
15090 		 */
15091 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15092 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15093 		    NULL) {
15094 			/* RSVP packet and rsvpd running. Treat as ours */
15095 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15096 			/*
15097 			 * This assumes that we deliver to all streams for
15098 			 * multicast and broadcast packets.
15099 			 * We have to force ll_multicast to 1 to handle the
15100 			 * M_DATA messages passed in from ip_mroute_decap.
15101 			 */
15102 			dst = INADDR_BROADCAST;
15103 			ll_multicast = 1;
15104 		} else if (CLASSD(dst)) {
15105 			/* packet is multicast */
15106 			mp->b_next = NULL;
15107 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15108 			    &ll_multicast, &dst))
15109 				continue;
15110 		}
15111 
15112 		if (ire == NULL) {
15113 			ire = ire_cache_lookup(dst, ALL_ZONES,
15114 			    MBLK_GETLABEL(mp), ipst);
15115 		}
15116 
15117 		if (ire == NULL) {
15118 			/*
15119 			 * No IRE for this destination, so it can't be for us.
15120 			 * Unless we are forwarding, drop the packet.
15121 			 * We have to let source routed packets through
15122 			 * since we don't yet know if they are 'ping -l'
15123 			 * packets i.e. if they will go out over the
15124 			 * same interface as they came in on.
15125 			 */
15126 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15127 			if (ire == NULL)
15128 				continue;
15129 		}
15130 
15131 		/*
15132 		 * Broadcast IRE may indicate either broadcast or
15133 		 * multicast packet
15134 		 */
15135 		if (ire->ire_type == IRE_BROADCAST) {
15136 			/*
15137 			 * Skip broadcast checks if packet is UDP multicast;
15138 			 * we'd rather not enter ip_rput_process_broadcast()
15139 			 * unless the packet is broadcast for real, since
15140 			 * that routine is a no-op for multicast.
15141 			 */
15142 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15143 			    !CLASSD(ipha->ipha_dst)) {
15144 				ire = ip_rput_process_broadcast(&q, mp,
15145 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15146 				    ll_multicast);
15147 				if (ire == NULL)
15148 					continue;
15149 			}
15150 		} else if (ire->ire_stq != NULL) {
15151 			/* fowarding? */
15152 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15153 			    ll_multicast);
15154 			/* ip_rput_process_forward consumed the packet */
15155 			continue;
15156 		}
15157 
15158 local:
15159 		/*
15160 		 * If the queue in the ire is different to the ingress queue
15161 		 * then we need to check to see if we can accept the packet.
15162 		 * Note that for multicast packets and broadcast packets sent
15163 		 * to a broadcast address which is shared between multiple
15164 		 * interfaces we should not do this since we just got a random
15165 		 * broadcast ire.
15166 		 */
15167 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15168 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15169 			    ill)) == NULL) {
15170 				/* Drop packet */
15171 				BUMP_MIB(ill->ill_ip_mib,
15172 				    ipIfStatsForwProhibits);
15173 				freemsg(mp);
15174 				continue;
15175 			}
15176 			if (ire->ire_rfq != NULL)
15177 				q = ire->ire_rfq;
15178 		}
15179 
15180 		switch (ipha->ipha_protocol) {
15181 		case IPPROTO_TCP:
15182 			ASSERT(first_mp == mp);
15183 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15184 			    mp, 0, q, ip_ring)) != NULL) {
15185 				if (curr_sqp == NULL) {
15186 					curr_sqp = GET_SQUEUE(mp);
15187 					ASSERT(cnt == 0);
15188 					cnt++;
15189 					head = tail = mp;
15190 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15191 					ASSERT(tail != NULL);
15192 					cnt++;
15193 					tail->b_next = mp;
15194 					tail = mp;
15195 				} else {
15196 					/*
15197 					 * A different squeue. Send the
15198 					 * chain for the previous squeue on
15199 					 * its way. This shouldn't happen
15200 					 * often unless interrupt binding
15201 					 * changes.
15202 					 */
15203 					IP_STAT(ipst, ip_input_multi_squeue);
15204 					squeue_enter_chain(curr_sqp, head,
15205 					    tail, cnt, SQTAG_IP_INPUT);
15206 					curr_sqp = GET_SQUEUE(mp);
15207 					head = mp;
15208 					tail = mp;
15209 					cnt = 1;
15210 				}
15211 			}
15212 			continue;
15213 		case IPPROTO_UDP:
15214 			ASSERT(first_mp == mp);
15215 			ip_udp_input(q, mp, ipha, ire, ill);
15216 			continue;
15217 		case IPPROTO_SCTP:
15218 			ASSERT(first_mp == mp);
15219 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15220 			    q, dst);
15221 			/* ire has been released by ip_sctp_input */
15222 			ire = NULL;
15223 			continue;
15224 		default:
15225 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15226 			continue;
15227 		}
15228 	}
15229 
15230 	if (ire != NULL)
15231 		ire_refrele(ire);
15232 
15233 	if (head != NULL)
15234 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15235 
15236 	/*
15237 	 * This code is there just to make netperf/ttcp look good.
15238 	 *
15239 	 * Its possible that after being in polling mode (and having cleared
15240 	 * the backlog), squeues have turned the interrupt frequency higher
15241 	 * to improve latency at the expense of more CPU utilization (less
15242 	 * packets per interrupts or more number of interrupts). Workloads
15243 	 * like ttcp/netperf do manage to tickle polling once in a while
15244 	 * but for the remaining time, stay in higher interrupt mode since
15245 	 * their packet arrival rate is pretty uniform and this shows up
15246 	 * as higher CPU utilization. Since people care about CPU utilization
15247 	 * while running netperf/ttcp, turn the interrupt frequency back to
15248 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15249 	 */
15250 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15251 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15252 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15253 			ip_ring->rr_blank(ip_ring->rr_handle,
15254 			    ip_ring->rr_normal_blank_time,
15255 			    ip_ring->rr_normal_pkt_cnt);
15256 		}
15257 		}
15258 
15259 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15260 	    "ip_input_end: q %p (%S)", q, "end");
15261 #undef  rptr
15262 }
15263 
15264 static void
15265 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15266     t_uscalar_t err)
15267 {
15268 	if (dl_err == DL_SYSERR) {
15269 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15270 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15271 		    ill->ill_name, dlpi_prim_str(prim), err);
15272 		return;
15273 	}
15274 
15275 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15276 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15277 	    dlpi_err_str(dl_err));
15278 }
15279 
15280 /*
15281  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15282  * than DL_UNITDATA_IND messages. If we need to process this message
15283  * exclusively, we call qwriter_ip, in which case we also need to call
15284  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15285  */
15286 void
15287 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15288 {
15289 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15290 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15291 	ill_t		*ill = (ill_t *)q->q_ptr;
15292 	boolean_t	pending;
15293 
15294 	ip1dbg(("ip_rput_dlpi"));
15295 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15296 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15297 		    "%s (0x%x), unix %u\n", ill->ill_name,
15298 		    dlpi_prim_str(dlea->dl_error_primitive),
15299 		    dlea->dl_error_primitive,
15300 		    dlpi_err_str(dlea->dl_errno),
15301 		    dlea->dl_errno,
15302 		    dlea->dl_unix_errno));
15303 	}
15304 
15305 	/*
15306 	 * If we received an ACK but didn't send a request for it, then it
15307 	 * can't be part of any pending operation; discard up-front.
15308 	 */
15309 	switch (dloa->dl_primitive) {
15310 	case DL_NOTIFY_IND:
15311 		pending = B_TRUE;
15312 		break;
15313 	case DL_ERROR_ACK:
15314 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15315 		break;
15316 	case DL_OK_ACK:
15317 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15318 		break;
15319 	case DL_INFO_ACK:
15320 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15321 		break;
15322 	case DL_BIND_ACK:
15323 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15324 		break;
15325 	case DL_PHYS_ADDR_ACK:
15326 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15327 		break;
15328 	case DL_NOTIFY_ACK:
15329 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15330 		break;
15331 	case DL_CONTROL_ACK:
15332 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15333 		break;
15334 	case DL_CAPABILITY_ACK:
15335 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15336 		break;
15337 	default:
15338 		/* Not a DLPI message we support or were expecting */
15339 		freemsg(mp);
15340 		return;
15341 	}
15342 
15343 	if (!pending) {
15344 		freemsg(mp);
15345 		return;
15346 	}
15347 
15348 	switch (dloa->dl_primitive) {
15349 	case DL_ERROR_ACK:
15350 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15351 			mutex_enter(&ill->ill_lock);
15352 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15353 			cv_signal(&ill->ill_cv);
15354 			mutex_exit(&ill->ill_lock);
15355 		}
15356 		break;
15357 
15358 	case DL_OK_ACK:
15359 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15360 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15361 		switch (dloa->dl_correct_primitive) {
15362 		case DL_UNBIND_REQ:
15363 			mutex_enter(&ill->ill_lock);
15364 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15365 			cv_signal(&ill->ill_cv);
15366 			mutex_exit(&ill->ill_lock);
15367 			break;
15368 
15369 		case DL_ENABMULTI_REQ:
15370 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15371 				ill->ill_dlpi_multicast_state = IDS_OK;
15372 			break;
15373 		}
15374 		break;
15375 	default:
15376 		break;
15377 	}
15378 
15379 	/*
15380 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15381 	 * and we need to become writer to continue to process it. If it's not
15382 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15383 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15384 	 * some work as part of the current exclusive operation that actually
15385 	 * is not part of it -- which is wrong, but better than the
15386 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15387 	 * should track which DLPI requests have ACKs that we wait on
15388 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15389 	 *
15390 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15391 	 * Since this is on the ill stream we unconditionally bump up the
15392 	 * refcount without doing ILL_CAN_LOOKUP().
15393 	 */
15394 	ill_refhold(ill);
15395 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15396 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15397 	else
15398 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15399 }
15400 
15401 /*
15402  * Handling of DLPI messages that require exclusive access to the ipsq.
15403  *
15404  * Need to do ill_pending_mp_release on ioctl completion, which could
15405  * happen here. (along with mi_copy_done)
15406  */
15407 /* ARGSUSED */
15408 static void
15409 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15410 {
15411 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15412 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15413 	int		err = 0;
15414 	ill_t		*ill;
15415 	ipif_t		*ipif = NULL;
15416 	mblk_t		*mp1 = NULL;
15417 	conn_t		*connp = NULL;
15418 	t_uscalar_t	paddrreq;
15419 	mblk_t		*mp_hw;
15420 	boolean_t	success;
15421 	boolean_t	ioctl_aborted = B_FALSE;
15422 	boolean_t	log = B_TRUE;
15423 	hook_nic_event_t	*info;
15424 	ip_stack_t		*ipst;
15425 
15426 	ip1dbg(("ip_rput_dlpi_writer .."));
15427 	ill = (ill_t *)q->q_ptr;
15428 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15429 
15430 	ASSERT(IAM_WRITER_ILL(ill));
15431 
15432 	ipst = ill->ill_ipst;
15433 
15434 	/*
15435 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15436 	 * both are null or non-null. However we can assert that only
15437 	 * after grabbing the ipsq_lock. So we don't make any assertion
15438 	 * here and in other places in the code.
15439 	 */
15440 	ipif = ipsq->ipsq_pending_ipif;
15441 	/*
15442 	 * The current ioctl could have been aborted by the user and a new
15443 	 * ioctl to bring up another ill could have started. We could still
15444 	 * get a response from the driver later.
15445 	 */
15446 	if (ipif != NULL && ipif->ipif_ill != ill)
15447 		ioctl_aborted = B_TRUE;
15448 
15449 	switch (dloa->dl_primitive) {
15450 	case DL_ERROR_ACK:
15451 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15452 		    dlpi_prim_str(dlea->dl_error_primitive)));
15453 
15454 		switch (dlea->dl_error_primitive) {
15455 		case DL_PROMISCON_REQ:
15456 		case DL_PROMISCOFF_REQ:
15457 		case DL_DISABMULTI_REQ:
15458 		case DL_UNBIND_REQ:
15459 		case DL_ATTACH_REQ:
15460 		case DL_INFO_REQ:
15461 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15462 			break;
15463 		case DL_NOTIFY_REQ:
15464 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15465 			log = B_FALSE;
15466 			break;
15467 		case DL_PHYS_ADDR_REQ:
15468 			/*
15469 			 * For IPv6 only, there are two additional
15470 			 * phys_addr_req's sent to the driver to get the
15471 			 * IPv6 token and lla. This allows IP to acquire
15472 			 * the hardware address format for a given interface
15473 			 * without having built in knowledge of the hardware
15474 			 * address. ill_phys_addr_pend keeps track of the last
15475 			 * DL_PAR sent so we know which response we are
15476 			 * dealing with. ill_dlpi_done will update
15477 			 * ill_phys_addr_pend when it sends the next req.
15478 			 * We don't complete the IOCTL until all three DL_PARs
15479 			 * have been attempted, so set *_len to 0 and break.
15480 			 */
15481 			paddrreq = ill->ill_phys_addr_pend;
15482 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15483 			if (paddrreq == DL_IPV6_TOKEN) {
15484 				ill->ill_token_length = 0;
15485 				log = B_FALSE;
15486 				break;
15487 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15488 				ill->ill_nd_lla_len = 0;
15489 				log = B_FALSE;
15490 				break;
15491 			}
15492 			/*
15493 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15494 			 * We presumably have an IOCTL hanging out waiting
15495 			 * for completion. Find it and complete the IOCTL
15496 			 * with the error noted.
15497 			 * However, ill_dl_phys was called on an ill queue
15498 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15499 			 * set. But the ioctl is known to be pending on ill_wq.
15500 			 */
15501 			if (!ill->ill_ifname_pending)
15502 				break;
15503 			ill->ill_ifname_pending = 0;
15504 			if (!ioctl_aborted)
15505 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15506 			if (mp1 != NULL) {
15507 				/*
15508 				 * This operation (SIOCSLIFNAME) must have
15509 				 * happened on the ill. Assert there is no conn
15510 				 */
15511 				ASSERT(connp == NULL);
15512 				q = ill->ill_wq;
15513 			}
15514 			break;
15515 		case DL_BIND_REQ:
15516 			ill_dlpi_done(ill, DL_BIND_REQ);
15517 			if (ill->ill_ifname_pending)
15518 				break;
15519 			/*
15520 			 * Something went wrong with the bind.  We presumably
15521 			 * have an IOCTL hanging out waiting for completion.
15522 			 * Find it, take down the interface that was coming
15523 			 * up, and complete the IOCTL with the error noted.
15524 			 */
15525 			if (!ioctl_aborted)
15526 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15527 			if (mp1 != NULL) {
15528 				/*
15529 				 * This operation (SIOCSLIFFLAGS) must have
15530 				 * happened from a conn.
15531 				 */
15532 				ASSERT(connp != NULL);
15533 				q = CONNP_TO_WQ(connp);
15534 				if (ill->ill_move_in_progress) {
15535 					ILL_CLEAR_MOVE(ill);
15536 				}
15537 				(void) ipif_down(ipif, NULL, NULL);
15538 				/* error is set below the switch */
15539 			}
15540 			break;
15541 		case DL_ENABMULTI_REQ:
15542 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15543 
15544 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15545 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15546 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15547 				ipif_t *ipif;
15548 
15549 				printf("ip: joining multicasts failed (%d)"
15550 				    " on %s - will use link layer "
15551 				    "broadcasts for multicast\n",
15552 				    dlea->dl_errno, ill->ill_name);
15553 
15554 				/*
15555 				 * Set up the multicast mapping alone.
15556 				 * writer, so ok to access ill->ill_ipif
15557 				 * without any lock.
15558 				 */
15559 				ipif = ill->ill_ipif;
15560 				mutex_enter(&ill->ill_phyint->phyint_lock);
15561 				ill->ill_phyint->phyint_flags |=
15562 				    PHYI_MULTI_BCAST;
15563 				mutex_exit(&ill->ill_phyint->phyint_lock);
15564 
15565 				if (!ill->ill_isv6) {
15566 					(void) ipif_arp_setup_multicast(ipif,
15567 					    NULL);
15568 				} else {
15569 					(void) ipif_ndp_setup_multicast(ipif,
15570 					    NULL);
15571 				}
15572 			}
15573 			freemsg(mp);	/* Don't want to pass this up */
15574 			return;
15575 
15576 		case DL_CAPABILITY_REQ:
15577 		case DL_CONTROL_REQ:
15578 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15579 			ill->ill_dlpi_capab_state = IDS_FAILED;
15580 			freemsg(mp);
15581 			return;
15582 		}
15583 		/*
15584 		 * Note the error for IOCTL completion (mp1 is set when
15585 		 * ready to complete ioctl). If ill_ifname_pending_err is
15586 		 * set, an error occured during plumbing (ill_ifname_pending),
15587 		 * so we want to report that error.
15588 		 *
15589 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15590 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15591 		 * expected to get errack'd if the driver doesn't support
15592 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15593 		 * if these error conditions are encountered.
15594 		 */
15595 		if (mp1 != NULL) {
15596 			if (ill->ill_ifname_pending_err != 0)  {
15597 				err = ill->ill_ifname_pending_err;
15598 				ill->ill_ifname_pending_err = 0;
15599 			} else {
15600 				err = dlea->dl_unix_errno ?
15601 				    dlea->dl_unix_errno : ENXIO;
15602 			}
15603 		/*
15604 		 * If we're plumbing an interface and an error hasn't already
15605 		 * been saved, set ill_ifname_pending_err to the error passed
15606 		 * up. Ignore the error if log is B_FALSE (see comment above).
15607 		 */
15608 		} else if (log && ill->ill_ifname_pending &&
15609 		    ill->ill_ifname_pending_err == 0) {
15610 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15611 			    dlea->dl_unix_errno : ENXIO;
15612 		}
15613 
15614 		if (log)
15615 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15616 			    dlea->dl_errno, dlea->dl_unix_errno);
15617 		break;
15618 	case DL_CAPABILITY_ACK: {
15619 		boolean_t reneg_flag = B_FALSE;
15620 		/* Call a routine to handle this one. */
15621 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15622 		/*
15623 		 * Check if the ACK is due to renegotiation case since we
15624 		 * will need to send a new CAPABILITY_REQ later.
15625 		 */
15626 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15627 			/* This is the ack for a renogiation case */
15628 			reneg_flag = B_TRUE;
15629 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15630 		}
15631 		ill_capability_ack(ill, mp);
15632 		if (reneg_flag)
15633 			ill_capability_probe(ill);
15634 		break;
15635 	}
15636 	case DL_CONTROL_ACK:
15637 		/* We treat all of these as "fire and forget" */
15638 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15639 		break;
15640 	case DL_INFO_ACK:
15641 		/* Call a routine to handle this one. */
15642 		ill_dlpi_done(ill, DL_INFO_REQ);
15643 		ip_ll_subnet_defaults(ill, mp);
15644 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15645 		return;
15646 	case DL_BIND_ACK:
15647 		/*
15648 		 * We should have an IOCTL waiting on this unless
15649 		 * sent by ill_dl_phys, in which case just return
15650 		 */
15651 		ill_dlpi_done(ill, DL_BIND_REQ);
15652 		if (ill->ill_ifname_pending)
15653 			break;
15654 
15655 		if (!ioctl_aborted)
15656 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15657 		if (mp1 == NULL)
15658 			break;
15659 		/*
15660 		 * Because mp1 was added by ill_dl_up(), and it always
15661 		 * passes a valid connp, connp must be valid here.
15662 		 */
15663 		ASSERT(connp != NULL);
15664 		q = CONNP_TO_WQ(connp);
15665 
15666 		/*
15667 		 * We are exclusive. So nothing can change even after
15668 		 * we get the pending mp. If need be we can put it back
15669 		 * and restart, as in calling ipif_arp_up()  below.
15670 		 */
15671 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15672 
15673 		mutex_enter(&ill->ill_lock);
15674 
15675 		ill->ill_dl_up = 1;
15676 
15677 		if ((info = ill->ill_nic_event_info) != NULL) {
15678 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15679 			    "attached for %s\n", info->hne_event,
15680 			    ill->ill_name));
15681 			if (info->hne_data != NULL)
15682 				kmem_free(info->hne_data, info->hne_datalen);
15683 			kmem_free(info, sizeof (hook_nic_event_t));
15684 		}
15685 
15686 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15687 		if (info != NULL) {
15688 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15689 			info->hne_lif = 0;
15690 			info->hne_event = NE_UP;
15691 			info->hne_data = NULL;
15692 			info->hne_datalen = 0;
15693 			info->hne_family = ill->ill_isv6 ?
15694 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15695 		} else
15696 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15697 			    "event information for %s (ENOMEM)\n",
15698 			    ill->ill_name));
15699 
15700 		ill->ill_nic_event_info = info;
15701 
15702 		mutex_exit(&ill->ill_lock);
15703 
15704 		/*
15705 		 * Now bring up the resolver; when that is complete, we'll
15706 		 * create IREs.  Note that we intentionally mirror what
15707 		 * ipif_up() would have done, because we got here by way of
15708 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15709 		 */
15710 		if (ill->ill_isv6) {
15711 			/*
15712 			 * v6 interfaces.
15713 			 * Unlike ARP which has to do another bind
15714 			 * and attach, once we get here we are
15715 			 * done with NDP. Except in the case of
15716 			 * ILLF_XRESOLV, in which case we send an
15717 			 * AR_INTERFACE_UP to the external resolver.
15718 			 * If all goes well, the ioctl will complete
15719 			 * in ip_rput(). If there's an error, we
15720 			 * complete it here.
15721 			 */
15722 			if ((err = ipif_ndp_up(ipif)) == 0) {
15723 				if (ill->ill_flags & ILLF_XRESOLV) {
15724 					mutex_enter(&connp->conn_lock);
15725 					mutex_enter(&ill->ill_lock);
15726 					success = ipsq_pending_mp_add(
15727 					    connp, ipif, q, mp1, 0);
15728 					mutex_exit(&ill->ill_lock);
15729 					mutex_exit(&connp->conn_lock);
15730 					if (success) {
15731 						err = ipif_resolver_up(ipif,
15732 						    Res_act_initial);
15733 						if (err == EINPROGRESS) {
15734 							freemsg(mp);
15735 							return;
15736 						}
15737 						ASSERT(err != 0);
15738 						mp1 = ipsq_pending_mp_get(ipsq,
15739 						    &connp);
15740 						ASSERT(mp1 != NULL);
15741 					} else {
15742 						/* conn has started closing */
15743 						err = EINTR;
15744 					}
15745 				} else { /* Non XRESOLV interface */
15746 					(void) ipif_resolver_up(ipif,
15747 					    Res_act_initial);
15748 					err = ipif_up_done_v6(ipif);
15749 				}
15750 			}
15751 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15752 			/*
15753 			 * ARP and other v4 external resolvers.
15754 			 * Leave the pending mblk intact so that
15755 			 * the ioctl completes in ip_rput().
15756 			 */
15757 			mutex_enter(&connp->conn_lock);
15758 			mutex_enter(&ill->ill_lock);
15759 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15760 			mutex_exit(&ill->ill_lock);
15761 			mutex_exit(&connp->conn_lock);
15762 			if (success) {
15763 				err = ipif_resolver_up(ipif, Res_act_initial);
15764 				if (err == EINPROGRESS) {
15765 					freemsg(mp);
15766 					return;
15767 				}
15768 				ASSERT(err != 0);
15769 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15770 			} else {
15771 				/* The conn has started closing */
15772 				err = EINTR;
15773 			}
15774 		} else {
15775 			/*
15776 			 * This one is complete. Reply to pending ioctl.
15777 			 */
15778 			(void) ipif_resolver_up(ipif, Res_act_initial);
15779 			err = ipif_up_done(ipif);
15780 		}
15781 
15782 		if ((err == 0) && (ill->ill_up_ipifs)) {
15783 			err = ill_up_ipifs(ill, q, mp1);
15784 			if (err == EINPROGRESS) {
15785 				freemsg(mp);
15786 				return;
15787 			}
15788 		}
15789 
15790 		if (ill->ill_up_ipifs) {
15791 			ill_group_cleanup(ill);
15792 		}
15793 
15794 		break;
15795 	case DL_NOTIFY_IND: {
15796 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15797 		ire_t *ire;
15798 		boolean_t need_ire_walk_v4 = B_FALSE;
15799 		boolean_t need_ire_walk_v6 = B_FALSE;
15800 
15801 		switch (notify->dl_notification) {
15802 		case DL_NOTE_PHYS_ADDR:
15803 			err = ill_set_phys_addr(ill, mp);
15804 			break;
15805 
15806 		case DL_NOTE_FASTPATH_FLUSH:
15807 			ill_fastpath_flush(ill);
15808 			break;
15809 
15810 		case DL_NOTE_SDU_SIZE:
15811 			/*
15812 			 * Change the MTU size of the interface, of all
15813 			 * attached ipif's, and of all relevant ire's.  The
15814 			 * new value's a uint32_t at notify->dl_data.
15815 			 * Mtu change Vs. new ire creation - protocol below.
15816 			 *
15817 			 * a Mark the ipif as IPIF_CHANGING.
15818 			 * b Set the new mtu in the ipif.
15819 			 * c Change the ire_max_frag on all affected ires
15820 			 * d Unmark the IPIF_CHANGING
15821 			 *
15822 			 * To see how the protocol works, assume an interface
15823 			 * route is also being added simultaneously by
15824 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15825 			 * the ire. If the ire is created before step a,
15826 			 * it will be cleaned up by step c. If the ire is
15827 			 * created after step d, it will see the new value of
15828 			 * ipif_mtu. Any attempt to create the ire between
15829 			 * steps a to d will fail because of the IPIF_CHANGING
15830 			 * flag. Note that ire_create() is passed a pointer to
15831 			 * the ipif_mtu, and not the value. During ire_add
15832 			 * under the bucket lock, the ire_max_frag of the
15833 			 * new ire being created is set from the ipif/ire from
15834 			 * which it is being derived.
15835 			 */
15836 			mutex_enter(&ill->ill_lock);
15837 			ill->ill_max_frag = (uint_t)notify->dl_data;
15838 
15839 			/*
15840 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15841 			 * leave it alone
15842 			 */
15843 			if (ill->ill_mtu_userspecified) {
15844 				mutex_exit(&ill->ill_lock);
15845 				break;
15846 			}
15847 			ill->ill_max_mtu = ill->ill_max_frag;
15848 			if (ill->ill_isv6) {
15849 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15850 					ill->ill_max_mtu = IPV6_MIN_MTU;
15851 			} else {
15852 				if (ill->ill_max_mtu < IP_MIN_MTU)
15853 					ill->ill_max_mtu = IP_MIN_MTU;
15854 			}
15855 			for (ipif = ill->ill_ipif; ipif != NULL;
15856 			    ipif = ipif->ipif_next) {
15857 				/*
15858 				 * Don't override the mtu if the user
15859 				 * has explicitly set it.
15860 				 */
15861 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15862 					continue;
15863 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15864 				if (ipif->ipif_isv6)
15865 					ire = ipif_to_ire_v6(ipif);
15866 				else
15867 					ire = ipif_to_ire(ipif);
15868 				if (ire != NULL) {
15869 					ire->ire_max_frag = ipif->ipif_mtu;
15870 					ire_refrele(ire);
15871 				}
15872 				if (ipif->ipif_flags & IPIF_UP) {
15873 					if (ill->ill_isv6)
15874 						need_ire_walk_v6 = B_TRUE;
15875 					else
15876 						need_ire_walk_v4 = B_TRUE;
15877 				}
15878 			}
15879 			mutex_exit(&ill->ill_lock);
15880 			if (need_ire_walk_v4)
15881 				ire_walk_v4(ill_mtu_change, (char *)ill,
15882 				    ALL_ZONES, ipst);
15883 			if (need_ire_walk_v6)
15884 				ire_walk_v6(ill_mtu_change, (char *)ill,
15885 				    ALL_ZONES, ipst);
15886 			break;
15887 		case DL_NOTE_LINK_UP:
15888 		case DL_NOTE_LINK_DOWN: {
15889 			/*
15890 			 * We are writer. ill / phyint / ipsq assocs stable.
15891 			 * The RUNNING flag reflects the state of the link.
15892 			 */
15893 			phyint_t *phyint = ill->ill_phyint;
15894 			uint64_t new_phyint_flags;
15895 			boolean_t changed = B_FALSE;
15896 			boolean_t went_up;
15897 
15898 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15899 			mutex_enter(&phyint->phyint_lock);
15900 			new_phyint_flags = went_up ?
15901 			    phyint->phyint_flags | PHYI_RUNNING :
15902 			    phyint->phyint_flags & ~PHYI_RUNNING;
15903 			if (new_phyint_flags != phyint->phyint_flags) {
15904 				phyint->phyint_flags = new_phyint_flags;
15905 				changed = B_TRUE;
15906 			}
15907 			mutex_exit(&phyint->phyint_lock);
15908 			/*
15909 			 * ill_restart_dad handles the DAD restart and routing
15910 			 * socket notification logic.
15911 			 */
15912 			if (changed) {
15913 				ill_restart_dad(phyint->phyint_illv4, went_up);
15914 				ill_restart_dad(phyint->phyint_illv6, went_up);
15915 			}
15916 			break;
15917 		}
15918 		case DL_NOTE_PROMISC_ON_PHYS:
15919 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15920 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15921 			mutex_enter(&ill->ill_lock);
15922 			ill->ill_promisc_on_phys = B_TRUE;
15923 			mutex_exit(&ill->ill_lock);
15924 			break;
15925 		case DL_NOTE_PROMISC_OFF_PHYS:
15926 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15927 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15928 			mutex_enter(&ill->ill_lock);
15929 			ill->ill_promisc_on_phys = B_FALSE;
15930 			mutex_exit(&ill->ill_lock);
15931 			break;
15932 		case DL_NOTE_CAPAB_RENEG:
15933 			/*
15934 			 * Something changed on the driver side.
15935 			 * It wants us to renegotiate the capabilities
15936 			 * on this ill. The most likely cause is the
15937 			 * aggregation interface under us where a
15938 			 * port got added or went away.
15939 			 *
15940 			 * We reset the capabilities and set the
15941 			 * state to IDS_RENG so that when the ack
15942 			 * comes back, we can start the
15943 			 * renegotiation process.
15944 			 */
15945 			ill_capability_reset(ill);
15946 			ill->ill_dlpi_capab_state = IDS_RENEG;
15947 			break;
15948 		default:
15949 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15950 			    "type 0x%x for DL_NOTIFY_IND\n",
15951 			    notify->dl_notification));
15952 			break;
15953 		}
15954 
15955 		/*
15956 		 * As this is an asynchronous operation, we
15957 		 * should not call ill_dlpi_done
15958 		 */
15959 		break;
15960 	}
15961 	case DL_NOTIFY_ACK: {
15962 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15963 
15964 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15965 			ill->ill_note_link = 1;
15966 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15967 		break;
15968 	}
15969 	case DL_PHYS_ADDR_ACK: {
15970 		/*
15971 		 * As part of plumbing the interface via SIOCSLIFNAME,
15972 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
15973 		 * whose answers we receive here.  As each answer is received,
15974 		 * we call ill_dlpi_done() to dispatch the next request as
15975 		 * we're processing the current one.  Once all answers have
15976 		 * been received, we use ipsq_pending_mp_get() to dequeue the
15977 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
15978 		 * is invoked from an ill queue, conn_oper_pending_ill is not
15979 		 * available, but we know the ioctl is pending on ill_wq.)
15980 		 */
15981 		uint_t paddrlen, paddroff;
15982 
15983 		paddrreq = ill->ill_phys_addr_pend;
15984 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
15985 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
15986 
15987 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15988 		if (paddrreq == DL_IPV6_TOKEN) {
15989 			/*
15990 			 * bcopy to low-order bits of ill_token
15991 			 *
15992 			 * XXX Temporary hack - currently, all known tokens
15993 			 * are 64 bits, so I'll cheat for the moment.
15994 			 */
15995 			bcopy(mp->b_rptr + paddroff,
15996 			    &ill->ill_token.s6_addr32[2], paddrlen);
15997 			ill->ill_token_length = paddrlen;
15998 			break;
15999 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16000 			ASSERT(ill->ill_nd_lla_mp == NULL);
16001 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16002 			mp = NULL;
16003 			break;
16004 		}
16005 
16006 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16007 		ASSERT(ill->ill_phys_addr_mp == NULL);
16008 		if (!ill->ill_ifname_pending)
16009 			break;
16010 		ill->ill_ifname_pending = 0;
16011 		if (!ioctl_aborted)
16012 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16013 		if (mp1 != NULL) {
16014 			ASSERT(connp == NULL);
16015 			q = ill->ill_wq;
16016 		}
16017 		/*
16018 		 * If any error acks received during the plumbing sequence,
16019 		 * ill_ifname_pending_err will be set. Break out and send up
16020 		 * the error to the pending ioctl.
16021 		 */
16022 		if (ill->ill_ifname_pending_err != 0) {
16023 			err = ill->ill_ifname_pending_err;
16024 			ill->ill_ifname_pending_err = 0;
16025 			break;
16026 		}
16027 
16028 		ill->ill_phys_addr_mp = mp;
16029 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16030 		mp = NULL;
16031 
16032 		/*
16033 		 * If paddrlen is zero, the DLPI provider doesn't support
16034 		 * physical addresses.  The other two tests were historical
16035 		 * workarounds for bugs in our former PPP implementation, but
16036 		 * now other things have grown dependencies on them -- e.g.,
16037 		 * the tun module specifies a dl_addr_length of zero in its
16038 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16039 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16040 		 * but only after careful testing ensures that all dependent
16041 		 * broken DLPI providers have been fixed.
16042 		 */
16043 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16044 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16045 			ill->ill_phys_addr = NULL;
16046 		} else if (paddrlen != ill->ill_phys_addr_length) {
16047 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16048 			    paddrlen, ill->ill_phys_addr_length));
16049 			err = EINVAL;
16050 			break;
16051 		}
16052 
16053 		if (ill->ill_nd_lla_mp == NULL) {
16054 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16055 				err = ENOMEM;
16056 				break;
16057 			}
16058 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16059 		}
16060 
16061 		/*
16062 		 * Set the interface token.  If the zeroth interface address
16063 		 * is unspecified, then set it to the link local address.
16064 		 */
16065 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16066 			(void) ill_setdefaulttoken(ill);
16067 
16068 		ASSERT(ill->ill_ipif->ipif_id == 0);
16069 		if (ipif != NULL &&
16070 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16071 			(void) ipif_setlinklocal(ipif);
16072 		}
16073 		break;
16074 	}
16075 	case DL_OK_ACK:
16076 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16077 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16078 		    dloa->dl_correct_primitive));
16079 		switch (dloa->dl_correct_primitive) {
16080 		case DL_PROMISCON_REQ:
16081 		case DL_PROMISCOFF_REQ:
16082 		case DL_ENABMULTI_REQ:
16083 		case DL_DISABMULTI_REQ:
16084 		case DL_UNBIND_REQ:
16085 		case DL_ATTACH_REQ:
16086 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16087 			break;
16088 		}
16089 		break;
16090 	default:
16091 		break;
16092 	}
16093 
16094 	freemsg(mp);
16095 	if (mp1 != NULL) {
16096 		/*
16097 		 * The operation must complete without EINPROGRESS
16098 		 * since ipsq_pending_mp_get() has removed the mblk
16099 		 * from ipsq_pending_mp.  Otherwise, the operation
16100 		 * will be stuck forever in the ipsq.
16101 		 */
16102 		ASSERT(err != EINPROGRESS);
16103 
16104 		switch (ipsq->ipsq_current_ioctl) {
16105 		case 0:
16106 			ipsq_current_finish(ipsq);
16107 			break;
16108 
16109 		case SIOCLIFADDIF:
16110 		case SIOCSLIFNAME:
16111 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16112 			break;
16113 
16114 		default:
16115 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16116 			break;
16117 		}
16118 	}
16119 }
16120 
16121 /*
16122  * ip_rput_other is called by ip_rput to handle messages modifying the global
16123  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16124  */
16125 /* ARGSUSED */
16126 void
16127 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16128 {
16129 	ill_t		*ill;
16130 	struct iocblk	*iocp;
16131 	mblk_t		*mp1;
16132 	conn_t		*connp = NULL;
16133 
16134 	ip1dbg(("ip_rput_other "));
16135 	ill = (ill_t *)q->q_ptr;
16136 	/*
16137 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16138 	 * in which case ipsq is NULL.
16139 	 */
16140 	if (ipsq != NULL) {
16141 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16142 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16143 	}
16144 
16145 	switch (mp->b_datap->db_type) {
16146 	case M_ERROR:
16147 	case M_HANGUP:
16148 		/*
16149 		 * The device has a problem.  We force the ILL down.  It can
16150 		 * be brought up again manually using SIOCSIFFLAGS (via
16151 		 * ifconfig or equivalent).
16152 		 */
16153 		ASSERT(ipsq != NULL);
16154 		if (mp->b_rptr < mp->b_wptr)
16155 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16156 		if (ill->ill_error == 0)
16157 			ill->ill_error = ENXIO;
16158 		if (!ill_down_start(q, mp))
16159 			return;
16160 		ipif_all_down_tail(ipsq, q, mp, NULL);
16161 		break;
16162 	case M_IOCACK:
16163 		iocp = (struct iocblk *)mp->b_rptr;
16164 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16165 		switch (iocp->ioc_cmd) {
16166 		case SIOCSTUNPARAM:
16167 		case OSIOCSTUNPARAM:
16168 			ASSERT(ipsq != NULL);
16169 			/*
16170 			 * Finish socket ioctl passed through to tun.
16171 			 * We should have an IOCTL waiting on this.
16172 			 */
16173 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16174 			if (ill->ill_isv6) {
16175 				struct iftun_req *ta;
16176 
16177 				/*
16178 				 * if a source or destination is
16179 				 * being set, try and set the link
16180 				 * local address for the tunnel
16181 				 */
16182 				ta = (struct iftun_req *)mp->b_cont->
16183 				    b_cont->b_rptr;
16184 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16185 					ipif_set_tun_llink(ill, ta);
16186 				}
16187 
16188 			}
16189 			if (mp1 != NULL) {
16190 				/*
16191 				 * Now copy back the b_next/b_prev used by
16192 				 * mi code for the mi_copy* functions.
16193 				 * See ip_sioctl_tunparam() for the reason.
16194 				 * Also protect against missing b_cont.
16195 				 */
16196 				if (mp->b_cont != NULL) {
16197 					mp->b_cont->b_next =
16198 					    mp1->b_cont->b_next;
16199 					mp->b_cont->b_prev =
16200 					    mp1->b_cont->b_prev;
16201 				}
16202 				inet_freemsg(mp1);
16203 				ASSERT(connp != NULL);
16204 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16205 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16206 			} else {
16207 				ASSERT(connp == NULL);
16208 				putnext(q, mp);
16209 			}
16210 			break;
16211 		case SIOCGTUNPARAM:
16212 		case OSIOCGTUNPARAM:
16213 			/*
16214 			 * This is really M_IOCDATA from the tunnel driver.
16215 			 * convert back and complete the ioctl.
16216 			 * We should have an IOCTL waiting on this.
16217 			 */
16218 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16219 			if (mp1) {
16220 				/*
16221 				 * Now copy back the b_next/b_prev used by
16222 				 * mi code for the mi_copy* functions.
16223 				 * See ip_sioctl_tunparam() for the reason.
16224 				 * Also protect against missing b_cont.
16225 				 */
16226 				if (mp->b_cont != NULL) {
16227 					mp->b_cont->b_next =
16228 					    mp1->b_cont->b_next;
16229 					mp->b_cont->b_prev =
16230 					    mp1->b_cont->b_prev;
16231 				}
16232 				inet_freemsg(mp1);
16233 				if (iocp->ioc_error == 0)
16234 					mp->b_datap->db_type = M_IOCDATA;
16235 				ASSERT(connp != NULL);
16236 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16237 				    iocp->ioc_error, COPYOUT, NULL);
16238 			} else {
16239 				ASSERT(connp == NULL);
16240 				putnext(q, mp);
16241 			}
16242 			break;
16243 		default:
16244 			break;
16245 		}
16246 		break;
16247 	case M_IOCNAK:
16248 		iocp = (struct iocblk *)mp->b_rptr;
16249 
16250 		switch (iocp->ioc_cmd) {
16251 		int mode;
16252 
16253 		case DL_IOC_HDR_INFO:
16254 			/*
16255 			 * If this was the first attempt turn of the
16256 			 * fastpath probing.
16257 			 */
16258 			mutex_enter(&ill->ill_lock);
16259 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16260 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16261 				mutex_exit(&ill->ill_lock);
16262 				ill_fastpath_nack(ill);
16263 				ip1dbg(("ip_rput: DLPI fastpath off on "
16264 				    "interface %s\n",
16265 				    ill->ill_name));
16266 			} else {
16267 				mutex_exit(&ill->ill_lock);
16268 			}
16269 			freemsg(mp);
16270 			break;
16271 		case SIOCSTUNPARAM:
16272 		case OSIOCSTUNPARAM:
16273 			ASSERT(ipsq != NULL);
16274 			/*
16275 			 * Finish socket ioctl passed through to tun
16276 			 * We should have an IOCTL waiting on this.
16277 			 */
16278 			/* FALLTHRU */
16279 		case SIOCGTUNPARAM:
16280 		case OSIOCGTUNPARAM:
16281 			/*
16282 			 * This is really M_IOCDATA from the tunnel driver.
16283 			 * convert back and complete the ioctl.
16284 			 * We should have an IOCTL waiting on this.
16285 			 */
16286 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16287 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16288 				mp1 = ill_pending_mp_get(ill, &connp,
16289 				    iocp->ioc_id);
16290 				mode = COPYOUT;
16291 				ipsq = NULL;
16292 			} else {
16293 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16294 				mode = NO_COPYOUT;
16295 			}
16296 			if (mp1 != NULL) {
16297 				/*
16298 				 * Now copy back the b_next/b_prev used by
16299 				 * mi code for the mi_copy* functions.
16300 				 * See ip_sioctl_tunparam() for the reason.
16301 				 * Also protect against missing b_cont.
16302 				 */
16303 				if (mp->b_cont != NULL) {
16304 					mp->b_cont->b_next =
16305 					    mp1->b_cont->b_next;
16306 					mp->b_cont->b_prev =
16307 					    mp1->b_cont->b_prev;
16308 				}
16309 				inet_freemsg(mp1);
16310 				if (iocp->ioc_error == 0)
16311 					iocp->ioc_error = EINVAL;
16312 				ASSERT(connp != NULL);
16313 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16314 				    iocp->ioc_error, mode, ipsq);
16315 			} else {
16316 				ASSERT(connp == NULL);
16317 				putnext(q, mp);
16318 			}
16319 			break;
16320 		default:
16321 			break;
16322 		}
16323 	default:
16324 		break;
16325 	}
16326 }
16327 
16328 /*
16329  * NOTE : This function does not ire_refrele the ire argument passed in.
16330  *
16331  * IPQoS notes
16332  * IP policy is invoked twice for a forwarded packet, once on the read side
16333  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16334  * enabled. An additional parameter, in_ill, has been added for this purpose.
16335  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16336  * because ip_mroute drops this information.
16337  *
16338  */
16339 void
16340 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16341 {
16342 	uint32_t	old_pkt_len;
16343 	uint32_t	pkt_len;
16344 	queue_t	*q;
16345 	uint32_t	sum;
16346 #define	rptr	((uchar_t *)ipha)
16347 	uint32_t	max_frag;
16348 	uint32_t	ill_index;
16349 	ill_t		*out_ill;
16350 	mib2_ipIfStatsEntry_t *mibptr;
16351 	ip_stack_t	*ipst = in_ill->ill_ipst;
16352 
16353 	/* Get the ill_index of the incoming ILL */
16354 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16355 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16356 
16357 	/* Initiate Read side IPPF processing */
16358 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16359 		ip_process(IPP_FWD_IN, &mp, ill_index);
16360 		if (mp == NULL) {
16361 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16362 			    "during IPPF processing\n"));
16363 			return;
16364 		}
16365 	}
16366 
16367 	/* Adjust the checksum to reflect the ttl decrement. */
16368 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16369 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16370 
16371 	if (ipha->ipha_ttl-- <= 1) {
16372 		if (ip_csum_hdr(ipha)) {
16373 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16374 			goto drop_pkt;
16375 		}
16376 		/*
16377 		 * Note: ire_stq this will be NULL for multicast
16378 		 * datagrams using the long path through arp (the IRE
16379 		 * is not an IRE_CACHE). This should not cause
16380 		 * problems since we don't generate ICMP errors for
16381 		 * multicast packets.
16382 		 */
16383 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16384 		q = ire->ire_stq;
16385 		if (q != NULL) {
16386 			/* Sent by forwarding path, and router is global zone */
16387 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16388 			    GLOBAL_ZONEID, ipst);
16389 		} else
16390 			freemsg(mp);
16391 		return;
16392 	}
16393 
16394 	/*
16395 	 * Don't forward if the interface is down
16396 	 */
16397 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16398 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16399 		ip2dbg(("ip_rput_forward:interface is down\n"));
16400 		goto drop_pkt;
16401 	}
16402 
16403 	/* Get the ill_index of the outgoing ILL */
16404 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16405 
16406 	out_ill = ire->ire_ipif->ipif_ill;
16407 
16408 	DTRACE_PROBE4(ip4__forwarding__start,
16409 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16410 
16411 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16412 	    ipst->ips_ipv4firewall_forwarding,
16413 	    in_ill, out_ill, ipha, mp, mp, ipst);
16414 
16415 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16416 
16417 	if (mp == NULL)
16418 		return;
16419 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16420 
16421 	if (is_system_labeled()) {
16422 		mblk_t *mp1;
16423 
16424 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16425 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16426 			goto drop_pkt;
16427 		}
16428 		/* Size may have changed */
16429 		mp = mp1;
16430 		ipha = (ipha_t *)mp->b_rptr;
16431 		pkt_len = ntohs(ipha->ipha_length);
16432 	}
16433 
16434 	/* Check if there are options to update */
16435 	if (!IS_SIMPLE_IPH(ipha)) {
16436 		if (ip_csum_hdr(ipha)) {
16437 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16438 			goto drop_pkt;
16439 		}
16440 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16441 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16442 			return;
16443 		}
16444 
16445 		ipha->ipha_hdr_checksum = 0;
16446 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16447 	}
16448 	max_frag = ire->ire_max_frag;
16449 	if (pkt_len > max_frag) {
16450 		/*
16451 		 * It needs fragging on its way out.  We haven't
16452 		 * verified the header checksum yet.  Since we
16453 		 * are going to put a surely good checksum in the
16454 		 * outgoing header, we have to make sure that it
16455 		 * was good coming in.
16456 		 */
16457 		if (ip_csum_hdr(ipha)) {
16458 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16459 			goto drop_pkt;
16460 		}
16461 		/* Initiate Write side IPPF processing */
16462 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16463 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16464 			if (mp == NULL) {
16465 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16466 				    " during IPPF processing\n"));
16467 				return;
16468 			}
16469 		}
16470 		/*
16471 		 * Handle labeled packet resizing.
16472 		 *
16473 		 * If we have added a label, inform ip_wput_frag() of its
16474 		 * effect on the MTU for ICMP messages.
16475 		 */
16476 		if (pkt_len > old_pkt_len) {
16477 			uint32_t secopt_size;
16478 
16479 			secopt_size = pkt_len - old_pkt_len;
16480 			if (secopt_size < max_frag)
16481 				max_frag -= secopt_size;
16482 		}
16483 
16484 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16485 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16486 		return;
16487 	}
16488 
16489 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16490 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16491 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16492 	    ipst->ips_ipv4firewall_physical_out,
16493 	    NULL, out_ill, ipha, mp, mp, ipst);
16494 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16495 	if (mp == NULL)
16496 		return;
16497 
16498 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16499 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16500 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16501 	/* ip_xmit_v4 always consumes the packet */
16502 	return;
16503 
16504 drop_pkt:;
16505 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16506 	freemsg(mp);
16507 #undef	rptr
16508 }
16509 
16510 void
16511 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16512 {
16513 	ire_t	*ire;
16514 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16515 
16516 	ASSERT(!ipif->ipif_isv6);
16517 	/*
16518 	 * Find an IRE which matches the destination and the outgoing
16519 	 * queue in the cache table. All we need is an IRE_CACHE which
16520 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16521 	 * then it is enough to have some IRE_CACHE in the group.
16522 	 */
16523 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16524 		dst = ipif->ipif_pp_dst_addr;
16525 
16526 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16527 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16528 	if (ire == NULL) {
16529 		/*
16530 		 * Mark this packet to make it be delivered to
16531 		 * ip_rput_forward after the new ire has been
16532 		 * created.
16533 		 */
16534 		mp->b_prev = NULL;
16535 		mp->b_next = mp;
16536 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16537 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16538 	} else {
16539 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16540 		IRE_REFRELE(ire);
16541 	}
16542 }
16543 
16544 /* Update any source route, record route or timestamp options */
16545 static int
16546 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16547 {
16548 	ipoptp_t	opts;
16549 	uchar_t		*opt;
16550 	uint8_t		optval;
16551 	uint8_t		optlen;
16552 	ipaddr_t	dst;
16553 	uint32_t	ts;
16554 	ire_t		*dst_ire = NULL;
16555 	ire_t		*tmp_ire = NULL;
16556 	timestruc_t	now;
16557 
16558 	ip2dbg(("ip_rput_forward_options\n"));
16559 	dst = ipha->ipha_dst;
16560 	for (optval = ipoptp_first(&opts, ipha);
16561 	    optval != IPOPT_EOL;
16562 	    optval = ipoptp_next(&opts)) {
16563 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16564 		opt = opts.ipoptp_cur;
16565 		optlen = opts.ipoptp_len;
16566 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16567 		    optval, opts.ipoptp_len));
16568 		switch (optval) {
16569 			uint32_t off;
16570 		case IPOPT_SSRR:
16571 		case IPOPT_LSRR:
16572 			/* Check if adminstratively disabled */
16573 			if (!ipst->ips_ip_forward_src_routed) {
16574 				if (ire->ire_stq != NULL) {
16575 					/*
16576 					 * Sent by forwarding path, and router
16577 					 * is global zone
16578 					 */
16579 					icmp_unreachable(ire->ire_stq, mp,
16580 					    ICMP_SOURCE_ROUTE_FAILED,
16581 					    GLOBAL_ZONEID, ipst);
16582 				} else {
16583 					ip0dbg(("ip_rput_forward_options: "
16584 					    "unable to send unreach\n"));
16585 					freemsg(mp);
16586 				}
16587 				return (-1);
16588 			}
16589 
16590 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16591 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16592 			if (dst_ire == NULL) {
16593 				/*
16594 				 * Must be partial since ip_rput_options
16595 				 * checked for strict.
16596 				 */
16597 				break;
16598 			}
16599 			off = opt[IPOPT_OFFSET];
16600 			off--;
16601 		redo_srr:
16602 			if (optlen < IP_ADDR_LEN ||
16603 			    off > optlen - IP_ADDR_LEN) {
16604 				/* End of source route */
16605 				ip1dbg((
16606 				    "ip_rput_forward_options: end of SR\n"));
16607 				ire_refrele(dst_ire);
16608 				break;
16609 			}
16610 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16611 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16612 			    IP_ADDR_LEN);
16613 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16614 			    ntohl(dst)));
16615 
16616 			/*
16617 			 * Check if our address is present more than
16618 			 * once as consecutive hops in source route.
16619 			 */
16620 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16621 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16622 			if (tmp_ire != NULL) {
16623 				ire_refrele(tmp_ire);
16624 				off += IP_ADDR_LEN;
16625 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16626 				goto redo_srr;
16627 			}
16628 			ipha->ipha_dst = dst;
16629 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16630 			ire_refrele(dst_ire);
16631 			break;
16632 		case IPOPT_RR:
16633 			off = opt[IPOPT_OFFSET];
16634 			off--;
16635 			if (optlen < IP_ADDR_LEN ||
16636 			    off > optlen - IP_ADDR_LEN) {
16637 				/* No more room - ignore */
16638 				ip1dbg((
16639 				    "ip_rput_forward_options: end of RR\n"));
16640 				break;
16641 			}
16642 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16643 			    IP_ADDR_LEN);
16644 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16645 			break;
16646 		case IPOPT_TS:
16647 			/* Insert timestamp if there is room */
16648 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16649 			case IPOPT_TS_TSONLY:
16650 				off = IPOPT_TS_TIMELEN;
16651 				break;
16652 			case IPOPT_TS_PRESPEC:
16653 			case IPOPT_TS_PRESPEC_RFC791:
16654 				/* Verify that the address matched */
16655 				off = opt[IPOPT_OFFSET] - 1;
16656 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16657 				dst_ire = ire_ctable_lookup(dst, 0,
16658 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16659 				    MATCH_IRE_TYPE, ipst);
16660 				if (dst_ire == NULL) {
16661 					/* Not for us */
16662 					break;
16663 				}
16664 				ire_refrele(dst_ire);
16665 				/* FALLTHRU */
16666 			case IPOPT_TS_TSANDADDR:
16667 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16668 				break;
16669 			default:
16670 				/*
16671 				 * ip_*put_options should have already
16672 				 * dropped this packet.
16673 				 */
16674 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16675 				    "unknown IT - bug in ip_rput_options?\n");
16676 				return (0);	/* Keep "lint" happy */
16677 			}
16678 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16679 				/* Increase overflow counter */
16680 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16681 				opt[IPOPT_POS_OV_FLG] =
16682 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16683 				    (off << 4));
16684 				break;
16685 			}
16686 			off = opt[IPOPT_OFFSET] - 1;
16687 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16688 			case IPOPT_TS_PRESPEC:
16689 			case IPOPT_TS_PRESPEC_RFC791:
16690 			case IPOPT_TS_TSANDADDR:
16691 				bcopy(&ire->ire_src_addr,
16692 				    (char *)opt + off, IP_ADDR_LEN);
16693 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16694 				/* FALLTHRU */
16695 			case IPOPT_TS_TSONLY:
16696 				off = opt[IPOPT_OFFSET] - 1;
16697 				/* Compute # of milliseconds since midnight */
16698 				gethrestime(&now);
16699 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16700 				    now.tv_nsec / (NANOSEC / MILLISEC);
16701 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16702 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16703 				break;
16704 			}
16705 			break;
16706 		}
16707 	}
16708 	return (0);
16709 }
16710 
16711 /*
16712  * This is called after processing at least one of AH/ESP headers.
16713  *
16714  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16715  * the actual, physical interface on which the packet was received,
16716  * but, when ip_strict_dst_multihoming is set to 1, could be the
16717  * interface which had the ipha_dst configured when the packet went
16718  * through ip_rput. The ill_index corresponding to the recv_ill
16719  * is saved in ipsec_in_rill_index
16720  *
16721  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16722  * cannot assume "ire" points to valid data for any IPv6 cases.
16723  */
16724 void
16725 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16726 {
16727 	mblk_t *mp;
16728 	ipaddr_t dst;
16729 	in6_addr_t *v6dstp;
16730 	ipha_t *ipha;
16731 	ip6_t *ip6h;
16732 	ipsec_in_t *ii;
16733 	boolean_t ill_need_rele = B_FALSE;
16734 	boolean_t rill_need_rele = B_FALSE;
16735 	boolean_t ire_need_rele = B_FALSE;
16736 	netstack_t	*ns;
16737 	ip_stack_t	*ipst;
16738 
16739 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16740 	ASSERT(ii->ipsec_in_ill_index != 0);
16741 	ns = ii->ipsec_in_ns;
16742 	ASSERT(ii->ipsec_in_ns != NULL);
16743 	ipst = ns->netstack_ip;
16744 
16745 	mp = ipsec_mp->b_cont;
16746 	ASSERT(mp != NULL);
16747 
16748 
16749 	if (ill == NULL) {
16750 		ASSERT(recv_ill == NULL);
16751 		/*
16752 		 * We need to get the original queue on which ip_rput_local
16753 		 * or ip_rput_data_v6 was called.
16754 		 */
16755 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16756 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16757 		ill_need_rele = B_TRUE;
16758 
16759 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16760 			recv_ill = ill_lookup_on_ifindex(
16761 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16762 			    NULL, NULL, NULL, NULL, ipst);
16763 			rill_need_rele = B_TRUE;
16764 		} else {
16765 			recv_ill = ill;
16766 		}
16767 
16768 		if ((ill == NULL) || (recv_ill == NULL)) {
16769 			ip0dbg(("ip_fanout_proto_again: interface "
16770 			    "disappeared\n"));
16771 			if (ill != NULL)
16772 				ill_refrele(ill);
16773 			if (recv_ill != NULL)
16774 				ill_refrele(recv_ill);
16775 			freemsg(ipsec_mp);
16776 			return;
16777 		}
16778 	}
16779 
16780 	ASSERT(ill != NULL && recv_ill != NULL);
16781 
16782 	if (mp->b_datap->db_type == M_CTL) {
16783 		/*
16784 		 * AH/ESP is returning the ICMP message after
16785 		 * removing their headers. Fanout again till
16786 		 * it gets to the right protocol.
16787 		 */
16788 		if (ii->ipsec_in_v4) {
16789 			icmph_t *icmph;
16790 			int iph_hdr_length;
16791 			int hdr_length;
16792 
16793 			ipha = (ipha_t *)mp->b_rptr;
16794 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16795 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16796 			ipha = (ipha_t *)&icmph[1];
16797 			hdr_length = IPH_HDR_LENGTH(ipha);
16798 			/*
16799 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16800 			 * Reset the type to M_DATA.
16801 			 */
16802 			mp->b_datap->db_type = M_DATA;
16803 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16804 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16805 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16806 		} else {
16807 			icmp6_t *icmp6;
16808 			int hdr_length;
16809 
16810 			ip6h = (ip6_t *)mp->b_rptr;
16811 			/* Don't call hdr_length_v6() unless you have to. */
16812 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16813 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16814 			else
16815 				hdr_length = IPV6_HDR_LEN;
16816 
16817 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16818 			/*
16819 			 * icmp_inbound_error_fanout_v6 may need to do
16820 			 * pullupmsg.  Reset the type to M_DATA.
16821 			 */
16822 			mp->b_datap->db_type = M_DATA;
16823 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16824 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16825 		}
16826 		if (ill_need_rele)
16827 			ill_refrele(ill);
16828 		if (rill_need_rele)
16829 			ill_refrele(recv_ill);
16830 		return;
16831 	}
16832 
16833 	if (ii->ipsec_in_v4) {
16834 		ipha = (ipha_t *)mp->b_rptr;
16835 		dst = ipha->ipha_dst;
16836 		if (CLASSD(dst)) {
16837 			/*
16838 			 * Multicast has to be delivered to all streams.
16839 			 */
16840 			dst = INADDR_BROADCAST;
16841 		}
16842 
16843 		if (ire == NULL) {
16844 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16845 			    MBLK_GETLABEL(mp), ipst);
16846 			if (ire == NULL) {
16847 				if (ill_need_rele)
16848 					ill_refrele(ill);
16849 				if (rill_need_rele)
16850 					ill_refrele(recv_ill);
16851 				ip1dbg(("ip_fanout_proto_again: "
16852 				    "IRE not found"));
16853 				freemsg(ipsec_mp);
16854 				return;
16855 			}
16856 			ire_need_rele = B_TRUE;
16857 		}
16858 
16859 		switch (ipha->ipha_protocol) {
16860 			case IPPROTO_UDP:
16861 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16862 				    recv_ill);
16863 				if (ire_need_rele)
16864 					ire_refrele(ire);
16865 				break;
16866 			case IPPROTO_TCP:
16867 				if (!ire_need_rele)
16868 					IRE_REFHOLD(ire);
16869 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16870 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16871 				IRE_REFRELE(ire);
16872 				if (mp != NULL)
16873 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16874 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16875 				break;
16876 			case IPPROTO_SCTP:
16877 				if (!ire_need_rele)
16878 					IRE_REFHOLD(ire);
16879 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16880 				    ipsec_mp, 0, ill->ill_rq, dst);
16881 				break;
16882 			default:
16883 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16884 				    recv_ill, B_FALSE);
16885 				if (ire_need_rele)
16886 					ire_refrele(ire);
16887 				break;
16888 		}
16889 	} else {
16890 		uint32_t rput_flags = 0;
16891 
16892 		ip6h = (ip6_t *)mp->b_rptr;
16893 		v6dstp = &ip6h->ip6_dst;
16894 		/*
16895 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16896 		 * address.
16897 		 *
16898 		 * Currently, we don't store that state in the IPSEC_IN
16899 		 * message, and we may need to.
16900 		 */
16901 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16902 		    IP6_IN_LLMCAST : 0);
16903 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16904 		    NULL, NULL);
16905 	}
16906 	if (ill_need_rele)
16907 		ill_refrele(ill);
16908 	if (rill_need_rele)
16909 		ill_refrele(recv_ill);
16910 }
16911 
16912 /*
16913  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16914  * returns 'true' if there are still fragments left on the queue, in
16915  * which case we restart the timer.
16916  */
16917 void
16918 ill_frag_timer(void *arg)
16919 {
16920 	ill_t	*ill = (ill_t *)arg;
16921 	boolean_t frag_pending;
16922 	ip_stack_t	*ipst = ill->ill_ipst;
16923 
16924 	mutex_enter(&ill->ill_lock);
16925 	ASSERT(!ill->ill_fragtimer_executing);
16926 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16927 		ill->ill_frag_timer_id = 0;
16928 		mutex_exit(&ill->ill_lock);
16929 		return;
16930 	}
16931 	ill->ill_fragtimer_executing = 1;
16932 	mutex_exit(&ill->ill_lock);
16933 
16934 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16935 
16936 	/*
16937 	 * Restart the timer, if we have fragments pending or if someone
16938 	 * wanted us to be scheduled again.
16939 	 */
16940 	mutex_enter(&ill->ill_lock);
16941 	ill->ill_fragtimer_executing = 0;
16942 	ill->ill_frag_timer_id = 0;
16943 	if (frag_pending || ill->ill_fragtimer_needrestart)
16944 		ill_frag_timer_start(ill);
16945 	mutex_exit(&ill->ill_lock);
16946 }
16947 
16948 void
16949 ill_frag_timer_start(ill_t *ill)
16950 {
16951 	ip_stack_t	*ipst = ill->ill_ipst;
16952 
16953 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16954 
16955 	/* If the ill is closing or opening don't proceed */
16956 	if (ill->ill_state_flags & ILL_CONDEMNED)
16957 		return;
16958 
16959 	if (ill->ill_fragtimer_executing) {
16960 		/*
16961 		 * ill_frag_timer is currently executing. Just record the
16962 		 * the fact that we want the timer to be restarted.
16963 		 * ill_frag_timer will post a timeout before it returns,
16964 		 * ensuring it will be called again.
16965 		 */
16966 		ill->ill_fragtimer_needrestart = 1;
16967 		return;
16968 	}
16969 
16970 	if (ill->ill_frag_timer_id == 0) {
16971 		/*
16972 		 * The timer is neither running nor is the timeout handler
16973 		 * executing. Post a timeout so that ill_frag_timer will be
16974 		 * called
16975 		 */
16976 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16977 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
16978 		ill->ill_fragtimer_needrestart = 0;
16979 	}
16980 }
16981 
16982 /*
16983  * This routine is needed for loopback when forwarding multicasts.
16984  *
16985  * IPQoS Notes:
16986  * IPPF processing is done in fanout routines.
16987  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16988  * processing for IPsec packets is done when it comes back in clear.
16989  * NOTE : The callers of this function need to do the ire_refrele for the
16990  *	  ire that is being passed in.
16991  */
16992 void
16993 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16994     ill_t *recv_ill, boolean_t esp_in_udp_packet)
16995 {
16996 	ill_t	*ill = (ill_t *)q->q_ptr;
16997 	uint32_t	sum;
16998 	uint32_t	u1;
16999 	uint32_t	u2;
17000 	int		hdr_length;
17001 	boolean_t	mctl_present;
17002 	mblk_t		*first_mp = mp;
17003 	mblk_t		*hada_mp = NULL;
17004 	ipha_t		*inner_ipha;
17005 	ip_stack_t	*ipst;
17006 
17007 	ASSERT(recv_ill != NULL);
17008 	ipst = recv_ill->ill_ipst;
17009 
17010 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17011 	    "ip_rput_locl_start: q %p", q);
17012 
17013 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17014 	ASSERT(ill != NULL);
17015 
17016 
17017 #define	rptr	((uchar_t *)ipha)
17018 #define	iphs	((uint16_t *)ipha)
17019 
17020 	/*
17021 	 * no UDP or TCP packet should come here anymore.
17022 	 */
17023 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17024 	    ipha->ipha_protocol != IPPROTO_UDP);
17025 
17026 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17027 	if (mctl_present &&
17028 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17029 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17030 
17031 		/*
17032 		 * It's an IPsec accelerated packet.
17033 		 * Keep a pointer to the data attributes around until
17034 		 * we allocate the ipsec_info_t.
17035 		 */
17036 		IPSECHW_DEBUG(IPSECHW_PKT,
17037 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17038 		hada_mp = first_mp;
17039 		hada_mp->b_cont = NULL;
17040 		/*
17041 		 * Since it is accelerated, it comes directly from
17042 		 * the ill and the data attributes is followed by
17043 		 * the packet data.
17044 		 */
17045 		ASSERT(mp->b_datap->db_type != M_CTL);
17046 		first_mp = mp;
17047 		mctl_present = B_FALSE;
17048 	}
17049 
17050 	/*
17051 	 * IF M_CTL is not present, then ipsec_in_is_secure
17052 	 * should return B_TRUE. There is a case where loopback
17053 	 * packets has an M_CTL in the front with all the
17054 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17055 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17056 	 * packets never comes here, it is safe to ASSERT the
17057 	 * following.
17058 	 */
17059 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17060 
17061 	/*
17062 	 * Also, we should never have an mctl_present if this is an
17063 	 * ESP-in-UDP packet.
17064 	 */
17065 	ASSERT(!mctl_present || !esp_in_udp_packet);
17066 
17067 
17068 	/* u1 is # words of IP options */
17069 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17070 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17071 
17072 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17073 		if (u1) {
17074 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17075 				if (hada_mp != NULL)
17076 					freemsg(hada_mp);
17077 				return;
17078 			}
17079 		} else {
17080 			/* Check the IP header checksum.  */
17081 #define	uph	((uint16_t *)ipha)
17082 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17083 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17084 #undef  uph
17085 			/* finish doing IP checksum */
17086 			sum = (sum & 0xFFFF) + (sum >> 16);
17087 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17088 			if (sum && sum != 0xFFFF) {
17089 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17090 				goto drop_pkt;
17091 			}
17092 		}
17093 	}
17094 
17095 	/*
17096 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17097 	 * might be called more than once for secure packets, count only
17098 	 * the first time.
17099 	 */
17100 	if (!mctl_present) {
17101 		UPDATE_IB_PKT_COUNT(ire);
17102 		ire->ire_last_used_time = lbolt;
17103 	}
17104 
17105 	/* Check for fragmentation offset. */
17106 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17107 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17108 	if (u1) {
17109 		/*
17110 		 * We re-assemble fragments before we do the AH/ESP
17111 		 * processing. Thus, M_CTL should not be present
17112 		 * while we are re-assembling.
17113 		 */
17114 		ASSERT(!mctl_present);
17115 		ASSERT(first_mp == mp);
17116 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17117 			return;
17118 		}
17119 		/*
17120 		 * Make sure that first_mp points back to mp as
17121 		 * the mp we came in with could have changed in
17122 		 * ip_rput_fragment().
17123 		 */
17124 		ipha = (ipha_t *)mp->b_rptr;
17125 		first_mp = mp;
17126 	}
17127 
17128 	/*
17129 	 * Clear hardware checksumming flag as it is currently only
17130 	 * used by TCP and UDP.
17131 	 */
17132 	DB_CKSUMFLAGS(mp) = 0;
17133 
17134 	/* Now we have a complete datagram, destined for this machine. */
17135 	u1 = IPH_HDR_LENGTH(ipha);
17136 	switch (ipha->ipha_protocol) {
17137 	case IPPROTO_ICMP: {
17138 		ire_t		*ire_zone;
17139 		ilm_t		*ilm;
17140 		mblk_t		*mp1;
17141 		zoneid_t	last_zoneid;
17142 
17143 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17144 			ASSERT(ire->ire_type == IRE_BROADCAST);
17145 			/*
17146 			 * In the multicast case, applications may have joined
17147 			 * the group from different zones, so we need to deliver
17148 			 * the packet to each of them. Loop through the
17149 			 * multicast memberships structures (ilm) on the receive
17150 			 * ill and send a copy of the packet up each matching
17151 			 * one. However, we don't do this for multicasts sent on
17152 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17153 			 * they must stay in the sender's zone.
17154 			 *
17155 			 * ilm_add_v6() ensures that ilms in the same zone are
17156 			 * contiguous in the ill_ilm list. We use this property
17157 			 * to avoid sending duplicates needed when two
17158 			 * applications in the same zone join the same group on
17159 			 * different logical interfaces: we ignore the ilm if
17160 			 * its zoneid is the same as the last matching one.
17161 			 * In addition, the sending of the packet for
17162 			 * ire_zoneid is delayed until all of the other ilms
17163 			 * have been exhausted.
17164 			 */
17165 			last_zoneid = -1;
17166 			ILM_WALKER_HOLD(recv_ill);
17167 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17168 			    ilm = ilm->ilm_next) {
17169 				if ((ilm->ilm_flags & ILM_DELETED) ||
17170 				    ipha->ipha_dst != ilm->ilm_addr ||
17171 				    ilm->ilm_zoneid == last_zoneid ||
17172 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17173 				    ilm->ilm_zoneid == ALL_ZONES ||
17174 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17175 					continue;
17176 				mp1 = ip_copymsg(first_mp);
17177 				if (mp1 == NULL)
17178 					continue;
17179 				icmp_inbound(q, mp1, B_TRUE, ill,
17180 				    0, sum, mctl_present, B_TRUE,
17181 				    recv_ill, ilm->ilm_zoneid);
17182 				last_zoneid = ilm->ilm_zoneid;
17183 			}
17184 			ILM_WALKER_RELE(recv_ill);
17185 		} else if (ire->ire_type == IRE_BROADCAST) {
17186 			/*
17187 			 * In the broadcast case, there may be many zones
17188 			 * which need a copy of the packet delivered to them.
17189 			 * There is one IRE_BROADCAST per broadcast address
17190 			 * and per zone; we walk those using a helper function.
17191 			 * In addition, the sending of the packet for ire is
17192 			 * delayed until all of the other ires have been
17193 			 * processed.
17194 			 */
17195 			IRB_REFHOLD(ire->ire_bucket);
17196 			ire_zone = NULL;
17197 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17198 			    ire)) != NULL) {
17199 				mp1 = ip_copymsg(first_mp);
17200 				if (mp1 == NULL)
17201 					continue;
17202 
17203 				UPDATE_IB_PKT_COUNT(ire_zone);
17204 				ire_zone->ire_last_used_time = lbolt;
17205 				icmp_inbound(q, mp1, B_TRUE, ill,
17206 				    0, sum, mctl_present, B_TRUE,
17207 				    recv_ill, ire_zone->ire_zoneid);
17208 			}
17209 			IRB_REFRELE(ire->ire_bucket);
17210 		}
17211 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17212 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17213 		    ire->ire_zoneid);
17214 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17215 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17216 		return;
17217 	}
17218 	case IPPROTO_IGMP:
17219 		/*
17220 		 * If we are not willing to accept IGMP packets in clear,
17221 		 * then check with global policy.
17222 		 */
17223 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17224 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17225 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17226 			if (first_mp == NULL)
17227 				return;
17228 		}
17229 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17230 			freemsg(first_mp);
17231 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17232 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17233 			return;
17234 		}
17235 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17236 			/* Bad packet - discarded by igmp_input */
17237 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17238 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17239 			if (mctl_present)
17240 				freeb(first_mp);
17241 			return;
17242 		}
17243 		/*
17244 		 * igmp_input() may have returned the pulled up message.
17245 		 * So first_mp and ipha need to be reinitialized.
17246 		 */
17247 		ipha = (ipha_t *)mp->b_rptr;
17248 		if (mctl_present)
17249 			first_mp->b_cont = mp;
17250 		else
17251 			first_mp = mp;
17252 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17253 		    connf_head != NULL) {
17254 			/* No user-level listener for IGMP packets */
17255 			goto drop_pkt;
17256 		}
17257 		/* deliver to local raw users */
17258 		break;
17259 	case IPPROTO_PIM:
17260 		/*
17261 		 * If we are not willing to accept PIM packets in clear,
17262 		 * then check with global policy.
17263 		 */
17264 		if (ipst->ips_pim_accept_clear_messages == 0) {
17265 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17266 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17267 			if (first_mp == NULL)
17268 				return;
17269 		}
17270 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17271 			freemsg(first_mp);
17272 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17273 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17274 			return;
17275 		}
17276 		if (pim_input(q, mp, ill) != 0) {
17277 			/* Bad packet - discarded by pim_input */
17278 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17279 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17280 			if (mctl_present)
17281 				freeb(first_mp);
17282 			return;
17283 		}
17284 
17285 		/*
17286 		 * pim_input() may have pulled up the message so ipha needs to
17287 		 * be reinitialized.
17288 		 */
17289 		ipha = (ipha_t *)mp->b_rptr;
17290 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17291 		    connf_head != NULL) {
17292 			/* No user-level listener for PIM packets */
17293 			goto drop_pkt;
17294 		}
17295 		/* deliver to local raw users */
17296 		break;
17297 	case IPPROTO_ENCAP:
17298 		/*
17299 		 * Handle self-encapsulated packets (IP-in-IP where
17300 		 * the inner addresses == the outer addresses).
17301 		 */
17302 		hdr_length = IPH_HDR_LENGTH(ipha);
17303 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17304 		    mp->b_wptr) {
17305 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17306 			    sizeof (ipha_t) - mp->b_rptr)) {
17307 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17308 				freemsg(first_mp);
17309 				return;
17310 			}
17311 			ipha = (ipha_t *)mp->b_rptr;
17312 		}
17313 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17314 		/*
17315 		 * Check the sanity of the inner IP header.
17316 		 */
17317 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17318 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17319 			freemsg(first_mp);
17320 			return;
17321 		}
17322 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17323 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17324 			freemsg(first_mp);
17325 			return;
17326 		}
17327 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17328 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17329 			ipsec_in_t *ii;
17330 
17331 			/*
17332 			 * Self-encapsulated tunnel packet. Remove
17333 			 * the outer IP header and fanout again.
17334 			 * We also need to make sure that the inner
17335 			 * header is pulled up until options.
17336 			 */
17337 			mp->b_rptr = (uchar_t *)inner_ipha;
17338 			ipha = inner_ipha;
17339 			hdr_length = IPH_HDR_LENGTH(ipha);
17340 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17341 				if (!pullupmsg(mp, (uchar_t *)ipha +
17342 				    + hdr_length - mp->b_rptr)) {
17343 					freemsg(first_mp);
17344 					return;
17345 				}
17346 				ipha = (ipha_t *)mp->b_rptr;
17347 			}
17348 			if (!mctl_present) {
17349 				ASSERT(first_mp == mp);
17350 				/*
17351 				 * This means that somebody is sending
17352 				 * Self-encapsualted packets without AH/ESP.
17353 				 * If AH/ESP was present, we would have already
17354 				 * allocated the first_mp.
17355 				 */
17356 				first_mp = ipsec_in_alloc(B_TRUE,
17357 				    ipst->ips_netstack);
17358 				if (first_mp == NULL) {
17359 					ip1dbg(("ip_proto_input: IPSEC_IN "
17360 					    "allocation failure.\n"));
17361 					BUMP_MIB(ill->ill_ip_mib,
17362 					    ipIfStatsInDiscards);
17363 					freemsg(mp);
17364 					return;
17365 				}
17366 				first_mp->b_cont = mp;
17367 			}
17368 			/*
17369 			 * We generally store the ill_index if we need to
17370 			 * do IPsec processing as we lose the ill queue when
17371 			 * we come back. But in this case, we never should
17372 			 * have to store the ill_index here as it should have
17373 			 * been stored previously when we processed the
17374 			 * AH/ESP header in this routine or for non-ipsec
17375 			 * cases, we still have the queue. But for some bad
17376 			 * packets from the wire, we can get to IPsec after
17377 			 * this and we better store the index for that case.
17378 			 */
17379 			ill = (ill_t *)q->q_ptr;
17380 			ii = (ipsec_in_t *)first_mp->b_rptr;
17381 			ii->ipsec_in_ill_index =
17382 			    ill->ill_phyint->phyint_ifindex;
17383 			ii->ipsec_in_rill_index =
17384 			    recv_ill->ill_phyint->phyint_ifindex;
17385 			if (ii->ipsec_in_decaps) {
17386 				/*
17387 				 * This packet is self-encapsulated multiple
17388 				 * times. We don't want to recurse infinitely.
17389 				 * To keep it simple, drop the packet.
17390 				 */
17391 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17392 				freemsg(first_mp);
17393 				return;
17394 			}
17395 			ii->ipsec_in_decaps = B_TRUE;
17396 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17397 			    ire);
17398 			return;
17399 		}
17400 		break;
17401 	case IPPROTO_AH:
17402 	case IPPROTO_ESP: {
17403 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17404 
17405 		/*
17406 		 * Fast path for AH/ESP. If this is the first time
17407 		 * we are sending a datagram to AH/ESP, allocate
17408 		 * a IPSEC_IN message and prepend it. Otherwise,
17409 		 * just fanout.
17410 		 */
17411 
17412 		int ipsec_rc;
17413 		ipsec_in_t *ii;
17414 		netstack_t *ns = ipst->ips_netstack;
17415 
17416 		IP_STAT(ipst, ipsec_proto_ahesp);
17417 		if (!mctl_present) {
17418 			ASSERT(first_mp == mp);
17419 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17420 			if (first_mp == NULL) {
17421 				ip1dbg(("ip_proto_input: IPSEC_IN "
17422 				    "allocation failure.\n"));
17423 				freemsg(hada_mp); /* okay ifnull */
17424 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17425 				freemsg(mp);
17426 				return;
17427 			}
17428 			/*
17429 			 * Store the ill_index so that when we come back
17430 			 * from IPsec we ride on the same queue.
17431 			 */
17432 			ill = (ill_t *)q->q_ptr;
17433 			ii = (ipsec_in_t *)first_mp->b_rptr;
17434 			ii->ipsec_in_ill_index =
17435 			    ill->ill_phyint->phyint_ifindex;
17436 			ii->ipsec_in_rill_index =
17437 			    recv_ill->ill_phyint->phyint_ifindex;
17438 			first_mp->b_cont = mp;
17439 			/*
17440 			 * Cache hardware acceleration info.
17441 			 */
17442 			if (hada_mp != NULL) {
17443 				IPSECHW_DEBUG(IPSECHW_PKT,
17444 				    ("ip_rput_local: caching data attr.\n"));
17445 				ii->ipsec_in_accelerated = B_TRUE;
17446 				ii->ipsec_in_da = hada_mp;
17447 				hada_mp = NULL;
17448 			}
17449 		} else {
17450 			ii = (ipsec_in_t *)first_mp->b_rptr;
17451 		}
17452 
17453 		if (!ipsec_loaded(ipss)) {
17454 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17455 			    ire->ire_zoneid, ipst);
17456 			return;
17457 		}
17458 
17459 		ns = ipst->ips_netstack;
17460 		/* select inbound SA and have IPsec process the pkt */
17461 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17462 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17463 			boolean_t esp_in_udp_sa;
17464 			if (esph == NULL)
17465 				return;
17466 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17467 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17468 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17469 			    IPSA_F_NATT) != 0);
17470 			/*
17471 			 * The following is a fancy, but quick, way of saying:
17472 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17473 			 *    OR
17474 			 * ESP SA and ESP-in-UDP packet --> drop
17475 			 */
17476 			if (esp_in_udp_sa != esp_in_udp_packet) {
17477 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17478 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17479 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17480 				    &ns->netstack_ipsec->ipsec_dropper);
17481 				return;
17482 			}
17483 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17484 			    first_mp, esph);
17485 		} else {
17486 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17487 			if (ah == NULL)
17488 				return;
17489 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17490 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17491 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17492 			    first_mp, ah);
17493 		}
17494 
17495 		switch (ipsec_rc) {
17496 		case IPSEC_STATUS_SUCCESS:
17497 			break;
17498 		case IPSEC_STATUS_FAILED:
17499 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17500 			/* FALLTHRU */
17501 		case IPSEC_STATUS_PENDING:
17502 			return;
17503 		}
17504 		/* we're done with IPsec processing, send it up */
17505 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17506 		return;
17507 	}
17508 	default:
17509 		break;
17510 	}
17511 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17512 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17513 		    ire->ire_zoneid));
17514 		goto drop_pkt;
17515 	}
17516 	/*
17517 	 * Handle protocols with which IP is less intimate.  There
17518 	 * can be more than one stream bound to a particular
17519 	 * protocol.  When this is the case, each one gets a copy
17520 	 * of any incoming packets.
17521 	 */
17522 	ip_fanout_proto(q, first_mp, ill, ipha,
17523 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17524 	    B_TRUE, recv_ill, ire->ire_zoneid);
17525 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17526 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17527 	return;
17528 
17529 drop_pkt:
17530 	freemsg(first_mp);
17531 	if (hada_mp != NULL)
17532 		freeb(hada_mp);
17533 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17534 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17535 #undef	rptr
17536 #undef  iphs
17537 
17538 }
17539 
17540 /*
17541  * Update any source route, record route or timestamp options.
17542  * Check that we are at end of strict source route.
17543  * The options have already been checked for sanity in ip_rput_options().
17544  */
17545 static boolean_t
17546 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17547     ip_stack_t *ipst)
17548 {
17549 	ipoptp_t	opts;
17550 	uchar_t		*opt;
17551 	uint8_t		optval;
17552 	uint8_t		optlen;
17553 	ipaddr_t	dst;
17554 	uint32_t	ts;
17555 	ire_t		*dst_ire;
17556 	timestruc_t	now;
17557 	zoneid_t	zoneid;
17558 	ill_t		*ill;
17559 
17560 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17561 
17562 	ip2dbg(("ip_rput_local_options\n"));
17563 
17564 	for (optval = ipoptp_first(&opts, ipha);
17565 	    optval != IPOPT_EOL;
17566 	    optval = ipoptp_next(&opts)) {
17567 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17568 		opt = opts.ipoptp_cur;
17569 		optlen = opts.ipoptp_len;
17570 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17571 		    optval, optlen));
17572 		switch (optval) {
17573 			uint32_t off;
17574 		case IPOPT_SSRR:
17575 		case IPOPT_LSRR:
17576 			off = opt[IPOPT_OFFSET];
17577 			off--;
17578 			if (optlen < IP_ADDR_LEN ||
17579 			    off > optlen - IP_ADDR_LEN) {
17580 				/* End of source route */
17581 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17582 				break;
17583 			}
17584 			/*
17585 			 * This will only happen if two consecutive entries
17586 			 * in the source route contains our address or if
17587 			 * it is a packet with a loose source route which
17588 			 * reaches us before consuming the whole source route
17589 			 */
17590 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17591 			if (optval == IPOPT_SSRR) {
17592 				goto bad_src_route;
17593 			}
17594 			/*
17595 			 * Hack: instead of dropping the packet truncate the
17596 			 * source route to what has been used by filling the
17597 			 * rest with IPOPT_NOP.
17598 			 */
17599 			opt[IPOPT_OLEN] = (uint8_t)off;
17600 			while (off < optlen) {
17601 				opt[off++] = IPOPT_NOP;
17602 			}
17603 			break;
17604 		case IPOPT_RR:
17605 			off = opt[IPOPT_OFFSET];
17606 			off--;
17607 			if (optlen < IP_ADDR_LEN ||
17608 			    off > optlen - IP_ADDR_LEN) {
17609 				/* No more room - ignore */
17610 				ip1dbg((
17611 				    "ip_rput_local_options: end of RR\n"));
17612 				break;
17613 			}
17614 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17615 			    IP_ADDR_LEN);
17616 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17617 			break;
17618 		case IPOPT_TS:
17619 			/* Insert timestamp if there is romm */
17620 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17621 			case IPOPT_TS_TSONLY:
17622 				off = IPOPT_TS_TIMELEN;
17623 				break;
17624 			case IPOPT_TS_PRESPEC:
17625 			case IPOPT_TS_PRESPEC_RFC791:
17626 				/* Verify that the address matched */
17627 				off = opt[IPOPT_OFFSET] - 1;
17628 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17629 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17630 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17631 				    ipst);
17632 				if (dst_ire == NULL) {
17633 					/* Not for us */
17634 					break;
17635 				}
17636 				ire_refrele(dst_ire);
17637 				/* FALLTHRU */
17638 			case IPOPT_TS_TSANDADDR:
17639 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17640 				break;
17641 			default:
17642 				/*
17643 				 * ip_*put_options should have already
17644 				 * dropped this packet.
17645 				 */
17646 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17647 				    "unknown IT - bug in ip_rput_options?\n");
17648 				return (B_TRUE);	/* Keep "lint" happy */
17649 			}
17650 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17651 				/* Increase overflow counter */
17652 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17653 				opt[IPOPT_POS_OV_FLG] =
17654 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17655 				    (off << 4));
17656 				break;
17657 			}
17658 			off = opt[IPOPT_OFFSET] - 1;
17659 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17660 			case IPOPT_TS_PRESPEC:
17661 			case IPOPT_TS_PRESPEC_RFC791:
17662 			case IPOPT_TS_TSANDADDR:
17663 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17664 				    IP_ADDR_LEN);
17665 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17666 				/* FALLTHRU */
17667 			case IPOPT_TS_TSONLY:
17668 				off = opt[IPOPT_OFFSET] - 1;
17669 				/* Compute # of milliseconds since midnight */
17670 				gethrestime(&now);
17671 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17672 				    now.tv_nsec / (NANOSEC / MILLISEC);
17673 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17674 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17675 				break;
17676 			}
17677 			break;
17678 		}
17679 	}
17680 	return (B_TRUE);
17681 
17682 bad_src_route:
17683 	q = WR(q);
17684 	if (q->q_next != NULL)
17685 		ill = q->q_ptr;
17686 	else
17687 		ill = NULL;
17688 
17689 	/* make sure we clear any indication of a hardware checksum */
17690 	DB_CKSUMFLAGS(mp) = 0;
17691 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17692 	if (zoneid == ALL_ZONES)
17693 		freemsg(mp);
17694 	else
17695 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17696 	return (B_FALSE);
17697 
17698 }
17699 
17700 /*
17701  * Process IP options in an inbound packet.  If an option affects the
17702  * effective destination address, return the next hop address via dstp.
17703  * Returns -1 if something fails in which case an ICMP error has been sent
17704  * and mp freed.
17705  */
17706 static int
17707 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17708     ip_stack_t *ipst)
17709 {
17710 	ipoptp_t	opts;
17711 	uchar_t		*opt;
17712 	uint8_t		optval;
17713 	uint8_t		optlen;
17714 	ipaddr_t	dst;
17715 	intptr_t	code = 0;
17716 	ire_t		*ire = NULL;
17717 	zoneid_t	zoneid;
17718 	ill_t		*ill;
17719 
17720 	ip2dbg(("ip_rput_options\n"));
17721 	dst = ipha->ipha_dst;
17722 	for (optval = ipoptp_first(&opts, ipha);
17723 	    optval != IPOPT_EOL;
17724 	    optval = ipoptp_next(&opts)) {
17725 		opt = opts.ipoptp_cur;
17726 		optlen = opts.ipoptp_len;
17727 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17728 		    optval, optlen));
17729 		/*
17730 		 * Note: we need to verify the checksum before we
17731 		 * modify anything thus this routine only extracts the next
17732 		 * hop dst from any source route.
17733 		 */
17734 		switch (optval) {
17735 			uint32_t off;
17736 		case IPOPT_SSRR:
17737 		case IPOPT_LSRR:
17738 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17739 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17740 			if (ire == NULL) {
17741 				if (optval == IPOPT_SSRR) {
17742 					ip1dbg(("ip_rput_options: not next"
17743 					    " strict source route 0x%x\n",
17744 					    ntohl(dst)));
17745 					code = (char *)&ipha->ipha_dst -
17746 					    (char *)ipha;
17747 					goto param_prob; /* RouterReq's */
17748 				}
17749 				ip2dbg(("ip_rput_options: "
17750 				    "not next source route 0x%x\n",
17751 				    ntohl(dst)));
17752 				break;
17753 			}
17754 			ire_refrele(ire);
17755 
17756 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17757 				ip1dbg((
17758 				    "ip_rput_options: bad option offset\n"));
17759 				code = (char *)&opt[IPOPT_OLEN] -
17760 				    (char *)ipha;
17761 				goto param_prob;
17762 			}
17763 			off = opt[IPOPT_OFFSET];
17764 			off--;
17765 		redo_srr:
17766 			if (optlen < IP_ADDR_LEN ||
17767 			    off > optlen - IP_ADDR_LEN) {
17768 				/* End of source route */
17769 				ip1dbg(("ip_rput_options: end of SR\n"));
17770 				break;
17771 			}
17772 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17773 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17774 			    ntohl(dst)));
17775 
17776 			/*
17777 			 * Check if our address is present more than
17778 			 * once as consecutive hops in source route.
17779 			 * XXX verify per-interface ip_forwarding
17780 			 * for source route?
17781 			 */
17782 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17783 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17784 
17785 			if (ire != NULL) {
17786 				ire_refrele(ire);
17787 				off += IP_ADDR_LEN;
17788 				goto redo_srr;
17789 			}
17790 
17791 			if (dst == htonl(INADDR_LOOPBACK)) {
17792 				ip1dbg(("ip_rput_options: loopback addr in "
17793 				    "source route!\n"));
17794 				goto bad_src_route;
17795 			}
17796 			/*
17797 			 * For strict: verify that dst is directly
17798 			 * reachable.
17799 			 */
17800 			if (optval == IPOPT_SSRR) {
17801 				ire = ire_ftable_lookup(dst, 0, 0,
17802 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17803 				    MBLK_GETLABEL(mp),
17804 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17805 				if (ire == NULL) {
17806 					ip1dbg(("ip_rput_options: SSRR not "
17807 					    "directly reachable: 0x%x\n",
17808 					    ntohl(dst)));
17809 					goto bad_src_route;
17810 				}
17811 				ire_refrele(ire);
17812 			}
17813 			/*
17814 			 * Defer update of the offset and the record route
17815 			 * until the packet is forwarded.
17816 			 */
17817 			break;
17818 		case IPOPT_RR:
17819 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17820 				ip1dbg((
17821 				    "ip_rput_options: bad option offset\n"));
17822 				code = (char *)&opt[IPOPT_OLEN] -
17823 				    (char *)ipha;
17824 				goto param_prob;
17825 			}
17826 			break;
17827 		case IPOPT_TS:
17828 			/*
17829 			 * Verify that length >= 5 and that there is either
17830 			 * room for another timestamp or that the overflow
17831 			 * counter is not maxed out.
17832 			 */
17833 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17834 			if (optlen < IPOPT_MINLEN_IT) {
17835 				goto param_prob;
17836 			}
17837 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17838 				ip1dbg((
17839 				    "ip_rput_options: bad option offset\n"));
17840 				code = (char *)&opt[IPOPT_OFFSET] -
17841 				    (char *)ipha;
17842 				goto param_prob;
17843 			}
17844 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17845 			case IPOPT_TS_TSONLY:
17846 				off = IPOPT_TS_TIMELEN;
17847 				break;
17848 			case IPOPT_TS_TSANDADDR:
17849 			case IPOPT_TS_PRESPEC:
17850 			case IPOPT_TS_PRESPEC_RFC791:
17851 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17852 				break;
17853 			default:
17854 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17855 				    (char *)ipha;
17856 				goto param_prob;
17857 			}
17858 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17859 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17860 				/*
17861 				 * No room and the overflow counter is 15
17862 				 * already.
17863 				 */
17864 				goto param_prob;
17865 			}
17866 			break;
17867 		}
17868 	}
17869 
17870 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17871 		*dstp = dst;
17872 		return (0);
17873 	}
17874 
17875 	ip1dbg(("ip_rput_options: error processing IP options."));
17876 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17877 
17878 param_prob:
17879 	q = WR(q);
17880 	if (q->q_next != NULL)
17881 		ill = q->q_ptr;
17882 	else
17883 		ill = NULL;
17884 
17885 	/* make sure we clear any indication of a hardware checksum */
17886 	DB_CKSUMFLAGS(mp) = 0;
17887 	/* Don't know whether this is for non-global or global/forwarding */
17888 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17889 	if (zoneid == ALL_ZONES)
17890 		freemsg(mp);
17891 	else
17892 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17893 	return (-1);
17894 
17895 bad_src_route:
17896 	q = WR(q);
17897 	if (q->q_next != NULL)
17898 		ill = q->q_ptr;
17899 	else
17900 		ill = NULL;
17901 
17902 	/* make sure we clear any indication of a hardware checksum */
17903 	DB_CKSUMFLAGS(mp) = 0;
17904 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17905 	if (zoneid == ALL_ZONES)
17906 		freemsg(mp);
17907 	else
17908 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17909 	return (-1);
17910 }
17911 
17912 /*
17913  * IP & ICMP info in >=14 msg's ...
17914  *  - ip fixed part (mib2_ip_t)
17915  *  - icmp fixed part (mib2_icmp_t)
17916  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17917  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17918  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17919  *  - ipRouteAttributeTable (ip 102)	labeled routes
17920  *  - ip multicast membership (ip_member_t)
17921  *  - ip multicast source filtering (ip_grpsrc_t)
17922  *  - igmp fixed part (struct igmpstat)
17923  *  - multicast routing stats (struct mrtstat)
17924  *  - multicast routing vifs (array of struct vifctl)
17925  *  - multicast routing routes (array of struct mfcctl)
17926  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17927  *					One per ill plus one generic
17928  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17929  *					One per ill plus one generic
17930  *  - ipv6RouteEntry			all IPv6 IREs
17931  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17932  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17933  *  - ipv6AddrEntry			all IPv6 ipifs
17934  *  - ipv6 multicast membership (ipv6_member_t)
17935  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17936  *
17937  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17938  *
17939  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17940  * already filled in by the caller.
17941  * Return value of 0 indicates that no messages were sent and caller
17942  * should free mpctl.
17943  */
17944 int
17945 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17946 {
17947 	ip_stack_t *ipst;
17948 	sctp_stack_t *sctps;
17949 
17950 
17951 	if (q->q_next != NULL) {
17952 		ipst = ILLQ_TO_IPST(q);
17953 	} else {
17954 		ipst = CONNQ_TO_IPST(q);
17955 	}
17956 	ASSERT(ipst != NULL);
17957 	sctps = ipst->ips_netstack->netstack_sctp;
17958 
17959 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17960 		return (0);
17961 	}
17962 
17963 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
17964 	    ipst)) == NULL) {
17965 		return (1);
17966 	}
17967 
17968 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
17969 		return (1);
17970 	}
17971 
17972 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
17973 		return (1);
17974 	}
17975 
17976 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
17977 		return (1);
17978 	}
17979 
17980 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
17981 		return (1);
17982 	}
17983 
17984 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
17985 		return (1);
17986 	}
17987 
17988 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
17989 		return (1);
17990 	}
17991 
17992 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
17993 		return (1);
17994 	}
17995 
17996 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
17997 		return (1);
17998 	}
17999 
18000 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18001 		return (1);
18002 	}
18003 
18004 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18005 		return (1);
18006 	}
18007 
18008 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18009 		return (1);
18010 	}
18011 
18012 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18013 		return (1);
18014 	}
18015 
18016 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18017 		return (1);
18018 	}
18019 
18020 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18021 		return (1);
18022 	}
18023 
18024 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18025 	if (mpctl == NULL) {
18026 		return (1);
18027 	}
18028 
18029 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18030 		return (1);
18031 	}
18032 	freemsg(mpctl);
18033 	return (1);
18034 }
18035 
18036 
18037 /* Get global (legacy) IPv4 statistics */
18038 static mblk_t *
18039 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18040     ip_stack_t *ipst)
18041 {
18042 	mib2_ip_t		old_ip_mib;
18043 	struct opthdr		*optp;
18044 	mblk_t			*mp2ctl;
18045 
18046 	/*
18047 	 * make a copy of the original message
18048 	 */
18049 	mp2ctl = copymsg(mpctl);
18050 
18051 	/* fixed length IP structure... */
18052 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18053 	optp->level = MIB2_IP;
18054 	optp->name = 0;
18055 	SET_MIB(old_ip_mib.ipForwarding,
18056 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18057 	SET_MIB(old_ip_mib.ipDefaultTTL,
18058 	    (uint32_t)ipst->ips_ip_def_ttl);
18059 	SET_MIB(old_ip_mib.ipReasmTimeout,
18060 	    ipst->ips_ip_g_frag_timeout);
18061 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18062 	    sizeof (mib2_ipAddrEntry_t));
18063 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18064 	    sizeof (mib2_ipRouteEntry_t));
18065 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18066 	    sizeof (mib2_ipNetToMediaEntry_t));
18067 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18068 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18069 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18070 	    sizeof (mib2_ipAttributeEntry_t));
18071 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18072 
18073 	/*
18074 	 * Grab the statistics from the new IP MIB
18075 	 */
18076 	SET_MIB(old_ip_mib.ipInReceives,
18077 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18078 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18079 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18080 	SET_MIB(old_ip_mib.ipForwDatagrams,
18081 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18082 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18083 	    ipmib->ipIfStatsInUnknownProtos);
18084 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18085 	SET_MIB(old_ip_mib.ipInDelivers,
18086 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18087 	SET_MIB(old_ip_mib.ipOutRequests,
18088 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18089 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18090 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18091 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18092 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18093 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18094 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18095 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18096 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18097 
18098 	/* ipRoutingDiscards is not being used */
18099 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18100 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18101 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18102 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18103 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18104 	    ipmib->ipIfStatsReasmDuplicates);
18105 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18106 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18107 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18108 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18109 	SET_MIB(old_ip_mib.rawipInOverflows,
18110 	    ipmib->rawipIfStatsInOverflows);
18111 
18112 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18113 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18114 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18115 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18116 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18117 	    ipmib->ipIfStatsOutSwitchIPVersion);
18118 
18119 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18120 	    (int)sizeof (old_ip_mib))) {
18121 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18122 		    (uint_t)sizeof (old_ip_mib)));
18123 	}
18124 
18125 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18126 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18127 	    (int)optp->level, (int)optp->name, (int)optp->len));
18128 	qreply(q, mpctl);
18129 	return (mp2ctl);
18130 }
18131 
18132 /* Per interface IPv4 statistics */
18133 static mblk_t *
18134 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18135 {
18136 	struct opthdr		*optp;
18137 	mblk_t			*mp2ctl;
18138 	ill_t			*ill;
18139 	ill_walk_context_t	ctx;
18140 	mblk_t			*mp_tail = NULL;
18141 	mib2_ipIfStatsEntry_t	global_ip_mib;
18142 
18143 	/*
18144 	 * Make a copy of the original message
18145 	 */
18146 	mp2ctl = copymsg(mpctl);
18147 
18148 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18149 	optp->level = MIB2_IP;
18150 	optp->name = MIB2_IP_TRAFFIC_STATS;
18151 	/* Include "unknown interface" ip_mib */
18152 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18153 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18154 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18155 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18156 	    (ipst->ips_ip_g_forward ? 1 : 2));
18157 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18158 	    (uint32_t)ipst->ips_ip_def_ttl);
18159 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18160 	    sizeof (mib2_ipIfStatsEntry_t));
18161 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18162 	    sizeof (mib2_ipAddrEntry_t));
18163 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18164 	    sizeof (mib2_ipRouteEntry_t));
18165 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18166 	    sizeof (mib2_ipNetToMediaEntry_t));
18167 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18168 	    sizeof (ip_member_t));
18169 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18170 	    sizeof (ip_grpsrc_t));
18171 
18172 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18173 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18174 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18175 		    "failed to allocate %u bytes\n",
18176 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18177 	}
18178 
18179 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18180 
18181 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18182 	ill = ILL_START_WALK_V4(&ctx, ipst);
18183 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18184 		ill->ill_ip_mib->ipIfStatsIfIndex =
18185 		    ill->ill_phyint->phyint_ifindex;
18186 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18187 		    (ipst->ips_ip_g_forward ? 1 : 2));
18188 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18189 		    (uint32_t)ipst->ips_ip_def_ttl);
18190 
18191 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18192 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18193 		    (char *)ill->ill_ip_mib,
18194 		    (int)sizeof (*ill->ill_ip_mib))) {
18195 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18196 			    "failed to allocate %u bytes\n",
18197 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18198 		}
18199 	}
18200 	rw_exit(&ipst->ips_ill_g_lock);
18201 
18202 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18203 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18204 	    "level %d, name %d, len %d\n",
18205 	    (int)optp->level, (int)optp->name, (int)optp->len));
18206 	qreply(q, mpctl);
18207 
18208 	if (mp2ctl == NULL)
18209 		return (NULL);
18210 
18211 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18212 }
18213 
18214 /* Global IPv4 ICMP statistics */
18215 static mblk_t *
18216 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18217 {
18218 	struct opthdr		*optp;
18219 	mblk_t			*mp2ctl;
18220 
18221 	/*
18222 	 * Make a copy of the original message
18223 	 */
18224 	mp2ctl = copymsg(mpctl);
18225 
18226 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18227 	optp->level = MIB2_ICMP;
18228 	optp->name = 0;
18229 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18230 	    (int)sizeof (ipst->ips_icmp_mib))) {
18231 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18232 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18233 	}
18234 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18235 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18236 	    (int)optp->level, (int)optp->name, (int)optp->len));
18237 	qreply(q, mpctl);
18238 	return (mp2ctl);
18239 }
18240 
18241 /* Global IPv4 IGMP statistics */
18242 static mblk_t *
18243 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18244 {
18245 	struct opthdr		*optp;
18246 	mblk_t			*mp2ctl;
18247 
18248 	/*
18249 	 * make a copy of the original message
18250 	 */
18251 	mp2ctl = copymsg(mpctl);
18252 
18253 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18254 	optp->level = EXPER_IGMP;
18255 	optp->name = 0;
18256 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18257 	    (int)sizeof (ipst->ips_igmpstat))) {
18258 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18259 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18260 	}
18261 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18262 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18263 	    (int)optp->level, (int)optp->name, (int)optp->len));
18264 	qreply(q, mpctl);
18265 	return (mp2ctl);
18266 }
18267 
18268 /* Global IPv4 Multicast Routing statistics */
18269 static mblk_t *
18270 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18271 {
18272 	struct opthdr		*optp;
18273 	mblk_t			*mp2ctl;
18274 
18275 	/*
18276 	 * make a copy of the original message
18277 	 */
18278 	mp2ctl = copymsg(mpctl);
18279 
18280 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18281 	optp->level = EXPER_DVMRP;
18282 	optp->name = 0;
18283 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18284 		ip0dbg(("ip_mroute_stats: failed\n"));
18285 	}
18286 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18287 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18288 	    (int)optp->level, (int)optp->name, (int)optp->len));
18289 	qreply(q, mpctl);
18290 	return (mp2ctl);
18291 }
18292 
18293 /* IPv4 address information */
18294 static mblk_t *
18295 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18296 {
18297 	struct opthdr		*optp;
18298 	mblk_t			*mp2ctl;
18299 	mblk_t			*mp_tail = NULL;
18300 	ill_t			*ill;
18301 	ipif_t			*ipif;
18302 	uint_t			bitval;
18303 	mib2_ipAddrEntry_t	mae;
18304 	zoneid_t		zoneid;
18305 	ill_walk_context_t ctx;
18306 
18307 	/*
18308 	 * make a copy of the original message
18309 	 */
18310 	mp2ctl = copymsg(mpctl);
18311 
18312 	/* ipAddrEntryTable */
18313 
18314 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18315 	optp->level = MIB2_IP;
18316 	optp->name = MIB2_IP_ADDR;
18317 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18318 
18319 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18320 	ill = ILL_START_WALK_V4(&ctx, ipst);
18321 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18322 		for (ipif = ill->ill_ipif; ipif != NULL;
18323 		    ipif = ipif->ipif_next) {
18324 			if (ipif->ipif_zoneid != zoneid &&
18325 			    ipif->ipif_zoneid != ALL_ZONES)
18326 				continue;
18327 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18328 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18329 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18330 
18331 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18332 			    OCTET_LENGTH);
18333 			mae.ipAdEntIfIndex.o_length =
18334 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18335 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18336 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18337 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18338 			mae.ipAdEntInfo.ae_subnet_len =
18339 			    ip_mask_to_plen(ipif->ipif_net_mask);
18340 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18341 			for (bitval = 1;
18342 			    bitval &&
18343 			    !(bitval & ipif->ipif_brd_addr);
18344 			    bitval <<= 1)
18345 				noop;
18346 			mae.ipAdEntBcastAddr = bitval;
18347 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18348 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18349 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18350 			mae.ipAdEntInfo.ae_broadcast_addr =
18351 			    ipif->ipif_brd_addr;
18352 			mae.ipAdEntInfo.ae_pp_dst_addr =
18353 			    ipif->ipif_pp_dst_addr;
18354 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18355 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18356 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18357 
18358 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18359 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18360 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18361 				    "allocate %u bytes\n",
18362 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18363 			}
18364 		}
18365 	}
18366 	rw_exit(&ipst->ips_ill_g_lock);
18367 
18368 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18369 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18370 	    (int)optp->level, (int)optp->name, (int)optp->len));
18371 	qreply(q, mpctl);
18372 	return (mp2ctl);
18373 }
18374 
18375 /* IPv6 address information */
18376 static mblk_t *
18377 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18378 {
18379 	struct opthdr		*optp;
18380 	mblk_t			*mp2ctl;
18381 	mblk_t			*mp_tail = NULL;
18382 	ill_t			*ill;
18383 	ipif_t			*ipif;
18384 	mib2_ipv6AddrEntry_t	mae6;
18385 	zoneid_t		zoneid;
18386 	ill_walk_context_t	ctx;
18387 
18388 	/*
18389 	 * make a copy of the original message
18390 	 */
18391 	mp2ctl = copymsg(mpctl);
18392 
18393 	/* ipv6AddrEntryTable */
18394 
18395 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18396 	optp->level = MIB2_IP6;
18397 	optp->name = MIB2_IP6_ADDR;
18398 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18399 
18400 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18401 	ill = ILL_START_WALK_V6(&ctx, ipst);
18402 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18403 		for (ipif = ill->ill_ipif; ipif != NULL;
18404 		    ipif = ipif->ipif_next) {
18405 			if (ipif->ipif_zoneid != zoneid &&
18406 			    ipif->ipif_zoneid != ALL_ZONES)
18407 				continue;
18408 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18409 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18410 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18411 
18412 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18413 			    OCTET_LENGTH);
18414 			mae6.ipv6AddrIfIndex.o_length =
18415 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18416 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18417 			mae6.ipv6AddrPfxLength =
18418 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18419 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18420 			mae6.ipv6AddrInfo.ae_subnet_len =
18421 			    mae6.ipv6AddrPfxLength;
18422 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18423 
18424 			/* Type: stateless(1), stateful(2), unknown(3) */
18425 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18426 				mae6.ipv6AddrType = 1;
18427 			else
18428 				mae6.ipv6AddrType = 2;
18429 			/* Anycast: true(1), false(2) */
18430 			if (ipif->ipif_flags & IPIF_ANYCAST)
18431 				mae6.ipv6AddrAnycastFlag = 1;
18432 			else
18433 				mae6.ipv6AddrAnycastFlag = 2;
18434 
18435 			/*
18436 			 * Address status: preferred(1), deprecated(2),
18437 			 * invalid(3), inaccessible(4), unknown(5)
18438 			 */
18439 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18440 				mae6.ipv6AddrStatus = 3;
18441 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18442 				mae6.ipv6AddrStatus = 2;
18443 			else
18444 				mae6.ipv6AddrStatus = 1;
18445 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18446 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18447 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18448 			    ipif->ipif_v6pp_dst_addr;
18449 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18450 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18451 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18452 			mae6.ipv6AddrIdentifier = ill->ill_token;
18453 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18454 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18455 			mae6.ipv6AddrRetransmitTime =
18456 			    ill->ill_reachable_retrans_time;
18457 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18458 			    (char *)&mae6,
18459 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18460 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18461 				    "allocate %u bytes\n",
18462 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18463 			}
18464 		}
18465 	}
18466 	rw_exit(&ipst->ips_ill_g_lock);
18467 
18468 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18469 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18470 	    (int)optp->level, (int)optp->name, (int)optp->len));
18471 	qreply(q, mpctl);
18472 	return (mp2ctl);
18473 }
18474 
18475 /* IPv4 multicast group membership. */
18476 static mblk_t *
18477 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18478 {
18479 	struct opthdr		*optp;
18480 	mblk_t			*mp2ctl;
18481 	ill_t			*ill;
18482 	ipif_t			*ipif;
18483 	ilm_t			*ilm;
18484 	ip_member_t		ipm;
18485 	mblk_t			*mp_tail = NULL;
18486 	ill_walk_context_t	ctx;
18487 	zoneid_t		zoneid;
18488 
18489 	/*
18490 	 * make a copy of the original message
18491 	 */
18492 	mp2ctl = copymsg(mpctl);
18493 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18494 
18495 	/* ipGroupMember table */
18496 	optp = (struct opthdr *)&mpctl->b_rptr[
18497 	    sizeof (struct T_optmgmt_ack)];
18498 	optp->level = MIB2_IP;
18499 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18500 
18501 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18502 	ill = ILL_START_WALK_V4(&ctx, ipst);
18503 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18504 		ILM_WALKER_HOLD(ill);
18505 		for (ipif = ill->ill_ipif; ipif != NULL;
18506 		    ipif = ipif->ipif_next) {
18507 			if (ipif->ipif_zoneid != zoneid &&
18508 			    ipif->ipif_zoneid != ALL_ZONES)
18509 				continue;	/* not this zone */
18510 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18511 			    OCTET_LENGTH);
18512 			ipm.ipGroupMemberIfIndex.o_length =
18513 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18514 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18515 				ASSERT(ilm->ilm_ipif != NULL);
18516 				ASSERT(ilm->ilm_ill == NULL);
18517 				if (ilm->ilm_ipif != ipif)
18518 					continue;
18519 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18520 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18521 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18522 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18523 				    (char *)&ipm, (int)sizeof (ipm))) {
18524 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18525 					    "failed to allocate %u bytes\n",
18526 					    (uint_t)sizeof (ipm)));
18527 				}
18528 			}
18529 		}
18530 		ILM_WALKER_RELE(ill);
18531 	}
18532 	rw_exit(&ipst->ips_ill_g_lock);
18533 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18534 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18535 	    (int)optp->level, (int)optp->name, (int)optp->len));
18536 	qreply(q, mpctl);
18537 	return (mp2ctl);
18538 }
18539 
18540 /* IPv6 multicast group membership. */
18541 static mblk_t *
18542 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18543 {
18544 	struct opthdr		*optp;
18545 	mblk_t			*mp2ctl;
18546 	ill_t			*ill;
18547 	ilm_t			*ilm;
18548 	ipv6_member_t		ipm6;
18549 	mblk_t			*mp_tail = NULL;
18550 	ill_walk_context_t	ctx;
18551 	zoneid_t		zoneid;
18552 
18553 	/*
18554 	 * make a copy of the original message
18555 	 */
18556 	mp2ctl = copymsg(mpctl);
18557 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18558 
18559 	/* ip6GroupMember table */
18560 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18561 	optp->level = MIB2_IP6;
18562 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18563 
18564 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18565 	ill = ILL_START_WALK_V6(&ctx, ipst);
18566 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18567 		ILM_WALKER_HOLD(ill);
18568 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18569 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18570 			ASSERT(ilm->ilm_ipif == NULL);
18571 			ASSERT(ilm->ilm_ill != NULL);
18572 			if (ilm->ilm_zoneid != zoneid)
18573 				continue;	/* not this zone */
18574 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18575 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18576 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18577 			if (!snmp_append_data2(mpctl->b_cont,
18578 			    &mp_tail,
18579 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18580 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18581 				    "failed to allocate %u bytes\n",
18582 				    (uint_t)sizeof (ipm6)));
18583 			}
18584 		}
18585 		ILM_WALKER_RELE(ill);
18586 	}
18587 	rw_exit(&ipst->ips_ill_g_lock);
18588 
18589 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18590 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18591 	    (int)optp->level, (int)optp->name, (int)optp->len));
18592 	qreply(q, mpctl);
18593 	return (mp2ctl);
18594 }
18595 
18596 /* IP multicast filtered sources */
18597 static mblk_t *
18598 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18599 {
18600 	struct opthdr		*optp;
18601 	mblk_t			*mp2ctl;
18602 	ill_t			*ill;
18603 	ipif_t			*ipif;
18604 	ilm_t			*ilm;
18605 	ip_grpsrc_t		ips;
18606 	mblk_t			*mp_tail = NULL;
18607 	ill_walk_context_t	ctx;
18608 	zoneid_t		zoneid;
18609 	int			i;
18610 	slist_t			*sl;
18611 
18612 	/*
18613 	 * make a copy of the original message
18614 	 */
18615 	mp2ctl = copymsg(mpctl);
18616 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18617 
18618 	/* ipGroupSource table */
18619 	optp = (struct opthdr *)&mpctl->b_rptr[
18620 	    sizeof (struct T_optmgmt_ack)];
18621 	optp->level = MIB2_IP;
18622 	optp->name = EXPER_IP_GROUP_SOURCES;
18623 
18624 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18625 	ill = ILL_START_WALK_V4(&ctx, ipst);
18626 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18627 		ILM_WALKER_HOLD(ill);
18628 		for (ipif = ill->ill_ipif; ipif != NULL;
18629 		    ipif = ipif->ipif_next) {
18630 			if (ipif->ipif_zoneid != zoneid)
18631 				continue;	/* not this zone */
18632 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18633 			    OCTET_LENGTH);
18634 			ips.ipGroupSourceIfIndex.o_length =
18635 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18636 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18637 				ASSERT(ilm->ilm_ipif != NULL);
18638 				ASSERT(ilm->ilm_ill == NULL);
18639 				sl = ilm->ilm_filter;
18640 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18641 					continue;
18642 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18643 				for (i = 0; i < sl->sl_numsrc; i++) {
18644 					if (!IN6_IS_ADDR_V4MAPPED(
18645 					    &sl->sl_addr[i]))
18646 						continue;
18647 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18648 					    ips.ipGroupSourceAddress);
18649 					if (snmp_append_data2(mpctl->b_cont,
18650 					    &mp_tail, (char *)&ips,
18651 					    (int)sizeof (ips)) == 0) {
18652 						ip1dbg(("ip_snmp_get_mib2_"
18653 						    "ip_group_src: failed to "
18654 						    "allocate %u bytes\n",
18655 						    (uint_t)sizeof (ips)));
18656 					}
18657 				}
18658 			}
18659 		}
18660 		ILM_WALKER_RELE(ill);
18661 	}
18662 	rw_exit(&ipst->ips_ill_g_lock);
18663 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18664 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18665 	    (int)optp->level, (int)optp->name, (int)optp->len));
18666 	qreply(q, mpctl);
18667 	return (mp2ctl);
18668 }
18669 
18670 /* IPv6 multicast filtered sources. */
18671 static mblk_t *
18672 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18673 {
18674 	struct opthdr		*optp;
18675 	mblk_t			*mp2ctl;
18676 	ill_t			*ill;
18677 	ilm_t			*ilm;
18678 	ipv6_grpsrc_t		ips6;
18679 	mblk_t			*mp_tail = NULL;
18680 	ill_walk_context_t	ctx;
18681 	zoneid_t		zoneid;
18682 	int			i;
18683 	slist_t			*sl;
18684 
18685 	/*
18686 	 * make a copy of the original message
18687 	 */
18688 	mp2ctl = copymsg(mpctl);
18689 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18690 
18691 	/* ip6GroupMember table */
18692 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18693 	optp->level = MIB2_IP6;
18694 	optp->name = EXPER_IP6_GROUP_SOURCES;
18695 
18696 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18697 	ill = ILL_START_WALK_V6(&ctx, ipst);
18698 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18699 		ILM_WALKER_HOLD(ill);
18700 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18701 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18702 			ASSERT(ilm->ilm_ipif == NULL);
18703 			ASSERT(ilm->ilm_ill != NULL);
18704 			sl = ilm->ilm_filter;
18705 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18706 				continue;
18707 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18708 			for (i = 0; i < sl->sl_numsrc; i++) {
18709 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18710 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18711 				    (char *)&ips6, (int)sizeof (ips6))) {
18712 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18713 					    "group_src: failed to allocate "
18714 					    "%u bytes\n",
18715 					    (uint_t)sizeof (ips6)));
18716 				}
18717 			}
18718 		}
18719 		ILM_WALKER_RELE(ill);
18720 	}
18721 	rw_exit(&ipst->ips_ill_g_lock);
18722 
18723 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18724 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18725 	    (int)optp->level, (int)optp->name, (int)optp->len));
18726 	qreply(q, mpctl);
18727 	return (mp2ctl);
18728 }
18729 
18730 /* Multicast routing virtual interface table. */
18731 static mblk_t *
18732 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18733 {
18734 	struct opthdr		*optp;
18735 	mblk_t			*mp2ctl;
18736 
18737 	/*
18738 	 * make a copy of the original message
18739 	 */
18740 	mp2ctl = copymsg(mpctl);
18741 
18742 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18743 	optp->level = EXPER_DVMRP;
18744 	optp->name = EXPER_DVMRP_VIF;
18745 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18746 		ip0dbg(("ip_mroute_vif: failed\n"));
18747 	}
18748 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18749 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18750 	    (int)optp->level, (int)optp->name, (int)optp->len));
18751 	qreply(q, mpctl);
18752 	return (mp2ctl);
18753 }
18754 
18755 /* Multicast routing table. */
18756 static mblk_t *
18757 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18758 {
18759 	struct opthdr		*optp;
18760 	mblk_t			*mp2ctl;
18761 
18762 	/*
18763 	 * make a copy of the original message
18764 	 */
18765 	mp2ctl = copymsg(mpctl);
18766 
18767 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18768 	optp->level = EXPER_DVMRP;
18769 	optp->name = EXPER_DVMRP_MRT;
18770 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18771 		ip0dbg(("ip_mroute_mrt: failed\n"));
18772 	}
18773 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18774 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18775 	    (int)optp->level, (int)optp->name, (int)optp->len));
18776 	qreply(q, mpctl);
18777 	return (mp2ctl);
18778 }
18779 
18780 /*
18781  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18782  * in one IRE walk.
18783  */
18784 static mblk_t *
18785 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18786 {
18787 	struct opthdr	*optp;
18788 	mblk_t		*mp2ctl;	/* Returned */
18789 	mblk_t		*mp3ctl;	/* nettomedia */
18790 	mblk_t		*mp4ctl;	/* routeattrs */
18791 	iproutedata_t	ird;
18792 	zoneid_t	zoneid;
18793 
18794 	/*
18795 	 * make copies of the original message
18796 	 *	- mp2ctl is returned unchanged to the caller for his use
18797 	 *	- mpctl is sent upstream as ipRouteEntryTable
18798 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18799 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18800 	 */
18801 	mp2ctl = copymsg(mpctl);
18802 	mp3ctl = copymsg(mpctl);
18803 	mp4ctl = copymsg(mpctl);
18804 	if (mp3ctl == NULL || mp4ctl == NULL) {
18805 		freemsg(mp4ctl);
18806 		freemsg(mp3ctl);
18807 		freemsg(mp2ctl);
18808 		freemsg(mpctl);
18809 		return (NULL);
18810 	}
18811 
18812 	bzero(&ird, sizeof (ird));
18813 
18814 	ird.ird_route.lp_head = mpctl->b_cont;
18815 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18816 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18817 
18818 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18819 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18820 
18821 	/* ipRouteEntryTable in mpctl */
18822 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18823 	optp->level = MIB2_IP;
18824 	optp->name = MIB2_IP_ROUTE;
18825 	optp->len = msgdsize(ird.ird_route.lp_head);
18826 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18827 	    (int)optp->level, (int)optp->name, (int)optp->len));
18828 	qreply(q, mpctl);
18829 
18830 	/* ipNetToMediaEntryTable in mp3ctl */
18831 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18832 	optp->level = MIB2_IP;
18833 	optp->name = MIB2_IP_MEDIA;
18834 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18835 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18836 	    (int)optp->level, (int)optp->name, (int)optp->len));
18837 	qreply(q, mp3ctl);
18838 
18839 	/* ipRouteAttributeTable in mp4ctl */
18840 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18841 	optp->level = MIB2_IP;
18842 	optp->name = EXPER_IP_RTATTR;
18843 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18844 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18845 	    (int)optp->level, (int)optp->name, (int)optp->len));
18846 	if (optp->len == 0)
18847 		freemsg(mp4ctl);
18848 	else
18849 		qreply(q, mp4ctl);
18850 
18851 	return (mp2ctl);
18852 }
18853 
18854 /*
18855  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18856  * ipv6NetToMediaEntryTable in an NDP walk.
18857  */
18858 static mblk_t *
18859 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18860 {
18861 	struct opthdr	*optp;
18862 	mblk_t		*mp2ctl;	/* Returned */
18863 	mblk_t		*mp3ctl;	/* nettomedia */
18864 	mblk_t		*mp4ctl;	/* routeattrs */
18865 	iproutedata_t	ird;
18866 	zoneid_t	zoneid;
18867 
18868 	/*
18869 	 * make copies of the original message
18870 	 *	- mp2ctl is returned unchanged to the caller for his use
18871 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18872 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18873 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18874 	 */
18875 	mp2ctl = copymsg(mpctl);
18876 	mp3ctl = copymsg(mpctl);
18877 	mp4ctl = copymsg(mpctl);
18878 	if (mp3ctl == NULL || mp4ctl == NULL) {
18879 		freemsg(mp4ctl);
18880 		freemsg(mp3ctl);
18881 		freemsg(mp2ctl);
18882 		freemsg(mpctl);
18883 		return (NULL);
18884 	}
18885 
18886 	bzero(&ird, sizeof (ird));
18887 
18888 	ird.ird_route.lp_head = mpctl->b_cont;
18889 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18890 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18891 
18892 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18893 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18894 
18895 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18896 	optp->level = MIB2_IP6;
18897 	optp->name = MIB2_IP6_ROUTE;
18898 	optp->len = msgdsize(ird.ird_route.lp_head);
18899 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18900 	    (int)optp->level, (int)optp->name, (int)optp->len));
18901 	qreply(q, mpctl);
18902 
18903 	/* ipv6NetToMediaEntryTable in mp3ctl */
18904 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18905 
18906 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18907 	optp->level = MIB2_IP6;
18908 	optp->name = MIB2_IP6_MEDIA;
18909 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18910 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18911 	    (int)optp->level, (int)optp->name, (int)optp->len));
18912 	qreply(q, mp3ctl);
18913 
18914 	/* ipv6RouteAttributeTable in mp4ctl */
18915 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18916 	optp->level = MIB2_IP6;
18917 	optp->name = EXPER_IP_RTATTR;
18918 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18919 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18920 	    (int)optp->level, (int)optp->name, (int)optp->len));
18921 	if (optp->len == 0)
18922 		freemsg(mp4ctl);
18923 	else
18924 		qreply(q, mp4ctl);
18925 
18926 	return (mp2ctl);
18927 }
18928 
18929 /*
18930  * IPv6 mib: One per ill
18931  */
18932 static mblk_t *
18933 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18934 {
18935 	struct opthdr		*optp;
18936 	mblk_t			*mp2ctl;
18937 	ill_t			*ill;
18938 	ill_walk_context_t	ctx;
18939 	mblk_t			*mp_tail = NULL;
18940 
18941 	/*
18942 	 * Make a copy of the original message
18943 	 */
18944 	mp2ctl = copymsg(mpctl);
18945 
18946 	/* fixed length IPv6 structure ... */
18947 
18948 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18949 	optp->level = MIB2_IP6;
18950 	optp->name = 0;
18951 	/* Include "unknown interface" ip6_mib */
18952 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
18953 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
18954 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18955 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
18956 	    ipst->ips_ipv6_forward ? 1 : 2);
18957 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
18958 	    ipst->ips_ipv6_def_hops);
18959 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
18960 	    sizeof (mib2_ipIfStatsEntry_t));
18961 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
18962 	    sizeof (mib2_ipv6AddrEntry_t));
18963 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
18964 	    sizeof (mib2_ipv6RouteEntry_t));
18965 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
18966 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18967 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
18968 	    sizeof (ipv6_member_t));
18969 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
18970 	    sizeof (ipv6_grpsrc_t));
18971 
18972 	/*
18973 	 * Synchronize 64- and 32-bit counters
18974 	 */
18975 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
18976 	    ipIfStatsHCInReceives);
18977 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
18978 	    ipIfStatsHCInDelivers);
18979 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
18980 	    ipIfStatsHCOutRequests);
18981 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
18982 	    ipIfStatsHCOutForwDatagrams);
18983 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
18984 	    ipIfStatsHCOutMcastPkts);
18985 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
18986 	    ipIfStatsHCInMcastPkts);
18987 
18988 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18989 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
18990 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18991 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
18992 	}
18993 
18994 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18995 	ill = ILL_START_WALK_V6(&ctx, ipst);
18996 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18997 		ill->ill_ip_mib->ipIfStatsIfIndex =
18998 		    ill->ill_phyint->phyint_ifindex;
18999 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19000 		    ipst->ips_ipv6_forward ? 1 : 2);
19001 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19002 		    ill->ill_max_hops);
19003 
19004 		/*
19005 		 * Synchronize 64- and 32-bit counters
19006 		 */
19007 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19008 		    ipIfStatsHCInReceives);
19009 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19010 		    ipIfStatsHCInDelivers);
19011 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19012 		    ipIfStatsHCOutRequests);
19013 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19014 		    ipIfStatsHCOutForwDatagrams);
19015 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19016 		    ipIfStatsHCOutMcastPkts);
19017 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19018 		    ipIfStatsHCInMcastPkts);
19019 
19020 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19021 		    (char *)ill->ill_ip_mib,
19022 		    (int)sizeof (*ill->ill_ip_mib))) {
19023 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19024 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19025 		}
19026 	}
19027 	rw_exit(&ipst->ips_ill_g_lock);
19028 
19029 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19030 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19031 	    (int)optp->level, (int)optp->name, (int)optp->len));
19032 	qreply(q, mpctl);
19033 	return (mp2ctl);
19034 }
19035 
19036 /*
19037  * ICMPv6 mib: One per ill
19038  */
19039 static mblk_t *
19040 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19041 {
19042 	struct opthdr		*optp;
19043 	mblk_t			*mp2ctl;
19044 	ill_t			*ill;
19045 	ill_walk_context_t	ctx;
19046 	mblk_t			*mp_tail = NULL;
19047 	/*
19048 	 * Make a copy of the original message
19049 	 */
19050 	mp2ctl = copymsg(mpctl);
19051 
19052 	/* fixed length ICMPv6 structure ... */
19053 
19054 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19055 	optp->level = MIB2_ICMP6;
19056 	optp->name = 0;
19057 	/* Include "unknown interface" icmp6_mib */
19058 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19059 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19060 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19061 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19062 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19063 	    (char *)&ipst->ips_icmp6_mib,
19064 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19065 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19066 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19067 	}
19068 
19069 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19070 	ill = ILL_START_WALK_V6(&ctx, ipst);
19071 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19072 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19073 		    ill->ill_phyint->phyint_ifindex;
19074 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19075 		    (char *)ill->ill_icmp6_mib,
19076 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19077 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19078 			    "%u bytes\n",
19079 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19080 		}
19081 	}
19082 	rw_exit(&ipst->ips_ill_g_lock);
19083 
19084 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19085 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19086 	    (int)optp->level, (int)optp->name, (int)optp->len));
19087 	qreply(q, mpctl);
19088 	return (mp2ctl);
19089 }
19090 
19091 /*
19092  * ire_walk routine to create both ipRouteEntryTable and
19093  * ipRouteAttributeTable in one IRE walk
19094  */
19095 static void
19096 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19097 {
19098 	ill_t				*ill;
19099 	ipif_t				*ipif;
19100 	mib2_ipRouteEntry_t		*re;
19101 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19102 	ipaddr_t			gw_addr;
19103 	tsol_ire_gw_secattr_t		*attrp;
19104 	tsol_gc_t			*gc = NULL;
19105 	tsol_gcgrp_t			*gcgrp = NULL;
19106 	uint_t				sacnt = 0;
19107 	int				i;
19108 
19109 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19110 
19111 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19112 		return;
19113 
19114 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19115 		mutex_enter(&attrp->igsa_lock);
19116 		if ((gc = attrp->igsa_gc) != NULL) {
19117 			gcgrp = gc->gc_grp;
19118 			ASSERT(gcgrp != NULL);
19119 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19120 			sacnt = 1;
19121 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19122 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19123 			gc = gcgrp->gcgrp_head;
19124 			sacnt = gcgrp->gcgrp_count;
19125 		}
19126 		mutex_exit(&attrp->igsa_lock);
19127 
19128 		/* do nothing if there's no gc to report */
19129 		if (gc == NULL) {
19130 			ASSERT(sacnt == 0);
19131 			if (gcgrp != NULL) {
19132 				/* we might as well drop the lock now */
19133 				rw_exit(&gcgrp->gcgrp_rwlock);
19134 				gcgrp = NULL;
19135 			}
19136 			attrp = NULL;
19137 		}
19138 
19139 		ASSERT(gc == NULL || (gcgrp != NULL &&
19140 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19141 	}
19142 	ASSERT(sacnt == 0 || gc != NULL);
19143 
19144 	if (sacnt != 0 &&
19145 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19146 		kmem_free(re, sizeof (*re));
19147 		rw_exit(&gcgrp->gcgrp_rwlock);
19148 		return;
19149 	}
19150 
19151 	/*
19152 	 * Return all IRE types for route table... let caller pick and choose
19153 	 */
19154 	re->ipRouteDest = ire->ire_addr;
19155 	ipif = ire->ire_ipif;
19156 	re->ipRouteIfIndex.o_length = 0;
19157 	if (ire->ire_type == IRE_CACHE) {
19158 		ill = (ill_t *)ire->ire_stq->q_ptr;
19159 		re->ipRouteIfIndex.o_length =
19160 		    ill->ill_name_length == 0 ? 0 :
19161 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19162 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19163 		    re->ipRouteIfIndex.o_length);
19164 	} else if (ipif != NULL) {
19165 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19166 		re->ipRouteIfIndex.o_length =
19167 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19168 	}
19169 	re->ipRouteMetric1 = -1;
19170 	re->ipRouteMetric2 = -1;
19171 	re->ipRouteMetric3 = -1;
19172 	re->ipRouteMetric4 = -1;
19173 
19174 	gw_addr = ire->ire_gateway_addr;
19175 
19176 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19177 		re->ipRouteNextHop = ire->ire_src_addr;
19178 	else
19179 		re->ipRouteNextHop = gw_addr;
19180 	/* indirect(4), direct(3), or invalid(2) */
19181 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19182 		re->ipRouteType = 2;
19183 	else
19184 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19185 	re->ipRouteProto = -1;
19186 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19187 	re->ipRouteMask = ire->ire_mask;
19188 	re->ipRouteMetric5 = -1;
19189 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19190 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19191 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19192 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19193 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19194 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19195 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19196 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19197 
19198 	if (ire->ire_flags & RTF_DYNAMIC) {
19199 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19200 	} else {
19201 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19202 	}
19203 
19204 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19205 	    (char *)re, (int)sizeof (*re))) {
19206 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19207 		    (uint_t)sizeof (*re)));
19208 	}
19209 
19210 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19211 		iaeptr->iae_routeidx = ird->ird_idx;
19212 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19213 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19214 	}
19215 
19216 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19217 	    (char *)iae, sacnt * sizeof (*iae))) {
19218 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19219 		    (unsigned)(sacnt * sizeof (*iae))));
19220 	}
19221 
19222 	/* bump route index for next pass */
19223 	ird->ird_idx++;
19224 
19225 	kmem_free(re, sizeof (*re));
19226 	if (sacnt != 0)
19227 		kmem_free(iae, sacnt * sizeof (*iae));
19228 
19229 	if (gcgrp != NULL)
19230 		rw_exit(&gcgrp->gcgrp_rwlock);
19231 }
19232 
19233 /*
19234  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19235  */
19236 static void
19237 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19238 {
19239 	ill_t				*ill;
19240 	ipif_t				*ipif;
19241 	mib2_ipv6RouteEntry_t		*re;
19242 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19243 	in6_addr_t			gw_addr_v6;
19244 	tsol_ire_gw_secattr_t		*attrp;
19245 	tsol_gc_t			*gc = NULL;
19246 	tsol_gcgrp_t			*gcgrp = NULL;
19247 	uint_t				sacnt = 0;
19248 	int				i;
19249 
19250 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19251 
19252 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19253 		return;
19254 
19255 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19256 		mutex_enter(&attrp->igsa_lock);
19257 		if ((gc = attrp->igsa_gc) != NULL) {
19258 			gcgrp = gc->gc_grp;
19259 			ASSERT(gcgrp != NULL);
19260 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19261 			sacnt = 1;
19262 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19263 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19264 			gc = gcgrp->gcgrp_head;
19265 			sacnt = gcgrp->gcgrp_count;
19266 		}
19267 		mutex_exit(&attrp->igsa_lock);
19268 
19269 		/* do nothing if there's no gc to report */
19270 		if (gc == NULL) {
19271 			ASSERT(sacnt == 0);
19272 			if (gcgrp != NULL) {
19273 				/* we might as well drop the lock now */
19274 				rw_exit(&gcgrp->gcgrp_rwlock);
19275 				gcgrp = NULL;
19276 			}
19277 			attrp = NULL;
19278 		}
19279 
19280 		ASSERT(gc == NULL || (gcgrp != NULL &&
19281 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19282 	}
19283 	ASSERT(sacnt == 0 || gc != NULL);
19284 
19285 	if (sacnt != 0 &&
19286 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19287 		kmem_free(re, sizeof (*re));
19288 		rw_exit(&gcgrp->gcgrp_rwlock);
19289 		return;
19290 	}
19291 
19292 	/*
19293 	 * Return all IRE types for route table... let caller pick and choose
19294 	 */
19295 	re->ipv6RouteDest = ire->ire_addr_v6;
19296 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19297 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19298 	re->ipv6RouteIfIndex.o_length = 0;
19299 	ipif = ire->ire_ipif;
19300 	if (ire->ire_type == IRE_CACHE) {
19301 		ill = (ill_t *)ire->ire_stq->q_ptr;
19302 		re->ipv6RouteIfIndex.o_length =
19303 		    ill->ill_name_length == 0 ? 0 :
19304 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19305 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19306 		    re->ipv6RouteIfIndex.o_length);
19307 	} else if (ipif != NULL) {
19308 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19309 		re->ipv6RouteIfIndex.o_length =
19310 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19311 	}
19312 
19313 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19314 
19315 	mutex_enter(&ire->ire_lock);
19316 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19317 	mutex_exit(&ire->ire_lock);
19318 
19319 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19320 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19321 	else
19322 		re->ipv6RouteNextHop = gw_addr_v6;
19323 
19324 	/* remote(4), local(3), or discard(2) */
19325 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19326 		re->ipv6RouteType = 2;
19327 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19328 		re->ipv6RouteType = 3;
19329 	else
19330 		re->ipv6RouteType = 4;
19331 
19332 	re->ipv6RouteProtocol	= -1;
19333 	re->ipv6RoutePolicy	= 0;
19334 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19335 	re->ipv6RouteNextHopRDI	= 0;
19336 	re->ipv6RouteWeight	= 0;
19337 	re->ipv6RouteMetric	= 0;
19338 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19339 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19340 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19341 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19342 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19343 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19344 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19345 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19346 
19347 	if (ire->ire_flags & RTF_DYNAMIC) {
19348 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19349 	} else {
19350 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19351 	}
19352 
19353 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19354 	    (char *)re, (int)sizeof (*re))) {
19355 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19356 		    (uint_t)sizeof (*re)));
19357 	}
19358 
19359 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19360 		iaeptr->iae_routeidx = ird->ird_idx;
19361 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19362 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19363 	}
19364 
19365 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19366 	    (char *)iae, sacnt * sizeof (*iae))) {
19367 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19368 		    (unsigned)(sacnt * sizeof (*iae))));
19369 	}
19370 
19371 	/* bump route index for next pass */
19372 	ird->ird_idx++;
19373 
19374 	kmem_free(re, sizeof (*re));
19375 	if (sacnt != 0)
19376 		kmem_free(iae, sacnt * sizeof (*iae));
19377 
19378 	if (gcgrp != NULL)
19379 		rw_exit(&gcgrp->gcgrp_rwlock);
19380 }
19381 
19382 /*
19383  * ndp_walk routine to create ipv6NetToMediaEntryTable
19384  */
19385 static int
19386 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19387 {
19388 	ill_t				*ill;
19389 	mib2_ipv6NetToMediaEntry_t	ntme;
19390 	dl_unitdata_req_t		*dl;
19391 
19392 	ill = nce->nce_ill;
19393 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19394 		return (0);
19395 
19396 	/*
19397 	 * Neighbor cache entry attached to IRE with on-link
19398 	 * destination.
19399 	 */
19400 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19401 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19402 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19403 	    (nce->nce_res_mp != NULL)) {
19404 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19405 		ntme.ipv6NetToMediaPhysAddress.o_length =
19406 		    dl->dl_dest_addr_length;
19407 	} else {
19408 		ntme.ipv6NetToMediaPhysAddress.o_length =
19409 		    ill->ill_phys_addr_length;
19410 	}
19411 	if (nce->nce_res_mp != NULL) {
19412 		bcopy((char *)nce->nce_res_mp->b_rptr +
19413 		    NCE_LL_ADDR_OFFSET(ill),
19414 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19415 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19416 	} else {
19417 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19418 		    ill->ill_phys_addr_length);
19419 	}
19420 	/*
19421 	 * Note: Returns ND_* states. Should be:
19422 	 * reachable(1), stale(2), delay(3), probe(4),
19423 	 * invalid(5), unknown(6)
19424 	 */
19425 	ntme.ipv6NetToMediaState = nce->nce_state;
19426 	ntme.ipv6NetToMediaLastUpdated = 0;
19427 
19428 	/* other(1), dynamic(2), static(3), local(4) */
19429 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19430 		ntme.ipv6NetToMediaType = 4;
19431 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19432 		ntme.ipv6NetToMediaType = 1;
19433 	} else {
19434 		ntme.ipv6NetToMediaType = 2;
19435 	}
19436 
19437 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19438 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19439 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19440 		    (uint_t)sizeof (ntme)));
19441 	}
19442 	return (0);
19443 }
19444 
19445 /*
19446  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19447  */
19448 /* ARGSUSED */
19449 int
19450 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19451 {
19452 	switch (level) {
19453 	case MIB2_IP:
19454 	case MIB2_ICMP:
19455 		switch (name) {
19456 		default:
19457 			break;
19458 		}
19459 		return (1);
19460 	default:
19461 		return (1);
19462 	}
19463 }
19464 
19465 /*
19466  * When there exists both a 64- and 32-bit counter of a particular type
19467  * (i.e., InReceives), only the 64-bit counters are added.
19468  */
19469 void
19470 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19471 {
19472 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19473 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19474 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19475 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19476 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19477 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19478 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19479 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19480 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19481 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19482 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19483 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19484 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19485 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19486 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19487 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19488 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19489 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19490 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19491 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19492 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19493 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19494 	    o2->ipIfStatsInWrongIPVersion);
19495 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19496 	    o2->ipIfStatsInWrongIPVersion);
19497 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19498 	    o2->ipIfStatsOutSwitchIPVersion);
19499 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19500 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19501 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19502 	    o2->ipIfStatsHCInForwDatagrams);
19503 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19504 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19505 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19506 	    o2->ipIfStatsHCOutForwDatagrams);
19507 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19508 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19509 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19510 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19511 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19512 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19513 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19514 	    o2->ipIfStatsHCOutMcastOctets);
19515 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19516 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19517 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19518 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19519 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19520 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19521 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19522 }
19523 
19524 void
19525 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19526 {
19527 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19528 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19529 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19530 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19531 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19532 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19533 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19534 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19535 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19536 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19537 	    o2->ipv6IfIcmpInRouterSolicits);
19538 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19539 	    o2->ipv6IfIcmpInRouterAdvertisements);
19540 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19541 	    o2->ipv6IfIcmpInNeighborSolicits);
19542 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19543 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19544 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19545 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19546 	    o2->ipv6IfIcmpInGroupMembQueries);
19547 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19548 	    o2->ipv6IfIcmpInGroupMembResponses);
19549 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19550 	    o2->ipv6IfIcmpInGroupMembReductions);
19551 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19552 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19553 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19554 	    o2->ipv6IfIcmpOutDestUnreachs);
19555 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19556 	    o2->ipv6IfIcmpOutAdminProhibs);
19557 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19558 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19559 	    o2->ipv6IfIcmpOutParmProblems);
19560 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19561 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19562 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19563 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19564 	    o2->ipv6IfIcmpOutRouterSolicits);
19565 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19566 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19567 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19568 	    o2->ipv6IfIcmpOutNeighborSolicits);
19569 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19570 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19571 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19572 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19573 	    o2->ipv6IfIcmpOutGroupMembQueries);
19574 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19575 	    o2->ipv6IfIcmpOutGroupMembResponses);
19576 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19577 	    o2->ipv6IfIcmpOutGroupMembReductions);
19578 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19579 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19580 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19581 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19582 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19583 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19584 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19585 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19586 	    o2->ipv6IfIcmpInGroupMembTotal);
19587 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19588 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19589 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19590 	    o2->ipv6IfIcmpInGroupMembBadReports);
19591 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19592 	    o2->ipv6IfIcmpInGroupMembOurReports);
19593 }
19594 
19595 /*
19596  * Called before the options are updated to check if this packet will
19597  * be source routed from here.
19598  * This routine assumes that the options are well formed i.e. that they
19599  * have already been checked.
19600  */
19601 static boolean_t
19602 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19603 {
19604 	ipoptp_t	opts;
19605 	uchar_t		*opt;
19606 	uint8_t		optval;
19607 	uint8_t		optlen;
19608 	ipaddr_t	dst;
19609 	ire_t		*ire;
19610 
19611 	if (IS_SIMPLE_IPH(ipha)) {
19612 		ip2dbg(("not source routed\n"));
19613 		return (B_FALSE);
19614 	}
19615 	dst = ipha->ipha_dst;
19616 	for (optval = ipoptp_first(&opts, ipha);
19617 	    optval != IPOPT_EOL;
19618 	    optval = ipoptp_next(&opts)) {
19619 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19620 		opt = opts.ipoptp_cur;
19621 		optlen = opts.ipoptp_len;
19622 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19623 		    optval, optlen));
19624 		switch (optval) {
19625 			uint32_t off;
19626 		case IPOPT_SSRR:
19627 		case IPOPT_LSRR:
19628 			/*
19629 			 * If dst is one of our addresses and there are some
19630 			 * entries left in the source route return (true).
19631 			 */
19632 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19633 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19634 			if (ire == NULL) {
19635 				ip2dbg(("ip_source_routed: not next"
19636 				    " source route 0x%x\n",
19637 				    ntohl(dst)));
19638 				return (B_FALSE);
19639 			}
19640 			ire_refrele(ire);
19641 			off = opt[IPOPT_OFFSET];
19642 			off--;
19643 			if (optlen < IP_ADDR_LEN ||
19644 			    off > optlen - IP_ADDR_LEN) {
19645 				/* End of source route */
19646 				ip1dbg(("ip_source_routed: end of SR\n"));
19647 				return (B_FALSE);
19648 			}
19649 			return (B_TRUE);
19650 		}
19651 	}
19652 	ip2dbg(("not source routed\n"));
19653 	return (B_FALSE);
19654 }
19655 
19656 /*
19657  * Check if the packet contains any source route.
19658  */
19659 static boolean_t
19660 ip_source_route_included(ipha_t *ipha)
19661 {
19662 	ipoptp_t	opts;
19663 	uint8_t		optval;
19664 
19665 	if (IS_SIMPLE_IPH(ipha))
19666 		return (B_FALSE);
19667 	for (optval = ipoptp_first(&opts, ipha);
19668 	    optval != IPOPT_EOL;
19669 	    optval = ipoptp_next(&opts)) {
19670 		switch (optval) {
19671 		case IPOPT_SSRR:
19672 		case IPOPT_LSRR:
19673 			return (B_TRUE);
19674 		}
19675 	}
19676 	return (B_FALSE);
19677 }
19678 
19679 /*
19680  * Called when the IRE expiration timer fires.
19681  */
19682 void
19683 ip_trash_timer_expire(void *args)
19684 {
19685 	int			flush_flag = 0;
19686 	ire_expire_arg_t	iea;
19687 	ip_stack_t		*ipst = (ip_stack_t *)args;
19688 
19689 	iea.iea_ipst = ipst;	/* No netstack_hold */
19690 
19691 	/*
19692 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19693 	 * This lock makes sure that a new invocation of this function
19694 	 * that occurs due to an almost immediate timer firing will not
19695 	 * progress beyond this point until the current invocation is done
19696 	 */
19697 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19698 	ipst->ips_ip_ire_expire_id = 0;
19699 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19700 
19701 	/* Periodic timer */
19702 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19703 	    ipst->ips_ip_ire_arp_interval) {
19704 		/*
19705 		 * Remove all IRE_CACHE entries since they might
19706 		 * contain arp information.
19707 		 */
19708 		flush_flag |= FLUSH_ARP_TIME;
19709 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19710 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19711 	}
19712 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19713 	    ipst->ips_ip_ire_redir_interval) {
19714 		/* Remove all redirects */
19715 		flush_flag |= FLUSH_REDIRECT_TIME;
19716 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19717 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19718 	}
19719 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19720 	    ipst->ips_ip_ire_pathmtu_interval) {
19721 		/* Increase path mtu */
19722 		flush_flag |= FLUSH_MTU_TIME;
19723 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19724 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19725 	}
19726 
19727 	/*
19728 	 * Optimize for the case when there are no redirects in the
19729 	 * ftable, that is, no need to walk the ftable in that case.
19730 	 */
19731 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19732 		iea.iea_flush_flag = flush_flag;
19733 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19734 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19735 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19736 		    NULL, ALL_ZONES, ipst);
19737 	}
19738 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19739 	    ipst->ips_ip_redirect_cnt > 0) {
19740 		iea.iea_flush_flag = flush_flag;
19741 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19742 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19743 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19744 	}
19745 	if (flush_flag & FLUSH_MTU_TIME) {
19746 		/*
19747 		 * Walk all IPv6 IRE's and update them
19748 		 * Note that ARP and redirect timers are not
19749 		 * needed since NUD handles stale entries.
19750 		 */
19751 		flush_flag = FLUSH_MTU_TIME;
19752 		iea.iea_flush_flag = flush_flag;
19753 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19754 		    ALL_ZONES, ipst);
19755 	}
19756 
19757 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19758 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19759 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19760 
19761 	/*
19762 	 * Hold the lock to serialize timeout calls and prevent
19763 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19764 	 * for the timer to fire and a new invocation of this function
19765 	 * to start before the return value of timeout has been stored
19766 	 * in ip_ire_expire_id by the current invocation.
19767 	 */
19768 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19769 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19770 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19771 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19772 }
19773 
19774 /*
19775  * Called by the memory allocator subsystem directly, when the system
19776  * is running low on memory.
19777  */
19778 /* ARGSUSED */
19779 void
19780 ip_trash_ire_reclaim(void *args)
19781 {
19782 	netstack_handle_t nh;
19783 	netstack_t *ns;
19784 
19785 	netstack_next_init(&nh);
19786 	while ((ns = netstack_next(&nh)) != NULL) {
19787 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19788 		netstack_rele(ns);
19789 	}
19790 	netstack_next_fini(&nh);
19791 }
19792 
19793 static void
19794 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19795 {
19796 	ire_cache_count_t icc;
19797 	ire_cache_reclaim_t icr;
19798 	ncc_cache_count_t ncc;
19799 	nce_cache_reclaim_t ncr;
19800 	uint_t delete_cnt;
19801 	/*
19802 	 * Memory reclaim call back.
19803 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19804 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19805 	 * entries, determine what fraction to free for
19806 	 * each category of IRE_CACHE entries giving absolute priority
19807 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19808 	 * entry will be freed unless all offlink entries are freed).
19809 	 */
19810 	icc.icc_total = 0;
19811 	icc.icc_unused = 0;
19812 	icc.icc_offlink = 0;
19813 	icc.icc_pmtu = 0;
19814 	icc.icc_onlink = 0;
19815 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19816 
19817 	/*
19818 	 * Free NCEs for IPv6 like the onlink ires.
19819 	 */
19820 	ncc.ncc_total = 0;
19821 	ncc.ncc_host = 0;
19822 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19823 
19824 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19825 	    icc.icc_pmtu + icc.icc_onlink);
19826 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19827 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19828 	if (delete_cnt == 0)
19829 		return;
19830 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19831 	/* Always delete all unused offlink entries */
19832 	icr.icr_ipst = ipst;
19833 	icr.icr_unused = 1;
19834 	if (delete_cnt <= icc.icc_unused) {
19835 		/*
19836 		 * Only need to free unused entries.  In other words,
19837 		 * there are enough unused entries to free to meet our
19838 		 * target number of freed ire cache entries.
19839 		 */
19840 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19841 		ncr.ncr_host = 0;
19842 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19843 		/*
19844 		 * Only need to free unused entries, plus a fraction of offlink
19845 		 * entries.  It follows from the first if statement that
19846 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19847 		 */
19848 		delete_cnt -= icc.icc_unused;
19849 		/* Round up # deleted by truncating fraction */
19850 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19851 		icr.icr_pmtu = icr.icr_onlink = 0;
19852 		ncr.ncr_host = 0;
19853 	} else if (delete_cnt <=
19854 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19855 		/*
19856 		 * Free all unused and offlink entries, plus a fraction of
19857 		 * pmtu entries.  It follows from the previous if statement
19858 		 * that icc_pmtu is non-zero, and that
19859 		 * delete_cnt != icc_unused + icc_offlink.
19860 		 */
19861 		icr.icr_offlink = 1;
19862 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19863 		/* Round up # deleted by truncating fraction */
19864 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19865 		icr.icr_onlink = 0;
19866 		ncr.ncr_host = 0;
19867 	} else {
19868 		/*
19869 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19870 		 * of onlink entries.  If we're here, then we know that
19871 		 * icc_onlink is non-zero, and that
19872 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19873 		 */
19874 		icr.icr_offlink = icr.icr_pmtu = 1;
19875 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19876 		    icc.icc_pmtu;
19877 		/* Round up # deleted by truncating fraction */
19878 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19879 		/* Using the same delete fraction as for onlink IREs */
19880 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19881 	}
19882 #ifdef DEBUG
19883 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19884 	    "fractions %d/%d/%d/%d\n",
19885 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19886 	    icc.icc_unused, icc.icc_offlink,
19887 	    icc.icc_pmtu, icc.icc_onlink,
19888 	    icr.icr_unused, icr.icr_offlink,
19889 	    icr.icr_pmtu, icr.icr_onlink));
19890 #endif
19891 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19892 	if (ncr.ncr_host != 0)
19893 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19894 		    (uchar_t *)&ncr, ipst);
19895 #ifdef DEBUG
19896 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19897 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19898 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19899 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19900 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19901 	    icc.icc_pmtu, icc.icc_onlink));
19902 #endif
19903 }
19904 
19905 /*
19906  * ip_unbind is called when a copy of an unbind request is received from the
19907  * upper level protocol.  We remove this conn from any fanout hash list it is
19908  * on, and zero out the bind information.  No reply is expected up above.
19909  */
19910 mblk_t *
19911 ip_unbind(queue_t *q, mblk_t *mp)
19912 {
19913 	conn_t	*connp = Q_TO_CONN(q);
19914 
19915 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19916 
19917 	if (is_system_labeled() && connp->conn_anon_port) {
19918 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19919 		    connp->conn_mlp_type, connp->conn_ulp,
19920 		    ntohs(connp->conn_lport), B_FALSE);
19921 		connp->conn_anon_port = 0;
19922 	}
19923 	connp->conn_mlp_type = mlptSingle;
19924 
19925 	ipcl_hash_remove(connp);
19926 
19927 	ASSERT(mp->b_cont == NULL);
19928 	/*
19929 	 * Convert mp into a T_OK_ACK
19930 	 */
19931 	mp = mi_tpi_ok_ack_alloc(mp);
19932 
19933 	/*
19934 	 * should not happen in practice... T_OK_ACK is smaller than the
19935 	 * original message.
19936 	 */
19937 	if (mp == NULL)
19938 		return (NULL);
19939 
19940 	/*
19941 	 * Don't bzero the ports if its TCP since TCP still needs the
19942 	 * lport to remove it from its own bind hash. TCP will do the
19943 	 * cleanup.
19944 	 */
19945 	if (!IPCL_IS_TCP(connp))
19946 		bzero(&connp->u_port, sizeof (connp->u_port));
19947 
19948 	return (mp);
19949 }
19950 
19951 /*
19952  * Write side put procedure.  Outbound data, IOCTLs, responses from
19953  * resolvers, etc, come down through here.
19954  *
19955  * arg2 is always a queue_t *.
19956  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19957  * the zoneid.
19958  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19959  */
19960 void
19961 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19962 {
19963 	ip_output_options(arg, mp, arg2, caller, &zero_info);
19964 }
19965 
19966 void
19967 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
19968     ip_opt_info_t *infop)
19969 {
19970 	conn_t		*connp = NULL;
19971 	queue_t		*q = (queue_t *)arg2;
19972 	ipha_t		*ipha;
19973 #define	rptr	((uchar_t *)ipha)
19974 	ire_t		*ire = NULL;
19975 	ire_t		*sctp_ire = NULL;
19976 	uint32_t	v_hlen_tos_len;
19977 	ipaddr_t	dst;
19978 	mblk_t		*first_mp = NULL;
19979 	boolean_t	mctl_present;
19980 	ipsec_out_t	*io;
19981 	int		match_flags;
19982 	ill_t		*attach_ill = NULL;
19983 					/* Bind to IPIF_NOFAILOVER ill etc. */
19984 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19985 	ipif_t		*dst_ipif;
19986 	boolean_t	multirt_need_resolve = B_FALSE;
19987 	mblk_t		*copy_mp = NULL;
19988 	int		err;
19989 	zoneid_t	zoneid;
19990 	int	adjust;
19991 	uint16_t iplen;
19992 	boolean_t	need_decref = B_FALSE;
19993 	boolean_t	ignore_dontroute = B_FALSE;
19994 	boolean_t	ignore_nexthop = B_FALSE;
19995 	boolean_t	ip_nexthop = B_FALSE;
19996 	ipaddr_t	nexthop_addr;
19997 	ip_stack_t	*ipst;
19998 
19999 #ifdef	_BIG_ENDIAN
20000 #define	V_HLEN	(v_hlen_tos_len >> 24)
20001 #else
20002 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20003 #endif
20004 
20005 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20006 	    "ip_wput_start: q %p", q);
20007 
20008 	/*
20009 	 * ip_wput fast path
20010 	 */
20011 
20012 	/* is packet from ARP ? */
20013 	if (q->q_next != NULL) {
20014 		zoneid = (zoneid_t)(uintptr_t)arg;
20015 		goto qnext;
20016 	}
20017 
20018 	connp = (conn_t *)arg;
20019 	ASSERT(connp != NULL);
20020 	zoneid = connp->conn_zoneid;
20021 	ipst = connp->conn_netstack->netstack_ip;
20022 
20023 	/* is queue flow controlled? */
20024 	if ((q->q_first != NULL || connp->conn_draining) &&
20025 	    (caller == IP_WPUT)) {
20026 		ASSERT(!need_decref);
20027 		(void) putq(q, mp);
20028 		return;
20029 	}
20030 
20031 	/* Multidata transmit? */
20032 	if (DB_TYPE(mp) == M_MULTIDATA) {
20033 		/*
20034 		 * We should never get here, since all Multidata messages
20035 		 * originating from tcp should have been directed over to
20036 		 * tcp_multisend() in the first place.
20037 		 */
20038 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20039 		freemsg(mp);
20040 		return;
20041 	} else if (DB_TYPE(mp) != M_DATA)
20042 		goto notdata;
20043 
20044 	if (mp->b_flag & MSGHASREF) {
20045 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20046 		mp->b_flag &= ~MSGHASREF;
20047 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20048 		need_decref = B_TRUE;
20049 	}
20050 	ipha = (ipha_t *)mp->b_rptr;
20051 
20052 	/* is IP header non-aligned or mblk smaller than basic IP header */
20053 #ifndef SAFETY_BEFORE_SPEED
20054 	if (!OK_32PTR(rptr) ||
20055 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20056 		goto hdrtoosmall;
20057 #endif
20058 
20059 	ASSERT(OK_32PTR(ipha));
20060 
20061 	/*
20062 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20063 	 * wrong version, we'll catch it again in ip_output_v6.
20064 	 *
20065 	 * Note that this is *only* locally-generated output here, and never
20066 	 * forwarded data, and that we need to deal only with transports that
20067 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20068 	 * label.)
20069 	 */
20070 	if (is_system_labeled() &&
20071 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20072 	    !connp->conn_ulp_labeled) {
20073 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20074 		    connp->conn_mac_exempt, ipst);
20075 		ipha = (ipha_t *)mp->b_rptr;
20076 		if (err != 0) {
20077 			first_mp = mp;
20078 			if (err == EINVAL)
20079 				goto icmp_parameter_problem;
20080 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20081 			goto discard_pkt;
20082 		}
20083 		iplen = ntohs(ipha->ipha_length) + adjust;
20084 		ipha->ipha_length = htons(iplen);
20085 	}
20086 
20087 	ASSERT(infop != NULL);
20088 
20089 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20090 		/*
20091 		 * IP_PKTINFO ancillary option is present.
20092 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20093 		 * allows using address of any zone as the source address.
20094 		 */
20095 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20096 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20097 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20098 		if (ire == NULL)
20099 			goto drop_pkt;
20100 		ire_refrele(ire);
20101 		ire = NULL;
20102 	}
20103 
20104 	/*
20105 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20106 	 * ill index passed in IP_PKTINFO.
20107 	 */
20108 	if (infop->ip_opt_ill_index != 0 &&
20109 	    connp->conn_xmit_if_ill == NULL &&
20110 	    connp->conn_nofailover_ill == NULL) {
20111 
20112 		xmit_ill = ill_lookup_on_ifindex(
20113 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20114 		    ipst);
20115 
20116 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20117 			goto drop_pkt;
20118 		/*
20119 		 * check that there is an ipif belonging
20120 		 * to our zone. IPCL_ZONEID is not used because
20121 		 * IP_ALLZONES option is valid only when the ill is
20122 		 * accessible from all zones i.e has a valid ipif in
20123 		 * all zones.
20124 		 */
20125 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20126 			goto drop_pkt;
20127 		}
20128 	}
20129 
20130 	/*
20131 	 * If there is a policy, try to attach an ipsec_out in
20132 	 * the front. At the end, first_mp either points to a
20133 	 * M_DATA message or IPSEC_OUT message linked to a
20134 	 * M_DATA message. We have to do it now as we might
20135 	 * lose the "conn" if we go through ip_newroute.
20136 	 */
20137 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20138 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20139 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20140 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20141 			if (need_decref)
20142 				CONN_DEC_REF(connp);
20143 			return;
20144 		} else {
20145 			ASSERT(mp->b_datap->db_type == M_CTL);
20146 			first_mp = mp;
20147 			mp = mp->b_cont;
20148 			mctl_present = B_TRUE;
20149 		}
20150 	} else {
20151 		first_mp = mp;
20152 		mctl_present = B_FALSE;
20153 	}
20154 
20155 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20156 
20157 	/* is wrong version or IP options present */
20158 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20159 		goto version_hdrlen_check;
20160 	dst = ipha->ipha_dst;
20161 
20162 	if (connp->conn_nofailover_ill != NULL) {
20163 		attach_ill = conn_get_held_ill(connp,
20164 		    &connp->conn_nofailover_ill, &err);
20165 		if (err == ILL_LOOKUP_FAILED) {
20166 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20167 			if (need_decref)
20168 				CONN_DEC_REF(connp);
20169 			freemsg(first_mp);
20170 			return;
20171 		}
20172 	}
20173 
20174 
20175 	/* is packet multicast? */
20176 	if (CLASSD(dst))
20177 		goto multicast;
20178 
20179 	/*
20180 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20181 	 * takes precedence over conn_dontroute and conn_nexthop_set
20182 	 */
20183 	if (xmit_ill != NULL) {
20184 		goto send_from_ill;
20185 	}
20186 
20187 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20188 	    (connp->conn_nexthop_set)) {
20189 		/*
20190 		 * If the destination is a broadcast or a loopback
20191 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20192 		 * through the standard path. But in the case of local
20193 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20194 		 * the standard path not IP_XMIT_IF.
20195 		 */
20196 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20197 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20198 		    (ire->ire_type != IRE_LOOPBACK))) {
20199 			if ((connp->conn_dontroute ||
20200 			    connp->conn_nexthop_set) && (ire != NULL) &&
20201 			    (ire->ire_type == IRE_LOCAL))
20202 				goto standard_path;
20203 
20204 			if (ire != NULL) {
20205 				ire_refrele(ire);
20206 				/* No more access to ire */
20207 				ire = NULL;
20208 			}
20209 			/*
20210 			 * bypass routing checks and go directly to
20211 			 * interface.
20212 			 */
20213 			if (connp->conn_dontroute) {
20214 				goto dontroute;
20215 			} else if (connp->conn_nexthop_set) {
20216 				ip_nexthop = B_TRUE;
20217 				nexthop_addr = connp->conn_nexthop_v4;
20218 				goto send_from_ill;
20219 			}
20220 
20221 			/*
20222 			 * If IP_XMIT_IF socket option is set,
20223 			 * then we allow unicast and multicast
20224 			 * packets to go through the ill. It is
20225 			 * quite possible that the destination
20226 			 * is not in the ire cache table and we
20227 			 * do not want to go to ip_newroute()
20228 			 * instead we call ip_newroute_ipif.
20229 			 */
20230 			xmit_ill = conn_get_held_ill(connp,
20231 			    &connp->conn_xmit_if_ill, &err);
20232 			if (err == ILL_LOOKUP_FAILED) {
20233 				BUMP_MIB(&ipst->ips_ip_mib,
20234 				    ipIfStatsOutDiscards);
20235 				if (attach_ill != NULL)
20236 					ill_refrele(attach_ill);
20237 				if (need_decref)
20238 					CONN_DEC_REF(connp);
20239 				freemsg(first_mp);
20240 				return;
20241 			}
20242 			goto send_from_ill;
20243 		}
20244 standard_path:
20245 		/* Must be a broadcast, a loopback or a local ire */
20246 		if (ire != NULL) {
20247 			ire_refrele(ire);
20248 			/* No more access to ire */
20249 			ire = NULL;
20250 		}
20251 	}
20252 
20253 	if (attach_ill != NULL)
20254 		goto send_from_ill;
20255 
20256 	/*
20257 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20258 	 * this for the tcp global queue and listen end point
20259 	 * as it does not really have a real destination to
20260 	 * talk to.  This is also true for SCTP.
20261 	 */
20262 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20263 	    !connp->conn_fully_bound) {
20264 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20265 		if (ire == NULL)
20266 			goto noirefound;
20267 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20268 		    "ip_wput_end: q %p (%S)", q, "end");
20269 
20270 		/*
20271 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20272 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20273 		 */
20274 		if (ire->ire_flags & RTF_MULTIRT) {
20275 
20276 			/*
20277 			 * Force the TTL of multirouted packets if required.
20278 			 * The TTL of such packets is bounded by the
20279 			 * ip_multirt_ttl ndd variable.
20280 			 */
20281 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20282 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20283 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20284 				    "(was %d), dst 0x%08x\n",
20285 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20286 				    ntohl(ire->ire_addr)));
20287 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20288 			}
20289 			/*
20290 			 * We look at this point if there are pending
20291 			 * unresolved routes. ire_multirt_resolvable()
20292 			 * checks in O(n) that all IRE_OFFSUBNET ire
20293 			 * entries for the packet's destination and
20294 			 * flagged RTF_MULTIRT are currently resolved.
20295 			 * If some remain unresolved, we make a copy
20296 			 * of the current message. It will be used
20297 			 * to initiate additional route resolutions.
20298 			 */
20299 			multirt_need_resolve =
20300 			    ire_multirt_need_resolve(ire->ire_addr,
20301 			    MBLK_GETLABEL(first_mp), ipst);
20302 			ip2dbg(("ip_wput[TCP]: ire %p, "
20303 			    "multirt_need_resolve %d, first_mp %p\n",
20304 			    (void *)ire, multirt_need_resolve,
20305 			    (void *)first_mp));
20306 			if (multirt_need_resolve) {
20307 				copy_mp = copymsg(first_mp);
20308 				if (copy_mp != NULL) {
20309 					MULTIRT_DEBUG_TAG(copy_mp);
20310 				}
20311 			}
20312 		}
20313 
20314 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20315 
20316 		/*
20317 		 * Try to resolve another multiroute if
20318 		 * ire_multirt_need_resolve() deemed it necessary.
20319 		 */
20320 		if (copy_mp != NULL)
20321 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20322 		if (need_decref)
20323 			CONN_DEC_REF(connp);
20324 		return;
20325 	}
20326 
20327 	/*
20328 	 * Access to conn_ire_cache. (protected by conn_lock)
20329 	 *
20330 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20331 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20332 	 * send a packet or two with the IRE_CACHE that is going away.
20333 	 * Access to the ire requires an ire refhold on the ire prior to
20334 	 * its use since an interface unplumb thread may delete the cached
20335 	 * ire and release the refhold at any time.
20336 	 *
20337 	 * Caching an ire in the conn_ire_cache
20338 	 *
20339 	 * o Caching an ire pointer in the conn requires a strict check for
20340 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20341 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20342 	 * in the conn is done after making sure under the bucket lock that the
20343 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20344 	 * caching an ire after the unplumb thread has cleaned up the conn.
20345 	 * If the conn does not send a packet subsequently the unplumb thread
20346 	 * will be hanging waiting for the ire count to drop to zero.
20347 	 *
20348 	 * o We also need to atomically test for a null conn_ire_cache and
20349 	 * set the conn_ire_cache under the the protection of the conn_lock
20350 	 * to avoid races among concurrent threads trying to simultaneously
20351 	 * cache an ire in the conn_ire_cache.
20352 	 */
20353 	mutex_enter(&connp->conn_lock);
20354 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20355 
20356 	if (ire != NULL && ire->ire_addr == dst &&
20357 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20358 
20359 		IRE_REFHOLD(ire);
20360 		mutex_exit(&connp->conn_lock);
20361 
20362 	} else {
20363 		boolean_t cached = B_FALSE;
20364 		connp->conn_ire_cache = NULL;
20365 		mutex_exit(&connp->conn_lock);
20366 		/* Release the old ire */
20367 		if (ire != NULL && sctp_ire == NULL)
20368 			IRE_REFRELE_NOTR(ire);
20369 
20370 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20371 		if (ire == NULL)
20372 			goto noirefound;
20373 		IRE_REFHOLD_NOTR(ire);
20374 
20375 		mutex_enter(&connp->conn_lock);
20376 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20377 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20378 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20379 				if (connp->conn_ulp == IPPROTO_TCP)
20380 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20381 				connp->conn_ire_cache = ire;
20382 				cached = B_TRUE;
20383 			}
20384 			rw_exit(&ire->ire_bucket->irb_lock);
20385 		}
20386 		mutex_exit(&connp->conn_lock);
20387 
20388 		/*
20389 		 * We can continue to use the ire but since it was
20390 		 * not cached, we should drop the extra reference.
20391 		 */
20392 		if (!cached)
20393 			IRE_REFRELE_NOTR(ire);
20394 	}
20395 
20396 
20397 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20398 	    "ip_wput_end: q %p (%S)", q, "end");
20399 
20400 	/*
20401 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20402 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20403 	 */
20404 	if (ire->ire_flags & RTF_MULTIRT) {
20405 
20406 		/*
20407 		 * Force the TTL of multirouted packets if required.
20408 		 * The TTL of such packets is bounded by the
20409 		 * ip_multirt_ttl ndd variable.
20410 		 */
20411 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20412 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20413 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20414 			    "(was %d), dst 0x%08x\n",
20415 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20416 			    ntohl(ire->ire_addr)));
20417 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20418 		}
20419 
20420 		/*
20421 		 * At this point, we check to see if there are any pending
20422 		 * unresolved routes. ire_multirt_resolvable()
20423 		 * checks in O(n) that all IRE_OFFSUBNET ire
20424 		 * entries for the packet's destination and
20425 		 * flagged RTF_MULTIRT are currently resolved.
20426 		 * If some remain unresolved, we make a copy
20427 		 * of the current message. It will be used
20428 		 * to initiate additional route resolutions.
20429 		 */
20430 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20431 		    MBLK_GETLABEL(first_mp), ipst);
20432 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20433 		    "multirt_need_resolve %d, first_mp %p\n",
20434 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20435 		if (multirt_need_resolve) {
20436 			copy_mp = copymsg(first_mp);
20437 			if (copy_mp != NULL) {
20438 				MULTIRT_DEBUG_TAG(copy_mp);
20439 			}
20440 		}
20441 	}
20442 
20443 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20444 
20445 	/*
20446 	 * Try to resolve another multiroute if
20447 	 * ire_multirt_resolvable() deemed it necessary
20448 	 */
20449 	if (copy_mp != NULL)
20450 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20451 	if (need_decref)
20452 		CONN_DEC_REF(connp);
20453 	return;
20454 
20455 qnext:
20456 	/*
20457 	 * Upper Level Protocols pass down complete IP datagrams
20458 	 * as M_DATA messages.	Everything else is a sideshow.
20459 	 *
20460 	 * 1) We could be re-entering ip_wput because of ip_neworute
20461 	 *    in which case we could have a IPSEC_OUT message. We
20462 	 *    need to pass through ip_wput like other datagrams and
20463 	 *    hence cannot branch to ip_wput_nondata.
20464 	 *
20465 	 * 2) ARP, AH, ESP, and other clients who are on the module
20466 	 *    instance of IP stream, give us something to deal with.
20467 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20468 	 *
20469 	 * 3) ICMP replies also could come here.
20470 	 */
20471 	ipst = ILLQ_TO_IPST(q);
20472 
20473 	if (DB_TYPE(mp) != M_DATA) {
20474 notdata:
20475 		if (DB_TYPE(mp) == M_CTL) {
20476 			/*
20477 			 * M_CTL messages are used by ARP, AH and ESP to
20478 			 * communicate with IP. We deal with IPSEC_IN and
20479 			 * IPSEC_OUT here. ip_wput_nondata handles other
20480 			 * cases.
20481 			 */
20482 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20483 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20484 				first_mp = mp->b_cont;
20485 				first_mp->b_flag &= ~MSGHASREF;
20486 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20487 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20488 				CONN_DEC_REF(connp);
20489 				connp = NULL;
20490 			}
20491 			if (ii->ipsec_info_type == IPSEC_IN) {
20492 				/*
20493 				 * Either this message goes back to
20494 				 * IPsec for further processing or to
20495 				 * ULP after policy checks.
20496 				 */
20497 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20498 				return;
20499 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20500 				io = (ipsec_out_t *)ii;
20501 				if (io->ipsec_out_proc_begin) {
20502 					/*
20503 					 * IPsec processing has already started.
20504 					 * Complete it.
20505 					 * IPQoS notes: We don't care what is
20506 					 * in ipsec_out_ill_index since this
20507 					 * won't be processed for IPQoS policies
20508 					 * in ipsec_out_process.
20509 					 */
20510 					ipsec_out_process(q, mp, NULL,
20511 					    io->ipsec_out_ill_index);
20512 					return;
20513 				} else {
20514 					connp = (q->q_next != NULL) ?
20515 					    NULL : Q_TO_CONN(q);
20516 					first_mp = mp;
20517 					mp = mp->b_cont;
20518 					mctl_present = B_TRUE;
20519 				}
20520 				zoneid = io->ipsec_out_zoneid;
20521 				ASSERT(zoneid != ALL_ZONES);
20522 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20523 				/*
20524 				 * It's an IPsec control message requesting
20525 				 * an SADB update to be sent to the IPsec
20526 				 * hardware acceleration capable ills.
20527 				 */
20528 				ipsec_ctl_t *ipsec_ctl =
20529 				    (ipsec_ctl_t *)mp->b_rptr;
20530 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20531 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20532 				mblk_t *cmp = mp->b_cont;
20533 
20534 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20535 				ASSERT(cmp != NULL);
20536 
20537 				freeb(mp);
20538 				ill_ipsec_capab_send_all(satype, cmp, sa,
20539 				    ipst->ips_netstack);
20540 				return;
20541 			} else {
20542 				/*
20543 				 * This must be ARP or special TSOL signaling.
20544 				 */
20545 				ip_wput_nondata(NULL, q, mp, NULL);
20546 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20547 				    "ip_wput_end: q %p (%S)", q, "nondata");
20548 				return;
20549 			}
20550 		} else {
20551 			/*
20552 			 * This must be non-(ARP/AH/ESP) messages.
20553 			 */
20554 			ASSERT(!need_decref);
20555 			ip_wput_nondata(NULL, q, mp, NULL);
20556 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20557 			    "ip_wput_end: q %p (%S)", q, "nondata");
20558 			return;
20559 		}
20560 	} else {
20561 		first_mp = mp;
20562 		mctl_present = B_FALSE;
20563 	}
20564 
20565 	ASSERT(first_mp != NULL);
20566 	/*
20567 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20568 	 * to make sure that this packet goes out on the same interface it
20569 	 * came in. We handle that here.
20570 	 */
20571 	if (mctl_present) {
20572 		uint_t ifindex;
20573 
20574 		io = (ipsec_out_t *)first_mp->b_rptr;
20575 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20576 			/*
20577 			 * We may have lost the conn context if we are
20578 			 * coming here from ip_newroute(). Copy the
20579 			 * nexthop information.
20580 			 */
20581 			if (io->ipsec_out_ip_nexthop) {
20582 				ip_nexthop = B_TRUE;
20583 				nexthop_addr = io->ipsec_out_nexthop_addr;
20584 
20585 				ipha = (ipha_t *)mp->b_rptr;
20586 				dst = ipha->ipha_dst;
20587 				goto send_from_ill;
20588 			} else {
20589 				ASSERT(io->ipsec_out_ill_index != 0);
20590 				ifindex = io->ipsec_out_ill_index;
20591 				attach_ill = ill_lookup_on_ifindex(ifindex,
20592 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20593 				if (attach_ill == NULL) {
20594 					ASSERT(xmit_ill == NULL);
20595 					ip1dbg(("ip_output: bad ifindex for "
20596 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20597 					    ifindex));
20598 					freemsg(first_mp);
20599 					BUMP_MIB(&ipst->ips_ip_mib,
20600 					    ipIfStatsOutDiscards);
20601 					ASSERT(!need_decref);
20602 					return;
20603 				}
20604 			}
20605 		}
20606 	}
20607 
20608 	ASSERT(xmit_ill == NULL);
20609 
20610 	/* We have a complete IP datagram heading outbound. */
20611 	ipha = (ipha_t *)mp->b_rptr;
20612 
20613 #ifndef SPEED_BEFORE_SAFETY
20614 	/*
20615 	 * Make sure we have a full-word aligned message and that at least
20616 	 * a simple IP header is accessible in the first message.  If not,
20617 	 * try a pullup.
20618 	 */
20619 	if (!OK_32PTR(rptr) ||
20620 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20621 hdrtoosmall:
20622 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20623 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20624 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20625 			if (first_mp == NULL)
20626 				first_mp = mp;
20627 			goto discard_pkt;
20628 		}
20629 
20630 		/* This function assumes that mp points to an IPv4 packet. */
20631 		if (is_system_labeled() && q->q_next == NULL &&
20632 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20633 		    !connp->conn_ulp_labeled) {
20634 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20635 			    &adjust, connp->conn_mac_exempt, ipst);
20636 			ipha = (ipha_t *)mp->b_rptr;
20637 			if (first_mp != NULL)
20638 				first_mp->b_cont = mp;
20639 			if (err != 0) {
20640 				if (first_mp == NULL)
20641 					first_mp = mp;
20642 				if (err == EINVAL)
20643 					goto icmp_parameter_problem;
20644 				ip2dbg(("ip_wput: label check failed (%d)\n",
20645 				    err));
20646 				goto discard_pkt;
20647 			}
20648 			iplen = ntohs(ipha->ipha_length) + adjust;
20649 			ipha->ipha_length = htons(iplen);
20650 		}
20651 
20652 		ipha = (ipha_t *)mp->b_rptr;
20653 		if (first_mp == NULL) {
20654 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20655 			/*
20656 			 * If we got here because of "goto hdrtoosmall"
20657 			 * We need to attach a IPSEC_OUT.
20658 			 */
20659 			if (connp->conn_out_enforce_policy) {
20660 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20661 				    NULL, ipha->ipha_protocol,
20662 				    ipst->ips_netstack)) == NULL)) {
20663 					BUMP_MIB(&ipst->ips_ip_mib,
20664 					    ipIfStatsOutDiscards);
20665 					if (need_decref)
20666 						CONN_DEC_REF(connp);
20667 					return;
20668 				} else {
20669 					ASSERT(mp->b_datap->db_type == M_CTL);
20670 					first_mp = mp;
20671 					mp = mp->b_cont;
20672 					mctl_present = B_TRUE;
20673 				}
20674 			} else {
20675 				first_mp = mp;
20676 				mctl_present = B_FALSE;
20677 			}
20678 		}
20679 	}
20680 #endif
20681 
20682 	/* Most of the code below is written for speed, not readability */
20683 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20684 
20685 	/*
20686 	 * If ip_newroute() fails, we're going to need a full
20687 	 * header for the icmp wraparound.
20688 	 */
20689 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20690 		uint_t	v_hlen;
20691 version_hdrlen_check:
20692 		ASSERT(first_mp != NULL);
20693 		v_hlen = V_HLEN;
20694 		/*
20695 		 * siphon off IPv6 packets coming down from transport
20696 		 * layer modules here.
20697 		 * Note: high-order bit carries NUD reachability confirmation
20698 		 */
20699 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20700 			/*
20701 			 * XXX implement a IPv4 and IPv6 packet counter per
20702 			 * conn and switch when ratio exceeds e.g. 10:1
20703 			 */
20704 #ifdef notyet
20705 			if (q->q_next == NULL) /* Avoid ill queue */
20706 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
20707 #endif
20708 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20709 			ASSERT(xmit_ill == NULL);
20710 			if (attach_ill != NULL)
20711 				ill_refrele(attach_ill);
20712 			if (need_decref)
20713 				mp->b_flag |= MSGHASREF;
20714 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20715 			return;
20716 		}
20717 
20718 		if ((v_hlen >> 4) != IP_VERSION) {
20719 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20720 			    "ip_wput_end: q %p (%S)", q, "badvers");
20721 			goto discard_pkt;
20722 		}
20723 		/*
20724 		 * Is the header length at least 20 bytes?
20725 		 *
20726 		 * Are there enough bytes accessible in the header?  If
20727 		 * not, try a pullup.
20728 		 */
20729 		v_hlen &= 0xF;
20730 		v_hlen <<= 2;
20731 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20732 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20733 			    "ip_wput_end: q %p (%S)", q, "badlen");
20734 			goto discard_pkt;
20735 		}
20736 		if (v_hlen > (mp->b_wptr - rptr)) {
20737 			if (!pullupmsg(mp, v_hlen)) {
20738 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20739 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20740 				goto discard_pkt;
20741 			}
20742 			ipha = (ipha_t *)mp->b_rptr;
20743 		}
20744 		/*
20745 		 * Move first entry from any source route into ipha_dst and
20746 		 * verify the options
20747 		 */
20748 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20749 		    zoneid, ipst)) {
20750 			ASSERT(xmit_ill == NULL);
20751 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20752 			if (attach_ill != NULL)
20753 				ill_refrele(attach_ill);
20754 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20755 			    "ip_wput_end: q %p (%S)", q, "badopts");
20756 			if (need_decref)
20757 				CONN_DEC_REF(connp);
20758 			return;
20759 		}
20760 	}
20761 	dst = ipha->ipha_dst;
20762 
20763 	/*
20764 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20765 	 * we have to run the packet through ip_newroute which will take
20766 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20767 	 * a resolver, or assigning a default gateway, etc.
20768 	 */
20769 	if (CLASSD(dst)) {
20770 		ipif_t	*ipif;
20771 		uint32_t setsrc = 0;
20772 
20773 multicast:
20774 		ASSERT(first_mp != NULL);
20775 		ip2dbg(("ip_wput: CLASSD\n"));
20776 		if (connp == NULL) {
20777 			/*
20778 			 * Use the first good ipif on the ill.
20779 			 * XXX Should this ever happen? (Appears
20780 			 * to show up with just ppp and no ethernet due
20781 			 * to in.rdisc.)
20782 			 * However, ire_send should be able to
20783 			 * call ip_wput_ire directly.
20784 			 *
20785 			 * XXX Also, this can happen for ICMP and other packets
20786 			 * with multicast source addresses.  Perhaps we should
20787 			 * fix things so that we drop the packet in question,
20788 			 * but for now, just run with it.
20789 			 */
20790 			ill_t *ill = (ill_t *)q->q_ptr;
20791 
20792 			/*
20793 			 * Don't honor attach_if for this case. If ill
20794 			 * is part of the group, ipif could belong to
20795 			 * any ill and we cannot maintain attach_ill
20796 			 * and ipif_ill same anymore and the assert
20797 			 * below would fail.
20798 			 */
20799 			if (mctl_present && io->ipsec_out_attach_if) {
20800 				io->ipsec_out_ill_index = 0;
20801 				io->ipsec_out_attach_if = B_FALSE;
20802 				ASSERT(attach_ill != NULL);
20803 				ill_refrele(attach_ill);
20804 				attach_ill = NULL;
20805 			}
20806 
20807 			ASSERT(attach_ill == NULL);
20808 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20809 			if (ipif == NULL) {
20810 				if (need_decref)
20811 					CONN_DEC_REF(connp);
20812 				freemsg(first_mp);
20813 				return;
20814 			}
20815 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20816 			    ntohl(dst), ill->ill_name));
20817 		} else {
20818 			/*
20819 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
20820 			 * and IP_MULTICAST_IF.
20821 			 * Block comment above this function explains the
20822 			 * locking mechanism used here
20823 			 */
20824 			if (xmit_ill == NULL) {
20825 				xmit_ill = conn_get_held_ill(connp,
20826 				    &connp->conn_xmit_if_ill, &err);
20827 				if (err == ILL_LOOKUP_FAILED) {
20828 					ip1dbg(("ip_wput: No ill for "
20829 					    "IP_XMIT_IF\n"));
20830 					BUMP_MIB(&ipst->ips_ip_mib,
20831 					    ipIfStatsOutNoRoutes);
20832 					goto drop_pkt;
20833 				}
20834 			}
20835 
20836 			if (xmit_ill == NULL) {
20837 				ipif = conn_get_held_ipif(connp,
20838 				    &connp->conn_multicast_ipif, &err);
20839 				if (err == IPIF_LOOKUP_FAILED) {
20840 					ip1dbg(("ip_wput: No ipif for "
20841 					    "multicast\n"));
20842 					BUMP_MIB(&ipst->ips_ip_mib,
20843 					    ipIfStatsOutNoRoutes);
20844 					goto drop_pkt;
20845 				}
20846 			}
20847 			if (xmit_ill != NULL) {
20848 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20849 				if (ipif == NULL) {
20850 					ip1dbg(("ip_wput: No ipif for "
20851 					    "IP_XMIT_IF\n"));
20852 					BUMP_MIB(&ipst->ips_ip_mib,
20853 					    ipIfStatsOutNoRoutes);
20854 					goto drop_pkt;
20855 				}
20856 			} else if (ipif == NULL || ipif->ipif_isv6) {
20857 				/*
20858 				 * We must do this ipif determination here
20859 				 * else we could pass through ip_newroute
20860 				 * and come back here without the conn context.
20861 				 *
20862 				 * Note: we do late binding i.e. we bind to
20863 				 * the interface when the first packet is sent.
20864 				 * For performance reasons we do not rebind on
20865 				 * each packet but keep the binding until the
20866 				 * next IP_MULTICAST_IF option.
20867 				 *
20868 				 * conn_multicast_{ipif,ill} are shared between
20869 				 * IPv4 and IPv6 and AF_INET6 sockets can
20870 				 * send both IPv4 and IPv6 packets. Hence
20871 				 * we have to check that "isv6" matches above.
20872 				 */
20873 				if (ipif != NULL)
20874 					ipif_refrele(ipif);
20875 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20876 				if (ipif == NULL) {
20877 					ip1dbg(("ip_wput: No ipif for "
20878 					    "multicast\n"));
20879 					BUMP_MIB(&ipst->ips_ip_mib,
20880 					    ipIfStatsOutNoRoutes);
20881 					goto drop_pkt;
20882 				}
20883 				err = conn_set_held_ipif(connp,
20884 				    &connp->conn_multicast_ipif, ipif);
20885 				if (err == IPIF_LOOKUP_FAILED) {
20886 					ipif_refrele(ipif);
20887 					ip1dbg(("ip_wput: No ipif for "
20888 					    "multicast\n"));
20889 					BUMP_MIB(&ipst->ips_ip_mib,
20890 					    ipIfStatsOutNoRoutes);
20891 					goto drop_pkt;
20892 				}
20893 			}
20894 		}
20895 		ASSERT(!ipif->ipif_isv6);
20896 		/*
20897 		 * As we may lose the conn by the time we reach ip_wput_ire,
20898 		 * we copy conn_multicast_loop and conn_dontroute on to an
20899 		 * ipsec_out. In case if this datagram goes out secure,
20900 		 * we need the ill_index also. Copy that also into the
20901 		 * ipsec_out.
20902 		 */
20903 		if (mctl_present) {
20904 			io = (ipsec_out_t *)first_mp->b_rptr;
20905 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20906 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20907 		} else {
20908 			ASSERT(mp == first_mp);
20909 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20910 			    BPRI_HI)) == NULL) {
20911 				ipif_refrele(ipif);
20912 				first_mp = mp;
20913 				goto discard_pkt;
20914 			}
20915 			first_mp->b_datap->db_type = M_CTL;
20916 			first_mp->b_wptr += sizeof (ipsec_info_t);
20917 			/* ipsec_out_secure is B_FALSE now */
20918 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20919 			io = (ipsec_out_t *)first_mp->b_rptr;
20920 			io->ipsec_out_type = IPSEC_OUT;
20921 			io->ipsec_out_len = sizeof (ipsec_out_t);
20922 			io->ipsec_out_use_global_policy = B_TRUE;
20923 			io->ipsec_out_ns = ipst->ips_netstack;
20924 			first_mp->b_cont = mp;
20925 			mctl_present = B_TRUE;
20926 		}
20927 		if (attach_ill != NULL) {
20928 			ASSERT(attach_ill == ipif->ipif_ill);
20929 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20930 
20931 			/*
20932 			 * Check if we need an ire that will not be
20933 			 * looked up by anybody else i.e. HIDDEN.
20934 			 */
20935 			if (ill_is_probeonly(attach_ill)) {
20936 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20937 			}
20938 			io->ipsec_out_ill_index =
20939 			    attach_ill->ill_phyint->phyint_ifindex;
20940 			io->ipsec_out_attach_if = B_TRUE;
20941 		} else {
20942 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20943 			io->ipsec_out_ill_index =
20944 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20945 		}
20946 		if (connp != NULL) {
20947 			io->ipsec_out_multicast_loop =
20948 			    connp->conn_multicast_loop;
20949 			io->ipsec_out_dontroute = connp->conn_dontroute;
20950 			io->ipsec_out_zoneid = connp->conn_zoneid;
20951 		}
20952 		/*
20953 		 * If the application uses IP_MULTICAST_IF with
20954 		 * different logical addresses of the same ILL, we
20955 		 * need to make sure that the soruce address of
20956 		 * the packet matches the logical IP address used
20957 		 * in the option. We do it by initializing ipha_src
20958 		 * here. This should keep IPsec also happy as
20959 		 * when we return from IPsec processing, we don't
20960 		 * have to worry about getting the right address on
20961 		 * the packet. Thus it is sufficient to look for
20962 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20963 		 * MATCH_IRE_IPIF.
20964 		 *
20965 		 * NOTE : We need to do it for non-secure case also as
20966 		 * this might go out secure if there is a global policy
20967 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20968 		 * address, the source should be initialized already and
20969 		 * hence we won't be initializing here.
20970 		 *
20971 		 * As we do not have the ire yet, it is possible that
20972 		 * we set the source address here and then later discover
20973 		 * that the ire implies the source address to be assigned
20974 		 * through the RTF_SETSRC flag.
20975 		 * In that case, the setsrc variable will remind us
20976 		 * that overwritting the source address by the one
20977 		 * of the RTF_SETSRC-flagged ire is allowed.
20978 		 */
20979 		if (ipha->ipha_src == INADDR_ANY &&
20980 		    (connp == NULL || !connp->conn_unspec_src)) {
20981 			ipha->ipha_src = ipif->ipif_src_addr;
20982 			setsrc = RTF_SETSRC;
20983 		}
20984 		/*
20985 		 * Find an IRE which matches the destination and the outgoing
20986 		 * queue (i.e. the outgoing interface.)
20987 		 * For loopback use a unicast IP address for
20988 		 * the ire lookup.
20989 		 */
20990 		if (IS_LOOPBACK(ipif->ipif_ill))
20991 			dst = ipif->ipif_lcl_addr;
20992 
20993 		/*
20994 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20995 		 * We don't need to lookup ire in ctable as the packet
20996 		 * needs to be sent to the destination through the specified
20997 		 * ill irrespective of ires in the cache table.
20998 		 */
20999 		ire = NULL;
21000 		if (xmit_ill == NULL) {
21001 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21002 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21003 		}
21004 
21005 		/*
21006 		 * refrele attach_ill as its not needed anymore.
21007 		 */
21008 		if (attach_ill != NULL) {
21009 			ill_refrele(attach_ill);
21010 			attach_ill = NULL;
21011 		}
21012 
21013 		if (ire == NULL) {
21014 			/*
21015 			 * Multicast loopback and multicast forwarding is
21016 			 * done in ip_wput_ire.
21017 			 *
21018 			 * Mark this packet to make it be delivered to
21019 			 * ip_wput_ire after the new ire has been
21020 			 * created.
21021 			 *
21022 			 * The call to ip_newroute_ipif takes into account
21023 			 * the setsrc reminder. In any case, we take care
21024 			 * of the RTF_MULTIRT flag.
21025 			 */
21026 			mp->b_prev = mp->b_next = NULL;
21027 			if (xmit_ill == NULL ||
21028 			    xmit_ill->ill_ipif_up_count > 0) {
21029 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21030 				    setsrc | RTF_MULTIRT, zoneid, infop);
21031 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21032 				    "ip_wput_end: q %p (%S)", q, "noire");
21033 			} else {
21034 				freemsg(first_mp);
21035 			}
21036 			ipif_refrele(ipif);
21037 			if (xmit_ill != NULL)
21038 				ill_refrele(xmit_ill);
21039 			if (need_decref)
21040 				CONN_DEC_REF(connp);
21041 			return;
21042 		}
21043 
21044 		ipif_refrele(ipif);
21045 		ipif = NULL;
21046 		ASSERT(xmit_ill == NULL);
21047 
21048 		/*
21049 		 * Honor the RTF_SETSRC flag for multicast packets,
21050 		 * if allowed by the setsrc reminder.
21051 		 */
21052 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21053 			ipha->ipha_src = ire->ire_src_addr;
21054 		}
21055 
21056 		/*
21057 		 * Unconditionally force the TTL to 1 for
21058 		 * multirouted multicast packets:
21059 		 * multirouted multicast should not cross
21060 		 * multicast routers.
21061 		 */
21062 		if (ire->ire_flags & RTF_MULTIRT) {
21063 			if (ipha->ipha_ttl > 1) {
21064 				ip2dbg(("ip_wput: forcing multicast "
21065 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21066 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21067 				ipha->ipha_ttl = 1;
21068 			}
21069 		}
21070 	} else {
21071 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21072 		if ((ire != NULL) && (ire->ire_type &
21073 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21074 			ignore_dontroute = B_TRUE;
21075 			ignore_nexthop = B_TRUE;
21076 		}
21077 		if (ire != NULL) {
21078 			ire_refrele(ire);
21079 			ire = NULL;
21080 		}
21081 		/*
21082 		 * Guard against coming in from arp in which case conn is NULL.
21083 		 * Also guard against non M_DATA with dontroute set but
21084 		 * destined to local, loopback or broadcast addresses.
21085 		 */
21086 		if (connp != NULL && connp->conn_dontroute &&
21087 		    !ignore_dontroute) {
21088 dontroute:
21089 			/*
21090 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21091 			 * routing protocols from seeing false direct
21092 			 * connectivity.
21093 			 */
21094 			ipha->ipha_ttl = 1;
21095 			/*
21096 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21097 			 * along with SO_DONTROUTE, higher precedence is
21098 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21099 			 */
21100 			if (connp->conn_xmit_if_ill == NULL) {
21101 				/* If suitable ipif not found, drop packet */
21102 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21103 				    ipst);
21104 				if (dst_ipif == NULL) {
21105 					ip1dbg(("ip_wput: no route for "
21106 					    "dst using SO_DONTROUTE\n"));
21107 					BUMP_MIB(&ipst->ips_ip_mib,
21108 					    ipIfStatsOutNoRoutes);
21109 					mp->b_prev = mp->b_next = NULL;
21110 					if (first_mp == NULL)
21111 						first_mp = mp;
21112 					goto drop_pkt;
21113 				} else {
21114 					/*
21115 					 * If suitable ipif has been found, set
21116 					 * xmit_ill to the corresponding
21117 					 * ipif_ill because we'll be following
21118 					 * the IP_XMIT_IF logic.
21119 					 */
21120 					ASSERT(xmit_ill == NULL);
21121 					xmit_ill = dst_ipif->ipif_ill;
21122 					mutex_enter(&xmit_ill->ill_lock);
21123 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21124 						mutex_exit(&xmit_ill->ill_lock);
21125 						xmit_ill = NULL;
21126 						ipif_refrele(dst_ipif);
21127 						ip1dbg(("ip_wput: no route for"
21128 						    " dst using"
21129 						    " SO_DONTROUTE\n"));
21130 						BUMP_MIB(&ipst->ips_ip_mib,
21131 						    ipIfStatsOutNoRoutes);
21132 						mp->b_prev = mp->b_next = NULL;
21133 						if (first_mp == NULL)
21134 							first_mp = mp;
21135 						goto drop_pkt;
21136 					}
21137 					ill_refhold_locked(xmit_ill);
21138 					mutex_exit(&xmit_ill->ill_lock);
21139 					ipif_refrele(dst_ipif);
21140 				}
21141 			}
21142 
21143 		}
21144 		/*
21145 		 * If we are bound to IPIF_NOFAILOVER address, look for
21146 		 * an IRE_CACHE matching the ill.
21147 		 */
21148 send_from_ill:
21149 		if (attach_ill != NULL) {
21150 			ipif_t	*attach_ipif;
21151 
21152 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21153 
21154 			/*
21155 			 * Check if we need an ire that will not be
21156 			 * looked up by anybody else i.e. HIDDEN.
21157 			 */
21158 			if (ill_is_probeonly(attach_ill)) {
21159 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21160 			}
21161 
21162 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21163 			if (attach_ipif == NULL) {
21164 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21165 				goto discard_pkt;
21166 			}
21167 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21168 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21169 			ipif_refrele(attach_ipif);
21170 		} else if (xmit_ill != NULL || (connp != NULL &&
21171 		    connp->conn_xmit_if_ill != NULL)) {
21172 			/*
21173 			 * Mark this packet as originated locally
21174 			 */
21175 			mp->b_prev = mp->b_next = NULL;
21176 			/*
21177 			 * xmit_ill could be NULL if SO_DONTROUTE
21178 			 * is also set.
21179 			 */
21180 			if (xmit_ill == NULL) {
21181 				xmit_ill = conn_get_held_ill(connp,
21182 				    &connp->conn_xmit_if_ill, &err);
21183 				if (err == ILL_LOOKUP_FAILED) {
21184 					BUMP_MIB(&ipst->ips_ip_mib,
21185 					    ipIfStatsOutDiscards);
21186 					if (need_decref)
21187 						CONN_DEC_REF(connp);
21188 					freemsg(first_mp);
21189 					return;
21190 				}
21191 				if (xmit_ill == NULL) {
21192 					if (connp->conn_dontroute)
21193 						goto dontroute;
21194 					goto send_from_ill;
21195 				}
21196 			}
21197 			/*
21198 			 * Could be SO_DONTROUTE case also.
21199 			 * check at least one interface is UP as
21200 			 * specified by this ILL
21201 			 */
21202 			if (xmit_ill->ill_ipif_up_count > 0) {
21203 				ipif_t *ipif;
21204 
21205 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21206 				if (ipif == NULL) {
21207 					ip1dbg(("ip_output: "
21208 					    "xmit_ill NULL ipif\n"));
21209 					goto drop_pkt;
21210 				}
21211 				/*
21212 				 * Look for a ire that is part of the group,
21213 				 * if found use it else call ip_newroute_ipif.
21214 				 * IPCL_ZONEID is not used for matching because
21215 				 * IP_ALLZONES option is valid only when the
21216 				 * ill is accessible from all zones i.e has a
21217 				 * valid ipif in all zones.
21218 				 */
21219 				match_flags = MATCH_IRE_ILL_GROUP |
21220 				    MATCH_IRE_SECATTR;
21221 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21222 				    MBLK_GETLABEL(mp), match_flags, ipst);
21223 				/*
21224 				 * If an ire exists use it or else create
21225 				 * an ire but don't add it to the cache.
21226 				 * Adding an ire may cause issues with
21227 				 * asymmetric routing.
21228 				 * In case of multiroute always act as if
21229 				 * ire does not exist.
21230 				 */
21231 				if (ire == NULL ||
21232 				    ire->ire_flags & RTF_MULTIRT) {
21233 					if (ire != NULL)
21234 						ire_refrele(ire);
21235 					ip_newroute_ipif(q, first_mp, ipif,
21236 					    dst, connp, 0, zoneid, infop);
21237 					ipif_refrele(ipif);
21238 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21239 					ill_refrele(xmit_ill);
21240 					if (need_decref)
21241 						CONN_DEC_REF(connp);
21242 					return;
21243 				}
21244 				ipif_refrele(ipif);
21245 			} else {
21246 				goto drop_pkt;
21247 			}
21248 		} else if (ip_nexthop || (connp != NULL &&
21249 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21250 			if (!ip_nexthop) {
21251 				ip_nexthop = B_TRUE;
21252 				nexthop_addr = connp->conn_nexthop_v4;
21253 			}
21254 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21255 			    MATCH_IRE_GW;
21256 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21257 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21258 		} else {
21259 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21260 			    ipst);
21261 		}
21262 		if (!ire) {
21263 			/*
21264 			 * Make sure we don't load spread if this
21265 			 * is IPIF_NOFAILOVER case.
21266 			 */
21267 			if ((attach_ill != NULL) ||
21268 			    (ip_nexthop && !ignore_nexthop)) {
21269 				if (mctl_present) {
21270 					io = (ipsec_out_t *)first_mp->b_rptr;
21271 					ASSERT(first_mp->b_datap->db_type ==
21272 					    M_CTL);
21273 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21274 				} else {
21275 					ASSERT(mp == first_mp);
21276 					first_mp = allocb(
21277 					    sizeof (ipsec_info_t), BPRI_HI);
21278 					if (first_mp == NULL) {
21279 						first_mp = mp;
21280 						goto discard_pkt;
21281 					}
21282 					first_mp->b_datap->db_type = M_CTL;
21283 					first_mp->b_wptr +=
21284 					    sizeof (ipsec_info_t);
21285 					/* ipsec_out_secure is B_FALSE now */
21286 					bzero(first_mp->b_rptr,
21287 					    sizeof (ipsec_info_t));
21288 					io = (ipsec_out_t *)first_mp->b_rptr;
21289 					io->ipsec_out_type = IPSEC_OUT;
21290 					io->ipsec_out_len =
21291 					    sizeof (ipsec_out_t);
21292 					io->ipsec_out_use_global_policy =
21293 					    B_TRUE;
21294 					io->ipsec_out_ns = ipst->ips_netstack;
21295 					first_mp->b_cont = mp;
21296 					mctl_present = B_TRUE;
21297 				}
21298 				if (attach_ill != NULL) {
21299 					io->ipsec_out_ill_index = attach_ill->
21300 					    ill_phyint->phyint_ifindex;
21301 					io->ipsec_out_attach_if = B_TRUE;
21302 				} else {
21303 					io->ipsec_out_ip_nexthop = ip_nexthop;
21304 					io->ipsec_out_nexthop_addr =
21305 					    nexthop_addr;
21306 				}
21307 			}
21308 noirefound:
21309 			/*
21310 			 * Mark this packet as having originated on
21311 			 * this machine.  This will be noted in
21312 			 * ire_add_then_send, which needs to know
21313 			 * whether to run it back through ip_wput or
21314 			 * ip_rput following successful resolution.
21315 			 */
21316 			mp->b_prev = NULL;
21317 			mp->b_next = NULL;
21318 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21319 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21320 			    "ip_wput_end: q %p (%S)", q, "newroute");
21321 			if (attach_ill != NULL)
21322 				ill_refrele(attach_ill);
21323 			if (xmit_ill != NULL)
21324 				ill_refrele(xmit_ill);
21325 			if (need_decref)
21326 				CONN_DEC_REF(connp);
21327 			return;
21328 		}
21329 	}
21330 
21331 	/* We now know where we are going with it. */
21332 
21333 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21334 	    "ip_wput_end: q %p (%S)", q, "end");
21335 
21336 	/*
21337 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21338 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21339 	 */
21340 	if (ire->ire_flags & RTF_MULTIRT) {
21341 		/*
21342 		 * Force the TTL of multirouted packets if required.
21343 		 * The TTL of such packets is bounded by the
21344 		 * ip_multirt_ttl ndd variable.
21345 		 */
21346 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21347 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21348 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21349 			    "(was %d), dst 0x%08x\n",
21350 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21351 			    ntohl(ire->ire_addr)));
21352 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21353 		}
21354 		/*
21355 		 * At this point, we check to see if there are any pending
21356 		 * unresolved routes. ire_multirt_resolvable()
21357 		 * checks in O(n) that all IRE_OFFSUBNET ire
21358 		 * entries for the packet's destination and
21359 		 * flagged RTF_MULTIRT are currently resolved.
21360 		 * If some remain unresolved, we make a copy
21361 		 * of the current message. It will be used
21362 		 * to initiate additional route resolutions.
21363 		 */
21364 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21365 		    MBLK_GETLABEL(first_mp), ipst);
21366 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21367 		    "multirt_need_resolve %d, first_mp %p\n",
21368 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21369 		if (multirt_need_resolve) {
21370 			copy_mp = copymsg(first_mp);
21371 			if (copy_mp != NULL) {
21372 				MULTIRT_DEBUG_TAG(copy_mp);
21373 			}
21374 		}
21375 	}
21376 
21377 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21378 	/*
21379 	 * Try to resolve another multiroute if
21380 	 * ire_multirt_resolvable() deemed it necessary.
21381 	 * At this point, we need to distinguish
21382 	 * multicasts from other packets. For multicasts,
21383 	 * we call ip_newroute_ipif() and request that both
21384 	 * multirouting and setsrc flags are checked.
21385 	 */
21386 	if (copy_mp != NULL) {
21387 		if (CLASSD(dst)) {
21388 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21389 			if (ipif) {
21390 				ASSERT(infop->ip_opt_ill_index == 0);
21391 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21392 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21393 				ipif_refrele(ipif);
21394 			} else {
21395 				MULTIRT_DEBUG_UNTAG(copy_mp);
21396 				freemsg(copy_mp);
21397 				copy_mp = NULL;
21398 			}
21399 		} else {
21400 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21401 		}
21402 	}
21403 	if (attach_ill != NULL)
21404 		ill_refrele(attach_ill);
21405 	if (xmit_ill != NULL)
21406 		ill_refrele(xmit_ill);
21407 	if (need_decref)
21408 		CONN_DEC_REF(connp);
21409 	return;
21410 
21411 icmp_parameter_problem:
21412 	/* could not have originated externally */
21413 	ASSERT(mp->b_prev == NULL);
21414 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21415 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21416 		/* it's the IP header length that's in trouble */
21417 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21418 		first_mp = NULL;
21419 	}
21420 
21421 discard_pkt:
21422 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21423 drop_pkt:
21424 	ip1dbg(("ip_wput: dropped packet\n"));
21425 	if (ire != NULL)
21426 		ire_refrele(ire);
21427 	if (need_decref)
21428 		CONN_DEC_REF(connp);
21429 	freemsg(first_mp);
21430 	if (attach_ill != NULL)
21431 		ill_refrele(attach_ill);
21432 	if (xmit_ill != NULL)
21433 		ill_refrele(xmit_ill);
21434 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21435 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21436 }
21437 
21438 /*
21439  * If this is a conn_t queue, then we pass in the conn. This includes the
21440  * zoneid.
21441  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21442  * in which case we use the global zoneid since those are all part of
21443  * the global zone.
21444  */
21445 void
21446 ip_wput(queue_t *q, mblk_t *mp)
21447 {
21448 	if (CONN_Q(q))
21449 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21450 	else
21451 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21452 }
21453 
21454 /*
21455  *
21456  * The following rules must be observed when accessing any ipif or ill
21457  * that has been cached in the conn. Typically conn_nofailover_ill,
21458  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21459  *
21460  * Access: The ipif or ill pointed to from the conn can be accessed under
21461  * the protection of the conn_lock or after it has been refheld under the
21462  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21463  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21464  * The reason for this is that a concurrent unplumb could actually be
21465  * cleaning up these cached pointers by walking the conns and might have
21466  * finished cleaning up the conn in question. The macros check that an
21467  * unplumb has not yet started on the ipif or ill.
21468  *
21469  * Caching: An ipif or ill pointer may be cached in the conn only after
21470  * making sure that an unplumb has not started. So the caching is done
21471  * while holding both the conn_lock and the ill_lock and after using the
21472  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21473  * flag before starting the cleanup of conns.
21474  *
21475  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21476  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21477  * or a reference to the ipif or a reference to an ire that references the
21478  * ipif. An ipif does not change its ill except for failover/failback. Since
21479  * failover/failback happens only after bringing down the ipif and making sure
21480  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21481  * the above holds.
21482  */
21483 ipif_t *
21484 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21485 {
21486 	ipif_t	*ipif;
21487 	ill_t	*ill;
21488 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21489 
21490 	*err = 0;
21491 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21492 	mutex_enter(&connp->conn_lock);
21493 	ipif = *ipifp;
21494 	if (ipif != NULL) {
21495 		ill = ipif->ipif_ill;
21496 		mutex_enter(&ill->ill_lock);
21497 		if (IPIF_CAN_LOOKUP(ipif)) {
21498 			ipif_refhold_locked(ipif);
21499 			mutex_exit(&ill->ill_lock);
21500 			mutex_exit(&connp->conn_lock);
21501 			rw_exit(&ipst->ips_ill_g_lock);
21502 			return (ipif);
21503 		} else {
21504 			*err = IPIF_LOOKUP_FAILED;
21505 		}
21506 		mutex_exit(&ill->ill_lock);
21507 	}
21508 	mutex_exit(&connp->conn_lock);
21509 	rw_exit(&ipst->ips_ill_g_lock);
21510 	return (NULL);
21511 }
21512 
21513 ill_t *
21514 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21515 {
21516 	ill_t	*ill;
21517 
21518 	*err = 0;
21519 	mutex_enter(&connp->conn_lock);
21520 	ill = *illp;
21521 	if (ill != NULL) {
21522 		mutex_enter(&ill->ill_lock);
21523 		if (ILL_CAN_LOOKUP(ill)) {
21524 			ill_refhold_locked(ill);
21525 			mutex_exit(&ill->ill_lock);
21526 			mutex_exit(&connp->conn_lock);
21527 			return (ill);
21528 		} else {
21529 			*err = ILL_LOOKUP_FAILED;
21530 		}
21531 		mutex_exit(&ill->ill_lock);
21532 	}
21533 	mutex_exit(&connp->conn_lock);
21534 	return (NULL);
21535 }
21536 
21537 static int
21538 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21539 {
21540 	ill_t	*ill;
21541 
21542 	ill = ipif->ipif_ill;
21543 	mutex_enter(&connp->conn_lock);
21544 	mutex_enter(&ill->ill_lock);
21545 	if (IPIF_CAN_LOOKUP(ipif)) {
21546 		*ipifp = ipif;
21547 		mutex_exit(&ill->ill_lock);
21548 		mutex_exit(&connp->conn_lock);
21549 		return (0);
21550 	}
21551 	mutex_exit(&ill->ill_lock);
21552 	mutex_exit(&connp->conn_lock);
21553 	return (IPIF_LOOKUP_FAILED);
21554 }
21555 
21556 /*
21557  * This is called if the outbound datagram needs fragmentation.
21558  *
21559  * NOTE : This function does not ire_refrele the ire argument passed in.
21560  */
21561 static void
21562 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21563     ip_stack_t *ipst)
21564 {
21565 	ipha_t		*ipha;
21566 	mblk_t		*mp;
21567 	uint32_t	v_hlen_tos_len;
21568 	uint32_t	max_frag;
21569 	uint32_t	frag_flag;
21570 	boolean_t	dont_use;
21571 
21572 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21573 		mp = ipsec_mp->b_cont;
21574 	} else {
21575 		mp = ipsec_mp;
21576 	}
21577 
21578 	ipha = (ipha_t *)mp->b_rptr;
21579 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21580 
21581 #ifdef	_BIG_ENDIAN
21582 #define	V_HLEN	(v_hlen_tos_len >> 24)
21583 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21584 #else
21585 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21586 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21587 #endif
21588 
21589 #ifndef SPEED_BEFORE_SAFETY
21590 	/*
21591 	 * Check that ipha_length is consistent with
21592 	 * the mblk length
21593 	 */
21594 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21595 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21596 		    LENGTH, msgdsize(mp)));
21597 		freemsg(ipsec_mp);
21598 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21599 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21600 		    "packet length mismatch");
21601 		return;
21602 	}
21603 #endif
21604 	/*
21605 	 * Don't use frag_flag if pre-built packet or source
21606 	 * routed or if multicast (since multicast packets do not solicit
21607 	 * ICMP "packet too big" messages). Get the values of
21608 	 * max_frag and frag_flag atomically by acquiring the
21609 	 * ire_lock.
21610 	 */
21611 	mutex_enter(&ire->ire_lock);
21612 	max_frag = ire->ire_max_frag;
21613 	frag_flag = ire->ire_frag_flag;
21614 	mutex_exit(&ire->ire_lock);
21615 
21616 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21617 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21618 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21619 
21620 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21621 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21622 }
21623 
21624 /*
21625  * Used for deciding the MSS size for the upper layer. Thus
21626  * we need to check the outbound policy values in the conn.
21627  */
21628 int
21629 conn_ipsec_length(conn_t *connp)
21630 {
21631 	ipsec_latch_t *ipl;
21632 
21633 	ipl = connp->conn_latch;
21634 	if (ipl == NULL)
21635 		return (0);
21636 
21637 	if (ipl->ipl_out_policy == NULL)
21638 		return (0);
21639 
21640 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21641 }
21642 
21643 /*
21644  * Returns an estimate of the IPsec headers size. This is used if
21645  * we don't want to call into IPsec to get the exact size.
21646  */
21647 int
21648 ipsec_out_extra_length(mblk_t *ipsec_mp)
21649 {
21650 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21651 	ipsec_action_t *a;
21652 
21653 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21654 	if (!io->ipsec_out_secure)
21655 		return (0);
21656 
21657 	a = io->ipsec_out_act;
21658 
21659 	if (a == NULL) {
21660 		ASSERT(io->ipsec_out_policy != NULL);
21661 		a = io->ipsec_out_policy->ipsp_act;
21662 	}
21663 	ASSERT(a != NULL);
21664 
21665 	return (a->ipa_ovhd);
21666 }
21667 
21668 /*
21669  * Returns an estimate of the IPsec headers size. This is used if
21670  * we don't want to call into IPsec to get the exact size.
21671  */
21672 int
21673 ipsec_in_extra_length(mblk_t *ipsec_mp)
21674 {
21675 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21676 	ipsec_action_t *a;
21677 
21678 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21679 
21680 	a = ii->ipsec_in_action;
21681 	return (a == NULL ? 0 : a->ipa_ovhd);
21682 }
21683 
21684 /*
21685  * If there are any source route options, return the true final
21686  * destination. Otherwise, return the destination.
21687  */
21688 ipaddr_t
21689 ip_get_dst(ipha_t *ipha)
21690 {
21691 	ipoptp_t	opts;
21692 	uchar_t		*opt;
21693 	uint8_t		optval;
21694 	uint8_t		optlen;
21695 	ipaddr_t	dst;
21696 	uint32_t off;
21697 
21698 	dst = ipha->ipha_dst;
21699 
21700 	if (IS_SIMPLE_IPH(ipha))
21701 		return (dst);
21702 
21703 	for (optval = ipoptp_first(&opts, ipha);
21704 	    optval != IPOPT_EOL;
21705 	    optval = ipoptp_next(&opts)) {
21706 		opt = opts.ipoptp_cur;
21707 		optlen = opts.ipoptp_len;
21708 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21709 		switch (optval) {
21710 		case IPOPT_SSRR:
21711 		case IPOPT_LSRR:
21712 			off = opt[IPOPT_OFFSET];
21713 			/*
21714 			 * If one of the conditions is true, it means
21715 			 * end of options and dst already has the right
21716 			 * value.
21717 			 */
21718 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21719 				off = optlen - IP_ADDR_LEN;
21720 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21721 			}
21722 			return (dst);
21723 		default:
21724 			break;
21725 		}
21726 	}
21727 
21728 	return (dst);
21729 }
21730 
21731 mblk_t *
21732 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21733     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21734 {
21735 	ipsec_out_t	*io;
21736 	mblk_t		*first_mp;
21737 	boolean_t policy_present;
21738 	ip_stack_t	*ipst;
21739 	ipsec_stack_t	*ipss;
21740 
21741 	ASSERT(ire != NULL);
21742 	ipst = ire->ire_ipst;
21743 	ipss = ipst->ips_netstack->netstack_ipsec;
21744 
21745 	first_mp = mp;
21746 	if (mp->b_datap->db_type == M_CTL) {
21747 		io = (ipsec_out_t *)first_mp->b_rptr;
21748 		/*
21749 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21750 		 *
21751 		 * 1) There is per-socket policy (including cached global
21752 		 *    policy) or a policy on the IP-in-IP tunnel.
21753 		 * 2) There is no per-socket policy, but it is
21754 		 *    a multicast packet that needs to go out
21755 		 *    on a specific interface. This is the case
21756 		 *    where (ip_wput and ip_wput_multicast) attaches
21757 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21758 		 *
21759 		 * In case (2) we check with global policy to
21760 		 * see if there is a match and set the ill_index
21761 		 * appropriately so that we can lookup the ire
21762 		 * properly in ip_wput_ipsec_out.
21763 		 */
21764 
21765 		/*
21766 		 * ipsec_out_use_global_policy is set to B_FALSE
21767 		 * in ipsec_in_to_out(). Refer to that function for
21768 		 * details.
21769 		 */
21770 		if ((io->ipsec_out_latch == NULL) &&
21771 		    (io->ipsec_out_use_global_policy)) {
21772 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21773 			    ire, connp, unspec_src, zoneid));
21774 		}
21775 		if (!io->ipsec_out_secure) {
21776 			/*
21777 			 * If this is not a secure packet, drop
21778 			 * the IPSEC_OUT mp and treat it as a clear
21779 			 * packet. This happens when we are sending
21780 			 * a ICMP reply back to a clear packet. See
21781 			 * ipsec_in_to_out() for details.
21782 			 */
21783 			mp = first_mp->b_cont;
21784 			freeb(first_mp);
21785 		}
21786 		return (mp);
21787 	}
21788 	/*
21789 	 * See whether we need to attach a global policy here. We
21790 	 * don't depend on the conn (as it could be null) for deciding
21791 	 * what policy this datagram should go through because it
21792 	 * should have happened in ip_wput if there was some
21793 	 * policy. This normally happens for connections which are not
21794 	 * fully bound preventing us from caching policies in
21795 	 * ip_bind. Packets coming from the TCP listener/global queue
21796 	 * - which are non-hard_bound - could also be affected by
21797 	 * applying policy here.
21798 	 *
21799 	 * If this packet is coming from tcp global queue or listener,
21800 	 * we will be applying policy here.  This may not be *right*
21801 	 * if these packets are coming from the detached connection as
21802 	 * it could have gone in clear before. This happens only if a
21803 	 * TCP connection started when there is no policy and somebody
21804 	 * added policy before it became detached. Thus packets of the
21805 	 * detached connection could go out secure and the other end
21806 	 * would drop it because it will be expecting in clear. The
21807 	 * converse is not true i.e if somebody starts a TCP
21808 	 * connection and deletes the policy, all the packets will
21809 	 * still go out with the policy that existed before deleting
21810 	 * because ip_unbind sends up policy information which is used
21811 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21812 	 * TCP to attach a dummy IPSEC_OUT and set
21813 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21814 	 * affect performance for normal cases, we are not doing it.
21815 	 * Thus, set policy before starting any TCP connections.
21816 	 *
21817 	 * NOTE - We might apply policy even for a hard bound connection
21818 	 * - for which we cached policy in ip_bind - if somebody added
21819 	 * global policy after we inherited the policy in ip_bind.
21820 	 * This means that the packets that were going out in clear
21821 	 * previously would start going secure and hence get dropped
21822 	 * on the other side. To fix this, TCP attaches a dummy
21823 	 * ipsec_out and make sure that we don't apply global policy.
21824 	 */
21825 	if (ipha != NULL)
21826 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21827 	else
21828 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21829 	if (!policy_present)
21830 		return (mp);
21831 
21832 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21833 	    zoneid));
21834 }
21835 
21836 ire_t *
21837 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21838 {
21839 	ipaddr_t addr;
21840 	ire_t *save_ire;
21841 	irb_t *irb;
21842 	ill_group_t *illgrp;
21843 	int	err;
21844 
21845 	save_ire = ire;
21846 	addr = ire->ire_addr;
21847 
21848 	ASSERT(ire->ire_type == IRE_BROADCAST);
21849 
21850 	illgrp = connp->conn_outgoing_ill->ill_group;
21851 	if (illgrp == NULL) {
21852 		*conn_outgoing_ill = conn_get_held_ill(connp,
21853 		    &connp->conn_outgoing_ill, &err);
21854 		if (err == ILL_LOOKUP_FAILED) {
21855 			ire_refrele(save_ire);
21856 			return (NULL);
21857 		}
21858 		return (save_ire);
21859 	}
21860 	/*
21861 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21862 	 * If it is part of the group, we need to send on the ire
21863 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21864 	 * to this group. This is okay as IP_BOUND_IF really means
21865 	 * any ill in the group. We depend on the fact that the
21866 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21867 	 * if such an ire exists. This is possible only if you have
21868 	 * at least one ill in the group that has not failed.
21869 	 *
21870 	 * First get to the ire that matches the address and group.
21871 	 *
21872 	 * We don't look for an ire with a matching zoneid because a given zone
21873 	 * won't always have broadcast ires on all ills in the group.
21874 	 */
21875 	irb = ire->ire_bucket;
21876 	rw_enter(&irb->irb_lock, RW_READER);
21877 	if (ire->ire_marks & IRE_MARK_NORECV) {
21878 		/*
21879 		 * If the current zone only has an ire broadcast for this
21880 		 * address marked NORECV, the ire we want is ahead in the
21881 		 * bucket, so we look it up deliberately ignoring the zoneid.
21882 		 */
21883 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21884 			if (ire->ire_addr != addr)
21885 				continue;
21886 			/* skip over deleted ires */
21887 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21888 				continue;
21889 		}
21890 	}
21891 	while (ire != NULL) {
21892 		/*
21893 		 * If a new interface is coming up, we could end up
21894 		 * seeing the loopback ire and the non-loopback ire
21895 		 * may not have been added yet. So check for ire_stq
21896 		 */
21897 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21898 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21899 			break;
21900 		}
21901 		ire = ire->ire_next;
21902 	}
21903 	if (ire != NULL && ire->ire_addr == addr &&
21904 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21905 		IRE_REFHOLD(ire);
21906 		rw_exit(&irb->irb_lock);
21907 		ire_refrele(save_ire);
21908 		*conn_outgoing_ill = ire_to_ill(ire);
21909 		/*
21910 		 * Refhold the ill to make the conn_outgoing_ill
21911 		 * independent of the ire. ip_wput_ire goes in a loop
21912 		 * and may refrele the ire. Since we have an ire at this
21913 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21914 		 */
21915 		ill_refhold(*conn_outgoing_ill);
21916 		return (ire);
21917 	}
21918 	rw_exit(&irb->irb_lock);
21919 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21920 	/*
21921 	 * If we can't find a suitable ire, return the original ire.
21922 	 */
21923 	return (save_ire);
21924 }
21925 
21926 /*
21927  * This function does the ire_refrele of the ire passed in as the
21928  * argument. As this function looks up more ires i.e broadcast ires,
21929  * it needs to REFRELE them. Currently, for simplicity we don't
21930  * differentiate the one passed in and looked up here. We always
21931  * REFRELE.
21932  * IPQoS Notes:
21933  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21934  * IPsec packets are done in ipsec_out_process.
21935  *
21936  */
21937 void
21938 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21939     zoneid_t zoneid)
21940 {
21941 	ipha_t		*ipha;
21942 #define	rptr	((uchar_t *)ipha)
21943 	queue_t		*stq;
21944 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21945 	uint32_t	v_hlen_tos_len;
21946 	uint32_t	ttl_protocol;
21947 	ipaddr_t	src;
21948 	ipaddr_t	dst;
21949 	uint32_t	cksum;
21950 	ipaddr_t	orig_src;
21951 	ire_t		*ire1;
21952 	mblk_t		*next_mp;
21953 	uint_t		hlen;
21954 	uint16_t	*up;
21955 	uint32_t	max_frag = ire->ire_max_frag;
21956 	ill_t		*ill = ire_to_ill(ire);
21957 	int		clusterwide;
21958 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21959 	int		ipsec_len;
21960 	mblk_t		*first_mp;
21961 	ipsec_out_t	*io;
21962 	boolean_t	conn_dontroute;		/* conn value for multicast */
21963 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21964 	boolean_t	multicast_forward;	/* Should we forward ? */
21965 	boolean_t	unspec_src;
21966 	ill_t		*conn_outgoing_ill = NULL;
21967 	ill_t		*ire_ill;
21968 	ill_t		*ire1_ill;
21969 	ill_t		*out_ill;
21970 	uint32_t 	ill_index = 0;
21971 	boolean_t	multirt_send = B_FALSE;
21972 	int		err;
21973 	ipxmit_state_t	pktxmit_state;
21974 	ip_stack_t	*ipst = ire->ire_ipst;
21975 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21976 
21977 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21978 	    "ip_wput_ire_start: q %p", q);
21979 
21980 	multicast_forward = B_FALSE;
21981 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21982 
21983 	if (ire->ire_flags & RTF_MULTIRT) {
21984 		/*
21985 		 * Multirouting case. The bucket where ire is stored
21986 		 * probably holds other RTF_MULTIRT flagged ire
21987 		 * to the destination. In this call to ip_wput_ire,
21988 		 * we attempt to send the packet through all
21989 		 * those ires. Thus, we first ensure that ire is the
21990 		 * first RTF_MULTIRT ire in the bucket,
21991 		 * before walking the ire list.
21992 		 */
21993 		ire_t *first_ire;
21994 		irb_t *irb = ire->ire_bucket;
21995 		ASSERT(irb != NULL);
21996 
21997 		/* Make sure we do not omit any multiroute ire. */
21998 		IRB_REFHOLD(irb);
21999 		for (first_ire = irb->irb_ire;
22000 		    first_ire != NULL;
22001 		    first_ire = first_ire->ire_next) {
22002 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22003 			    (first_ire->ire_addr == ire->ire_addr) &&
22004 			    !(first_ire->ire_marks &
22005 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22006 				break;
22007 			}
22008 		}
22009 
22010 		if ((first_ire != NULL) && (first_ire != ire)) {
22011 			IRE_REFHOLD(first_ire);
22012 			ire_refrele(ire);
22013 			ire = first_ire;
22014 			ill = ire_to_ill(ire);
22015 		}
22016 		IRB_REFRELE(irb);
22017 	}
22018 
22019 	/*
22020 	 * conn_outgoing_ill is used only in the broadcast loop.
22021 	 * for performance we don't grab the mutexs in the fastpath
22022 	 */
22023 	if ((connp != NULL) &&
22024 	    (connp->conn_xmit_if_ill == NULL) &&
22025 	    (ire->ire_type == IRE_BROADCAST) &&
22026 	    ((connp->conn_nofailover_ill != NULL) ||
22027 	    (connp->conn_outgoing_ill != NULL))) {
22028 		/*
22029 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22030 		 * option. So, see if this endpoint is bound to a
22031 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22032 		 * that if the interface is failed, we will still send
22033 		 * the packet on the same ill which is what we want.
22034 		 */
22035 		conn_outgoing_ill = conn_get_held_ill(connp,
22036 		    &connp->conn_nofailover_ill, &err);
22037 		if (err == ILL_LOOKUP_FAILED) {
22038 			ire_refrele(ire);
22039 			freemsg(mp);
22040 			return;
22041 		}
22042 		if (conn_outgoing_ill == NULL) {
22043 			/*
22044 			 * Choose a good ill in the group to send the
22045 			 * packets on.
22046 			 */
22047 			ire = conn_set_outgoing_ill(connp, ire,
22048 			    &conn_outgoing_ill);
22049 			if (ire == NULL) {
22050 				freemsg(mp);
22051 				return;
22052 			}
22053 		}
22054 	}
22055 
22056 	if (mp->b_datap->db_type != M_CTL) {
22057 		ipha = (ipha_t *)mp->b_rptr;
22058 	} else {
22059 		io = (ipsec_out_t *)mp->b_rptr;
22060 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22061 		ASSERT(zoneid == io->ipsec_out_zoneid);
22062 		ASSERT(zoneid != ALL_ZONES);
22063 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22064 		dst = ipha->ipha_dst;
22065 		/*
22066 		 * For the multicast case, ipsec_out carries conn_dontroute and
22067 		 * conn_multicast_loop as conn may not be available here. We
22068 		 * need this for multicast loopback and forwarding which is done
22069 		 * later in the code.
22070 		 */
22071 		if (CLASSD(dst)) {
22072 			conn_dontroute = io->ipsec_out_dontroute;
22073 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22074 			/*
22075 			 * If conn_dontroute is not set or conn_multicast_loop
22076 			 * is set, we need to do forwarding/loopback. For
22077 			 * datagrams from ip_wput_multicast, conn_dontroute is
22078 			 * set to B_TRUE and conn_multicast_loop is set to
22079 			 * B_FALSE so that we neither do forwarding nor
22080 			 * loopback.
22081 			 */
22082 			if (!conn_dontroute || conn_multicast_loop)
22083 				multicast_forward = B_TRUE;
22084 		}
22085 	}
22086 
22087 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22088 	    ire->ire_zoneid != ALL_ZONES) {
22089 		/*
22090 		 * When a zone sends a packet to another zone, we try to deliver
22091 		 * the packet under the same conditions as if the destination
22092 		 * was a real node on the network. To do so, we look for a
22093 		 * matching route in the forwarding table.
22094 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22095 		 * ip_newroute() does.
22096 		 * Note that IRE_LOCAL are special, since they are used
22097 		 * when the zoneid doesn't match in some cases. This means that
22098 		 * we need to handle ipha_src differently since ire_src_addr
22099 		 * belongs to the receiving zone instead of the sending zone.
22100 		 * When ip_restrict_interzone_loopback is set, then
22101 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22102 		 * for loopback between zones when the logical "Ethernet" would
22103 		 * have looped them back.
22104 		 */
22105 		ire_t *src_ire;
22106 
22107 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22108 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22109 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22110 		if (src_ire != NULL &&
22111 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22112 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22113 		    ire_local_same_ill_group(ire, src_ire))) {
22114 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22115 				ipha->ipha_src = src_ire->ire_src_addr;
22116 			ire_refrele(src_ire);
22117 		} else {
22118 			ire_refrele(ire);
22119 			if (conn_outgoing_ill != NULL)
22120 				ill_refrele(conn_outgoing_ill);
22121 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22122 			if (src_ire != NULL) {
22123 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22124 					ire_refrele(src_ire);
22125 					freemsg(mp);
22126 					return;
22127 				}
22128 				ire_refrele(src_ire);
22129 			}
22130 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22131 				/* Failed */
22132 				freemsg(mp);
22133 				return;
22134 			}
22135 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22136 			    ipst);
22137 			return;
22138 		}
22139 	}
22140 
22141 	if (mp->b_datap->db_type == M_CTL ||
22142 	    ipss->ipsec_outbound_v4_policy_present) {
22143 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22144 		    unspec_src, zoneid);
22145 		if (mp == NULL) {
22146 			ire_refrele(ire);
22147 			if (conn_outgoing_ill != NULL)
22148 				ill_refrele(conn_outgoing_ill);
22149 			return;
22150 		}
22151 	}
22152 
22153 	first_mp = mp;
22154 	ipsec_len = 0;
22155 
22156 	if (first_mp->b_datap->db_type == M_CTL) {
22157 		io = (ipsec_out_t *)first_mp->b_rptr;
22158 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22159 		mp = first_mp->b_cont;
22160 		ipsec_len = ipsec_out_extra_length(first_mp);
22161 		ASSERT(ipsec_len >= 0);
22162 		/* We already picked up the zoneid from the M_CTL above */
22163 		ASSERT(zoneid == io->ipsec_out_zoneid);
22164 		ASSERT(zoneid != ALL_ZONES);
22165 
22166 		/*
22167 		 * Drop M_CTL here if IPsec processing is not needed.
22168 		 * (Non-IPsec use of M_CTL extracted any information it
22169 		 * needed above).
22170 		 */
22171 		if (ipsec_len == 0) {
22172 			freeb(first_mp);
22173 			first_mp = mp;
22174 		}
22175 	}
22176 
22177 	/*
22178 	 * Fast path for ip_wput_ire
22179 	 */
22180 
22181 	ipha = (ipha_t *)mp->b_rptr;
22182 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22183 	dst = ipha->ipha_dst;
22184 
22185 	/*
22186 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22187 	 * if the socket is a SOCK_RAW type. The transport checksum should
22188 	 * be provided in the pre-built packet, so we don't need to compute it.
22189 	 * Also, other application set flags, like DF, should not be altered.
22190 	 * Other transport MUST pass down zero.
22191 	 */
22192 	ip_hdr_included = ipha->ipha_ident;
22193 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22194 
22195 	if (CLASSD(dst)) {
22196 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22197 		    ntohl(dst),
22198 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22199 		    ntohl(ire->ire_addr)));
22200 	}
22201 
22202 /* Macros to extract header fields from data already in registers */
22203 #ifdef	_BIG_ENDIAN
22204 #define	V_HLEN	(v_hlen_tos_len >> 24)
22205 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22206 #define	PROTO	(ttl_protocol & 0xFF)
22207 #else
22208 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22209 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22210 #define	PROTO	(ttl_protocol >> 8)
22211 #endif
22212 
22213 
22214 	orig_src = src = ipha->ipha_src;
22215 	/* (The loop back to "another" is explained down below.) */
22216 another:;
22217 	/*
22218 	 * Assign an ident value for this packet.  We assign idents on
22219 	 * a per destination basis out of the IRE.  There could be
22220 	 * other threads targeting the same destination, so we have to
22221 	 * arrange for a atomic increment.  Note that we use a 32-bit
22222 	 * atomic add because it has better performance than its
22223 	 * 16-bit sibling.
22224 	 *
22225 	 * If running in cluster mode and if the source address
22226 	 * belongs to a replicated service then vector through
22227 	 * cl_inet_ipident vector to allocate ip identifier
22228 	 * NOTE: This is a contract private interface with the
22229 	 * clustering group.
22230 	 */
22231 	clusterwide = 0;
22232 	if (cl_inet_ipident) {
22233 		ASSERT(cl_inet_isclusterwide);
22234 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22235 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22236 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22237 			    AF_INET, (uint8_t *)(uintptr_t)src,
22238 			    (uint8_t *)(uintptr_t)dst);
22239 			clusterwide = 1;
22240 		}
22241 	}
22242 	if (!clusterwide) {
22243 		ipha->ipha_ident =
22244 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22245 	}
22246 
22247 #ifndef _BIG_ENDIAN
22248 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22249 #endif
22250 
22251 	/*
22252 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22253 	 * This is needed to obey conn_unspec_src when packets go through
22254 	 * ip_newroute + arp.
22255 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22256 	 */
22257 	if (src == INADDR_ANY && !unspec_src) {
22258 		/*
22259 		 * Assign the appropriate source address from the IRE if none
22260 		 * was specified.
22261 		 */
22262 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22263 
22264 		/*
22265 		 * With IP multipathing, broadcast packets are sent on the ire
22266 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22267 		 * the group. However, this ire might not be in the same zone so
22268 		 * we can't always use its source address. We look for a
22269 		 * broadcast ire in the same group and in the right zone.
22270 		 */
22271 		if (ire->ire_type == IRE_BROADCAST &&
22272 		    ire->ire_zoneid != zoneid) {
22273 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22274 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22275 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22276 			if (src_ire != NULL) {
22277 				src = src_ire->ire_src_addr;
22278 				ire_refrele(src_ire);
22279 			} else {
22280 				ire_refrele(ire);
22281 				if (conn_outgoing_ill != NULL)
22282 					ill_refrele(conn_outgoing_ill);
22283 				freemsg(first_mp);
22284 				if (ill != NULL) {
22285 					BUMP_MIB(ill->ill_ip_mib,
22286 					    ipIfStatsOutDiscards);
22287 				} else {
22288 					BUMP_MIB(&ipst->ips_ip_mib,
22289 					    ipIfStatsOutDiscards);
22290 				}
22291 				return;
22292 			}
22293 		} else {
22294 			src = ire->ire_src_addr;
22295 		}
22296 
22297 		if (connp == NULL) {
22298 			ip1dbg(("ip_wput_ire: no connp and no src "
22299 			    "address for dst 0x%x, using src 0x%x\n",
22300 			    ntohl(dst),
22301 			    ntohl(src)));
22302 		}
22303 		ipha->ipha_src = src;
22304 	}
22305 	stq = ire->ire_stq;
22306 
22307 	/*
22308 	 * We only allow ire chains for broadcasts since there will
22309 	 * be multiple IRE_CACHE entries for the same multicast
22310 	 * address (one per ipif).
22311 	 */
22312 	next_mp = NULL;
22313 
22314 	/* broadcast packet */
22315 	if (ire->ire_type == IRE_BROADCAST)
22316 		goto broadcast;
22317 
22318 	/* loopback ? */
22319 	if (stq == NULL)
22320 		goto nullstq;
22321 
22322 	/* The ill_index for outbound ILL */
22323 	ill_index = Q_TO_INDEX(stq);
22324 
22325 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22326 	ttl_protocol = ((uint16_t *)ipha)[4];
22327 
22328 	/* pseudo checksum (do it in parts for IP header checksum) */
22329 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22330 
22331 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22332 		queue_t *dev_q = stq->q_next;
22333 
22334 		/* flow controlled */
22335 		if ((dev_q->q_next || dev_q->q_first) &&
22336 		    !canput(dev_q))
22337 			goto blocked;
22338 		if ((PROTO == IPPROTO_UDP) &&
22339 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22340 			hlen = (V_HLEN & 0xF) << 2;
22341 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22342 			if (*up != 0) {
22343 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22344 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22345 				/* Software checksum? */
22346 				if (DB_CKSUMFLAGS(mp) == 0) {
22347 					IP_STAT(ipst, ip_out_sw_cksum);
22348 					IP_STAT_UPDATE(ipst,
22349 					    ip_udp_out_sw_cksum_bytes,
22350 					    LENGTH - hlen);
22351 				}
22352 			}
22353 		}
22354 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22355 		hlen = (V_HLEN & 0xF) << 2;
22356 		if (PROTO == IPPROTO_TCP) {
22357 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22358 			/*
22359 			 * The packet header is processed once and for all, even
22360 			 * in the multirouting case. We disable hardware
22361 			 * checksum if the packet is multirouted, as it will be
22362 			 * replicated via several interfaces, and not all of
22363 			 * them may have this capability.
22364 			 */
22365 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22366 			    LENGTH, max_frag, ipsec_len, cksum);
22367 			/* Software checksum? */
22368 			if (DB_CKSUMFLAGS(mp) == 0) {
22369 				IP_STAT(ipst, ip_out_sw_cksum);
22370 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22371 				    LENGTH - hlen);
22372 			}
22373 		} else {
22374 			sctp_hdr_t	*sctph;
22375 
22376 			ASSERT(PROTO == IPPROTO_SCTP);
22377 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22378 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22379 			/*
22380 			 * Zero out the checksum field to ensure proper
22381 			 * checksum calculation.
22382 			 */
22383 			sctph->sh_chksum = 0;
22384 #ifdef	DEBUG
22385 			if (!skip_sctp_cksum)
22386 #endif
22387 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22388 		}
22389 	}
22390 
22391 	/*
22392 	 * If this is a multicast packet and originated from ip_wput
22393 	 * we need to do loopback and forwarding checks. If it comes
22394 	 * from ip_wput_multicast, we SHOULD not do this.
22395 	 */
22396 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22397 
22398 	/* checksum */
22399 	cksum += ttl_protocol;
22400 
22401 	/* fragment the packet */
22402 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22403 		goto fragmentit;
22404 	/*
22405 	 * Don't use frag_flag if packet is pre-built or source
22406 	 * routed or if multicast (since multicast packets do
22407 	 * not solicit ICMP "packet too big" messages).
22408 	 */
22409 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22410 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22411 	    !ip_source_route_included(ipha)) &&
22412 	    !CLASSD(ipha->ipha_dst))
22413 		ipha->ipha_fragment_offset_and_flags |=
22414 		    htons(ire->ire_frag_flag);
22415 
22416 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22417 		/* calculate IP header checksum */
22418 		cksum += ipha->ipha_ident;
22419 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22420 		cksum += ipha->ipha_fragment_offset_and_flags;
22421 
22422 		/* IP options present */
22423 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22424 		if (hlen)
22425 			goto checksumoptions;
22426 
22427 		/* calculate hdr checksum */
22428 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22429 		cksum = ~(cksum + (cksum >> 16));
22430 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22431 	}
22432 	if (ipsec_len != 0) {
22433 		/*
22434 		 * We will do the rest of the processing after
22435 		 * we come back from IPsec in ip_wput_ipsec_out().
22436 		 */
22437 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22438 
22439 		io = (ipsec_out_t *)first_mp->b_rptr;
22440 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22441 		    ill_phyint->phyint_ifindex;
22442 
22443 		ipsec_out_process(q, first_mp, ire, ill_index);
22444 		ire_refrele(ire);
22445 		if (conn_outgoing_ill != NULL)
22446 			ill_refrele(conn_outgoing_ill);
22447 		return;
22448 	}
22449 
22450 	/*
22451 	 * In most cases, the emission loop below is entered only
22452 	 * once. Only in the case where the ire holds the
22453 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22454 	 * flagged ires in the bucket, and send the packet
22455 	 * through all crossed RTF_MULTIRT routes.
22456 	 */
22457 	if (ire->ire_flags & RTF_MULTIRT) {
22458 		multirt_send = B_TRUE;
22459 	}
22460 	do {
22461 		if (multirt_send) {
22462 			irb_t *irb;
22463 			/*
22464 			 * We are in a multiple send case, need to get
22465 			 * the next ire and make a duplicate of the packet.
22466 			 * ire1 holds here the next ire to process in the
22467 			 * bucket. If multirouting is expected,
22468 			 * any non-RTF_MULTIRT ire that has the
22469 			 * right destination address is ignored.
22470 			 */
22471 			irb = ire->ire_bucket;
22472 			ASSERT(irb != NULL);
22473 
22474 			IRB_REFHOLD(irb);
22475 			for (ire1 = ire->ire_next;
22476 			    ire1 != NULL;
22477 			    ire1 = ire1->ire_next) {
22478 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22479 					continue;
22480 				if (ire1->ire_addr != ire->ire_addr)
22481 					continue;
22482 				if (ire1->ire_marks &
22483 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22484 					continue;
22485 
22486 				/* Got one */
22487 				IRE_REFHOLD(ire1);
22488 				break;
22489 			}
22490 			IRB_REFRELE(irb);
22491 
22492 			if (ire1 != NULL) {
22493 				next_mp = copyb(mp);
22494 				if ((next_mp == NULL) ||
22495 				    ((mp->b_cont != NULL) &&
22496 				    ((next_mp->b_cont =
22497 				    dupmsg(mp->b_cont)) == NULL))) {
22498 					freemsg(next_mp);
22499 					next_mp = NULL;
22500 					ire_refrele(ire1);
22501 					ire1 = NULL;
22502 				}
22503 			}
22504 
22505 			/* Last multiroute ire; don't loop anymore. */
22506 			if (ire1 == NULL) {
22507 				multirt_send = B_FALSE;
22508 			}
22509 		}
22510 
22511 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22512 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22513 		    mblk_t *, mp);
22514 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22515 		    ipst->ips_ipv4firewall_physical_out,
22516 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22517 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22518 		if (mp == NULL)
22519 			goto release_ire_and_ill;
22520 
22521 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22522 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22523 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22524 		if ((pktxmit_state == SEND_FAILED) ||
22525 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22526 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22527 			    "- packet dropped\n"));
22528 release_ire_and_ill:
22529 			ire_refrele(ire);
22530 			if (next_mp != NULL) {
22531 				freemsg(next_mp);
22532 				ire_refrele(ire1);
22533 			}
22534 			if (conn_outgoing_ill != NULL)
22535 				ill_refrele(conn_outgoing_ill);
22536 			return;
22537 		}
22538 
22539 		if (CLASSD(dst)) {
22540 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22541 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22542 			    LENGTH);
22543 		}
22544 
22545 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22546 		    "ip_wput_ire_end: q %p (%S)",
22547 		    q, "last copy out");
22548 		IRE_REFRELE(ire);
22549 
22550 		if (multirt_send) {
22551 			ASSERT(ire1);
22552 			/*
22553 			 * Proceed with the next RTF_MULTIRT ire,
22554 			 * Also set up the send-to queue accordingly.
22555 			 */
22556 			ire = ire1;
22557 			ire1 = NULL;
22558 			stq = ire->ire_stq;
22559 			mp = next_mp;
22560 			next_mp = NULL;
22561 			ipha = (ipha_t *)mp->b_rptr;
22562 			ill_index = Q_TO_INDEX(stq);
22563 			ill = (ill_t *)stq->q_ptr;
22564 		}
22565 	} while (multirt_send);
22566 	if (conn_outgoing_ill != NULL)
22567 		ill_refrele(conn_outgoing_ill);
22568 	return;
22569 
22570 	/*
22571 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22572 	 */
22573 broadcast:
22574 	{
22575 		/*
22576 		 * Avoid broadcast storms by setting the ttl to 1
22577 		 * for broadcasts. This parameter can be set
22578 		 * via ndd, so make sure that for the SO_DONTROUTE
22579 		 * case that ipha_ttl is always set to 1.
22580 		 * In the event that we are replying to incoming
22581 		 * ICMP packets, conn could be NULL.
22582 		 */
22583 		if ((connp != NULL) && connp->conn_dontroute)
22584 			ipha->ipha_ttl = 1;
22585 		else
22586 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22587 
22588 		/*
22589 		 * Note that we are not doing a IRB_REFHOLD here.
22590 		 * Actually we don't care if the list changes i.e
22591 		 * if somebody deletes an IRE from the list while
22592 		 * we drop the lock, the next time we come around
22593 		 * ire_next will be NULL and hence we won't send
22594 		 * out multiple copies which is fine.
22595 		 */
22596 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22597 		ire1 = ire->ire_next;
22598 		if (conn_outgoing_ill != NULL) {
22599 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22600 				ASSERT(ire1 == ire->ire_next);
22601 				if (ire1 != NULL && ire1->ire_addr == dst) {
22602 					ire_refrele(ire);
22603 					ire = ire1;
22604 					IRE_REFHOLD(ire);
22605 					ire1 = ire->ire_next;
22606 					continue;
22607 				}
22608 				rw_exit(&ire->ire_bucket->irb_lock);
22609 				/* Did not find a matching ill */
22610 				ip1dbg(("ip_wput_ire: broadcast with no "
22611 				    "matching IP_BOUND_IF ill %s\n",
22612 				    conn_outgoing_ill->ill_name));
22613 				freemsg(first_mp);
22614 				if (ire != NULL)
22615 					ire_refrele(ire);
22616 				ill_refrele(conn_outgoing_ill);
22617 				return;
22618 			}
22619 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22620 			/*
22621 			 * If the next IRE has the same address and is not one
22622 			 * of the two copies that we need to send, try to see
22623 			 * whether this copy should be sent at all. This
22624 			 * assumes that we insert loopbacks first and then
22625 			 * non-loopbacks. This is acheived by inserting the
22626 			 * loopback always before non-loopback.
22627 			 * This is used to send a single copy of a broadcast
22628 			 * packet out all physical interfaces that have an
22629 			 * matching IRE_BROADCAST while also looping
22630 			 * back one copy (to ip_wput_local) for each
22631 			 * matching physical interface. However, we avoid
22632 			 * sending packets out different logical that match by
22633 			 * having ipif_up/ipif_down supress duplicate
22634 			 * IRE_BROADCASTS.
22635 			 *
22636 			 * This feature is currently used to get broadcasts
22637 			 * sent to multiple interfaces, when the broadcast
22638 			 * address being used applies to multiple interfaces.
22639 			 * For example, a whole net broadcast will be
22640 			 * replicated on every connected subnet of
22641 			 * the target net.
22642 			 *
22643 			 * Each zone has its own set of IRE_BROADCASTs, so that
22644 			 * we're able to distribute inbound packets to multiple
22645 			 * zones who share a broadcast address. We avoid looping
22646 			 * back outbound packets in different zones but on the
22647 			 * same ill, as the application would see duplicates.
22648 			 *
22649 			 * If the interfaces are part of the same group,
22650 			 * we would want to send only one copy out for
22651 			 * whole group.
22652 			 *
22653 			 * This logic assumes that ire_add_v4() groups the
22654 			 * IRE_BROADCAST entries so that those with the same
22655 			 * ire_addr and ill_group are kept together.
22656 			 */
22657 			ire_ill = ire->ire_ipif->ipif_ill;
22658 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22659 				if (ire_ill->ill_group != NULL &&
22660 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22661 					/*
22662 					 * If the current zone only has an ire
22663 					 * broadcast for this address marked
22664 					 * NORECV, the ire we want is ahead in
22665 					 * the bucket, so we look it up
22666 					 * deliberately ignoring the zoneid.
22667 					 */
22668 					for (ire1 = ire->ire_bucket->irb_ire;
22669 					    ire1 != NULL;
22670 					    ire1 = ire1->ire_next) {
22671 						ire1_ill =
22672 						    ire1->ire_ipif->ipif_ill;
22673 						if (ire1->ire_addr != dst)
22674 							continue;
22675 						/* skip over the current ire */
22676 						if (ire1 == ire)
22677 							continue;
22678 						/* skip over deleted ires */
22679 						if (ire1->ire_marks &
22680 						    IRE_MARK_CONDEMNED)
22681 							continue;
22682 						/*
22683 						 * non-loopback ire in our
22684 						 * group: use it for the next
22685 						 * pass in the loop
22686 						 */
22687 						if (ire1->ire_stq != NULL &&
22688 						    ire1_ill->ill_group ==
22689 						    ire_ill->ill_group)
22690 							break;
22691 					}
22692 				}
22693 			} else {
22694 				while (ire1 != NULL && ire1->ire_addr == dst) {
22695 					ire1_ill = ire1->ire_ipif->ipif_ill;
22696 					/*
22697 					 * We can have two broadcast ires on the
22698 					 * same ill in different zones; here
22699 					 * we'll send a copy of the packet on
22700 					 * each ill and the fanout code will
22701 					 * call conn_wantpacket() to check that
22702 					 * the zone has the broadcast address
22703 					 * configured on the ill. If the two
22704 					 * ires are in the same group we only
22705 					 * send one copy up.
22706 					 */
22707 					if (ire1_ill != ire_ill &&
22708 					    (ire1_ill->ill_group == NULL ||
22709 					    ire_ill->ill_group == NULL ||
22710 					    ire1_ill->ill_group !=
22711 					    ire_ill->ill_group)) {
22712 						break;
22713 					}
22714 					ire1 = ire1->ire_next;
22715 				}
22716 			}
22717 		}
22718 		ASSERT(multirt_send == B_FALSE);
22719 		if (ire1 != NULL && ire1->ire_addr == dst) {
22720 			if ((ire->ire_flags & RTF_MULTIRT) &&
22721 			    (ire1->ire_flags & RTF_MULTIRT)) {
22722 				/*
22723 				 * We are in the multirouting case.
22724 				 * The message must be sent at least
22725 				 * on both ires. These ires have been
22726 				 * inserted AFTER the standard ones
22727 				 * in ip_rt_add(). There are thus no
22728 				 * other ire entries for the destination
22729 				 * address in the rest of the bucket
22730 				 * that do not have the RTF_MULTIRT
22731 				 * flag. We don't process a copy
22732 				 * of the message here. This will be
22733 				 * done in the final sending loop.
22734 				 */
22735 				multirt_send = B_TRUE;
22736 			} else {
22737 				next_mp = ip_copymsg(first_mp);
22738 				if (next_mp != NULL)
22739 					IRE_REFHOLD(ire1);
22740 			}
22741 		}
22742 		rw_exit(&ire->ire_bucket->irb_lock);
22743 	}
22744 
22745 	if (stq) {
22746 		/*
22747 		 * A non-NULL send-to queue means this packet is going
22748 		 * out of this machine.
22749 		 */
22750 		out_ill = (ill_t *)stq->q_ptr;
22751 
22752 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22753 		ttl_protocol = ((uint16_t *)ipha)[4];
22754 		/*
22755 		 * We accumulate the pseudo header checksum in cksum.
22756 		 * This is pretty hairy code, so watch close.  One
22757 		 * thing to keep in mind is that UDP and TCP have
22758 		 * stored their respective datagram lengths in their
22759 		 * checksum fields.  This lines things up real nice.
22760 		 */
22761 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22762 		    (src >> 16) + (src & 0xFFFF);
22763 		/*
22764 		 * We assume the udp checksum field contains the
22765 		 * length, so to compute the pseudo header checksum,
22766 		 * all we need is the protocol number and src/dst.
22767 		 */
22768 		/* Provide the checksums for UDP and TCP. */
22769 		if ((PROTO == IPPROTO_TCP) &&
22770 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22771 			/* hlen gets the number of uchar_ts in the IP header */
22772 			hlen = (V_HLEN & 0xF) << 2;
22773 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22774 			IP_STAT(ipst, ip_out_sw_cksum);
22775 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22776 			    LENGTH - hlen);
22777 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22778 		} else if (PROTO == IPPROTO_SCTP &&
22779 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22780 			sctp_hdr_t	*sctph;
22781 
22782 			hlen = (V_HLEN & 0xF) << 2;
22783 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22784 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22785 			sctph->sh_chksum = 0;
22786 #ifdef	DEBUG
22787 			if (!skip_sctp_cksum)
22788 #endif
22789 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22790 		} else {
22791 			queue_t *dev_q = stq->q_next;
22792 
22793 			if ((dev_q->q_next || dev_q->q_first) &&
22794 			    !canput(dev_q)) {
22795 blocked:
22796 				ipha->ipha_ident = ip_hdr_included;
22797 				/*
22798 				 * If we don't have a conn to apply
22799 				 * backpressure, free the message.
22800 				 * In the ire_send path, we don't know
22801 				 * the position to requeue the packet. Rather
22802 				 * than reorder packets, we just drop this
22803 				 * packet.
22804 				 */
22805 				if (ipst->ips_ip_output_queue &&
22806 				    connp != NULL &&
22807 				    caller != IRE_SEND) {
22808 					if (caller == IP_WSRV) {
22809 						connp->conn_did_putbq = 1;
22810 						(void) putbq(connp->conn_wq,
22811 						    first_mp);
22812 						conn_drain_insert(connp);
22813 						/*
22814 						 * This is the service thread,
22815 						 * and the queue is already
22816 						 * noenabled. The check for
22817 						 * canput and the putbq is not
22818 						 * atomic. So we need to check
22819 						 * again.
22820 						 */
22821 						if (canput(stq->q_next))
22822 							connp->conn_did_putbq
22823 							    = 0;
22824 						IP_STAT(ipst, ip_conn_flputbq);
22825 					} else {
22826 						/*
22827 						 * We are not the service proc.
22828 						 * ip_wsrv will be scheduled or
22829 						 * is already running.
22830 						 */
22831 						(void) putq(connp->conn_wq,
22832 						    first_mp);
22833 					}
22834 				} else {
22835 					out_ill = (ill_t *)stq->q_ptr;
22836 					BUMP_MIB(out_ill->ill_ip_mib,
22837 					    ipIfStatsOutDiscards);
22838 					freemsg(first_mp);
22839 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22840 					    "ip_wput_ire_end: q %p (%S)",
22841 					    q, "discard");
22842 				}
22843 				ire_refrele(ire);
22844 				if (next_mp) {
22845 					ire_refrele(ire1);
22846 					freemsg(next_mp);
22847 				}
22848 				if (conn_outgoing_ill != NULL)
22849 					ill_refrele(conn_outgoing_ill);
22850 				return;
22851 			}
22852 			if ((PROTO == IPPROTO_UDP) &&
22853 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22854 				/*
22855 				 * hlen gets the number of uchar_ts in the
22856 				 * IP header
22857 				 */
22858 				hlen = (V_HLEN & 0xF) << 2;
22859 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22860 				max_frag = ire->ire_max_frag;
22861 				if (*up != 0) {
22862 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22863 					    up, PROTO, hlen, LENGTH, max_frag,
22864 					    ipsec_len, cksum);
22865 					/* Software checksum? */
22866 					if (DB_CKSUMFLAGS(mp) == 0) {
22867 						IP_STAT(ipst, ip_out_sw_cksum);
22868 						IP_STAT_UPDATE(ipst,
22869 						    ip_udp_out_sw_cksum_bytes,
22870 						    LENGTH - hlen);
22871 					}
22872 				}
22873 			}
22874 		}
22875 		/*
22876 		 * Need to do this even when fragmenting. The local
22877 		 * loopback can be done without computing checksums
22878 		 * but forwarding out other interface must be done
22879 		 * after the IP checksum (and ULP checksums) have been
22880 		 * computed.
22881 		 *
22882 		 * NOTE : multicast_forward is set only if this packet
22883 		 * originated from ip_wput. For packets originating from
22884 		 * ip_wput_multicast, it is not set.
22885 		 */
22886 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22887 multi_loopback:
22888 			ip2dbg(("ip_wput: multicast, loop %d\n",
22889 			    conn_multicast_loop));
22890 
22891 			/*  Forget header checksum offload */
22892 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22893 
22894 			/*
22895 			 * Local loopback of multicasts?  Check the
22896 			 * ill.
22897 			 *
22898 			 * Note that the loopback function will not come
22899 			 * in through ip_rput - it will only do the
22900 			 * client fanout thus we need to do an mforward
22901 			 * as well.  The is different from the BSD
22902 			 * logic.
22903 			 */
22904 			if (ill != NULL) {
22905 				ilm_t	*ilm;
22906 
22907 				ILM_WALKER_HOLD(ill);
22908 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22909 				    ALL_ZONES);
22910 				ILM_WALKER_RELE(ill);
22911 				if (ilm != NULL) {
22912 					/*
22913 					 * Pass along the virtual output q.
22914 					 * ip_wput_local() will distribute the
22915 					 * packet to all the matching zones,
22916 					 * except the sending zone when
22917 					 * IP_MULTICAST_LOOP is false.
22918 					 */
22919 					ip_multicast_loopback(q, ill, first_mp,
22920 					    conn_multicast_loop ? 0 :
22921 					    IP_FF_NO_MCAST_LOOP, zoneid);
22922 				}
22923 			}
22924 			if (ipha->ipha_ttl == 0) {
22925 				/*
22926 				 * 0 => only to this host i.e. we are
22927 				 * done. We are also done if this was the
22928 				 * loopback interface since it is sufficient
22929 				 * to loopback one copy of a multicast packet.
22930 				 */
22931 				freemsg(first_mp);
22932 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22933 				    "ip_wput_ire_end: q %p (%S)",
22934 				    q, "loopback");
22935 				ire_refrele(ire);
22936 				if (conn_outgoing_ill != NULL)
22937 					ill_refrele(conn_outgoing_ill);
22938 				return;
22939 			}
22940 			/*
22941 			 * ILLF_MULTICAST is checked in ip_newroute
22942 			 * i.e. we don't need to check it here since
22943 			 * all IRE_CACHEs come from ip_newroute.
22944 			 * For multicast traffic, SO_DONTROUTE is interpreted
22945 			 * to mean only send the packet out the interface
22946 			 * (optionally specified with IP_MULTICAST_IF)
22947 			 * and do not forward it out additional interfaces.
22948 			 * RSVP and the rsvp daemon is an example of a
22949 			 * protocol and user level process that
22950 			 * handles it's own routing. Hence, it uses the
22951 			 * SO_DONTROUTE option to accomplish this.
22952 			 */
22953 
22954 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22955 			    ill != NULL) {
22956 				/* Unconditionally redo the checksum */
22957 				ipha->ipha_hdr_checksum = 0;
22958 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22959 
22960 				/*
22961 				 * If this needs to go out secure, we need
22962 				 * to wait till we finish the IPsec
22963 				 * processing.
22964 				 */
22965 				if (ipsec_len == 0 &&
22966 				    ip_mforward(ill, ipha, mp)) {
22967 					freemsg(first_mp);
22968 					ip1dbg(("ip_wput: mforward failed\n"));
22969 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22970 					    "ip_wput_ire_end: q %p (%S)",
22971 					    q, "mforward failed");
22972 					ire_refrele(ire);
22973 					if (conn_outgoing_ill != NULL)
22974 						ill_refrele(conn_outgoing_ill);
22975 					return;
22976 				}
22977 			}
22978 		}
22979 		max_frag = ire->ire_max_frag;
22980 		cksum += ttl_protocol;
22981 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22982 			/* No fragmentation required for this one. */
22983 			/*
22984 			 * Don't use frag_flag if packet is pre-built or source
22985 			 * routed or if multicast (since multicast packets do
22986 			 * not solicit ICMP "packet too big" messages).
22987 			 */
22988 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22989 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22990 			    !ip_source_route_included(ipha)) &&
22991 			    !CLASSD(ipha->ipha_dst))
22992 				ipha->ipha_fragment_offset_and_flags |=
22993 				    htons(ire->ire_frag_flag);
22994 
22995 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22996 				/* Complete the IP header checksum. */
22997 				cksum += ipha->ipha_ident;
22998 				cksum += (v_hlen_tos_len >> 16)+
22999 				    (v_hlen_tos_len & 0xFFFF);
23000 				cksum += ipha->ipha_fragment_offset_and_flags;
23001 				hlen = (V_HLEN & 0xF) -
23002 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23003 				if (hlen) {
23004 checksumoptions:
23005 					/*
23006 					 * Account for the IP Options in the IP
23007 					 * header checksum.
23008 					 */
23009 					up = (uint16_t *)(rptr+
23010 					    IP_SIMPLE_HDR_LENGTH);
23011 					do {
23012 						cksum += up[0];
23013 						cksum += up[1];
23014 						up += 2;
23015 					} while (--hlen);
23016 				}
23017 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23018 				cksum = ~(cksum + (cksum >> 16));
23019 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23020 			}
23021 			if (ipsec_len != 0) {
23022 				ipsec_out_process(q, first_mp, ire, ill_index);
23023 				if (!next_mp) {
23024 					ire_refrele(ire);
23025 					if (conn_outgoing_ill != NULL)
23026 						ill_refrele(conn_outgoing_ill);
23027 					return;
23028 				}
23029 				goto next;
23030 			}
23031 
23032 			/*
23033 			 * multirt_send has already been handled
23034 			 * for broadcast, but not yet for multicast
23035 			 * or IP options.
23036 			 */
23037 			if (next_mp == NULL) {
23038 				if (ire->ire_flags & RTF_MULTIRT) {
23039 					multirt_send = B_TRUE;
23040 				}
23041 			}
23042 
23043 			/*
23044 			 * In most cases, the emission loop below is
23045 			 * entered only once. Only in the case where
23046 			 * the ire holds the RTF_MULTIRT flag, do we loop
23047 			 * to process all RTF_MULTIRT ires in the bucket,
23048 			 * and send the packet through all crossed
23049 			 * RTF_MULTIRT routes.
23050 			 */
23051 			do {
23052 				if (multirt_send) {
23053 					irb_t *irb;
23054 
23055 					irb = ire->ire_bucket;
23056 					ASSERT(irb != NULL);
23057 					/*
23058 					 * We are in a multiple send case,
23059 					 * need to get the next IRE and make
23060 					 * a duplicate of the packet.
23061 					 */
23062 					IRB_REFHOLD(irb);
23063 					for (ire1 = ire->ire_next;
23064 					    ire1 != NULL;
23065 					    ire1 = ire1->ire_next) {
23066 						if (!(ire1->ire_flags &
23067 						    RTF_MULTIRT)) {
23068 							continue;
23069 						}
23070 						if (ire1->ire_addr !=
23071 						    ire->ire_addr) {
23072 							continue;
23073 						}
23074 						if (ire1->ire_marks &
23075 						    (IRE_MARK_CONDEMNED|
23076 						    IRE_MARK_HIDDEN)) {
23077 							continue;
23078 						}
23079 
23080 						/* Got one */
23081 						IRE_REFHOLD(ire1);
23082 						break;
23083 					}
23084 					IRB_REFRELE(irb);
23085 
23086 					if (ire1 != NULL) {
23087 						next_mp = copyb(mp);
23088 						if ((next_mp == NULL) ||
23089 						    ((mp->b_cont != NULL) &&
23090 						    ((next_mp->b_cont =
23091 						    dupmsg(mp->b_cont))
23092 						    == NULL))) {
23093 							freemsg(next_mp);
23094 							next_mp = NULL;
23095 							ire_refrele(ire1);
23096 							ire1 = NULL;
23097 						}
23098 					}
23099 
23100 					/*
23101 					 * Last multiroute ire; don't loop
23102 					 * anymore. The emission is over
23103 					 * and next_mp is NULL.
23104 					 */
23105 					if (ire1 == NULL) {
23106 						multirt_send = B_FALSE;
23107 					}
23108 				}
23109 
23110 				out_ill = ire->ire_ipif->ipif_ill;
23111 				DTRACE_PROBE4(ip4__physical__out__start,
23112 				    ill_t *, NULL,
23113 				    ill_t *, out_ill,
23114 				    ipha_t *, ipha, mblk_t *, mp);
23115 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23116 				    ipst->ips_ipv4firewall_physical_out,
23117 				    NULL, out_ill, ipha, mp, mp, ipst);
23118 				DTRACE_PROBE1(ip4__physical__out__end,
23119 				    mblk_t *, mp);
23120 				if (mp == NULL)
23121 					goto release_ire_and_ill_2;
23122 
23123 				ASSERT(ipsec_len == 0);
23124 				mp->b_prev =
23125 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23126 				DTRACE_PROBE2(ip__xmit__2,
23127 				    mblk_t *, mp, ire_t *, ire);
23128 				pktxmit_state = ip_xmit_v4(mp, ire,
23129 				    NULL, B_TRUE);
23130 				if ((pktxmit_state == SEND_FAILED) ||
23131 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23132 release_ire_and_ill_2:
23133 					if (next_mp) {
23134 						freemsg(next_mp);
23135 						ire_refrele(ire1);
23136 					}
23137 					ire_refrele(ire);
23138 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23139 					    "ip_wput_ire_end: q %p (%S)",
23140 					    q, "discard MDATA");
23141 					if (conn_outgoing_ill != NULL)
23142 						ill_refrele(conn_outgoing_ill);
23143 					return;
23144 				}
23145 
23146 				if (CLASSD(dst)) {
23147 					BUMP_MIB(out_ill->ill_ip_mib,
23148 					    ipIfStatsHCOutMcastPkts);
23149 					UPDATE_MIB(out_ill->ill_ip_mib,
23150 					    ipIfStatsHCOutMcastOctets,
23151 					    LENGTH);
23152 				} else if (ire->ire_type == IRE_BROADCAST) {
23153 					BUMP_MIB(out_ill->ill_ip_mib,
23154 					    ipIfStatsHCOutBcastPkts);
23155 				}
23156 
23157 				if (multirt_send) {
23158 					/*
23159 					 * We are in a multiple send case,
23160 					 * need to re-enter the sending loop
23161 					 * using the next ire.
23162 					 */
23163 					ire_refrele(ire);
23164 					ire = ire1;
23165 					stq = ire->ire_stq;
23166 					mp = next_mp;
23167 					next_mp = NULL;
23168 					ipha = (ipha_t *)mp->b_rptr;
23169 					ill_index = Q_TO_INDEX(stq);
23170 				}
23171 			} while (multirt_send);
23172 
23173 			if (!next_mp) {
23174 				/*
23175 				 * Last copy going out (the ultra-common
23176 				 * case).  Note that we intentionally replicate
23177 				 * the putnext rather than calling it before
23178 				 * the next_mp check in hopes of a little
23179 				 * tail-call action out of the compiler.
23180 				 */
23181 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23182 				    "ip_wput_ire_end: q %p (%S)",
23183 				    q, "last copy out(1)");
23184 				ire_refrele(ire);
23185 				if (conn_outgoing_ill != NULL)
23186 					ill_refrele(conn_outgoing_ill);
23187 				return;
23188 			}
23189 			/* More copies going out below. */
23190 		} else {
23191 			int offset;
23192 fragmentit:
23193 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23194 			/*
23195 			 * If this would generate a icmp_frag_needed message,
23196 			 * we need to handle it before we do the IPsec
23197 			 * processing. Otherwise, we need to strip the IPsec
23198 			 * headers before we send up the message to the ULPs
23199 			 * which becomes messy and difficult.
23200 			 */
23201 			if (ipsec_len != 0) {
23202 				if ((max_frag < (unsigned int)(LENGTH +
23203 				    ipsec_len)) && (offset & IPH_DF)) {
23204 					out_ill = (ill_t *)stq->q_ptr;
23205 					BUMP_MIB(out_ill->ill_ip_mib,
23206 					    ipIfStatsOutFragFails);
23207 					BUMP_MIB(out_ill->ill_ip_mib,
23208 					    ipIfStatsOutFragReqds);
23209 					ipha->ipha_hdr_checksum = 0;
23210 					ipha->ipha_hdr_checksum =
23211 					    (uint16_t)ip_csum_hdr(ipha);
23212 					icmp_frag_needed(ire->ire_stq, first_mp,
23213 					    max_frag, zoneid, ipst);
23214 					if (!next_mp) {
23215 						ire_refrele(ire);
23216 						if (conn_outgoing_ill != NULL) {
23217 							ill_refrele(
23218 							    conn_outgoing_ill);
23219 						}
23220 						return;
23221 					}
23222 				} else {
23223 					/*
23224 					 * This won't cause a icmp_frag_needed
23225 					 * message. to be generated. Send it on
23226 					 * the wire. Note that this could still
23227 					 * cause fragmentation and all we
23228 					 * do is the generation of the message
23229 					 * to the ULP if needed before IPsec.
23230 					 */
23231 					if (!next_mp) {
23232 						ipsec_out_process(q, first_mp,
23233 						    ire, ill_index);
23234 						TRACE_2(TR_FAC_IP,
23235 						    TR_IP_WPUT_IRE_END,
23236 						    "ip_wput_ire_end: q %p "
23237 						    "(%S)", q,
23238 						    "last ipsec_out_process");
23239 						ire_refrele(ire);
23240 						if (conn_outgoing_ill != NULL) {
23241 							ill_refrele(
23242 							    conn_outgoing_ill);
23243 						}
23244 						return;
23245 					}
23246 					ipsec_out_process(q, first_mp,
23247 					    ire, ill_index);
23248 				}
23249 			} else {
23250 				/*
23251 				 * Initiate IPPF processing. For
23252 				 * fragmentable packets we finish
23253 				 * all QOS packet processing before
23254 				 * calling:
23255 				 * ip_wput_ire_fragmentit->ip_wput_frag
23256 				 */
23257 
23258 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23259 					ip_process(IPP_LOCAL_OUT, &mp,
23260 					    ill_index);
23261 					if (mp == NULL) {
23262 						out_ill = (ill_t *)stq->q_ptr;
23263 						BUMP_MIB(out_ill->ill_ip_mib,
23264 						    ipIfStatsOutDiscards);
23265 						if (next_mp != NULL) {
23266 							freemsg(next_mp);
23267 							ire_refrele(ire1);
23268 						}
23269 						ire_refrele(ire);
23270 						TRACE_2(TR_FAC_IP,
23271 						    TR_IP_WPUT_IRE_END,
23272 						    "ip_wput_ire: q %p (%S)",
23273 						    q, "discard MDATA");
23274 						if (conn_outgoing_ill != NULL) {
23275 							ill_refrele(
23276 							    conn_outgoing_ill);
23277 						}
23278 						return;
23279 					}
23280 				}
23281 				if (!next_mp) {
23282 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23283 					    "ip_wput_ire_end: q %p (%S)",
23284 					    q, "last fragmentation");
23285 					ip_wput_ire_fragmentit(mp, ire,
23286 					    zoneid, ipst);
23287 					ire_refrele(ire);
23288 					if (conn_outgoing_ill != NULL)
23289 						ill_refrele(conn_outgoing_ill);
23290 					return;
23291 				}
23292 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23293 			}
23294 		}
23295 	} else {
23296 nullstq:
23297 		/* A NULL stq means the destination address is local. */
23298 		UPDATE_OB_PKT_COUNT(ire);
23299 		ire->ire_last_used_time = lbolt;
23300 		ASSERT(ire->ire_ipif != NULL);
23301 		if (!next_mp) {
23302 			/*
23303 			 * Is there an "in" and "out" for traffic local
23304 			 * to a host (loopback)?  The code in Solaris doesn't
23305 			 * explicitly draw a line in its code for in vs out,
23306 			 * so we've had to draw a line in the sand: ip_wput_ire
23307 			 * is considered to be the "output" side and
23308 			 * ip_wput_local to be the "input" side.
23309 			 */
23310 			out_ill = ire->ire_ipif->ipif_ill;
23311 
23312 			DTRACE_PROBE4(ip4__loopback__out__start,
23313 			    ill_t *, NULL, ill_t *, out_ill,
23314 			    ipha_t *, ipha, mblk_t *, first_mp);
23315 
23316 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23317 			    ipst->ips_ipv4firewall_loopback_out,
23318 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23319 
23320 			DTRACE_PROBE1(ip4__loopback__out_end,
23321 			    mblk_t *, first_mp);
23322 
23323 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23324 			    "ip_wput_ire_end: q %p (%S)",
23325 			    q, "local address");
23326 
23327 			if (first_mp != NULL)
23328 				ip_wput_local(q, out_ill, ipha,
23329 				    first_mp, ire, 0, ire->ire_zoneid);
23330 			ire_refrele(ire);
23331 			if (conn_outgoing_ill != NULL)
23332 				ill_refrele(conn_outgoing_ill);
23333 			return;
23334 		}
23335 
23336 		out_ill = ire->ire_ipif->ipif_ill;
23337 
23338 		DTRACE_PROBE4(ip4__loopback__out__start,
23339 		    ill_t *, NULL, ill_t *, out_ill,
23340 		    ipha_t *, ipha, mblk_t *, first_mp);
23341 
23342 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23343 		    ipst->ips_ipv4firewall_loopback_out,
23344 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23345 
23346 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23347 
23348 		if (first_mp != NULL)
23349 			ip_wput_local(q, out_ill, ipha,
23350 			    first_mp, ire, 0, ire->ire_zoneid);
23351 	}
23352 next:
23353 	/*
23354 	 * More copies going out to additional interfaces.
23355 	 * ire1 has already been held. We don't need the
23356 	 * "ire" anymore.
23357 	 */
23358 	ire_refrele(ire);
23359 	ire = ire1;
23360 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23361 	mp = next_mp;
23362 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23363 	ill = ire_to_ill(ire);
23364 	first_mp = mp;
23365 	if (ipsec_len != 0) {
23366 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23367 		mp = mp->b_cont;
23368 	}
23369 	dst = ire->ire_addr;
23370 	ipha = (ipha_t *)mp->b_rptr;
23371 	/*
23372 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23373 	 * Restore ipha_ident "no checksum" flag.
23374 	 */
23375 	src = orig_src;
23376 	ipha->ipha_ident = ip_hdr_included;
23377 	goto another;
23378 
23379 #undef	rptr
23380 #undef	Q_TO_INDEX
23381 }
23382 
23383 /*
23384  * Routine to allocate a message that is used to notify the ULP about MDT.
23385  * The caller may provide a pointer to the link-layer MDT capabilities,
23386  * or NULL if MDT is to be disabled on the stream.
23387  */
23388 mblk_t *
23389 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23390 {
23391 	mblk_t *mp;
23392 	ip_mdt_info_t *mdti;
23393 	ill_mdt_capab_t *idst;
23394 
23395 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23396 		DB_TYPE(mp) = M_CTL;
23397 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23398 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23399 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23400 		idst = &(mdti->mdt_capab);
23401 
23402 		/*
23403 		 * If the caller provides us with the capability, copy
23404 		 * it over into our notification message; otherwise
23405 		 * we zero out the capability portion.
23406 		 */
23407 		if (isrc != NULL)
23408 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23409 		else
23410 			bzero((caddr_t)idst, sizeof (*idst));
23411 	}
23412 	return (mp);
23413 }
23414 
23415 /*
23416  * Routine which determines whether MDT can be enabled on the destination
23417  * IRE and IPC combination, and if so, allocates and returns the MDT
23418  * notification mblk that may be used by ULP.  We also check if we need to
23419  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23420  * MDT usage in the past have been lifted.  This gets called during IP
23421  * and ULP binding.
23422  */
23423 mblk_t *
23424 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23425     ill_mdt_capab_t *mdt_cap)
23426 {
23427 	mblk_t *mp;
23428 	boolean_t rc = B_FALSE;
23429 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23430 
23431 	ASSERT(dst_ire != NULL);
23432 	ASSERT(connp != NULL);
23433 	ASSERT(mdt_cap != NULL);
23434 
23435 	/*
23436 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23437 	 * Multidata, which is handled in tcp_multisend().  This
23438 	 * is the reason why we do all these checks here, to ensure
23439 	 * that we don't enable Multidata for the cases which we
23440 	 * can't handle at the moment.
23441 	 */
23442 	do {
23443 		/* Only do TCP at the moment */
23444 		if (connp->conn_ulp != IPPROTO_TCP)
23445 			break;
23446 
23447 		/*
23448 		 * IPsec outbound policy present?  Note that we get here
23449 		 * after calling ipsec_conn_cache_policy() where the global
23450 		 * policy checking is performed.  conn_latch will be
23451 		 * non-NULL as long as there's a policy defined,
23452 		 * i.e. conn_out_enforce_policy may be NULL in such case
23453 		 * when the connection is non-secure, and hence we check
23454 		 * further if the latch refers to an outbound policy.
23455 		 */
23456 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23457 			break;
23458 
23459 		/* CGTP (multiroute) is enabled? */
23460 		if (dst_ire->ire_flags & RTF_MULTIRT)
23461 			break;
23462 
23463 		/* Outbound IPQoS enabled? */
23464 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23465 			/*
23466 			 * In this case, we disable MDT for this and all
23467 			 * future connections going over the interface.
23468 			 */
23469 			mdt_cap->ill_mdt_on = 0;
23470 			break;
23471 		}
23472 
23473 		/* socket option(s) present? */
23474 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23475 			break;
23476 
23477 		rc = B_TRUE;
23478 	/* CONSTCOND */
23479 	} while (0);
23480 
23481 	/* Remember the result */
23482 	connp->conn_mdt_ok = rc;
23483 
23484 	if (!rc)
23485 		return (NULL);
23486 	else if (!mdt_cap->ill_mdt_on) {
23487 		/*
23488 		 * If MDT has been previously turned off in the past, and we
23489 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23490 		 * then enable it for this interface.
23491 		 */
23492 		mdt_cap->ill_mdt_on = 1;
23493 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23494 		    "interface %s\n", ill_name));
23495 	}
23496 
23497 	/* Allocate the MDT info mblk */
23498 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23499 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23500 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23501 		return (NULL);
23502 	}
23503 	return (mp);
23504 }
23505 
23506 /*
23507  * Routine to allocate a message that is used to notify the ULP about LSO.
23508  * The caller may provide a pointer to the link-layer LSO capabilities,
23509  * or NULL if LSO is to be disabled on the stream.
23510  */
23511 mblk_t *
23512 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23513 {
23514 	mblk_t *mp;
23515 	ip_lso_info_t *lsoi;
23516 	ill_lso_capab_t *idst;
23517 
23518 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23519 		DB_TYPE(mp) = M_CTL;
23520 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23521 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23522 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23523 		idst = &(lsoi->lso_capab);
23524 
23525 		/*
23526 		 * If the caller provides us with the capability, copy
23527 		 * it over into our notification message; otherwise
23528 		 * we zero out the capability portion.
23529 		 */
23530 		if (isrc != NULL)
23531 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23532 		else
23533 			bzero((caddr_t)idst, sizeof (*idst));
23534 	}
23535 	return (mp);
23536 }
23537 
23538 /*
23539  * Routine which determines whether LSO can be enabled on the destination
23540  * IRE and IPC combination, and if so, allocates and returns the LSO
23541  * notification mblk that may be used by ULP.  We also check if we need to
23542  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23543  * LSO usage in the past have been lifted.  This gets called during IP
23544  * and ULP binding.
23545  */
23546 mblk_t *
23547 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23548     ill_lso_capab_t *lso_cap)
23549 {
23550 	mblk_t *mp;
23551 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23552 
23553 	ASSERT(dst_ire != NULL);
23554 	ASSERT(connp != NULL);
23555 	ASSERT(lso_cap != NULL);
23556 
23557 	connp->conn_lso_ok = B_TRUE;
23558 
23559 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23560 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23561 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23562 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23563 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23564 		connp->conn_lso_ok = B_FALSE;
23565 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23566 			/*
23567 			 * Disable LSO for this and all future connections going
23568 			 * over the interface.
23569 			 */
23570 			lso_cap->ill_lso_on = 0;
23571 		}
23572 	}
23573 
23574 	if (!connp->conn_lso_ok)
23575 		return (NULL);
23576 	else if (!lso_cap->ill_lso_on) {
23577 		/*
23578 		 * If LSO has been previously turned off in the past, and we
23579 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23580 		 * then enable it for this interface.
23581 		 */
23582 		lso_cap->ill_lso_on = 1;
23583 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23584 		    ill_name));
23585 	}
23586 
23587 	/* Allocate the LSO info mblk */
23588 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23589 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23590 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23591 
23592 	return (mp);
23593 }
23594 
23595 /*
23596  * Create destination address attribute, and fill it with the physical
23597  * destination address and SAP taken from the template DL_UNITDATA_REQ
23598  * message block.
23599  */
23600 boolean_t
23601 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23602 {
23603 	dl_unitdata_req_t *dlurp;
23604 	pattr_t *pa;
23605 	pattrinfo_t pa_info;
23606 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23607 	uint_t das_len, das_off;
23608 
23609 	ASSERT(dlmp != NULL);
23610 
23611 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23612 	das_len = dlurp->dl_dest_addr_length;
23613 	das_off = dlurp->dl_dest_addr_offset;
23614 
23615 	pa_info.type = PATTR_DSTADDRSAP;
23616 	pa_info.len = sizeof (**das) + das_len - 1;
23617 
23618 	/* create and associate the attribute */
23619 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23620 	if (pa != NULL) {
23621 		ASSERT(*das != NULL);
23622 		(*das)->addr_is_group = 0;
23623 		(*das)->addr_len = (uint8_t)das_len;
23624 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23625 	}
23626 
23627 	return (pa != NULL);
23628 }
23629 
23630 /*
23631  * Create hardware checksum attribute and fill it with the values passed.
23632  */
23633 boolean_t
23634 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23635     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23636 {
23637 	pattr_t *pa;
23638 	pattrinfo_t pa_info;
23639 
23640 	ASSERT(mmd != NULL);
23641 
23642 	pa_info.type = PATTR_HCKSUM;
23643 	pa_info.len = sizeof (pattr_hcksum_t);
23644 
23645 	/* create and associate the attribute */
23646 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23647 	if (pa != NULL) {
23648 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23649 
23650 		hck->hcksum_start_offset = start_offset;
23651 		hck->hcksum_stuff_offset = stuff_offset;
23652 		hck->hcksum_end_offset = end_offset;
23653 		hck->hcksum_flags = flags;
23654 	}
23655 	return (pa != NULL);
23656 }
23657 
23658 /*
23659  * Create zerocopy attribute and fill it with the specified flags
23660  */
23661 boolean_t
23662 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23663 {
23664 	pattr_t *pa;
23665 	pattrinfo_t pa_info;
23666 
23667 	ASSERT(mmd != NULL);
23668 	pa_info.type = PATTR_ZCOPY;
23669 	pa_info.len = sizeof (pattr_zcopy_t);
23670 
23671 	/* create and associate the attribute */
23672 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23673 	if (pa != NULL) {
23674 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23675 
23676 		zcopy->zcopy_flags = flags;
23677 	}
23678 	return (pa != NULL);
23679 }
23680 
23681 /*
23682  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23683  * block chain. We could rewrite to handle arbitrary message block chains but
23684  * that would make the code complicated and slow. Right now there three
23685  * restrictions:
23686  *
23687  *   1. The first message block must contain the complete IP header and
23688  *	at least 1 byte of payload data.
23689  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23690  *	so that we can use a single Multidata message.
23691  *   3. No frag must be distributed over two or more message blocks so
23692  *	that we don't need more than two packet descriptors per frag.
23693  *
23694  * The above restrictions allow us to support userland applications (which
23695  * will send down a single message block) and NFS over UDP (which will
23696  * send down a chain of at most three message blocks).
23697  *
23698  * We also don't use MDT for payloads with less than or equal to
23699  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23700  */
23701 boolean_t
23702 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23703 {
23704 	int	blocks;
23705 	ssize_t	total, missing, size;
23706 
23707 	ASSERT(mp != NULL);
23708 	ASSERT(hdr_len > 0);
23709 
23710 	size = MBLKL(mp) - hdr_len;
23711 	if (size <= 0)
23712 		return (B_FALSE);
23713 
23714 	/* The first mblk contains the header and some payload. */
23715 	blocks = 1;
23716 	total = size;
23717 	size %= len;
23718 	missing = (size == 0) ? 0 : (len - size);
23719 	mp = mp->b_cont;
23720 
23721 	while (mp != NULL) {
23722 		/*
23723 		 * Give up if we encounter a zero length message block.
23724 		 * In practice, this should rarely happen and therefore
23725 		 * not worth the trouble of freeing and re-linking the
23726 		 * mblk from the chain to handle such case.
23727 		 */
23728 		if ((size = MBLKL(mp)) == 0)
23729 			return (B_FALSE);
23730 
23731 		/* Too many payload buffers for a single Multidata message? */
23732 		if (++blocks > MULTIDATA_MAX_PBUFS)
23733 			return (B_FALSE);
23734 
23735 		total += size;
23736 		/* Is a frag distributed over two or more message blocks? */
23737 		if (missing > size)
23738 			return (B_FALSE);
23739 		size -= missing;
23740 
23741 		size %= len;
23742 		missing = (size == 0) ? 0 : (len - size);
23743 
23744 		mp = mp->b_cont;
23745 	}
23746 
23747 	return (total > ip_wput_frag_mdt_min);
23748 }
23749 
23750 /*
23751  * Outbound IPv4 fragmentation routine using MDT.
23752  */
23753 static void
23754 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23755     uint32_t frag_flag, int offset)
23756 {
23757 	ipha_t		*ipha_orig;
23758 	int		i1, ip_data_end;
23759 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23760 	mblk_t		*hdr_mp, *md_mp = NULL;
23761 	unsigned char	*hdr_ptr, *pld_ptr;
23762 	multidata_t	*mmd;
23763 	ip_pdescinfo_t	pdi;
23764 	ill_t		*ill;
23765 	ip_stack_t	*ipst = ire->ire_ipst;
23766 
23767 	ASSERT(DB_TYPE(mp) == M_DATA);
23768 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23769 
23770 	ill = ire_to_ill(ire);
23771 	ASSERT(ill != NULL);
23772 
23773 	ipha_orig = (ipha_t *)mp->b_rptr;
23774 	mp->b_rptr += sizeof (ipha_t);
23775 
23776 	/* Calculate how many packets we will send out */
23777 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23778 	pkts = (i1 + len - 1) / len;
23779 	ASSERT(pkts > 1);
23780 
23781 	/* Allocate a message block which will hold all the IP Headers. */
23782 	wroff = ipst->ips_ip_wroff_extra;
23783 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23784 
23785 	i1 = pkts * hdr_chunk_len;
23786 	/*
23787 	 * Create the header buffer, Multidata and destination address
23788 	 * and SAP attribute that should be associated with it.
23789 	 */
23790 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23791 	    ((hdr_mp->b_wptr += i1),
23792 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23793 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23794 		freemsg(mp);
23795 		if (md_mp == NULL) {
23796 			freemsg(hdr_mp);
23797 		} else {
23798 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23799 			freemsg(md_mp);
23800 		}
23801 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23802 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23803 		return;
23804 	}
23805 	IP_STAT(ipst, ip_frag_mdt_allocd);
23806 
23807 	/*
23808 	 * Add a payload buffer to the Multidata; this operation must not
23809 	 * fail, or otherwise our logic in this routine is broken.  There
23810 	 * is no memory allocation done by the routine, so any returned
23811 	 * failure simply tells us that we've done something wrong.
23812 	 *
23813 	 * A failure tells us that either we're adding the same payload
23814 	 * buffer more than once, or we're trying to add more buffers than
23815 	 * allowed.  None of the above cases should happen, and we panic
23816 	 * because either there's horrible heap corruption, and/or
23817 	 * programming mistake.
23818 	 */
23819 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23820 		goto pbuf_panic;
23821 
23822 	hdr_ptr = hdr_mp->b_rptr;
23823 	pld_ptr = mp->b_rptr;
23824 
23825 	/* Establish the ending byte offset, based on the starting offset. */
23826 	offset <<= 3;
23827 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23828 	    IP_SIMPLE_HDR_LENGTH;
23829 
23830 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23831 
23832 	while (pld_ptr < mp->b_wptr) {
23833 		ipha_t		*ipha;
23834 		uint16_t	offset_and_flags;
23835 		uint16_t	ip_len;
23836 		int		error;
23837 
23838 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23839 		ipha = (ipha_t *)(hdr_ptr + wroff);
23840 		ASSERT(OK_32PTR(ipha));
23841 		*ipha = *ipha_orig;
23842 
23843 		if (ip_data_end - offset > len) {
23844 			offset_and_flags = IPH_MF;
23845 		} else {
23846 			/*
23847 			 * Last frag. Set len to the length of this last piece.
23848 			 */
23849 			len = ip_data_end - offset;
23850 			/* A frag of a frag might have IPH_MF non-zero */
23851 			offset_and_flags =
23852 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23853 			    IPH_MF;
23854 		}
23855 		offset_and_flags |= (uint16_t)(offset >> 3);
23856 		offset_and_flags |= (uint16_t)frag_flag;
23857 		/* Store the offset and flags in the IP header. */
23858 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23859 
23860 		/* Store the length in the IP header. */
23861 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23862 		ipha->ipha_length = htons(ip_len);
23863 
23864 		/*
23865 		 * Set the IP header checksum.  Note that mp is just
23866 		 * the header, so this is easy to pass to ip_csum.
23867 		 */
23868 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23869 
23870 		/*
23871 		 * Record offset and size of header and data of the next packet
23872 		 * in the multidata message.
23873 		 */
23874 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23875 		PDESC_PLD_INIT(&pdi);
23876 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23877 		ASSERT(i1 > 0);
23878 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23879 		if (i1 == len) {
23880 			pld_ptr += len;
23881 		} else {
23882 			i1 = len - i1;
23883 			mp = mp->b_cont;
23884 			ASSERT(mp != NULL);
23885 			ASSERT(MBLKL(mp) >= i1);
23886 			/*
23887 			 * Attach the next payload message block to the
23888 			 * multidata message.
23889 			 */
23890 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23891 				goto pbuf_panic;
23892 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23893 			pld_ptr = mp->b_rptr + i1;
23894 		}
23895 
23896 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23897 		    KM_NOSLEEP)) == NULL) {
23898 			/*
23899 			 * Any failure other than ENOMEM indicates that we
23900 			 * have passed in invalid pdesc info or parameters
23901 			 * to mmd_addpdesc, which must not happen.
23902 			 *
23903 			 * EINVAL is a result of failure on boundary checks
23904 			 * against the pdesc info contents.  It should not
23905 			 * happen, and we panic because either there's
23906 			 * horrible heap corruption, and/or programming
23907 			 * mistake.
23908 			 */
23909 			if (error != ENOMEM) {
23910 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23911 				    "pdesc logic error detected for "
23912 				    "mmd %p pinfo %p (%d)\n",
23913 				    (void *)mmd, (void *)&pdi, error);
23914 				/* NOTREACHED */
23915 			}
23916 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23917 			/* Free unattached payload message blocks as well */
23918 			md_mp->b_cont = mp->b_cont;
23919 			goto free_mmd;
23920 		}
23921 
23922 		/* Advance fragment offset. */
23923 		offset += len;
23924 
23925 		/* Advance to location for next header in the buffer. */
23926 		hdr_ptr += hdr_chunk_len;
23927 
23928 		/* Did we reach the next payload message block? */
23929 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23930 			mp = mp->b_cont;
23931 			/*
23932 			 * Attach the next message block with payload
23933 			 * data to the multidata message.
23934 			 */
23935 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23936 				goto pbuf_panic;
23937 			pld_ptr = mp->b_rptr;
23938 		}
23939 	}
23940 
23941 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23942 	ASSERT(mp->b_wptr == pld_ptr);
23943 
23944 	/* Update IP statistics */
23945 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23946 
23947 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23948 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23949 
23950 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23951 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23952 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23953 
23954 	if (pkt_type == OB_PKT) {
23955 		ire->ire_ob_pkt_count += pkts;
23956 		if (ire->ire_ipif != NULL)
23957 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23958 	} else {
23959 		/* The type is IB_PKT in the forwarding path. */
23960 		ire->ire_ib_pkt_count += pkts;
23961 		ASSERT(!IRE_IS_LOCAL(ire));
23962 		if (ire->ire_type & IRE_BROADCAST) {
23963 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23964 		} else {
23965 			UPDATE_MIB(ill->ill_ip_mib,
23966 			    ipIfStatsHCOutForwDatagrams, pkts);
23967 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23968 		}
23969 	}
23970 	ire->ire_last_used_time = lbolt;
23971 	/* Send it down */
23972 	putnext(ire->ire_stq, md_mp);
23973 	return;
23974 
23975 pbuf_panic:
23976 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23977 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23978 	    pbuf_idx);
23979 	/* NOTREACHED */
23980 }
23981 
23982 /*
23983  * Outbound IP fragmentation routine.
23984  *
23985  * NOTE : This routine does not ire_refrele the ire that is passed in
23986  * as the argument.
23987  */
23988 static void
23989 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23990     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
23991 {
23992 	int		i1;
23993 	mblk_t		*ll_hdr_mp;
23994 	int 		ll_hdr_len;
23995 	int		hdr_len;
23996 	mblk_t		*hdr_mp;
23997 	ipha_t		*ipha;
23998 	int		ip_data_end;
23999 	int		len;
24000 	mblk_t		*mp = mp_orig, *mp1;
24001 	int		offset;
24002 	queue_t		*q;
24003 	uint32_t	v_hlen_tos_len;
24004 	mblk_t		*first_mp;
24005 	boolean_t	mctl_present;
24006 	ill_t		*ill;
24007 	ill_t		*out_ill;
24008 	mblk_t		*xmit_mp;
24009 	mblk_t		*carve_mp;
24010 	ire_t		*ire1 = NULL;
24011 	ire_t		*save_ire = NULL;
24012 	mblk_t  	*next_mp = NULL;
24013 	boolean_t	last_frag = B_FALSE;
24014 	boolean_t	multirt_send = B_FALSE;
24015 	ire_t		*first_ire = NULL;
24016 	irb_t		*irb = NULL;
24017 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24018 
24019 	ill = ire_to_ill(ire);
24020 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24021 
24022 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24023 
24024 	if (max_frag == 0) {
24025 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24026 		    " -  dropping packet\n"));
24027 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24028 		freemsg(mp);
24029 		return;
24030 	}
24031 
24032 	/*
24033 	 * IPsec does not allow hw accelerated packets to be fragmented
24034 	 * This check is made in ip_wput_ipsec_out prior to coming here
24035 	 * via ip_wput_ire_fragmentit.
24036 	 *
24037 	 * If at this point we have an ire whose ARP request has not
24038 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24039 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24040 	 * This packet and all fragmentable packets for this ire will
24041 	 * continue to get dropped while ire_nce->nce_state remains in
24042 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24043 	 * ND_REACHABLE, all subsquent large packets for this ire will
24044 	 * get fragemented and sent out by this function.
24045 	 */
24046 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24047 		/* If nce_state is ND_INITIAL, trigger ARP query */
24048 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24049 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24050 		    " -  dropping packet\n"));
24051 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24052 		freemsg(mp);
24053 		return;
24054 	}
24055 
24056 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24057 	    "ip_wput_frag_start:");
24058 
24059 	if (mp->b_datap->db_type == M_CTL) {
24060 		first_mp = mp;
24061 		mp_orig = mp = mp->b_cont;
24062 		mctl_present = B_TRUE;
24063 	} else {
24064 		first_mp = mp;
24065 		mctl_present = B_FALSE;
24066 	}
24067 
24068 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24069 	ipha = (ipha_t *)mp->b_rptr;
24070 
24071 	/*
24072 	 * If the Don't Fragment flag is on, generate an ICMP destination
24073 	 * unreachable, fragmentation needed.
24074 	 */
24075 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24076 	if (offset & IPH_DF) {
24077 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24078 		if (is_system_labeled()) {
24079 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24080 			    ire->ire_max_frag - max_frag, AF_INET);
24081 		}
24082 		/*
24083 		 * Need to compute hdr checksum if called from ip_wput_ire.
24084 		 * Note that ip_rput_forward verifies the checksum before
24085 		 * calling this routine so in that case this is a noop.
24086 		 */
24087 		ipha->ipha_hdr_checksum = 0;
24088 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24089 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24090 		    ipst);
24091 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24092 		    "ip_wput_frag_end:(%S)",
24093 		    "don't fragment");
24094 		return;
24095 	}
24096 	/*
24097 	 * Labeled systems adjust max_frag if they add a label
24098 	 * to send the correct path mtu.  We need the real mtu since we
24099 	 * are fragmenting the packet after label adjustment.
24100 	 */
24101 	if (is_system_labeled())
24102 		max_frag = ire->ire_max_frag;
24103 	if (mctl_present)
24104 		freeb(first_mp);
24105 	/*
24106 	 * Establish the starting offset.  May not be zero if we are fragging
24107 	 * a fragment that is being forwarded.
24108 	 */
24109 	offset = offset & IPH_OFFSET;
24110 
24111 	/* TODO why is this test needed? */
24112 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24113 	if (((max_frag - LENGTH) & ~7) < 8) {
24114 		/* TODO: notify ulp somehow */
24115 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24116 		freemsg(mp);
24117 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24118 		    "ip_wput_frag_end:(%S)",
24119 		    "len < 8");
24120 		return;
24121 	}
24122 
24123 	hdr_len = (V_HLEN & 0xF) << 2;
24124 
24125 	ipha->ipha_hdr_checksum = 0;
24126 
24127 	/*
24128 	 * Establish the number of bytes maximum per frag, after putting
24129 	 * in the header.
24130 	 */
24131 	len = (max_frag - hdr_len) & ~7;
24132 
24133 	/* Check if we can use MDT to send out the frags. */
24134 	ASSERT(!IRE_IS_LOCAL(ire));
24135 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24136 	    ipst->ips_ip_multidata_outbound &&
24137 	    !(ire->ire_flags & RTF_MULTIRT) &&
24138 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24139 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24140 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24141 		ASSERT(ill->ill_mdt_capab != NULL);
24142 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24143 			/*
24144 			 * If MDT has been previously turned off in the past,
24145 			 * and we currently can do MDT (due to IPQoS policy
24146 			 * removal, etc.) then enable it for this interface.
24147 			 */
24148 			ill->ill_mdt_capab->ill_mdt_on = 1;
24149 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24150 			    ill->ill_name));
24151 		}
24152 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24153 		    offset);
24154 		return;
24155 	}
24156 
24157 	/* Get a copy of the header for the trailing frags */
24158 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24159 	if (!hdr_mp) {
24160 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24161 		freemsg(mp);
24162 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24163 		    "ip_wput_frag_end:(%S)",
24164 		    "couldn't copy hdr");
24165 		return;
24166 	}
24167 	if (DB_CRED(mp) != NULL)
24168 		mblk_setcred(hdr_mp, DB_CRED(mp));
24169 
24170 	/* Store the starting offset, with the MoreFrags flag. */
24171 	i1 = offset | IPH_MF | frag_flag;
24172 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24173 
24174 	/* Establish the ending byte offset, based on the starting offset. */
24175 	offset <<= 3;
24176 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24177 
24178 	/* Store the length of the first fragment in the IP header. */
24179 	i1 = len + hdr_len;
24180 	ASSERT(i1 <= IP_MAXPACKET);
24181 	ipha->ipha_length = htons((uint16_t)i1);
24182 
24183 	/*
24184 	 * Compute the IP header checksum for the first frag.  We have to
24185 	 * watch out that we stop at the end of the header.
24186 	 */
24187 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24188 
24189 	/*
24190 	 * Now carve off the first frag.  Note that this will include the
24191 	 * original IP header.
24192 	 */
24193 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24194 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24195 		freeb(hdr_mp);
24196 		freemsg(mp_orig);
24197 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24198 		    "ip_wput_frag_end:(%S)",
24199 		    "couldn't carve first");
24200 		return;
24201 	}
24202 
24203 	/*
24204 	 * Multirouting case. Each fragment is replicated
24205 	 * via all non-condemned RTF_MULTIRT routes
24206 	 * currently resolved.
24207 	 * We ensure that first_ire is the first RTF_MULTIRT
24208 	 * ire in the bucket.
24209 	 */
24210 	if (ire->ire_flags & RTF_MULTIRT) {
24211 		irb = ire->ire_bucket;
24212 		ASSERT(irb != NULL);
24213 
24214 		multirt_send = B_TRUE;
24215 
24216 		/* Make sure we do not omit any multiroute ire. */
24217 		IRB_REFHOLD(irb);
24218 		for (first_ire = irb->irb_ire;
24219 		    first_ire != NULL;
24220 		    first_ire = first_ire->ire_next) {
24221 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24222 			    (first_ire->ire_addr == ire->ire_addr) &&
24223 			    !(first_ire->ire_marks &
24224 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24225 				break;
24226 			}
24227 		}
24228 
24229 		if (first_ire != NULL) {
24230 			if (first_ire != ire) {
24231 				IRE_REFHOLD(first_ire);
24232 				/*
24233 				 * Do not release the ire passed in
24234 				 * as the argument.
24235 				 */
24236 				ire = first_ire;
24237 			} else {
24238 				first_ire = NULL;
24239 			}
24240 		}
24241 		IRB_REFRELE(irb);
24242 
24243 		/*
24244 		 * Save the first ire; we will need to restore it
24245 		 * for the trailing frags.
24246 		 * We REFHOLD save_ire, as each iterated ire will be
24247 		 * REFRELEd.
24248 		 */
24249 		save_ire = ire;
24250 		IRE_REFHOLD(save_ire);
24251 	}
24252 
24253 	/*
24254 	 * First fragment emission loop.
24255 	 * In most cases, the emission loop below is entered only
24256 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24257 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24258 	 * bucket, and send the fragment through all crossed
24259 	 * RTF_MULTIRT routes.
24260 	 */
24261 	do {
24262 		if (ire->ire_flags & RTF_MULTIRT) {
24263 			/*
24264 			 * We are in a multiple send case, need to get
24265 			 * the next ire and make a copy of the packet.
24266 			 * ire1 holds here the next ire to process in the
24267 			 * bucket. If multirouting is expected,
24268 			 * any non-RTF_MULTIRT ire that has the
24269 			 * right destination address is ignored.
24270 			 *
24271 			 * We have to take into account the MTU of
24272 			 * each walked ire. max_frag is set by the
24273 			 * the caller and generally refers to
24274 			 * the primary ire entry. Here we ensure that
24275 			 * no route with a lower MTU will be used, as
24276 			 * fragments are carved once for all ires,
24277 			 * then replicated.
24278 			 */
24279 			ASSERT(irb != NULL);
24280 			IRB_REFHOLD(irb);
24281 			for (ire1 = ire->ire_next;
24282 			    ire1 != NULL;
24283 			    ire1 = ire1->ire_next) {
24284 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24285 					continue;
24286 				if (ire1->ire_addr != ire->ire_addr)
24287 					continue;
24288 				if (ire1->ire_marks &
24289 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24290 					continue;
24291 				/*
24292 				 * Ensure we do not exceed the MTU
24293 				 * of the next route.
24294 				 */
24295 				if (ire1->ire_max_frag < max_frag) {
24296 					ip_multirt_bad_mtu(ire1, max_frag);
24297 					continue;
24298 				}
24299 
24300 				/* Got one. */
24301 				IRE_REFHOLD(ire1);
24302 				break;
24303 			}
24304 			IRB_REFRELE(irb);
24305 
24306 			if (ire1 != NULL) {
24307 				next_mp = copyb(mp);
24308 				if ((next_mp == NULL) ||
24309 				    ((mp->b_cont != NULL) &&
24310 				    ((next_mp->b_cont =
24311 				    dupmsg(mp->b_cont)) == NULL))) {
24312 					freemsg(next_mp);
24313 					next_mp = NULL;
24314 					ire_refrele(ire1);
24315 					ire1 = NULL;
24316 				}
24317 			}
24318 
24319 			/* Last multiroute ire; don't loop anymore. */
24320 			if (ire1 == NULL) {
24321 				multirt_send = B_FALSE;
24322 			}
24323 		}
24324 
24325 		ll_hdr_len = 0;
24326 		LOCK_IRE_FP_MP(ire);
24327 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24328 		if (ll_hdr_mp != NULL) {
24329 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24330 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24331 		} else {
24332 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24333 		}
24334 
24335 		/* If there is a transmit header, get a copy for this frag. */
24336 		/*
24337 		 * TODO: should check db_ref before calling ip_carve_mp since
24338 		 * it might give us a dup.
24339 		 */
24340 		if (!ll_hdr_mp) {
24341 			/* No xmit header. */
24342 			xmit_mp = mp;
24343 
24344 		/* We have a link-layer header that can fit in our mblk. */
24345 		} else if (mp->b_datap->db_ref == 1 &&
24346 		    ll_hdr_len != 0 &&
24347 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24348 			/* M_DATA fastpath */
24349 			mp->b_rptr -= ll_hdr_len;
24350 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24351 			xmit_mp = mp;
24352 
24353 		/* Corner case if copyb has failed */
24354 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24355 			UNLOCK_IRE_FP_MP(ire);
24356 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24357 			freeb(hdr_mp);
24358 			freemsg(mp);
24359 			freemsg(mp_orig);
24360 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24361 			    "ip_wput_frag_end:(%S)",
24362 			    "discard");
24363 
24364 			if (multirt_send) {
24365 				ASSERT(ire1);
24366 				ASSERT(next_mp);
24367 
24368 				freemsg(next_mp);
24369 				ire_refrele(ire1);
24370 			}
24371 			if (save_ire != NULL)
24372 				IRE_REFRELE(save_ire);
24373 
24374 			if (first_ire != NULL)
24375 				ire_refrele(first_ire);
24376 			return;
24377 
24378 		/*
24379 		 * Case of res_mp OR the fastpath mp can't fit
24380 		 * in the mblk
24381 		 */
24382 		} else {
24383 			xmit_mp->b_cont = mp;
24384 			if (DB_CRED(mp) != NULL)
24385 				mblk_setcred(xmit_mp, DB_CRED(mp));
24386 			/*
24387 			 * Get priority marking, if any.
24388 			 * We propagate the CoS marking from the
24389 			 * original packet that went to QoS processing
24390 			 * in ip_wput_ire to the newly carved mp.
24391 			 */
24392 			if (DB_TYPE(xmit_mp) == M_DATA)
24393 				xmit_mp->b_band = mp->b_band;
24394 		}
24395 		UNLOCK_IRE_FP_MP(ire);
24396 
24397 		q = ire->ire_stq;
24398 		out_ill = (ill_t *)q->q_ptr;
24399 
24400 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24401 
24402 		DTRACE_PROBE4(ip4__physical__out__start,
24403 		    ill_t *, NULL, ill_t *, out_ill,
24404 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24405 
24406 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24407 		    ipst->ips_ipv4firewall_physical_out,
24408 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24409 
24410 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24411 
24412 		if (xmit_mp != NULL) {
24413 			putnext(q, xmit_mp);
24414 
24415 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24416 			UPDATE_MIB(out_ill->ill_ip_mib,
24417 			    ipIfStatsHCOutOctets, i1);
24418 
24419 			if (pkt_type != OB_PKT) {
24420 				/*
24421 				 * Update the packet count and MIB stats
24422 				 * of trailing RTF_MULTIRT ires.
24423 				 */
24424 				UPDATE_OB_PKT_COUNT(ire);
24425 				BUMP_MIB(out_ill->ill_ip_mib,
24426 				    ipIfStatsOutFragReqds);
24427 			}
24428 		}
24429 
24430 		if (multirt_send) {
24431 			/*
24432 			 * We are in a multiple send case; look for
24433 			 * the next ire and re-enter the loop.
24434 			 */
24435 			ASSERT(ire1);
24436 			ASSERT(next_mp);
24437 			/* REFRELE the current ire before looping */
24438 			ire_refrele(ire);
24439 			ire = ire1;
24440 			ire1 = NULL;
24441 			mp = next_mp;
24442 			next_mp = NULL;
24443 		}
24444 	} while (multirt_send);
24445 
24446 	ASSERT(ire1 == NULL);
24447 
24448 	/* Restore the original ire; we need it for the trailing frags */
24449 	if (save_ire != NULL) {
24450 		/* REFRELE the last iterated ire */
24451 		ire_refrele(ire);
24452 		/* save_ire has been REFHOLDed */
24453 		ire = save_ire;
24454 		save_ire = NULL;
24455 		q = ire->ire_stq;
24456 	}
24457 
24458 	if (pkt_type == OB_PKT) {
24459 		UPDATE_OB_PKT_COUNT(ire);
24460 	} else {
24461 		out_ill = (ill_t *)q->q_ptr;
24462 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24463 		UPDATE_IB_PKT_COUNT(ire);
24464 	}
24465 
24466 	/* Advance the offset to the second frag starting point. */
24467 	offset += len;
24468 	/*
24469 	 * Update hdr_len from the copied header - there might be less options
24470 	 * in the later fragments.
24471 	 */
24472 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24473 	/* Loop until done. */
24474 	for (;;) {
24475 		uint16_t	offset_and_flags;
24476 		uint16_t	ip_len;
24477 
24478 		if (ip_data_end - offset > len) {
24479 			/*
24480 			 * Carve off the appropriate amount from the original
24481 			 * datagram.
24482 			 */
24483 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24484 				mp = NULL;
24485 				break;
24486 			}
24487 			/*
24488 			 * More frags after this one.  Get another copy
24489 			 * of the header.
24490 			 */
24491 			if (carve_mp->b_datap->db_ref == 1 &&
24492 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24493 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24494 				/* Inline IP header */
24495 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24496 				    hdr_mp->b_rptr;
24497 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24498 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24499 				mp = carve_mp;
24500 			} else {
24501 				if (!(mp = copyb(hdr_mp))) {
24502 					freemsg(carve_mp);
24503 					break;
24504 				}
24505 				/* Get priority marking, if any. */
24506 				mp->b_band = carve_mp->b_band;
24507 				mp->b_cont = carve_mp;
24508 			}
24509 			ipha = (ipha_t *)mp->b_rptr;
24510 			offset_and_flags = IPH_MF;
24511 		} else {
24512 			/*
24513 			 * Last frag.  Consume the header. Set len to
24514 			 * the length of this last piece.
24515 			 */
24516 			len = ip_data_end - offset;
24517 
24518 			/*
24519 			 * Carve off the appropriate amount from the original
24520 			 * datagram.
24521 			 */
24522 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24523 				mp = NULL;
24524 				break;
24525 			}
24526 			if (carve_mp->b_datap->db_ref == 1 &&
24527 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24528 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24529 				/* Inline IP header */
24530 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24531 				    hdr_mp->b_rptr;
24532 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24533 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24534 				mp = carve_mp;
24535 				freeb(hdr_mp);
24536 				hdr_mp = mp;
24537 			} else {
24538 				mp = hdr_mp;
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 			/* A frag of a frag might have IPH_MF non-zero */
24545 			offset_and_flags =
24546 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24547 			    IPH_MF;
24548 		}
24549 		offset_and_flags |= (uint16_t)(offset >> 3);
24550 		offset_and_flags |= (uint16_t)frag_flag;
24551 		/* Store the offset and flags in the IP header. */
24552 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24553 
24554 		/* Store the length in the IP header. */
24555 		ip_len = (uint16_t)(len + hdr_len);
24556 		ipha->ipha_length = htons(ip_len);
24557 
24558 		/*
24559 		 * Set the IP header checksum.	Note that mp is just
24560 		 * the header, so this is easy to pass to ip_csum.
24561 		 */
24562 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24563 
24564 		/* Attach a transmit header, if any, and ship it. */
24565 		if (pkt_type == OB_PKT) {
24566 			UPDATE_OB_PKT_COUNT(ire);
24567 		} else {
24568 			out_ill = (ill_t *)q->q_ptr;
24569 			BUMP_MIB(out_ill->ill_ip_mib,
24570 			    ipIfStatsHCOutForwDatagrams);
24571 			UPDATE_IB_PKT_COUNT(ire);
24572 		}
24573 
24574 		if (ire->ire_flags & RTF_MULTIRT) {
24575 			irb = ire->ire_bucket;
24576 			ASSERT(irb != NULL);
24577 
24578 			multirt_send = B_TRUE;
24579 
24580 			/*
24581 			 * Save the original ire; we will need to restore it
24582 			 * for the tailing frags.
24583 			 */
24584 			save_ire = ire;
24585 			IRE_REFHOLD(save_ire);
24586 		}
24587 		/*
24588 		 * Emission loop for this fragment, similar
24589 		 * to what is done for the first fragment.
24590 		 */
24591 		do {
24592 			if (multirt_send) {
24593 				/*
24594 				 * We are in a multiple send case, need to get
24595 				 * the next ire and make a copy of the packet.
24596 				 */
24597 				ASSERT(irb != NULL);
24598 				IRB_REFHOLD(irb);
24599 				for (ire1 = ire->ire_next;
24600 				    ire1 != NULL;
24601 				    ire1 = ire1->ire_next) {
24602 					if (!(ire1->ire_flags & RTF_MULTIRT))
24603 						continue;
24604 					if (ire1->ire_addr != ire->ire_addr)
24605 						continue;
24606 					if (ire1->ire_marks &
24607 					    (IRE_MARK_CONDEMNED|
24608 					    IRE_MARK_HIDDEN)) {
24609 						continue;
24610 					}
24611 					/*
24612 					 * Ensure we do not exceed the MTU
24613 					 * of the next route.
24614 					 */
24615 					if (ire1->ire_max_frag < max_frag) {
24616 						ip_multirt_bad_mtu(ire1,
24617 						    max_frag);
24618 						continue;
24619 					}
24620 
24621 					/* Got one. */
24622 					IRE_REFHOLD(ire1);
24623 					break;
24624 				}
24625 				IRB_REFRELE(irb);
24626 
24627 				if (ire1 != NULL) {
24628 					next_mp = copyb(mp);
24629 					if ((next_mp == NULL) ||
24630 					    ((mp->b_cont != NULL) &&
24631 					    ((next_mp->b_cont =
24632 					    dupmsg(mp->b_cont)) == NULL))) {
24633 						freemsg(next_mp);
24634 						next_mp = NULL;
24635 						ire_refrele(ire1);
24636 						ire1 = NULL;
24637 					}
24638 				}
24639 
24640 				/* Last multiroute ire; don't loop anymore. */
24641 				if (ire1 == NULL) {
24642 					multirt_send = B_FALSE;
24643 				}
24644 			}
24645 
24646 			/* Update transmit header */
24647 			ll_hdr_len = 0;
24648 			LOCK_IRE_FP_MP(ire);
24649 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24650 			if (ll_hdr_mp != NULL) {
24651 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24652 				ll_hdr_len = MBLKL(ll_hdr_mp);
24653 			} else {
24654 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24655 			}
24656 
24657 			if (!ll_hdr_mp) {
24658 				xmit_mp = mp;
24659 
24660 			/*
24661 			 * We have link-layer header that can fit in
24662 			 * our mblk.
24663 			 */
24664 			} else if (mp->b_datap->db_ref == 1 &&
24665 			    ll_hdr_len != 0 &&
24666 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24667 				/* M_DATA fastpath */
24668 				mp->b_rptr -= ll_hdr_len;
24669 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24670 				    ll_hdr_len);
24671 				xmit_mp = mp;
24672 
24673 			/*
24674 			 * Case of res_mp OR the fastpath mp can't fit
24675 			 * in the mblk
24676 			 */
24677 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24678 				xmit_mp->b_cont = mp;
24679 				if (DB_CRED(mp) != NULL)
24680 					mblk_setcred(xmit_mp, DB_CRED(mp));
24681 				/* Get priority marking, if any. */
24682 				if (DB_TYPE(xmit_mp) == M_DATA)
24683 					xmit_mp->b_band = mp->b_band;
24684 
24685 			/* Corner case if copyb failed */
24686 			} else {
24687 				/*
24688 				 * Exit both the replication and
24689 				 * fragmentation loops.
24690 				 */
24691 				UNLOCK_IRE_FP_MP(ire);
24692 				goto drop_pkt;
24693 			}
24694 			UNLOCK_IRE_FP_MP(ire);
24695 
24696 			mp1 = mp;
24697 			out_ill = (ill_t *)q->q_ptr;
24698 
24699 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24700 
24701 			DTRACE_PROBE4(ip4__physical__out__start,
24702 			    ill_t *, NULL, ill_t *, out_ill,
24703 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24704 
24705 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24706 			    ipst->ips_ipv4firewall_physical_out,
24707 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24708 
24709 			DTRACE_PROBE1(ip4__physical__out__end,
24710 			    mblk_t *, xmit_mp);
24711 
24712 			if (mp != mp1 && hdr_mp == mp1)
24713 				hdr_mp = mp;
24714 			if (mp != mp1 && mp_orig == mp1)
24715 				mp_orig = mp;
24716 
24717 			if (xmit_mp != NULL) {
24718 				putnext(q, xmit_mp);
24719 
24720 				BUMP_MIB(out_ill->ill_ip_mib,
24721 				    ipIfStatsHCOutTransmits);
24722 				UPDATE_MIB(out_ill->ill_ip_mib,
24723 				    ipIfStatsHCOutOctets, ip_len);
24724 
24725 				if (pkt_type != OB_PKT) {
24726 					/*
24727 					 * Update the packet count of trailing
24728 					 * RTF_MULTIRT ires.
24729 					 */
24730 					UPDATE_OB_PKT_COUNT(ire);
24731 				}
24732 			}
24733 
24734 			/* All done if we just consumed the hdr_mp. */
24735 			if (mp == hdr_mp) {
24736 				last_frag = B_TRUE;
24737 				BUMP_MIB(out_ill->ill_ip_mib,
24738 				    ipIfStatsOutFragOKs);
24739 			}
24740 
24741 			if (multirt_send) {
24742 				/*
24743 				 * We are in a multiple send case; look for
24744 				 * the next ire and re-enter the loop.
24745 				 */
24746 				ASSERT(ire1);
24747 				ASSERT(next_mp);
24748 				/* REFRELE the current ire before looping */
24749 				ire_refrele(ire);
24750 				ire = ire1;
24751 				ire1 = NULL;
24752 				q = ire->ire_stq;
24753 				mp = next_mp;
24754 				next_mp = NULL;
24755 			}
24756 		} while (multirt_send);
24757 		/*
24758 		 * Restore the original ire; we need it for the
24759 		 * trailing frags
24760 		 */
24761 		if (save_ire != NULL) {
24762 			ASSERT(ire1 == NULL);
24763 			/* REFRELE the last iterated ire */
24764 			ire_refrele(ire);
24765 			/* save_ire has been REFHOLDed */
24766 			ire = save_ire;
24767 			q = ire->ire_stq;
24768 			save_ire = NULL;
24769 		}
24770 
24771 		if (last_frag) {
24772 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24773 			    "ip_wput_frag_end:(%S)",
24774 			    "consumed hdr_mp");
24775 
24776 			if (first_ire != NULL)
24777 				ire_refrele(first_ire);
24778 			return;
24779 		}
24780 		/* Otherwise, advance and loop. */
24781 		offset += len;
24782 	}
24783 
24784 drop_pkt:
24785 	/* Clean up following allocation failure. */
24786 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24787 	freemsg(mp);
24788 	if (mp != hdr_mp)
24789 		freeb(hdr_mp);
24790 	if (mp != mp_orig)
24791 		freemsg(mp_orig);
24792 
24793 	if (save_ire != NULL)
24794 		IRE_REFRELE(save_ire);
24795 	if (first_ire != NULL)
24796 		ire_refrele(first_ire);
24797 
24798 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24799 	    "ip_wput_frag_end:(%S)",
24800 	    "end--alloc failure");
24801 }
24802 
24803 /*
24804  * Copy the header plus those options which have the copy bit set
24805  */
24806 static mblk_t *
24807 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24808 {
24809 	mblk_t	*mp;
24810 	uchar_t	*up;
24811 
24812 	/*
24813 	 * Quick check if we need to look for options without the copy bit
24814 	 * set
24815 	 */
24816 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24817 	if (!mp)
24818 		return (mp);
24819 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24820 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24821 		bcopy(rptr, mp->b_rptr, hdr_len);
24822 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24823 		return (mp);
24824 	}
24825 	up  = mp->b_rptr;
24826 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24827 	up += IP_SIMPLE_HDR_LENGTH;
24828 	rptr += IP_SIMPLE_HDR_LENGTH;
24829 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24830 	while (hdr_len > 0) {
24831 		uint32_t optval;
24832 		uint32_t optlen;
24833 
24834 		optval = *rptr;
24835 		if (optval == IPOPT_EOL)
24836 			break;
24837 		if (optval == IPOPT_NOP)
24838 			optlen = 1;
24839 		else
24840 			optlen = rptr[1];
24841 		if (optval & IPOPT_COPY) {
24842 			bcopy(rptr, up, optlen);
24843 			up += optlen;
24844 		}
24845 		rptr += optlen;
24846 		hdr_len -= optlen;
24847 	}
24848 	/*
24849 	 * Make sure that we drop an even number of words by filling
24850 	 * with EOL to the next word boundary.
24851 	 */
24852 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24853 	    hdr_len & 0x3; hdr_len++)
24854 		*up++ = IPOPT_EOL;
24855 	mp->b_wptr = up;
24856 	/* Update header length */
24857 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24858 	return (mp);
24859 }
24860 
24861 /*
24862  * Delivery to local recipients including fanout to multiple recipients.
24863  * Does not do checksumming of UDP/TCP.
24864  * Note: q should be the read side queue for either the ill or conn.
24865  * Note: rq should be the read side q for the lower (ill) stream.
24866  * We don't send packets to IPPF processing, thus the last argument
24867  * to all the fanout calls are B_FALSE.
24868  */
24869 void
24870 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24871     int fanout_flags, zoneid_t zoneid)
24872 {
24873 	uint32_t	protocol;
24874 	mblk_t		*first_mp;
24875 	boolean_t	mctl_present;
24876 	int		ire_type;
24877 #define	rptr	((uchar_t *)ipha)
24878 	ip_stack_t	*ipst = ill->ill_ipst;
24879 
24880 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24881 	    "ip_wput_local_start: q %p", q);
24882 
24883 	if (ire != NULL) {
24884 		ire_type = ire->ire_type;
24885 	} else {
24886 		/*
24887 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24888 		 * packet is not multicast, we can't tell the ire type.
24889 		 */
24890 		ASSERT(CLASSD(ipha->ipha_dst));
24891 		ire_type = IRE_BROADCAST;
24892 	}
24893 
24894 	first_mp = mp;
24895 	if (first_mp->b_datap->db_type == M_CTL) {
24896 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24897 		if (!io->ipsec_out_secure) {
24898 			/*
24899 			 * This ipsec_out_t was allocated in ip_wput
24900 			 * for multicast packets to store the ill_index.
24901 			 * As this is being delivered locally, we don't
24902 			 * need this anymore.
24903 			 */
24904 			mp = first_mp->b_cont;
24905 			freeb(first_mp);
24906 			first_mp = mp;
24907 			mctl_present = B_FALSE;
24908 		} else {
24909 			/*
24910 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24911 			 * security properties for the looped-back packet.
24912 			 */
24913 			mctl_present = B_TRUE;
24914 			mp = first_mp->b_cont;
24915 			ASSERT(mp != NULL);
24916 			ipsec_out_to_in(first_mp);
24917 		}
24918 	} else {
24919 		mctl_present = B_FALSE;
24920 	}
24921 
24922 	DTRACE_PROBE4(ip4__loopback__in__start,
24923 	    ill_t *, ill, ill_t *, NULL,
24924 	    ipha_t *, ipha, mblk_t *, first_mp);
24925 
24926 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24927 	    ipst->ips_ipv4firewall_loopback_in,
24928 	    ill, NULL, ipha, first_mp, mp, ipst);
24929 
24930 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24931 
24932 	if (first_mp == NULL)
24933 		return;
24934 
24935 	ipst->ips_loopback_packets++;
24936 
24937 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24938 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24939 	if (!IS_SIMPLE_IPH(ipha)) {
24940 		ip_wput_local_options(ipha, ipst);
24941 	}
24942 
24943 	protocol = ipha->ipha_protocol;
24944 	switch (protocol) {
24945 	case IPPROTO_ICMP: {
24946 		ire_t		*ire_zone;
24947 		ilm_t		*ilm;
24948 		mblk_t		*mp1;
24949 		zoneid_t	last_zoneid;
24950 
24951 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24952 			ASSERT(ire_type == IRE_BROADCAST);
24953 			/*
24954 			 * In the multicast case, applications may have joined
24955 			 * the group from different zones, so we need to deliver
24956 			 * the packet to each of them. Loop through the
24957 			 * multicast memberships structures (ilm) on the receive
24958 			 * ill and send a copy of the packet up each matching
24959 			 * one. However, we don't do this for multicasts sent on
24960 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24961 			 * they must stay in the sender's zone.
24962 			 *
24963 			 * ilm_add_v6() ensures that ilms in the same zone are
24964 			 * contiguous in the ill_ilm list. We use this property
24965 			 * to avoid sending duplicates needed when two
24966 			 * applications in the same zone join the same group on
24967 			 * different logical interfaces: we ignore the ilm if
24968 			 * it's zoneid is the same as the last matching one.
24969 			 * In addition, the sending of the packet for
24970 			 * ire_zoneid is delayed until all of the other ilms
24971 			 * have been exhausted.
24972 			 */
24973 			last_zoneid = -1;
24974 			ILM_WALKER_HOLD(ill);
24975 			for (ilm = ill->ill_ilm; ilm != NULL;
24976 			    ilm = ilm->ilm_next) {
24977 				if ((ilm->ilm_flags & ILM_DELETED) ||
24978 				    ipha->ipha_dst != ilm->ilm_addr ||
24979 				    ilm->ilm_zoneid == last_zoneid ||
24980 				    ilm->ilm_zoneid == zoneid ||
24981 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24982 					continue;
24983 				mp1 = ip_copymsg(first_mp);
24984 				if (mp1 == NULL)
24985 					continue;
24986 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24987 				    mctl_present, B_FALSE, ill,
24988 				    ilm->ilm_zoneid);
24989 				last_zoneid = ilm->ilm_zoneid;
24990 			}
24991 			ILM_WALKER_RELE(ill);
24992 			/*
24993 			 * Loopback case: the sending endpoint has
24994 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24995 			 * dispatch the multicast packet to the sending zone.
24996 			 */
24997 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24998 				freemsg(first_mp);
24999 				return;
25000 			}
25001 		} else if (ire_type == IRE_BROADCAST) {
25002 			/*
25003 			 * In the broadcast case, there may be many zones
25004 			 * which need a copy of the packet delivered to them.
25005 			 * There is one IRE_BROADCAST per broadcast address
25006 			 * and per zone; we walk those using a helper function.
25007 			 * In addition, the sending of the packet for zoneid is
25008 			 * delayed until all of the other ires have been
25009 			 * processed.
25010 			 */
25011 			IRB_REFHOLD(ire->ire_bucket);
25012 			ire_zone = NULL;
25013 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25014 			    ire)) != NULL) {
25015 				mp1 = ip_copymsg(first_mp);
25016 				if (mp1 == NULL)
25017 					continue;
25018 
25019 				UPDATE_IB_PKT_COUNT(ire_zone);
25020 				ire_zone->ire_last_used_time = lbolt;
25021 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25022 				    mctl_present, B_FALSE, ill,
25023 				    ire_zone->ire_zoneid);
25024 			}
25025 			IRB_REFRELE(ire->ire_bucket);
25026 		}
25027 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25028 		    0, mctl_present, B_FALSE, ill, zoneid);
25029 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25030 		    "ip_wput_local_end: q %p (%S)",
25031 		    q, "icmp");
25032 		return;
25033 	}
25034 	case IPPROTO_IGMP:
25035 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25036 			/* Bad packet - discarded by igmp_input */
25037 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25038 			    "ip_wput_local_end: q %p (%S)",
25039 			    q, "igmp_input--bad packet");
25040 			if (mctl_present)
25041 				freeb(first_mp);
25042 			return;
25043 		}
25044 		/*
25045 		 * igmp_input() may have returned the pulled up message.
25046 		 * So first_mp and ipha need to be reinitialized.
25047 		 */
25048 		ipha = (ipha_t *)mp->b_rptr;
25049 		if (mctl_present)
25050 			first_mp->b_cont = mp;
25051 		else
25052 			first_mp = mp;
25053 		/* deliver to local raw users */
25054 		break;
25055 	case IPPROTO_ENCAP:
25056 		/*
25057 		 * This case is covered by either ip_fanout_proto, or by
25058 		 * the above security processing for self-tunneled packets.
25059 		 */
25060 		break;
25061 	case IPPROTO_UDP: {
25062 		uint16_t	*up;
25063 		uint32_t	ports;
25064 
25065 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25066 		    UDP_PORTS_OFFSET);
25067 		/* Force a 'valid' checksum. */
25068 		up[3] = 0;
25069 
25070 		ports = *(uint32_t *)up;
25071 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25072 		    (ire_type == IRE_BROADCAST),
25073 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25074 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25075 		    ill, zoneid);
25076 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25077 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25078 		return;
25079 	}
25080 	case IPPROTO_TCP: {
25081 
25082 		/*
25083 		 * For TCP, discard broadcast packets.
25084 		 */
25085 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25086 			freemsg(first_mp);
25087 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25088 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25089 			return;
25090 		}
25091 
25092 		if (mp->b_datap->db_type == M_DATA) {
25093 			/*
25094 			 * M_DATA mblk, so init mblk (chain) for no struio().
25095 			 */
25096 			mblk_t	*mp1 = mp;
25097 
25098 			do {
25099 				mp1->b_datap->db_struioflag = 0;
25100 			} while ((mp1 = mp1->b_cont) != NULL);
25101 		}
25102 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25103 		    <= mp->b_wptr);
25104 		ip_fanout_tcp(q, first_mp, ill, ipha,
25105 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25106 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25107 		    mctl_present, B_FALSE, zoneid);
25108 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25109 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25110 		return;
25111 	}
25112 	case IPPROTO_SCTP:
25113 	{
25114 		uint32_t	ports;
25115 
25116 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25117 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25118 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25119 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25120 		return;
25121 	}
25122 
25123 	default:
25124 		break;
25125 	}
25126 	/*
25127 	 * Find a client for some other protocol.  We give
25128 	 * copies to multiple clients, if more than one is
25129 	 * bound.
25130 	 */
25131 	ip_fanout_proto(q, first_mp, ill, ipha,
25132 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25133 	    mctl_present, B_FALSE, ill, zoneid);
25134 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25135 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25136 #undef	rptr
25137 }
25138 
25139 /*
25140  * Update any source route, record route, or timestamp options.
25141  * Check that we are at end of strict source route.
25142  * The options have been sanity checked by ip_wput_options().
25143  */
25144 static void
25145 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25146 {
25147 	ipoptp_t	opts;
25148 	uchar_t		*opt;
25149 	uint8_t		optval;
25150 	uint8_t		optlen;
25151 	ipaddr_t	dst;
25152 	uint32_t	ts;
25153 	ire_t		*ire;
25154 	timestruc_t	now;
25155 
25156 	ip2dbg(("ip_wput_local_options\n"));
25157 	for (optval = ipoptp_first(&opts, ipha);
25158 	    optval != IPOPT_EOL;
25159 	    optval = ipoptp_next(&opts)) {
25160 		opt = opts.ipoptp_cur;
25161 		optlen = opts.ipoptp_len;
25162 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25163 		switch (optval) {
25164 			uint32_t off;
25165 		case IPOPT_SSRR:
25166 		case IPOPT_LSRR:
25167 			off = opt[IPOPT_OFFSET];
25168 			off--;
25169 			if (optlen < IP_ADDR_LEN ||
25170 			    off > optlen - IP_ADDR_LEN) {
25171 				/* End of source route */
25172 				break;
25173 			}
25174 			/*
25175 			 * This will only happen if two consecutive entries
25176 			 * in the source route contains our address or if
25177 			 * it is a packet with a loose source route which
25178 			 * reaches us before consuming the whole source route
25179 			 */
25180 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25181 			if (optval == IPOPT_SSRR) {
25182 				return;
25183 			}
25184 			/*
25185 			 * Hack: instead of dropping the packet truncate the
25186 			 * source route to what has been used by filling the
25187 			 * rest with IPOPT_NOP.
25188 			 */
25189 			opt[IPOPT_OLEN] = (uint8_t)off;
25190 			while (off < optlen) {
25191 				opt[off++] = IPOPT_NOP;
25192 			}
25193 			break;
25194 		case IPOPT_RR:
25195 			off = opt[IPOPT_OFFSET];
25196 			off--;
25197 			if (optlen < IP_ADDR_LEN ||
25198 			    off > optlen - IP_ADDR_LEN) {
25199 				/* No more room - ignore */
25200 				ip1dbg((
25201 				    "ip_wput_forward_options: end of RR\n"));
25202 				break;
25203 			}
25204 			dst = htonl(INADDR_LOOPBACK);
25205 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25206 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25207 			break;
25208 		case IPOPT_TS:
25209 			/* Insert timestamp if there is romm */
25210 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25211 			case IPOPT_TS_TSONLY:
25212 				off = IPOPT_TS_TIMELEN;
25213 				break;
25214 			case IPOPT_TS_PRESPEC:
25215 			case IPOPT_TS_PRESPEC_RFC791:
25216 				/* Verify that the address matched */
25217 				off = opt[IPOPT_OFFSET] - 1;
25218 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25219 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25220 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25221 				    ipst);
25222 				if (ire == NULL) {
25223 					/* Not for us */
25224 					break;
25225 				}
25226 				ire_refrele(ire);
25227 				/* FALLTHRU */
25228 			case IPOPT_TS_TSANDADDR:
25229 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25230 				break;
25231 			default:
25232 				/*
25233 				 * ip_*put_options should have already
25234 				 * dropped this packet.
25235 				 */
25236 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25237 				    "unknown IT - bug in ip_wput_options?\n");
25238 				return;	/* Keep "lint" happy */
25239 			}
25240 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25241 				/* Increase overflow counter */
25242 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25243 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25244 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25245 				    (off << 4);
25246 				break;
25247 			}
25248 			off = opt[IPOPT_OFFSET] - 1;
25249 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25250 			case IPOPT_TS_PRESPEC:
25251 			case IPOPT_TS_PRESPEC_RFC791:
25252 			case IPOPT_TS_TSANDADDR:
25253 				dst = htonl(INADDR_LOOPBACK);
25254 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25255 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25256 				/* FALLTHRU */
25257 			case IPOPT_TS_TSONLY:
25258 				off = opt[IPOPT_OFFSET] - 1;
25259 				/* Compute # of milliseconds since midnight */
25260 				gethrestime(&now);
25261 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25262 				    now.tv_nsec / (NANOSEC / MILLISEC);
25263 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25264 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25265 				break;
25266 			}
25267 			break;
25268 		}
25269 	}
25270 }
25271 
25272 /*
25273  * Send out a multicast packet on interface ipif.
25274  * The sender does not have an conn.
25275  * Caller verifies that this isn't a PHYI_LOOPBACK.
25276  */
25277 void
25278 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25279 {
25280 	ipha_t	*ipha;
25281 	ire_t	*ire;
25282 	ipaddr_t	dst;
25283 	mblk_t		*first_mp;
25284 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25285 
25286 	/* igmp_sendpkt always allocates a ipsec_out_t */
25287 	ASSERT(mp->b_datap->db_type == M_CTL);
25288 	ASSERT(!ipif->ipif_isv6);
25289 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25290 
25291 	first_mp = mp;
25292 	mp = first_mp->b_cont;
25293 	ASSERT(mp->b_datap->db_type == M_DATA);
25294 	ipha = (ipha_t *)mp->b_rptr;
25295 
25296 	/*
25297 	 * Find an IRE which matches the destination and the outgoing
25298 	 * queue (i.e. the outgoing interface.)
25299 	 */
25300 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25301 		dst = ipif->ipif_pp_dst_addr;
25302 	else
25303 		dst = ipha->ipha_dst;
25304 	/*
25305 	 * The source address has already been initialized by the
25306 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25307 	 * be sufficient rather than MATCH_IRE_IPIF.
25308 	 *
25309 	 * This function is used for sending IGMP packets. We need
25310 	 * to make sure that we send the packet out of the interface
25311 	 * (ipif->ipif_ill) where we joined the group. This is to
25312 	 * prevent from switches doing IGMP snooping to send us multicast
25313 	 * packets for a given group on the interface we have joined.
25314 	 * If we can't find an ire, igmp_sendpkt has already initialized
25315 	 * ipsec_out_attach_if so that this will not be load spread in
25316 	 * ip_newroute_ipif.
25317 	 */
25318 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25319 	    MATCH_IRE_ILL, ipst);
25320 	if (!ire) {
25321 		/*
25322 		 * Mark this packet to make it be delivered to
25323 		 * ip_wput_ire after the new ire has been
25324 		 * created.
25325 		 */
25326 		mp->b_prev = NULL;
25327 		mp->b_next = NULL;
25328 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25329 		    zoneid, &zero_info);
25330 		return;
25331 	}
25332 
25333 	/*
25334 	 * Honor the RTF_SETSRC flag; this is the only case
25335 	 * where we force this addr whatever the current src addr is,
25336 	 * because this address is set by igmp_sendpkt(), and
25337 	 * cannot be specified by any user.
25338 	 */
25339 	if (ire->ire_flags & RTF_SETSRC) {
25340 		ipha->ipha_src = ire->ire_src_addr;
25341 	}
25342 
25343 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25344 }
25345 
25346 /*
25347  * NOTE : This function does not ire_refrele the ire argument passed in.
25348  *
25349  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25350  * failure. The nce_fp_mp can vanish any time in the case of
25351  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25352  * the ire_lock to access the nce_fp_mp in this case.
25353  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25354  * prepending a fastpath message IPQoS processing must precede it, we also set
25355  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25356  * (IPQoS might have set the b_band for CoS marking).
25357  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25358  * must follow it so that IPQoS can mark the dl_priority field for CoS
25359  * marking, if needed.
25360  */
25361 static mblk_t *
25362 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25363 {
25364 	uint_t	hlen;
25365 	ipha_t *ipha;
25366 	mblk_t *mp1;
25367 	boolean_t qos_done = B_FALSE;
25368 	uchar_t	*ll_hdr;
25369 	ip_stack_t	*ipst = ire->ire_ipst;
25370 
25371 #define	rptr	((uchar_t *)ipha)
25372 
25373 	ipha = (ipha_t *)mp->b_rptr;
25374 	hlen = 0;
25375 	LOCK_IRE_FP_MP(ire);
25376 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25377 		ASSERT(DB_TYPE(mp1) == M_DATA);
25378 		/* Initiate IPPF processing */
25379 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25380 			UNLOCK_IRE_FP_MP(ire);
25381 			ip_process(proc, &mp, ill_index);
25382 			if (mp == NULL)
25383 				return (NULL);
25384 
25385 			ipha = (ipha_t *)mp->b_rptr;
25386 			LOCK_IRE_FP_MP(ire);
25387 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25388 				qos_done = B_TRUE;
25389 				goto no_fp_mp;
25390 			}
25391 			ASSERT(DB_TYPE(mp1) == M_DATA);
25392 		}
25393 		hlen = MBLKL(mp1);
25394 		/*
25395 		 * Check if we have enough room to prepend fastpath
25396 		 * header
25397 		 */
25398 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25399 			ll_hdr = rptr - hlen;
25400 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25401 			/*
25402 			 * Set the b_rptr to the start of the link layer
25403 			 * header
25404 			 */
25405 			mp->b_rptr = ll_hdr;
25406 			mp1 = mp;
25407 		} else {
25408 			mp1 = copyb(mp1);
25409 			if (mp1 == NULL)
25410 				goto unlock_err;
25411 			mp1->b_band = mp->b_band;
25412 			mp1->b_cont = mp;
25413 			/*
25414 			 * certain system generated traffic may not
25415 			 * have cred/label in ip header block. This
25416 			 * is true even for a labeled system. But for
25417 			 * labeled traffic, inherit the label in the
25418 			 * new header.
25419 			 */
25420 			if (DB_CRED(mp) != NULL)
25421 				mblk_setcred(mp1, DB_CRED(mp));
25422 			/*
25423 			 * XXX disable ICK_VALID and compute checksum
25424 			 * here; can happen if nce_fp_mp changes and
25425 			 * it can't be copied now due to insufficient
25426 			 * space. (unlikely, fp mp can change, but it
25427 			 * does not increase in length)
25428 			 */
25429 		}
25430 		UNLOCK_IRE_FP_MP(ire);
25431 	} else {
25432 no_fp_mp:
25433 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25434 		if (mp1 == NULL) {
25435 unlock_err:
25436 			UNLOCK_IRE_FP_MP(ire);
25437 			freemsg(mp);
25438 			return (NULL);
25439 		}
25440 		UNLOCK_IRE_FP_MP(ire);
25441 		mp1->b_cont = mp;
25442 		/*
25443 		 * certain system generated traffic may not
25444 		 * have cred/label in ip header block. This
25445 		 * is true even for a labeled system. But for
25446 		 * labeled traffic, inherit the label in the
25447 		 * new header.
25448 		 */
25449 		if (DB_CRED(mp) != NULL)
25450 			mblk_setcred(mp1, DB_CRED(mp));
25451 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25452 			ip_process(proc, &mp1, ill_index);
25453 			if (mp1 == NULL)
25454 				return (NULL);
25455 		}
25456 	}
25457 	return (mp1);
25458 #undef rptr
25459 }
25460 
25461 /*
25462  * Finish the outbound IPsec processing for an IPv6 packet. This function
25463  * is called from ipsec_out_process() if the IPsec packet was processed
25464  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25465  * asynchronously.
25466  */
25467 void
25468 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25469     ire_t *ire_arg)
25470 {
25471 	in6_addr_t *v6dstp;
25472 	ire_t *ire;
25473 	mblk_t *mp;
25474 	ip6_t *ip6h1;
25475 	uint_t	ill_index;
25476 	ipsec_out_t *io;
25477 	boolean_t attach_if, hwaccel;
25478 	uint32_t flags = IP6_NO_IPPOLICY;
25479 	int match_flags;
25480 	zoneid_t zoneid;
25481 	boolean_t ill_need_rele = B_FALSE;
25482 	boolean_t ire_need_rele = B_FALSE;
25483 	ip_stack_t	*ipst;
25484 
25485 	mp = ipsec_mp->b_cont;
25486 	ip6h1 = (ip6_t *)mp->b_rptr;
25487 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25488 	ASSERT(io->ipsec_out_ns != NULL);
25489 	ipst = io->ipsec_out_ns->netstack_ip;
25490 	ill_index = io->ipsec_out_ill_index;
25491 	if (io->ipsec_out_reachable) {
25492 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25493 	}
25494 	attach_if = io->ipsec_out_attach_if;
25495 	hwaccel = io->ipsec_out_accelerated;
25496 	zoneid = io->ipsec_out_zoneid;
25497 	ASSERT(zoneid != ALL_ZONES);
25498 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25499 	/* Multicast addresses should have non-zero ill_index. */
25500 	v6dstp = &ip6h->ip6_dst;
25501 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25502 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25503 	ASSERT(!attach_if || ill_index != 0);
25504 	if (ill_index != 0) {
25505 		if (ill == NULL) {
25506 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25507 			    B_TRUE, ipst);
25508 
25509 			/* Failure case frees things for us. */
25510 			if (ill == NULL)
25511 				return;
25512 
25513 			ill_need_rele = B_TRUE;
25514 		}
25515 		/*
25516 		 * If this packet needs to go out on a particular interface
25517 		 * honor it.
25518 		 */
25519 		if (attach_if) {
25520 			match_flags = MATCH_IRE_ILL;
25521 
25522 			/*
25523 			 * Check if we need an ire that will not be
25524 			 * looked up by anybody else i.e. HIDDEN.
25525 			 */
25526 			if (ill_is_probeonly(ill)) {
25527 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25528 			}
25529 		}
25530 	}
25531 	ASSERT(mp != NULL);
25532 
25533 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25534 		boolean_t unspec_src;
25535 		ipif_t	*ipif;
25536 
25537 		/*
25538 		 * Use the ill_index to get the right ill.
25539 		 */
25540 		unspec_src = io->ipsec_out_unspec_src;
25541 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25542 		if (ipif == NULL) {
25543 			if (ill_need_rele)
25544 				ill_refrele(ill);
25545 			freemsg(ipsec_mp);
25546 			return;
25547 		}
25548 
25549 		if (ire_arg != NULL) {
25550 			ire = ire_arg;
25551 		} else {
25552 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25553 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25554 			ire_need_rele = B_TRUE;
25555 		}
25556 		if (ire != NULL) {
25557 			ipif_refrele(ipif);
25558 			/*
25559 			 * XXX Do the multicast forwarding now, as the IPsec
25560 			 * processing has been done.
25561 			 */
25562 			goto send;
25563 		}
25564 
25565 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25566 		mp->b_prev = NULL;
25567 		mp->b_next = NULL;
25568 
25569 		/*
25570 		 * If the IPsec packet was processed asynchronously,
25571 		 * drop it now.
25572 		 */
25573 		if (q == NULL) {
25574 			if (ill_need_rele)
25575 				ill_refrele(ill);
25576 			freemsg(ipsec_mp);
25577 			return;
25578 		}
25579 
25580 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25581 		    unspec_src, zoneid);
25582 		ipif_refrele(ipif);
25583 	} else {
25584 		if (attach_if) {
25585 			ipif_t	*ipif;
25586 
25587 			ipif = ipif_get_next_ipif(NULL, ill);
25588 			if (ipif == NULL) {
25589 				if (ill_need_rele)
25590 					ill_refrele(ill);
25591 				freemsg(ipsec_mp);
25592 				return;
25593 			}
25594 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25595 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25596 			ire_need_rele = B_TRUE;
25597 			ipif_refrele(ipif);
25598 		} else {
25599 			if (ire_arg != NULL) {
25600 				ire = ire_arg;
25601 			} else {
25602 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25603 				    ipst);
25604 				ire_need_rele = B_TRUE;
25605 			}
25606 		}
25607 		if (ire != NULL)
25608 			goto send;
25609 		/*
25610 		 * ire disappeared underneath.
25611 		 *
25612 		 * What we need to do here is the ip_newroute
25613 		 * logic to get the ire without doing the IPsec
25614 		 * processing. Follow the same old path. But this
25615 		 * time, ip_wput or ire_add_then_send will call us
25616 		 * directly as all the IPsec operations are done.
25617 		 */
25618 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25619 		mp->b_prev = NULL;
25620 		mp->b_next = NULL;
25621 
25622 		/*
25623 		 * If the IPsec packet was processed asynchronously,
25624 		 * drop it now.
25625 		 */
25626 		if (q == NULL) {
25627 			if (ill_need_rele)
25628 				ill_refrele(ill);
25629 			freemsg(ipsec_mp);
25630 			return;
25631 		}
25632 
25633 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25634 		    zoneid, ipst);
25635 	}
25636 	if (ill != NULL && ill_need_rele)
25637 		ill_refrele(ill);
25638 	return;
25639 send:
25640 	if (ill != NULL && ill_need_rele)
25641 		ill_refrele(ill);
25642 
25643 	/* Local delivery */
25644 	if (ire->ire_stq == NULL) {
25645 		ill_t	*out_ill;
25646 		ASSERT(q != NULL);
25647 
25648 		/* PFHooks: LOOPBACK_OUT */
25649 		out_ill = ire->ire_ipif->ipif_ill;
25650 
25651 		DTRACE_PROBE4(ip6__loopback__out__start,
25652 		    ill_t *, NULL, ill_t *, out_ill,
25653 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25654 
25655 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25656 		    ipst->ips_ipv6firewall_loopback_out,
25657 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25658 
25659 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25660 
25661 		if (ipsec_mp != NULL)
25662 			ip_wput_local_v6(RD(q), out_ill,
25663 			    ip6h, ipsec_mp, ire, 0);
25664 		if (ire_need_rele)
25665 			ire_refrele(ire);
25666 		return;
25667 	}
25668 	/*
25669 	 * Everything is done. Send it out on the wire.
25670 	 * We force the insertion of a fragment header using the
25671 	 * IPH_FRAG_HDR flag in two cases:
25672 	 * - after reception of an ICMPv6 "packet too big" message
25673 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25674 	 * - for multirouted IPv6 packets, so that the receiver can
25675 	 *   discard duplicates according to their fragment identifier
25676 	 */
25677 	/* XXX fix flow control problems. */
25678 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25679 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25680 		if (hwaccel) {
25681 			/*
25682 			 * hardware acceleration does not handle these
25683 			 * "slow path" cases.
25684 			 */
25685 			/* IPsec KSTATS: should bump bean counter here. */
25686 			if (ire_need_rele)
25687 				ire_refrele(ire);
25688 			freemsg(ipsec_mp);
25689 			return;
25690 		}
25691 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25692 		    (mp->b_cont ? msgdsize(mp) :
25693 		    mp->b_wptr - (uchar_t *)ip6h)) {
25694 			/* IPsec KSTATS: should bump bean counter here. */
25695 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25696 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25697 			    msgdsize(mp)));
25698 			if (ire_need_rele)
25699 				ire_refrele(ire);
25700 			freemsg(ipsec_mp);
25701 			return;
25702 		}
25703 		ASSERT(mp->b_prev == NULL);
25704 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25705 		    ntohs(ip6h->ip6_plen) +
25706 		    IPV6_HDR_LEN, ire->ire_max_frag));
25707 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25708 		    ire->ire_max_frag);
25709 	} else {
25710 		UPDATE_OB_PKT_COUNT(ire);
25711 		ire->ire_last_used_time = lbolt;
25712 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25713 	}
25714 	if (ire_need_rele)
25715 		ire_refrele(ire);
25716 	freeb(ipsec_mp);
25717 }
25718 
25719 void
25720 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25721 {
25722 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25723 	da_ipsec_t *hada;	/* data attributes */
25724 	ill_t *ill = (ill_t *)q->q_ptr;
25725 
25726 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25727 
25728 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25729 		/* IPsec KSTATS: Bump lose counter here! */
25730 		freemsg(mp);
25731 		return;
25732 	}
25733 
25734 	/*
25735 	 * It's an IPsec packet that must be
25736 	 * accelerated by the Provider, and the
25737 	 * outbound ill is IPsec acceleration capable.
25738 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25739 	 * to the ill.
25740 	 * IPsec KSTATS: should bump packet counter here.
25741 	 */
25742 
25743 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25744 	if (hada_mp == NULL) {
25745 		/* IPsec KSTATS: should bump packet counter here. */
25746 		freemsg(mp);
25747 		return;
25748 	}
25749 
25750 	hada_mp->b_datap->db_type = M_CTL;
25751 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25752 	hada_mp->b_cont = mp;
25753 
25754 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25755 	bzero(hada, sizeof (da_ipsec_t));
25756 	hada->da_type = IPHADA_M_CTL;
25757 
25758 	putnext(q, hada_mp);
25759 }
25760 
25761 /*
25762  * Finish the outbound IPsec processing. This function is called from
25763  * ipsec_out_process() if the IPsec packet was processed
25764  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25765  * asynchronously.
25766  */
25767 void
25768 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25769     ire_t *ire_arg)
25770 {
25771 	uint32_t v_hlen_tos_len;
25772 	ipaddr_t	dst;
25773 	ipif_t	*ipif = NULL;
25774 	ire_t *ire;
25775 	ire_t *ire1 = NULL;
25776 	mblk_t *next_mp = NULL;
25777 	uint32_t max_frag;
25778 	boolean_t multirt_send = B_FALSE;
25779 	mblk_t *mp;
25780 	ipha_t *ipha1;
25781 	uint_t	ill_index;
25782 	ipsec_out_t *io;
25783 	boolean_t attach_if;
25784 	int match_flags;
25785 	irb_t *irb = NULL;
25786 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25787 	zoneid_t zoneid;
25788 	ipxmit_state_t	pktxmit_state;
25789 	ip_stack_t	*ipst;
25790 
25791 #ifdef	_BIG_ENDIAN
25792 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25793 #else
25794 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25795 #endif
25796 
25797 	mp = ipsec_mp->b_cont;
25798 	ipha1 = (ipha_t *)mp->b_rptr;
25799 	ASSERT(mp != NULL);
25800 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25801 	dst = ipha->ipha_dst;
25802 
25803 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25804 	ill_index = io->ipsec_out_ill_index;
25805 	attach_if = io->ipsec_out_attach_if;
25806 	zoneid = io->ipsec_out_zoneid;
25807 	ASSERT(zoneid != ALL_ZONES);
25808 	ipst = io->ipsec_out_ns->netstack_ip;
25809 	ASSERT(io->ipsec_out_ns != NULL);
25810 
25811 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25812 	if (ill_index != 0) {
25813 		if (ill == NULL) {
25814 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25815 			    ill_index, B_FALSE, ipst);
25816 
25817 			/* Failure case frees things for us. */
25818 			if (ill == NULL)
25819 				return;
25820 
25821 			ill_need_rele = B_TRUE;
25822 		}
25823 		/*
25824 		 * If this packet needs to go out on a particular interface
25825 		 * honor it.
25826 		 */
25827 		if (attach_if) {
25828 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25829 
25830 			/*
25831 			 * Check if we need an ire that will not be
25832 			 * looked up by anybody else i.e. HIDDEN.
25833 			 */
25834 			if (ill_is_probeonly(ill)) {
25835 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25836 			}
25837 		}
25838 	}
25839 
25840 	if (CLASSD(dst)) {
25841 		boolean_t conn_dontroute;
25842 		/*
25843 		 * Use the ill_index to get the right ipif.
25844 		 */
25845 		conn_dontroute = io->ipsec_out_dontroute;
25846 		if (ill_index == 0)
25847 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25848 		else
25849 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25850 		if (ipif == NULL) {
25851 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25852 			    " multicast\n"));
25853 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25854 			freemsg(ipsec_mp);
25855 			goto done;
25856 		}
25857 		/*
25858 		 * ipha_src has already been intialized with the
25859 		 * value of the ipif in ip_wput. All we need now is
25860 		 * an ire to send this downstream.
25861 		 */
25862 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25863 		    MBLK_GETLABEL(mp), match_flags, ipst);
25864 		if (ire != NULL) {
25865 			ill_t *ill1;
25866 			/*
25867 			 * Do the multicast forwarding now, as the IPsec
25868 			 * processing has been done.
25869 			 */
25870 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25871 			    (ill1 = ire_to_ill(ire))) {
25872 				if (ip_mforward(ill1, ipha, mp)) {
25873 					freemsg(ipsec_mp);
25874 					ip1dbg(("ip_wput_ipsec_out: mforward "
25875 					    "failed\n"));
25876 					ire_refrele(ire);
25877 					goto done;
25878 				}
25879 			}
25880 			goto send;
25881 		}
25882 
25883 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25884 		mp->b_prev = NULL;
25885 		mp->b_next = NULL;
25886 
25887 		/*
25888 		 * If the IPsec packet was processed asynchronously,
25889 		 * drop it now.
25890 		 */
25891 		if (q == NULL) {
25892 			freemsg(ipsec_mp);
25893 			goto done;
25894 		}
25895 
25896 		/*
25897 		 * We may be using a wrong ipif to create the ire.
25898 		 * But it is okay as the source address is assigned
25899 		 * for the packet already. Next outbound packet would
25900 		 * create the IRE with the right IPIF in ip_wput.
25901 		 *
25902 		 * Also handle RTF_MULTIRT routes.
25903 		 */
25904 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25905 		    zoneid, &zero_info);
25906 	} else {
25907 		if (attach_if) {
25908 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25909 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25910 		} else {
25911 			if (ire_arg != NULL) {
25912 				ire = ire_arg;
25913 				ire_need_rele = B_FALSE;
25914 			} else {
25915 				ire = ire_cache_lookup(dst, zoneid,
25916 				    MBLK_GETLABEL(mp), ipst);
25917 			}
25918 		}
25919 		if (ire != NULL) {
25920 			goto send;
25921 		}
25922 
25923 		/*
25924 		 * ire disappeared underneath.
25925 		 *
25926 		 * What we need to do here is the ip_newroute
25927 		 * logic to get the ire without doing the IPsec
25928 		 * processing. Follow the same old path. But this
25929 		 * time, ip_wput or ire_add_then_put will call us
25930 		 * directly as all the IPsec operations are done.
25931 		 */
25932 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25933 		mp->b_prev = NULL;
25934 		mp->b_next = NULL;
25935 
25936 		/*
25937 		 * If the IPsec packet was processed asynchronously,
25938 		 * drop it now.
25939 		 */
25940 		if (q == NULL) {
25941 			freemsg(ipsec_mp);
25942 			goto done;
25943 		}
25944 
25945 		/*
25946 		 * Since we're going through ip_newroute() again, we
25947 		 * need to make sure we don't:
25948 		 *
25949 		 *	1.) Trigger the ASSERT() with the ipha_ident
25950 		 *	    overloading.
25951 		 *	2.) Redo transport-layer checksumming, since we've
25952 		 *	    already done all that to get this far.
25953 		 *
25954 		 * The easiest way not do either of the above is to set
25955 		 * the ipha_ident field to IP_HDR_INCLUDED.
25956 		 */
25957 		ipha->ipha_ident = IP_HDR_INCLUDED;
25958 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25959 		    zoneid, ipst);
25960 	}
25961 	goto done;
25962 send:
25963 	if (ire->ire_stq == NULL) {
25964 		ill_t	*out_ill;
25965 		/*
25966 		 * Loopbacks go through ip_wput_local except for one case.
25967 		 * We come here if we generate a icmp_frag_needed message
25968 		 * after IPsec processing is over. When this function calls
25969 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25970 		 * icmp_frag_needed. The message generated comes back here
25971 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25972 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25973 		 * source address as it is usually set in ip_wput_ire. As
25974 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25975 		 * and we end up here. We can't enter ip_wput_ire once the
25976 		 * IPsec processing is over and hence we need to do it here.
25977 		 */
25978 		ASSERT(q != NULL);
25979 		UPDATE_OB_PKT_COUNT(ire);
25980 		ire->ire_last_used_time = lbolt;
25981 		if (ipha->ipha_src == 0)
25982 			ipha->ipha_src = ire->ire_src_addr;
25983 
25984 		/* PFHooks: LOOPBACK_OUT */
25985 		out_ill = ire->ire_ipif->ipif_ill;
25986 
25987 		DTRACE_PROBE4(ip4__loopback__out__start,
25988 		    ill_t *, NULL, ill_t *, out_ill,
25989 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25990 
25991 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25992 		    ipst->ips_ipv4firewall_loopback_out,
25993 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
25994 
25995 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25996 
25997 		if (ipsec_mp != NULL)
25998 			ip_wput_local(RD(q), out_ill,
25999 			    ipha, ipsec_mp, ire, 0, zoneid);
26000 		if (ire_need_rele)
26001 			ire_refrele(ire);
26002 		goto done;
26003 	}
26004 
26005 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26006 		/*
26007 		 * We are through with IPsec processing.
26008 		 * Fragment this and send it on the wire.
26009 		 */
26010 		if (io->ipsec_out_accelerated) {
26011 			/*
26012 			 * The packet has been accelerated but must
26013 			 * be fragmented. This should not happen
26014 			 * since AH and ESP must not accelerate
26015 			 * packets that need fragmentation, however
26016 			 * the configuration could have changed
26017 			 * since the AH or ESP processing.
26018 			 * Drop packet.
26019 			 * IPsec KSTATS: bump bean counter here.
26020 			 */
26021 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26022 			    "fragmented accelerated packet!\n"));
26023 			freemsg(ipsec_mp);
26024 		} else {
26025 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26026 		}
26027 		if (ire_need_rele)
26028 			ire_refrele(ire);
26029 		goto done;
26030 	}
26031 
26032 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26033 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26034 	    (void *)ire->ire_ipif, (void *)ipif));
26035 
26036 	/*
26037 	 * Multiroute the secured packet, unless IPsec really
26038 	 * requires the packet to go out only through a particular
26039 	 * interface.
26040 	 */
26041 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26042 		ire_t *first_ire;
26043 		irb = ire->ire_bucket;
26044 		ASSERT(irb != NULL);
26045 		/*
26046 		 * This ire has been looked up as the one that
26047 		 * goes through the given ipif;
26048 		 * make sure we do not omit any other multiroute ire
26049 		 * that may be present in the bucket before this one.
26050 		 */
26051 		IRB_REFHOLD(irb);
26052 		for (first_ire = irb->irb_ire;
26053 		    first_ire != NULL;
26054 		    first_ire = first_ire->ire_next) {
26055 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26056 			    (first_ire->ire_addr == ire->ire_addr) &&
26057 			    !(first_ire->ire_marks &
26058 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26059 				break;
26060 			}
26061 		}
26062 
26063 		if ((first_ire != NULL) && (first_ire != ire)) {
26064 			/*
26065 			 * Don't change the ire if the packet must
26066 			 * be fragmented if sent via this new one.
26067 			 */
26068 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26069 				IRE_REFHOLD(first_ire);
26070 				if (ire_need_rele)
26071 					ire_refrele(ire);
26072 				else
26073 					ire_need_rele = B_TRUE;
26074 				ire = first_ire;
26075 			}
26076 		}
26077 		IRB_REFRELE(irb);
26078 
26079 		multirt_send = B_TRUE;
26080 		max_frag = ire->ire_max_frag;
26081 	} else {
26082 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26083 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26084 			    "flag, attach_if %d\n", attach_if));
26085 		}
26086 	}
26087 
26088 	/*
26089 	 * In most cases, the emission loop below is entered only once.
26090 	 * Only in the case where the ire holds the RTF_MULTIRT
26091 	 * flag, we loop to process all RTF_MULTIRT ires in the
26092 	 * bucket, and send the packet through all crossed
26093 	 * RTF_MULTIRT routes.
26094 	 */
26095 	do {
26096 		if (multirt_send) {
26097 			/*
26098 			 * ire1 holds here the next ire to process in the
26099 			 * bucket. If multirouting is expected,
26100 			 * any non-RTF_MULTIRT ire that has the
26101 			 * right destination address is ignored.
26102 			 */
26103 			ASSERT(irb != NULL);
26104 			IRB_REFHOLD(irb);
26105 			for (ire1 = ire->ire_next;
26106 			    ire1 != NULL;
26107 			    ire1 = ire1->ire_next) {
26108 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26109 					continue;
26110 				if (ire1->ire_addr != ire->ire_addr)
26111 					continue;
26112 				if (ire1->ire_marks &
26113 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26114 					continue;
26115 				/* No loopback here */
26116 				if (ire1->ire_stq == NULL)
26117 					continue;
26118 				/*
26119 				 * Ensure we do not exceed the MTU
26120 				 * of the next route.
26121 				 */
26122 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26123 					ip_multirt_bad_mtu(ire1, max_frag);
26124 					continue;
26125 				}
26126 
26127 				IRE_REFHOLD(ire1);
26128 				break;
26129 			}
26130 			IRB_REFRELE(irb);
26131 			if (ire1 != NULL) {
26132 				/*
26133 				 * We are in a multiple send case, need to
26134 				 * make a copy of the packet.
26135 				 */
26136 				next_mp = copymsg(ipsec_mp);
26137 				if (next_mp == NULL) {
26138 					ire_refrele(ire1);
26139 					ire1 = NULL;
26140 				}
26141 			}
26142 		}
26143 		/*
26144 		 * Everything is done. Send it out on the wire
26145 		 *
26146 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26147 		 * either send it on the wire or, in the case of
26148 		 * HW acceleration, call ipsec_hw_putnext.
26149 		 */
26150 		if (ire->ire_nce &&
26151 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26152 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26153 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26154 			/*
26155 			 * If ire's link-layer is unresolved (this
26156 			 * would only happen if the incomplete ire
26157 			 * was added to cachetable via forwarding path)
26158 			 * don't bother going to ip_xmit_v4. Just drop the
26159 			 * packet.
26160 			 * There is a slight risk here, in that, if we
26161 			 * have the forwarding path create an incomplete
26162 			 * IRE, then until the IRE is completed, any
26163 			 * transmitted IPsec packets will be dropped
26164 			 * instead of being queued waiting for resolution.
26165 			 *
26166 			 * But the likelihood of a forwarding packet and a wput
26167 			 * packet sending to the same dst at the same time
26168 			 * and there not yet be an ARP entry for it is small.
26169 			 * Furthermore, if this actually happens, it might
26170 			 * be likely that wput would generate multiple
26171 			 * packets (and forwarding would also have a train
26172 			 * of packets) for that destination. If this is
26173 			 * the case, some of them would have been dropped
26174 			 * anyway, since ARP only queues a few packets while
26175 			 * waiting for resolution
26176 			 *
26177 			 * NOTE: We should really call ip_xmit_v4,
26178 			 * and let it queue the packet and send the
26179 			 * ARP query and have ARP come back thus:
26180 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26181 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26182 			 * hw accel work. But it's too complex to get
26183 			 * the IPsec hw  acceleration approach to fit
26184 			 * well with ip_xmit_v4 doing ARP without
26185 			 * doing IPsec simplification. For now, we just
26186 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26187 			 * that we can continue with the send on the next
26188 			 * attempt.
26189 			 *
26190 			 * XXX THis should be revisited, when
26191 			 * the IPsec/IP interaction is cleaned up
26192 			 */
26193 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26194 			    " - dropping packet\n"));
26195 			freemsg(ipsec_mp);
26196 			/*
26197 			 * Call ip_xmit_v4() to trigger ARP query
26198 			 * in case the nce_state is ND_INITIAL
26199 			 */
26200 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26201 			goto drop_pkt;
26202 		}
26203 
26204 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26205 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26206 		    mblk_t *, ipsec_mp);
26207 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26208 		    ipst->ips_ipv4firewall_physical_out,
26209 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26210 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26211 		if (ipsec_mp == NULL)
26212 			goto drop_pkt;
26213 
26214 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26215 		pktxmit_state = ip_xmit_v4(mp, ire,
26216 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26217 
26218 		if ((pktxmit_state ==  SEND_FAILED) ||
26219 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26220 
26221 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26222 drop_pkt:
26223 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26224 			    ipIfStatsOutDiscards);
26225 			if (ire_need_rele)
26226 				ire_refrele(ire);
26227 			if (ire1 != NULL) {
26228 				ire_refrele(ire1);
26229 				freemsg(next_mp);
26230 			}
26231 			goto done;
26232 		}
26233 
26234 		freeb(ipsec_mp);
26235 		if (ire_need_rele)
26236 			ire_refrele(ire);
26237 
26238 		if (ire1 != NULL) {
26239 			ire = ire1;
26240 			ire_need_rele = B_TRUE;
26241 			ASSERT(next_mp);
26242 			ipsec_mp = next_mp;
26243 			mp = ipsec_mp->b_cont;
26244 			ire1 = NULL;
26245 			next_mp = NULL;
26246 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26247 		} else {
26248 			multirt_send = B_FALSE;
26249 		}
26250 	} while (multirt_send);
26251 done:
26252 	if (ill != NULL && ill_need_rele)
26253 		ill_refrele(ill);
26254 	if (ipif != NULL)
26255 		ipif_refrele(ipif);
26256 }
26257 
26258 /*
26259  * Get the ill corresponding to the specified ire, and compare its
26260  * capabilities with the protocol and algorithms specified by the
26261  * the SA obtained from ipsec_out. If they match, annotate the
26262  * ipsec_out structure to indicate that the packet needs acceleration.
26263  *
26264  *
26265  * A packet is eligible for outbound hardware acceleration if the
26266  * following conditions are satisfied:
26267  *
26268  * 1. the packet will not be fragmented
26269  * 2. the provider supports the algorithm
26270  * 3. there is no pending control message being exchanged
26271  * 4. snoop is not attached
26272  * 5. the destination address is not a broadcast or multicast address.
26273  *
26274  * Rationale:
26275  *	- Hardware drivers do not support fragmentation with
26276  *	  the current interface.
26277  *	- snoop, multicast, and broadcast may result in exposure of
26278  *	  a cleartext datagram.
26279  * We check all five of these conditions here.
26280  *
26281  * XXX would like to nuke "ire_t *" parameter here; problem is that
26282  * IRE is only way to figure out if a v4 address is a broadcast and
26283  * thus ineligible for acceleration...
26284  */
26285 static void
26286 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26287 {
26288 	ipsec_out_t *io;
26289 	mblk_t *data_mp;
26290 	uint_t plen, overhead;
26291 	ip_stack_t	*ipst;
26292 
26293 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26294 		return;
26295 
26296 	if (ill == NULL)
26297 		return;
26298 	ipst = ill->ill_ipst;
26299 	/*
26300 	 * Destination address is a broadcast or multicast.  Punt.
26301 	 */
26302 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26303 	    IRE_LOCAL)))
26304 		return;
26305 
26306 	data_mp = ipsec_mp->b_cont;
26307 
26308 	if (ill->ill_isv6) {
26309 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26310 
26311 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26312 			return;
26313 
26314 		plen = ip6h->ip6_plen;
26315 	} else {
26316 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26317 
26318 		if (CLASSD(ipha->ipha_dst))
26319 			return;
26320 
26321 		plen = ipha->ipha_length;
26322 	}
26323 	/*
26324 	 * Is there a pending DLPI control message being exchanged
26325 	 * between IP/IPsec and the DLS Provider? If there is, it
26326 	 * could be a SADB update, and the state of the DLS Provider
26327 	 * SADB might not be in sync with the SADB maintained by
26328 	 * IPsec. To avoid dropping packets or using the wrong keying
26329 	 * material, we do not accelerate this packet.
26330 	 */
26331 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26332 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26333 		    "ill_dlpi_pending! don't accelerate packet\n"));
26334 		return;
26335 	}
26336 
26337 	/*
26338 	 * Is the Provider in promiscous mode? If it does, we don't
26339 	 * accelerate the packet since it will bounce back up to the
26340 	 * listeners in the clear.
26341 	 */
26342 	if (ill->ill_promisc_on_phys) {
26343 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26344 		    "ill in promiscous mode, don't accelerate packet\n"));
26345 		return;
26346 	}
26347 
26348 	/*
26349 	 * Will the packet require fragmentation?
26350 	 */
26351 
26352 	/*
26353 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26354 	 * as is used elsewhere.
26355 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26356 	 *	+ 2-byte trailer
26357 	 */
26358 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26359 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26360 
26361 	if ((plen + overhead) > ill->ill_max_mtu)
26362 		return;
26363 
26364 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26365 
26366 	/*
26367 	 * Can the ill accelerate this IPsec protocol and algorithm
26368 	 * specified by the SA?
26369 	 */
26370 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26371 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26372 		return;
26373 	}
26374 
26375 	/*
26376 	 * Tell AH or ESP that the outbound ill is capable of
26377 	 * accelerating this packet.
26378 	 */
26379 	io->ipsec_out_is_capab_ill = B_TRUE;
26380 }
26381 
26382 /*
26383  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26384  *
26385  * If this function returns B_TRUE, the requested SA's have been filled
26386  * into the ipsec_out_*_sa pointers.
26387  *
26388  * If the function returns B_FALSE, the packet has been "consumed", most
26389  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26390  *
26391  * The SA references created by the protocol-specific "select"
26392  * function will be released when the ipsec_mp is freed, thanks to the
26393  * ipsec_out_free destructor -- see spd.c.
26394  */
26395 static boolean_t
26396 ipsec_out_select_sa(mblk_t *ipsec_mp)
26397 {
26398 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26399 	ipsec_out_t *io;
26400 	ipsec_policy_t *pp;
26401 	ipsec_action_t *ap;
26402 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26403 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26404 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26405 
26406 	if (!io->ipsec_out_secure) {
26407 		/*
26408 		 * We came here by mistake.
26409 		 * Don't bother with ipsec processing
26410 		 * We should "discourage" this path in the future.
26411 		 */
26412 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26413 		return (B_FALSE);
26414 	}
26415 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26416 	ASSERT((io->ipsec_out_policy != NULL) ||
26417 	    (io->ipsec_out_act != NULL));
26418 
26419 	ASSERT(io->ipsec_out_failed == B_FALSE);
26420 
26421 	/*
26422 	 * IPsec processing has started.
26423 	 */
26424 	io->ipsec_out_proc_begin = B_TRUE;
26425 	ap = io->ipsec_out_act;
26426 	if (ap == NULL) {
26427 		pp = io->ipsec_out_policy;
26428 		ASSERT(pp != NULL);
26429 		ap = pp->ipsp_act;
26430 		ASSERT(ap != NULL);
26431 	}
26432 
26433 	/*
26434 	 * We have an action.  now, let's select SA's.
26435 	 * (In the future, we can cache this in the conn_t..)
26436 	 */
26437 	if (ap->ipa_want_esp) {
26438 		if (io->ipsec_out_esp_sa == NULL) {
26439 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26440 			    IPPROTO_ESP);
26441 		}
26442 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26443 	}
26444 
26445 	if (ap->ipa_want_ah) {
26446 		if (io->ipsec_out_ah_sa == NULL) {
26447 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26448 			    IPPROTO_AH);
26449 		}
26450 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26451 		/*
26452 		 * The ESP and AH processing order needs to be preserved
26453 		 * when both protocols are required (ESP should be applied
26454 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26455 		 * when both ESP and AH are required, and an AH ACQUIRE
26456 		 * is needed.
26457 		 */
26458 		if (ap->ipa_want_esp && need_ah_acquire)
26459 			need_esp_acquire = B_TRUE;
26460 	}
26461 
26462 	/*
26463 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26464 	 * Release SAs that got referenced, but will not be used until we
26465 	 * acquire _all_ of the SAs we need.
26466 	 */
26467 	if (need_ah_acquire || need_esp_acquire) {
26468 		if (io->ipsec_out_ah_sa != NULL) {
26469 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26470 			io->ipsec_out_ah_sa = NULL;
26471 		}
26472 		if (io->ipsec_out_esp_sa != NULL) {
26473 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26474 			io->ipsec_out_esp_sa = NULL;
26475 		}
26476 
26477 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26478 		return (B_FALSE);
26479 	}
26480 
26481 	return (B_TRUE);
26482 }
26483 
26484 /*
26485  * Process an IPSEC_OUT message and see what you can
26486  * do with it.
26487  * IPQoS Notes:
26488  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26489  * IPsec.
26490  * XXX would like to nuke ire_t.
26491  * XXX ill_index better be "real"
26492  */
26493 void
26494 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26495 {
26496 	ipsec_out_t *io;
26497 	ipsec_policy_t *pp;
26498 	ipsec_action_t *ap;
26499 	ipha_t *ipha;
26500 	ip6_t *ip6h;
26501 	mblk_t *mp;
26502 	ill_t *ill;
26503 	zoneid_t zoneid;
26504 	ipsec_status_t ipsec_rc;
26505 	boolean_t ill_need_rele = B_FALSE;
26506 	ip_stack_t	*ipst;
26507 	ipsec_stack_t	*ipss;
26508 
26509 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26510 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26511 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26512 	ipst = io->ipsec_out_ns->netstack_ip;
26513 	mp = ipsec_mp->b_cont;
26514 
26515 	/*
26516 	 * Initiate IPPF processing. We do it here to account for packets
26517 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26518 	 * We can check for ipsec_out_proc_begin even for such packets, as
26519 	 * they will always be false (asserted below).
26520 	 */
26521 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26522 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26523 		    io->ipsec_out_ill_index : ill_index);
26524 		if (mp == NULL) {
26525 			ip2dbg(("ipsec_out_process: packet dropped "\
26526 			    "during IPPF processing\n"));
26527 			freeb(ipsec_mp);
26528 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26529 			return;
26530 		}
26531 	}
26532 
26533 	if (!io->ipsec_out_secure) {
26534 		/*
26535 		 * We came here by mistake.
26536 		 * Don't bother with ipsec processing
26537 		 * Should "discourage" this path in the future.
26538 		 */
26539 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26540 		goto done;
26541 	}
26542 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26543 	ASSERT((io->ipsec_out_policy != NULL) ||
26544 	    (io->ipsec_out_act != NULL));
26545 	ASSERT(io->ipsec_out_failed == B_FALSE);
26546 
26547 	ipss = ipst->ips_netstack->netstack_ipsec;
26548 	if (!ipsec_loaded(ipss)) {
26549 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26550 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26551 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26552 		} else {
26553 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26554 		}
26555 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26556 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26557 		    &ipss->ipsec_dropper);
26558 		return;
26559 	}
26560 
26561 	/*
26562 	 * IPsec processing has started.
26563 	 */
26564 	io->ipsec_out_proc_begin = B_TRUE;
26565 	ap = io->ipsec_out_act;
26566 	if (ap == NULL) {
26567 		pp = io->ipsec_out_policy;
26568 		ASSERT(pp != NULL);
26569 		ap = pp->ipsp_act;
26570 		ASSERT(ap != NULL);
26571 	}
26572 
26573 	/*
26574 	 * Save the outbound ill index. When the packet comes back
26575 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26576 	 * before sending it the accelerated packet.
26577 	 */
26578 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26579 		int ifindex;
26580 		ill = ire_to_ill(ire);
26581 		ifindex = ill->ill_phyint->phyint_ifindex;
26582 		io->ipsec_out_capab_ill_index = ifindex;
26583 	}
26584 
26585 	/*
26586 	 * The order of processing is first insert a IP header if needed.
26587 	 * Then insert the ESP header and then the AH header.
26588 	 */
26589 	if ((io->ipsec_out_se_done == B_FALSE) &&
26590 	    (ap->ipa_want_se)) {
26591 		/*
26592 		 * First get the outer IP header before sending
26593 		 * it to ESP.
26594 		 */
26595 		ipha_t *oipha, *iipha;
26596 		mblk_t *outer_mp, *inner_mp;
26597 
26598 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26599 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26600 			    "ipsec_out_process: "
26601 			    "Self-Encapsulation failed: Out of memory\n");
26602 			freemsg(ipsec_mp);
26603 			if (ill != NULL) {
26604 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26605 			} else {
26606 				BUMP_MIB(&ipst->ips_ip_mib,
26607 				    ipIfStatsOutDiscards);
26608 			}
26609 			return;
26610 		}
26611 		inner_mp = ipsec_mp->b_cont;
26612 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26613 		oipha = (ipha_t *)outer_mp->b_rptr;
26614 		iipha = (ipha_t *)inner_mp->b_rptr;
26615 		*oipha = *iipha;
26616 		outer_mp->b_wptr += sizeof (ipha_t);
26617 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26618 		    sizeof (ipha_t));
26619 		oipha->ipha_protocol = IPPROTO_ENCAP;
26620 		oipha->ipha_version_and_hdr_length =
26621 		    IP_SIMPLE_HDR_VERSION;
26622 		oipha->ipha_hdr_checksum = 0;
26623 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26624 		outer_mp->b_cont = inner_mp;
26625 		ipsec_mp->b_cont = outer_mp;
26626 
26627 		io->ipsec_out_se_done = B_TRUE;
26628 		io->ipsec_out_tunnel = B_TRUE;
26629 	}
26630 
26631 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26632 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26633 	    !ipsec_out_select_sa(ipsec_mp))
26634 		return;
26635 
26636 	/*
26637 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26638 	 * to do the heavy lifting.
26639 	 */
26640 	zoneid = io->ipsec_out_zoneid;
26641 	ASSERT(zoneid != ALL_ZONES);
26642 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26643 		ASSERT(io->ipsec_out_esp_sa != NULL);
26644 		io->ipsec_out_esp_done = B_TRUE;
26645 		/*
26646 		 * Note that since hw accel can only apply one transform,
26647 		 * not two, we skip hw accel for ESP if we also have AH
26648 		 * This is an design limitation of the interface
26649 		 * which should be revisited.
26650 		 */
26651 		ASSERT(ire != NULL);
26652 		if (io->ipsec_out_ah_sa == NULL) {
26653 			ill = (ill_t *)ire->ire_stq->q_ptr;
26654 			ipsec_out_is_accelerated(ipsec_mp,
26655 			    io->ipsec_out_esp_sa, ill, ire);
26656 		}
26657 
26658 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26659 		switch (ipsec_rc) {
26660 		case IPSEC_STATUS_SUCCESS:
26661 			break;
26662 		case IPSEC_STATUS_FAILED:
26663 			if (ill != NULL) {
26664 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26665 			} else {
26666 				BUMP_MIB(&ipst->ips_ip_mib,
26667 				    ipIfStatsOutDiscards);
26668 			}
26669 			/* FALLTHRU */
26670 		case IPSEC_STATUS_PENDING:
26671 			return;
26672 		}
26673 	}
26674 
26675 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26676 		ASSERT(io->ipsec_out_ah_sa != NULL);
26677 		io->ipsec_out_ah_done = B_TRUE;
26678 		if (ire == NULL) {
26679 			int idx = io->ipsec_out_capab_ill_index;
26680 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26681 			    NULL, NULL, NULL, NULL, ipst);
26682 			ill_need_rele = B_TRUE;
26683 		} else {
26684 			ill = (ill_t *)ire->ire_stq->q_ptr;
26685 		}
26686 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26687 		    ire);
26688 
26689 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26690 		switch (ipsec_rc) {
26691 		case IPSEC_STATUS_SUCCESS:
26692 			break;
26693 		case IPSEC_STATUS_FAILED:
26694 			if (ill != NULL) {
26695 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26696 			} else {
26697 				BUMP_MIB(&ipst->ips_ip_mib,
26698 				    ipIfStatsOutDiscards);
26699 			}
26700 			/* FALLTHRU */
26701 		case IPSEC_STATUS_PENDING:
26702 			if (ill != NULL && ill_need_rele)
26703 				ill_refrele(ill);
26704 			return;
26705 		}
26706 	}
26707 	/*
26708 	 * We are done with IPsec processing. Send it over
26709 	 * the wire.
26710 	 */
26711 done:
26712 	mp = ipsec_mp->b_cont;
26713 	ipha = (ipha_t *)mp->b_rptr;
26714 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26715 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26716 	} else {
26717 		ip6h = (ip6_t *)ipha;
26718 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26719 	}
26720 	if (ill != NULL && ill_need_rele)
26721 		ill_refrele(ill);
26722 }
26723 
26724 /* ARGSUSED */
26725 void
26726 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26727 {
26728 	opt_restart_t	*or;
26729 	int	err;
26730 	conn_t	*connp;
26731 
26732 	ASSERT(CONN_Q(q));
26733 	connp = Q_TO_CONN(q);
26734 
26735 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26736 	or = (opt_restart_t *)first_mp->b_rptr;
26737 	/*
26738 	 * We don't need to pass any credentials here since this is just
26739 	 * a restart. The credentials are passed in when svr4_optcom_req
26740 	 * is called the first time (from ip_wput_nondata).
26741 	 */
26742 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26743 		err = svr4_optcom_req(q, first_mp, NULL,
26744 		    &ip_opt_obj);
26745 	} else {
26746 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26747 		err = tpi_optcom_req(q, first_mp, NULL,
26748 		    &ip_opt_obj);
26749 	}
26750 	if (err != EINPROGRESS) {
26751 		/* operation is done */
26752 		CONN_OPER_PENDING_DONE(connp);
26753 	}
26754 }
26755 
26756 /*
26757  * ioctls that go through a down/up sequence may need to wait for the down
26758  * to complete. This involves waiting for the ire and ipif refcnts to go down
26759  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26760  */
26761 /* ARGSUSED */
26762 void
26763 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26764 {
26765 	struct iocblk *iocp;
26766 	mblk_t *mp1;
26767 	ip_ioctl_cmd_t *ipip;
26768 	int err;
26769 	sin_t	*sin;
26770 	struct lifreq *lifr;
26771 	struct ifreq *ifr;
26772 
26773 	iocp = (struct iocblk *)mp->b_rptr;
26774 	ASSERT(ipsq != NULL);
26775 	/* Existence of mp1 verified in ip_wput_nondata */
26776 	mp1 = mp->b_cont->b_cont;
26777 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26778 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26779 		/*
26780 		 * Special case where ipsq_current_ipif is not set:
26781 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26782 		 * ill could also have become part of a ipmp group in the
26783 		 * process, we are here as were not able to complete the
26784 		 * operation in ipif_set_values because we could not become
26785 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26786 		 * will not be set so we need to set it.
26787 		 */
26788 		ill_t *ill = q->q_ptr;
26789 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26790 	}
26791 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26792 
26793 	if (ipip->ipi_cmd_type == IF_CMD) {
26794 		/* This a old style SIOC[GS]IF* command */
26795 		ifr = (struct ifreq *)mp1->b_rptr;
26796 		sin = (sin_t *)&ifr->ifr_addr;
26797 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26798 		/* This a new style SIOC[GS]LIF* command */
26799 		lifr = (struct lifreq *)mp1->b_rptr;
26800 		sin = (sin_t *)&lifr->lifr_addr;
26801 	} else {
26802 		sin = NULL;
26803 	}
26804 
26805 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26806 	    ipip, mp1->b_rptr);
26807 
26808 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26809 }
26810 
26811 /*
26812  * ioctl processing
26813  *
26814  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26815  * the ioctl command in the ioctl tables, determines the copyin data size
26816  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26817  *
26818  * ioctl processing then continues when the M_IOCDATA makes its way down to
26819  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26820  * associated 'conn' is refheld till the end of the ioctl and the general
26821  * ioctl processing function ip_process_ioctl() is called to extract the
26822  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26823  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26824  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26825  * is used to extract the ioctl's arguments.
26826  *
26827  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26828  * so goes thru the serialization primitive ipsq_try_enter. Then the
26829  * appropriate function to handle the ioctl is called based on the entry in
26830  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26831  * which also refreleases the 'conn' that was refheld at the start of the
26832  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26833  *
26834  * Many exclusive ioctls go thru an internal down up sequence as part of
26835  * the operation. For example an attempt to change the IP address of an
26836  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26837  * does all the cleanup such as deleting all ires that use this address.
26838  * Then we need to wait till all references to the interface go away.
26839  */
26840 void
26841 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26842 {
26843 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26844 	ip_ioctl_cmd_t *ipip = arg;
26845 	ip_extract_func_t *extract_funcp;
26846 	cmd_info_t ci;
26847 	int err;
26848 	boolean_t entered_ipsq = B_FALSE;
26849 
26850 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26851 
26852 	if (ipip == NULL)
26853 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26854 
26855 	/*
26856 	 * SIOCLIFADDIF needs to go thru a special path since the
26857 	 * ill may not exist yet. This happens in the case of lo0
26858 	 * which is created using this ioctl.
26859 	 */
26860 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26861 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26862 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26863 		return;
26864 	}
26865 
26866 	ci.ci_ipif = NULL;
26867 	if (ipip->ipi_cmd_type == MISC_CMD) {
26868 		/*
26869 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26870 		 */
26871 		if (ipip->ipi_cmd == IF_UNITSEL) {
26872 			/* ioctl comes down the ill */
26873 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26874 			ipif_refhold(ci.ci_ipif);
26875 		}
26876 		err = 0;
26877 		ci.ci_sin = NULL;
26878 		ci.ci_sin6 = NULL;
26879 		ci.ci_lifr = NULL;
26880 	} else {
26881 		switch (ipip->ipi_cmd_type) {
26882 		case IF_CMD:
26883 		case LIF_CMD:
26884 			extract_funcp = ip_extract_lifreq;
26885 			break;
26886 
26887 		case ARP_CMD:
26888 		case XARP_CMD:
26889 			extract_funcp = ip_extract_arpreq;
26890 			break;
26891 
26892 		case TUN_CMD:
26893 			extract_funcp = ip_extract_tunreq;
26894 			break;
26895 
26896 		case MSFILT_CMD:
26897 			extract_funcp = ip_extract_msfilter;
26898 			break;
26899 
26900 		default:
26901 			ASSERT(0);
26902 		}
26903 
26904 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26905 		if (err != 0) {
26906 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26907 			return;
26908 		}
26909 
26910 		/*
26911 		 * All of the extraction functions return a refheld ipif.
26912 		 */
26913 		ASSERT(ci.ci_ipif != NULL);
26914 	}
26915 
26916 	/*
26917 	 * If ipsq is non-null, we are already being called exclusively
26918 	 */
26919 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26920 	if (!(ipip->ipi_flags & IPI_WR)) {
26921 		/*
26922 		 * A return value of EINPROGRESS means the ioctl is
26923 		 * either queued and waiting for some reason or has
26924 		 * already completed.
26925 		 */
26926 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26927 		    ci.ci_lifr);
26928 		if (ci.ci_ipif != NULL)
26929 			ipif_refrele(ci.ci_ipif);
26930 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26931 		return;
26932 	}
26933 
26934 	ASSERT(ci.ci_ipif != NULL);
26935 
26936 	if (ipsq == NULL) {
26937 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26938 		    ip_process_ioctl, NEW_OP, B_TRUE);
26939 		entered_ipsq = B_TRUE;
26940 	}
26941 	/*
26942 	 * Release the ipif so that ipif_down and friends that wait for
26943 	 * references to go away are not misled about the current ipif_refcnt
26944 	 * values. We are writer so we can access the ipif even after releasing
26945 	 * the ipif.
26946 	 */
26947 	ipif_refrele(ci.ci_ipif);
26948 	if (ipsq == NULL)
26949 		return;
26950 
26951 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26952 
26953 	/*
26954 	 * For most set ioctls that come here, this serves as a single point
26955 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26956 	 * be any new references to the ipif. This helps functions that go
26957 	 * through this path and end up trying to wait for the refcnts
26958 	 * associated with the ipif to go down to zero. Some exceptions are
26959 	 * Failover, Failback, and Groupname commands that operate on more than
26960 	 * just the ci.ci_ipif. These commands internally determine the
26961 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26962 	 * flags on that set. Another exception is the Removeif command that
26963 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26964 	 * ipif to operate on.
26965 	 */
26966 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26967 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26968 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26969 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26970 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26971 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26972 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26973 
26974 	/*
26975 	 * A return value of EINPROGRESS means the ioctl is
26976 	 * either queued and waiting for some reason or has
26977 	 * already completed.
26978 	 */
26979 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26980 
26981 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26982 
26983 	if (entered_ipsq)
26984 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26985 }
26986 
26987 /*
26988  * Complete the ioctl. Typically ioctls use the mi package and need to
26989  * do mi_copyout/mi_copy_done.
26990  */
26991 void
26992 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26993 {
26994 	conn_t	*connp = NULL;
26995 
26996 	if (err == EINPROGRESS)
26997 		return;
26998 
26999 	if (CONN_Q(q)) {
27000 		connp = Q_TO_CONN(q);
27001 		ASSERT(connp->conn_ref >= 2);
27002 	}
27003 
27004 	switch (mode) {
27005 	case COPYOUT:
27006 		if (err == 0)
27007 			mi_copyout(q, mp);
27008 		else
27009 			mi_copy_done(q, mp, err);
27010 		break;
27011 
27012 	case NO_COPYOUT:
27013 		mi_copy_done(q, mp, err);
27014 		break;
27015 
27016 	default:
27017 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27018 		break;
27019 	}
27020 
27021 	/*
27022 	 * The refhold placed at the start of the ioctl is released here.
27023 	 */
27024 	if (connp != NULL)
27025 		CONN_OPER_PENDING_DONE(connp);
27026 
27027 	if (ipsq != NULL)
27028 		ipsq_current_finish(ipsq);
27029 }
27030 
27031 /*
27032  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27033  */
27034 /* ARGSUSED */
27035 void
27036 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27037 {
27038 	conn_t *connp = arg;
27039 	tcp_t	*tcp;
27040 
27041 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27042 	tcp = connp->conn_tcp;
27043 
27044 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27045 		freemsg(mp);
27046 	else
27047 		tcp_rput_other(tcp, mp);
27048 	CONN_OPER_PENDING_DONE(connp);
27049 }
27050 
27051 /* Called from ip_wput for all non data messages */
27052 /* ARGSUSED */
27053 void
27054 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27055 {
27056 	mblk_t		*mp1;
27057 	ire_t		*ire, *fake_ire;
27058 	ill_t		*ill;
27059 	struct iocblk	*iocp;
27060 	ip_ioctl_cmd_t	*ipip;
27061 	cred_t		*cr;
27062 	conn_t		*connp;
27063 	int		err;
27064 	nce_t		*nce;
27065 	ipif_t		*ipif;
27066 	ip_stack_t	*ipst;
27067 	char		*proto_str;
27068 
27069 	if (CONN_Q(q)) {
27070 		connp = Q_TO_CONN(q);
27071 		ipst = connp->conn_netstack->netstack_ip;
27072 	} else {
27073 		connp = NULL;
27074 		ipst = ILLQ_TO_IPST(q);
27075 	}
27076 
27077 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27078 
27079 	/* Check if it is a queue to /dev/sctp. */
27080 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27081 	    connp->conn_rq == NULL) {
27082 		sctp_wput(q, mp);
27083 		return;
27084 	}
27085 
27086 	switch (DB_TYPE(mp)) {
27087 	case M_IOCTL:
27088 		/*
27089 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27090 		 * will arrange to copy in associated control structures.
27091 		 */
27092 		ip_sioctl_copyin_setup(q, mp);
27093 		return;
27094 	case M_IOCDATA:
27095 		/*
27096 		 * Ensure that this is associated with one of our trans-
27097 		 * parent ioctls.  If it's not ours, discard it if we're
27098 		 * running as a driver, or pass it on if we're a module.
27099 		 */
27100 		iocp = (struct iocblk *)mp->b_rptr;
27101 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27102 		if (ipip == NULL) {
27103 			if (q->q_next == NULL) {
27104 				goto nak;
27105 			} else {
27106 				putnext(q, mp);
27107 			}
27108 			return;
27109 		}
27110 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27111 			/*
27112 			 * the ioctl is one we recognise, but is not
27113 			 * consumed by IP as a module, pass M_IOCDATA
27114 			 * for processing downstream, but only for
27115 			 * common Streams ioctls.
27116 			 */
27117 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27118 				putnext(q, mp);
27119 				return;
27120 			} else {
27121 				goto nak;
27122 			}
27123 		}
27124 
27125 		/* IOCTL continuation following copyin or copyout. */
27126 		if (mi_copy_state(q, mp, NULL) == -1) {
27127 			/*
27128 			 * The copy operation failed.  mi_copy_state already
27129 			 * cleaned up, so we're out of here.
27130 			 */
27131 			return;
27132 		}
27133 		/*
27134 		 * If we just completed a copy in, we become writer and
27135 		 * continue processing in ip_sioctl_copyin_done.  If it
27136 		 * was a copy out, we call mi_copyout again.  If there is
27137 		 * nothing more to copy out, it will complete the IOCTL.
27138 		 */
27139 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27140 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27141 				mi_copy_done(q, mp, EPROTO);
27142 				return;
27143 			}
27144 			/*
27145 			 * Check for cases that need more copying.  A return
27146 			 * value of 0 means a second copyin has been started,
27147 			 * so we return; a return value of 1 means no more
27148 			 * copying is needed, so we continue.
27149 			 */
27150 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27151 			    MI_COPY_COUNT(mp) == 1) {
27152 				if (ip_copyin_msfilter(q, mp) == 0)
27153 					return;
27154 			}
27155 			/*
27156 			 * Refhold the conn, till the ioctl completes. This is
27157 			 * needed in case the ioctl ends up in the pending mp
27158 			 * list. Every mp in the ill_pending_mp list and
27159 			 * the ipsq_pending_mp must have a refhold on the conn
27160 			 * to resume processing. The refhold is released when
27161 			 * the ioctl completes. (normally or abnormally)
27162 			 * In all cases ip_ioctl_finish is called to finish
27163 			 * the ioctl.
27164 			 */
27165 			if (connp != NULL) {
27166 				/* This is not a reentry */
27167 				ASSERT(ipsq == NULL);
27168 				CONN_INC_REF(connp);
27169 			} else {
27170 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27171 					mi_copy_done(q, mp, EINVAL);
27172 					return;
27173 				}
27174 			}
27175 
27176 			ip_process_ioctl(ipsq, q, mp, ipip);
27177 
27178 		} else {
27179 			mi_copyout(q, mp);
27180 		}
27181 		return;
27182 nak:
27183 		iocp->ioc_error = EINVAL;
27184 		mp->b_datap->db_type = M_IOCNAK;
27185 		iocp->ioc_count = 0;
27186 		qreply(q, mp);
27187 		return;
27188 
27189 	case M_IOCNAK:
27190 		/*
27191 		 * The only way we could get here is if a resolver didn't like
27192 		 * an IOCTL we sent it.	 This shouldn't happen.
27193 		 */
27194 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27195 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27196 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27197 		freemsg(mp);
27198 		return;
27199 	case M_IOCACK:
27200 		/* /dev/ip shouldn't see this */
27201 		if (CONN_Q(q))
27202 			goto nak;
27203 
27204 		/* Finish socket ioctls passed through to ARP. */
27205 		ip_sioctl_iocack(q, mp);
27206 		return;
27207 	case M_FLUSH:
27208 		if (*mp->b_rptr & FLUSHW)
27209 			flushq(q, FLUSHALL);
27210 		if (q->q_next) {
27211 			putnext(q, mp);
27212 			return;
27213 		}
27214 		if (*mp->b_rptr & FLUSHR) {
27215 			*mp->b_rptr &= ~FLUSHW;
27216 			qreply(q, mp);
27217 			return;
27218 		}
27219 		freemsg(mp);
27220 		return;
27221 	case IRE_DB_REQ_TYPE:
27222 		if (connp == NULL) {
27223 			proto_str = "IRE_DB_REQ_TYPE";
27224 			goto protonak;
27225 		}
27226 		/* An Upper Level Protocol wants a copy of an IRE. */
27227 		ip_ire_req(q, mp);
27228 		return;
27229 	case M_CTL:
27230 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27231 			break;
27232 
27233 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27234 		    TUN_HELLO) {
27235 			ASSERT(connp != NULL);
27236 			connp->conn_flags |= IPCL_IPTUN;
27237 			freeb(mp);
27238 			return;
27239 		}
27240 
27241 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27242 		    IP_ULP_OUT_LABELED) {
27243 			out_labeled_t *olp;
27244 
27245 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27246 				break;
27247 			olp = (out_labeled_t *)mp->b_rptr;
27248 			connp->conn_ulp_labeled = olp->out_qnext == q;
27249 			freemsg(mp);
27250 			return;
27251 		}
27252 
27253 		/* M_CTL messages are used by ARP to tell us things. */
27254 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27255 			break;
27256 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27257 		case AR_ENTRY_SQUERY:
27258 			ip_wput_ctl(q, mp);
27259 			return;
27260 		case AR_CLIENT_NOTIFY:
27261 			ip_arp_news(q, mp);
27262 			return;
27263 		case AR_DLPIOP_DONE:
27264 			ASSERT(q->q_next != NULL);
27265 			ill = (ill_t *)q->q_ptr;
27266 			/* qwriter_ip releases the refhold */
27267 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27268 			ill_refhold(ill);
27269 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27270 			return;
27271 		case AR_ARP_CLOSING:
27272 			/*
27273 			 * ARP (above us) is closing. If no ARP bringup is
27274 			 * currently pending, ack the message so that ARP
27275 			 * can complete its close. Also mark ill_arp_closing
27276 			 * so that new ARP bringups will fail. If any
27277 			 * ARP bringup is currently in progress, we will
27278 			 * ack this when the current ARP bringup completes.
27279 			 */
27280 			ASSERT(q->q_next != NULL);
27281 			ill = (ill_t *)q->q_ptr;
27282 			mutex_enter(&ill->ill_lock);
27283 			ill->ill_arp_closing = 1;
27284 			if (!ill->ill_arp_bringup_pending) {
27285 				mutex_exit(&ill->ill_lock);
27286 				qreply(q, mp);
27287 			} else {
27288 				mutex_exit(&ill->ill_lock);
27289 				freemsg(mp);
27290 			}
27291 			return;
27292 		case AR_ARP_EXTEND:
27293 			/*
27294 			 * The ARP module above us is capable of duplicate
27295 			 * address detection.  Old ATM drivers will not send
27296 			 * this message.
27297 			 */
27298 			ASSERT(q->q_next != NULL);
27299 			ill = (ill_t *)q->q_ptr;
27300 			ill->ill_arp_extend = B_TRUE;
27301 			freemsg(mp);
27302 			return;
27303 		default:
27304 			break;
27305 		}
27306 		break;
27307 	case M_PROTO:
27308 	case M_PCPROTO:
27309 		/*
27310 		 * The only PROTO messages we expect are ULP binds and
27311 		 * copies of option negotiation acknowledgements.
27312 		 */
27313 		switch (((union T_primitives *)mp->b_rptr)->type) {
27314 		case O_T_BIND_REQ:
27315 		case T_BIND_REQ: {
27316 			/* Request can get queued in bind */
27317 			if (connp == NULL) {
27318 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27319 				goto protonak;
27320 			}
27321 			/*
27322 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27323 			 * instead of going through this path.  We only get
27324 			 * here in the following cases:
27325 			 *
27326 			 * a. Bind retries, where ipsq is non-NULL.
27327 			 * b. T_BIND_REQ is issued from non TCP/UDP
27328 			 *    transport, e.g. icmp for raw socket,
27329 			 *    in which case ipsq will be NULL.
27330 			 */
27331 			ASSERT(ipsq != NULL ||
27332 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27333 
27334 			/* Don't increment refcnt if this is a re-entry */
27335 			if (ipsq == NULL)
27336 				CONN_INC_REF(connp);
27337 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27338 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27339 			if (mp == NULL)
27340 				return;
27341 			if (IPCL_IS_TCP(connp)) {
27342 				/*
27343 				 * In the case of TCP endpoint we
27344 				 * come here only for bind retries
27345 				 */
27346 				ASSERT(ipsq != NULL);
27347 				CONN_INC_REF(connp);
27348 				squeue_fill(connp->conn_sqp, mp,
27349 				    ip_resume_tcp_bind, connp,
27350 				    SQTAG_BIND_RETRY);
27351 				return;
27352 			} else if (IPCL_IS_UDP(connp)) {
27353 				/*
27354 				 * In the case of UDP endpoint we
27355 				 * come here only for bind retries
27356 				 */
27357 				ASSERT(ipsq != NULL);
27358 				udp_resume_bind(connp, mp);
27359 				return;
27360 			}
27361 			qreply(q, mp);
27362 			CONN_OPER_PENDING_DONE(connp);
27363 			return;
27364 		}
27365 		case T_SVR4_OPTMGMT_REQ:
27366 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27367 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27368 
27369 			if (connp == NULL) {
27370 				proto_str = "T_SVR4_OPTMGMT_REQ";
27371 				goto protonak;
27372 			}
27373 
27374 			if (!snmpcom_req(q, mp, ip_snmp_set,
27375 			    ip_snmp_get, cr)) {
27376 				/*
27377 				 * Call svr4_optcom_req so that it can
27378 				 * generate the ack. We don't come here
27379 				 * if this operation is being restarted.
27380 				 * ip_restart_optmgmt will drop the conn ref.
27381 				 * In the case of ipsec option after the ipsec
27382 				 * load is complete conn_restart_ipsec_waiter
27383 				 * drops the conn ref.
27384 				 */
27385 				ASSERT(ipsq == NULL);
27386 				CONN_INC_REF(connp);
27387 				if (ip_check_for_ipsec_opt(q, mp))
27388 					return;
27389 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27390 				if (err != EINPROGRESS) {
27391 					/* Operation is done */
27392 					CONN_OPER_PENDING_DONE(connp);
27393 				}
27394 			}
27395 			return;
27396 		case T_OPTMGMT_REQ:
27397 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27398 			/*
27399 			 * Note: No snmpcom_req support through new
27400 			 * T_OPTMGMT_REQ.
27401 			 * Call tpi_optcom_req so that it can
27402 			 * generate the ack.
27403 			 */
27404 			if (connp == NULL) {
27405 				proto_str = "T_OPTMGMT_REQ";
27406 				goto protonak;
27407 			}
27408 
27409 			ASSERT(ipsq == NULL);
27410 			/*
27411 			 * We don't come here for restart. ip_restart_optmgmt
27412 			 * will drop the conn ref. In the case of ipsec option
27413 			 * after the ipsec load is complete
27414 			 * conn_restart_ipsec_waiter drops the conn ref.
27415 			 */
27416 			CONN_INC_REF(connp);
27417 			if (ip_check_for_ipsec_opt(q, mp))
27418 				return;
27419 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27420 			if (err != EINPROGRESS) {
27421 				/* Operation is done */
27422 				CONN_OPER_PENDING_DONE(connp);
27423 			}
27424 			return;
27425 		case T_UNBIND_REQ:
27426 			if (connp == NULL) {
27427 				proto_str = "T_UNBIND_REQ";
27428 				goto protonak;
27429 			}
27430 			mp = ip_unbind(q, mp);
27431 			qreply(q, mp);
27432 			return;
27433 		default:
27434 			/*
27435 			 * Have to drop any DLPI messages coming down from
27436 			 * arp (such as an info_req which would cause ip
27437 			 * to receive an extra info_ack if it was passed
27438 			 * through.
27439 			 */
27440 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27441 			    (int)*(uint_t *)mp->b_rptr));
27442 			freemsg(mp);
27443 			return;
27444 		}
27445 		/* NOTREACHED */
27446 	case IRE_DB_TYPE: {
27447 		nce_t		*nce;
27448 		ill_t		*ill;
27449 		in6_addr_t	gw_addr_v6;
27450 
27451 
27452 		/*
27453 		 * This is a response back from a resolver.  It
27454 		 * consists of a message chain containing:
27455 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27456 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27457 		 * The LL_HDR_MBLK is the DLPI header to use to get
27458 		 * the attached packet, and subsequent ones for the
27459 		 * same destination, transmitted.
27460 		 */
27461 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27462 			break;
27463 		/*
27464 		 * First, check to make sure the resolution succeeded.
27465 		 * If it failed, the second mblk will be empty.
27466 		 * If it is, free the chain, dropping the packet.
27467 		 * (We must ire_delete the ire; that frees the ire mblk)
27468 		 * We're doing this now to support PVCs for ATM; it's
27469 		 * a partial xresolv implementation. When we fully implement
27470 		 * xresolv interfaces, instead of freeing everything here
27471 		 * we'll initiate neighbor discovery.
27472 		 *
27473 		 * For v4 (ARP and other external resolvers) the resolver
27474 		 * frees the message, so no check is needed. This check
27475 		 * is required, though, for a full xresolve implementation.
27476 		 * Including this code here now both shows how external
27477 		 * resolvers can NACK a resolution request using an
27478 		 * existing design that has no specific provisions for NACKs,
27479 		 * and also takes into account that the current non-ARP
27480 		 * external resolver has been coded to use this method of
27481 		 * NACKing for all IPv6 (xresolv) cases,
27482 		 * whether our xresolv implementation is complete or not.
27483 		 *
27484 		 */
27485 		ire = (ire_t *)mp->b_rptr;
27486 		ill = ire_to_ill(ire);
27487 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27488 		if (mp1->b_rptr == mp1->b_wptr) {
27489 			if (ire->ire_ipversion == IPV6_VERSION) {
27490 				/*
27491 				 * XRESOLV interface.
27492 				 */
27493 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27494 				mutex_enter(&ire->ire_lock);
27495 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27496 				mutex_exit(&ire->ire_lock);
27497 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27498 					nce = ndp_lookup_v6(ill,
27499 					    &ire->ire_addr_v6, B_FALSE);
27500 				} else {
27501 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27502 					    B_FALSE);
27503 				}
27504 				if (nce != NULL) {
27505 					nce_resolv_failed(nce);
27506 					ndp_delete(nce);
27507 					NCE_REFRELE(nce);
27508 				}
27509 			}
27510 			mp->b_cont = NULL;
27511 			freemsg(mp1);		/* frees the pkt as well */
27512 			ASSERT(ire->ire_nce == NULL);
27513 			ire_delete((ire_t *)mp->b_rptr);
27514 			return;
27515 		}
27516 
27517 		/*
27518 		 * Split them into IRE_MBLK and pkt and feed it into
27519 		 * ire_add_then_send. Then in ire_add_then_send
27520 		 * the IRE will be added, and then the packet will be
27521 		 * run back through ip_wput. This time it will make
27522 		 * it to the wire.
27523 		 */
27524 		mp->b_cont = NULL;
27525 		mp = mp1->b_cont;		/* now, mp points to pkt */
27526 		mp1->b_cont = NULL;
27527 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27528 		if (ire->ire_ipversion == IPV6_VERSION) {
27529 			/*
27530 			 * XRESOLV interface. Find the nce and put a copy
27531 			 * of the dl_unitdata_req in nce_res_mp
27532 			 */
27533 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27534 			mutex_enter(&ire->ire_lock);
27535 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27536 			mutex_exit(&ire->ire_lock);
27537 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27538 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27539 				    B_FALSE);
27540 			} else {
27541 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27542 			}
27543 			if (nce != NULL) {
27544 				/*
27545 				 * We have to protect nce_res_mp here
27546 				 * from being accessed by other threads
27547 				 * while we change the mblk pointer.
27548 				 * Other functions will also lock the nce when
27549 				 * accessing nce_res_mp.
27550 				 *
27551 				 * The reason we change the mblk pointer
27552 				 * here rather than copying the resolved address
27553 				 * into the template is that, unlike with
27554 				 * ethernet, we have no guarantee that the
27555 				 * resolved address length will be
27556 				 * smaller than or equal to the lla length
27557 				 * with which the template was allocated,
27558 				 * (for ethernet, they're equal)
27559 				 * so we have to use the actual resolved
27560 				 * address mblk - which holds the real
27561 				 * dl_unitdata_req with the resolved address.
27562 				 *
27563 				 * Doing this is the same behavior as was
27564 				 * previously used in the v4 ARP case.
27565 				 */
27566 				mutex_enter(&nce->nce_lock);
27567 				if (nce->nce_res_mp != NULL)
27568 					freemsg(nce->nce_res_mp);
27569 				nce->nce_res_mp = mp1;
27570 				mutex_exit(&nce->nce_lock);
27571 				/*
27572 				 * We do a fastpath probe here because
27573 				 * we have resolved the address without
27574 				 * using Neighbor Discovery.
27575 				 * In the non-XRESOLV v6 case, the fastpath
27576 				 * probe is done right after neighbor
27577 				 * discovery completes.
27578 				 */
27579 				if (nce->nce_res_mp != NULL) {
27580 					int res;
27581 					nce_fastpath_list_add(nce);
27582 					res = ill_fastpath_probe(ill,
27583 					    nce->nce_res_mp);
27584 					if (res != 0 && res != EAGAIN)
27585 						nce_fastpath_list_delete(nce);
27586 				}
27587 
27588 				ire_add_then_send(q, ire, mp);
27589 				/*
27590 				 * Now we have to clean out any packets
27591 				 * that may have been queued on the nce
27592 				 * while it was waiting for address resolution
27593 				 * to complete.
27594 				 */
27595 				mutex_enter(&nce->nce_lock);
27596 				mp1 = nce->nce_qd_mp;
27597 				nce->nce_qd_mp = NULL;
27598 				mutex_exit(&nce->nce_lock);
27599 				while (mp1 != NULL) {
27600 					mblk_t *nxt_mp;
27601 					queue_t *fwdq = NULL;
27602 					ill_t   *inbound_ill;
27603 					uint_t ifindex;
27604 
27605 					nxt_mp = mp1->b_next;
27606 					mp1->b_next = NULL;
27607 					/*
27608 					 * Retrieve ifindex stored in
27609 					 * ip_rput_data_v6()
27610 					 */
27611 					ifindex =
27612 					    (uint_t)(uintptr_t)mp1->b_prev;
27613 					inbound_ill =
27614 					    ill_lookup_on_ifindex(ifindex,
27615 					    B_TRUE, NULL, NULL, NULL,
27616 					    NULL, ipst);
27617 					mp1->b_prev = NULL;
27618 					if (inbound_ill != NULL)
27619 						fwdq = inbound_ill->ill_rq;
27620 
27621 					if (fwdq != NULL) {
27622 						put(fwdq, mp1);
27623 						ill_refrele(inbound_ill);
27624 					} else
27625 						put(WR(ill->ill_rq), mp1);
27626 					mp1 = nxt_mp;
27627 				}
27628 				NCE_REFRELE(nce);
27629 			} else {	/* nce is NULL; clean up */
27630 				ire_delete(ire);
27631 				freemsg(mp);
27632 				freemsg(mp1);
27633 				return;
27634 			}
27635 		} else {
27636 			nce_t *arpce;
27637 			/*
27638 			 * Link layer resolution succeeded. Recompute the
27639 			 * ire_nce.
27640 			 */
27641 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27642 			if ((arpce = ndp_lookup_v4(ill,
27643 			    (ire->ire_gateway_addr != INADDR_ANY ?
27644 			    &ire->ire_gateway_addr : &ire->ire_addr),
27645 			    B_FALSE)) == NULL) {
27646 				freeb(ire->ire_mp);
27647 				freeb(mp1);
27648 				freemsg(mp);
27649 				return;
27650 			}
27651 			mutex_enter(&arpce->nce_lock);
27652 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27653 			if (arpce->nce_state == ND_REACHABLE) {
27654 				/*
27655 				 * Someone resolved this before us;
27656 				 * cleanup the res_mp. Since ire has
27657 				 * not been added yet, the call to ire_add_v4
27658 				 * from ire_add_then_send (when a dup is
27659 				 * detected) will clean up the ire.
27660 				 */
27661 				freeb(mp1);
27662 			} else {
27663 				ASSERT(arpce->nce_res_mp == NULL);
27664 				arpce->nce_res_mp = mp1;
27665 				arpce->nce_state = ND_REACHABLE;
27666 			}
27667 			mutex_exit(&arpce->nce_lock);
27668 			if (ire->ire_marks & IRE_MARK_NOADD) {
27669 				/*
27670 				 * this ire will not be added to the ire
27671 				 * cache table, so we can set the ire_nce
27672 				 * here, as there are no atomicity constraints.
27673 				 */
27674 				ire->ire_nce = arpce;
27675 				/*
27676 				 * We are associating this nce with the ire
27677 				 * so change the nce ref taken in
27678 				 * ndp_lookup_v4() from
27679 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27680 				 */
27681 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27682 			} else {
27683 				NCE_REFRELE(arpce);
27684 			}
27685 			ire_add_then_send(q, ire, mp);
27686 		}
27687 		return;	/* All is well, the packet has been sent. */
27688 	}
27689 	case IRE_ARPRESOLVE_TYPE: {
27690 
27691 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27692 			break;
27693 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27694 		mp->b_cont = NULL;
27695 		/*
27696 		 * First, check to make sure the resolution succeeded.
27697 		 * If it failed, the second mblk will be empty.
27698 		 */
27699 		if (mp1->b_rptr == mp1->b_wptr) {
27700 			/* cleanup  the incomplete ire, free queued packets */
27701 			freemsg(mp); /* fake ire */
27702 			freeb(mp1);  /* dl_unitdata response */
27703 			return;
27704 		}
27705 
27706 		/*
27707 		 * update any incomplete nce_t found. we lookup the ctable
27708 		 * and find the nce from the ire->ire_nce because we need
27709 		 * to pass the ire to ip_xmit_v4 later, and can find both
27710 		 * ire and nce in one lookup from the ctable.
27711 		 */
27712 		fake_ire = (ire_t *)mp->b_rptr;
27713 		/*
27714 		 * By the time we come back here from ARP
27715 		 * the logical outgoing interface  of the incomplete ire
27716 		 * we added in ire_forward could have disappeared,
27717 		 * causing the incomplete ire to also have
27718 		 * dissapeared. So we need to retreive the
27719 		 * proper ipif for the ire  before looking
27720 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27721 		 */
27722 		ill = q->q_ptr;
27723 
27724 		/* Get the outgoing ipif */
27725 		mutex_enter(&ill->ill_lock);
27726 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27727 			mutex_exit(&ill->ill_lock);
27728 			freemsg(mp); /* fake ire */
27729 			freeb(mp1);  /* dl_unitdata response */
27730 			return;
27731 		}
27732 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27733 
27734 		if (ipif == NULL) {
27735 			mutex_exit(&ill->ill_lock);
27736 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27737 			freemsg(mp);
27738 			freeb(mp1);
27739 			return;
27740 		}
27741 		ipif_refhold_locked(ipif);
27742 		mutex_exit(&ill->ill_lock);
27743 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27744 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27745 		    ipif, fake_ire->ire_zoneid, NULL,
27746 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27747 		ipif_refrele(ipif);
27748 		if (ire == NULL) {
27749 			/*
27750 			 * no ire was found; check if there is an nce
27751 			 * for this lookup; if it has no ire's pointing at it
27752 			 * cleanup.
27753 			 */
27754 			if ((nce = ndp_lookup_v4(ill,
27755 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27756 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27757 			    B_FALSE)) != NULL) {
27758 				/*
27759 				 * cleanup:
27760 				 * We check for refcnt 2 (one for the nce
27761 				 * hash list + 1 for the ref taken by
27762 				 * ndp_lookup_v4) to check that there are
27763 				 * no ire's pointing at the nce.
27764 				 */
27765 				if (nce->nce_refcnt == 2)
27766 					ndp_delete(nce);
27767 				NCE_REFRELE(nce);
27768 			}
27769 			freeb(mp1);  /* dl_unitdata response */
27770 			freemsg(mp); /* fake ire */
27771 			return;
27772 		}
27773 		nce = ire->ire_nce;
27774 		DTRACE_PROBE2(ire__arpresolve__type,
27775 		    ire_t *, ire, nce_t *, nce);
27776 		ASSERT(nce->nce_state != ND_INITIAL);
27777 		mutex_enter(&nce->nce_lock);
27778 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27779 		if (nce->nce_state == ND_REACHABLE) {
27780 			/*
27781 			 * Someone resolved this before us;
27782 			 * our response is not needed any more.
27783 			 */
27784 			mutex_exit(&nce->nce_lock);
27785 			freeb(mp1);  /* dl_unitdata response */
27786 		} else {
27787 			ASSERT(nce->nce_res_mp == NULL);
27788 			nce->nce_res_mp = mp1;
27789 			nce->nce_state = ND_REACHABLE;
27790 			mutex_exit(&nce->nce_lock);
27791 			nce_fastpath(nce);
27792 		}
27793 		/*
27794 		 * The cached nce_t has been updated to be reachable;
27795 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27796 		 */
27797 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27798 		freemsg(mp);
27799 		/*
27800 		 * send out queued packets.
27801 		 */
27802 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27803 
27804 		IRE_REFRELE(ire);
27805 		return;
27806 	}
27807 	default:
27808 		break;
27809 	}
27810 	if (q->q_next) {
27811 		putnext(q, mp);
27812 	} else
27813 		freemsg(mp);
27814 	return;
27815 
27816 protonak:
27817 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27818 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27819 		qreply(q, mp);
27820 }
27821 
27822 /*
27823  * Process IP options in an outbound packet.  Modify the destination if there
27824  * is a source route option.
27825  * Returns non-zero if something fails in which case an ICMP error has been
27826  * sent and mp freed.
27827  */
27828 static int
27829 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27830     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27831 {
27832 	ipoptp_t	opts;
27833 	uchar_t		*opt;
27834 	uint8_t		optval;
27835 	uint8_t		optlen;
27836 	ipaddr_t	dst;
27837 	intptr_t	code = 0;
27838 	mblk_t		*mp;
27839 	ire_t		*ire = NULL;
27840 
27841 	ip2dbg(("ip_wput_options\n"));
27842 	mp = ipsec_mp;
27843 	if (mctl_present) {
27844 		mp = ipsec_mp->b_cont;
27845 	}
27846 
27847 	dst = ipha->ipha_dst;
27848 	for (optval = ipoptp_first(&opts, ipha);
27849 	    optval != IPOPT_EOL;
27850 	    optval = ipoptp_next(&opts)) {
27851 		opt = opts.ipoptp_cur;
27852 		optlen = opts.ipoptp_len;
27853 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27854 		    optval, optlen));
27855 		switch (optval) {
27856 			uint32_t off;
27857 		case IPOPT_SSRR:
27858 		case IPOPT_LSRR:
27859 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27860 				ip1dbg((
27861 				    "ip_wput_options: bad option offset\n"));
27862 				code = (char *)&opt[IPOPT_OLEN] -
27863 				    (char *)ipha;
27864 				goto param_prob;
27865 			}
27866 			off = opt[IPOPT_OFFSET];
27867 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27868 			    ntohl(dst)));
27869 			/*
27870 			 * For strict: verify that dst is directly
27871 			 * reachable.
27872 			 */
27873 			if (optval == IPOPT_SSRR) {
27874 				ire = ire_ftable_lookup(dst, 0, 0,
27875 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27876 				    MBLK_GETLABEL(mp),
27877 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27878 				if (ire == NULL) {
27879 					ip1dbg(("ip_wput_options: SSRR not"
27880 					    " directly reachable: 0x%x\n",
27881 					    ntohl(dst)));
27882 					goto bad_src_route;
27883 				}
27884 				ire_refrele(ire);
27885 			}
27886 			break;
27887 		case IPOPT_RR:
27888 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27889 				ip1dbg((
27890 				    "ip_wput_options: bad option offset\n"));
27891 				code = (char *)&opt[IPOPT_OLEN] -
27892 				    (char *)ipha;
27893 				goto param_prob;
27894 			}
27895 			break;
27896 		case IPOPT_TS:
27897 			/*
27898 			 * Verify that length >=5 and that there is either
27899 			 * room for another timestamp or that the overflow
27900 			 * counter is not maxed out.
27901 			 */
27902 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27903 			if (optlen < IPOPT_MINLEN_IT) {
27904 				goto param_prob;
27905 			}
27906 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27907 				ip1dbg((
27908 				    "ip_wput_options: bad option offset\n"));
27909 				code = (char *)&opt[IPOPT_OFFSET] -
27910 				    (char *)ipha;
27911 				goto param_prob;
27912 			}
27913 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27914 			case IPOPT_TS_TSONLY:
27915 				off = IPOPT_TS_TIMELEN;
27916 				break;
27917 			case IPOPT_TS_TSANDADDR:
27918 			case IPOPT_TS_PRESPEC:
27919 			case IPOPT_TS_PRESPEC_RFC791:
27920 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27921 				break;
27922 			default:
27923 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27924 				    (char *)ipha;
27925 				goto param_prob;
27926 			}
27927 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27928 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27929 				/*
27930 				 * No room and the overflow counter is 15
27931 				 * already.
27932 				 */
27933 				goto param_prob;
27934 			}
27935 			break;
27936 		}
27937 	}
27938 
27939 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27940 		return (0);
27941 
27942 	ip1dbg(("ip_wput_options: error processing IP options."));
27943 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27944 
27945 param_prob:
27946 	/*
27947 	 * Since ip_wput() isn't close to finished, we fill
27948 	 * in enough of the header for credible error reporting.
27949 	 */
27950 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27951 		/* Failed */
27952 		freemsg(ipsec_mp);
27953 		return (-1);
27954 	}
27955 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27956 	return (-1);
27957 
27958 bad_src_route:
27959 	/*
27960 	 * Since ip_wput() isn't close to finished, we fill
27961 	 * in enough of the header for credible error reporting.
27962 	 */
27963 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27964 		/* Failed */
27965 		freemsg(ipsec_mp);
27966 		return (-1);
27967 	}
27968 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27969 	return (-1);
27970 }
27971 
27972 /*
27973  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27974  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27975  * thru /etc/system.
27976  */
27977 #define	CONN_MAXDRAINCNT	64
27978 
27979 static void
27980 conn_drain_init(ip_stack_t *ipst)
27981 {
27982 	int i;
27983 
27984 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27985 
27986 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27987 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27988 		/*
27989 		 * Default value of the number of drainers is the
27990 		 * number of cpus, subject to maximum of 8 drainers.
27991 		 */
27992 		if (boot_max_ncpus != -1)
27993 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27994 		else
27995 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27996 	}
27997 
27998 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27999 	    sizeof (idl_t), KM_SLEEP);
28000 
28001 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28002 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28003 		    MUTEX_DEFAULT, NULL);
28004 	}
28005 }
28006 
28007 static void
28008 conn_drain_fini(ip_stack_t *ipst)
28009 {
28010 	int i;
28011 
28012 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28013 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28014 	kmem_free(ipst->ips_conn_drain_list,
28015 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28016 	ipst->ips_conn_drain_list = NULL;
28017 }
28018 
28019 /*
28020  * Note: For an overview of how flowcontrol is handled in IP please see the
28021  * IP Flowcontrol notes at the top of this file.
28022  *
28023  * Flow control has blocked us from proceeding. Insert the given conn in one
28024  * of the conn drain lists. These conn wq's will be qenabled later on when
28025  * STREAMS flow control does a backenable. conn_walk_drain will enable
28026  * the first conn in each of these drain lists. Each of these qenabled conns
28027  * in turn enables the next in the list, after it runs, or when it closes,
28028  * thus sustaining the drain process.
28029  *
28030  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28031  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28032  * running at any time, on a given conn, since there can be only 1 service proc
28033  * running on a queue at any time.
28034  */
28035 void
28036 conn_drain_insert(conn_t *connp)
28037 {
28038 	idl_t	*idl;
28039 	uint_t	index;
28040 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28041 
28042 	mutex_enter(&connp->conn_lock);
28043 	if (connp->conn_state_flags & CONN_CLOSING) {
28044 		/*
28045 		 * The conn is closing as a result of which CONN_CLOSING
28046 		 * is set. Return.
28047 		 */
28048 		mutex_exit(&connp->conn_lock);
28049 		return;
28050 	} else if (connp->conn_idl == NULL) {
28051 		/*
28052 		 * Assign the next drain list round robin. We dont' use
28053 		 * a lock, and thus it may not be strictly round robin.
28054 		 * Atomicity of load/stores is enough to make sure that
28055 		 * conn_drain_list_index is always within bounds.
28056 		 */
28057 		index = ipst->ips_conn_drain_list_index;
28058 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28059 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28060 		index++;
28061 		if (index == ipst->ips_conn_drain_list_cnt)
28062 			index = 0;
28063 		ipst->ips_conn_drain_list_index = index;
28064 	}
28065 	mutex_exit(&connp->conn_lock);
28066 
28067 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28068 	if ((connp->conn_drain_prev != NULL) ||
28069 	    (connp->conn_state_flags & CONN_CLOSING)) {
28070 		/*
28071 		 * The conn is already in the drain list, OR
28072 		 * the conn is closing. We need to check again for
28073 		 * the closing case again since close can happen
28074 		 * after we drop the conn_lock, and before we
28075 		 * acquire the CONN_DRAIN_LIST_LOCK.
28076 		 */
28077 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28078 		return;
28079 	} else {
28080 		idl = connp->conn_idl;
28081 	}
28082 
28083 	/*
28084 	 * The conn is not in the drain list. Insert it at the
28085 	 * tail of the drain list. The drain list is circular
28086 	 * and doubly linked. idl_conn points to the 1st element
28087 	 * in the list.
28088 	 */
28089 	if (idl->idl_conn == NULL) {
28090 		idl->idl_conn = connp;
28091 		connp->conn_drain_next = connp;
28092 		connp->conn_drain_prev = connp;
28093 	} else {
28094 		conn_t *head = idl->idl_conn;
28095 
28096 		connp->conn_drain_next = head;
28097 		connp->conn_drain_prev = head->conn_drain_prev;
28098 		head->conn_drain_prev->conn_drain_next = connp;
28099 		head->conn_drain_prev = connp;
28100 	}
28101 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28102 }
28103 
28104 /*
28105  * This conn is closing, and we are called from ip_close. OR
28106  * This conn has been serviced by ip_wsrv, and we need to do the tail
28107  * processing.
28108  * If this conn is part of the drain list, we may need to sustain the drain
28109  * process by qenabling the next conn in the drain list. We may also need to
28110  * remove this conn from the list, if it is done.
28111  */
28112 static void
28113 conn_drain_tail(conn_t *connp, boolean_t closing)
28114 {
28115 	idl_t *idl;
28116 
28117 	/*
28118 	 * connp->conn_idl is stable at this point, and no lock is needed
28119 	 * to check it. If we are called from ip_close, close has already
28120 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28121 	 * called us only because conn_idl is non-null. If we are called thru
28122 	 * service, conn_idl could be null, but it cannot change because
28123 	 * service is single-threaded per queue, and there cannot be another
28124 	 * instance of service trying to call conn_drain_insert on this conn
28125 	 * now.
28126 	 */
28127 	ASSERT(!closing || (connp->conn_idl != NULL));
28128 
28129 	/*
28130 	 * If connp->conn_idl is null, the conn has not been inserted into any
28131 	 * drain list even once since creation of the conn. Just return.
28132 	 */
28133 	if (connp->conn_idl == NULL)
28134 		return;
28135 
28136 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28137 
28138 	if (connp->conn_drain_prev == NULL) {
28139 		/* This conn is currently not in the drain list.  */
28140 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28141 		return;
28142 	}
28143 	idl = connp->conn_idl;
28144 	if (idl->idl_conn_draining == connp) {
28145 		/*
28146 		 * This conn is the current drainer. If this is the last conn
28147 		 * in the drain list, we need to do more checks, in the 'if'
28148 		 * below. Otherwwise we need to just qenable the next conn,
28149 		 * to sustain the draining, and is handled in the 'else'
28150 		 * below.
28151 		 */
28152 		if (connp->conn_drain_next == idl->idl_conn) {
28153 			/*
28154 			 * This conn is the last in this list. This round
28155 			 * of draining is complete. If idl_repeat is set,
28156 			 * it means another flow enabling has happened from
28157 			 * the driver/streams and we need to another round
28158 			 * of draining.
28159 			 * If there are more than 2 conns in the drain list,
28160 			 * do a left rotate by 1, so that all conns except the
28161 			 * conn at the head move towards the head by 1, and the
28162 			 * the conn at the head goes to the tail. This attempts
28163 			 * a more even share for all queues that are being
28164 			 * drained.
28165 			 */
28166 			if ((connp->conn_drain_next != connp) &&
28167 			    (idl->idl_conn->conn_drain_next != connp)) {
28168 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28169 			}
28170 			if (idl->idl_repeat) {
28171 				qenable(idl->idl_conn->conn_wq);
28172 				idl->idl_conn_draining = idl->idl_conn;
28173 				idl->idl_repeat = 0;
28174 			} else {
28175 				idl->idl_conn_draining = NULL;
28176 			}
28177 		} else {
28178 			/*
28179 			 * If the next queue that we are now qenable'ing,
28180 			 * is closing, it will remove itself from this list
28181 			 * and qenable the subsequent queue in ip_close().
28182 			 * Serialization is acheived thru idl_lock.
28183 			 */
28184 			qenable(connp->conn_drain_next->conn_wq);
28185 			idl->idl_conn_draining = connp->conn_drain_next;
28186 		}
28187 	}
28188 	if (!connp->conn_did_putbq || closing) {
28189 		/*
28190 		 * Remove ourself from the drain list, if we did not do
28191 		 * a putbq, or if the conn is closing.
28192 		 * Note: It is possible that q->q_first is non-null. It means
28193 		 * that these messages landed after we did a enableok() in
28194 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28195 		 * service them.
28196 		 */
28197 		if (connp->conn_drain_next == connp) {
28198 			/* Singleton in the list */
28199 			ASSERT(connp->conn_drain_prev == connp);
28200 			idl->idl_conn = NULL;
28201 			idl->idl_conn_draining = NULL;
28202 		} else {
28203 			connp->conn_drain_prev->conn_drain_next =
28204 			    connp->conn_drain_next;
28205 			connp->conn_drain_next->conn_drain_prev =
28206 			    connp->conn_drain_prev;
28207 			if (idl->idl_conn == connp)
28208 				idl->idl_conn = connp->conn_drain_next;
28209 			ASSERT(idl->idl_conn_draining != connp);
28210 
28211 		}
28212 		connp->conn_drain_next = NULL;
28213 		connp->conn_drain_prev = NULL;
28214 	}
28215 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28216 }
28217 
28218 /*
28219  * Write service routine. Shared perimeter entry point.
28220  * ip_wsrv can be called in any of the following ways.
28221  * 1. The device queue's messages has fallen below the low water mark
28222  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28223  *    the drain lists and backenable the first conn in each list.
28224  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28225  *    qenabled non-tcp upper layers. We start dequeing messages and call
28226  *    ip_wput for each message.
28227  */
28228 
28229 void
28230 ip_wsrv(queue_t *q)
28231 {
28232 	conn_t	*connp;
28233 	ill_t	*ill;
28234 	mblk_t	*mp;
28235 
28236 	if (q->q_next) {
28237 		ill = (ill_t *)q->q_ptr;
28238 		if (ill->ill_state_flags == 0) {
28239 			/*
28240 			 * The device flow control has opened up.
28241 			 * Walk through conn drain lists and qenable the
28242 			 * first conn in each list. This makes sense only
28243 			 * if the stream is fully plumbed and setup.
28244 			 * Hence the if check above.
28245 			 */
28246 			ip1dbg(("ip_wsrv: walking\n"));
28247 			conn_walk_drain(ill->ill_ipst);
28248 		}
28249 		return;
28250 	}
28251 
28252 	connp = Q_TO_CONN(q);
28253 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28254 
28255 	/*
28256 	 * 1. Set conn_draining flag to signal that service is active.
28257 	 *
28258 	 * 2. ip_output determines whether it has been called from service,
28259 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28260 	 *    has been called from service.
28261 	 *
28262 	 * 3. Message ordering is preserved by the following logic.
28263 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28264 	 *    the message at the tail, if conn_draining is set (i.e. service
28265 	 *    is running) or if q->q_first is non-null.
28266 	 *
28267 	 *    ii. If ip_output is called from service, and if ip_output cannot
28268 	 *    putnext due to flow control, it does a putbq.
28269 	 *
28270 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28271 	 *    (causing an infinite loop).
28272 	 */
28273 	ASSERT(!connp->conn_did_putbq);
28274 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28275 		connp->conn_draining = 1;
28276 		noenable(q);
28277 		while ((mp = getq(q)) != NULL) {
28278 			ASSERT(CONN_Q(q));
28279 
28280 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28281 			if (connp->conn_did_putbq) {
28282 				/* ip_wput did a putbq */
28283 				break;
28284 			}
28285 		}
28286 		/*
28287 		 * At this point, a thread coming down from top, calling
28288 		 * ip_wput, may end up queueing the message. We have not yet
28289 		 * enabled the queue, so ip_wsrv won't be called again.
28290 		 * To avoid this race, check q->q_first again (in the loop)
28291 		 * If the other thread queued the message before we call
28292 		 * enableok(), we will catch it in the q->q_first check.
28293 		 * If the other thread queues the message after we call
28294 		 * enableok(), ip_wsrv will be called again by STREAMS.
28295 		 */
28296 		connp->conn_draining = 0;
28297 		enableok(q);
28298 	}
28299 
28300 	/* Enable the next conn for draining */
28301 	conn_drain_tail(connp, B_FALSE);
28302 
28303 	connp->conn_did_putbq = 0;
28304 }
28305 
28306 /*
28307  * Walk the list of all conn's calling the function provided with the
28308  * specified argument for each.	 Note that this only walks conn's that
28309  * have been bound.
28310  * Applies to both IPv4 and IPv6.
28311  */
28312 static void
28313 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28314 {
28315 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28316 	    ipst->ips_ipcl_udp_fanout_size,
28317 	    func, arg, zoneid);
28318 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28319 	    ipst->ips_ipcl_conn_fanout_size,
28320 	    func, arg, zoneid);
28321 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28322 	    ipst->ips_ipcl_bind_fanout_size,
28323 	    func, arg, zoneid);
28324 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28325 	    IPPROTO_MAX, func, arg, zoneid);
28326 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28327 	    IPPROTO_MAX, func, arg, zoneid);
28328 }
28329 
28330 /*
28331  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28332  * of conns that need to be drained, check if drain is already in progress.
28333  * If so set the idl_repeat bit, indicating that the last conn in the list
28334  * needs to reinitiate the drain once again, for the list. If drain is not
28335  * in progress for the list, initiate the draining, by qenabling the 1st
28336  * conn in the list. The drain is self-sustaining, each qenabled conn will
28337  * in turn qenable the next conn, when it is done/blocked/closing.
28338  */
28339 static void
28340 conn_walk_drain(ip_stack_t *ipst)
28341 {
28342 	int i;
28343 	idl_t *idl;
28344 
28345 	IP_STAT(ipst, ip_conn_walk_drain);
28346 
28347 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28348 		idl = &ipst->ips_conn_drain_list[i];
28349 		mutex_enter(&idl->idl_lock);
28350 		if (idl->idl_conn == NULL) {
28351 			mutex_exit(&idl->idl_lock);
28352 			continue;
28353 		}
28354 		/*
28355 		 * If this list is not being drained currently by
28356 		 * an ip_wsrv thread, start the process.
28357 		 */
28358 		if (idl->idl_conn_draining == NULL) {
28359 			ASSERT(idl->idl_repeat == 0);
28360 			qenable(idl->idl_conn->conn_wq);
28361 			idl->idl_conn_draining = idl->idl_conn;
28362 		} else {
28363 			idl->idl_repeat = 1;
28364 		}
28365 		mutex_exit(&idl->idl_lock);
28366 	}
28367 }
28368 
28369 /*
28370  * Walk an conn hash table of `count' buckets, calling func for each entry.
28371  */
28372 static void
28373 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28374     zoneid_t zoneid)
28375 {
28376 	conn_t	*connp;
28377 
28378 	while (count-- > 0) {
28379 		mutex_enter(&connfp->connf_lock);
28380 		for (connp = connfp->connf_head; connp != NULL;
28381 		    connp = connp->conn_next) {
28382 			if (zoneid == GLOBAL_ZONEID ||
28383 			    zoneid == connp->conn_zoneid) {
28384 				CONN_INC_REF(connp);
28385 				mutex_exit(&connfp->connf_lock);
28386 				(*func)(connp, arg);
28387 				mutex_enter(&connfp->connf_lock);
28388 				CONN_DEC_REF(connp);
28389 			}
28390 		}
28391 		mutex_exit(&connfp->connf_lock);
28392 		connfp++;
28393 	}
28394 }
28395 
28396 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28397 static void
28398 conn_report1(conn_t *connp, void *mp)
28399 {
28400 	char	buf1[INET6_ADDRSTRLEN];
28401 	char	buf2[INET6_ADDRSTRLEN];
28402 	uint_t	print_len, buf_len;
28403 
28404 	ASSERT(connp != NULL);
28405 
28406 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28407 	if (buf_len <= 0)
28408 		return;
28409 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28410 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28411 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28412 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28413 	    "%5d %s/%05d %s/%05d\n",
28414 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28415 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28416 	    buf1, connp->conn_lport,
28417 	    buf2, connp->conn_fport);
28418 	if (print_len < buf_len) {
28419 		((mblk_t *)mp)->b_wptr += print_len;
28420 	} else {
28421 		((mblk_t *)mp)->b_wptr += buf_len;
28422 	}
28423 }
28424 
28425 /*
28426  * Named Dispatch routine to produce a formatted report on all conns
28427  * that are listed in one of the fanout tables.
28428  * This report is accessed by using the ndd utility to "get" ND variable
28429  * "ip_conn_status".
28430  */
28431 /* ARGSUSED */
28432 static int
28433 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28434 {
28435 	conn_t *connp = Q_TO_CONN(q);
28436 
28437 	(void) mi_mpprintf(mp,
28438 	    "CONN      " MI_COL_HDRPAD_STR
28439 	    "rfq      " MI_COL_HDRPAD_STR
28440 	    "stq      " MI_COL_HDRPAD_STR
28441 	    " zone local                 remote");
28442 
28443 	/*
28444 	 * Because of the ndd constraint, at most we can have 64K buffer
28445 	 * to put in all conn info.  So to be more efficient, just
28446 	 * allocate a 64K buffer here, assuming we need that large buffer.
28447 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28448 	 */
28449 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28450 		/* The following may work even if we cannot get a large buf. */
28451 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28452 		return (0);
28453 	}
28454 
28455 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28456 	    connp->conn_netstack->netstack_ip);
28457 	return (0);
28458 }
28459 
28460 /*
28461  * Determine if the ill and multicast aspects of that packets
28462  * "matches" the conn.
28463  */
28464 boolean_t
28465 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28466     zoneid_t zoneid)
28467 {
28468 	ill_t *in_ill;
28469 	boolean_t found;
28470 	ipif_t *ipif;
28471 	ire_t *ire;
28472 	ipaddr_t dst, src;
28473 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28474 
28475 	dst = ipha->ipha_dst;
28476 	src = ipha->ipha_src;
28477 
28478 	/*
28479 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28480 	 * unicast, broadcast and multicast reception to
28481 	 * conn_incoming_ill. conn_wantpacket itself is called
28482 	 * only for BROADCAST and multicast.
28483 	 *
28484 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28485 	 *    is part of a group. Hence, we should be receiving
28486 	 *    just one copy of broadcast for the whole group.
28487 	 *    Thus, if it is part of the group the packet could
28488 	 *    come on any ill of the group and hence we need a
28489 	 *    match on the group. Otherwise, match on ill should
28490 	 *    be sufficient.
28491 	 *
28492 	 * 2) ip_rput does not suppress duplicate multicast packets.
28493 	 *    If there are two interfaces in a ill group and we have
28494 	 *    2 applications (conns) joined a multicast group G on
28495 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28496 	 *    will give us two packets because we join G on both the
28497 	 *    interfaces rather than nominating just one interface
28498 	 *    for receiving multicast like broadcast above. So,
28499 	 *    we have to call ilg_lookup_ill to filter out duplicate
28500 	 *    copies, if ill is part of a group.
28501 	 */
28502 	in_ill = connp->conn_incoming_ill;
28503 	if (in_ill != NULL) {
28504 		if (in_ill->ill_group == NULL) {
28505 			if (in_ill != ill)
28506 				return (B_FALSE);
28507 		} else if (in_ill->ill_group != ill->ill_group) {
28508 			return (B_FALSE);
28509 		}
28510 	}
28511 
28512 	if (!CLASSD(dst)) {
28513 		if (IPCL_ZONE_MATCH(connp, zoneid))
28514 			return (B_TRUE);
28515 		/*
28516 		 * The conn is in a different zone; we need to check that this
28517 		 * broadcast address is configured in the application's zone and
28518 		 * on one ill in the group.
28519 		 */
28520 		ipif = ipif_get_next_ipif(NULL, ill);
28521 		if (ipif == NULL)
28522 			return (B_FALSE);
28523 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28524 		    connp->conn_zoneid, NULL,
28525 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28526 		ipif_refrele(ipif);
28527 		if (ire != NULL) {
28528 			ire_refrele(ire);
28529 			return (B_TRUE);
28530 		} else {
28531 			return (B_FALSE);
28532 		}
28533 	}
28534 
28535 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28536 	    connp->conn_zoneid == zoneid) {
28537 		/*
28538 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28539 		 * disabled, therefore we don't dispatch the multicast packet to
28540 		 * the sending zone.
28541 		 */
28542 		return (B_FALSE);
28543 	}
28544 
28545 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28546 		/*
28547 		 * Multicast packet on the loopback interface: we only match
28548 		 * conns who joined the group in the specified zone.
28549 		 */
28550 		return (B_FALSE);
28551 	}
28552 
28553 	if (connp->conn_multi_router) {
28554 		/* multicast packet and multicast router socket: send up */
28555 		return (B_TRUE);
28556 	}
28557 
28558 	mutex_enter(&connp->conn_lock);
28559 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28560 	mutex_exit(&connp->conn_lock);
28561 	return (found);
28562 }
28563 
28564 /*
28565  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28566  */
28567 /* ARGSUSED */
28568 static void
28569 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28570 {
28571 	ill_t *ill = (ill_t *)q->q_ptr;
28572 	mblk_t	*mp1, *mp2;
28573 	ipif_t  *ipif;
28574 	int err = 0;
28575 	conn_t *connp = NULL;
28576 	ipsq_t	*ipsq;
28577 	arc_t	*arc;
28578 
28579 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28580 
28581 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28582 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28583 
28584 	ASSERT(IAM_WRITER_ILL(ill));
28585 	mp2 = mp->b_cont;
28586 	mp->b_cont = NULL;
28587 
28588 	/*
28589 	 * We have now received the arp bringup completion message
28590 	 * from ARP. Mark the arp bringup as done. Also if the arp
28591 	 * stream has already started closing, send up the AR_ARP_CLOSING
28592 	 * ack now since ARP is waiting in close for this ack.
28593 	 */
28594 	mutex_enter(&ill->ill_lock);
28595 	ill->ill_arp_bringup_pending = 0;
28596 	if (ill->ill_arp_closing) {
28597 		mutex_exit(&ill->ill_lock);
28598 		/* Let's reuse the mp for sending the ack */
28599 		arc = (arc_t *)mp->b_rptr;
28600 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28601 		arc->arc_cmd = AR_ARP_CLOSING;
28602 		qreply(q, mp);
28603 	} else {
28604 		mutex_exit(&ill->ill_lock);
28605 		freeb(mp);
28606 	}
28607 
28608 	ipsq = ill->ill_phyint->phyint_ipsq;
28609 	ipif = ipsq->ipsq_pending_ipif;
28610 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28611 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28612 	if (mp1 == NULL) {
28613 		/* bringup was aborted by the user */
28614 		freemsg(mp2);
28615 		return;
28616 	}
28617 
28618 	/*
28619 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28620 	 * must have an associated conn_t.  Otherwise, we're bringing this
28621 	 * interface back up as part of handling an asynchronous event (e.g.,
28622 	 * physical address change).
28623 	 */
28624 	if (ipsq->ipsq_current_ioctl != 0) {
28625 		ASSERT(connp != NULL);
28626 		q = CONNP_TO_WQ(connp);
28627 	} else {
28628 		ASSERT(connp == NULL);
28629 		q = ill->ill_rq;
28630 	}
28631 
28632 	/*
28633 	 * If the DL_BIND_REQ fails, it is noted
28634 	 * in arc_name_offset.
28635 	 */
28636 	err = *((int *)mp2->b_rptr);
28637 	if (err == 0) {
28638 		if (ipif->ipif_isv6) {
28639 			if ((err = ipif_up_done_v6(ipif)) != 0)
28640 				ip0dbg(("ip_arp_done: init failed\n"));
28641 		} else {
28642 			if ((err = ipif_up_done(ipif)) != 0)
28643 				ip0dbg(("ip_arp_done: init failed\n"));
28644 		}
28645 	} else {
28646 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28647 	}
28648 
28649 	freemsg(mp2);
28650 
28651 	if ((err == 0) && (ill->ill_up_ipifs)) {
28652 		err = ill_up_ipifs(ill, q, mp1);
28653 		if (err == EINPROGRESS)
28654 			return;
28655 	}
28656 
28657 	if (ill->ill_up_ipifs)
28658 		ill_group_cleanup(ill);
28659 
28660 	/*
28661 	 * The operation must complete without EINPROGRESS since
28662 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28663 	 * Otherwise, the operation will be stuck forever in the ipsq.
28664 	 */
28665 	ASSERT(err != EINPROGRESS);
28666 	if (ipsq->ipsq_current_ioctl != 0)
28667 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28668 	else
28669 		ipsq_current_finish(ipsq);
28670 }
28671 
28672 /* Allocate the private structure */
28673 static int
28674 ip_priv_alloc(void **bufp)
28675 {
28676 	void	*buf;
28677 
28678 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28679 		return (ENOMEM);
28680 
28681 	*bufp = buf;
28682 	return (0);
28683 }
28684 
28685 /* Function to delete the private structure */
28686 void
28687 ip_priv_free(void *buf)
28688 {
28689 	ASSERT(buf != NULL);
28690 	kmem_free(buf, sizeof (ip_priv_t));
28691 }
28692 
28693 /*
28694  * The entry point for IPPF processing.
28695  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28696  * routine just returns.
28697  *
28698  * When called, ip_process generates an ipp_packet_t structure
28699  * which holds the state information for this packet and invokes the
28700  * the classifier (via ipp_packet_process). The classification, depending on
28701  * configured filters, results in a list of actions for this packet. Invoking
28702  * an action may cause the packet to be dropped, in which case the resulting
28703  * mblk (*mpp) is NULL. proc indicates the callout position for
28704  * this packet and ill_index is the interface this packet on or will leave
28705  * on (inbound and outbound resp.).
28706  */
28707 void
28708 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28709 {
28710 	mblk_t		*mp;
28711 	ip_priv_t	*priv;
28712 	ipp_action_id_t	aid;
28713 	int		rc = 0;
28714 	ipp_packet_t	*pp;
28715 #define	IP_CLASS	"ip"
28716 
28717 	/* If the classifier is not loaded, return  */
28718 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28719 		return;
28720 	}
28721 
28722 	mp = *mpp;
28723 	ASSERT(mp != NULL);
28724 
28725 	/* Allocate the packet structure */
28726 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28727 	if (rc != 0) {
28728 		*mpp = NULL;
28729 		freemsg(mp);
28730 		return;
28731 	}
28732 
28733 	/* Allocate the private structure */
28734 	rc = ip_priv_alloc((void **)&priv);
28735 	if (rc != 0) {
28736 		*mpp = NULL;
28737 		freemsg(mp);
28738 		ipp_packet_free(pp);
28739 		return;
28740 	}
28741 	priv->proc = proc;
28742 	priv->ill_index = ill_index;
28743 	ipp_packet_set_private(pp, priv, ip_priv_free);
28744 	ipp_packet_set_data(pp, mp);
28745 
28746 	/* Invoke the classifier */
28747 	rc = ipp_packet_process(&pp);
28748 	if (pp != NULL) {
28749 		mp = ipp_packet_get_data(pp);
28750 		ipp_packet_free(pp);
28751 		if (rc != 0) {
28752 			freemsg(mp);
28753 			*mpp = NULL;
28754 		}
28755 	} else {
28756 		*mpp = NULL;
28757 	}
28758 #undef	IP_CLASS
28759 }
28760 
28761 /*
28762  * Propagate a multicast group membership operation (add/drop) on
28763  * all the interfaces crossed by the related multirt routes.
28764  * The call is considered successful if the operation succeeds
28765  * on at least one interface.
28766  */
28767 static int
28768 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28769     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28770     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28771     mblk_t *first_mp)
28772 {
28773 	ire_t		*ire_gw;
28774 	irb_t		*irb;
28775 	int		error = 0;
28776 	opt_restart_t	*or;
28777 	ip_stack_t	*ipst = ire->ire_ipst;
28778 
28779 	irb = ire->ire_bucket;
28780 	ASSERT(irb != NULL);
28781 
28782 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28783 
28784 	or = (opt_restart_t *)first_mp->b_rptr;
28785 	IRB_REFHOLD(irb);
28786 	for (; ire != NULL; ire = ire->ire_next) {
28787 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28788 			continue;
28789 		if (ire->ire_addr != group)
28790 			continue;
28791 
28792 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28793 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28794 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28795 		/* No resolver exists for the gateway; skip this ire. */
28796 		if (ire_gw == NULL)
28797 			continue;
28798 
28799 		/*
28800 		 * This function can return EINPROGRESS. If so the operation
28801 		 * will be restarted from ip_restart_optmgmt which will
28802 		 * call ip_opt_set and option processing will restart for
28803 		 * this option. So we may end up calling 'fn' more than once.
28804 		 * This requires that 'fn' is idempotent except for the
28805 		 * return value. The operation is considered a success if
28806 		 * it succeeds at least once on any one interface.
28807 		 */
28808 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28809 		    NULL, fmode, src, first_mp);
28810 		if (error == 0)
28811 			or->or_private = CGTP_MCAST_SUCCESS;
28812 
28813 		if (ip_debug > 0) {
28814 			ulong_t	off;
28815 			char	*ksym;
28816 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28817 			ip2dbg(("ip_multirt_apply_membership: "
28818 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28819 			    "error %d [success %u]\n",
28820 			    ksym ? ksym : "?",
28821 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28822 			    error, or->or_private));
28823 		}
28824 
28825 		ire_refrele(ire_gw);
28826 		if (error == EINPROGRESS) {
28827 			IRB_REFRELE(irb);
28828 			return (error);
28829 		}
28830 	}
28831 	IRB_REFRELE(irb);
28832 	/*
28833 	 * Consider the call as successful if we succeeded on at least
28834 	 * one interface. Otherwise, return the last encountered error.
28835 	 */
28836 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28837 }
28838 
28839 
28840 /*
28841  * Issue a warning regarding a route crossing an interface with an
28842  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28843  * amount of time is logged.
28844  */
28845 static void
28846 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28847 {
28848 	hrtime_t	current = gethrtime();
28849 	char		buf[INET_ADDRSTRLEN];
28850 	ip_stack_t	*ipst = ire->ire_ipst;
28851 
28852 	/* Convert interval in ms to hrtime in ns */
28853 	if (ipst->ips_multirt_bad_mtu_last_time +
28854 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28855 	    current) {
28856 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28857 		    "to %s, incorrect MTU %u (expected %u)\n",
28858 		    ip_dot_addr(ire->ire_addr, buf),
28859 		    ire->ire_max_frag, max_frag);
28860 
28861 		ipst->ips_multirt_bad_mtu_last_time = current;
28862 	}
28863 }
28864 
28865 
28866 /*
28867  * Get the CGTP (multirouting) filtering status.
28868  * If 0, the CGTP hooks are transparent.
28869  */
28870 /* ARGSUSED */
28871 static int
28872 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28873 {
28874 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28875 
28876 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28877 	return (0);
28878 }
28879 
28880 
28881 /*
28882  * Set the CGTP (multirouting) filtering status.
28883  * If the status is changed from active to transparent
28884  * or from transparent to active, forward the new status
28885  * to the filtering module (if loaded).
28886  */
28887 /* ARGSUSED */
28888 static int
28889 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28890     cred_t *ioc_cr)
28891 {
28892 	long		new_value;
28893 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28894 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28895 
28896 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28897 		return (EPERM);
28898 
28899 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28900 	    new_value < 0 || new_value > 1) {
28901 		return (EINVAL);
28902 	}
28903 
28904 	if ((!*ip_cgtp_filter_value) && new_value) {
28905 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28906 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28907 		    " (module not loaded)" : "");
28908 	}
28909 	if (*ip_cgtp_filter_value && (!new_value)) {
28910 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28911 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28912 		    " (module not loaded)" : "");
28913 	}
28914 
28915 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28916 		int	res;
28917 		netstackid_t stackid;
28918 
28919 		stackid = ipst->ips_netstack->netstack_stackid;
28920 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28921 		    new_value);
28922 		if (res)
28923 			return (res);
28924 	}
28925 
28926 	*ip_cgtp_filter_value = (boolean_t)new_value;
28927 
28928 	return (0);
28929 }
28930 
28931 
28932 /*
28933  * Return the expected CGTP hooks version number.
28934  */
28935 int
28936 ip_cgtp_filter_supported(void)
28937 {
28938 	return (ip_cgtp_filter_rev);
28939 }
28940 
28941 
28942 /*
28943  * CGTP hooks can be registered by invoking this function.
28944  * Checks that the version number matches.
28945  */
28946 int
28947 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28948 {
28949 	netstack_t *ns;
28950 	ip_stack_t *ipst;
28951 
28952 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28953 		return (ENOTSUP);
28954 
28955 	ns = netstack_find_by_stackid(stackid);
28956 	if (ns == NULL)
28957 		return (EINVAL);
28958 	ipst = ns->netstack_ip;
28959 	ASSERT(ipst != NULL);
28960 
28961 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28962 		netstack_rele(ns);
28963 		return (EALREADY);
28964 	}
28965 
28966 	ipst->ips_ip_cgtp_filter_ops = ops;
28967 	netstack_rele(ns);
28968 	return (0);
28969 }
28970 
28971 /*
28972  * CGTP hooks can be unregistered by invoking this function.
28973  * Returns ENXIO if there was no registration.
28974  * Returns EBUSY if the ndd variable has not been turned off.
28975  */
28976 int
28977 ip_cgtp_filter_unregister(netstackid_t stackid)
28978 {
28979 	netstack_t *ns;
28980 	ip_stack_t *ipst;
28981 
28982 	ns = netstack_find_by_stackid(stackid);
28983 	if (ns == NULL)
28984 		return (EINVAL);
28985 	ipst = ns->netstack_ip;
28986 	ASSERT(ipst != NULL);
28987 
28988 	if (ipst->ips_ip_cgtp_filter) {
28989 		netstack_rele(ns);
28990 		return (EBUSY);
28991 	}
28992 
28993 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28994 		netstack_rele(ns);
28995 		return (ENXIO);
28996 	}
28997 	ipst->ips_ip_cgtp_filter_ops = NULL;
28998 	netstack_rele(ns);
28999 	return (0);
29000 }
29001 
29002 /*
29003  * Check whether there is a CGTP filter registration.
29004  * Returns non-zero if there is a registration, otherwise returns zero.
29005  * Note: returns zero if bad stackid.
29006  */
29007 int
29008 ip_cgtp_filter_is_registered(netstackid_t stackid)
29009 {
29010 	netstack_t *ns;
29011 	ip_stack_t *ipst;
29012 	int ret;
29013 
29014 	ns = netstack_find_by_stackid(stackid);
29015 	if (ns == NULL)
29016 		return (0);
29017 	ipst = ns->netstack_ip;
29018 	ASSERT(ipst != NULL);
29019 
29020 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29021 		ret = 1;
29022 	else
29023 		ret = 0;
29024 
29025 	netstack_rele(ns);
29026 	return (ret);
29027 }
29028 
29029 static squeue_func_t
29030 ip_squeue_switch(int val)
29031 {
29032 	squeue_func_t rval = squeue_fill;
29033 
29034 	switch (val) {
29035 	case IP_SQUEUE_ENTER_NODRAIN:
29036 		rval = squeue_enter_nodrain;
29037 		break;
29038 	case IP_SQUEUE_ENTER:
29039 		rval = squeue_enter;
29040 		break;
29041 	default:
29042 		break;
29043 	}
29044 	return (rval);
29045 }
29046 
29047 /* ARGSUSED */
29048 static int
29049 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29050     caddr_t addr, cred_t *cr)
29051 {
29052 	int *v = (int *)addr;
29053 	long new_value;
29054 
29055 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29056 		return (EPERM);
29057 
29058 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29059 		return (EINVAL);
29060 
29061 	ip_input_proc = ip_squeue_switch(new_value);
29062 	*v = new_value;
29063 	return (0);
29064 }
29065 
29066 /* ARGSUSED */
29067 static int
29068 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29069     caddr_t addr, cred_t *cr)
29070 {
29071 	int *v = (int *)addr;
29072 	long new_value;
29073 
29074 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29075 		return (EPERM);
29076 
29077 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29078 		return (EINVAL);
29079 
29080 	*v = new_value;
29081 	return (0);
29082 }
29083 
29084 /*
29085  * Handle changes to ipmp_hook_emulation ndd variable.
29086  * Need to update phyint_hook_ifindex.
29087  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29088  */
29089 static void
29090 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29091 {
29092 	phyint_t *phyi;
29093 	phyint_t *phyi_tmp;
29094 	char *groupname;
29095 	int namelen;
29096 	ill_t	*ill;
29097 	boolean_t new_group;
29098 
29099 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29100 	/*
29101 	 * Group indicies are stored in the phyint - a common structure
29102 	 * to both IPv4 and IPv6.
29103 	 */
29104 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29105 	for (; phyi != NULL;
29106 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29107 	    phyi, AVL_AFTER)) {
29108 		/* Ignore the ones that do not have a group */
29109 		if (phyi->phyint_groupname_len == 0)
29110 			continue;
29111 
29112 		/*
29113 		 * Look for other phyint in group.
29114 		 * Clear name/namelen so the lookup doesn't find ourselves.
29115 		 */
29116 		namelen = phyi->phyint_groupname_len;
29117 		groupname = phyi->phyint_groupname;
29118 		phyi->phyint_groupname_len = 0;
29119 		phyi->phyint_groupname = NULL;
29120 
29121 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29122 		/* Restore */
29123 		phyi->phyint_groupname_len = namelen;
29124 		phyi->phyint_groupname = groupname;
29125 
29126 		new_group = B_FALSE;
29127 		if (ipst->ips_ipmp_hook_emulation) {
29128 			/*
29129 			 * If the group already exists and has already
29130 			 * been assigned a group ifindex, we use the existing
29131 			 * group_ifindex, otherwise we pick a new group_ifindex
29132 			 * here.
29133 			 */
29134 			if (phyi_tmp != NULL &&
29135 			    phyi_tmp->phyint_group_ifindex != 0) {
29136 				phyi->phyint_group_ifindex =
29137 				    phyi_tmp->phyint_group_ifindex;
29138 			} else {
29139 				/* XXX We need a recovery strategy here. */
29140 				if (!ip_assign_ifindex(
29141 				    &phyi->phyint_group_ifindex, ipst))
29142 					cmn_err(CE_PANIC,
29143 					    "ip_assign_ifindex() failed");
29144 				new_group = B_TRUE;
29145 			}
29146 		} else {
29147 			phyi->phyint_group_ifindex = 0;
29148 		}
29149 		if (ipst->ips_ipmp_hook_emulation)
29150 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29151 		else
29152 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29153 
29154 		/*
29155 		 * For IP Filter to find out the relationship between
29156 		 * names and interface indicies, we need to generate
29157 		 * a NE_PLUMB event when a new group can appear.
29158 		 * We always generate events when a new interface appears
29159 		 * (even when ipmp_hook_emulation is set) so there
29160 		 * is no need to generate NE_PLUMB events when
29161 		 * ipmp_hook_emulation is turned off.
29162 		 * And since it isn't critical for IP Filter to get
29163 		 * the NE_UNPLUMB events we skip those here.
29164 		 */
29165 		if (new_group) {
29166 			/*
29167 			 * First phyint in group - generate group PLUMB event.
29168 			 * Since we are not running inside the ipsq we do
29169 			 * the dispatch immediately.
29170 			 */
29171 			if (phyi->phyint_illv4 != NULL)
29172 				ill = phyi->phyint_illv4;
29173 			else
29174 				ill = phyi->phyint_illv6;
29175 
29176 			if (ill != NULL) {
29177 				mutex_enter(&ill->ill_lock);
29178 				ill_nic_info_plumb(ill, B_TRUE);
29179 				ill_nic_info_dispatch(ill);
29180 				mutex_exit(&ill->ill_lock);
29181 			}
29182 		}
29183 	}
29184 	rw_exit(&ipst->ips_ill_g_lock);
29185 }
29186 
29187 /* ARGSUSED */
29188 static int
29189 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29190     caddr_t addr, cred_t *cr)
29191 {
29192 	int *v = (int *)addr;
29193 	long new_value;
29194 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29195 
29196 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29197 		return (EINVAL);
29198 
29199 	if (*v != new_value) {
29200 		*v = new_value;
29201 		ipmp_hook_emulation_changed(ipst);
29202 	}
29203 	return (0);
29204 }
29205 
29206 static void *
29207 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29208 {
29209 	kstat_t *ksp;
29210 
29211 	ip_stat_t template = {
29212 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29213 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29214 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29215 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29216 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29217 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29218 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29219 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29220 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29221 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29222 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29223 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29224 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29225 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29226 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29227 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29228 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29229 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29230 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29231 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29232 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29233 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29234 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29235 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29236 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29237 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29238 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29239 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29240 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29241 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29242 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29243 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29244 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29245 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29246 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29247 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29248 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29249 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29250 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29251 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29252 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29253 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29254 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29255 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29256 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29257 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29258 	};
29259 
29260 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29261 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29262 	    KSTAT_FLAG_VIRTUAL, stackid);
29263 
29264 	if (ksp == NULL)
29265 		return (NULL);
29266 
29267 	bcopy(&template, ip_statisticsp, sizeof (template));
29268 	ksp->ks_data = (void *)ip_statisticsp;
29269 	ksp->ks_private = (void *)(uintptr_t)stackid;
29270 
29271 	kstat_install(ksp);
29272 	return (ksp);
29273 }
29274 
29275 static void
29276 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29277 {
29278 	if (ksp != NULL) {
29279 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29280 		kstat_delete_netstack(ksp, stackid);
29281 	}
29282 }
29283 
29284 static void *
29285 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29286 {
29287 	kstat_t	*ksp;
29288 
29289 	ip_named_kstat_t template = {
29290 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29291 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29292 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29293 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29294 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29295 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29296 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29297 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29298 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29299 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29300 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29301 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29302 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29303 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29304 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29305 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29306 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29307 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29308 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29309 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29310 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29311 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29312 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29313 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29314 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29315 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29316 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29317 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29318 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29319 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29320 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29321 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29322 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29323 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29324 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29325 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29326 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29327 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29328 	};
29329 
29330 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29331 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29332 	if (ksp == NULL || ksp->ks_data == NULL)
29333 		return (NULL);
29334 
29335 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29336 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29337 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29338 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29339 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29340 
29341 	template.netToMediaEntrySize.value.i32 =
29342 	    sizeof (mib2_ipNetToMediaEntry_t);
29343 
29344 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29345 
29346 	bcopy(&template, ksp->ks_data, sizeof (template));
29347 	ksp->ks_update = ip_kstat_update;
29348 	ksp->ks_private = (void *)(uintptr_t)stackid;
29349 
29350 	kstat_install(ksp);
29351 	return (ksp);
29352 }
29353 
29354 static void
29355 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29356 {
29357 	if (ksp != NULL) {
29358 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29359 		kstat_delete_netstack(ksp, stackid);
29360 	}
29361 }
29362 
29363 static int
29364 ip_kstat_update(kstat_t *kp, int rw)
29365 {
29366 	ip_named_kstat_t *ipkp;
29367 	mib2_ipIfStatsEntry_t ipmib;
29368 	ill_walk_context_t ctx;
29369 	ill_t *ill;
29370 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29371 	netstack_t	*ns;
29372 	ip_stack_t	*ipst;
29373 
29374 	if (kp == NULL || kp->ks_data == NULL)
29375 		return (EIO);
29376 
29377 	if (rw == KSTAT_WRITE)
29378 		return (EACCES);
29379 
29380 	ns = netstack_find_by_stackid(stackid);
29381 	if (ns == NULL)
29382 		return (-1);
29383 	ipst = ns->netstack_ip;
29384 	if (ipst == NULL) {
29385 		netstack_rele(ns);
29386 		return (-1);
29387 	}
29388 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29389 
29390 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29391 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29392 	ill = ILL_START_WALK_V4(&ctx, ipst);
29393 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29394 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29395 	rw_exit(&ipst->ips_ill_g_lock);
29396 
29397 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29398 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29399 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29400 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29401 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29402 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29403 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29404 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29405 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29406 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29407 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29408 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29409 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29410 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29411 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29412 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29413 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29414 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29415 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29416 
29417 	ipkp->routingDiscards.value.ui32 =	0;
29418 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29419 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29420 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29421 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29422 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29423 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29424 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29425 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29426 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29427 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29428 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29429 
29430 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29431 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29432 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29433 
29434 	netstack_rele(ns);
29435 
29436 	return (0);
29437 }
29438 
29439 static void *
29440 icmp_kstat_init(netstackid_t stackid)
29441 {
29442 	kstat_t	*ksp;
29443 
29444 	icmp_named_kstat_t template = {
29445 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29446 		{ "inErrors",		KSTAT_DATA_UINT32 },
29447 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29448 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29449 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29450 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29451 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29452 		{ "inEchos",		KSTAT_DATA_UINT32 },
29453 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29454 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29455 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29456 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29457 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29458 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29459 		{ "outErrors",		KSTAT_DATA_UINT32 },
29460 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29461 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29462 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29463 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29464 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29465 		{ "outEchos",		KSTAT_DATA_UINT32 },
29466 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29467 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29468 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29469 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29470 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29471 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29472 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29473 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29474 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29475 		{ "outDrops",		KSTAT_DATA_UINT32 },
29476 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29477 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29478 	};
29479 
29480 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29481 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29482 	if (ksp == NULL || ksp->ks_data == NULL)
29483 		return (NULL);
29484 
29485 	bcopy(&template, ksp->ks_data, sizeof (template));
29486 
29487 	ksp->ks_update = icmp_kstat_update;
29488 	ksp->ks_private = (void *)(uintptr_t)stackid;
29489 
29490 	kstat_install(ksp);
29491 	return (ksp);
29492 }
29493 
29494 static void
29495 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29496 {
29497 	if (ksp != NULL) {
29498 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29499 		kstat_delete_netstack(ksp, stackid);
29500 	}
29501 }
29502 
29503 static int
29504 icmp_kstat_update(kstat_t *kp, int rw)
29505 {
29506 	icmp_named_kstat_t *icmpkp;
29507 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29508 	netstack_t	*ns;
29509 	ip_stack_t	*ipst;
29510 
29511 	if ((kp == NULL) || (kp->ks_data == NULL))
29512 		return (EIO);
29513 
29514 	if (rw == KSTAT_WRITE)
29515 		return (EACCES);
29516 
29517 	ns = netstack_find_by_stackid(stackid);
29518 	if (ns == NULL)
29519 		return (-1);
29520 	ipst = ns->netstack_ip;
29521 	if (ipst == NULL) {
29522 		netstack_rele(ns);
29523 		return (-1);
29524 	}
29525 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29526 
29527 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29528 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29529 	icmpkp->inDestUnreachs.value.ui32 =
29530 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29531 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29532 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29533 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29534 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29535 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29536 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29537 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29538 	icmpkp->inTimestampReps.value.ui32 =
29539 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29540 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29541 	icmpkp->inAddrMaskReps.value.ui32 =
29542 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29543 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29544 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29545 	icmpkp->outDestUnreachs.value.ui32 =
29546 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29547 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29548 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29549 	icmpkp->outSrcQuenchs.value.ui32 =
29550 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29551 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29552 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29553 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29554 	icmpkp->outTimestamps.value.ui32 =
29555 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29556 	icmpkp->outTimestampReps.value.ui32 =
29557 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29558 	icmpkp->outAddrMasks.value.ui32 =
29559 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29560 	icmpkp->outAddrMaskReps.value.ui32 =
29561 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29562 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29563 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29564 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29565 	icmpkp->outFragNeeded.value.ui32 =
29566 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29567 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29568 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29569 	icmpkp->inBadRedirects.value.ui32 =
29570 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29571 
29572 	netstack_rele(ns);
29573 	return (0);
29574 }
29575 
29576 /*
29577  * This is the fanout function for raw socket opened for SCTP.  Note
29578  * that it is called after SCTP checks that there is no socket which
29579  * wants a packet.  Then before SCTP handles this out of the blue packet,
29580  * this function is called to see if there is any raw socket for SCTP.
29581  * If there is and it is bound to the correct address, the packet will
29582  * be sent to that socket.  Note that only one raw socket can be bound to
29583  * a port.  This is assured in ipcl_sctp_hash_insert();
29584  */
29585 void
29586 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29587     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29588     zoneid_t zoneid)
29589 {
29590 	conn_t		*connp;
29591 	queue_t		*rq;
29592 	mblk_t		*first_mp;
29593 	boolean_t	secure;
29594 	ip6_t		*ip6h;
29595 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29596 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29597 
29598 	first_mp = mp;
29599 	if (mctl_present) {
29600 		mp = first_mp->b_cont;
29601 		secure = ipsec_in_is_secure(first_mp);
29602 		ASSERT(mp != NULL);
29603 	} else {
29604 		secure = B_FALSE;
29605 	}
29606 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29607 
29608 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29609 	if (connp == NULL) {
29610 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29611 		return;
29612 	}
29613 	rq = connp->conn_rq;
29614 	if (!canputnext(rq)) {
29615 		CONN_DEC_REF(connp);
29616 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29617 		freemsg(first_mp);
29618 		return;
29619 	}
29620 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29621 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29622 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29623 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29624 		if (first_mp == NULL) {
29625 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29626 			CONN_DEC_REF(connp);
29627 			return;
29628 		}
29629 	}
29630 	/*
29631 	 * We probably should not send M_CTL message up to
29632 	 * raw socket.
29633 	 */
29634 	if (mctl_present)
29635 		freeb(first_mp);
29636 
29637 	/* Initiate IPPF processing here if needed. */
29638 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29639 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29640 		ip_process(IPP_LOCAL_IN, &mp,
29641 		    recv_ill->ill_phyint->phyint_ifindex);
29642 		if (mp == NULL) {
29643 			CONN_DEC_REF(connp);
29644 			return;
29645 		}
29646 	}
29647 
29648 	if (connp->conn_recvif || connp->conn_recvslla ||
29649 	    ((connp->conn_ip_recvpktinfo ||
29650 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29651 	    (flags & IP_FF_IPINFO))) {
29652 		int in_flags = 0;
29653 
29654 		/*
29655 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29656 		 * IPF_RECVIF.
29657 		 */
29658 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29659 			in_flags = IPF_RECVIF;
29660 		}
29661 		if (connp->conn_recvslla) {
29662 			in_flags |= IPF_RECVSLLA;
29663 		}
29664 		if (isv4) {
29665 			mp = ip_add_info(mp, recv_ill, in_flags,
29666 			    IPCL_ZONEID(connp), ipst);
29667 		} else {
29668 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29669 			if (mp == NULL) {
29670 				BUMP_MIB(recv_ill->ill_ip_mib,
29671 				    ipIfStatsInDiscards);
29672 				CONN_DEC_REF(connp);
29673 				return;
29674 			}
29675 		}
29676 	}
29677 
29678 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29679 	/*
29680 	 * We are sending the IPSEC_IN message also up. Refer
29681 	 * to comments above this function.
29682 	 */
29683 	putnext(rq, mp);
29684 	CONN_DEC_REF(connp);
29685 }
29686 
29687 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29688 {									\
29689 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29690 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29691 }
29692 /*
29693  * This function should be called only if all packet processing
29694  * including fragmentation is complete. Callers of this function
29695  * must set mp->b_prev to one of these values:
29696  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29697  * prior to handing over the mp as first argument to this function.
29698  *
29699  * If the ire passed by caller is incomplete, this function
29700  * queues the packet and if necessary, sends ARP request and bails.
29701  * If the ire passed is fully resolved, we simply prepend
29702  * the link-layer header to the packet, do ipsec hw acceleration
29703  * work if necessary, and send the packet out on the wire.
29704  *
29705  * NOTE: IPsec will only call this function with fully resolved
29706  * ires if hw acceleration is involved.
29707  * TODO list :
29708  * 	a Handle M_MULTIDATA so that
29709  *	  tcp_multisend->tcp_multisend_data can
29710  *	  call ip_xmit_v4 directly
29711  *	b Handle post-ARP work for fragments so that
29712  *	  ip_wput_frag can call this function.
29713  */
29714 ipxmit_state_t
29715 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29716 {
29717 	nce_t		*arpce;
29718 	queue_t		*q;
29719 	int		ill_index;
29720 	mblk_t		*nxt_mp, *first_mp;
29721 	boolean_t	xmit_drop = B_FALSE;
29722 	ip_proc_t	proc;
29723 	ill_t		*out_ill;
29724 	int		pkt_len;
29725 
29726 	arpce = ire->ire_nce;
29727 	ASSERT(arpce != NULL);
29728 
29729 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29730 
29731 	mutex_enter(&arpce->nce_lock);
29732 	switch (arpce->nce_state) {
29733 	case ND_REACHABLE:
29734 		/* If there are other queued packets, queue this packet */
29735 		if (arpce->nce_qd_mp != NULL) {
29736 			if (mp != NULL)
29737 				nce_queue_mp_common(arpce, mp, B_FALSE);
29738 			mp = arpce->nce_qd_mp;
29739 		}
29740 		arpce->nce_qd_mp = NULL;
29741 		mutex_exit(&arpce->nce_lock);
29742 
29743 		/*
29744 		 * Flush the queue.  In the common case, where the
29745 		 * ARP is already resolved,  it will go through the
29746 		 * while loop only once.
29747 		 */
29748 		while (mp != NULL) {
29749 
29750 			nxt_mp = mp->b_next;
29751 			mp->b_next = NULL;
29752 			ASSERT(mp->b_datap->db_type != M_CTL);
29753 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29754 			/*
29755 			 * This info is needed for IPQOS to do COS marking
29756 			 * in ip_wput_attach_llhdr->ip_process.
29757 			 */
29758 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29759 			mp->b_prev = NULL;
29760 
29761 			/* set up ill index for outbound qos processing */
29762 			out_ill = ire->ire_ipif->ipif_ill;
29763 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29764 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29765 			    ill_index);
29766 			if (first_mp == NULL) {
29767 				xmit_drop = B_TRUE;
29768 				BUMP_MIB(out_ill->ill_ip_mib,
29769 				    ipIfStatsOutDiscards);
29770 				goto next_mp;
29771 			}
29772 			/* non-ipsec hw accel case */
29773 			if (io == NULL || !io->ipsec_out_accelerated) {
29774 				/* send it */
29775 				q = ire->ire_stq;
29776 				if (proc == IPP_FWD_OUT) {
29777 					UPDATE_IB_PKT_COUNT(ire);
29778 				} else {
29779 					UPDATE_OB_PKT_COUNT(ire);
29780 				}
29781 				ire->ire_last_used_time = lbolt;
29782 
29783 				if (flow_ctl_enabled || canputnext(q)) {
29784 					if (proc == IPP_FWD_OUT) {
29785 
29786 					BUMP_MIB(out_ill->ill_ip_mib,
29787 					    ipIfStatsHCOutForwDatagrams);
29788 
29789 					}
29790 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29791 					    pkt_len);
29792 
29793 					putnext(q, first_mp);
29794 				} else {
29795 					BUMP_MIB(out_ill->ill_ip_mib,
29796 					    ipIfStatsOutDiscards);
29797 					xmit_drop = B_TRUE;
29798 					freemsg(first_mp);
29799 				}
29800 			} else {
29801 				/*
29802 				 * Safety Pup says: make sure this
29803 				 *  is going to the right interface!
29804 				 */
29805 				ill_t *ill1 =
29806 				    (ill_t *)ire->ire_stq->q_ptr;
29807 				int ifindex =
29808 				    ill1->ill_phyint->phyint_ifindex;
29809 				if (ifindex !=
29810 				    io->ipsec_out_capab_ill_index) {
29811 					xmit_drop = B_TRUE;
29812 					freemsg(mp);
29813 				} else {
29814 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29815 					    pkt_len);
29816 					ipsec_hw_putnext(ire->ire_stq, mp);
29817 				}
29818 			}
29819 next_mp:
29820 			mp = nxt_mp;
29821 		} /* while (mp != NULL) */
29822 		if (xmit_drop)
29823 			return (SEND_FAILED);
29824 		else
29825 			return (SEND_PASSED);
29826 
29827 	case ND_INITIAL:
29828 	case ND_INCOMPLETE:
29829 
29830 		/*
29831 		 * While we do send off packets to dests that
29832 		 * use fully-resolved CGTP routes, we do not
29833 		 * handle unresolved CGTP routes.
29834 		 */
29835 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29836 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29837 
29838 		if (mp != NULL) {
29839 			/* queue the packet */
29840 			nce_queue_mp_common(arpce, mp, B_FALSE);
29841 		}
29842 
29843 		if (arpce->nce_state == ND_INCOMPLETE) {
29844 			mutex_exit(&arpce->nce_lock);
29845 			DTRACE_PROBE3(ip__xmit__incomplete,
29846 			    (ire_t *), ire, (mblk_t *), mp,
29847 			    (ipsec_out_t *), io);
29848 			return (LOOKUP_IN_PROGRESS);
29849 		}
29850 
29851 		arpce->nce_state = ND_INCOMPLETE;
29852 		mutex_exit(&arpce->nce_lock);
29853 		/*
29854 		 * Note that ire_add() (called from ire_forward())
29855 		 * holds a ref on the ire until ARP is completed.
29856 		 */
29857 
29858 		ire_arpresolve(ire, ire_to_ill(ire));
29859 		return (LOOKUP_IN_PROGRESS);
29860 	default:
29861 		ASSERT(0);
29862 		mutex_exit(&arpce->nce_lock);
29863 		return (LLHDR_RESLV_FAILED);
29864 	}
29865 }
29866 
29867 #undef	UPDATE_IP_MIB_OB_COUNTERS
29868 
29869 /*
29870  * Return B_TRUE if the buffers differ in length or content.
29871  * This is used for comparing extension header buffers.
29872  * Note that an extension header would be declared different
29873  * even if all that changed was the next header value in that header i.e.
29874  * what really changed is the next extension header.
29875  */
29876 boolean_t
29877 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29878     uint_t blen)
29879 {
29880 	if (!b_valid)
29881 		blen = 0;
29882 
29883 	if (alen != blen)
29884 		return (B_TRUE);
29885 	if (alen == 0)
29886 		return (B_FALSE);	/* Both zero length */
29887 	return (bcmp(abuf, bbuf, alen));
29888 }
29889 
29890 /*
29891  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29892  * Return B_FALSE if memory allocation fails - don't change any state!
29893  */
29894 boolean_t
29895 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29896     const void *src, uint_t srclen)
29897 {
29898 	void *dst;
29899 
29900 	if (!src_valid)
29901 		srclen = 0;
29902 
29903 	ASSERT(*dstlenp == 0);
29904 	if (src != NULL && srclen != 0) {
29905 		dst = mi_alloc(srclen, BPRI_MED);
29906 		if (dst == NULL)
29907 			return (B_FALSE);
29908 	} else {
29909 		dst = NULL;
29910 	}
29911 	if (*dstp != NULL)
29912 		mi_free(*dstp);
29913 	*dstp = dst;
29914 	*dstlenp = dst == NULL ? 0 : srclen;
29915 	return (B_TRUE);
29916 }
29917 
29918 /*
29919  * Replace what is in *dst, *dstlen with the source.
29920  * Assumes ip_allocbuf has already been called.
29921  */
29922 void
29923 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29924     const void *src, uint_t srclen)
29925 {
29926 	if (!src_valid)
29927 		srclen = 0;
29928 
29929 	ASSERT(*dstlenp == srclen);
29930 	if (src != NULL && srclen != 0)
29931 		bcopy(src, *dstp, srclen);
29932 }
29933 
29934 /*
29935  * Free the storage pointed to by the members of an ip6_pkt_t.
29936  */
29937 void
29938 ip6_pkt_free(ip6_pkt_t *ipp)
29939 {
29940 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29941 
29942 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29943 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29944 		ipp->ipp_hopopts = NULL;
29945 		ipp->ipp_hopoptslen = 0;
29946 	}
29947 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29948 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29949 		ipp->ipp_rtdstopts = NULL;
29950 		ipp->ipp_rtdstoptslen = 0;
29951 	}
29952 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29953 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29954 		ipp->ipp_dstopts = NULL;
29955 		ipp->ipp_dstoptslen = 0;
29956 	}
29957 	if (ipp->ipp_fields & IPPF_RTHDR) {
29958 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29959 		ipp->ipp_rthdr = NULL;
29960 		ipp->ipp_rthdrlen = 0;
29961 	}
29962 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29963 	    IPPF_RTHDR);
29964 }
29965