xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 96fe64c1)
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 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
797 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
798 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
799 
800 /*
801  * XXX following really should only be in a header. Would need more
802  * header and .c clean up first.
803  */
804 extern optdb_obj_t	ip_opt_obj;
805 
806 ulong_t ip_squeue_enter_unbound = 0;
807 
808 /*
809  * Named Dispatch Parameter Table.
810  * All of these are alterable, within the min/max values given, at run time.
811  */
812 static ipparam_t	lcl_param_arr[] = {
813 	/* min	max	value	name */
814 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
815 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
816 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
817 	{  0,	1,	0,	"ip_respond_to_timestamp"},
818 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
819 	{  0,	1,	1,	"ip_send_redirects"},
820 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
821 	{  0,	10,	0,	"ip_debug"},
822 	{  0,	10,	0,	"ip_mrtdebug"},
823 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
824 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
825 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
826 	{  1,	255,	255,	"ip_def_ttl" },
827 	{  0,	1,	0,	"ip_forward_src_routed"},
828 	{  0,	256,	32,	"ip_wroff_extra" },
829 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
830 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
831 	{  0,	1,	1,	"ip_path_mtu_discovery" },
832 	{  0,	240,	30,	"ip_ignore_delete_time" },
833 	{  0,	1,	0,	"ip_ignore_redirect" },
834 	{  0,	1,	1,	"ip_output_queue" },
835 	{  1,	254,	1,	"ip_broadcast_ttl" },
836 	{  0,	99999,	100,	"ip_icmp_err_interval" },
837 	{  1,	99999,	10,	"ip_icmp_err_burst" },
838 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
839 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
840 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
841 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
842 	{  0,	1,	1,	"icmp_accept_clear_messages" },
843 	{  0,	1,	1,	"igmp_accept_clear_messages" },
844 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
845 				"ip_ndp_delay_first_probe_time"},
846 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
847 				"ip_ndp_max_unicast_solicit"},
848 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
849 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
850 	{  0,	1,	0,	"ip6_forward_src_routed"},
851 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
852 	{  0,	1,	1,	"ip6_send_redirects"},
853 	{  0,	1,	0,	"ip6_ignore_redirect" },
854 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
855 
856 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
857 
858 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
859 
860 	{  0,	1,	1,	"pim_accept_clear_messages" },
861 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
862 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
863 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
864 	{  0,	15,	0,	"ip_policy_mask" },
865 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
866 	{  0,	255,	1,	"ip_multirt_ttl" },
867 	{  0,	1,	1,	"ip_multidata_outbound" },
868 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
869 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
870 	{  0,	1000,	1,	"ip_max_temp_defend" },
871 	{  0,	1000,	3,	"ip_max_defend" },
872 	{  0,	999999,	30,	"ip_defend_interval" },
873 	{  0,	3600000, 300000, "ip_dup_recovery" },
874 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
875 	{  0,	1,	1,	"ip_lso_outbound" },
876 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
877 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
878 #ifdef DEBUG
879 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
880 #else
881 	{  0,	0,	0,	"" },
882 #endif
883 };
884 
885 /*
886  * Extended NDP table
887  * The addresses for the first two are filled in to be ips_ip_g_forward
888  * and ips_ipv6_forward at init time.
889  */
890 static ipndp_t	lcl_ndp_arr[] = {
891 	/* getf			setf		data			name */
892 #define	IPNDP_IP_FORWARDING_OFFSET	0
893 	{  ip_param_generic_get,	ip_forward_set,	NULL,
894 	    "ip_forwarding" },
895 #define	IPNDP_IP6_FORWARDING_OFFSET	1
896 	{  ip_param_generic_get,	ip_forward_set,	NULL,
897 	    "ip6_forwarding" },
898 	{  ip_ill_report,	NULL,		NULL,
899 	    "ip_ill_status" },
900 	{  ip_ipif_report,	NULL,		NULL,
901 	    "ip_ipif_status" },
902 	{  ip_ire_report,	NULL,		NULL,
903 	    "ipv4_ire_status" },
904 	{  ip_ire_report_v6,	NULL,		NULL,
905 	    "ipv6_ire_status" },
906 	{  ip_conn_report,	NULL,		NULL,
907 	    "ip_conn_status" },
908 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
909 	    "ip_rput_pullups" },
910 	{  ndp_report,		NULL,		NULL,
911 	    "ip_ndp_cache_report" },
912 	{  ip_srcid_report,	NULL,		NULL,
913 	    "ip_srcid_status" },
914 	{ ip_param_generic_get, ip_squeue_profile_set,
915 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
916 	{ ip_param_generic_get, ip_squeue_bind_set,
917 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
918 	{ ip_param_generic_get, ip_input_proc_set,
919 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
920 	{ ip_param_generic_get, ip_int_set,
921 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
922 #define	IPNDP_CGTP_FILTER_OFFSET	14
923 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
924 	    "ip_cgtp_filter" },
925 	{ ip_param_generic_get, ip_int_set,
926 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
927 #define	IPNDP_IPMP_HOOK_OFFSET	16
928 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
929 	    "ipmp_hook_emulation" },
930 };
931 
932 /*
933  * Table of IP ioctls encoding the various properties of the ioctl and
934  * indexed based on the last byte of the ioctl command. Occasionally there
935  * is a clash, and there is more than 1 ioctl with the same last byte.
936  * In such a case 1 ioctl is encoded in the ndx table and the remaining
937  * ioctls are encoded in the misc table. An entry in the ndx table is
938  * retrieved by indexing on the last byte of the ioctl command and comparing
939  * the ioctl command with the value in the ndx table. In the event of a
940  * mismatch the misc table is then searched sequentially for the desired
941  * ioctl command.
942  *
943  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
944  */
945 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
946 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
947 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
948 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 
957 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
958 			MISC_CMD, ip_siocaddrt, NULL },
959 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
960 			MISC_CMD, ip_siocdelrt, NULL },
961 
962 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
963 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
964 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
965 			IF_CMD, ip_sioctl_get_addr, NULL },
966 
967 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
968 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
969 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
970 			IPI_GET_CMD | IPI_REPL,
971 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
972 
973 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
974 			IPI_PRIV | IPI_WR | IPI_REPL,
975 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
976 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
977 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
978 			IF_CMD, ip_sioctl_get_flags, NULL },
979 
980 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
981 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
982 
983 	/* copyin size cannot be coded for SIOCGIFCONF */
984 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
985 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
986 
987 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
988 			IF_CMD, ip_sioctl_mtu, NULL },
989 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
990 			IF_CMD, ip_sioctl_get_mtu, NULL },
991 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
992 			IPI_GET_CMD | IPI_REPL,
993 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
994 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
995 			IF_CMD, ip_sioctl_brdaddr, NULL },
996 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
997 			IPI_GET_CMD | IPI_REPL,
998 			IF_CMD, ip_sioctl_get_netmask, NULL },
999 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1000 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1001 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1002 			IPI_GET_CMD | IPI_REPL,
1003 			IF_CMD, ip_sioctl_get_metric, NULL },
1004 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1005 			IF_CMD, ip_sioctl_metric, NULL },
1006 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1007 
1008 	/* See 166-168 below for extended SIOC*XARP ioctls */
1009 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1010 			MISC_CMD, ip_sioctl_arp, NULL },
1011 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1012 			MISC_CMD, ip_sioctl_arp, NULL },
1013 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1014 			MISC_CMD, ip_sioctl_arp, NULL },
1015 
1016 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1017 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 
1038 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1039 			MISC_CMD, if_unitsel, if_unitsel_restart },
1040 
1041 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 
1060 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1061 			IPI_PRIV | IPI_WR | IPI_MODOK,
1062 			IF_CMD, ip_sioctl_sifname, NULL },
1063 
1064 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 
1078 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1079 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1080 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1081 			IF_CMD, ip_sioctl_get_muxid, NULL },
1082 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1083 			IPI_PRIV | IPI_WR | IPI_REPL,
1084 			IF_CMD, ip_sioctl_muxid, NULL },
1085 
1086 	/* Both if and lif variants share same func */
1087 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1088 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1089 	/* Both if and lif variants share same func */
1090 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1091 			IPI_PRIV | IPI_WR | IPI_REPL,
1092 			IF_CMD, ip_sioctl_slifindex, NULL },
1093 
1094 	/* copyin size cannot be coded for SIOCGIFCONF */
1095 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1096 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1097 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 
1115 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1116 			IPI_PRIV | IPI_WR | IPI_REPL,
1117 			LIF_CMD, ip_sioctl_removeif,
1118 			ip_sioctl_removeif_restart },
1119 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1120 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1121 			LIF_CMD, ip_sioctl_addif, NULL },
1122 #define	SIOCLIFADDR_NDX 112
1123 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1124 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1125 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1126 			IPI_GET_CMD | IPI_REPL,
1127 			LIF_CMD, ip_sioctl_get_addr, NULL },
1128 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1129 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1130 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1131 			IPI_GET_CMD | IPI_REPL,
1132 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1133 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1134 			IPI_PRIV | IPI_WR | IPI_REPL,
1135 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1136 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1137 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1138 			LIF_CMD, ip_sioctl_get_flags, NULL },
1139 
1140 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 
1143 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1144 			ip_sioctl_get_lifconf, NULL },
1145 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1146 			LIF_CMD, ip_sioctl_mtu, NULL },
1147 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1148 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1149 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1150 			IPI_GET_CMD | IPI_REPL,
1151 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1152 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1153 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1154 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1155 			IPI_GET_CMD | IPI_REPL,
1156 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1157 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1158 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1159 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1160 			IPI_GET_CMD | IPI_REPL,
1161 			LIF_CMD, ip_sioctl_get_metric, NULL },
1162 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1163 			LIF_CMD, ip_sioctl_metric, NULL },
1164 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1165 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1166 			LIF_CMD, ip_sioctl_slifname,
1167 			ip_sioctl_slifname_restart },
1168 
1169 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1170 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1171 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1172 			IPI_GET_CMD | IPI_REPL,
1173 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1174 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1175 			IPI_PRIV | IPI_WR | IPI_REPL,
1176 			LIF_CMD, ip_sioctl_muxid, NULL },
1177 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1178 			IPI_GET_CMD | IPI_REPL,
1179 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1180 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1181 			IPI_PRIV | IPI_WR | IPI_REPL,
1182 			LIF_CMD, ip_sioctl_slifindex, 0 },
1183 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1184 			LIF_CMD, ip_sioctl_token, NULL },
1185 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1186 			IPI_GET_CMD | IPI_REPL,
1187 			LIF_CMD, ip_sioctl_get_token, NULL },
1188 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1189 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1190 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1191 			IPI_GET_CMD | IPI_REPL,
1192 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1193 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1194 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1195 
1196 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1197 			IPI_GET_CMD | IPI_REPL,
1198 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1199 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1200 			LIF_CMD, ip_siocdelndp_v6, NULL },
1201 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1202 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1203 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1204 			LIF_CMD, ip_siocsetndp_v6, NULL },
1205 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1206 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1207 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1208 			MISC_CMD, ip_sioctl_tonlink, NULL },
1209 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1210 			MISC_CMD, ip_sioctl_tmysite, NULL },
1211 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1212 			TUN_CMD, ip_sioctl_tunparam, NULL },
1213 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1214 			IPI_PRIV | IPI_WR,
1215 			TUN_CMD, ip_sioctl_tunparam, NULL },
1216 
1217 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1218 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1219 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1220 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1221 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1222 
1223 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1224 			IPI_PRIV | IPI_WR | IPI_REPL,
1225 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1226 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1227 			IPI_PRIV | IPI_WR | IPI_REPL,
1228 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1229 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1230 			IPI_PRIV | IPI_WR,
1231 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1232 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1233 			IPI_GET_CMD | IPI_REPL,
1234 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1235 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1236 			IPI_GET_CMD | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1238 
1239 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1240 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1241 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1242 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1243 
1244 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1245 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1246 
1247 	/* These are handled in ip_sioctl_copyin_setup itself */
1248 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1249 			MISC_CMD, NULL, NULL },
1250 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1251 			MISC_CMD, NULL, NULL },
1252 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1253 
1254 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1255 			ip_sioctl_get_lifconf, NULL },
1256 
1257 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1258 			MISC_CMD, ip_sioctl_xarp, NULL },
1259 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1260 			MISC_CMD, ip_sioctl_xarp, NULL },
1261 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1262 			MISC_CMD, ip_sioctl_xarp, NULL },
1263 
1264 	/* SIOCPOPSOCKFS is not handled by IP */
1265 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1266 
1267 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1268 			IPI_GET_CMD | IPI_REPL,
1269 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1270 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1271 			IPI_PRIV | IPI_WR | IPI_REPL,
1272 			LIF_CMD, ip_sioctl_slifzone,
1273 			ip_sioctl_slifzone_restart },
1274 	/* 172-174 are SCTP ioctls and not handled by IP */
1275 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1276 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1277 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1278 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1279 			IPI_GET_CMD, LIF_CMD,
1280 			ip_sioctl_get_lifusesrc, 0 },
1281 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1282 			IPI_PRIV | IPI_WR,
1283 			LIF_CMD, ip_sioctl_slifusesrc,
1284 			NULL },
1285 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1286 			ip_sioctl_get_lifsrcof, NULL },
1287 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1288 			MISC_CMD, ip_sioctl_msfilter, NULL },
1289 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1290 			MISC_CMD, ip_sioctl_msfilter, NULL },
1291 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1292 			MISC_CMD, ip_sioctl_msfilter, NULL },
1293 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1294 			MISC_CMD, ip_sioctl_msfilter, NULL },
1295 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1296 			ip_sioctl_set_ipmpfailback, NULL }
1297 };
1298 
1299 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1300 
1301 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1302 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1303 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1304 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1305 		TUN_CMD, ip_sioctl_tunparam, NULL },
1306 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1307 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1308 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1309 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1310 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1313 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1314 		MISC_CMD, mrt_ioctl},
1315 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1316 		MISC_CMD, mrt_ioctl},
1317 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1318 		MISC_CMD, mrt_ioctl}
1319 };
1320 
1321 int ip_misc_ioctl_count =
1322     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1323 
1324 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1325 					/* Settable in /etc/system */
1326 /* Defined in ip_ire.c */
1327 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1328 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1329 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1330 
1331 static nv_t	ire_nv_arr[] = {
1332 	{ IRE_BROADCAST, "BROADCAST" },
1333 	{ IRE_LOCAL, "LOCAL" },
1334 	{ IRE_LOOPBACK, "LOOPBACK" },
1335 	{ IRE_CACHE, "CACHE" },
1336 	{ IRE_DEFAULT, "DEFAULT" },
1337 	{ IRE_PREFIX, "PREFIX" },
1338 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1339 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1340 	{ IRE_HOST, "HOST" },
1341 	{ 0 }
1342 };
1343 
1344 nv_t	*ire_nv_tbl = ire_nv_arr;
1345 
1346 /* Defined in ip_netinfo.c */
1347 extern ddi_taskq_t	*eventq_queue_nic;
1348 
1349 /* Simple ICMP IP Header Template */
1350 static ipha_t icmp_ipha = {
1351 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1352 };
1353 
1354 struct module_info ip_mod_info = {
1355 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1356 };
1357 
1358 /*
1359  * Duplicate static symbols within a module confuses mdb; so we avoid the
1360  * problem by making the symbols here distinct from those in udp.c.
1361  */
1362 
1363 static struct qinit iprinit = {
1364 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1365 	&ip_mod_info
1366 };
1367 
1368 static struct qinit ipwinit = {
1369 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1370 	&ip_mod_info
1371 };
1372 
1373 static struct qinit iplrinit = {
1374 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1375 	&ip_mod_info
1376 };
1377 
1378 static struct qinit iplwinit = {
1379 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1380 	&ip_mod_info
1381 };
1382 
1383 struct streamtab ipinfo = {
1384 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1385 };
1386 
1387 #ifdef	DEBUG
1388 static boolean_t skip_sctp_cksum = B_FALSE;
1389 #endif
1390 
1391 /*
1392  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1393  * ip_rput_v6(), ip_output(), etc.  If the message
1394  * block already has a M_CTL at the front of it, then simply set the zoneid
1395  * appropriately.
1396  */
1397 mblk_t *
1398 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1399 {
1400 	mblk_t		*first_mp;
1401 	ipsec_out_t	*io;
1402 
1403 	ASSERT(zoneid != ALL_ZONES);
1404 	if (mp->b_datap->db_type == M_CTL) {
1405 		io = (ipsec_out_t *)mp->b_rptr;
1406 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1407 		io->ipsec_out_zoneid = zoneid;
1408 		return (mp);
1409 	}
1410 
1411 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1412 	if (first_mp == NULL)
1413 		return (NULL);
1414 	io = (ipsec_out_t *)first_mp->b_rptr;
1415 	/* This is not a secure packet */
1416 	io->ipsec_out_secure = B_FALSE;
1417 	io->ipsec_out_zoneid = zoneid;
1418 	first_mp->b_cont = mp;
1419 	return (first_mp);
1420 }
1421 
1422 /*
1423  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1424  */
1425 mblk_t *
1426 ip_copymsg(mblk_t *mp)
1427 {
1428 	mblk_t *nmp;
1429 	ipsec_info_t *in;
1430 
1431 	if (mp->b_datap->db_type != M_CTL)
1432 		return (copymsg(mp));
1433 
1434 	in = (ipsec_info_t *)mp->b_rptr;
1435 
1436 	/*
1437 	 * Note that M_CTL is also used for delivering ICMP error messages
1438 	 * upstream to transport layers.
1439 	 */
1440 	if (in->ipsec_info_type != IPSEC_OUT &&
1441 	    in->ipsec_info_type != IPSEC_IN)
1442 		return (copymsg(mp));
1443 
1444 	nmp = copymsg(mp->b_cont);
1445 
1446 	if (in->ipsec_info_type == IPSEC_OUT) {
1447 		return (ipsec_out_tag(mp, nmp,
1448 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1449 	} else {
1450 		return (ipsec_in_tag(mp, nmp,
1451 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1452 	}
1453 }
1454 
1455 /* Generate an ICMP fragmentation needed message. */
1456 static void
1457 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1458     ip_stack_t *ipst)
1459 {
1460 	icmph_t	icmph;
1461 	mblk_t *first_mp;
1462 	boolean_t mctl_present;
1463 
1464 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1465 
1466 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1467 		if (mctl_present)
1468 			freeb(first_mp);
1469 		return;
1470 	}
1471 
1472 	bzero(&icmph, sizeof (icmph_t));
1473 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1474 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1475 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1476 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1477 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1478 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1479 	    ipst);
1480 }
1481 
1482 /*
1483  * icmp_inbound deals with ICMP messages in the following ways.
1484  *
1485  * 1) It needs to send a reply back and possibly delivering it
1486  *    to the "interested" upper clients.
1487  * 2) It needs to send it to the upper clients only.
1488  * 3) It needs to change some values in IP only.
1489  * 4) It needs to change some values in IP and upper layers e.g TCP.
1490  *
1491  * We need to accomodate icmp messages coming in clear until we get
1492  * everything secure from the wire. If icmp_accept_clear_messages
1493  * is zero we check with the global policy and act accordingly. If
1494  * it is non-zero, we accept the message without any checks. But
1495  * *this does not mean* that this will be delivered to the upper
1496  * clients. By accepting we might send replies back, change our MTU
1497  * value etc. but delivery to the ULP/clients depends on their policy
1498  * dispositions.
1499  *
1500  * We handle the above 4 cases in the context of IPSEC in the
1501  * following way :
1502  *
1503  * 1) Send the reply back in the same way as the request came in.
1504  *    If it came in encrypted, it goes out encrypted. If it came in
1505  *    clear, it goes out in clear. Thus, this will prevent chosen
1506  *    plain text attack.
1507  * 2) The client may or may not expect things to come in secure.
1508  *    If it comes in secure, the policy constraints are checked
1509  *    before delivering it to the upper layers. If it comes in
1510  *    clear, ipsec_inbound_accept_clear will decide whether to
1511  *    accept this in clear or not. In both the cases, if the returned
1512  *    message (IP header + 8 bytes) that caused the icmp message has
1513  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1514  *    sending up. If there are only 8 bytes of returned message, then
1515  *    upper client will not be notified.
1516  * 3) Check with global policy to see whether it matches the constaints.
1517  *    But this will be done only if icmp_accept_messages_in_clear is
1518  *    zero.
1519  * 4) If we need to change both in IP and ULP, then the decision taken
1520  *    while affecting the values in IP and while delivering up to TCP
1521  *    should be the same.
1522  *
1523  * 	There are two cases.
1524  *
1525  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1526  *	   failed), we will not deliver it to the ULP, even though they
1527  *	   are *willing* to accept in *clear*. This is fine as our global
1528  *	   disposition to icmp messages asks us reject the datagram.
1529  *
1530  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1531  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1532  *	   to deliver it to ULP (policy failed), it can lead to
1533  *	   consistency problems. The cases known at this time are
1534  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1535  *	   values :
1536  *
1537  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1538  *	     and Upper layer rejects. Then the communication will
1539  *	     come to a stop. This is solved by making similar decisions
1540  *	     at both levels. Currently, when we are unable to deliver
1541  *	     to the Upper Layer (due to policy failures) while IP has
1542  *	     adjusted ire_max_frag, the next outbound datagram would
1543  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1544  *	     will be with the right level of protection. Thus the right
1545  *	     value will be communicated even if we are not able to
1546  *	     communicate when we get from the wire initially. But this
1547  *	     assumes there would be at least one outbound datagram after
1548  *	     IP has adjusted its ire_max_frag value. To make things
1549  *	     simpler, we accept in clear after the validation of
1550  *	     AH/ESP headers.
1551  *
1552  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1553  *	     upper layer depending on the level of protection the upper
1554  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1555  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1556  *	     should be accepted in clear when the Upper layer expects secure.
1557  *	     Thus the communication may get aborted by some bad ICMP
1558  *	     packets.
1559  *
1560  * IPQoS Notes:
1561  * The only instance when a packet is sent for processing is when there
1562  * isn't an ICMP client and if we are interested in it.
1563  * If there is a client, IPPF processing will take place in the
1564  * ip_fanout_proto routine.
1565  *
1566  * Zones notes:
1567  * The packet is only processed in the context of the specified zone: typically
1568  * only this zone will reply to an echo request, and only interested clients in
1569  * this zone will receive a copy of the packet. This means that the caller must
1570  * call icmp_inbound() for each relevant zone.
1571  */
1572 static void
1573 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1574     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1575     ill_t *recv_ill, zoneid_t zoneid)
1576 {
1577 	icmph_t	*icmph;
1578 	ipha_t	*ipha;
1579 	int	iph_hdr_length;
1580 	int	hdr_length;
1581 	boolean_t	interested;
1582 	uint32_t	ts;
1583 	uchar_t	*wptr;
1584 	ipif_t	*ipif;
1585 	mblk_t *first_mp;
1586 	ipsec_in_t *ii;
1587 	ire_t *src_ire;
1588 	boolean_t onlink;
1589 	timestruc_t now;
1590 	uint32_t ill_index;
1591 	ip_stack_t *ipst;
1592 
1593 	ASSERT(ill != NULL);
1594 	ipst = ill->ill_ipst;
1595 
1596 	first_mp = mp;
1597 	if (mctl_present) {
1598 		mp = first_mp->b_cont;
1599 		ASSERT(mp != NULL);
1600 	}
1601 
1602 	ipha = (ipha_t *)mp->b_rptr;
1603 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1604 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1605 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1606 		if (first_mp == NULL)
1607 			return;
1608 	}
1609 
1610 	/*
1611 	 * On a labeled system, we have to check whether the zone itself is
1612 	 * permitted to receive raw traffic.
1613 	 */
1614 	if (is_system_labeled()) {
1615 		if (zoneid == ALL_ZONES)
1616 			zoneid = tsol_packet_to_zoneid(mp);
1617 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1618 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1619 			    zoneid));
1620 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1621 			freemsg(first_mp);
1622 			return;
1623 		}
1624 	}
1625 
1626 	/*
1627 	 * We have accepted the ICMP message. It means that we will
1628 	 * respond to the packet if needed. It may not be delivered
1629 	 * to the upper client depending on the policy constraints
1630 	 * and the disposition in ipsec_inbound_accept_clear.
1631 	 */
1632 
1633 	ASSERT(ill != NULL);
1634 
1635 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1636 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1637 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1638 		/* Last chance to get real. */
1639 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1640 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1641 			freemsg(first_mp);
1642 			return;
1643 		}
1644 		/* Refresh iph following the pullup. */
1645 		ipha = (ipha_t *)mp->b_rptr;
1646 	}
1647 	/* ICMP header checksum, including checksum field, should be zero. */
1648 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1649 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1650 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1651 		freemsg(first_mp);
1652 		return;
1653 	}
1654 	/* The IP header will always be a multiple of four bytes */
1655 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1656 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1657 	    icmph->icmph_code));
1658 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1659 	/* We will set "interested" to "true" if we want a copy */
1660 	interested = B_FALSE;
1661 	switch (icmph->icmph_type) {
1662 	case ICMP_ECHO_REPLY:
1663 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1664 		break;
1665 	case ICMP_DEST_UNREACHABLE:
1666 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1667 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1668 		interested = B_TRUE;	/* Pass up to transport */
1669 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1670 		break;
1671 	case ICMP_SOURCE_QUENCH:
1672 		interested = B_TRUE;	/* Pass up to transport */
1673 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1674 		break;
1675 	case ICMP_REDIRECT:
1676 		if (!ipst->ips_ip_ignore_redirect)
1677 			interested = B_TRUE;
1678 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1679 		break;
1680 	case ICMP_ECHO_REQUEST:
1681 		/*
1682 		 * Whether to respond to echo requests that come in as IP
1683 		 * broadcasts or as IP multicast is subject to debate
1684 		 * (what isn't?).  We aim to please, you pick it.
1685 		 * Default is do it.
1686 		 */
1687 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1688 			/* unicast: always respond */
1689 			interested = B_TRUE;
1690 		} else if (CLASSD(ipha->ipha_dst)) {
1691 			/* multicast: respond based on tunable */
1692 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1693 		} else if (broadcast) {
1694 			/* broadcast: respond based on tunable */
1695 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1696 		}
1697 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1698 		break;
1699 	case ICMP_ROUTER_ADVERTISEMENT:
1700 	case ICMP_ROUTER_SOLICITATION:
1701 		break;
1702 	case ICMP_TIME_EXCEEDED:
1703 		interested = B_TRUE;	/* Pass up to transport */
1704 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1705 		break;
1706 	case ICMP_PARAM_PROBLEM:
1707 		interested = B_TRUE;	/* Pass up to transport */
1708 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1709 		break;
1710 	case ICMP_TIME_STAMP_REQUEST:
1711 		/* Response to Time Stamp Requests is local policy. */
1712 		if (ipst->ips_ip_g_resp_to_timestamp &&
1713 		    /* So is whether to respond if it was an IP broadcast. */
1714 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1715 			int tstamp_len = 3 * sizeof (uint32_t);
1716 
1717 			if (wptr +  tstamp_len > mp->b_wptr) {
1718 				if (!pullupmsg(mp, wptr + tstamp_len -
1719 				    mp->b_rptr)) {
1720 					BUMP_MIB(ill->ill_ip_mib,
1721 					    ipIfStatsInDiscards);
1722 					freemsg(first_mp);
1723 					return;
1724 				}
1725 				/* Refresh ipha following the pullup. */
1726 				ipha = (ipha_t *)mp->b_rptr;
1727 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1728 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1729 			}
1730 			interested = B_TRUE;
1731 		}
1732 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1733 		break;
1734 	case ICMP_TIME_STAMP_REPLY:
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1736 		break;
1737 	case ICMP_INFO_REQUEST:
1738 		/* Per RFC 1122 3.2.2.7, ignore this. */
1739 	case ICMP_INFO_REPLY:
1740 		break;
1741 	case ICMP_ADDRESS_MASK_REQUEST:
1742 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1743 		    !broadcast) &&
1744 		    /* TODO m_pullup of complete header? */
1745 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1746 			interested = B_TRUE;
1747 		}
1748 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1749 		break;
1750 	case ICMP_ADDRESS_MASK_REPLY:
1751 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1752 		break;
1753 	default:
1754 		interested = B_TRUE;	/* Pass up to transport */
1755 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1756 		break;
1757 	}
1758 	/* See if there is an ICMP client. */
1759 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1760 		/* If there is an ICMP client and we want one too, copy it. */
1761 		mblk_t *first_mp1;
1762 
1763 		if (!interested) {
1764 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1765 			    ip_policy, recv_ill, zoneid);
1766 			return;
1767 		}
1768 		first_mp1 = ip_copymsg(first_mp);
1769 		if (first_mp1 != NULL) {
1770 			ip_fanout_proto(q, first_mp1, ill, ipha,
1771 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1772 		}
1773 	} else if (!interested) {
1774 		freemsg(first_mp);
1775 		return;
1776 	} else {
1777 		/*
1778 		 * Initiate policy processing for this packet if ip_policy
1779 		 * is true.
1780 		 */
1781 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1782 			ill_index = ill->ill_phyint->phyint_ifindex;
1783 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1784 			if (mp == NULL) {
1785 				if (mctl_present) {
1786 					freeb(first_mp);
1787 				}
1788 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1789 				return;
1790 			}
1791 		}
1792 	}
1793 	/* We want to do something with it. */
1794 	/* Check db_ref to make sure we can modify the packet. */
1795 	if (mp->b_datap->db_ref > 1) {
1796 		mblk_t	*first_mp1;
1797 
1798 		first_mp1 = ip_copymsg(first_mp);
1799 		freemsg(first_mp);
1800 		if (!first_mp1) {
1801 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1802 			return;
1803 		}
1804 		first_mp = first_mp1;
1805 		if (mctl_present) {
1806 			mp = first_mp->b_cont;
1807 			ASSERT(mp != NULL);
1808 		} else {
1809 			mp = first_mp;
1810 		}
1811 		ipha = (ipha_t *)mp->b_rptr;
1812 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1813 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1814 	}
1815 	switch (icmph->icmph_type) {
1816 	case ICMP_ADDRESS_MASK_REQUEST:
1817 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1818 		if (ipif == NULL) {
1819 			freemsg(first_mp);
1820 			return;
1821 		}
1822 		/*
1823 		 * outging interface must be IPv4
1824 		 */
1825 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1826 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1827 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1828 		ipif_refrele(ipif);
1829 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1830 		break;
1831 	case ICMP_ECHO_REQUEST:
1832 		icmph->icmph_type = ICMP_ECHO_REPLY;
1833 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1834 		break;
1835 	case ICMP_TIME_STAMP_REQUEST: {
1836 		uint32_t *tsp;
1837 
1838 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1839 		tsp = (uint32_t *)wptr;
1840 		tsp++;		/* Skip past 'originate time' */
1841 		/* Compute # of milliseconds since midnight */
1842 		gethrestime(&now);
1843 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1844 		    now.tv_nsec / (NANOSEC / MILLISEC);
1845 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1846 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1847 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1848 		break;
1849 	}
1850 	default:
1851 		ipha = (ipha_t *)&icmph[1];
1852 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1853 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1854 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1855 				freemsg(first_mp);
1856 				return;
1857 			}
1858 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1859 			ipha = (ipha_t *)&icmph[1];
1860 		}
1861 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1862 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1863 			freemsg(first_mp);
1864 			return;
1865 		}
1866 		hdr_length = IPH_HDR_LENGTH(ipha);
1867 		if (hdr_length < sizeof (ipha_t)) {
1868 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1869 			freemsg(first_mp);
1870 			return;
1871 		}
1872 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1873 			if (!pullupmsg(mp,
1874 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1875 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1876 				freemsg(first_mp);
1877 				return;
1878 			}
1879 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1880 			ipha = (ipha_t *)&icmph[1];
1881 		}
1882 		switch (icmph->icmph_type) {
1883 		case ICMP_REDIRECT:
1884 			/*
1885 			 * As there is no upper client to deliver, we don't
1886 			 * need the first_mp any more.
1887 			 */
1888 			if (mctl_present) {
1889 				freeb(first_mp);
1890 			}
1891 			icmp_redirect(ill, mp);
1892 			return;
1893 		case ICMP_DEST_UNREACHABLE:
1894 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1895 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1896 				    zoneid, mp, iph_hdr_length, ipst)) {
1897 					freemsg(first_mp);
1898 					return;
1899 				}
1900 				/*
1901 				 * icmp_inbound_too_big() may alter mp.
1902 				 * Resynch ipha and icmph accordingly.
1903 				 */
1904 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1905 				ipha = (ipha_t *)&icmph[1];
1906 			}
1907 			/* FALLTHRU */
1908 		default :
1909 			/*
1910 			 * IPQoS notes: Since we have already done IPQoS
1911 			 * processing we don't want to do it again in
1912 			 * the fanout routines called by
1913 			 * icmp_inbound_error_fanout, hence the last
1914 			 * argument, ip_policy, is B_FALSE.
1915 			 */
1916 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1917 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1918 			    B_FALSE, recv_ill, zoneid);
1919 		}
1920 		return;
1921 	}
1922 	/* Send out an ICMP packet */
1923 	icmph->icmph_checksum = 0;
1924 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1925 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1926 		ipif_t	*ipif_chosen;
1927 		/*
1928 		 * Make it look like it was directed to us, so we don't look
1929 		 * like a fool with a broadcast or multicast source address.
1930 		 */
1931 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1932 		/*
1933 		 * Make sure that we haven't grabbed an interface that's DOWN.
1934 		 */
1935 		if (ipif != NULL) {
1936 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1937 			    ipha->ipha_src, zoneid);
1938 			if (ipif_chosen != NULL) {
1939 				ipif_refrele(ipif);
1940 				ipif = ipif_chosen;
1941 			}
1942 		}
1943 		if (ipif == NULL) {
1944 			ip0dbg(("icmp_inbound: "
1945 			    "No source for broadcast/multicast:\n"
1946 			    "\tsrc 0x%x dst 0x%x ill %p "
1947 			    "ipif_lcl_addr 0x%x\n",
1948 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1949 			    (void *)ill,
1950 			    ill->ill_ipif->ipif_lcl_addr));
1951 			freemsg(first_mp);
1952 			return;
1953 		}
1954 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1955 		ipha->ipha_dst = ipif->ipif_src_addr;
1956 		ipif_refrele(ipif);
1957 	}
1958 	/* Reset time to live. */
1959 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1960 	{
1961 		/* Swap source and destination addresses */
1962 		ipaddr_t tmp;
1963 
1964 		tmp = ipha->ipha_src;
1965 		ipha->ipha_src = ipha->ipha_dst;
1966 		ipha->ipha_dst = tmp;
1967 	}
1968 	ipha->ipha_ident = 0;
1969 	if (!IS_SIMPLE_IPH(ipha))
1970 		icmp_options_update(ipha);
1971 
1972 	/*
1973 	 * ICMP echo replies should go out on the same interface
1974 	 * the request came on as probes used by in.mpathd for detecting
1975 	 * NIC failures are ECHO packets. We turn-off load spreading
1976 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1977 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1978 	 * function. This is in turn handled by ip_wput and ip_newroute
1979 	 * to make sure that the packet goes out on the interface it came
1980 	 * in on. If we don't turnoff load spreading, the packets might get
1981 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1982 	 * to go out and in.mpathd would wrongly detect a failure or
1983 	 * mis-detect a NIC failure for link failure. As load spreading
1984 	 * can happen only if ill_group is not NULL, we do only for
1985 	 * that case and this does not affect the normal case.
1986 	 *
1987 	 * We turn off load spreading only on echo packets that came from
1988 	 * on-link hosts. If the interface route has been deleted, this will
1989 	 * not be enforced as we can't do much. For off-link hosts, as the
1990 	 * default routes in IPv4 does not typically have an ire_ipif
1991 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
1992 	 * Moreover, expecting a default route through this interface may
1993 	 * not be correct. We use ipha_dst because of the swap above.
1994 	 */
1995 	onlink = B_FALSE;
1996 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
1997 		/*
1998 		 * First, we need to make sure that it is not one of our
1999 		 * local addresses. If we set onlink when it is one of
2000 		 * our local addresses, we will end up creating IRE_CACHES
2001 		 * for one of our local addresses. Then, we will never
2002 		 * accept packets for them afterwards.
2003 		 */
2004 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2005 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2006 		if (src_ire == NULL) {
2007 			ipif = ipif_get_next_ipif(NULL, ill);
2008 			if (ipif == NULL) {
2009 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2010 				freemsg(mp);
2011 				return;
2012 			}
2013 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2014 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2015 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2016 			ipif_refrele(ipif);
2017 			if (src_ire != NULL) {
2018 				onlink = B_TRUE;
2019 				ire_refrele(src_ire);
2020 			}
2021 		} else {
2022 			ire_refrele(src_ire);
2023 		}
2024 	}
2025 	if (!mctl_present) {
2026 		/*
2027 		 * This packet should go out the same way as it
2028 		 * came in i.e in clear. To make sure that global
2029 		 * policy will not be applied to this in ip_wput_ire,
2030 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2031 		 */
2032 		ASSERT(first_mp == mp);
2033 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2034 		if (first_mp == NULL) {
2035 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2036 			freemsg(mp);
2037 			return;
2038 		}
2039 		ii = (ipsec_in_t *)first_mp->b_rptr;
2040 
2041 		/* This is not a secure packet */
2042 		ii->ipsec_in_secure = B_FALSE;
2043 		if (onlink) {
2044 			ii->ipsec_in_attach_if = B_TRUE;
2045 			ii->ipsec_in_ill_index =
2046 			    ill->ill_phyint->phyint_ifindex;
2047 			ii->ipsec_in_rill_index =
2048 			    recv_ill->ill_phyint->phyint_ifindex;
2049 		}
2050 		first_mp->b_cont = mp;
2051 	} else if (onlink) {
2052 		ii = (ipsec_in_t *)first_mp->b_rptr;
2053 		ii->ipsec_in_attach_if = B_TRUE;
2054 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2055 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2056 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2057 	} else {
2058 		ii = (ipsec_in_t *)first_mp->b_rptr;
2059 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2060 	}
2061 	ii->ipsec_in_zoneid = zoneid;
2062 	ASSERT(zoneid != ALL_ZONES);
2063 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2064 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2065 		return;
2066 	}
2067 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2068 	put(WR(q), first_mp);
2069 }
2070 
2071 static ipaddr_t
2072 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2073 {
2074 	conn_t *connp;
2075 	connf_t *connfp;
2076 	ipaddr_t nexthop_addr = INADDR_ANY;
2077 	int hdr_length = IPH_HDR_LENGTH(ipha);
2078 	uint16_t *up;
2079 	uint32_t ports;
2080 	ip_stack_t *ipst = ill->ill_ipst;
2081 
2082 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2083 	switch (ipha->ipha_protocol) {
2084 		case IPPROTO_TCP:
2085 		{
2086 			tcph_t *tcph;
2087 
2088 			/* do a reverse lookup */
2089 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2090 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2091 			    TCPS_LISTEN, ipst);
2092 			break;
2093 		}
2094 		case IPPROTO_UDP:
2095 		{
2096 			uint32_t dstport, srcport;
2097 
2098 			((uint16_t *)&ports)[0] = up[1];
2099 			((uint16_t *)&ports)[1] = up[0];
2100 
2101 			/* Extract ports in net byte order */
2102 			dstport = htons(ntohl(ports) & 0xFFFF);
2103 			srcport = htons(ntohl(ports) >> 16);
2104 
2105 			connfp = &ipst->ips_ipcl_udp_fanout[
2106 			    IPCL_UDP_HASH(dstport, ipst)];
2107 			mutex_enter(&connfp->connf_lock);
2108 			connp = connfp->connf_head;
2109 
2110 			/* do a reverse lookup */
2111 			while ((connp != NULL) &&
2112 			    (!IPCL_UDP_MATCH(connp, dstport,
2113 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2114 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2115 				connp = connp->conn_next;
2116 			}
2117 			if (connp != NULL)
2118 				CONN_INC_REF(connp);
2119 			mutex_exit(&connfp->connf_lock);
2120 			break;
2121 		}
2122 		case IPPROTO_SCTP:
2123 		{
2124 			in6_addr_t map_src, map_dst;
2125 
2126 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2127 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2128 			((uint16_t *)&ports)[0] = up[1];
2129 			((uint16_t *)&ports)[1] = up[0];
2130 
2131 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2132 			    zoneid, ipst->ips_netstack->netstack_sctp);
2133 			if (connp == NULL) {
2134 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2135 				    zoneid, ports, ipha, ipst);
2136 			} else {
2137 				CONN_INC_REF(connp);
2138 				SCTP_REFRELE(CONN2SCTP(connp));
2139 			}
2140 			break;
2141 		}
2142 		default:
2143 		{
2144 			ipha_t ripha;
2145 
2146 			ripha.ipha_src = ipha->ipha_dst;
2147 			ripha.ipha_dst = ipha->ipha_src;
2148 			ripha.ipha_protocol = ipha->ipha_protocol;
2149 
2150 			connfp = &ipst->ips_ipcl_proto_fanout[
2151 			    ipha->ipha_protocol];
2152 			mutex_enter(&connfp->connf_lock);
2153 			connp = connfp->connf_head;
2154 			for (connp = connfp->connf_head; connp != NULL;
2155 			    connp = connp->conn_next) {
2156 				if (IPCL_PROTO_MATCH(connp,
2157 				    ipha->ipha_protocol, &ripha, ill,
2158 				    0, zoneid)) {
2159 					CONN_INC_REF(connp);
2160 					break;
2161 				}
2162 			}
2163 			mutex_exit(&connfp->connf_lock);
2164 		}
2165 	}
2166 	if (connp != NULL) {
2167 		if (connp->conn_nexthop_set)
2168 			nexthop_addr = connp->conn_nexthop_v4;
2169 		CONN_DEC_REF(connp);
2170 	}
2171 	return (nexthop_addr);
2172 }
2173 
2174 /* Table from RFC 1191 */
2175 static int icmp_frag_size_table[] =
2176 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2177 
2178 /*
2179  * Process received ICMP Packet too big.
2180  * After updating any IRE it does the fanout to any matching transport streams.
2181  * Assumes the message has been pulled up till the IP header that caused
2182  * the error.
2183  *
2184  * Returns B_FALSE on failure and B_TRUE on success.
2185  */
2186 static boolean_t
2187 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2188     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2189     ip_stack_t *ipst)
2190 {
2191 	ire_t	*ire, *first_ire;
2192 	int	mtu;
2193 	int	hdr_length;
2194 	ipaddr_t nexthop_addr;
2195 
2196 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2197 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2198 	ASSERT(ill != NULL);
2199 
2200 	hdr_length = IPH_HDR_LENGTH(ipha);
2201 
2202 	/* Drop if the original packet contained a source route */
2203 	if (ip_source_route_included(ipha)) {
2204 		return (B_FALSE);
2205 	}
2206 	/*
2207 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2208 	 * header.
2209 	 */
2210 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2211 	    mp->b_wptr) {
2212 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2213 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2214 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2215 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2216 			return (B_FALSE);
2217 		}
2218 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2219 		ipha = (ipha_t *)&icmph[1];
2220 	}
2221 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2222 	if (nexthop_addr != INADDR_ANY) {
2223 		/* nexthop set */
2224 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2225 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2226 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2227 	} else {
2228 		/* nexthop not set */
2229 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2230 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2231 	}
2232 
2233 	if (!first_ire) {
2234 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2235 		    ntohl(ipha->ipha_dst)));
2236 		return (B_FALSE);
2237 	}
2238 	/* Check for MTU discovery advice as described in RFC 1191 */
2239 	mtu = ntohs(icmph->icmph_du_mtu);
2240 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2241 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2242 	    ire = ire->ire_next) {
2243 		/*
2244 		 * Look for the connection to which this ICMP message is
2245 		 * directed. If it has the IP_NEXTHOP option set, then the
2246 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2247 		 * option. Else the search is limited to regular IREs.
2248 		 */
2249 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2250 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2251 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2252 		    (nexthop_addr != INADDR_ANY)))
2253 			continue;
2254 
2255 		mutex_enter(&ire->ire_lock);
2256 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2257 			/* Reduce the IRE max frag value as advised. */
2258 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2259 			    mtu, ire->ire_max_frag));
2260 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2261 		} else {
2262 			uint32_t length;
2263 			int	i;
2264 
2265 			/*
2266 			 * Use the table from RFC 1191 to figure out
2267 			 * the next "plateau" based on the length in
2268 			 * the original IP packet.
2269 			 */
2270 			length = ntohs(ipha->ipha_length);
2271 			if (ire->ire_max_frag <= length &&
2272 			    ire->ire_max_frag >= length - hdr_length) {
2273 				/*
2274 				 * Handle broken BSD 4.2 systems that
2275 				 * return the wrong iph_length in ICMP
2276 				 * errors.
2277 				 */
2278 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2279 				    length, ire->ire_max_frag));
2280 				length -= hdr_length;
2281 			}
2282 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2283 				if (length > icmp_frag_size_table[i])
2284 					break;
2285 			}
2286 			if (i == A_CNT(icmp_frag_size_table)) {
2287 				/* Smaller than 68! */
2288 				ip1dbg(("Too big for packet size %d\n",
2289 				    length));
2290 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2291 				ire->ire_frag_flag = 0;
2292 			} else {
2293 				mtu = icmp_frag_size_table[i];
2294 				ip1dbg(("Calculated mtu %d, packet size %d, "
2295 				    "before %d", mtu, length,
2296 				    ire->ire_max_frag));
2297 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2298 				ip1dbg((", after %d\n", ire->ire_max_frag));
2299 			}
2300 			/* Record the new max frag size for the ULP. */
2301 			icmph->icmph_du_zero = 0;
2302 			icmph->icmph_du_mtu =
2303 			    htons((uint16_t)ire->ire_max_frag);
2304 		}
2305 		mutex_exit(&ire->ire_lock);
2306 	}
2307 	rw_exit(&first_ire->ire_bucket->irb_lock);
2308 	ire_refrele(first_ire);
2309 	return (B_TRUE);
2310 }
2311 
2312 /*
2313  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2314  * calls this function.
2315  */
2316 static mblk_t *
2317 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2318 {
2319 	ipha_t *ipha;
2320 	icmph_t *icmph;
2321 	ipha_t *in_ipha;
2322 	int length;
2323 
2324 	ASSERT(mp->b_datap->db_type == M_DATA);
2325 
2326 	/*
2327 	 * For Self-encapsulated packets, we added an extra IP header
2328 	 * without the options. Inner IP header is the one from which
2329 	 * the outer IP header was formed. Thus, we need to remove the
2330 	 * outer IP header. To do this, we pullup the whole message
2331 	 * and overlay whatever follows the outer IP header over the
2332 	 * outer IP header.
2333 	 */
2334 
2335 	if (!pullupmsg(mp, -1))
2336 		return (NULL);
2337 
2338 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2339 	ipha = (ipha_t *)&icmph[1];
2340 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2341 
2342 	/*
2343 	 * The length that we want to overlay is following the inner
2344 	 * IP header. Subtracting the IP header + icmp header + outer
2345 	 * IP header's length should give us the length that we want to
2346 	 * overlay.
2347 	 */
2348 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2349 	    hdr_length;
2350 	/*
2351 	 * Overlay whatever follows the inner header over the
2352 	 * outer header.
2353 	 */
2354 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2355 
2356 	/* Set the wptr to account for the outer header */
2357 	mp->b_wptr -= hdr_length;
2358 	return (mp);
2359 }
2360 
2361 /*
2362  * Try to pass the ICMP message upstream in case the ULP cares.
2363  *
2364  * If the packet that caused the ICMP error is secure, we send
2365  * it to AH/ESP to make sure that the attached packet has a
2366  * valid association. ipha in the code below points to the
2367  * IP header of the packet that caused the error.
2368  *
2369  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2370  * in the context of IPSEC. Normally we tell the upper layer
2371  * whenever we send the ire (including ip_bind), the IPSEC header
2372  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2373  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2374  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2375  * same thing. As TCP has the IPSEC options size that needs to be
2376  * adjusted, we just pass the MTU unchanged.
2377  *
2378  * IFN could have been generated locally or by some router.
2379  *
2380  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2381  *	    This happens because IP adjusted its value of MTU on an
2382  *	    earlier IFN message and could not tell the upper layer,
2383  *	    the new adjusted value of MTU e.g. Packet was encrypted
2384  *	    or there was not enough information to fanout to upper
2385  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2386  *	    generates the IFN, where IPSEC processing has *not* been
2387  *	    done.
2388  *
2389  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2390  *	    could have generated this. This happens because ire_max_frag
2391  *	    value in IP was set to a new value, while the IPSEC processing
2392  *	    was being done and after we made the fragmentation check in
2393  *	    ip_wput_ire. Thus on return from IPSEC processing,
2394  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2395  *	    and generates the IFN. As IPSEC processing is over, we fanout
2396  *	    to AH/ESP to remove the header.
2397  *
2398  *	    In both these cases, ipsec_in_loopback will be set indicating
2399  *	    that IFN was generated locally.
2400  *
2401  * ROUTER : IFN could be secure or non-secure.
2402  *
2403  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2404  *	      packet in error has AH/ESP headers to validate the AH/ESP
2405  *	      headers. AH/ESP will verify whether there is a valid SA or
2406  *	      not and send it back. We will fanout again if we have more
2407  *	      data in the packet.
2408  *
2409  *	      If the packet in error does not have AH/ESP, we handle it
2410  *	      like any other case.
2411  *
2412  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2413  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2414  *	      for validation. AH/ESP will verify whether there is a
2415  *	      valid SA or not and send it back. We will fanout again if
2416  *	      we have more data in the packet.
2417  *
2418  *	      If the packet in error does not have AH/ESP, we handle it
2419  *	      like any other case.
2420  */
2421 static void
2422 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2423     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2424     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2425     zoneid_t zoneid)
2426 {
2427 	uint16_t *up;	/* Pointer to ports in ULP header */
2428 	uint32_t ports;	/* reversed ports for fanout */
2429 	ipha_t ripha;	/* With reversed addresses */
2430 	mblk_t *first_mp;
2431 	ipsec_in_t *ii;
2432 	tcph_t	*tcph;
2433 	conn_t	*connp;
2434 	ip_stack_t *ipst;
2435 
2436 	ASSERT(ill != NULL);
2437 
2438 	ASSERT(recv_ill != NULL);
2439 	ipst = recv_ill->ill_ipst;
2440 
2441 	first_mp = mp;
2442 	if (mctl_present) {
2443 		mp = first_mp->b_cont;
2444 		ASSERT(mp != NULL);
2445 
2446 		ii = (ipsec_in_t *)first_mp->b_rptr;
2447 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2448 	} else {
2449 		ii = NULL;
2450 	}
2451 
2452 	switch (ipha->ipha_protocol) {
2453 	case IPPROTO_UDP:
2454 		/*
2455 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2456 		 * transport header.
2457 		 */
2458 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2459 		    mp->b_wptr) {
2460 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2461 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2462 				goto discard_pkt;
2463 			}
2464 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2465 			ipha = (ipha_t *)&icmph[1];
2466 		}
2467 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2468 
2469 		/*
2470 		 * Attempt to find a client stream based on port.
2471 		 * Note that we do a reverse lookup since the header is
2472 		 * in the form we sent it out.
2473 		 * The ripha header is only used for the IP_UDP_MATCH and we
2474 		 * only set the src and dst addresses and protocol.
2475 		 */
2476 		ripha.ipha_src = ipha->ipha_dst;
2477 		ripha.ipha_dst = ipha->ipha_src;
2478 		ripha.ipha_protocol = ipha->ipha_protocol;
2479 		((uint16_t *)&ports)[0] = up[1];
2480 		((uint16_t *)&ports)[1] = up[0];
2481 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2482 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2483 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2484 		    icmph->icmph_type, icmph->icmph_code));
2485 
2486 		/* Have to change db_type after any pullupmsg */
2487 		DB_TYPE(mp) = M_CTL;
2488 
2489 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2490 		    mctl_present, ip_policy, recv_ill, zoneid);
2491 		return;
2492 
2493 	case IPPROTO_TCP:
2494 		/*
2495 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2496 		 * transport header.
2497 		 */
2498 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2499 		    mp->b_wptr) {
2500 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2501 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2502 				goto discard_pkt;
2503 			}
2504 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2505 			ipha = (ipha_t *)&icmph[1];
2506 		}
2507 		/*
2508 		 * Find a TCP client stream for this packet.
2509 		 * Note that we do a reverse lookup since the header is
2510 		 * in the form we sent it out.
2511 		 */
2512 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2513 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2514 		    ipst);
2515 		if (connp == NULL)
2516 			goto discard_pkt;
2517 
2518 		/* Have to change db_type after any pullupmsg */
2519 		DB_TYPE(mp) = M_CTL;
2520 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2521 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2522 		return;
2523 
2524 	case IPPROTO_SCTP:
2525 		/*
2526 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2527 		 * transport header.
2528 		 */
2529 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2530 		    mp->b_wptr) {
2531 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2532 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2533 				goto discard_pkt;
2534 			}
2535 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2536 			ipha = (ipha_t *)&icmph[1];
2537 		}
2538 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2539 		/*
2540 		 * Find a SCTP client stream for this packet.
2541 		 * Note that we do a reverse lookup since the header is
2542 		 * in the form we sent it out.
2543 		 * The ripha header is only used for the matching and we
2544 		 * only set the src and dst addresses, protocol, and version.
2545 		 */
2546 		ripha.ipha_src = ipha->ipha_dst;
2547 		ripha.ipha_dst = ipha->ipha_src;
2548 		ripha.ipha_protocol = ipha->ipha_protocol;
2549 		ripha.ipha_version_and_hdr_length =
2550 		    ipha->ipha_version_and_hdr_length;
2551 		((uint16_t *)&ports)[0] = up[1];
2552 		((uint16_t *)&ports)[1] = up[0];
2553 
2554 		/* Have to change db_type after any pullupmsg */
2555 		DB_TYPE(mp) = M_CTL;
2556 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2557 		    mctl_present, ip_policy, zoneid);
2558 		return;
2559 
2560 	case IPPROTO_ESP:
2561 	case IPPROTO_AH: {
2562 		int ipsec_rc;
2563 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2564 
2565 		/*
2566 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2567 		 * We will re-use the IPSEC_IN if it is already present as
2568 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2569 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2570 		 * one and attach it in the front.
2571 		 */
2572 		if (ii != NULL) {
2573 			/*
2574 			 * ip_fanout_proto_again converts the ICMP errors
2575 			 * that come back from AH/ESP to M_DATA so that
2576 			 * if it is non-AH/ESP and we do a pullupmsg in
2577 			 * this function, it would work. Convert it back
2578 			 * to M_CTL before we send up as this is a ICMP
2579 			 * error. This could have been generated locally or
2580 			 * by some router. Validate the inner IPSEC
2581 			 * headers.
2582 			 *
2583 			 * NOTE : ill_index is used by ip_fanout_proto_again
2584 			 * to locate the ill.
2585 			 */
2586 			ASSERT(ill != NULL);
2587 			ii->ipsec_in_ill_index =
2588 			    ill->ill_phyint->phyint_ifindex;
2589 			ii->ipsec_in_rill_index =
2590 			    recv_ill->ill_phyint->phyint_ifindex;
2591 			DB_TYPE(first_mp->b_cont) = M_CTL;
2592 		} else {
2593 			/*
2594 			 * IPSEC_IN is not present. We attach a ipsec_in
2595 			 * message and send up to IPSEC for validating
2596 			 * and removing the IPSEC headers. Clear
2597 			 * ipsec_in_secure so that when we return
2598 			 * from IPSEC, we don't mistakenly think that this
2599 			 * is a secure packet came from the network.
2600 			 *
2601 			 * NOTE : ill_index is used by ip_fanout_proto_again
2602 			 * to locate the ill.
2603 			 */
2604 			ASSERT(first_mp == mp);
2605 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2606 			if (first_mp == NULL) {
2607 				freemsg(mp);
2608 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2609 				return;
2610 			}
2611 			ii = (ipsec_in_t *)first_mp->b_rptr;
2612 
2613 			/* This is not a secure packet */
2614 			ii->ipsec_in_secure = B_FALSE;
2615 			first_mp->b_cont = mp;
2616 			DB_TYPE(mp) = M_CTL;
2617 			ASSERT(ill != NULL);
2618 			ii->ipsec_in_ill_index =
2619 			    ill->ill_phyint->phyint_ifindex;
2620 			ii->ipsec_in_rill_index =
2621 			    recv_ill->ill_phyint->phyint_ifindex;
2622 		}
2623 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2624 
2625 		if (!ipsec_loaded(ipss)) {
2626 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2627 			return;
2628 		}
2629 
2630 		if (ipha->ipha_protocol == IPPROTO_ESP)
2631 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2632 		else
2633 			ipsec_rc = ipsecah_icmp_error(first_mp);
2634 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2635 			return;
2636 
2637 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2638 		return;
2639 	}
2640 	default:
2641 		/*
2642 		 * The ripha header is only used for the lookup and we
2643 		 * only set the src and dst addresses and protocol.
2644 		 */
2645 		ripha.ipha_src = ipha->ipha_dst;
2646 		ripha.ipha_dst = ipha->ipha_src;
2647 		ripha.ipha_protocol = ipha->ipha_protocol;
2648 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2649 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2650 		    ntohl(ipha->ipha_dst),
2651 		    icmph->icmph_type, icmph->icmph_code));
2652 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2653 			ipha_t *in_ipha;
2654 
2655 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2656 			    mp->b_wptr) {
2657 				if (!pullupmsg(mp, (uchar_t *)ipha +
2658 				    hdr_length + sizeof (ipha_t) -
2659 				    mp->b_rptr)) {
2660 					goto discard_pkt;
2661 				}
2662 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2663 				ipha = (ipha_t *)&icmph[1];
2664 			}
2665 			/*
2666 			 * Caller has verified that length has to be
2667 			 * at least the size of IP header.
2668 			 */
2669 			ASSERT(hdr_length >= sizeof (ipha_t));
2670 			/*
2671 			 * Check the sanity of the inner IP header like
2672 			 * we did for the outer header.
2673 			 */
2674 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2675 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2676 				goto discard_pkt;
2677 			}
2678 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2679 				goto discard_pkt;
2680 			}
2681 			/* Check for Self-encapsulated tunnels */
2682 			if (in_ipha->ipha_src == ipha->ipha_src &&
2683 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2684 
2685 				mp = icmp_inbound_self_encap_error(mp,
2686 				    iph_hdr_length, hdr_length);
2687 				if (mp == NULL)
2688 					goto discard_pkt;
2689 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2690 				ipha = (ipha_t *)&icmph[1];
2691 				hdr_length = IPH_HDR_LENGTH(ipha);
2692 				/*
2693 				 * The packet in error is self-encapsualted.
2694 				 * And we are finding it further encapsulated
2695 				 * which we could not have possibly generated.
2696 				 */
2697 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2698 					goto discard_pkt;
2699 				}
2700 				icmp_inbound_error_fanout(q, ill, first_mp,
2701 				    icmph, ipha, iph_hdr_length, hdr_length,
2702 				    mctl_present, ip_policy, recv_ill, zoneid);
2703 				return;
2704 			}
2705 		}
2706 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2707 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2708 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2709 		    ii != NULL &&
2710 		    ii->ipsec_in_loopback &&
2711 		    ii->ipsec_in_secure) {
2712 			/*
2713 			 * For IP tunnels that get a looped-back
2714 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2715 			 * reported new MTU to take into account the IPsec
2716 			 * headers protecting this configured tunnel.
2717 			 *
2718 			 * This allows the tunnel module (tun.c) to blindly
2719 			 * accept the MTU reported in an ICMP "too big"
2720 			 * message.
2721 			 *
2722 			 * Non-looped back ICMP messages will just be
2723 			 * handled by the security protocols (if needed),
2724 			 * and the first subsequent packet will hit this
2725 			 * path.
2726 			 */
2727 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2728 			    ipsec_in_extra_length(first_mp));
2729 		}
2730 		/* Have to change db_type after any pullupmsg */
2731 		DB_TYPE(mp) = M_CTL;
2732 
2733 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2734 		    ip_policy, recv_ill, zoneid);
2735 		return;
2736 	}
2737 	/* NOTREACHED */
2738 discard_pkt:
2739 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2740 drop_pkt:;
2741 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2742 	freemsg(first_mp);
2743 }
2744 
2745 /*
2746  * Common IP options parser.
2747  *
2748  * Setup routine: fill in *optp with options-parsing state, then
2749  * tail-call ipoptp_next to return the first option.
2750  */
2751 uint8_t
2752 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2753 {
2754 	uint32_t totallen; /* total length of all options */
2755 
2756 	totallen = ipha->ipha_version_and_hdr_length -
2757 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2758 	totallen <<= 2;
2759 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2760 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2761 	optp->ipoptp_flags = 0;
2762 	return (ipoptp_next(optp));
2763 }
2764 
2765 /*
2766  * Common IP options parser: extract next option.
2767  */
2768 uint8_t
2769 ipoptp_next(ipoptp_t *optp)
2770 {
2771 	uint8_t *end = optp->ipoptp_end;
2772 	uint8_t *cur = optp->ipoptp_next;
2773 	uint8_t opt, len, pointer;
2774 
2775 	/*
2776 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2777 	 * has been corrupted.
2778 	 */
2779 	ASSERT(cur <= end);
2780 
2781 	if (cur == end)
2782 		return (IPOPT_EOL);
2783 
2784 	opt = cur[IPOPT_OPTVAL];
2785 
2786 	/*
2787 	 * Skip any NOP options.
2788 	 */
2789 	while (opt == IPOPT_NOP) {
2790 		cur++;
2791 		if (cur == end)
2792 			return (IPOPT_EOL);
2793 		opt = cur[IPOPT_OPTVAL];
2794 	}
2795 
2796 	if (opt == IPOPT_EOL)
2797 		return (IPOPT_EOL);
2798 
2799 	/*
2800 	 * Option requiring a length.
2801 	 */
2802 	if ((cur + 1) >= end) {
2803 		optp->ipoptp_flags |= IPOPTP_ERROR;
2804 		return (IPOPT_EOL);
2805 	}
2806 	len = cur[IPOPT_OLEN];
2807 	if (len < 2) {
2808 		optp->ipoptp_flags |= IPOPTP_ERROR;
2809 		return (IPOPT_EOL);
2810 	}
2811 	optp->ipoptp_cur = cur;
2812 	optp->ipoptp_len = len;
2813 	optp->ipoptp_next = cur + len;
2814 	if (cur + len > end) {
2815 		optp->ipoptp_flags |= IPOPTP_ERROR;
2816 		return (IPOPT_EOL);
2817 	}
2818 
2819 	/*
2820 	 * For the options which require a pointer field, make sure
2821 	 * its there, and make sure it points to either something
2822 	 * inside this option, or the end of the option.
2823 	 */
2824 	switch (opt) {
2825 	case IPOPT_RR:
2826 	case IPOPT_TS:
2827 	case IPOPT_LSRR:
2828 	case IPOPT_SSRR:
2829 		if (len <= IPOPT_OFFSET) {
2830 			optp->ipoptp_flags |= IPOPTP_ERROR;
2831 			return (opt);
2832 		}
2833 		pointer = cur[IPOPT_OFFSET];
2834 		if (pointer - 1 > len) {
2835 			optp->ipoptp_flags |= IPOPTP_ERROR;
2836 			return (opt);
2837 		}
2838 		break;
2839 	}
2840 
2841 	/*
2842 	 * Sanity check the pointer field based on the type of the
2843 	 * option.
2844 	 */
2845 	switch (opt) {
2846 	case IPOPT_RR:
2847 	case IPOPT_SSRR:
2848 	case IPOPT_LSRR:
2849 		if (pointer < IPOPT_MINOFF_SR)
2850 			optp->ipoptp_flags |= IPOPTP_ERROR;
2851 		break;
2852 	case IPOPT_TS:
2853 		if (pointer < IPOPT_MINOFF_IT)
2854 			optp->ipoptp_flags |= IPOPTP_ERROR;
2855 		/*
2856 		 * Note that the Internet Timestamp option also
2857 		 * contains two four bit fields (the Overflow field,
2858 		 * and the Flag field), which follow the pointer
2859 		 * field.  We don't need to check that these fields
2860 		 * fall within the length of the option because this
2861 		 * was implicitely done above.  We've checked that the
2862 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2863 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2864 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2865 		 */
2866 		ASSERT(len > IPOPT_POS_OV_FLG);
2867 		break;
2868 	}
2869 
2870 	return (opt);
2871 }
2872 
2873 /*
2874  * Use the outgoing IP header to create an IP_OPTIONS option the way
2875  * it was passed down from the application.
2876  */
2877 int
2878 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2879 {
2880 	ipoptp_t	opts;
2881 	const uchar_t	*opt;
2882 	uint8_t		optval;
2883 	uint8_t		optlen;
2884 	uint32_t	len = 0;
2885 	uchar_t	*buf1 = buf;
2886 
2887 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2888 	len += IP_ADDR_LEN;
2889 	bzero(buf1, IP_ADDR_LEN);
2890 
2891 	/*
2892 	 * OK to cast away const here, as we don't store through the returned
2893 	 * opts.ipoptp_cur pointer.
2894 	 */
2895 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2896 	    optval != IPOPT_EOL;
2897 	    optval = ipoptp_next(&opts)) {
2898 		int	off;
2899 
2900 		opt = opts.ipoptp_cur;
2901 		optlen = opts.ipoptp_len;
2902 		switch (optval) {
2903 		case IPOPT_SSRR:
2904 		case IPOPT_LSRR:
2905 
2906 			/*
2907 			 * Insert ipha_dst as the first entry in the source
2908 			 * route and move down the entries on step.
2909 			 * The last entry gets placed at buf1.
2910 			 */
2911 			buf[IPOPT_OPTVAL] = optval;
2912 			buf[IPOPT_OLEN] = optlen;
2913 			buf[IPOPT_OFFSET] = optlen;
2914 
2915 			off = optlen - IP_ADDR_LEN;
2916 			if (off < 0) {
2917 				/* No entries in source route */
2918 				break;
2919 			}
2920 			/* Last entry in source route */
2921 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2922 			off -= IP_ADDR_LEN;
2923 
2924 			while (off > 0) {
2925 				bcopy(opt + off,
2926 				    buf + off + IP_ADDR_LEN,
2927 				    IP_ADDR_LEN);
2928 				off -= IP_ADDR_LEN;
2929 			}
2930 			/* ipha_dst into first slot */
2931 			bcopy(&ipha->ipha_dst,
2932 			    buf + off + IP_ADDR_LEN,
2933 			    IP_ADDR_LEN);
2934 			buf += optlen;
2935 			len += optlen;
2936 			break;
2937 
2938 		case IPOPT_COMSEC:
2939 		case IPOPT_SECURITY:
2940 			/* if passing up a label is not ok, then remove */
2941 			if (is_system_labeled())
2942 				break;
2943 			/* FALLTHROUGH */
2944 		default:
2945 			bcopy(opt, buf, optlen);
2946 			buf += optlen;
2947 			len += optlen;
2948 			break;
2949 		}
2950 	}
2951 done:
2952 	/* Pad the resulting options */
2953 	while (len & 0x3) {
2954 		*buf++ = IPOPT_EOL;
2955 		len++;
2956 	}
2957 	return (len);
2958 }
2959 
2960 /*
2961  * Update any record route or timestamp options to include this host.
2962  * Reverse any source route option.
2963  * This routine assumes that the options are well formed i.e. that they
2964  * have already been checked.
2965  */
2966 static void
2967 icmp_options_update(ipha_t *ipha)
2968 {
2969 	ipoptp_t	opts;
2970 	uchar_t		*opt;
2971 	uint8_t		optval;
2972 	ipaddr_t	src;		/* Our local address */
2973 	ipaddr_t	dst;
2974 
2975 	ip2dbg(("icmp_options_update\n"));
2976 	src = ipha->ipha_src;
2977 	dst = ipha->ipha_dst;
2978 
2979 	for (optval = ipoptp_first(&opts, ipha);
2980 	    optval != IPOPT_EOL;
2981 	    optval = ipoptp_next(&opts)) {
2982 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2983 		opt = opts.ipoptp_cur;
2984 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2985 		    optval, opts.ipoptp_len));
2986 		switch (optval) {
2987 			int off1, off2;
2988 		case IPOPT_SSRR:
2989 		case IPOPT_LSRR:
2990 			/*
2991 			 * Reverse the source route.  The first entry
2992 			 * should be the next to last one in the current
2993 			 * source route (the last entry is our address).
2994 			 * The last entry should be the final destination.
2995 			 */
2996 			off1 = IPOPT_MINOFF_SR - 1;
2997 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2998 			if (off2 < 0) {
2999 				/* No entries in source route */
3000 				ip1dbg((
3001 				    "icmp_options_update: bad src route\n"));
3002 				break;
3003 			}
3004 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3005 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3006 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3007 			off2 -= IP_ADDR_LEN;
3008 
3009 			while (off1 < off2) {
3010 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3011 				bcopy((char *)opt + off2, (char *)opt + off1,
3012 				    IP_ADDR_LEN);
3013 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3014 				off1 += IP_ADDR_LEN;
3015 				off2 -= IP_ADDR_LEN;
3016 			}
3017 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3018 			break;
3019 		}
3020 	}
3021 }
3022 
3023 /*
3024  * Process received ICMP Redirect messages.
3025  */
3026 static void
3027 icmp_redirect(ill_t *ill, mblk_t *mp)
3028 {
3029 	ipha_t	*ipha;
3030 	int	iph_hdr_length;
3031 	icmph_t	*icmph;
3032 	ipha_t	*ipha_err;
3033 	ire_t	*ire;
3034 	ire_t	*prev_ire;
3035 	ire_t	*save_ire;
3036 	ipaddr_t  src, dst, gateway;
3037 	iulp_t	ulp_info = { 0 };
3038 	int	error;
3039 	ip_stack_t *ipst;
3040 
3041 	ASSERT(ill != NULL);
3042 	ipst = ill->ill_ipst;
3043 
3044 	ipha = (ipha_t *)mp->b_rptr;
3045 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3046 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3047 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3048 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3049 		freemsg(mp);
3050 		return;
3051 	}
3052 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3053 	ipha_err = (ipha_t *)&icmph[1];
3054 	src = ipha->ipha_src;
3055 	dst = ipha_err->ipha_dst;
3056 	gateway = icmph->icmph_rd_gateway;
3057 	/* Make sure the new gateway is reachable somehow. */
3058 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3059 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3060 	/*
3061 	 * Make sure we had a route for the dest in question and that
3062 	 * that route was pointing to the old gateway (the source of the
3063 	 * redirect packet.)
3064 	 */
3065 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3066 	    NULL, MATCH_IRE_GW, ipst);
3067 	/*
3068 	 * Check that
3069 	 *	the redirect was not from ourselves
3070 	 *	the new gateway and the old gateway are directly reachable
3071 	 */
3072 	if (!prev_ire ||
3073 	    !ire ||
3074 	    ire->ire_type == IRE_LOCAL) {
3075 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3076 		freemsg(mp);
3077 		if (ire != NULL)
3078 			ire_refrele(ire);
3079 		if (prev_ire != NULL)
3080 			ire_refrele(prev_ire);
3081 		return;
3082 	}
3083 
3084 	/*
3085 	 * Should we use the old ULP info to create the new gateway?  From
3086 	 * a user's perspective, we should inherit the info so that it
3087 	 * is a "smooth" transition.  If we do not do that, then new
3088 	 * connections going thru the new gateway will have no route metrics,
3089 	 * which is counter-intuitive to user.  From a network point of
3090 	 * view, this may or may not make sense even though the new gateway
3091 	 * is still directly connected to us so the route metrics should not
3092 	 * change much.
3093 	 *
3094 	 * But if the old ire_uinfo is not initialized, we do another
3095 	 * recursive lookup on the dest using the new gateway.  There may
3096 	 * be a route to that.  If so, use it to initialize the redirect
3097 	 * route.
3098 	 */
3099 	if (prev_ire->ire_uinfo.iulp_set) {
3100 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3101 	} else {
3102 		ire_t *tmp_ire;
3103 		ire_t *sire;
3104 
3105 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3106 		    ALL_ZONES, 0, NULL,
3107 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3108 		    ipst);
3109 		if (sire != NULL) {
3110 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3111 			/*
3112 			 * If sire != NULL, ire_ftable_lookup() should not
3113 			 * return a NULL value.
3114 			 */
3115 			ASSERT(tmp_ire != NULL);
3116 			ire_refrele(tmp_ire);
3117 			ire_refrele(sire);
3118 		} else if (tmp_ire != NULL) {
3119 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3120 			    sizeof (iulp_t));
3121 			ire_refrele(tmp_ire);
3122 		}
3123 	}
3124 	if (prev_ire->ire_type == IRE_CACHE)
3125 		ire_delete(prev_ire);
3126 	ire_refrele(prev_ire);
3127 	/*
3128 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3129 	 * require TOS routing
3130 	 */
3131 	switch (icmph->icmph_code) {
3132 	case 0:
3133 	case 1:
3134 		/* TODO: TOS specificity for cases 2 and 3 */
3135 	case 2:
3136 	case 3:
3137 		break;
3138 	default:
3139 		freemsg(mp);
3140 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3141 		ire_refrele(ire);
3142 		return;
3143 	}
3144 	/*
3145 	 * Create a Route Association.  This will allow us to remember that
3146 	 * someone we believe told us to use the particular gateway.
3147 	 */
3148 	save_ire = ire;
3149 	ire = ire_create(
3150 	    (uchar_t *)&dst,			/* dest addr */
3151 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3152 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3153 	    (uchar_t *)&gateway,		/* gateway addr */
3154 	    &save_ire->ire_max_frag,		/* max frag */
3155 	    NULL,				/* no src nce */
3156 	    NULL,				/* no rfq */
3157 	    NULL,				/* no stq */
3158 	    IRE_HOST,
3159 	    NULL,				/* ipif */
3160 	    0,					/* cmask */
3161 	    0,					/* phandle */
3162 	    0,					/* ihandle */
3163 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3164 	    &ulp_info,
3165 	    NULL,				/* tsol_gc_t */
3166 	    NULL,				/* gcgrp */
3167 	    ipst);
3168 
3169 	if (ire == NULL) {
3170 		freemsg(mp);
3171 		ire_refrele(save_ire);
3172 		return;
3173 	}
3174 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3175 	ire_refrele(save_ire);
3176 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3177 
3178 	if (error == 0) {
3179 		ire_refrele(ire);		/* Held in ire_add_v4 */
3180 		/* tell routing sockets that we received a redirect */
3181 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3182 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3183 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3184 	}
3185 
3186 	/*
3187 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3188 	 * This together with the added IRE has the effect of
3189 	 * modifying an existing redirect.
3190 	 */
3191 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3192 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3193 	if (prev_ire != NULL) {
3194 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3195 			ire_delete(prev_ire);
3196 		ire_refrele(prev_ire);
3197 	}
3198 
3199 	freemsg(mp);
3200 }
3201 
3202 /*
3203  * Generate an ICMP parameter problem message.
3204  */
3205 static void
3206 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3207 	ip_stack_t *ipst)
3208 {
3209 	icmph_t	icmph;
3210 	boolean_t mctl_present;
3211 	mblk_t *first_mp;
3212 
3213 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3214 
3215 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3216 		if (mctl_present)
3217 			freeb(first_mp);
3218 		return;
3219 	}
3220 
3221 	bzero(&icmph, sizeof (icmph_t));
3222 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3223 	icmph.icmph_pp_ptr = ptr;
3224 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3225 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3226 	    ipst);
3227 }
3228 
3229 /*
3230  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3231  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3232  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3233  * an icmp error packet can be sent.
3234  * Assigns an appropriate source address to the packet. If ipha_dst is
3235  * one of our addresses use it for source. Otherwise pick a source based
3236  * on a route lookup back to ipha_src.
3237  * Note that ipha_src must be set here since the
3238  * packet is likely to arrive on an ill queue in ip_wput() which will
3239  * not set a source address.
3240  */
3241 static void
3242 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3243     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3244 {
3245 	ipaddr_t dst;
3246 	icmph_t	*icmph;
3247 	ipha_t	*ipha;
3248 	uint_t	len_needed;
3249 	size_t	msg_len;
3250 	mblk_t	*mp1;
3251 	ipaddr_t src;
3252 	ire_t	*ire;
3253 	mblk_t *ipsec_mp;
3254 	ipsec_out_t	*io = NULL;
3255 
3256 	if (mctl_present) {
3257 		/*
3258 		 * If it is :
3259 		 *
3260 		 * 1) a IPSEC_OUT, then this is caused by outbound
3261 		 *    datagram originating on this host. IPSEC processing
3262 		 *    may or may not have been done. Refer to comments above
3263 		 *    icmp_inbound_error_fanout for details.
3264 		 *
3265 		 * 2) a IPSEC_IN if we are generating a icmp_message
3266 		 *    for an incoming datagram destined for us i.e called
3267 		 *    from ip_fanout_send_icmp.
3268 		 */
3269 		ipsec_info_t *in;
3270 		ipsec_mp = mp;
3271 		mp = ipsec_mp->b_cont;
3272 
3273 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3274 		ipha = (ipha_t *)mp->b_rptr;
3275 
3276 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3277 		    in->ipsec_info_type == IPSEC_IN);
3278 
3279 		if (in->ipsec_info_type == IPSEC_IN) {
3280 			/*
3281 			 * Convert the IPSEC_IN to IPSEC_OUT.
3282 			 */
3283 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3284 				BUMP_MIB(&ipst->ips_ip_mib,
3285 				    ipIfStatsOutDiscards);
3286 				return;
3287 			}
3288 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3289 		} else {
3290 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3291 			io = (ipsec_out_t *)in;
3292 			/*
3293 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3294 			 * ire lookup.
3295 			 */
3296 			io->ipsec_out_proc_begin = B_FALSE;
3297 		}
3298 		ASSERT(zoneid == io->ipsec_out_zoneid);
3299 		ASSERT(zoneid != ALL_ZONES);
3300 	} else {
3301 		/*
3302 		 * This is in clear. The icmp message we are building
3303 		 * here should go out in clear.
3304 		 *
3305 		 * Pardon the convolution of it all, but it's easier to
3306 		 * allocate a "use cleartext" IPSEC_IN message and convert
3307 		 * it than it is to allocate a new one.
3308 		 */
3309 		ipsec_in_t *ii;
3310 		ASSERT(DB_TYPE(mp) == M_DATA);
3311 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3312 		if (ipsec_mp == NULL) {
3313 			freemsg(mp);
3314 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3315 			return;
3316 		}
3317 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3318 
3319 		/* This is not a secure packet */
3320 		ii->ipsec_in_secure = B_FALSE;
3321 		/*
3322 		 * For trusted extensions using a shared IP address we can
3323 		 * send using any zoneid.
3324 		 */
3325 		if (zoneid == ALL_ZONES)
3326 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3327 		else
3328 			ii->ipsec_in_zoneid = zoneid;
3329 		ipsec_mp->b_cont = mp;
3330 		ipha = (ipha_t *)mp->b_rptr;
3331 		/*
3332 		 * Convert the IPSEC_IN to IPSEC_OUT.
3333 		 */
3334 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3335 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3336 			return;
3337 		}
3338 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3339 	}
3340 
3341 	/* Remember our eventual destination */
3342 	dst = ipha->ipha_src;
3343 
3344 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3345 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3346 	if (ire != NULL &&
3347 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3348 		src = ipha->ipha_dst;
3349 	} else {
3350 		if (ire != NULL)
3351 			ire_refrele(ire);
3352 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3353 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3354 		    ipst);
3355 		if (ire == NULL) {
3356 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3357 			freemsg(ipsec_mp);
3358 			return;
3359 		}
3360 		src = ire->ire_src_addr;
3361 	}
3362 
3363 	if (ire != NULL)
3364 		ire_refrele(ire);
3365 
3366 	/*
3367 	 * Check if we can send back more then 8 bytes in addition to
3368 	 * the IP header.  We try to send 64 bytes of data and the internal
3369 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3370 	 */
3371 	len_needed = IPH_HDR_LENGTH(ipha);
3372 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3373 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3374 
3375 		if (!pullupmsg(mp, -1)) {
3376 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3377 			freemsg(ipsec_mp);
3378 			return;
3379 		}
3380 		ipha = (ipha_t *)mp->b_rptr;
3381 
3382 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3383 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3384 			    len_needed));
3385 		} else {
3386 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3387 
3388 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3389 			len_needed += ip_hdr_length_v6(mp, ip6h);
3390 		}
3391 	}
3392 	len_needed += ipst->ips_ip_icmp_return;
3393 	msg_len = msgdsize(mp);
3394 	if (msg_len > len_needed) {
3395 		(void) adjmsg(mp, len_needed - msg_len);
3396 		msg_len = len_needed;
3397 	}
3398 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3399 	if (mp1 == NULL) {
3400 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3401 		freemsg(ipsec_mp);
3402 		return;
3403 	}
3404 	mp1->b_cont = mp;
3405 	mp = mp1;
3406 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3407 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3408 	    io->ipsec_out_type == IPSEC_OUT);
3409 	ipsec_mp->b_cont = mp;
3410 
3411 	/*
3412 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3413 	 * node generates be accepted in peace by all on-host destinations.
3414 	 * If we do NOT assume that all on-host destinations trust
3415 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3416 	 * (Look for ipsec_out_icmp_loopback).
3417 	 */
3418 	io->ipsec_out_icmp_loopback = B_TRUE;
3419 
3420 	ipha = (ipha_t *)mp->b_rptr;
3421 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3422 	*ipha = icmp_ipha;
3423 	ipha->ipha_src = src;
3424 	ipha->ipha_dst = dst;
3425 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3426 	msg_len += sizeof (icmp_ipha) + len;
3427 	if (msg_len > IP_MAXPACKET) {
3428 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3429 		msg_len = IP_MAXPACKET;
3430 	}
3431 	ipha->ipha_length = htons((uint16_t)msg_len);
3432 	icmph = (icmph_t *)&ipha[1];
3433 	bcopy(stuff, icmph, len);
3434 	icmph->icmph_checksum = 0;
3435 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3436 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3437 	put(q, ipsec_mp);
3438 }
3439 
3440 /*
3441  * Determine if an ICMP error packet can be sent given the rate limit.
3442  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3443  * in milliseconds) and a burst size. Burst size number of packets can
3444  * be sent arbitrarely closely spaced.
3445  * The state is tracked using two variables to implement an approximate
3446  * token bucket filter:
3447  *	icmp_pkt_err_last - lbolt value when the last burst started
3448  *	icmp_pkt_err_sent - number of packets sent in current burst
3449  */
3450 boolean_t
3451 icmp_err_rate_limit(ip_stack_t *ipst)
3452 {
3453 	clock_t now = TICK_TO_MSEC(lbolt);
3454 	uint_t refilled; /* Number of packets refilled in tbf since last */
3455 	/* Guard against changes by loading into local variable */
3456 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3457 
3458 	if (err_interval == 0)
3459 		return (B_FALSE);
3460 
3461 	if (ipst->ips_icmp_pkt_err_last > now) {
3462 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3463 		ipst->ips_icmp_pkt_err_last = 0;
3464 		ipst->ips_icmp_pkt_err_sent = 0;
3465 	}
3466 	/*
3467 	 * If we are in a burst update the token bucket filter.
3468 	 * Update the "last" time to be close to "now" but make sure
3469 	 * we don't loose precision.
3470 	 */
3471 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3472 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3473 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3474 			ipst->ips_icmp_pkt_err_sent = 0;
3475 		} else {
3476 			ipst->ips_icmp_pkt_err_sent -= refilled;
3477 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3478 		}
3479 	}
3480 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3481 		/* Start of new burst */
3482 		ipst->ips_icmp_pkt_err_last = now;
3483 	}
3484 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3485 		ipst->ips_icmp_pkt_err_sent++;
3486 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3487 		    ipst->ips_icmp_pkt_err_sent));
3488 		return (B_FALSE);
3489 	}
3490 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3491 	return (B_TRUE);
3492 }
3493 
3494 /*
3495  * Check if it is ok to send an IPv4 ICMP error packet in
3496  * response to the IPv4 packet in mp.
3497  * Free the message and return null if no
3498  * ICMP error packet should be sent.
3499  */
3500 static mblk_t *
3501 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3502 {
3503 	icmph_t	*icmph;
3504 	ipha_t	*ipha;
3505 	uint_t	len_needed;
3506 	ire_t	*src_ire;
3507 	ire_t	*dst_ire;
3508 
3509 	if (!mp)
3510 		return (NULL);
3511 	ipha = (ipha_t *)mp->b_rptr;
3512 	if (ip_csum_hdr(ipha)) {
3513 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3514 		freemsg(mp);
3515 		return (NULL);
3516 	}
3517 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3518 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3519 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3520 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3521 	if (src_ire != NULL || dst_ire != NULL ||
3522 	    CLASSD(ipha->ipha_dst) ||
3523 	    CLASSD(ipha->ipha_src) ||
3524 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3525 		/* Note: only errors to the fragment with offset 0 */
3526 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3527 		freemsg(mp);
3528 		if (src_ire != NULL)
3529 			ire_refrele(src_ire);
3530 		if (dst_ire != NULL)
3531 			ire_refrele(dst_ire);
3532 		return (NULL);
3533 	}
3534 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3535 		/*
3536 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3537 		 * errors in response to any ICMP errors.
3538 		 */
3539 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3540 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3541 			if (!pullupmsg(mp, len_needed)) {
3542 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3543 				freemsg(mp);
3544 				return (NULL);
3545 			}
3546 			ipha = (ipha_t *)mp->b_rptr;
3547 		}
3548 		icmph = (icmph_t *)
3549 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3550 		switch (icmph->icmph_type) {
3551 		case ICMP_DEST_UNREACHABLE:
3552 		case ICMP_SOURCE_QUENCH:
3553 		case ICMP_TIME_EXCEEDED:
3554 		case ICMP_PARAM_PROBLEM:
3555 		case ICMP_REDIRECT:
3556 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3557 			freemsg(mp);
3558 			return (NULL);
3559 		default:
3560 			break;
3561 		}
3562 	}
3563 	/*
3564 	 * If this is a labeled system, then check to see if we're allowed to
3565 	 * send a response to this particular sender.  If not, then just drop.
3566 	 */
3567 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3568 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3569 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3570 		freemsg(mp);
3571 		return (NULL);
3572 	}
3573 	if (icmp_err_rate_limit(ipst)) {
3574 		/*
3575 		 * Only send ICMP error packets every so often.
3576 		 * This should be done on a per port/source basis,
3577 		 * but for now this will suffice.
3578 		 */
3579 		freemsg(mp);
3580 		return (NULL);
3581 	}
3582 	return (mp);
3583 }
3584 
3585 /*
3586  * Generate an ICMP redirect message.
3587  */
3588 static void
3589 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3590 {
3591 	icmph_t	icmph;
3592 
3593 	/*
3594 	 * We are called from ip_rput where we could
3595 	 * not have attached an IPSEC_IN.
3596 	 */
3597 	ASSERT(mp->b_datap->db_type == M_DATA);
3598 
3599 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3600 		return;
3601 	}
3602 
3603 	bzero(&icmph, sizeof (icmph_t));
3604 	icmph.icmph_type = ICMP_REDIRECT;
3605 	icmph.icmph_code = 1;
3606 	icmph.icmph_rd_gateway = gateway;
3607 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3608 	/* Redirects sent by router, and router is global zone */
3609 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3610 }
3611 
3612 /*
3613  * Generate an ICMP time exceeded message.
3614  */
3615 void
3616 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3617     ip_stack_t *ipst)
3618 {
3619 	icmph_t	icmph;
3620 	boolean_t mctl_present;
3621 	mblk_t *first_mp;
3622 
3623 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3624 
3625 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3626 		if (mctl_present)
3627 			freeb(first_mp);
3628 		return;
3629 	}
3630 
3631 	bzero(&icmph, sizeof (icmph_t));
3632 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3633 	icmph.icmph_code = code;
3634 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3635 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3636 	    ipst);
3637 }
3638 
3639 /*
3640  * Generate an ICMP unreachable message.
3641  */
3642 void
3643 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3644     ip_stack_t *ipst)
3645 {
3646 	icmph_t	icmph;
3647 	mblk_t *first_mp;
3648 	boolean_t mctl_present;
3649 
3650 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3651 
3652 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3653 		if (mctl_present)
3654 			freeb(first_mp);
3655 		return;
3656 	}
3657 
3658 	bzero(&icmph, sizeof (icmph_t));
3659 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3660 	icmph.icmph_code = code;
3661 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3662 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3663 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3664 	    zoneid, ipst);
3665 }
3666 
3667 /*
3668  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3669  * duplicate.  As long as someone else holds the address, the interface will
3670  * stay down.  When that conflict goes away, the interface is brought back up.
3671  * This is done so that accidental shutdowns of addresses aren't made
3672  * permanent.  Your server will recover from a failure.
3673  *
3674  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3675  * user space process (dhcpagent).
3676  *
3677  * Recovery completes if ARP reports that the address is now ours (via
3678  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3679  *
3680  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3681  */
3682 static void
3683 ipif_dup_recovery(void *arg)
3684 {
3685 	ipif_t *ipif = arg;
3686 	ill_t *ill = ipif->ipif_ill;
3687 	mblk_t *arp_add_mp;
3688 	mblk_t *arp_del_mp;
3689 	area_t *area;
3690 	ip_stack_t *ipst = ill->ill_ipst;
3691 
3692 	ipif->ipif_recovery_id = 0;
3693 
3694 	/*
3695 	 * No lock needed for moving or condemned check, as this is just an
3696 	 * optimization.
3697 	 */
3698 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3699 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3700 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3701 		/* No reason to try to bring this address back. */
3702 		return;
3703 	}
3704 
3705 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3706 		goto alloc_fail;
3707 
3708 	if (ipif->ipif_arp_del_mp == NULL) {
3709 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3710 			goto alloc_fail;
3711 		ipif->ipif_arp_del_mp = arp_del_mp;
3712 	}
3713 
3714 	/* Setting the 'unverified' flag restarts DAD */
3715 	area = (area_t *)arp_add_mp->b_rptr;
3716 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3717 	    ACE_F_UNVERIFIED;
3718 	putnext(ill->ill_rq, arp_add_mp);
3719 	return;
3720 
3721 alloc_fail:
3722 	/*
3723 	 * On allocation failure, just restart the timer.  Note that the ipif
3724 	 * is down here, so no other thread could be trying to start a recovery
3725 	 * timer.  The ill_lock protects the condemned flag and the recovery
3726 	 * timer ID.
3727 	 */
3728 	freemsg(arp_add_mp);
3729 	mutex_enter(&ill->ill_lock);
3730 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3731 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3732 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3733 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3734 	}
3735 	mutex_exit(&ill->ill_lock);
3736 }
3737 
3738 /*
3739  * This is for exclusive changes due to ARP.  Either tear down an interface due
3740  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3741  */
3742 /* ARGSUSED */
3743 static void
3744 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3745 {
3746 	ill_t	*ill = rq->q_ptr;
3747 	arh_t *arh;
3748 	ipaddr_t src;
3749 	ipif_t	*ipif;
3750 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3751 	char hbuf[MAC_STR_LEN];
3752 	char sbuf[INET_ADDRSTRLEN];
3753 	const char *failtype;
3754 	boolean_t bring_up;
3755 	ip_stack_t *ipst = ill->ill_ipst;
3756 
3757 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3758 	case AR_CN_READY:
3759 		failtype = NULL;
3760 		bring_up = B_TRUE;
3761 		break;
3762 	case AR_CN_FAILED:
3763 		failtype = "in use";
3764 		bring_up = B_FALSE;
3765 		break;
3766 	default:
3767 		failtype = "claimed";
3768 		bring_up = B_FALSE;
3769 		break;
3770 	}
3771 
3772 	arh = (arh_t *)mp->b_cont->b_rptr;
3773 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3774 
3775 	/* Handle failures due to probes */
3776 	if (src == 0) {
3777 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3778 		    IP_ADDR_LEN);
3779 	}
3780 
3781 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3782 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3783 	    sizeof (hbuf));
3784 	(void) ip_dot_addr(src, sbuf);
3785 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3786 
3787 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3788 		    ipif->ipif_lcl_addr != src) {
3789 			continue;
3790 		}
3791 
3792 		/*
3793 		 * If we failed on a recovery probe, then restart the timer to
3794 		 * try again later.
3795 		 */
3796 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3797 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3798 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3799 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3800 		    ipst->ips_ip_dup_recovery > 0 &&
3801 		    ipif->ipif_recovery_id == 0) {
3802 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3803 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3804 			continue;
3805 		}
3806 
3807 		/*
3808 		 * If what we're trying to do has already been done, then do
3809 		 * nothing.
3810 		 */
3811 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3812 			continue;
3813 
3814 		if (ipif->ipif_id != 0) {
3815 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3816 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3817 			    ipif->ipif_id);
3818 		}
3819 		if (failtype == NULL) {
3820 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3821 			    ibuf);
3822 		} else {
3823 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3824 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3825 		}
3826 
3827 		if (bring_up) {
3828 			ASSERT(ill->ill_dl_up);
3829 			/*
3830 			 * Free up the ARP delete message so we can allocate
3831 			 * a fresh one through the normal path.
3832 			 */
3833 			freemsg(ipif->ipif_arp_del_mp);
3834 			ipif->ipif_arp_del_mp = NULL;
3835 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3836 			    EINPROGRESS) {
3837 				ipif->ipif_addr_ready = 1;
3838 				(void) ipif_up_done(ipif);
3839 			}
3840 			continue;
3841 		}
3842 
3843 		mutex_enter(&ill->ill_lock);
3844 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3845 		ipif->ipif_flags |= IPIF_DUPLICATE;
3846 		ill->ill_ipif_dup_count++;
3847 		mutex_exit(&ill->ill_lock);
3848 		/*
3849 		 * Already exclusive on the ill; no need to handle deferred
3850 		 * processing here.
3851 		 */
3852 		(void) ipif_down(ipif, NULL, NULL);
3853 		ipif_down_tail(ipif);
3854 		mutex_enter(&ill->ill_lock);
3855 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3856 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3857 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3858 		    ipst->ips_ip_dup_recovery > 0) {
3859 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3860 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3861 		}
3862 		mutex_exit(&ill->ill_lock);
3863 	}
3864 	freemsg(mp);
3865 }
3866 
3867 /* ARGSUSED */
3868 static void
3869 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3870 {
3871 	ill_t	*ill = rq->q_ptr;
3872 	arh_t *arh;
3873 	ipaddr_t src;
3874 	ipif_t	*ipif;
3875 
3876 	arh = (arh_t *)mp->b_cont->b_rptr;
3877 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3878 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3879 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3880 			(void) ipif_resolver_up(ipif, Res_act_defend);
3881 	}
3882 	freemsg(mp);
3883 }
3884 
3885 /*
3886  * News from ARP.  ARP sends notification of interesting events down
3887  * to its clients using M_CTL messages with the interesting ARP packet
3888  * attached via b_cont.
3889  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3890  * queue as opposed to ARP sending the message to all the clients, i.e. all
3891  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3892  * table if a cache IRE is found to delete all the entries for the address in
3893  * the packet.
3894  */
3895 static void
3896 ip_arp_news(queue_t *q, mblk_t *mp)
3897 {
3898 	arcn_t		*arcn;
3899 	arh_t		*arh;
3900 	ire_t		*ire = NULL;
3901 	char		hbuf[MAC_STR_LEN];
3902 	char		sbuf[INET_ADDRSTRLEN];
3903 	ipaddr_t	src;
3904 	in6_addr_t	v6src;
3905 	boolean_t	isv6 = B_FALSE;
3906 	ipif_t		*ipif;
3907 	ill_t		*ill;
3908 	ip_stack_t	*ipst;
3909 
3910 	if (CONN_Q(q)) {
3911 		conn_t *connp = Q_TO_CONN(q);
3912 
3913 		ipst = connp->conn_netstack->netstack_ip;
3914 	} else {
3915 		ill_t *ill = (ill_t *)q->q_ptr;
3916 
3917 		ipst = ill->ill_ipst;
3918 	}
3919 
3920 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3921 		if (q->q_next) {
3922 			putnext(q, mp);
3923 		} else
3924 			freemsg(mp);
3925 		return;
3926 	}
3927 	arh = (arh_t *)mp->b_cont->b_rptr;
3928 	/* Is it one we are interested in? */
3929 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3930 		isv6 = B_TRUE;
3931 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3932 		    IPV6_ADDR_LEN);
3933 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3934 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3935 		    IP_ADDR_LEN);
3936 	} else {
3937 		freemsg(mp);
3938 		return;
3939 	}
3940 
3941 	ill = q->q_ptr;
3942 
3943 	arcn = (arcn_t *)mp->b_rptr;
3944 	switch (arcn->arcn_code) {
3945 	case AR_CN_BOGON:
3946 		/*
3947 		 * Someone is sending ARP packets with a source protocol
3948 		 * address that we have published and for which we believe our
3949 		 * entry is authoritative and (when ill_arp_extend is set)
3950 		 * verified to be unique on the network.
3951 		 *
3952 		 * The ARP module internally handles the cases where the sender
3953 		 * is just probing (for DAD) and where the hardware address of
3954 		 * a non-authoritative entry has changed.  Thus, these are the
3955 		 * real conflicts, and we have to do resolution.
3956 		 *
3957 		 * We back away quickly from the address if it's from DHCP or
3958 		 * otherwise temporary and hasn't been used recently (or at
3959 		 * all).  We'd like to include "deprecated" addresses here as
3960 		 * well (as there's no real reason to defend something we're
3961 		 * discarding), but IPMP "reuses" this flag to mean something
3962 		 * other than the standard meaning.
3963 		 *
3964 		 * If the ARP module above is not extended (meaning that it
3965 		 * doesn't know how to defend the address), then we just log
3966 		 * the problem as we always did and continue on.  It's not
3967 		 * right, but there's little else we can do, and those old ATM
3968 		 * users are going away anyway.
3969 		 */
3970 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3971 		    hbuf, sizeof (hbuf));
3972 		(void) ip_dot_addr(src, sbuf);
3973 		if (isv6) {
3974 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3975 			    ipst);
3976 		} else {
3977 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3978 		}
3979 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3980 			uint32_t now;
3981 			uint32_t maxage;
3982 			clock_t lused;
3983 			uint_t maxdefense;
3984 			uint_t defs;
3985 
3986 			/*
3987 			 * First, figure out if this address hasn't been used
3988 			 * in a while.  If it hasn't, then it's a better
3989 			 * candidate for abandoning.
3990 			 */
3991 			ipif = ire->ire_ipif;
3992 			ASSERT(ipif != NULL);
3993 			now = gethrestime_sec();
3994 			maxage = now - ire->ire_create_time;
3995 			if (maxage > ipst->ips_ip_max_temp_idle)
3996 				maxage = ipst->ips_ip_max_temp_idle;
3997 			lused = drv_hztousec(ddi_get_lbolt() -
3998 			    ire->ire_last_used_time) / MICROSEC + 1;
3999 			if (lused >= maxage && (ipif->ipif_flags &
4000 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4001 				maxdefense = ipst->ips_ip_max_temp_defend;
4002 			else
4003 				maxdefense = ipst->ips_ip_max_defend;
4004 
4005 			/*
4006 			 * Now figure out how many times we've defended
4007 			 * ourselves.  Ignore defenses that happened long in
4008 			 * the past.
4009 			 */
4010 			mutex_enter(&ire->ire_lock);
4011 			if ((defs = ire->ire_defense_count) > 0 &&
4012 			    now - ire->ire_defense_time >
4013 			    ipst->ips_ip_defend_interval) {
4014 				ire->ire_defense_count = defs = 0;
4015 			}
4016 			ire->ire_defense_count++;
4017 			ire->ire_defense_time = now;
4018 			mutex_exit(&ire->ire_lock);
4019 			ill_refhold(ill);
4020 			ire_refrele(ire);
4021 
4022 			/*
4023 			 * If we've defended ourselves too many times already,
4024 			 * then give up and tear down the interface(s) using
4025 			 * this address.  Otherwise, defend by sending out a
4026 			 * gratuitous ARP.
4027 			 */
4028 			if (defs >= maxdefense && ill->ill_arp_extend) {
4029 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4030 				    B_FALSE);
4031 			} else {
4032 				cmn_err(CE_WARN,
4033 				    "node %s is using our IP address %s on %s",
4034 				    hbuf, sbuf, ill->ill_name);
4035 				/*
4036 				 * If this is an old (ATM) ARP module, then
4037 				 * don't try to defend the address.  Remain
4038 				 * compatible with the old behavior.  Defend
4039 				 * only with new ARP.
4040 				 */
4041 				if (ill->ill_arp_extend) {
4042 					qwriter_ip(ill, q, mp, ip_arp_defend,
4043 					    NEW_OP, B_FALSE);
4044 				} else {
4045 					ill_refrele(ill);
4046 				}
4047 			}
4048 			return;
4049 		}
4050 		cmn_err(CE_WARN,
4051 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4052 		    hbuf, sbuf, ill->ill_name);
4053 		if (ire != NULL)
4054 			ire_refrele(ire);
4055 		break;
4056 	case AR_CN_ANNOUNCE:
4057 		if (isv6) {
4058 			/*
4059 			 * For XRESOLV interfaces.
4060 			 * Delete the IRE cache entry and NCE for this
4061 			 * v6 address
4062 			 */
4063 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4064 			/*
4065 			 * If v6src is a non-zero, it's a router address
4066 			 * as below. Do the same sort of thing to clean
4067 			 * out off-net IRE_CACHE entries that go through
4068 			 * the router.
4069 			 */
4070 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4071 				ire_walk_v6(ire_delete_cache_gw_v6,
4072 				    (char *)&v6src, ALL_ZONES, ipst);
4073 			}
4074 		} else {
4075 			nce_hw_map_t hwm;
4076 
4077 			/*
4078 			 * ARP gives us a copy of any packet where it thinks
4079 			 * the address has changed, so that we can update our
4080 			 * caches.  We're responsible for caching known answers
4081 			 * in the current design.  We check whether the
4082 			 * hardware address really has changed in all of our
4083 			 * entries that have cached this mapping, and if so, we
4084 			 * blow them away.  This way we will immediately pick
4085 			 * up the rare case of a host changing hardware
4086 			 * address.
4087 			 */
4088 			if (src == 0)
4089 				break;
4090 			hwm.hwm_addr = src;
4091 			hwm.hwm_hwlen = arh->arh_hlen;
4092 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4093 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4094 			ndp_walk_common(ipst->ips_ndp4, NULL,
4095 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4096 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4097 		}
4098 		break;
4099 	case AR_CN_READY:
4100 		/* No external v6 resolver has a contract to use this */
4101 		if (isv6)
4102 			break;
4103 		/* If the link is down, we'll retry this later */
4104 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4105 			break;
4106 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4107 		    NULL, NULL, ipst);
4108 		if (ipif != NULL) {
4109 			/*
4110 			 * If this is a duplicate recovery, then we now need to
4111 			 * go exclusive to bring this thing back up.
4112 			 */
4113 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4114 			    IPIF_DUPLICATE) {
4115 				ipif_refrele(ipif);
4116 				ill_refhold(ill);
4117 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4118 				    B_FALSE);
4119 				return;
4120 			}
4121 			/*
4122 			 * If this is the first notice that this address is
4123 			 * ready, then let the user know now.
4124 			 */
4125 			if ((ipif->ipif_flags & IPIF_UP) &&
4126 			    !ipif->ipif_addr_ready) {
4127 				ipif_mask_reply(ipif);
4128 				ip_rts_ifmsg(ipif);
4129 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4130 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4131 			}
4132 			ipif->ipif_addr_ready = 1;
4133 			ipif_refrele(ipif);
4134 		}
4135 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4136 		if (ire != NULL) {
4137 			ire->ire_defense_count = 0;
4138 			ire_refrele(ire);
4139 		}
4140 		break;
4141 	case AR_CN_FAILED:
4142 		/* No external v6 resolver has a contract to use this */
4143 		if (isv6)
4144 			break;
4145 		ill_refhold(ill);
4146 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4147 		return;
4148 	}
4149 	freemsg(mp);
4150 }
4151 
4152 /*
4153  * Create a mblk suitable for carrying the interface index and/or source link
4154  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4155  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4156  * application.
4157  */
4158 mblk_t *
4159 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4160     ip_stack_t *ipst)
4161 {
4162 	mblk_t		*mp;
4163 	ip_pktinfo_t	*pinfo;
4164 	ipha_t *ipha;
4165 	struct ether_header *pether;
4166 
4167 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4168 	if (mp == NULL) {
4169 		ip1dbg(("ip_add_info: allocation failure.\n"));
4170 		return (data_mp);
4171 	}
4172 
4173 	ipha	= (ipha_t *)data_mp->b_rptr;
4174 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4175 	bzero(pinfo, sizeof (ip_pktinfo_t));
4176 	pinfo->ip_pkt_flags = (uchar_t)flags;
4177 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4178 
4179 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4180 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4181 	if (flags & IPF_RECVADDR) {
4182 		ipif_t	*ipif;
4183 		ire_t	*ire;
4184 
4185 		/*
4186 		 * Only valid for V4
4187 		 */
4188 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4189 		    (IPV4_VERSION << 4));
4190 
4191 		ipif = ipif_get_next_ipif(NULL, ill);
4192 		if (ipif != NULL) {
4193 			/*
4194 			 * Since a decision has already been made to deliver the
4195 			 * packet, there is no need to test for SECATTR and
4196 			 * ZONEONLY.
4197 			 * When a multicast packet is transmitted
4198 			 * a cache entry is created for the multicast address.
4199 			 * When delivering a copy of the packet or when new
4200 			 * packets are received we do not want to match on the
4201 			 * cached entry so explicitly match on
4202 			 * IRE_LOCAL and IRE_LOOPBACK
4203 			 */
4204 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4205 			    IRE_LOCAL | IRE_LOOPBACK,
4206 			    ipif, zoneid, NULL,
4207 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4208 			if (ire == NULL) {
4209 				/*
4210 				 * packet must have come on a different
4211 				 * interface.
4212 				 * Since a decision has already been made to
4213 				 * deliver the packet, there is no need to test
4214 				 * for SECATTR and ZONEONLY.
4215 				 * Only match on local and broadcast ire's.
4216 				 * See detailed comment above.
4217 				 */
4218 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4219 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4220 				    NULL, MATCH_IRE_TYPE, ipst);
4221 			}
4222 
4223 			if (ire == NULL) {
4224 				/*
4225 				 * This is either a multicast packet or
4226 				 * the address has been removed since
4227 				 * the packet was received.
4228 				 * Return INADDR_ANY so that normal source
4229 				 * selection occurs for the response.
4230 				 */
4231 
4232 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4233 			} else {
4234 				pinfo->ip_pkt_match_addr.s_addr =
4235 				    ire->ire_src_addr;
4236 				ire_refrele(ire);
4237 			}
4238 			ipif_refrele(ipif);
4239 		} else {
4240 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4241 		}
4242 	}
4243 
4244 	pether = (struct ether_header *)((char *)ipha
4245 	    - sizeof (struct ether_header));
4246 	/*
4247 	 * Make sure the interface is an ethernet type, since this option
4248 	 * is currently supported only on this type of interface. Also make
4249 	 * sure we are pointing correctly above db_base.
4250 	 */
4251 
4252 	if ((flags & IPF_RECVSLLA) &&
4253 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4254 	    (ill->ill_type == IFT_ETHER) &&
4255 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4256 
4257 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4258 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4259 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4260 	} else {
4261 		/*
4262 		 * Clear the bit. Indicate to upper layer that IP is not
4263 		 * sending this ancillary info.
4264 		 */
4265 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4266 	}
4267 
4268 	mp->b_datap->db_type = M_CTL;
4269 	mp->b_wptr += sizeof (ip_pktinfo_t);
4270 	mp->b_cont = data_mp;
4271 
4272 	return (mp);
4273 }
4274 
4275 /*
4276  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4277  * part of the bind request.
4278  */
4279 
4280 boolean_t
4281 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4282 {
4283 	ipsec_in_t *ii;
4284 
4285 	ASSERT(policy_mp != NULL);
4286 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4287 
4288 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4289 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4290 
4291 	connp->conn_policy = ii->ipsec_in_policy;
4292 	ii->ipsec_in_policy = NULL;
4293 
4294 	if (ii->ipsec_in_action != NULL) {
4295 		if (connp->conn_latch == NULL) {
4296 			connp->conn_latch = iplatch_create();
4297 			if (connp->conn_latch == NULL)
4298 				return (B_FALSE);
4299 		}
4300 		ipsec_latch_inbound(connp->conn_latch, ii);
4301 	}
4302 	return (B_TRUE);
4303 }
4304 
4305 /*
4306  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4307  * and to arrange for power-fanout assist.  The ULP is identified by
4308  * adding a single byte at the end of the original bind message.
4309  * A ULP other than UDP or TCP that wishes to be recognized passes
4310  * down a bind with a zero length address.
4311  *
4312  * The binding works as follows:
4313  * - A zero byte address means just bind to the protocol.
4314  * - A four byte address is treated as a request to validate
4315  *   that the address is a valid local address, appropriate for
4316  *   an application to bind to. This does not affect any fanout
4317  *   information in IP.
4318  * - A sizeof sin_t byte address is used to bind to only the local address
4319  *   and port.
4320  * - A sizeof ipa_conn_t byte address contains complete fanout information
4321  *   consisting of local and remote addresses and ports.  In
4322  *   this case, the addresses are both validated as appropriate
4323  *   for this operation, and, if so, the information is retained
4324  *   for use in the inbound fanout.
4325  *
4326  * The ULP (except in the zero-length bind) can append an
4327  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4328  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4329  * a copy of the source or destination IRE (source for local bind;
4330  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4331  * policy information contained should be copied on to the conn.
4332  *
4333  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4334  */
4335 mblk_t *
4336 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4337 {
4338 	ssize_t		len;
4339 	struct T_bind_req	*tbr;
4340 	sin_t		*sin;
4341 	ipa_conn_t	*ac;
4342 	uchar_t		*ucp;
4343 	mblk_t		*mp1;
4344 	boolean_t	ire_requested;
4345 	boolean_t	ipsec_policy_set = B_FALSE;
4346 	int		error = 0;
4347 	int		protocol;
4348 	ipa_conn_x_t	*acx;
4349 
4350 	ASSERT(!connp->conn_af_isv6);
4351 	connp->conn_pkt_isv6 = B_FALSE;
4352 
4353 	len = MBLKL(mp);
4354 	if (len < (sizeof (*tbr) + 1)) {
4355 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4356 		    "ip_bind: bogus msg, len %ld", len);
4357 		/* XXX: Need to return something better */
4358 		goto bad_addr;
4359 	}
4360 	/* Back up and extract the protocol identifier. */
4361 	mp->b_wptr--;
4362 	protocol = *mp->b_wptr & 0xFF;
4363 	tbr = (struct T_bind_req *)mp->b_rptr;
4364 	/* Reset the message type in preparation for shipping it back. */
4365 	DB_TYPE(mp) = M_PCPROTO;
4366 
4367 	connp->conn_ulp = (uint8_t)protocol;
4368 
4369 	/*
4370 	 * Check for a zero length address.  This is from a protocol that
4371 	 * wants to register to receive all packets of its type.
4372 	 */
4373 	if (tbr->ADDR_length == 0) {
4374 		/*
4375 		 * These protocols are now intercepted in ip_bind_v6().
4376 		 * Reject protocol-level binds here for now.
4377 		 *
4378 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4379 		 * so that the protocol type cannot be SCTP.
4380 		 */
4381 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4382 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4383 			goto bad_addr;
4384 		}
4385 
4386 		/*
4387 		 *
4388 		 * The udp module never sends down a zero-length address,
4389 		 * and allowing this on a labeled system will break MLP
4390 		 * functionality.
4391 		 */
4392 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4393 			goto bad_addr;
4394 
4395 		if (connp->conn_mac_exempt)
4396 			goto bad_addr;
4397 
4398 		/* No hash here really.  The table is big enough. */
4399 		connp->conn_srcv6 = ipv6_all_zeros;
4400 
4401 		ipcl_proto_insert(connp, protocol);
4402 
4403 		tbr->PRIM_type = T_BIND_ACK;
4404 		return (mp);
4405 	}
4406 
4407 	/* Extract the address pointer from the message. */
4408 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4409 	    tbr->ADDR_length);
4410 	if (ucp == NULL) {
4411 		ip1dbg(("ip_bind: no address\n"));
4412 		goto bad_addr;
4413 	}
4414 	if (!OK_32PTR(ucp)) {
4415 		ip1dbg(("ip_bind: unaligned address\n"));
4416 		goto bad_addr;
4417 	}
4418 	/*
4419 	 * Check for trailing mps.
4420 	 */
4421 
4422 	mp1 = mp->b_cont;
4423 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4424 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4425 
4426 	switch (tbr->ADDR_length) {
4427 	default:
4428 		ip1dbg(("ip_bind: bad address length %d\n",
4429 		    (int)tbr->ADDR_length));
4430 		goto bad_addr;
4431 
4432 	case IP_ADDR_LEN:
4433 		/* Verification of local address only */
4434 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4435 		    ire_requested, ipsec_policy_set, B_FALSE);
4436 		break;
4437 
4438 	case sizeof (sin_t):
4439 		sin = (sin_t *)ucp;
4440 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4441 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4442 		break;
4443 
4444 	case sizeof (ipa_conn_t):
4445 		ac = (ipa_conn_t *)ucp;
4446 		/* For raw socket, the local port is not set. */
4447 		if (ac->ac_lport == 0)
4448 			ac->ac_lport = connp->conn_lport;
4449 		/* Always verify destination reachability. */
4450 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4451 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4452 		    ipsec_policy_set, B_TRUE, B_TRUE);
4453 		break;
4454 
4455 	case sizeof (ipa_conn_x_t):
4456 		acx = (ipa_conn_x_t *)ucp;
4457 		/*
4458 		 * Whether or not to verify destination reachability depends
4459 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4460 		 */
4461 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4462 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4463 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4464 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4465 		break;
4466 	}
4467 	if (error == EINPROGRESS)
4468 		return (NULL);
4469 	else if (error != 0)
4470 		goto bad_addr;
4471 	/*
4472 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4473 	 * We can't do this in ip_bind_insert_ire because the policy
4474 	 * may not have been inherited at that point in time and hence
4475 	 * conn_out_enforce_policy may not be set.
4476 	 */
4477 	mp1 = mp->b_cont;
4478 	if (ire_requested && connp->conn_out_enforce_policy &&
4479 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4480 		ire_t *ire = (ire_t *)mp1->b_rptr;
4481 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4482 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4483 	}
4484 
4485 	/* Send it home. */
4486 	mp->b_datap->db_type = M_PCPROTO;
4487 	tbr->PRIM_type = T_BIND_ACK;
4488 	return (mp);
4489 
4490 bad_addr:
4491 	/*
4492 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4493 	 * a unix errno.
4494 	 */
4495 	if (error > 0)
4496 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4497 	else
4498 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4499 	return (mp);
4500 }
4501 
4502 /*
4503  * Here address is verified to be a valid local address.
4504  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4505  * address is also considered a valid local address.
4506  * In the case of a broadcast/multicast address, however, the
4507  * upper protocol is expected to reset the src address
4508  * to 0 if it sees a IRE_BROADCAST type returned so that
4509  * no packets are emitted with broadcast/multicast address as
4510  * source address (that violates hosts requirements RFC1122)
4511  * The addresses valid for bind are:
4512  *	(1) - INADDR_ANY (0)
4513  *	(2) - IP address of an UP interface
4514  *	(3) - IP address of a DOWN interface
4515  *	(4) - valid local IP broadcast addresses. In this case
4516  *	the conn will only receive packets destined to
4517  *	the specified broadcast address.
4518  *	(5) - a multicast address. In this case
4519  *	the conn will only receive packets destined to
4520  *	the specified multicast address. Note: the
4521  *	application still has to issue an
4522  *	IP_ADD_MEMBERSHIP socket option.
4523  *
4524  * On error, return -1 for TBADADDR otherwise pass the
4525  * errno with TSYSERR reply.
4526  *
4527  * In all the above cases, the bound address must be valid in the current zone.
4528  * When the address is loopback, multicast or broadcast, there might be many
4529  * matching IREs so bind has to look up based on the zone.
4530  *
4531  * Note: lport is in network byte order.
4532  */
4533 int
4534 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4535     boolean_t ire_requested, boolean_t ipsec_policy_set,
4536     boolean_t fanout_insert)
4537 {
4538 	int		error = 0;
4539 	ire_t		*src_ire;
4540 	mblk_t		*policy_mp;
4541 	ipif_t		*ipif;
4542 	zoneid_t	zoneid;
4543 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4544 
4545 	if (ipsec_policy_set) {
4546 		policy_mp = mp->b_cont;
4547 	}
4548 
4549 	/*
4550 	 * If it was previously connected, conn_fully_bound would have
4551 	 * been set.
4552 	 */
4553 	connp->conn_fully_bound = B_FALSE;
4554 
4555 	src_ire = NULL;
4556 	ipif = NULL;
4557 
4558 	zoneid = IPCL_ZONEID(connp);
4559 
4560 	if (src_addr) {
4561 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4562 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4563 		/*
4564 		 * If an address other than 0.0.0.0 is requested,
4565 		 * we verify that it is a valid address for bind
4566 		 * Note: Following code is in if-else-if form for
4567 		 * readability compared to a condition check.
4568 		 */
4569 		/* LINTED - statement has no consequent */
4570 		if (IRE_IS_LOCAL(src_ire)) {
4571 			/*
4572 			 * (2) Bind to address of local UP interface
4573 			 */
4574 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4575 			/*
4576 			 * (4) Bind to broadcast address
4577 			 * Note: permitted only from transports that
4578 			 * request IRE
4579 			 */
4580 			if (!ire_requested)
4581 				error = EADDRNOTAVAIL;
4582 		} else {
4583 			/*
4584 			 * (3) Bind to address of local DOWN interface
4585 			 * (ipif_lookup_addr() looks up all interfaces
4586 			 * but we do not get here for UP interfaces
4587 			 * - case (2) above)
4588 			 * We put the protocol byte back into the mblk
4589 			 * since we may come back via ip_wput_nondata()
4590 			 * later with this mblk if ipif_lookup_addr chooses
4591 			 * to defer processing.
4592 			 */
4593 			*mp->b_wptr++ = (char)connp->conn_ulp;
4594 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4595 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4596 			    &error, ipst)) != NULL) {
4597 				ipif_refrele(ipif);
4598 			} else if (error == EINPROGRESS) {
4599 				if (src_ire != NULL)
4600 					ire_refrele(src_ire);
4601 				return (EINPROGRESS);
4602 			} else if (CLASSD(src_addr)) {
4603 				error = 0;
4604 				if (src_ire != NULL)
4605 					ire_refrele(src_ire);
4606 				/*
4607 				 * (5) bind to multicast address.
4608 				 * Fake out the IRE returned to upper
4609 				 * layer to be a broadcast IRE.
4610 				 */
4611 				src_ire = ire_ctable_lookup(
4612 				    INADDR_BROADCAST, INADDR_ANY,
4613 				    IRE_BROADCAST, NULL, zoneid, NULL,
4614 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4615 				    ipst);
4616 				if (src_ire == NULL || !ire_requested)
4617 					error = EADDRNOTAVAIL;
4618 			} else {
4619 				/*
4620 				 * Not a valid address for bind
4621 				 */
4622 				error = EADDRNOTAVAIL;
4623 			}
4624 			/*
4625 			 * Just to keep it consistent with the processing in
4626 			 * ip_bind_v4()
4627 			 */
4628 			mp->b_wptr--;
4629 		}
4630 		if (error) {
4631 			/* Red Alert!  Attempting to be a bogon! */
4632 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4633 			    ntohl(src_addr)));
4634 			goto bad_addr;
4635 		}
4636 	}
4637 
4638 	/*
4639 	 * Allow setting new policies. For example, disconnects come
4640 	 * down as ipa_t bind. As we would have set conn_policy_cached
4641 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4642 	 * can change after the disconnect.
4643 	 */
4644 	connp->conn_policy_cached = B_FALSE;
4645 
4646 	/*
4647 	 * If not fanout_insert this was just an address verification
4648 	 */
4649 	if (fanout_insert) {
4650 		/*
4651 		 * The addresses have been verified. Time to insert in
4652 		 * the correct fanout list.
4653 		 */
4654 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4655 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4656 		connp->conn_lport = lport;
4657 		connp->conn_fport = 0;
4658 		/*
4659 		 * Do we need to add a check to reject Multicast packets
4660 		 *
4661 		 * We need to make sure that the conn_recv is set to a non-null
4662 		 * value before we insert the conn into the classifier table.
4663 		 * This is to avoid a race with an incoming packet which does an
4664 		 * ipcl_classify().
4665 		 */
4666 		if (*mp->b_wptr == IPPROTO_TCP)
4667 			connp->conn_recv = tcp_conn_request;
4668 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4669 	}
4670 
4671 	if (error == 0) {
4672 		if (ire_requested) {
4673 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4674 				error = -1;
4675 				/* Falls through to bad_addr */
4676 			}
4677 		} else if (ipsec_policy_set) {
4678 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4679 				error = -1;
4680 				/* Falls through to bad_addr */
4681 			}
4682 		}
4683 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4684 		connp->conn_recv = tcp_input;
4685 	}
4686 bad_addr:
4687 	if (error != 0) {
4688 		if (connp->conn_anon_port) {
4689 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4690 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4691 			    B_FALSE);
4692 		}
4693 		connp->conn_mlp_type = mlptSingle;
4694 	}
4695 	if (src_ire != NULL)
4696 		IRE_REFRELE(src_ire);
4697 	if (ipsec_policy_set) {
4698 		ASSERT(policy_mp == mp->b_cont);
4699 		ASSERT(policy_mp != NULL);
4700 		freeb(policy_mp);
4701 		/*
4702 		 * As of now assume that nothing else accompanies
4703 		 * IPSEC_POLICY_SET.
4704 		 */
4705 		mp->b_cont = NULL;
4706 	}
4707 	return (error);
4708 }
4709 
4710 /*
4711  * Verify that both the source and destination addresses
4712  * are valid.  If verify_dst is false, then the destination address may be
4713  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4714  * destination reachability, while tunnels do not.
4715  * Note that we allow connect to broadcast and multicast
4716  * addresses when ire_requested is set. Thus the ULP
4717  * has to check for IRE_BROADCAST and multicast.
4718  *
4719  * Returns zero if ok.
4720  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4721  * (for use with TSYSERR reply).
4722  *
4723  * Note: lport and fport are in network byte order.
4724  */
4725 int
4726 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4727     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4728     boolean_t ire_requested, boolean_t ipsec_policy_set,
4729     boolean_t fanout_insert, boolean_t verify_dst)
4730 {
4731 	ire_t		*src_ire;
4732 	ire_t		*dst_ire;
4733 	int		error = 0;
4734 	int 		protocol;
4735 	mblk_t		*policy_mp;
4736 	ire_t		*sire = NULL;
4737 	ire_t		*md_dst_ire = NULL;
4738 	ire_t		*lso_dst_ire = NULL;
4739 	ill_t		*ill = NULL;
4740 	zoneid_t	zoneid;
4741 	ipaddr_t	src_addr = *src_addrp;
4742 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4743 
4744 	src_ire = dst_ire = NULL;
4745 	protocol = *mp->b_wptr & 0xFF;
4746 
4747 	/*
4748 	 * If we never got a disconnect before, clear it now.
4749 	 */
4750 	connp->conn_fully_bound = B_FALSE;
4751 
4752 	if (ipsec_policy_set) {
4753 		policy_mp = mp->b_cont;
4754 	}
4755 
4756 	zoneid = IPCL_ZONEID(connp);
4757 
4758 	if (CLASSD(dst_addr)) {
4759 		/* Pick up an IRE_BROADCAST */
4760 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4761 		    NULL, zoneid, MBLK_GETLABEL(mp),
4762 		    (MATCH_IRE_RECURSIVE |
4763 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4764 		    MATCH_IRE_SECATTR), ipst);
4765 	} else {
4766 		/*
4767 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4768 		 * and onlink ipif is not found set ENETUNREACH error.
4769 		 */
4770 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4771 			ipif_t *ipif;
4772 
4773 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4774 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4775 			if (ipif == NULL) {
4776 				error = ENETUNREACH;
4777 				goto bad_addr;
4778 			}
4779 			ipif_refrele(ipif);
4780 		}
4781 
4782 		if (connp->conn_nexthop_set) {
4783 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4784 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4785 			    MATCH_IRE_SECATTR, ipst);
4786 		} else {
4787 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4788 			    &sire, zoneid, MBLK_GETLABEL(mp),
4789 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4790 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4791 			    MATCH_IRE_SECATTR), ipst);
4792 		}
4793 	}
4794 	/*
4795 	 * dst_ire can't be a broadcast when not ire_requested.
4796 	 * We also prevent ire's with src address INADDR_ANY to
4797 	 * be used, which are created temporarily for
4798 	 * sending out packets from endpoints that have
4799 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4800 	 * reachable.  If verify_dst is false, the destination needn't be
4801 	 * reachable.
4802 	 *
4803 	 * If we match on a reject or black hole, then we've got a
4804 	 * local failure.  May as well fail out the connect() attempt,
4805 	 * since it's never going to succeed.
4806 	 */
4807 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4808 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4809 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4810 		/*
4811 		 * If we're verifying destination reachability, we always want
4812 		 * to complain here.
4813 		 *
4814 		 * If we're not verifying destination reachability but the
4815 		 * destination has a route, we still want to fail on the
4816 		 * temporary address and broadcast address tests.
4817 		 */
4818 		if (verify_dst || (dst_ire != NULL)) {
4819 			if (ip_debug > 2) {
4820 				pr_addr_dbg("ip_bind_connected: bad connected "
4821 				    "dst %s\n", AF_INET, &dst_addr);
4822 			}
4823 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4824 				error = ENETUNREACH;
4825 			else
4826 				error = EHOSTUNREACH;
4827 			goto bad_addr;
4828 		}
4829 	}
4830 
4831 	/*
4832 	 * We now know that routing will allow us to reach the destination.
4833 	 * Check whether Trusted Solaris policy allows communication with this
4834 	 * host, and pretend that the destination is unreachable if not.
4835 	 *
4836 	 * This is never a problem for TCP, since that transport is known to
4837 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4838 	 * handling.  If the remote is unreachable, it will be detected at that
4839 	 * point, so there's no reason to check it here.
4840 	 *
4841 	 * Note that for sendto (and other datagram-oriented friends), this
4842 	 * check is done as part of the data path label computation instead.
4843 	 * The check here is just to make non-TCP connect() report the right
4844 	 * error.
4845 	 */
4846 	if (dst_ire != NULL && is_system_labeled() &&
4847 	    !IPCL_IS_TCP(connp) &&
4848 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4849 	    connp->conn_mac_exempt, ipst) != 0) {
4850 		error = EHOSTUNREACH;
4851 		if (ip_debug > 2) {
4852 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4853 			    AF_INET, &dst_addr);
4854 		}
4855 		goto bad_addr;
4856 	}
4857 
4858 	/*
4859 	 * If the app does a connect(), it means that it will most likely
4860 	 * send more than 1 packet to the destination.  It makes sense
4861 	 * to clear the temporary flag.
4862 	 */
4863 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4864 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4865 		irb_t *irb = dst_ire->ire_bucket;
4866 
4867 		rw_enter(&irb->irb_lock, RW_WRITER);
4868 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4869 		irb->irb_tmp_ire_cnt--;
4870 		rw_exit(&irb->irb_lock);
4871 	}
4872 
4873 	/*
4874 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4875 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4876 	 * eligibility tests for passive connects are handled separately
4877 	 * through tcp_adapt_ire().  We do this before the source address
4878 	 * selection, because dst_ire may change after a call to
4879 	 * ipif_select_source().  This is a best-effort check, as the
4880 	 * packet for this connection may not actually go through
4881 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4882 	 * calling ip_newroute().  This is why we further check on the
4883 	 * IRE during LSO/Multidata packet transmission in
4884 	 * tcp_lsosend()/tcp_multisend().
4885 	 */
4886 	if (!ipsec_policy_set && dst_ire != NULL &&
4887 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4888 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4889 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4890 			lso_dst_ire = dst_ire;
4891 			IRE_REFHOLD(lso_dst_ire);
4892 		} else if (ipst->ips_ip_multidata_outbound &&
4893 		    ILL_MDT_CAPABLE(ill)) {
4894 			md_dst_ire = dst_ire;
4895 			IRE_REFHOLD(md_dst_ire);
4896 		}
4897 	}
4898 
4899 	if (dst_ire != NULL &&
4900 	    dst_ire->ire_type == IRE_LOCAL &&
4901 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4902 		/*
4903 		 * If the IRE belongs to a different zone, look for a matching
4904 		 * route in the forwarding table and use the source address from
4905 		 * that route.
4906 		 */
4907 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4908 		    zoneid, 0, NULL,
4909 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4910 		    MATCH_IRE_RJ_BHOLE, ipst);
4911 		if (src_ire == NULL) {
4912 			error = EHOSTUNREACH;
4913 			goto bad_addr;
4914 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4915 			if (!(src_ire->ire_type & IRE_HOST))
4916 				error = ENETUNREACH;
4917 			else
4918 				error = EHOSTUNREACH;
4919 			goto bad_addr;
4920 		}
4921 		if (src_addr == INADDR_ANY)
4922 			src_addr = src_ire->ire_src_addr;
4923 		ire_refrele(src_ire);
4924 		src_ire = NULL;
4925 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4926 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4927 			src_addr = sire->ire_src_addr;
4928 			ire_refrele(dst_ire);
4929 			dst_ire = sire;
4930 			sire = NULL;
4931 		} else {
4932 			/*
4933 			 * Pick a source address so that a proper inbound
4934 			 * load spreading would happen.
4935 			 */
4936 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4937 			ipif_t *src_ipif = NULL;
4938 			ire_t *ipif_ire;
4939 
4940 			/*
4941 			 * Supply a local source address such that inbound
4942 			 * load spreading happens.
4943 			 *
4944 			 * Determine the best source address on this ill for
4945 			 * the destination.
4946 			 *
4947 			 * 1) For broadcast, we should return a broadcast ire
4948 			 *    found above so that upper layers know that the
4949 			 *    destination address is a broadcast address.
4950 			 *
4951 			 * 2) If this is part of a group, select a better
4952 			 *    source address so that better inbound load
4953 			 *    balancing happens. Do the same if the ipif
4954 			 *    is DEPRECATED.
4955 			 *
4956 			 * 3) If the outgoing interface is part of a usesrc
4957 			 *    group, then try selecting a source address from
4958 			 *    the usesrc ILL.
4959 			 */
4960 			if ((dst_ire->ire_zoneid != zoneid &&
4961 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4962 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4963 			    ((dst_ill->ill_group != NULL) ||
4964 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4965 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4966 				/*
4967 				 * If the destination is reachable via a
4968 				 * given gateway, the selected source address
4969 				 * should be in the same subnet as the gateway.
4970 				 * Otherwise, the destination is not reachable.
4971 				 *
4972 				 * If there are no interfaces on the same subnet
4973 				 * as the destination, ipif_select_source gives
4974 				 * first non-deprecated interface which might be
4975 				 * on a different subnet than the gateway.
4976 				 * This is not desirable. Hence pass the dst_ire
4977 				 * source address to ipif_select_source.
4978 				 * It is sure that the destination is reachable
4979 				 * with the dst_ire source address subnet.
4980 				 * So passing dst_ire source address to
4981 				 * ipif_select_source will make sure that the
4982 				 * selected source will be on the same subnet
4983 				 * as dst_ire source address.
4984 				 */
4985 				ipaddr_t saddr =
4986 				    dst_ire->ire_ipif->ipif_src_addr;
4987 				src_ipif = ipif_select_source(dst_ill,
4988 				    saddr, zoneid);
4989 				if (src_ipif != NULL) {
4990 					if (IS_VNI(src_ipif->ipif_ill)) {
4991 						/*
4992 						 * For VNI there is no
4993 						 * interface route
4994 						 */
4995 						src_addr =
4996 						    src_ipif->ipif_src_addr;
4997 					} else {
4998 						ipif_ire =
4999 						    ipif_to_ire(src_ipif);
5000 						if (ipif_ire != NULL) {
5001 							IRE_REFRELE(dst_ire);
5002 							dst_ire = ipif_ire;
5003 						}
5004 						src_addr =
5005 						    dst_ire->ire_src_addr;
5006 					}
5007 					ipif_refrele(src_ipif);
5008 				} else {
5009 					src_addr = dst_ire->ire_src_addr;
5010 				}
5011 			} else {
5012 				src_addr = dst_ire->ire_src_addr;
5013 			}
5014 		}
5015 	}
5016 
5017 	/*
5018 	 * We do ire_route_lookup() here (and not
5019 	 * interface lookup as we assert that
5020 	 * src_addr should only come from an
5021 	 * UP interface for hard binding.
5022 	 */
5023 	ASSERT(src_ire == NULL);
5024 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5025 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5026 	/* src_ire must be a local|loopback */
5027 	if (!IRE_IS_LOCAL(src_ire)) {
5028 		if (ip_debug > 2) {
5029 			pr_addr_dbg("ip_bind_connected: bad connected "
5030 			    "src %s\n", AF_INET, &src_addr);
5031 		}
5032 		error = EADDRNOTAVAIL;
5033 		goto bad_addr;
5034 	}
5035 
5036 	/*
5037 	 * If the source address is a loopback address, the
5038 	 * destination had best be local or multicast.
5039 	 * The transports that can't handle multicast will reject
5040 	 * those addresses.
5041 	 */
5042 	if (src_ire->ire_type == IRE_LOOPBACK &&
5043 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5044 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5045 		error = -1;
5046 		goto bad_addr;
5047 	}
5048 
5049 	/*
5050 	 * Allow setting new policies. For example, disconnects come
5051 	 * down as ipa_t bind. As we would have set conn_policy_cached
5052 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5053 	 * can change after the disconnect.
5054 	 */
5055 	connp->conn_policy_cached = B_FALSE;
5056 
5057 	/*
5058 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5059 	 * can handle their passed-in conn's.
5060 	 */
5061 
5062 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5063 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5064 	connp->conn_lport = lport;
5065 	connp->conn_fport = fport;
5066 	*src_addrp = src_addr;
5067 
5068 	ASSERT(!(ipsec_policy_set && ire_requested));
5069 	if (ire_requested) {
5070 		iulp_t *ulp_info = NULL;
5071 
5072 		/*
5073 		 * Note that sire will not be NULL if this is an off-link
5074 		 * connection and there is not cache for that dest yet.
5075 		 *
5076 		 * XXX Because of an existing bug, if there are multiple
5077 		 * default routes, the IRE returned now may not be the actual
5078 		 * default route used (default routes are chosen in a
5079 		 * round robin fashion).  So if the metrics for different
5080 		 * default routes are different, we may return the wrong
5081 		 * metrics.  This will not be a problem if the existing
5082 		 * bug is fixed.
5083 		 */
5084 		if (sire != NULL) {
5085 			ulp_info = &(sire->ire_uinfo);
5086 		}
5087 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5088 			error = -1;
5089 			goto bad_addr;
5090 		}
5091 	} else if (ipsec_policy_set) {
5092 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5093 			error = -1;
5094 			goto bad_addr;
5095 		}
5096 	}
5097 
5098 	/*
5099 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5100 	 * we'll cache that.  If we don't, we'll inherit global policy.
5101 	 *
5102 	 * We can't insert until the conn reflects the policy. Note that
5103 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5104 	 * connections where we don't have a policy. This is to prevent
5105 	 * global policy lookups in the inbound path.
5106 	 *
5107 	 * If we insert before we set conn_policy_cached,
5108 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5109 	 * because global policy cound be non-empty. We normally call
5110 	 * ipsec_check_policy() for conn_policy_cached connections only if
5111 	 * ipc_in_enforce_policy is set. But in this case,
5112 	 * conn_policy_cached can get set anytime since we made the
5113 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5114 	 * called, which will make the above assumption false.  Thus, we
5115 	 * need to insert after we set conn_policy_cached.
5116 	 */
5117 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5118 		goto bad_addr;
5119 
5120 	if (fanout_insert) {
5121 		/*
5122 		 * The addresses have been verified. Time to insert in
5123 		 * the correct fanout list.
5124 		 * We need to make sure that the conn_recv is set to a non-null
5125 		 * value before we insert into the classifier table to avoid a
5126 		 * race with an incoming packet which does an ipcl_classify().
5127 		 */
5128 		if (protocol == IPPROTO_TCP)
5129 			connp->conn_recv = tcp_input;
5130 		error = ipcl_conn_insert(connp, protocol, src_addr,
5131 		    dst_addr, connp->conn_ports);
5132 	}
5133 
5134 	if (error == 0) {
5135 		connp->conn_fully_bound = B_TRUE;
5136 		/*
5137 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5138 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5139 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5140 		 * ip_xxinfo_return(), which performs further checks
5141 		 * against them and upon success, returns the LSO/MDT info
5142 		 * mblk which we will attach to the bind acknowledgment.
5143 		 */
5144 		if (lso_dst_ire != NULL) {
5145 			mblk_t *lsoinfo_mp;
5146 
5147 			ASSERT(ill->ill_lso_capab != NULL);
5148 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5149 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5150 				linkb(mp, lsoinfo_mp);
5151 		} else if (md_dst_ire != NULL) {
5152 			mblk_t *mdinfo_mp;
5153 
5154 			ASSERT(ill->ill_mdt_capab != NULL);
5155 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5156 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5157 				linkb(mp, mdinfo_mp);
5158 		}
5159 	}
5160 bad_addr:
5161 	if (ipsec_policy_set) {
5162 		ASSERT(policy_mp == mp->b_cont);
5163 		ASSERT(policy_mp != NULL);
5164 		freeb(policy_mp);
5165 		/*
5166 		 * As of now assume that nothing else accompanies
5167 		 * IPSEC_POLICY_SET.
5168 		 */
5169 		mp->b_cont = NULL;
5170 	}
5171 	if (src_ire != NULL)
5172 		IRE_REFRELE(src_ire);
5173 	if (dst_ire != NULL)
5174 		IRE_REFRELE(dst_ire);
5175 	if (sire != NULL)
5176 		IRE_REFRELE(sire);
5177 	if (md_dst_ire != NULL)
5178 		IRE_REFRELE(md_dst_ire);
5179 	if (lso_dst_ire != NULL)
5180 		IRE_REFRELE(lso_dst_ire);
5181 	return (error);
5182 }
5183 
5184 /*
5185  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5186  * Prefers dst_ire over src_ire.
5187  */
5188 static boolean_t
5189 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5190 {
5191 	mblk_t	*mp1;
5192 	ire_t *ret_ire = NULL;
5193 
5194 	mp1 = mp->b_cont;
5195 	ASSERT(mp1 != NULL);
5196 
5197 	if (ire != NULL) {
5198 		/*
5199 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5200 		 * appended mblk. Its <upper protocol>'s
5201 		 * job to make sure there is room.
5202 		 */
5203 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5204 			return (0);
5205 
5206 		mp1->b_datap->db_type = IRE_DB_TYPE;
5207 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5208 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5209 		ret_ire = (ire_t *)mp1->b_rptr;
5210 		/*
5211 		 * Pass the latest setting of the ip_path_mtu_discovery and
5212 		 * copy the ulp info if any.
5213 		 */
5214 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5215 		    IPH_DF : 0;
5216 		if (ulp_info != NULL) {
5217 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5218 			    sizeof (iulp_t));
5219 		}
5220 		ret_ire->ire_mp = mp1;
5221 	} else {
5222 		/*
5223 		 * No IRE was found. Remove IRE mblk.
5224 		 */
5225 		mp->b_cont = mp1->b_cont;
5226 		freeb(mp1);
5227 	}
5228 
5229 	return (1);
5230 }
5231 
5232 /*
5233  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5234  * the final piece where we don't.  Return a pointer to the first mblk in the
5235  * result, and update the pointer to the next mblk to chew on.  If anything
5236  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5237  * NULL pointer.
5238  */
5239 mblk_t *
5240 ip_carve_mp(mblk_t **mpp, ssize_t len)
5241 {
5242 	mblk_t	*mp0;
5243 	mblk_t	*mp1;
5244 	mblk_t	*mp2;
5245 
5246 	if (!len || !mpp || !(mp0 = *mpp))
5247 		return (NULL);
5248 	/* If we aren't going to consume the first mblk, we need a dup. */
5249 	if (mp0->b_wptr - mp0->b_rptr > len) {
5250 		mp1 = dupb(mp0);
5251 		if (mp1) {
5252 			/* Partition the data between the two mblks. */
5253 			mp1->b_wptr = mp1->b_rptr + len;
5254 			mp0->b_rptr = mp1->b_wptr;
5255 			/*
5256 			 * after adjustments if mblk not consumed is now
5257 			 * unaligned, try to align it. If this fails free
5258 			 * all messages and let upper layer recover.
5259 			 */
5260 			if (!OK_32PTR(mp0->b_rptr)) {
5261 				if (!pullupmsg(mp0, -1)) {
5262 					freemsg(mp0);
5263 					freemsg(mp1);
5264 					*mpp = NULL;
5265 					return (NULL);
5266 				}
5267 			}
5268 		}
5269 		return (mp1);
5270 	}
5271 	/* Eat through as many mblks as we need to get len bytes. */
5272 	len -= mp0->b_wptr - mp0->b_rptr;
5273 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5274 		if (mp2->b_wptr - mp2->b_rptr > len) {
5275 			/*
5276 			 * We won't consume the entire last mblk.  Like
5277 			 * above, dup and partition it.
5278 			 */
5279 			mp1->b_cont = dupb(mp2);
5280 			mp1 = mp1->b_cont;
5281 			if (!mp1) {
5282 				/*
5283 				 * Trouble.  Rather than go to a lot of
5284 				 * trouble to clean up, we free the messages.
5285 				 * This won't be any worse than losing it on
5286 				 * the wire.
5287 				 */
5288 				freemsg(mp0);
5289 				freemsg(mp2);
5290 				*mpp = NULL;
5291 				return (NULL);
5292 			}
5293 			mp1->b_wptr = mp1->b_rptr + len;
5294 			mp2->b_rptr = mp1->b_wptr;
5295 			/*
5296 			 * after adjustments if mblk not consumed is now
5297 			 * unaligned, try to align it. If this fails free
5298 			 * all messages and let upper layer recover.
5299 			 */
5300 			if (!OK_32PTR(mp2->b_rptr)) {
5301 				if (!pullupmsg(mp2, -1)) {
5302 					freemsg(mp0);
5303 					freemsg(mp2);
5304 					*mpp = NULL;
5305 					return (NULL);
5306 				}
5307 			}
5308 			*mpp = mp2;
5309 			return (mp0);
5310 		}
5311 		/* Decrement len by the amount we just got. */
5312 		len -= mp2->b_wptr - mp2->b_rptr;
5313 	}
5314 	/*
5315 	 * len should be reduced to zero now.  If not our caller has
5316 	 * screwed up.
5317 	 */
5318 	if (len) {
5319 		/* Shouldn't happen! */
5320 		freemsg(mp0);
5321 		*mpp = NULL;
5322 		return (NULL);
5323 	}
5324 	/*
5325 	 * We consumed up to exactly the end of an mblk.  Detach the part
5326 	 * we are returning from the rest of the chain.
5327 	 */
5328 	mp1->b_cont = NULL;
5329 	*mpp = mp2;
5330 	return (mp0);
5331 }
5332 
5333 /* The ill stream is being unplumbed. Called from ip_close */
5334 int
5335 ip_modclose(ill_t *ill)
5336 {
5337 	boolean_t success;
5338 	ipsq_t	*ipsq;
5339 	ipif_t	*ipif;
5340 	queue_t	*q = ill->ill_rq;
5341 	ip_stack_t	*ipst = ill->ill_ipst;
5342 	clock_t timeout;
5343 
5344 	/*
5345 	 * Wait for the ACKs of all deferred control messages to be processed.
5346 	 * In particular, we wait for a potential capability reset initiated
5347 	 * in ip_sioctl_plink() to complete before proceeding.
5348 	 *
5349 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5350 	 * in case the driver never replies.
5351 	 */
5352 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5353 	mutex_enter(&ill->ill_lock);
5354 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5355 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5356 			/* Timeout */
5357 			break;
5358 		}
5359 	}
5360 	mutex_exit(&ill->ill_lock);
5361 
5362 	/*
5363 	 * Forcibly enter the ipsq after some delay. This is to take
5364 	 * care of the case when some ioctl does not complete because
5365 	 * we sent a control message to the driver and it did not
5366 	 * send us a reply. We want to be able to at least unplumb
5367 	 * and replumb rather than force the user to reboot the system.
5368 	 */
5369 	success = ipsq_enter(ill, B_FALSE);
5370 
5371 	/*
5372 	 * Open/close/push/pop is guaranteed to be single threaded
5373 	 * per stream by STREAMS. FS guarantees that all references
5374 	 * from top are gone before close is called. So there can't
5375 	 * be another close thread that has set CONDEMNED on this ill.
5376 	 * and cause ipsq_enter to return failure.
5377 	 */
5378 	ASSERT(success);
5379 	ipsq = ill->ill_phyint->phyint_ipsq;
5380 
5381 	/*
5382 	 * Mark it condemned. No new reference will be made to this ill.
5383 	 * Lookup functions will return an error. Threads that try to
5384 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5385 	 * that the refcnt will drop down to zero.
5386 	 */
5387 	mutex_enter(&ill->ill_lock);
5388 	ill->ill_state_flags |= ILL_CONDEMNED;
5389 	for (ipif = ill->ill_ipif; ipif != NULL;
5390 	    ipif = ipif->ipif_next) {
5391 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5392 	}
5393 	/*
5394 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5395 	 * returns  error if ILL_CONDEMNED is set
5396 	 */
5397 	cv_broadcast(&ill->ill_cv);
5398 	mutex_exit(&ill->ill_lock);
5399 
5400 	/*
5401 	 * Send all the deferred DLPI messages downstream which came in
5402 	 * during the small window right before ipsq_enter(). We do this
5403 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5404 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5405 	 */
5406 	ill_dlpi_send_deferred(ill);
5407 
5408 	/*
5409 	 * Shut down fragmentation reassembly.
5410 	 * ill_frag_timer won't start a timer again.
5411 	 * Now cancel any existing timer
5412 	 */
5413 	(void) untimeout(ill->ill_frag_timer_id);
5414 	(void) ill_frag_timeout(ill, 0);
5415 
5416 	/*
5417 	 * If MOVE was in progress, clear the
5418 	 * move_in_progress fields also.
5419 	 */
5420 	if (ill->ill_move_in_progress) {
5421 		ILL_CLEAR_MOVE(ill);
5422 	}
5423 
5424 	/*
5425 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5426 	 * this ill. Then wait for the refcnts to drop to zero.
5427 	 * ill_is_quiescent checks whether the ill is really quiescent.
5428 	 * Then make sure that threads that are waiting to enter the
5429 	 * ipsq have seen the error returned by ipsq_enter and have
5430 	 * gone away. Then we call ill_delete_tail which does the
5431 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5432 	 */
5433 	ill_delete(ill);
5434 	mutex_enter(&ill->ill_lock);
5435 	while (!ill_is_quiescent(ill))
5436 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5437 	while (ill->ill_waiters)
5438 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5439 
5440 	mutex_exit(&ill->ill_lock);
5441 
5442 	/*
5443 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5444 	 * it held until the end of the function since the cleanup
5445 	 * below needs to be able to use the ip_stack_t.
5446 	 */
5447 	netstack_hold(ipst->ips_netstack);
5448 
5449 	/* qprocsoff is called in ill_delete_tail */
5450 	ill_delete_tail(ill);
5451 	ASSERT(ill->ill_ipst == NULL);
5452 
5453 	/*
5454 	 * Walk through all upper (conn) streams and qenable
5455 	 * those that have queued data.
5456 	 * close synchronization needs this to
5457 	 * be done to ensure that all upper layers blocked
5458 	 * due to flow control to the closing device
5459 	 * get unblocked.
5460 	 */
5461 	ip1dbg(("ip_wsrv: walking\n"));
5462 	conn_walk_drain(ipst);
5463 
5464 	mutex_enter(&ipst->ips_ip_mi_lock);
5465 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5466 	mutex_exit(&ipst->ips_ip_mi_lock);
5467 
5468 	/*
5469 	 * credp could be null if the open didn't succeed and ip_modopen
5470 	 * itself calls ip_close.
5471 	 */
5472 	if (ill->ill_credp != NULL)
5473 		crfree(ill->ill_credp);
5474 
5475 	mutex_enter(&ill->ill_lock);
5476 	ill_nic_info_dispatch(ill);
5477 	mutex_exit(&ill->ill_lock);
5478 
5479 	/*
5480 	 * Now we are done with the module close pieces that
5481 	 * need the netstack_t.
5482 	 */
5483 	netstack_rele(ipst->ips_netstack);
5484 
5485 	mi_close_free((IDP)ill);
5486 	q->q_ptr = WR(q)->q_ptr = NULL;
5487 
5488 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5489 
5490 	return (0);
5491 }
5492 
5493 /*
5494  * This is called as part of close() for both IP and UDP
5495  * in order to quiesce the conn.
5496  */
5497 void
5498 ip_quiesce_conn(conn_t *connp)
5499 {
5500 	boolean_t	drain_cleanup_reqd = B_FALSE;
5501 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5502 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5503 	ip_stack_t	*ipst;
5504 
5505 	ASSERT(!IPCL_IS_TCP(connp));
5506 	ipst = connp->conn_netstack->netstack_ip;
5507 
5508 	/*
5509 	 * Mark the conn as closing, and this conn must not be
5510 	 * inserted in future into any list. Eg. conn_drain_insert(),
5511 	 * won't insert this conn into the conn_drain_list.
5512 	 * Similarly ill_pending_mp_add() will not add any mp to
5513 	 * the pending mp list, after this conn has started closing.
5514 	 *
5515 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5516 	 * cannot get set henceforth.
5517 	 */
5518 	mutex_enter(&connp->conn_lock);
5519 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5520 	connp->conn_state_flags |= CONN_CLOSING;
5521 	if (connp->conn_idl != NULL)
5522 		drain_cleanup_reqd = B_TRUE;
5523 	if (connp->conn_oper_pending_ill != NULL)
5524 		conn_ioctl_cleanup_reqd = B_TRUE;
5525 	if (connp->conn_ilg_inuse != 0)
5526 		ilg_cleanup_reqd = B_TRUE;
5527 	mutex_exit(&connp->conn_lock);
5528 
5529 	if (IPCL_IS_UDP(connp))
5530 		udp_quiesce_conn(connp);
5531 
5532 	if (conn_ioctl_cleanup_reqd)
5533 		conn_ioctl_cleanup(connp);
5534 
5535 	if (is_system_labeled() && connp->conn_anon_port) {
5536 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5537 		    connp->conn_mlp_type, connp->conn_ulp,
5538 		    ntohs(connp->conn_lport), B_FALSE);
5539 		connp->conn_anon_port = 0;
5540 	}
5541 	connp->conn_mlp_type = mlptSingle;
5542 
5543 	/*
5544 	 * Remove this conn from any fanout list it is on.
5545 	 * and then wait for any threads currently operating
5546 	 * on this endpoint to finish
5547 	 */
5548 	ipcl_hash_remove(connp);
5549 
5550 	/*
5551 	 * Remove this conn from the drain list, and do
5552 	 * any other cleanup that may be required.
5553 	 * (Only non-tcp streams may have a non-null conn_idl.
5554 	 * TCP streams are never flow controlled, and
5555 	 * conn_idl will be null)
5556 	 */
5557 	if (drain_cleanup_reqd)
5558 		conn_drain_tail(connp, B_TRUE);
5559 
5560 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5561 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5562 		(void) ip_mrouter_done(NULL, ipst);
5563 
5564 	if (ilg_cleanup_reqd)
5565 		ilg_delete_all(connp);
5566 
5567 	conn_delete_ire(connp, NULL);
5568 
5569 	/*
5570 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5571 	 * callers from write side can't be there now because close
5572 	 * is in progress. The only other caller is ipcl_walk
5573 	 * which checks for the condemned flag.
5574 	 */
5575 	mutex_enter(&connp->conn_lock);
5576 	connp->conn_state_flags |= CONN_CONDEMNED;
5577 	while (connp->conn_ref != 1)
5578 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5579 	connp->conn_state_flags |= CONN_QUIESCED;
5580 	mutex_exit(&connp->conn_lock);
5581 }
5582 
5583 /* ARGSUSED */
5584 int
5585 ip_close(queue_t *q, int flags)
5586 {
5587 	conn_t		*connp;
5588 
5589 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5590 
5591 	/*
5592 	 * Call the appropriate delete routine depending on whether this is
5593 	 * a module or device.
5594 	 */
5595 	if (WR(q)->q_next != NULL) {
5596 		/* This is a module close */
5597 		return (ip_modclose((ill_t *)q->q_ptr));
5598 	}
5599 
5600 	connp = q->q_ptr;
5601 	ip_quiesce_conn(connp);
5602 
5603 	qprocsoff(q);
5604 
5605 	/*
5606 	 * Now we are truly single threaded on this stream, and can
5607 	 * delete the things hanging off the connp, and finally the connp.
5608 	 * We removed this connp from the fanout list, it cannot be
5609 	 * accessed thru the fanouts, and we already waited for the
5610 	 * conn_ref to drop to 0. We are already in close, so
5611 	 * there cannot be any other thread from the top. qprocsoff
5612 	 * has completed, and service has completed or won't run in
5613 	 * future.
5614 	 */
5615 	ASSERT(connp->conn_ref == 1);
5616 
5617 	/*
5618 	 * A conn which was previously marked as IPCL_UDP cannot
5619 	 * retain the flag because it would have been cleared by
5620 	 * udp_close().
5621 	 */
5622 	ASSERT(!IPCL_IS_UDP(connp));
5623 
5624 	if (connp->conn_latch != NULL) {
5625 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5626 		connp->conn_latch = NULL;
5627 	}
5628 	if (connp->conn_policy != NULL) {
5629 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5630 		connp->conn_policy = NULL;
5631 	}
5632 	if (connp->conn_ipsec_opt_mp != NULL) {
5633 		freemsg(connp->conn_ipsec_opt_mp);
5634 		connp->conn_ipsec_opt_mp = NULL;
5635 	}
5636 
5637 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5638 
5639 	connp->conn_ref--;
5640 	ipcl_conn_destroy(connp);
5641 
5642 	q->q_ptr = WR(q)->q_ptr = NULL;
5643 	return (0);
5644 }
5645 
5646 int
5647 ip_snmpmod_close(queue_t *q)
5648 {
5649 	conn_t *connp = Q_TO_CONN(q);
5650 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5651 
5652 	qprocsoff(q);
5653 
5654 	if (connp->conn_flags & IPCL_UDPMOD)
5655 		udp_close_free(connp);
5656 
5657 	if (connp->conn_cred != NULL) {
5658 		crfree(connp->conn_cred);
5659 		connp->conn_cred = NULL;
5660 	}
5661 	CONN_DEC_REF(connp);
5662 	q->q_ptr = WR(q)->q_ptr = NULL;
5663 	return (0);
5664 }
5665 
5666 /*
5667  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5668  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5669  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5670  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5671  * queues as we never enqueue messages there and we don't handle any ioctls.
5672  * Everything else is freed.
5673  */
5674 void
5675 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5676 {
5677 	conn_t	*connp = q->q_ptr;
5678 	pfi_t	setfn;
5679 	pfi_t	getfn;
5680 
5681 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5682 
5683 	switch (DB_TYPE(mp)) {
5684 	case M_PROTO:
5685 	case M_PCPROTO:
5686 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5687 		    ((((union T_primitives *)mp->b_rptr)->type ==
5688 		    T_SVR4_OPTMGMT_REQ) ||
5689 		    (((union T_primitives *)mp->b_rptr)->type ==
5690 		    T_OPTMGMT_REQ))) {
5691 			/*
5692 			 * This is the only TPI primitive supported. Its
5693 			 * handling does not require tcp_t, but it does require
5694 			 * conn_t to check permissions.
5695 			 */
5696 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5697 
5698 			if (connp->conn_flags & IPCL_TCPMOD) {
5699 				setfn = tcp_snmp_set;
5700 				getfn = tcp_snmp_get;
5701 			} else {
5702 				setfn = udp_snmp_set;
5703 				getfn = udp_snmp_get;
5704 			}
5705 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5706 				freemsg(mp);
5707 				return;
5708 			}
5709 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5710 		    != NULL)
5711 			qreply(q, mp);
5712 		break;
5713 	case M_FLUSH:
5714 	case M_IOCTL:
5715 		putnext(q, mp);
5716 		break;
5717 	default:
5718 		freemsg(mp);
5719 		break;
5720 	}
5721 }
5722 
5723 /* Return the IP checksum for the IP header at "iph". */
5724 uint16_t
5725 ip_csum_hdr(ipha_t *ipha)
5726 {
5727 	uint16_t	*uph;
5728 	uint32_t	sum;
5729 	int		opt_len;
5730 
5731 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5732 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5733 	uph = (uint16_t *)ipha;
5734 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5735 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5736 	if (opt_len > 0) {
5737 		do {
5738 			sum += uph[10];
5739 			sum += uph[11];
5740 			uph += 2;
5741 		} while (--opt_len);
5742 	}
5743 	sum = (sum & 0xFFFF) + (sum >> 16);
5744 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5745 	if (sum == 0xffff)
5746 		sum = 0;
5747 	return ((uint16_t)sum);
5748 }
5749 
5750 /*
5751  * Called when the module is about to be unloaded
5752  */
5753 void
5754 ip_ddi_destroy(void)
5755 {
5756 	tnet_fini();
5757 
5758 	sctp_ddi_g_destroy();
5759 	tcp_ddi_g_destroy();
5760 	ipsec_policy_g_destroy();
5761 	ipcl_g_destroy();
5762 	ip_net_g_destroy();
5763 	ip_ire_g_fini();
5764 	inet_minor_destroy(ip_minor_arena);
5765 
5766 	netstack_unregister(NS_IP);
5767 }
5768 
5769 /*
5770  * First step in cleanup.
5771  */
5772 /* ARGSUSED */
5773 static void
5774 ip_stack_shutdown(netstackid_t stackid, void *arg)
5775 {
5776 	ip_stack_t *ipst = (ip_stack_t *)arg;
5777 
5778 #ifdef NS_DEBUG
5779 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5780 #endif
5781 
5782 	/* Get rid of loopback interfaces and their IREs */
5783 	ip_loopback_cleanup(ipst);
5784 }
5785 
5786 /*
5787  * Free the IP stack instance.
5788  */
5789 static void
5790 ip_stack_fini(netstackid_t stackid, void *arg)
5791 {
5792 	ip_stack_t *ipst = (ip_stack_t *)arg;
5793 	int ret;
5794 
5795 #ifdef NS_DEBUG
5796 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5797 #endif
5798 	ipv4_hook_destroy(ipst);
5799 	ipv6_hook_destroy(ipst);
5800 	ip_net_destroy(ipst);
5801 
5802 	rw_destroy(&ipst->ips_srcid_lock);
5803 
5804 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5805 	ipst->ips_ip_mibkp = NULL;
5806 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5807 	ipst->ips_icmp_mibkp = NULL;
5808 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5809 	ipst->ips_ip_kstat = NULL;
5810 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5811 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5812 	ipst->ips_ip6_kstat = NULL;
5813 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5814 
5815 	nd_free(&ipst->ips_ip_g_nd);
5816 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5817 	ipst->ips_param_arr = NULL;
5818 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5819 	ipst->ips_ndp_arr = NULL;
5820 
5821 	ip_mrouter_stack_destroy(ipst);
5822 
5823 	mutex_destroy(&ipst->ips_ip_mi_lock);
5824 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5825 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5826 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5827 
5828 	ret = untimeout(ipst->ips_igmp_timeout_id);
5829 	if (ret == -1) {
5830 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5831 	} else {
5832 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5833 		ipst->ips_igmp_timeout_id = 0;
5834 	}
5835 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5836 	if (ret == -1) {
5837 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5838 	} else {
5839 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5840 		ipst->ips_igmp_slowtimeout_id = 0;
5841 	}
5842 	ret = untimeout(ipst->ips_mld_timeout_id);
5843 	if (ret == -1) {
5844 		ASSERT(ipst->ips_mld_timeout_id == 0);
5845 	} else {
5846 		ASSERT(ipst->ips_mld_timeout_id != 0);
5847 		ipst->ips_mld_timeout_id = 0;
5848 	}
5849 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5850 	if (ret == -1) {
5851 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5852 	} else {
5853 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5854 		ipst->ips_mld_slowtimeout_id = 0;
5855 	}
5856 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5857 	if (ret == -1) {
5858 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5859 	} else {
5860 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5861 		ipst->ips_ip_ire_expire_id = 0;
5862 	}
5863 
5864 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5865 	mutex_destroy(&ipst->ips_mld_timer_lock);
5866 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5867 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5868 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5869 	rw_destroy(&ipst->ips_ill_g_lock);
5870 
5871 	ip_ire_fini(ipst);
5872 	ip6_asp_free(ipst);
5873 	conn_drain_fini(ipst);
5874 	ipcl_destroy(ipst);
5875 
5876 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5877 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5878 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5879 	ipst->ips_ndp4 = NULL;
5880 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5881 	ipst->ips_ndp6 = NULL;
5882 
5883 	if (ipst->ips_loopback_ksp != NULL) {
5884 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5885 		ipst->ips_loopback_ksp = NULL;
5886 	}
5887 
5888 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5889 	ipst->ips_phyint_g_list = NULL;
5890 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5891 	ipst->ips_ill_g_heads = NULL;
5892 
5893 	kmem_free(ipst, sizeof (*ipst));
5894 }
5895 
5896 /*
5897  * Called when the IP kernel module is loaded into the kernel
5898  */
5899 void
5900 ip_ddi_init(void)
5901 {
5902 	TCP6_MAJ = ddi_name_to_major(TCP6);
5903 	TCP_MAJ	= ddi_name_to_major(TCP);
5904 	SCTP_MAJ = ddi_name_to_major(SCTP);
5905 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5906 
5907 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5908 
5909 	/*
5910 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5911 	 * initial devices: ip, ip6, tcp, tcp6.
5912 	 */
5913 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5914 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5915 		cmn_err(CE_PANIC,
5916 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5917 	}
5918 
5919 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5920 
5921 	ipcl_g_init();
5922 	ip_ire_g_init();
5923 	ip_net_g_init();
5924 
5925 #ifdef ILL_DEBUG
5926 	/* Default cleanup function */
5927 	ip_cleanup_func = ip_thread_exit;
5928 #endif
5929 
5930 	/*
5931 	 * We want to be informed each time a stack is created or
5932 	 * destroyed in the kernel, so we can maintain the
5933 	 * set of udp_stack_t's.
5934 	 */
5935 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5936 	    ip_stack_fini);
5937 
5938 	ipsec_policy_g_init();
5939 	tcp_ddi_g_init();
5940 	sctp_ddi_g_init();
5941 
5942 	tnet_init();
5943 }
5944 
5945 /*
5946  * Initialize the IP stack instance.
5947  */
5948 static void *
5949 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5950 {
5951 	ip_stack_t	*ipst;
5952 	ipparam_t	*pa;
5953 	ipndp_t		*na;
5954 
5955 #ifdef NS_DEBUG
5956 	printf("ip_stack_init(stack %d)\n", stackid);
5957 #endif
5958 
5959 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5960 	ipst->ips_netstack = ns;
5961 
5962 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5963 	    KM_SLEEP);
5964 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5965 	    KM_SLEEP);
5966 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5967 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5968 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5969 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5970 
5971 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5972 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5973 	ipst->ips_igmp_deferred_next = INFINITY;
5974 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5975 	ipst->ips_mld_deferred_next = INFINITY;
5976 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5977 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5978 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5979 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5980 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5981 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5982 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5983 
5984 	ipcl_init(ipst);
5985 	ip_ire_init(ipst);
5986 	ip6_asp_init(ipst);
5987 	ipif_init(ipst);
5988 	conn_drain_init(ipst);
5989 	ip_mrouter_stack_init(ipst);
5990 
5991 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5992 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5993 
5994 	ipst->ips_ip_multirt_log_interval = 1000;
5995 
5996 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5997 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5998 	ipst->ips_ill_index = 1;
5999 
6000 	ipst->ips_saved_ip_g_forward = -1;
6001 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6002 
6003 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6004 	ipst->ips_param_arr = pa;
6005 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6006 
6007 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6008 	ipst->ips_ndp_arr = na;
6009 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6010 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6011 	    (caddr_t)&ipst->ips_ip_g_forward;
6012 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6013 	    (caddr_t)&ipst->ips_ipv6_forward;
6014 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6015 	    "ip_cgtp_filter") == 0);
6016 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6017 	    (caddr_t)&ip_cgtp_filter;
6018 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6019 	    "ipmp_hook_emulation") == 0);
6020 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6021 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6022 
6023 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6024 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6025 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6026 
6027 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6028 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6029 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6030 	ipst->ips_ip6_kstat =
6031 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6032 
6033 	ipst->ips_ipmp_enable_failback = B_TRUE;
6034 
6035 	ipst->ips_ip_src_id = 1;
6036 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6037 
6038 	ip_net_init(ipst, ns);
6039 	ipv4_hook_init(ipst);
6040 	ipv6_hook_init(ipst);
6041 
6042 	return (ipst);
6043 }
6044 
6045 /*
6046  * Allocate and initialize a DLPI template of the specified length.  (May be
6047  * called as writer.)
6048  */
6049 mblk_t *
6050 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6051 {
6052 	mblk_t	*mp;
6053 
6054 	mp = allocb(len, BPRI_MED);
6055 	if (!mp)
6056 		return (NULL);
6057 
6058 	/*
6059 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6060 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6061 	 * that other DLPI are M_PROTO.
6062 	 */
6063 	if (prim == DL_INFO_REQ) {
6064 		mp->b_datap->db_type = M_PCPROTO;
6065 	} else {
6066 		mp->b_datap->db_type = M_PROTO;
6067 	}
6068 
6069 	mp->b_wptr = mp->b_rptr + len;
6070 	bzero(mp->b_rptr, len);
6071 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6072 	return (mp);
6073 }
6074 
6075 const char *
6076 dlpi_prim_str(int prim)
6077 {
6078 	switch (prim) {
6079 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6080 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6081 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6082 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6083 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6084 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6085 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6086 	case DL_OK_ACK:		return ("DL_OK_ACK");
6087 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6088 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6089 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6090 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6091 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6092 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6093 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6094 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6095 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6096 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6097 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6098 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6099 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6100 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6101 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6102 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6103 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6104 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6105 	default:		return ("<unknown primitive>");
6106 	}
6107 }
6108 
6109 const char *
6110 dlpi_err_str(int err)
6111 {
6112 	switch (err) {
6113 	case DL_ACCESS:		return ("DL_ACCESS");
6114 	case DL_BADADDR:	return ("DL_BADADDR");
6115 	case DL_BADCORR:	return ("DL_BADCORR");
6116 	case DL_BADDATA:	return ("DL_BADDATA");
6117 	case DL_BADPPA:		return ("DL_BADPPA");
6118 	case DL_BADPRIM:	return ("DL_BADPRIM");
6119 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6120 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6121 	case DL_BADSAP:		return ("DL_BADSAP");
6122 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6123 	case DL_BOUND:		return ("DL_BOUND");
6124 	case DL_INITFAILED:	return ("DL_INITFAILED");
6125 	case DL_NOADDR:		return ("DL_NOADDR");
6126 	case DL_NOTINIT:	return ("DL_NOTINIT");
6127 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6128 	case DL_SYSERR:		return ("DL_SYSERR");
6129 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6130 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6131 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6132 	case DL_TOOMANY:	return ("DL_TOOMANY");
6133 	case DL_NOTENAB:	return ("DL_NOTENAB");
6134 	case DL_BUSY:		return ("DL_BUSY");
6135 	case DL_NOAUTO:		return ("DL_NOAUTO");
6136 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6137 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6138 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6139 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6140 	case DL_PENDING:	return ("DL_PENDING");
6141 	default:		return ("<unknown error>");
6142 	}
6143 }
6144 
6145 /*
6146  * Debug formatting routine.  Returns a character string representation of the
6147  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6148  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6149  *
6150  * Once the ndd table-printing interfaces are removed, this can be changed to
6151  * standard dotted-decimal form.
6152  */
6153 char *
6154 ip_dot_addr(ipaddr_t addr, char *buf)
6155 {
6156 	uint8_t *ap = (uint8_t *)&addr;
6157 
6158 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6159 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6160 	return (buf);
6161 }
6162 
6163 /*
6164  * Write the given MAC address as a printable string in the usual colon-
6165  * separated format.
6166  */
6167 const char *
6168 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6169 {
6170 	char *bp;
6171 
6172 	if (alen == 0 || buflen < 4)
6173 		return ("?");
6174 	bp = buf;
6175 	for (;;) {
6176 		/*
6177 		 * If there are more MAC address bytes available, but we won't
6178 		 * have any room to print them, then add "..." to the string
6179 		 * instead.  See below for the 'magic number' explanation.
6180 		 */
6181 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6182 			(void) strcpy(bp, "...");
6183 			break;
6184 		}
6185 		(void) sprintf(bp, "%02x", *addr++);
6186 		bp += 2;
6187 		if (--alen == 0)
6188 			break;
6189 		*bp++ = ':';
6190 		buflen -= 3;
6191 		/*
6192 		 * At this point, based on the first 'if' statement above,
6193 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6194 		 * buflen >= 4.  The first case leaves room for the final "xx"
6195 		 * number and trailing NUL byte.  The second leaves room for at
6196 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6197 		 * that statement.
6198 		 */
6199 	}
6200 	return (buf);
6201 }
6202 
6203 /*
6204  * Send an ICMP error after patching up the packet appropriately.  Returns
6205  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6206  */
6207 static boolean_t
6208 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6209     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6210     zoneid_t zoneid, ip_stack_t *ipst)
6211 {
6212 	ipha_t *ipha;
6213 	mblk_t *first_mp;
6214 	boolean_t secure;
6215 	unsigned char db_type;
6216 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6217 
6218 	first_mp = mp;
6219 	if (mctl_present) {
6220 		mp = mp->b_cont;
6221 		secure = ipsec_in_is_secure(first_mp);
6222 		ASSERT(mp != NULL);
6223 	} else {
6224 		/*
6225 		 * If this is an ICMP error being reported - which goes
6226 		 * up as M_CTLs, we need to convert them to M_DATA till
6227 		 * we finish checking with global policy because
6228 		 * ipsec_check_global_policy() assumes M_DATA as clear
6229 		 * and M_CTL as secure.
6230 		 */
6231 		db_type = DB_TYPE(mp);
6232 		DB_TYPE(mp) = M_DATA;
6233 		secure = B_FALSE;
6234 	}
6235 	/*
6236 	 * We are generating an icmp error for some inbound packet.
6237 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6238 	 * Before we generate an error, check with global policy
6239 	 * to see whether this is allowed to enter the system. As
6240 	 * there is no "conn", we are checking with global policy.
6241 	 */
6242 	ipha = (ipha_t *)mp->b_rptr;
6243 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6244 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6245 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6246 		if (first_mp == NULL)
6247 			return (B_FALSE);
6248 	}
6249 
6250 	if (!mctl_present)
6251 		DB_TYPE(mp) = db_type;
6252 
6253 	if (flags & IP_FF_SEND_ICMP) {
6254 		if (flags & IP_FF_HDR_COMPLETE) {
6255 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6256 				freemsg(first_mp);
6257 				return (B_TRUE);
6258 			}
6259 		}
6260 		if (flags & IP_FF_CKSUM) {
6261 			/*
6262 			 * Have to correct checksum since
6263 			 * the packet might have been
6264 			 * fragmented and the reassembly code in ip_rput
6265 			 * does not restore the IP checksum.
6266 			 */
6267 			ipha->ipha_hdr_checksum = 0;
6268 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6269 		}
6270 		switch (icmp_type) {
6271 		case ICMP_DEST_UNREACHABLE:
6272 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6273 			    ipst);
6274 			break;
6275 		default:
6276 			freemsg(first_mp);
6277 			break;
6278 		}
6279 	} else {
6280 		freemsg(first_mp);
6281 		return (B_FALSE);
6282 	}
6283 
6284 	return (B_TRUE);
6285 }
6286 
6287 /*
6288  * Used to send an ICMP error message when a packet is received for
6289  * a protocol that is not supported. The mblk passed as argument
6290  * is consumed by this function.
6291  */
6292 void
6293 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6294     ip_stack_t *ipst)
6295 {
6296 	mblk_t *mp;
6297 	ipha_t *ipha;
6298 	ill_t *ill;
6299 	ipsec_in_t *ii;
6300 
6301 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6302 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6303 
6304 	mp = ipsec_mp->b_cont;
6305 	ipsec_mp->b_cont = NULL;
6306 	ipha = (ipha_t *)mp->b_rptr;
6307 	/* Get ill from index in ipsec_in_t. */
6308 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6309 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6310 	    ipst);
6311 	if (ill != NULL) {
6312 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6313 			if (ip_fanout_send_icmp(q, mp, flags,
6314 			    ICMP_DEST_UNREACHABLE,
6315 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6316 				BUMP_MIB(ill->ill_ip_mib,
6317 				    ipIfStatsInUnknownProtos);
6318 			}
6319 		} else {
6320 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6321 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6322 			    0, B_FALSE, zoneid, ipst)) {
6323 				BUMP_MIB(ill->ill_ip_mib,
6324 				    ipIfStatsInUnknownProtos);
6325 			}
6326 		}
6327 		ill_refrele(ill);
6328 	} else { /* re-link for the freemsg() below. */
6329 		ipsec_mp->b_cont = mp;
6330 	}
6331 
6332 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6333 	freemsg(ipsec_mp);
6334 }
6335 
6336 /*
6337  * See if the inbound datagram has had IPsec processing applied to it.
6338  */
6339 boolean_t
6340 ipsec_in_is_secure(mblk_t *ipsec_mp)
6341 {
6342 	ipsec_in_t *ii;
6343 
6344 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6345 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6346 
6347 	if (ii->ipsec_in_loopback) {
6348 		return (ii->ipsec_in_secure);
6349 	} else {
6350 		return (ii->ipsec_in_ah_sa != NULL ||
6351 		    ii->ipsec_in_esp_sa != NULL ||
6352 		    ii->ipsec_in_decaps);
6353 	}
6354 }
6355 
6356 /*
6357  * Handle protocols with which IP is less intimate.  There
6358  * can be more than one stream bound to a particular
6359  * protocol.  When this is the case, normally each one gets a copy
6360  * of any incoming packets.
6361  *
6362  * IPSEC NOTE :
6363  *
6364  * Don't allow a secure packet going up a non-secure connection.
6365  * We don't allow this because
6366  *
6367  * 1) Reply might go out in clear which will be dropped at
6368  *    the sending side.
6369  * 2) If the reply goes out in clear it will give the
6370  *    adversary enough information for getting the key in
6371  *    most of the cases.
6372  *
6373  * Moreover getting a secure packet when we expect clear
6374  * implies that SA's were added without checking for
6375  * policy on both ends. This should not happen once ISAKMP
6376  * is used to negotiate SAs as SAs will be added only after
6377  * verifying the policy.
6378  *
6379  * NOTE : If the packet was tunneled and not multicast we only send
6380  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6381  * back to delivering packets to AF_INET6 raw sockets.
6382  *
6383  * IPQoS Notes:
6384  * Once we have determined the client, invoke IPPF processing.
6385  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6386  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6387  * ip_policy will be false.
6388  *
6389  * Zones notes:
6390  * Currently only applications in the global zone can create raw sockets for
6391  * protocols other than ICMP. So unlike the broadcast / multicast case of
6392  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6393  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6394  */
6395 static void
6396 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6397     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6398     zoneid_t zoneid)
6399 {
6400 	queue_t	*rq;
6401 	mblk_t	*mp1, *first_mp1;
6402 	uint_t	protocol = ipha->ipha_protocol;
6403 	ipaddr_t dst;
6404 	boolean_t one_only;
6405 	mblk_t *first_mp = mp;
6406 	boolean_t secure;
6407 	uint32_t ill_index;
6408 	conn_t	*connp, *first_connp, *next_connp;
6409 	connf_t	*connfp;
6410 	boolean_t shared_addr;
6411 	mib2_ipIfStatsEntry_t *mibptr;
6412 	ip_stack_t *ipst = recv_ill->ill_ipst;
6413 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6414 
6415 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6416 	if (mctl_present) {
6417 		mp = first_mp->b_cont;
6418 		secure = ipsec_in_is_secure(first_mp);
6419 		ASSERT(mp != NULL);
6420 	} else {
6421 		secure = B_FALSE;
6422 	}
6423 	dst = ipha->ipha_dst;
6424 	/*
6425 	 * If the packet was tunneled and not multicast we only send to it
6426 	 * the first match.
6427 	 */
6428 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6429 	    !CLASSD(dst));
6430 
6431 	shared_addr = (zoneid == ALL_ZONES);
6432 	if (shared_addr) {
6433 		/*
6434 		 * We don't allow multilevel ports for raw IP, so no need to
6435 		 * check for that here.
6436 		 */
6437 		zoneid = tsol_packet_to_zoneid(mp);
6438 	}
6439 
6440 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6441 	mutex_enter(&connfp->connf_lock);
6442 	connp = connfp->connf_head;
6443 	for (connp = connfp->connf_head; connp != NULL;
6444 	    connp = connp->conn_next) {
6445 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6446 		    zoneid) &&
6447 		    (!is_system_labeled() ||
6448 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6449 		    connp))) {
6450 			break;
6451 		}
6452 	}
6453 
6454 	if (connp == NULL || connp->conn_upq == NULL) {
6455 		/*
6456 		 * No one bound to these addresses.  Is
6457 		 * there a client that wants all
6458 		 * unclaimed datagrams?
6459 		 */
6460 		mutex_exit(&connfp->connf_lock);
6461 		/*
6462 		 * Check for IPPROTO_ENCAP...
6463 		 */
6464 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6465 			/*
6466 			 * If an IPsec mblk is here on a multicast
6467 			 * tunnel (using ip_mroute stuff), check policy here,
6468 			 * THEN ship off to ip_mroute_decap().
6469 			 *
6470 			 * BTW,  If I match a configured IP-in-IP
6471 			 * tunnel, this path will not be reached, and
6472 			 * ip_mroute_decap will never be called.
6473 			 */
6474 			first_mp = ipsec_check_global_policy(first_mp, connp,
6475 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6476 			if (first_mp != NULL) {
6477 				if (mctl_present)
6478 					freeb(first_mp);
6479 				ip_mroute_decap(q, mp, ill);
6480 			} /* Else we already freed everything! */
6481 		} else {
6482 			/*
6483 			 * Otherwise send an ICMP protocol unreachable.
6484 			 */
6485 			if (ip_fanout_send_icmp(q, first_mp, flags,
6486 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6487 			    mctl_present, zoneid, ipst)) {
6488 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6489 			}
6490 		}
6491 		return;
6492 	}
6493 	CONN_INC_REF(connp);
6494 	first_connp = connp;
6495 
6496 	/*
6497 	 * Only send message to one tunnel driver by immediately
6498 	 * terminating the loop.
6499 	 */
6500 	connp = one_only ? NULL : connp->conn_next;
6501 
6502 	for (;;) {
6503 		while (connp != NULL) {
6504 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6505 			    flags, zoneid) &&
6506 			    (!is_system_labeled() ||
6507 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6508 			    shared_addr, connp)))
6509 				break;
6510 			connp = connp->conn_next;
6511 		}
6512 
6513 		/*
6514 		 * Copy the packet.
6515 		 */
6516 		if (connp == NULL || connp->conn_upq == NULL ||
6517 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6518 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6519 			/*
6520 			 * No more interested clients or memory
6521 			 * allocation failed
6522 			 */
6523 			connp = first_connp;
6524 			break;
6525 		}
6526 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6527 		CONN_INC_REF(connp);
6528 		mutex_exit(&connfp->connf_lock);
6529 		rq = connp->conn_rq;
6530 		if (!canputnext(rq)) {
6531 			if (flags & IP_FF_RAWIP) {
6532 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6533 			} else {
6534 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6535 			}
6536 
6537 			freemsg(first_mp1);
6538 		} else {
6539 			/*
6540 			 * Don't enforce here if we're an actual tunnel -
6541 			 * let "tun" do it instead.
6542 			 */
6543 			if (!IPCL_IS_IPTUN(connp) &&
6544 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6545 			    secure)) {
6546 				first_mp1 = ipsec_check_inbound_policy
6547 				    (first_mp1, connp, ipha, NULL,
6548 				    mctl_present);
6549 			}
6550 			if (first_mp1 != NULL) {
6551 				int in_flags = 0;
6552 				/*
6553 				 * ip_fanout_proto also gets called from
6554 				 * icmp_inbound_error_fanout, in which case
6555 				 * the msg type is M_CTL.  Don't add info
6556 				 * in this case for the time being. In future
6557 				 * when there is a need for knowing the
6558 				 * inbound iface index for ICMP error msgs,
6559 				 * then this can be changed.
6560 				 */
6561 				if (connp->conn_recvif)
6562 					in_flags = IPF_RECVIF;
6563 				/*
6564 				 * The ULP may support IP_RECVPKTINFO for both
6565 				 * IP v4 and v6 so pass the appropriate argument
6566 				 * based on conn IP version.
6567 				 */
6568 				if (connp->conn_ip_recvpktinfo) {
6569 					if (connp->conn_af_isv6) {
6570 						/*
6571 						 * V6 only needs index
6572 						 */
6573 						in_flags |= IPF_RECVIF;
6574 					} else {
6575 						/*
6576 						 * V4 needs index +
6577 						 * matching address.
6578 						 */
6579 						in_flags |= IPF_RECVADDR;
6580 					}
6581 				}
6582 				if ((in_flags != 0) &&
6583 				    (mp->b_datap->db_type != M_CTL)) {
6584 					/*
6585 					 * the actual data will be
6586 					 * contained in b_cont upon
6587 					 * successful return of the
6588 					 * following call else
6589 					 * original mblk is returned
6590 					 */
6591 					ASSERT(recv_ill != NULL);
6592 					mp1 = ip_add_info(mp1, recv_ill,
6593 					    in_flags, IPCL_ZONEID(connp), ipst);
6594 				}
6595 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6596 				if (mctl_present)
6597 					freeb(first_mp1);
6598 				putnext(rq, mp1);
6599 			}
6600 		}
6601 		mutex_enter(&connfp->connf_lock);
6602 		/* Follow the next pointer before releasing the conn. */
6603 		next_connp = connp->conn_next;
6604 		CONN_DEC_REF(connp);
6605 		connp = next_connp;
6606 	}
6607 
6608 	/* Last one.  Send it upstream. */
6609 	mutex_exit(&connfp->connf_lock);
6610 
6611 	/*
6612 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6613 	 * will be set to false.
6614 	 */
6615 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6616 		ill_index = ill->ill_phyint->phyint_ifindex;
6617 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6618 		if (mp == NULL) {
6619 			CONN_DEC_REF(connp);
6620 			if (mctl_present) {
6621 				freeb(first_mp);
6622 			}
6623 			return;
6624 		}
6625 	}
6626 
6627 	rq = connp->conn_rq;
6628 	if (!canputnext(rq)) {
6629 		if (flags & IP_FF_RAWIP) {
6630 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6631 		} else {
6632 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6633 		}
6634 
6635 		freemsg(first_mp);
6636 	} else {
6637 		if (IPCL_IS_IPTUN(connp)) {
6638 			/*
6639 			 * Tunneled packet.  We enforce policy in the tunnel
6640 			 * module itself.
6641 			 *
6642 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6643 			 * a policy check.
6644 			 */
6645 			putnext(rq, first_mp);
6646 			CONN_DEC_REF(connp);
6647 			return;
6648 		}
6649 
6650 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6651 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6652 			    ipha, NULL, mctl_present);
6653 		}
6654 
6655 		if (first_mp != NULL) {
6656 			int in_flags = 0;
6657 
6658 			/*
6659 			 * ip_fanout_proto also gets called
6660 			 * from icmp_inbound_error_fanout, in
6661 			 * which case the msg type is M_CTL.
6662 			 * Don't add info in this case for time
6663 			 * being. In future when there is a
6664 			 * need for knowing the inbound iface
6665 			 * index for ICMP error msgs, then this
6666 			 * can be changed
6667 			 */
6668 			if (connp->conn_recvif)
6669 				in_flags = IPF_RECVIF;
6670 			if (connp->conn_ip_recvpktinfo) {
6671 				if (connp->conn_af_isv6) {
6672 					/*
6673 					 * V6 only needs index
6674 					 */
6675 					in_flags |= IPF_RECVIF;
6676 				} else {
6677 					/*
6678 					 * V4 needs index +
6679 					 * matching address.
6680 					 */
6681 					in_flags |= IPF_RECVADDR;
6682 				}
6683 			}
6684 			if ((in_flags != 0) &&
6685 			    (mp->b_datap->db_type != M_CTL)) {
6686 
6687 				/*
6688 				 * the actual data will be contained in
6689 				 * b_cont upon successful return
6690 				 * of the following call else original
6691 				 * mblk is returned
6692 				 */
6693 				ASSERT(recv_ill != NULL);
6694 				mp = ip_add_info(mp, recv_ill,
6695 				    in_flags, IPCL_ZONEID(connp), ipst);
6696 			}
6697 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6698 			putnext(rq, mp);
6699 			if (mctl_present)
6700 				freeb(first_mp);
6701 		}
6702 	}
6703 	CONN_DEC_REF(connp);
6704 }
6705 
6706 /*
6707  * Fanout for TCP packets
6708  * The caller puts <fport, lport> in the ports parameter.
6709  *
6710  * IPQoS Notes
6711  * Before sending it to the client, invoke IPPF processing.
6712  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6713  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6714  * ip_policy is false.
6715  */
6716 static void
6717 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6718     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6719 {
6720 	mblk_t  *first_mp;
6721 	boolean_t secure;
6722 	uint32_t ill_index;
6723 	int	ip_hdr_len;
6724 	tcph_t	*tcph;
6725 	boolean_t syn_present = B_FALSE;
6726 	conn_t	*connp;
6727 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6728 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6729 
6730 	ASSERT(recv_ill != NULL);
6731 
6732 	first_mp = mp;
6733 	if (mctl_present) {
6734 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6735 		mp = first_mp->b_cont;
6736 		secure = ipsec_in_is_secure(first_mp);
6737 		ASSERT(mp != NULL);
6738 	} else {
6739 		secure = B_FALSE;
6740 	}
6741 
6742 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6743 
6744 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6745 	    zoneid, ipst)) == NULL) {
6746 		/*
6747 		 * No connected connection or listener. Send a
6748 		 * TH_RST via tcp_xmit_listeners_reset.
6749 		 */
6750 
6751 		/* Initiate IPPf processing, if needed. */
6752 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6753 			uint32_t ill_index;
6754 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6755 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6756 			if (first_mp == NULL)
6757 				return;
6758 		}
6759 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6760 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6761 		    zoneid));
6762 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6763 		    ipst->ips_netstack->netstack_tcp);
6764 		return;
6765 	}
6766 
6767 	/*
6768 	 * Allocate the SYN for the TCP connection here itself
6769 	 */
6770 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6771 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6772 		if (IPCL_IS_TCP(connp)) {
6773 			squeue_t *sqp;
6774 
6775 			/*
6776 			 * For fused tcp loopback, assign the eager's
6777 			 * squeue to be that of the active connect's.
6778 			 * Note that we don't check for IP_FF_LOOPBACK
6779 			 * here since this routine gets called only
6780 			 * for loopback (unlike the IPv6 counterpart).
6781 			 */
6782 			ASSERT(Q_TO_CONN(q) != NULL);
6783 			if (do_tcp_fusion &&
6784 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6785 			    !secure &&
6786 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6787 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6788 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6789 				sqp = Q_TO_CONN(q)->conn_sqp;
6790 			} else {
6791 				sqp = IP_SQUEUE_GET(lbolt);
6792 			}
6793 
6794 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6795 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6796 			syn_present = B_TRUE;
6797 		}
6798 	}
6799 
6800 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6801 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6802 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6803 		if ((flags & TH_RST) || (flags & TH_URG)) {
6804 			CONN_DEC_REF(connp);
6805 			freemsg(first_mp);
6806 			return;
6807 		}
6808 		if (flags & TH_ACK) {
6809 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6810 			    ipst->ips_netstack->netstack_tcp);
6811 			CONN_DEC_REF(connp);
6812 			return;
6813 		}
6814 
6815 		CONN_DEC_REF(connp);
6816 		freemsg(first_mp);
6817 		return;
6818 	}
6819 
6820 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6821 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6822 		    NULL, mctl_present);
6823 		if (first_mp == NULL) {
6824 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6825 			CONN_DEC_REF(connp);
6826 			return;
6827 		}
6828 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6829 			ASSERT(syn_present);
6830 			if (mctl_present) {
6831 				ASSERT(first_mp != mp);
6832 				first_mp->b_datap->db_struioflag |=
6833 				    STRUIO_POLICY;
6834 			} else {
6835 				ASSERT(first_mp == mp);
6836 				mp->b_datap->db_struioflag &=
6837 				    ~STRUIO_EAGER;
6838 				mp->b_datap->db_struioflag |=
6839 				    STRUIO_POLICY;
6840 			}
6841 		} else {
6842 			/*
6843 			 * Discard first_mp early since we're dealing with a
6844 			 * fully-connected conn_t and tcp doesn't do policy in
6845 			 * this case.
6846 			 */
6847 			if (mctl_present) {
6848 				freeb(first_mp);
6849 				mctl_present = B_FALSE;
6850 			}
6851 			first_mp = mp;
6852 		}
6853 	}
6854 
6855 	/*
6856 	 * Initiate policy processing here if needed. If we get here from
6857 	 * icmp_inbound_error_fanout, ip_policy is false.
6858 	 */
6859 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6860 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6861 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6862 		if (mp == NULL) {
6863 			CONN_DEC_REF(connp);
6864 			if (mctl_present)
6865 				freeb(first_mp);
6866 			return;
6867 		} else if (mctl_present) {
6868 			ASSERT(first_mp != mp);
6869 			first_mp->b_cont = mp;
6870 		} else {
6871 			first_mp = mp;
6872 		}
6873 	}
6874 
6875 
6876 
6877 	/* Handle socket options. */
6878 	if (!syn_present &&
6879 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6880 		/* Add header */
6881 		ASSERT(recv_ill != NULL);
6882 		/*
6883 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6884 		 * IPF_RECVIF.
6885 		 */
6886 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6887 		    ipst);
6888 		if (mp == NULL) {
6889 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6890 			CONN_DEC_REF(connp);
6891 			if (mctl_present)
6892 				freeb(first_mp);
6893 			return;
6894 		} else if (mctl_present) {
6895 			/*
6896 			 * ip_add_info might return a new mp.
6897 			 */
6898 			ASSERT(first_mp != mp);
6899 			first_mp->b_cont = mp;
6900 		} else {
6901 			first_mp = mp;
6902 		}
6903 	}
6904 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6905 	if (IPCL_IS_TCP(connp)) {
6906 		/* do not drain, certain use cases can blow the stack */
6907 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6908 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6909 	} else {
6910 		putnext(connp->conn_rq, first_mp);
6911 		CONN_DEC_REF(connp);
6912 	}
6913 }
6914 
6915 /*
6916  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6917  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6918  * Caller is responsible for dropping references to the conn, and freeing
6919  * first_mp.
6920  *
6921  * IPQoS Notes
6922  * Before sending it to the client, invoke IPPF processing. Policy processing
6923  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6924  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6925  * ip_wput_local, ip_policy is false.
6926  */
6927 static void
6928 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6929     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6930     boolean_t ip_policy)
6931 {
6932 	boolean_t	mctl_present = (first_mp != NULL);
6933 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6934 	uint32_t	ill_index;
6935 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6936 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6937 
6938 	ASSERT(ill != NULL);
6939 
6940 	if (mctl_present)
6941 		first_mp->b_cont = mp;
6942 	else
6943 		first_mp = mp;
6944 
6945 	if (CONN_UDP_FLOWCTLD(connp)) {
6946 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6947 		freemsg(first_mp);
6948 		return;
6949 	}
6950 
6951 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6952 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6953 		    NULL, mctl_present);
6954 		if (first_mp == NULL) {
6955 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6956 			return;	/* Freed by ipsec_check_inbound_policy(). */
6957 		}
6958 	}
6959 	if (mctl_present)
6960 		freeb(first_mp);
6961 
6962 	/* Handle options. */
6963 	if (connp->conn_recvif)
6964 		in_flags = IPF_RECVIF;
6965 	/*
6966 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6967 	 * passed to ip_add_info is based on IP version of connp.
6968 	 */
6969 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6970 		if (connp->conn_af_isv6) {
6971 			/*
6972 			 * V6 only needs index
6973 			 */
6974 			in_flags |= IPF_RECVIF;
6975 		} else {
6976 			/*
6977 			 * V4 needs index + matching address.
6978 			 */
6979 			in_flags |= IPF_RECVADDR;
6980 		}
6981 	}
6982 
6983 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6984 		in_flags |= IPF_RECVSLLA;
6985 
6986 	/*
6987 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6988 	 * freed if the packet is dropped. The caller will do so.
6989 	 */
6990 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6991 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6992 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6993 		if (mp == NULL) {
6994 			return;
6995 		}
6996 	}
6997 	if ((in_flags != 0) &&
6998 	    (mp->b_datap->db_type != M_CTL)) {
6999 		/*
7000 		 * The actual data will be contained in b_cont
7001 		 * upon successful return of the following call
7002 		 * else original mblk is returned
7003 		 */
7004 		ASSERT(recv_ill != NULL);
7005 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7006 		    ipst);
7007 	}
7008 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7009 	/* Send it upstream */
7010 	CONN_UDP_RECV(connp, mp);
7011 }
7012 
7013 /*
7014  * Fanout for UDP packets.
7015  * The caller puts <fport, lport> in the ports parameter.
7016  *
7017  * If SO_REUSEADDR is set all multicast and broadcast packets
7018  * will be delivered to all streams bound to the same port.
7019  *
7020  * Zones notes:
7021  * Multicast and broadcast packets will be distributed to streams in all zones.
7022  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7023  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7024  * packets. To maintain this behavior with multiple zones, the conns are grouped
7025  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7026  * each zone. If unset, all the following conns in the same zone are skipped.
7027  */
7028 static void
7029 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7030     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7031     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7032 {
7033 	uint32_t	dstport, srcport;
7034 	ipaddr_t	dst;
7035 	mblk_t		*first_mp;
7036 	boolean_t	secure;
7037 	in6_addr_t	v6src;
7038 	conn_t		*connp;
7039 	connf_t		*connfp;
7040 	conn_t		*first_connp;
7041 	conn_t		*next_connp;
7042 	mblk_t		*mp1, *first_mp1;
7043 	ipaddr_t	src;
7044 	zoneid_t	last_zoneid;
7045 	boolean_t	reuseaddr;
7046 	boolean_t	shared_addr;
7047 	ip_stack_t	*ipst;
7048 
7049 	ASSERT(recv_ill != NULL);
7050 	ipst = recv_ill->ill_ipst;
7051 
7052 	first_mp = mp;
7053 	if (mctl_present) {
7054 		mp = first_mp->b_cont;
7055 		first_mp->b_cont = NULL;
7056 		secure = ipsec_in_is_secure(first_mp);
7057 		ASSERT(mp != NULL);
7058 	} else {
7059 		first_mp = NULL;
7060 		secure = B_FALSE;
7061 	}
7062 
7063 	/* Extract ports in net byte order */
7064 	dstport = htons(ntohl(ports) & 0xFFFF);
7065 	srcport = htons(ntohl(ports) >> 16);
7066 	dst = ipha->ipha_dst;
7067 	src = ipha->ipha_src;
7068 
7069 	shared_addr = (zoneid == ALL_ZONES);
7070 	if (shared_addr) {
7071 		/*
7072 		 * No need to handle exclusive-stack zones since ALL_ZONES
7073 		 * only applies to the shared stack.
7074 		 */
7075 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7076 		if (zoneid == ALL_ZONES)
7077 			zoneid = tsol_packet_to_zoneid(mp);
7078 	}
7079 
7080 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7081 	mutex_enter(&connfp->connf_lock);
7082 	connp = connfp->connf_head;
7083 	if (!broadcast && !CLASSD(dst)) {
7084 		/*
7085 		 * Not broadcast or multicast. Send to the one (first)
7086 		 * client we find. No need to check conn_wantpacket()
7087 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7088 		 * IPv4 unicast packets.
7089 		 */
7090 		while ((connp != NULL) &&
7091 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7092 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7093 			connp = connp->conn_next;
7094 		}
7095 
7096 		if (connp == NULL || connp->conn_upq == NULL)
7097 			goto notfound;
7098 
7099 		if (is_system_labeled() &&
7100 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7101 		    connp))
7102 			goto notfound;
7103 
7104 		CONN_INC_REF(connp);
7105 		mutex_exit(&connfp->connf_lock);
7106 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7107 		    flags, recv_ill, ip_policy);
7108 		IP_STAT(ipst, ip_udp_fannorm);
7109 		CONN_DEC_REF(connp);
7110 		return;
7111 	}
7112 
7113 	/*
7114 	 * Broadcast and multicast case
7115 	 *
7116 	 * Need to check conn_wantpacket().
7117 	 * If SO_REUSEADDR has been set on the first we send the
7118 	 * packet to all clients that have joined the group and
7119 	 * match the port.
7120 	 */
7121 
7122 	while (connp != NULL) {
7123 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7124 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7125 		    (!is_system_labeled() ||
7126 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7127 		    connp)))
7128 			break;
7129 		connp = connp->conn_next;
7130 	}
7131 
7132 	if (connp == NULL || connp->conn_upq == NULL)
7133 		goto notfound;
7134 
7135 	first_connp = connp;
7136 	/*
7137 	 * When SO_REUSEADDR is not set, send the packet only to the first
7138 	 * matching connection in its zone by keeping track of the zoneid.
7139 	 */
7140 	reuseaddr = first_connp->conn_reuseaddr;
7141 	last_zoneid = first_connp->conn_zoneid;
7142 
7143 	CONN_INC_REF(connp);
7144 	connp = connp->conn_next;
7145 	for (;;) {
7146 		while (connp != NULL) {
7147 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7148 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7149 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7150 			    (!is_system_labeled() ||
7151 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7152 			    shared_addr, connp)))
7153 				break;
7154 			connp = connp->conn_next;
7155 		}
7156 		/*
7157 		 * Just copy the data part alone. The mctl part is
7158 		 * needed just for verifying policy and it is never
7159 		 * sent up.
7160 		 */
7161 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7162 		    ((mp1 = copymsg(mp)) == NULL))) {
7163 			/*
7164 			 * No more interested clients or memory
7165 			 * allocation failed
7166 			 */
7167 			connp = first_connp;
7168 			break;
7169 		}
7170 		if (connp->conn_zoneid != last_zoneid) {
7171 			/*
7172 			 * Update the zoneid so that the packet isn't sent to
7173 			 * any more conns in the same zone unless SO_REUSEADDR
7174 			 * is set.
7175 			 */
7176 			reuseaddr = connp->conn_reuseaddr;
7177 			last_zoneid = connp->conn_zoneid;
7178 		}
7179 		if (first_mp != NULL) {
7180 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7181 			    ipsec_info_type == IPSEC_IN);
7182 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7183 			    ipst->ips_netstack);
7184 			if (first_mp1 == NULL) {
7185 				freemsg(mp1);
7186 				connp = first_connp;
7187 				break;
7188 			}
7189 		} else {
7190 			first_mp1 = NULL;
7191 		}
7192 		CONN_INC_REF(connp);
7193 		mutex_exit(&connfp->connf_lock);
7194 		/*
7195 		 * IPQoS notes: We don't send the packet for policy
7196 		 * processing here, will do it for the last one (below).
7197 		 * i.e. we do it per-packet now, but if we do policy
7198 		 * processing per-conn, then we would need to do it
7199 		 * here too.
7200 		 */
7201 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7202 		    ipha, flags, recv_ill, B_FALSE);
7203 		mutex_enter(&connfp->connf_lock);
7204 		/* Follow the next pointer before releasing the conn. */
7205 		next_connp = connp->conn_next;
7206 		IP_STAT(ipst, ip_udp_fanmb);
7207 		CONN_DEC_REF(connp);
7208 		connp = next_connp;
7209 	}
7210 
7211 	/* Last one.  Send it upstream. */
7212 	mutex_exit(&connfp->connf_lock);
7213 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7214 	    recv_ill, ip_policy);
7215 	IP_STAT(ipst, ip_udp_fanmb);
7216 	CONN_DEC_REF(connp);
7217 	return;
7218 
7219 notfound:
7220 
7221 	mutex_exit(&connfp->connf_lock);
7222 	IP_STAT(ipst, ip_udp_fanothers);
7223 	/*
7224 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7225 	 * have already been matched above, since they live in the IPv4
7226 	 * fanout tables. This implies we only need to
7227 	 * check for IPv6 in6addr_any endpoints here.
7228 	 * Thus we compare using ipv6_all_zeros instead of the destination
7229 	 * address, except for the multicast group membership lookup which
7230 	 * uses the IPv4 destination.
7231 	 */
7232 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7233 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7234 	mutex_enter(&connfp->connf_lock);
7235 	connp = connfp->connf_head;
7236 	if (!broadcast && !CLASSD(dst)) {
7237 		while (connp != NULL) {
7238 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7239 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7240 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7241 			    !connp->conn_ipv6_v6only)
7242 				break;
7243 			connp = connp->conn_next;
7244 		}
7245 
7246 		if (connp != NULL && is_system_labeled() &&
7247 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7248 		    connp))
7249 			connp = NULL;
7250 
7251 		if (connp == NULL || connp->conn_upq == NULL) {
7252 			/*
7253 			 * No one bound to this port.  Is
7254 			 * there a client that wants all
7255 			 * unclaimed datagrams?
7256 			 */
7257 			mutex_exit(&connfp->connf_lock);
7258 
7259 			if (mctl_present)
7260 				first_mp->b_cont = mp;
7261 			else
7262 				first_mp = mp;
7263 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7264 			    connf_head != NULL) {
7265 				ip_fanout_proto(q, first_mp, ill, ipha,
7266 				    flags | IP_FF_RAWIP, mctl_present,
7267 				    ip_policy, recv_ill, zoneid);
7268 			} else {
7269 				if (ip_fanout_send_icmp(q, first_mp, flags,
7270 				    ICMP_DEST_UNREACHABLE,
7271 				    ICMP_PORT_UNREACHABLE,
7272 				    mctl_present, zoneid, ipst)) {
7273 					BUMP_MIB(ill->ill_ip_mib,
7274 					    udpIfStatsNoPorts);
7275 				}
7276 			}
7277 			return;
7278 		}
7279 
7280 		CONN_INC_REF(connp);
7281 		mutex_exit(&connfp->connf_lock);
7282 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7283 		    flags, recv_ill, ip_policy);
7284 		CONN_DEC_REF(connp);
7285 		return;
7286 	}
7287 	/*
7288 	 * IPv4 multicast packet being delivered to an AF_INET6
7289 	 * in6addr_any endpoint.
7290 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7291 	 * and not conn_wantpacket_v6() since any multicast membership is
7292 	 * for an IPv4-mapped multicast address.
7293 	 * The packet is sent to all clients in all zones that have joined the
7294 	 * group and match the port.
7295 	 */
7296 	while (connp != NULL) {
7297 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7298 		    srcport, v6src) &&
7299 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7300 		    (!is_system_labeled() ||
7301 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7302 		    connp)))
7303 			break;
7304 		connp = connp->conn_next;
7305 	}
7306 
7307 	if (connp == NULL || connp->conn_upq == NULL) {
7308 		/*
7309 		 * No one bound to this port.  Is
7310 		 * there a client that wants all
7311 		 * unclaimed datagrams?
7312 		 */
7313 		mutex_exit(&connfp->connf_lock);
7314 
7315 		if (mctl_present)
7316 			first_mp->b_cont = mp;
7317 		else
7318 			first_mp = mp;
7319 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7320 		    NULL) {
7321 			ip_fanout_proto(q, first_mp, ill, ipha,
7322 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7323 			    recv_ill, zoneid);
7324 		} else {
7325 			/*
7326 			 * We used to attempt to send an icmp error here, but
7327 			 * since this is known to be a multicast packet
7328 			 * and we don't send icmp errors in response to
7329 			 * multicast, just drop the packet and give up sooner.
7330 			 */
7331 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7332 			freemsg(first_mp);
7333 		}
7334 		return;
7335 	}
7336 
7337 	first_connp = connp;
7338 
7339 	CONN_INC_REF(connp);
7340 	connp = connp->conn_next;
7341 	for (;;) {
7342 		while (connp != NULL) {
7343 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7344 			    ipv6_all_zeros, srcport, v6src) &&
7345 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7346 			    (!is_system_labeled() ||
7347 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7348 			    shared_addr, connp)))
7349 				break;
7350 			connp = connp->conn_next;
7351 		}
7352 		/*
7353 		 * Just copy the data part alone. The mctl part is
7354 		 * needed just for verifying policy and it is never
7355 		 * sent up.
7356 		 */
7357 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7358 		    ((mp1 = copymsg(mp)) == NULL))) {
7359 			/*
7360 			 * No more intested clients or memory
7361 			 * allocation failed
7362 			 */
7363 			connp = first_connp;
7364 			break;
7365 		}
7366 		if (first_mp != NULL) {
7367 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7368 			    ipsec_info_type == IPSEC_IN);
7369 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7370 			    ipst->ips_netstack);
7371 			if (first_mp1 == NULL) {
7372 				freemsg(mp1);
7373 				connp = first_connp;
7374 				break;
7375 			}
7376 		} else {
7377 			first_mp1 = NULL;
7378 		}
7379 		CONN_INC_REF(connp);
7380 		mutex_exit(&connfp->connf_lock);
7381 		/*
7382 		 * IPQoS notes: We don't send the packet for policy
7383 		 * processing here, will do it for the last one (below).
7384 		 * i.e. we do it per-packet now, but if we do policy
7385 		 * processing per-conn, then we would need to do it
7386 		 * here too.
7387 		 */
7388 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7389 		    ipha, flags, recv_ill, B_FALSE);
7390 		mutex_enter(&connfp->connf_lock);
7391 		/* Follow the next pointer before releasing the conn. */
7392 		next_connp = connp->conn_next;
7393 		CONN_DEC_REF(connp);
7394 		connp = next_connp;
7395 	}
7396 
7397 	/* Last one.  Send it upstream. */
7398 	mutex_exit(&connfp->connf_lock);
7399 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7400 	    recv_ill, ip_policy);
7401 	CONN_DEC_REF(connp);
7402 }
7403 
7404 /*
7405  * Complete the ip_wput header so that it
7406  * is possible to generate ICMP
7407  * errors.
7408  */
7409 int
7410 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7411 {
7412 	ire_t *ire;
7413 
7414 	if (ipha->ipha_src == INADDR_ANY) {
7415 		ire = ire_lookup_local(zoneid, ipst);
7416 		if (ire == NULL) {
7417 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7418 			return (1);
7419 		}
7420 		ipha->ipha_src = ire->ire_addr;
7421 		ire_refrele(ire);
7422 	}
7423 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7424 	ipha->ipha_hdr_checksum = 0;
7425 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7426 	return (0);
7427 }
7428 
7429 /*
7430  * Nobody should be sending
7431  * packets up this stream
7432  */
7433 static void
7434 ip_lrput(queue_t *q, mblk_t *mp)
7435 {
7436 	mblk_t *mp1;
7437 
7438 	switch (mp->b_datap->db_type) {
7439 	case M_FLUSH:
7440 		/* Turn around */
7441 		if (*mp->b_rptr & FLUSHW) {
7442 			*mp->b_rptr &= ~FLUSHR;
7443 			qreply(q, mp);
7444 			return;
7445 		}
7446 		break;
7447 	}
7448 	/* Could receive messages that passed through ar_rput */
7449 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7450 		mp1->b_prev = mp1->b_next = NULL;
7451 	freemsg(mp);
7452 }
7453 
7454 /* Nobody should be sending packets down this stream */
7455 /* ARGSUSED */
7456 void
7457 ip_lwput(queue_t *q, mblk_t *mp)
7458 {
7459 	freemsg(mp);
7460 }
7461 
7462 /*
7463  * Move the first hop in any source route to ipha_dst and remove that part of
7464  * the source route.  Called by other protocols.  Errors in option formatting
7465  * are ignored - will be handled by ip_wput_options Return the final
7466  * destination (either ipha_dst or the last entry in a source route.)
7467  */
7468 ipaddr_t
7469 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7470 {
7471 	ipoptp_t	opts;
7472 	uchar_t		*opt;
7473 	uint8_t		optval;
7474 	uint8_t		optlen;
7475 	ipaddr_t	dst;
7476 	int		i;
7477 	ire_t		*ire;
7478 	ip_stack_t	*ipst = ns->netstack_ip;
7479 
7480 	ip2dbg(("ip_massage_options\n"));
7481 	dst = ipha->ipha_dst;
7482 	for (optval = ipoptp_first(&opts, ipha);
7483 	    optval != IPOPT_EOL;
7484 	    optval = ipoptp_next(&opts)) {
7485 		opt = opts.ipoptp_cur;
7486 		switch (optval) {
7487 			uint8_t off;
7488 		case IPOPT_SSRR:
7489 		case IPOPT_LSRR:
7490 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7491 				ip1dbg(("ip_massage_options: bad src route\n"));
7492 				break;
7493 			}
7494 			optlen = opts.ipoptp_len;
7495 			off = opt[IPOPT_OFFSET];
7496 			off--;
7497 		redo_srr:
7498 			if (optlen < IP_ADDR_LEN ||
7499 			    off > optlen - IP_ADDR_LEN) {
7500 				/* End of source route */
7501 				ip1dbg(("ip_massage_options: end of SR\n"));
7502 				break;
7503 			}
7504 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7505 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7506 			    ntohl(dst)));
7507 			/*
7508 			 * Check if our address is present more than
7509 			 * once as consecutive hops in source route.
7510 			 * XXX verify per-interface ip_forwarding
7511 			 * for source route?
7512 			 */
7513 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7514 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7515 			if (ire != NULL) {
7516 				ire_refrele(ire);
7517 				off += IP_ADDR_LEN;
7518 				goto redo_srr;
7519 			}
7520 			if (dst == htonl(INADDR_LOOPBACK)) {
7521 				ip1dbg(("ip_massage_options: loopback addr in "
7522 				    "source route!\n"));
7523 				break;
7524 			}
7525 			/*
7526 			 * Update ipha_dst to be the first hop and remove the
7527 			 * first hop from the source route (by overwriting
7528 			 * part of the option with NOP options).
7529 			 */
7530 			ipha->ipha_dst = dst;
7531 			/* Put the last entry in dst */
7532 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7533 			    3;
7534 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7535 
7536 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7537 			    ntohl(dst)));
7538 			/* Move down and overwrite */
7539 			opt[IP_ADDR_LEN] = opt[0];
7540 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7541 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7542 			for (i = 0; i < IP_ADDR_LEN; i++)
7543 				opt[i] = IPOPT_NOP;
7544 			break;
7545 		}
7546 	}
7547 	return (dst);
7548 }
7549 
7550 /*
7551  * Return the network mask
7552  * associated with the specified address.
7553  */
7554 ipaddr_t
7555 ip_net_mask(ipaddr_t addr)
7556 {
7557 	uchar_t	*up = (uchar_t *)&addr;
7558 	ipaddr_t mask = 0;
7559 	uchar_t	*maskp = (uchar_t *)&mask;
7560 
7561 #if defined(__i386) || defined(__amd64)
7562 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7563 #endif
7564 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7565 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7566 #endif
7567 	if (CLASSD(addr)) {
7568 		maskp[0] = 0xF0;
7569 		return (mask);
7570 	}
7571 	if (addr == 0)
7572 		return (0);
7573 	maskp[0] = 0xFF;
7574 	if ((up[0] & 0x80) == 0)
7575 		return (mask);
7576 
7577 	maskp[1] = 0xFF;
7578 	if ((up[0] & 0xC0) == 0x80)
7579 		return (mask);
7580 
7581 	maskp[2] = 0xFF;
7582 	if ((up[0] & 0xE0) == 0xC0)
7583 		return (mask);
7584 
7585 	/* Must be experimental or multicast, indicate as much */
7586 	return ((ipaddr_t)0);
7587 }
7588 
7589 /*
7590  * Select an ill for the packet by considering load spreading across
7591  * a different ill in the group if dst_ill is part of some group.
7592  */
7593 ill_t *
7594 ip_newroute_get_dst_ill(ill_t *dst_ill)
7595 {
7596 	ill_t *ill;
7597 
7598 	/*
7599 	 * We schedule irrespective of whether the source address is
7600 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7601 	 */
7602 	ill = illgrp_scheduler(dst_ill);
7603 	if (ill == NULL)
7604 		return (NULL);
7605 
7606 	/*
7607 	 * For groups with names ip_sioctl_groupname ensures that all
7608 	 * ills are of same type. For groups without names, ifgrp_insert
7609 	 * ensures this.
7610 	 */
7611 	ASSERT(dst_ill->ill_type == ill->ill_type);
7612 
7613 	return (ill);
7614 }
7615 
7616 /*
7617  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7618  */
7619 ill_t *
7620 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7621     ip_stack_t *ipst)
7622 {
7623 	ill_t *ret_ill;
7624 
7625 	ASSERT(ifindex != 0);
7626 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7627 	    ipst);
7628 	if (ret_ill == NULL ||
7629 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7630 		if (isv6) {
7631 			if (ill != NULL) {
7632 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7633 			} else {
7634 				BUMP_MIB(&ipst->ips_ip6_mib,
7635 				    ipIfStatsOutDiscards);
7636 			}
7637 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7638 			    "bad ifindex %d.\n", ifindex));
7639 		} else {
7640 			if (ill != NULL) {
7641 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7642 			} else {
7643 				BUMP_MIB(&ipst->ips_ip_mib,
7644 				    ipIfStatsOutDiscards);
7645 			}
7646 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7647 			    "bad ifindex %d.\n", ifindex));
7648 		}
7649 		if (ret_ill != NULL)
7650 			ill_refrele(ret_ill);
7651 		freemsg(first_mp);
7652 		return (NULL);
7653 	}
7654 
7655 	return (ret_ill);
7656 }
7657 
7658 /*
7659  * IPv4 -
7660  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7661  * out a packet to a destination address for which we do not have specific
7662  * (or sufficient) routing information.
7663  *
7664  * NOTE : These are the scopes of some of the variables that point at IRE,
7665  *	  which needs to be followed while making any future modifications
7666  *	  to avoid memory leaks.
7667  *
7668  *	- ire and sire are the entries looked up initially by
7669  *	  ire_ftable_lookup.
7670  *	- ipif_ire is used to hold the interface ire associated with
7671  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7672  *	  it before branching out to error paths.
7673  *	- save_ire is initialized before ire_create, so that ire returned
7674  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7675  *	  before breaking out of the switch.
7676  *
7677  *	Thus on failures, we have to REFRELE only ire and sire, if they
7678  *	are not NULL.
7679  */
7680 void
7681 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7682     zoneid_t zoneid, ip_stack_t *ipst)
7683 {
7684 	areq_t	*areq;
7685 	ipaddr_t gw = 0;
7686 	ire_t	*ire = NULL;
7687 	mblk_t	*res_mp;
7688 	ipaddr_t *addrp;
7689 	ipaddr_t nexthop_addr;
7690 	ipif_t  *src_ipif = NULL;
7691 	ill_t	*dst_ill = NULL;
7692 	ipha_t  *ipha;
7693 	ire_t	*sire = NULL;
7694 	mblk_t	*first_mp;
7695 	ire_t	*save_ire;
7696 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7697 	ushort_t ire_marks = 0;
7698 	boolean_t mctl_present;
7699 	ipsec_out_t *io;
7700 	mblk_t	*saved_mp;
7701 	ire_t	*first_sire = NULL;
7702 	mblk_t	*copy_mp = NULL;
7703 	mblk_t	*xmit_mp = NULL;
7704 	ipaddr_t save_dst;
7705 	uint32_t multirt_flags =
7706 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7707 	boolean_t multirt_is_resolvable;
7708 	boolean_t multirt_resolve_next;
7709 	boolean_t do_attach_ill = B_FALSE;
7710 	boolean_t ip_nexthop = B_FALSE;
7711 	tsol_ire_gw_secattr_t *attrp = NULL;
7712 	tsol_gcgrp_t *gcgrp = NULL;
7713 	tsol_gcgrp_addr_t ga;
7714 
7715 	if (ip_debug > 2) {
7716 		/* ip1dbg */
7717 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7718 	}
7719 
7720 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7721 	if (mctl_present) {
7722 		io = (ipsec_out_t *)first_mp->b_rptr;
7723 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7724 		ASSERT(zoneid == io->ipsec_out_zoneid);
7725 		ASSERT(zoneid != ALL_ZONES);
7726 	}
7727 
7728 	ipha = (ipha_t *)mp->b_rptr;
7729 
7730 	/* All multicast lookups come through ip_newroute_ipif() */
7731 	if (CLASSD(dst)) {
7732 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7733 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7734 		freemsg(first_mp);
7735 		return;
7736 	}
7737 
7738 	if (mctl_present && io->ipsec_out_attach_if) {
7739 		/* ip_grab_attach_ill returns a held ill */
7740 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7741 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7742 
7743 		/* Failure case frees things for us. */
7744 		if (attach_ill == NULL)
7745 			return;
7746 
7747 		/*
7748 		 * Check if we need an ire that will not be
7749 		 * looked up by anybody else i.e. HIDDEN.
7750 		 */
7751 		if (ill_is_probeonly(attach_ill))
7752 			ire_marks = IRE_MARK_HIDDEN;
7753 	}
7754 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7755 		ip_nexthop = B_TRUE;
7756 		nexthop_addr = io->ipsec_out_nexthop_addr;
7757 	}
7758 	/*
7759 	 * If this IRE is created for forwarding or it is not for
7760 	 * traffic for congestion controlled protocols, mark it as temporary.
7761 	 */
7762 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7763 		ire_marks |= IRE_MARK_TEMPORARY;
7764 
7765 	/*
7766 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7767 	 * chain until it gets the most specific information available.
7768 	 * For example, we know that there is no IRE_CACHE for this dest,
7769 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7770 	 * ire_ftable_lookup will look up the gateway, etc.
7771 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7772 	 * to the destination, of equal netmask length in the forward table,
7773 	 * will be recursively explored. If no information is available
7774 	 * for the final gateway of that route, we force the returned ire
7775 	 * to be equal to sire using MATCH_IRE_PARENT.
7776 	 * At least, in this case we have a starting point (in the buckets)
7777 	 * to look for other routes to the destination in the forward table.
7778 	 * This is actually used only for multirouting, where a list
7779 	 * of routes has to be processed in sequence.
7780 	 *
7781 	 * In the process of coming up with the most specific information,
7782 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7783 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7784 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7785 	 * Two caveats when handling incomplete ire's in ip_newroute:
7786 	 * - we should be careful when accessing its ire_nce (specifically
7787 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7788 	 * - not all legacy code path callers are prepared to handle
7789 	 *   incomplete ire's, so we should not create/add incomplete
7790 	 *   ire_cache entries here. (See discussion about temporary solution
7791 	 *   further below).
7792 	 *
7793 	 * In order to minimize packet dropping, and to preserve existing
7794 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7795 	 * gateway, and instead use the IF_RESOLVER ire to send out
7796 	 * another request to ARP (this is achieved by passing the
7797 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7798 	 * arp response comes back in ip_wput_nondata, we will create
7799 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7800 	 *
7801 	 * Note that this is a temporary solution; the correct solution is
7802 	 * to create an incomplete  per-dst ire_cache entry, and send the
7803 	 * packet out when the gw's nce is resolved. In order to achieve this,
7804 	 * all packet processing must have been completed prior to calling
7805 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7806 	 * to be modified to accomodate this solution.
7807 	 */
7808 	if (ip_nexthop) {
7809 		/*
7810 		 * The first time we come here, we look for an IRE_INTERFACE
7811 		 * entry for the specified nexthop, set the dst to be the
7812 		 * nexthop address and create an IRE_CACHE entry for the
7813 		 * nexthop. The next time around, we are able to find an
7814 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7815 		 * nexthop address and create an IRE_CACHE entry for the
7816 		 * destination address via the specified nexthop.
7817 		 */
7818 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7819 		    MBLK_GETLABEL(mp), ipst);
7820 		if (ire != NULL) {
7821 			gw = nexthop_addr;
7822 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7823 		} else {
7824 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7825 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7826 			    MBLK_GETLABEL(mp),
7827 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7828 			    ipst);
7829 			if (ire != NULL) {
7830 				dst = nexthop_addr;
7831 			}
7832 		}
7833 	} else if (attach_ill == NULL) {
7834 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7835 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7836 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7837 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7838 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7839 		    ipst);
7840 	} else {
7841 		/*
7842 		 * attach_ill is set only for communicating with
7843 		 * on-link hosts. So, don't look for DEFAULT.
7844 		 */
7845 		ipif_t	*attach_ipif;
7846 
7847 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7848 		if (attach_ipif == NULL) {
7849 			ill_refrele(attach_ill);
7850 			goto icmp_err_ret;
7851 		}
7852 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7853 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7854 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7855 		    MATCH_IRE_SECATTR, ipst);
7856 		ipif_refrele(attach_ipif);
7857 	}
7858 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7859 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7860 
7861 	/*
7862 	 * This loop is run only once in most cases.
7863 	 * We loop to resolve further routes only when the destination
7864 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7865 	 */
7866 	do {
7867 		/* Clear the previous iteration's values */
7868 		if (src_ipif != NULL) {
7869 			ipif_refrele(src_ipif);
7870 			src_ipif = NULL;
7871 		}
7872 		if (dst_ill != NULL) {
7873 			ill_refrele(dst_ill);
7874 			dst_ill = NULL;
7875 		}
7876 
7877 		multirt_resolve_next = B_FALSE;
7878 		/*
7879 		 * We check if packets have to be multirouted.
7880 		 * In this case, given the current <ire, sire> couple,
7881 		 * we look for the next suitable <ire, sire>.
7882 		 * This check is done in ire_multirt_lookup(),
7883 		 * which applies various criteria to find the next route
7884 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7885 		 * unchanged if it detects it has not been tried yet.
7886 		 */
7887 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7888 			ip3dbg(("ip_newroute: starting next_resolution "
7889 			    "with first_mp %p, tag %d\n",
7890 			    (void *)first_mp,
7891 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7892 
7893 			ASSERT(sire != NULL);
7894 			multirt_is_resolvable =
7895 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7896 			    MBLK_GETLABEL(mp), ipst);
7897 
7898 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7899 			    "ire %p, sire %p\n",
7900 			    multirt_is_resolvable,
7901 			    (void *)ire, (void *)sire));
7902 
7903 			if (!multirt_is_resolvable) {
7904 				/*
7905 				 * No more multirt route to resolve; give up
7906 				 * (all routes resolved or no more
7907 				 * resolvable routes).
7908 				 */
7909 				if (ire != NULL) {
7910 					ire_refrele(ire);
7911 					ire = NULL;
7912 				}
7913 			} else {
7914 				ASSERT(sire != NULL);
7915 				ASSERT(ire != NULL);
7916 				/*
7917 				 * We simply use first_sire as a flag that
7918 				 * indicates if a resolvable multirt route
7919 				 * has already been found.
7920 				 * If it is not the case, we may have to send
7921 				 * an ICMP error to report that the
7922 				 * destination is unreachable.
7923 				 * We do not IRE_REFHOLD first_sire.
7924 				 */
7925 				if (first_sire == NULL) {
7926 					first_sire = sire;
7927 				}
7928 			}
7929 		}
7930 		if (ire == NULL) {
7931 			if (ip_debug > 3) {
7932 				/* ip2dbg */
7933 				pr_addr_dbg("ip_newroute: "
7934 				    "can't resolve %s\n", AF_INET, &dst);
7935 			}
7936 			ip3dbg(("ip_newroute: "
7937 			    "ire %p, sire %p, first_sire %p\n",
7938 			    (void *)ire, (void *)sire, (void *)first_sire));
7939 
7940 			if (sire != NULL) {
7941 				ire_refrele(sire);
7942 				sire = NULL;
7943 			}
7944 
7945 			if (first_sire != NULL) {
7946 				/*
7947 				 * At least one multirt route has been found
7948 				 * in the same call to ip_newroute();
7949 				 * there is no need to report an ICMP error.
7950 				 * first_sire was not IRE_REFHOLDed.
7951 				 */
7952 				MULTIRT_DEBUG_UNTAG(first_mp);
7953 				freemsg(first_mp);
7954 				return;
7955 			}
7956 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7957 			    RTA_DST, ipst);
7958 			if (attach_ill != NULL)
7959 				ill_refrele(attach_ill);
7960 			goto icmp_err_ret;
7961 		}
7962 
7963 		/*
7964 		 * Verify that the returned IRE does not have either
7965 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7966 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7967 		 */
7968 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7969 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7970 			if (attach_ill != NULL)
7971 				ill_refrele(attach_ill);
7972 			goto icmp_err_ret;
7973 		}
7974 		/*
7975 		 * Increment the ire_ob_pkt_count field for ire if it is an
7976 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7977 		 * increment the same for the parent IRE, sire, if it is some
7978 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
7979 		 */
7980 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7981 			UPDATE_OB_PKT_COUNT(ire);
7982 			ire->ire_last_used_time = lbolt;
7983 		}
7984 
7985 		if (sire != NULL) {
7986 			gw = sire->ire_gateway_addr;
7987 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7988 			    IRE_INTERFACE)) == 0);
7989 			UPDATE_OB_PKT_COUNT(sire);
7990 			sire->ire_last_used_time = lbolt;
7991 		}
7992 		/*
7993 		 * We have a route to reach the destination.
7994 		 *
7995 		 * 1) If the interface is part of ill group, try to get a new
7996 		 *    ill taking load spreading into account.
7997 		 *
7998 		 * 2) After selecting the ill, get a source address that
7999 		 *    might create good inbound load spreading.
8000 		 *    ipif_select_source does this for us.
8001 		 *
8002 		 * If the application specified the ill (ifindex), we still
8003 		 * load spread. Only if the packets needs to go out
8004 		 * specifically on a given ill e.g. binding to
8005 		 * IPIF_NOFAILOVER address, then we don't try to use a
8006 		 * different ill for load spreading.
8007 		 */
8008 		if (attach_ill == NULL) {
8009 			/*
8010 			 * Don't perform outbound load spreading in the
8011 			 * case of an RTF_MULTIRT route, as we actually
8012 			 * typically want to replicate outgoing packets
8013 			 * through particular interfaces.
8014 			 */
8015 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8016 				dst_ill = ire->ire_ipif->ipif_ill;
8017 				/* for uniformity */
8018 				ill_refhold(dst_ill);
8019 			} else {
8020 				/*
8021 				 * If we are here trying to create an IRE_CACHE
8022 				 * for an offlink destination and have the
8023 				 * IRE_CACHE for the next hop and the latter is
8024 				 * using virtual IP source address selection i.e
8025 				 * it's ire->ire_ipif is pointing to a virtual
8026 				 * network interface (vni) then
8027 				 * ip_newroute_get_dst_ll() will return the vni
8028 				 * interface as the dst_ill. Since the vni is
8029 				 * virtual i.e not associated with any physical
8030 				 * interface, it cannot be the dst_ill, hence
8031 				 * in such a case call ip_newroute_get_dst_ll()
8032 				 * with the stq_ill instead of the ire_ipif ILL.
8033 				 * The function returns a refheld ill.
8034 				 */
8035 				if ((ire->ire_type == IRE_CACHE) &&
8036 				    IS_VNI(ire->ire_ipif->ipif_ill))
8037 					dst_ill = ip_newroute_get_dst_ill(
8038 					    ire->ire_stq->q_ptr);
8039 				else
8040 					dst_ill = ip_newroute_get_dst_ill(
8041 					    ire->ire_ipif->ipif_ill);
8042 			}
8043 			if (dst_ill == NULL) {
8044 				if (ip_debug > 2) {
8045 					pr_addr_dbg("ip_newroute: "
8046 					    "no dst ill for dst"
8047 					    " %s\n", AF_INET, &dst);
8048 				}
8049 				goto icmp_err_ret;
8050 			}
8051 		} else {
8052 			dst_ill = ire->ire_ipif->ipif_ill;
8053 			/* for uniformity */
8054 			ill_refhold(dst_ill);
8055 			/*
8056 			 * We should have found a route matching ill as we
8057 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8058 			 * Rather than asserting, when there is a mismatch,
8059 			 * we just drop the packet.
8060 			 */
8061 			if (dst_ill != attach_ill) {
8062 				ip0dbg(("ip_newroute: Packet dropped as "
8063 				    "IPIF_NOFAILOVER ill is %s, "
8064 				    "ire->ire_ipif->ipif_ill is %s\n",
8065 				    attach_ill->ill_name,
8066 				    dst_ill->ill_name));
8067 				ill_refrele(attach_ill);
8068 				goto icmp_err_ret;
8069 			}
8070 		}
8071 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8072 		if (attach_ill != NULL) {
8073 			ill_refrele(attach_ill);
8074 			attach_ill = NULL;
8075 			do_attach_ill = B_TRUE;
8076 		}
8077 		ASSERT(dst_ill != NULL);
8078 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8079 
8080 		/*
8081 		 * Pick the best source address from dst_ill.
8082 		 *
8083 		 * 1) If it is part of a multipathing group, we would
8084 		 *    like to spread the inbound packets across different
8085 		 *    interfaces. ipif_select_source picks a random source
8086 		 *    across the different ills in the group.
8087 		 *
8088 		 * 2) If it is not part of a multipathing group, we try
8089 		 *    to pick the source address from the destination
8090 		 *    route. Clustering assumes that when we have multiple
8091 		 *    prefixes hosted on an interface, the prefix of the
8092 		 *    source address matches the prefix of the destination
8093 		 *    route. We do this only if the address is not
8094 		 *    DEPRECATED.
8095 		 *
8096 		 * 3) If the conn is in a different zone than the ire, we
8097 		 *    need to pick a source address from the right zone.
8098 		 *
8099 		 * NOTE : If we hit case (1) above, the prefix of the source
8100 		 *	  address picked may not match the prefix of the
8101 		 *	  destination routes prefix as ipif_select_source
8102 		 *	  does not look at "dst" while picking a source
8103 		 *	  address.
8104 		 *	  If we want the same behavior as (2), we will need
8105 		 *	  to change the behavior of ipif_select_source.
8106 		 */
8107 		ASSERT(src_ipif == NULL);
8108 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8109 			/*
8110 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8111 			 * Check that the ipif matching the requested source
8112 			 * address still exists.
8113 			 */
8114 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8115 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8116 		}
8117 		if (src_ipif == NULL) {
8118 			ire_marks |= IRE_MARK_USESRC_CHECK;
8119 			if ((dst_ill->ill_group != NULL) ||
8120 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8121 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8122 			    ire->ire_zoneid != ALL_ZONES) ||
8123 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8124 				/*
8125 				 * If the destination is reachable via a
8126 				 * given gateway, the selected source address
8127 				 * should be in the same subnet as the gateway.
8128 				 * Otherwise, the destination is not reachable.
8129 				 *
8130 				 * If there are no interfaces on the same subnet
8131 				 * as the destination, ipif_select_source gives
8132 				 * first non-deprecated interface which might be
8133 				 * on a different subnet than the gateway.
8134 				 * This is not desirable. Hence pass the dst_ire
8135 				 * source address to ipif_select_source.
8136 				 * It is sure that the destination is reachable
8137 				 * with the dst_ire source address subnet.
8138 				 * So passing dst_ire source address to
8139 				 * ipif_select_source will make sure that the
8140 				 * selected source will be on the same subnet
8141 				 * as dst_ire source address.
8142 				 */
8143 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8144 				src_ipif = ipif_select_source(dst_ill, saddr,
8145 				    zoneid);
8146 				if (src_ipif == NULL) {
8147 					if (ip_debug > 2) {
8148 						pr_addr_dbg("ip_newroute: "
8149 						    "no src for dst %s ",
8150 						    AF_INET, &dst);
8151 						printf("through interface %s\n",
8152 						    dst_ill->ill_name);
8153 					}
8154 					goto icmp_err_ret;
8155 				}
8156 			} else {
8157 				src_ipif = ire->ire_ipif;
8158 				ASSERT(src_ipif != NULL);
8159 				/* hold src_ipif for uniformity */
8160 				ipif_refhold(src_ipif);
8161 			}
8162 		}
8163 
8164 		/*
8165 		 * Assign a source address while we have the conn.
8166 		 * We can't have ip_wput_ire pick a source address when the
8167 		 * packet returns from arp since we need to look at
8168 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8169 		 * going through arp.
8170 		 *
8171 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8172 		 *	  it uses ip6i to store this information.
8173 		 */
8174 		if (ipha->ipha_src == INADDR_ANY &&
8175 		    (connp == NULL || !connp->conn_unspec_src)) {
8176 			ipha->ipha_src = src_ipif->ipif_src_addr;
8177 		}
8178 		if (ip_debug > 3) {
8179 			/* ip2dbg */
8180 			pr_addr_dbg("ip_newroute: first hop %s\n",
8181 			    AF_INET, &gw);
8182 		}
8183 		ip2dbg(("\tire type %s (%d)\n",
8184 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8185 
8186 		/*
8187 		 * The TTL of multirouted packets is bounded by the
8188 		 * ip_multirt_ttl ndd variable.
8189 		 */
8190 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8191 			/* Force TTL of multirouted packets */
8192 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8193 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8194 				ip2dbg(("ip_newroute: forcing multirt TTL "
8195 				    "to %d (was %d), dst 0x%08x\n",
8196 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8197 				    ntohl(sire->ire_addr)));
8198 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8199 			}
8200 		}
8201 		/*
8202 		 * At this point in ip_newroute(), ire is either the
8203 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8204 		 * destination or an IRE_INTERFACE type that should be used
8205 		 * to resolve an on-subnet destination or an on-subnet
8206 		 * next-hop gateway.
8207 		 *
8208 		 * In the IRE_CACHE case, we have the following :
8209 		 *
8210 		 * 1) src_ipif - used for getting a source address.
8211 		 *
8212 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8213 		 *    means packets using this IRE_CACHE will go out on
8214 		 *    dst_ill.
8215 		 *
8216 		 * 3) The IRE sire will point to the prefix that is the
8217 		 *    longest  matching route for the destination. These
8218 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8219 		 *
8220 		 *    The newly created IRE_CACHE entry for the off-subnet
8221 		 *    destination is tied to both the prefix route and the
8222 		 *    interface route used to resolve the next-hop gateway
8223 		 *    via the ire_phandle and ire_ihandle fields,
8224 		 *    respectively.
8225 		 *
8226 		 * In the IRE_INTERFACE case, we have the following :
8227 		 *
8228 		 * 1) src_ipif - used for getting a source address.
8229 		 *
8230 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8231 		 *    means packets using the IRE_CACHE that we will build
8232 		 *    here will go out on dst_ill.
8233 		 *
8234 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8235 		 *    to be created will only be tied to the IRE_INTERFACE
8236 		 *    that was derived from the ire_ihandle field.
8237 		 *
8238 		 *    If sire is non-NULL, it means the destination is
8239 		 *    off-link and we will first create the IRE_CACHE for the
8240 		 *    gateway. Next time through ip_newroute, we will create
8241 		 *    the IRE_CACHE for the final destination as described
8242 		 *    above.
8243 		 *
8244 		 * In both cases, after the current resolution has been
8245 		 * completed (or possibly initialised, in the IRE_INTERFACE
8246 		 * case), the loop may be re-entered to attempt the resolution
8247 		 * of another RTF_MULTIRT route.
8248 		 *
8249 		 * When an IRE_CACHE entry for the off-subnet destination is
8250 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8251 		 * for further processing in emission loops.
8252 		 */
8253 		save_ire = ire;
8254 		switch (ire->ire_type) {
8255 		case IRE_CACHE: {
8256 			ire_t	*ipif_ire;
8257 
8258 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8259 			if (gw == 0)
8260 				gw = ire->ire_gateway_addr;
8261 			/*
8262 			 * We need 3 ire's to create a new cache ire for an
8263 			 * off-link destination from the cache ire of the
8264 			 * gateway.
8265 			 *
8266 			 *	1. The prefix ire 'sire' (Note that this does
8267 			 *	   not apply to the conn_nexthop_set case)
8268 			 *	2. The cache ire of the gateway 'ire'
8269 			 *	3. The interface ire 'ipif_ire'
8270 			 *
8271 			 * We have (1) and (2). We lookup (3) below.
8272 			 *
8273 			 * If there is no interface route to the gateway,
8274 			 * it is a race condition, where we found the cache
8275 			 * but the interface route has been deleted.
8276 			 */
8277 			if (ip_nexthop) {
8278 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8279 			} else {
8280 				ipif_ire =
8281 				    ire_ihandle_lookup_offlink(ire, sire);
8282 			}
8283 			if (ipif_ire == NULL) {
8284 				ip1dbg(("ip_newroute: "
8285 				    "ire_ihandle_lookup_offlink failed\n"));
8286 				goto icmp_err_ret;
8287 			}
8288 
8289 			/*
8290 			 * Check cached gateway IRE for any security
8291 			 * attributes; if found, associate the gateway
8292 			 * credentials group to the destination IRE.
8293 			 */
8294 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8295 				mutex_enter(&attrp->igsa_lock);
8296 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8297 					GCGRP_REFHOLD(gcgrp);
8298 				mutex_exit(&attrp->igsa_lock);
8299 			}
8300 
8301 			/*
8302 			 * XXX For the source of the resolver mp,
8303 			 * we are using the same DL_UNITDATA_REQ
8304 			 * (from save_ire->ire_nce->nce_res_mp)
8305 			 * though the save_ire is not pointing at the same ill.
8306 			 * This is incorrect. We need to send it up to the
8307 			 * resolver to get the right res_mp. For ethernets
8308 			 * this may be okay (ill_type == DL_ETHER).
8309 			 */
8310 
8311 			ire = ire_create(
8312 			    (uchar_t *)&dst,		/* dest address */
8313 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8314 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8315 			    (uchar_t *)&gw,		/* gateway address */
8316 			    &save_ire->ire_max_frag,
8317 			    save_ire->ire_nce,		/* src nce */
8318 			    dst_ill->ill_rq,		/* recv-from queue */
8319 			    dst_ill->ill_wq,		/* send-to queue */
8320 			    IRE_CACHE,			/* IRE type */
8321 			    src_ipif,
8322 			    (sire != NULL) ?
8323 			    sire->ire_mask : 0, 	/* Parent mask */
8324 			    (sire != NULL) ?
8325 			    sire->ire_phandle : 0,	/* Parent handle */
8326 			    ipif_ire->ire_ihandle,	/* Interface handle */
8327 			    (sire != NULL) ? (sire->ire_flags &
8328 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8329 			    (sire != NULL) ?
8330 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8331 			    NULL,
8332 			    gcgrp,
8333 			    ipst);
8334 
8335 			if (ire == NULL) {
8336 				if (gcgrp != NULL) {
8337 					GCGRP_REFRELE(gcgrp);
8338 					gcgrp = NULL;
8339 				}
8340 				ire_refrele(ipif_ire);
8341 				ire_refrele(save_ire);
8342 				break;
8343 			}
8344 
8345 			/* reference now held by IRE */
8346 			gcgrp = NULL;
8347 
8348 			ire->ire_marks |= ire_marks;
8349 
8350 			/*
8351 			 * Prevent sire and ipif_ire from getting deleted.
8352 			 * The newly created ire is tied to both of them via
8353 			 * the phandle and ihandle respectively.
8354 			 */
8355 			if (sire != NULL) {
8356 				IRB_REFHOLD(sire->ire_bucket);
8357 				/* Has it been removed already ? */
8358 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8359 					IRB_REFRELE(sire->ire_bucket);
8360 					ire_refrele(ipif_ire);
8361 					ire_refrele(save_ire);
8362 					break;
8363 				}
8364 			}
8365 
8366 			IRB_REFHOLD(ipif_ire->ire_bucket);
8367 			/* Has it been removed already ? */
8368 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8369 				IRB_REFRELE(ipif_ire->ire_bucket);
8370 				if (sire != NULL)
8371 					IRB_REFRELE(sire->ire_bucket);
8372 				ire_refrele(ipif_ire);
8373 				ire_refrele(save_ire);
8374 				break;
8375 			}
8376 
8377 			xmit_mp = first_mp;
8378 			/*
8379 			 * In the case of multirouting, a copy
8380 			 * of the packet is done before its sending.
8381 			 * The copy is used to attempt another
8382 			 * route resolution, in a next loop.
8383 			 */
8384 			if (ire->ire_flags & RTF_MULTIRT) {
8385 				copy_mp = copymsg(first_mp);
8386 				if (copy_mp != NULL) {
8387 					xmit_mp = copy_mp;
8388 					MULTIRT_DEBUG_TAG(first_mp);
8389 				}
8390 			}
8391 			ire_add_then_send(q, ire, xmit_mp);
8392 			ire_refrele(save_ire);
8393 
8394 			/* Assert that sire is not deleted yet. */
8395 			if (sire != NULL) {
8396 				ASSERT(sire->ire_ptpn != NULL);
8397 				IRB_REFRELE(sire->ire_bucket);
8398 			}
8399 
8400 			/* Assert that ipif_ire is not deleted yet. */
8401 			ASSERT(ipif_ire->ire_ptpn != NULL);
8402 			IRB_REFRELE(ipif_ire->ire_bucket);
8403 			ire_refrele(ipif_ire);
8404 
8405 			/*
8406 			 * If copy_mp is not NULL, multirouting was
8407 			 * requested. We loop to initiate a next
8408 			 * route resolution attempt, starting from sire.
8409 			 */
8410 			if (copy_mp != NULL) {
8411 				/*
8412 				 * Search for the next unresolved
8413 				 * multirt route.
8414 				 */
8415 				copy_mp = NULL;
8416 				ipif_ire = NULL;
8417 				ire = NULL;
8418 				multirt_resolve_next = B_TRUE;
8419 				continue;
8420 			}
8421 			if (sire != NULL)
8422 				ire_refrele(sire);
8423 			ipif_refrele(src_ipif);
8424 			ill_refrele(dst_ill);
8425 			return;
8426 		}
8427 		case IRE_IF_NORESOLVER: {
8428 
8429 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8430 			    dst_ill->ill_resolver_mp == NULL) {
8431 				ip1dbg(("ip_newroute: dst_ill %p "
8432 				    "for IRE_IF_NORESOLVER ire %p has "
8433 				    "no ill_resolver_mp\n",
8434 				    (void *)dst_ill, (void *)ire));
8435 				break;
8436 			}
8437 
8438 			/*
8439 			 * TSol note: We are creating the ire cache for the
8440 			 * destination 'dst'. If 'dst' is offlink, going
8441 			 * through the first hop 'gw', the security attributes
8442 			 * of 'dst' must be set to point to the gateway
8443 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8444 			 * is possible that 'dst' is a potential gateway that is
8445 			 * referenced by some route that has some security
8446 			 * attributes. Thus in the former case, we need to do a
8447 			 * gcgrp_lookup of 'gw' while in the latter case we
8448 			 * need to do gcgrp_lookup of 'dst' itself.
8449 			 */
8450 			ga.ga_af = AF_INET;
8451 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8452 			    &ga.ga_addr);
8453 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8454 
8455 			ire = ire_create(
8456 			    (uchar_t *)&dst,		/* dest address */
8457 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8458 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8459 			    (uchar_t *)&gw,		/* gateway address */
8460 			    &save_ire->ire_max_frag,
8461 			    NULL,			/* no src nce */
8462 			    dst_ill->ill_rq,		/* recv-from queue */
8463 			    dst_ill->ill_wq,		/* send-to queue */
8464 			    IRE_CACHE,
8465 			    src_ipif,
8466 			    save_ire->ire_mask,		/* Parent mask */
8467 			    (sire != NULL) ?		/* Parent handle */
8468 			    sire->ire_phandle : 0,
8469 			    save_ire->ire_ihandle,	/* Interface handle */
8470 			    (sire != NULL) ? sire->ire_flags &
8471 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8472 			    &(save_ire->ire_uinfo),
8473 			    NULL,
8474 			    gcgrp,
8475 			    ipst);
8476 
8477 			if (ire == NULL) {
8478 				if (gcgrp != NULL) {
8479 					GCGRP_REFRELE(gcgrp);
8480 					gcgrp = NULL;
8481 				}
8482 				ire_refrele(save_ire);
8483 				break;
8484 			}
8485 
8486 			/* reference now held by IRE */
8487 			gcgrp = NULL;
8488 
8489 			ire->ire_marks |= ire_marks;
8490 
8491 			/* Prevent save_ire from getting deleted */
8492 			IRB_REFHOLD(save_ire->ire_bucket);
8493 			/* Has it been removed already ? */
8494 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8495 				IRB_REFRELE(save_ire->ire_bucket);
8496 				ire_refrele(save_ire);
8497 				break;
8498 			}
8499 
8500 			/*
8501 			 * In the case of multirouting, a copy
8502 			 * of the packet is made before it is sent.
8503 			 * The copy is used in the next
8504 			 * loop to attempt another resolution.
8505 			 */
8506 			xmit_mp = first_mp;
8507 			if ((sire != NULL) &&
8508 			    (sire->ire_flags & RTF_MULTIRT)) {
8509 				copy_mp = copymsg(first_mp);
8510 				if (copy_mp != NULL) {
8511 					xmit_mp = copy_mp;
8512 					MULTIRT_DEBUG_TAG(first_mp);
8513 				}
8514 			}
8515 			ire_add_then_send(q, ire, xmit_mp);
8516 
8517 			/* Assert that it is not deleted yet. */
8518 			ASSERT(save_ire->ire_ptpn != NULL);
8519 			IRB_REFRELE(save_ire->ire_bucket);
8520 			ire_refrele(save_ire);
8521 
8522 			if (copy_mp != NULL) {
8523 				/*
8524 				 * If we found a (no)resolver, we ignore any
8525 				 * trailing top priority IRE_CACHE in further
8526 				 * loops. This ensures that we do not omit any
8527 				 * (no)resolver.
8528 				 * This IRE_CACHE, if any, will be processed
8529 				 * by another thread entering ip_newroute().
8530 				 * IRE_CACHE entries, if any, will be processed
8531 				 * by another thread entering ip_newroute(),
8532 				 * (upon resolver response, for instance).
8533 				 * This aims to force parallel multirt
8534 				 * resolutions as soon as a packet must be sent.
8535 				 * In the best case, after the tx of only one
8536 				 * packet, all reachable routes are resolved.
8537 				 * Otherwise, the resolution of all RTF_MULTIRT
8538 				 * routes would require several emissions.
8539 				 */
8540 				multirt_flags &= ~MULTIRT_CACHEGW;
8541 
8542 				/*
8543 				 * Search for the next unresolved multirt
8544 				 * route.
8545 				 */
8546 				copy_mp = NULL;
8547 				save_ire = NULL;
8548 				ire = NULL;
8549 				multirt_resolve_next = B_TRUE;
8550 				continue;
8551 			}
8552 
8553 			/*
8554 			 * Don't need sire anymore
8555 			 */
8556 			if (sire != NULL)
8557 				ire_refrele(sire);
8558 
8559 			ipif_refrele(src_ipif);
8560 			ill_refrele(dst_ill);
8561 			return;
8562 		}
8563 		case IRE_IF_RESOLVER:
8564 			/*
8565 			 * We can't build an IRE_CACHE yet, but at least we
8566 			 * found a resolver that can help.
8567 			 */
8568 			res_mp = dst_ill->ill_resolver_mp;
8569 			if (!OK_RESOLVER_MP(res_mp))
8570 				break;
8571 
8572 			/*
8573 			 * To be at this point in the code with a non-zero gw
8574 			 * means that dst is reachable through a gateway that
8575 			 * we have never resolved.  By changing dst to the gw
8576 			 * addr we resolve the gateway first.
8577 			 * When ire_add_then_send() tries to put the IP dg
8578 			 * to dst, it will reenter ip_newroute() at which
8579 			 * time we will find the IRE_CACHE for the gw and
8580 			 * create another IRE_CACHE in case IRE_CACHE above.
8581 			 */
8582 			if (gw != INADDR_ANY) {
8583 				/*
8584 				 * The source ipif that was determined above was
8585 				 * relative to the destination address, not the
8586 				 * gateway's. If src_ipif was not taken out of
8587 				 * the IRE_IF_RESOLVER entry, we'll need to call
8588 				 * ipif_select_source() again.
8589 				 */
8590 				if (src_ipif != ire->ire_ipif) {
8591 					ipif_refrele(src_ipif);
8592 					src_ipif = ipif_select_source(dst_ill,
8593 					    gw, zoneid);
8594 					if (src_ipif == NULL) {
8595 						if (ip_debug > 2) {
8596 							pr_addr_dbg(
8597 							    "ip_newroute: no "
8598 							    "src for gw %s ",
8599 							    AF_INET, &gw);
8600 							printf("through "
8601 							    "interface %s\n",
8602 							    dst_ill->ill_name);
8603 						}
8604 						goto icmp_err_ret;
8605 					}
8606 				}
8607 				save_dst = dst;
8608 				dst = gw;
8609 				gw = INADDR_ANY;
8610 			}
8611 
8612 			/*
8613 			 * We obtain a partial IRE_CACHE which we will pass
8614 			 * along with the resolver query.  When the response
8615 			 * comes back it will be there ready for us to add.
8616 			 * The ire_max_frag is atomically set under the
8617 			 * irebucket lock in ire_add_v[46].
8618 			 */
8619 
8620 			ire = ire_create_mp(
8621 			    (uchar_t *)&dst,		/* dest address */
8622 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8623 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8624 			    (uchar_t *)&gw,		/* gateway address */
8625 			    NULL,			/* ire_max_frag */
8626 			    NULL,			/* no src nce */
8627 			    dst_ill->ill_rq,		/* recv-from queue */
8628 			    dst_ill->ill_wq,		/* send-to queue */
8629 			    IRE_CACHE,
8630 			    src_ipif,			/* Interface ipif */
8631 			    save_ire->ire_mask,		/* Parent mask */
8632 			    0,
8633 			    save_ire->ire_ihandle,	/* Interface handle */
8634 			    0,				/* flags if any */
8635 			    &(save_ire->ire_uinfo),
8636 			    NULL,
8637 			    NULL,
8638 			    ipst);
8639 
8640 			if (ire == NULL) {
8641 				ire_refrele(save_ire);
8642 				break;
8643 			}
8644 
8645 			if ((sire != NULL) &&
8646 			    (sire->ire_flags & RTF_MULTIRT)) {
8647 				copy_mp = copymsg(first_mp);
8648 				if (copy_mp != NULL)
8649 					MULTIRT_DEBUG_TAG(copy_mp);
8650 			}
8651 
8652 			ire->ire_marks |= ire_marks;
8653 
8654 			/*
8655 			 * Construct message chain for the resolver
8656 			 * of the form:
8657 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8658 			 * Packet could contain a IPSEC_OUT mp.
8659 			 *
8660 			 * NOTE : ire will be added later when the response
8661 			 * comes back from ARP. If the response does not
8662 			 * come back, ARP frees the packet. For this reason,
8663 			 * we can't REFHOLD the bucket of save_ire to prevent
8664 			 * deletions. We may not be able to REFRELE the bucket
8665 			 * if the response never comes back. Thus, before
8666 			 * adding the ire, ire_add_v4 will make sure that the
8667 			 * interface route does not get deleted. This is the
8668 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8669 			 * where we can always prevent deletions because of
8670 			 * the synchronous nature of adding IRES i.e
8671 			 * ire_add_then_send is called after creating the IRE.
8672 			 */
8673 			ASSERT(ire->ire_mp != NULL);
8674 			ire->ire_mp->b_cont = first_mp;
8675 			/* Have saved_mp handy, for cleanup if canput fails */
8676 			saved_mp = mp;
8677 			mp = copyb(res_mp);
8678 			if (mp == NULL) {
8679 				/* Prepare for cleanup */
8680 				mp = saved_mp; /* pkt */
8681 				ire_delete(ire); /* ire_mp */
8682 				ire = NULL;
8683 				ire_refrele(save_ire);
8684 				if (copy_mp != NULL) {
8685 					MULTIRT_DEBUG_UNTAG(copy_mp);
8686 					freemsg(copy_mp);
8687 					copy_mp = NULL;
8688 				}
8689 				break;
8690 			}
8691 			linkb(mp, ire->ire_mp);
8692 
8693 			/*
8694 			 * Fill in the source and dest addrs for the resolver.
8695 			 * NOTE: this depends on memory layouts imposed by
8696 			 * ill_init().
8697 			 */
8698 			areq = (areq_t *)mp->b_rptr;
8699 			addrp = (ipaddr_t *)((char *)areq +
8700 			    areq->areq_sender_addr_offset);
8701 			if (do_attach_ill) {
8702 				/*
8703 				 * This is bind to no failover case.
8704 				 * arp packet also must go out on attach_ill.
8705 				 */
8706 				ASSERT(ipha->ipha_src != NULL);
8707 				*addrp = ipha->ipha_src;
8708 			} else {
8709 				*addrp = save_ire->ire_src_addr;
8710 			}
8711 
8712 			ire_refrele(save_ire);
8713 			addrp = (ipaddr_t *)((char *)areq +
8714 			    areq->areq_target_addr_offset);
8715 			*addrp = dst;
8716 			/* Up to the resolver. */
8717 			if (canputnext(dst_ill->ill_rq) &&
8718 			    !(dst_ill->ill_arp_closing)) {
8719 				putnext(dst_ill->ill_rq, mp);
8720 				ire = NULL;
8721 				if (copy_mp != NULL) {
8722 					/*
8723 					 * If we found a resolver, we ignore
8724 					 * any trailing top priority IRE_CACHE
8725 					 * in the further loops. This ensures
8726 					 * that we do not omit any resolver.
8727 					 * IRE_CACHE entries, if any, will be
8728 					 * processed next time we enter
8729 					 * ip_newroute().
8730 					 */
8731 					multirt_flags &= ~MULTIRT_CACHEGW;
8732 					/*
8733 					 * Search for the next unresolved
8734 					 * multirt route.
8735 					 */
8736 					first_mp = copy_mp;
8737 					copy_mp = NULL;
8738 					/* Prepare the next resolution loop. */
8739 					mp = first_mp;
8740 					EXTRACT_PKT_MP(mp, first_mp,
8741 					    mctl_present);
8742 					if (mctl_present)
8743 						io = (ipsec_out_t *)
8744 						    first_mp->b_rptr;
8745 					ipha = (ipha_t *)mp->b_rptr;
8746 
8747 					ASSERT(sire != NULL);
8748 
8749 					dst = save_dst;
8750 					multirt_resolve_next = B_TRUE;
8751 					continue;
8752 				}
8753 
8754 				if (sire != NULL)
8755 					ire_refrele(sire);
8756 
8757 				/*
8758 				 * The response will come back in ip_wput
8759 				 * with db_type IRE_DB_TYPE.
8760 				 */
8761 				ipif_refrele(src_ipif);
8762 				ill_refrele(dst_ill);
8763 				return;
8764 			} else {
8765 				/* Prepare for cleanup */
8766 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8767 				    mp);
8768 				mp->b_cont = NULL;
8769 				freeb(mp); /* areq */
8770 				/*
8771 				 * this is an ire that is not added to the
8772 				 * cache. ire_freemblk will handle the release
8773 				 * of any resources associated with the ire.
8774 				 */
8775 				ire_delete(ire); /* ire_mp */
8776 				mp = saved_mp; /* pkt */
8777 				ire = NULL;
8778 				if (copy_mp != NULL) {
8779 					MULTIRT_DEBUG_UNTAG(copy_mp);
8780 					freemsg(copy_mp);
8781 					copy_mp = NULL;
8782 				}
8783 				break;
8784 			}
8785 		default:
8786 			break;
8787 		}
8788 	} while (multirt_resolve_next);
8789 
8790 	ip1dbg(("ip_newroute: dropped\n"));
8791 	/* Did this packet originate externally? */
8792 	if (mp->b_prev) {
8793 		mp->b_next = NULL;
8794 		mp->b_prev = NULL;
8795 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8796 	} else {
8797 		if (dst_ill != NULL) {
8798 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8799 		} else {
8800 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8801 		}
8802 	}
8803 	ASSERT(copy_mp == NULL);
8804 	MULTIRT_DEBUG_UNTAG(first_mp);
8805 	freemsg(first_mp);
8806 	if (ire != NULL)
8807 		ire_refrele(ire);
8808 	if (sire != NULL)
8809 		ire_refrele(sire);
8810 	if (src_ipif != NULL)
8811 		ipif_refrele(src_ipif);
8812 	if (dst_ill != NULL)
8813 		ill_refrele(dst_ill);
8814 	return;
8815 
8816 icmp_err_ret:
8817 	ip1dbg(("ip_newroute: no route\n"));
8818 	if (src_ipif != NULL)
8819 		ipif_refrele(src_ipif);
8820 	if (dst_ill != NULL)
8821 		ill_refrele(dst_ill);
8822 	if (sire != NULL)
8823 		ire_refrele(sire);
8824 	/* Did this packet originate externally? */
8825 	if (mp->b_prev) {
8826 		mp->b_next = NULL;
8827 		mp->b_prev = NULL;
8828 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8829 		q = WR(q);
8830 	} else {
8831 		/*
8832 		 * There is no outgoing ill, so just increment the
8833 		 * system MIB.
8834 		 */
8835 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8836 		/*
8837 		 * Since ip_wput() isn't close to finished, we fill
8838 		 * in enough of the header for credible error reporting.
8839 		 */
8840 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8841 			/* Failed */
8842 			MULTIRT_DEBUG_UNTAG(first_mp);
8843 			freemsg(first_mp);
8844 			if (ire != NULL)
8845 				ire_refrele(ire);
8846 			return;
8847 		}
8848 	}
8849 
8850 	/*
8851 	 * At this point we will have ire only if RTF_BLACKHOLE
8852 	 * or RTF_REJECT flags are set on the IRE. It will not
8853 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8854 	 */
8855 	if (ire != NULL) {
8856 		if (ire->ire_flags & RTF_BLACKHOLE) {
8857 			ire_refrele(ire);
8858 			MULTIRT_DEBUG_UNTAG(first_mp);
8859 			freemsg(first_mp);
8860 			return;
8861 		}
8862 		ire_refrele(ire);
8863 	}
8864 	if (ip_source_routed(ipha, ipst)) {
8865 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8866 		    zoneid, ipst);
8867 		return;
8868 	}
8869 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8870 }
8871 
8872 ip_opt_info_t zero_info;
8873 
8874 /*
8875  * IPv4 -
8876  * ip_newroute_ipif is called by ip_wput_multicast and
8877  * ip_rput_forward_multicast whenever we need to send
8878  * out a packet to a destination address for which we do not have specific
8879  * routing information. It is used when the packet will be sent out
8880  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8881  * socket option is set or icmp error message wants to go out on a particular
8882  * interface for a unicast packet.
8883  *
8884  * In most cases, the destination address is resolved thanks to the ipif
8885  * intrinsic resolver. However, there are some cases where the call to
8886  * ip_newroute_ipif must take into account the potential presence of
8887  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8888  * that uses the interface. This is specified through flags,
8889  * which can be a combination of:
8890  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8891  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8892  *   and flags. Additionally, the packet source address has to be set to
8893  *   the specified address. The caller is thus expected to set this flag
8894  *   if the packet has no specific source address yet.
8895  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8896  *   flag, the resulting ire will inherit the flag. All unresolved routes
8897  *   to the destination must be explored in the same call to
8898  *   ip_newroute_ipif().
8899  */
8900 static void
8901 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8902     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8903 {
8904 	areq_t	*areq;
8905 	ire_t	*ire = NULL;
8906 	mblk_t	*res_mp;
8907 	ipaddr_t *addrp;
8908 	mblk_t *first_mp;
8909 	ire_t	*save_ire = NULL;
8910 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8911 	ipif_t	*src_ipif = NULL;
8912 	ushort_t ire_marks = 0;
8913 	ill_t	*dst_ill = NULL;
8914 	boolean_t mctl_present;
8915 	ipsec_out_t *io;
8916 	ipha_t *ipha;
8917 	int	ihandle = 0;
8918 	mblk_t	*saved_mp;
8919 	ire_t   *fire = NULL;
8920 	mblk_t  *copy_mp = NULL;
8921 	boolean_t multirt_resolve_next;
8922 	ipaddr_t ipha_dst;
8923 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8924 
8925 	/*
8926 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8927 	 * here for uniformity
8928 	 */
8929 	ipif_refhold(ipif);
8930 
8931 	/*
8932 	 * This loop is run only once in most cases.
8933 	 * We loop to resolve further routes only when the destination
8934 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8935 	 */
8936 	do {
8937 		if (dst_ill != NULL) {
8938 			ill_refrele(dst_ill);
8939 			dst_ill = NULL;
8940 		}
8941 		if (src_ipif != NULL) {
8942 			ipif_refrele(src_ipif);
8943 			src_ipif = NULL;
8944 		}
8945 		multirt_resolve_next = B_FALSE;
8946 
8947 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8948 		    ipif->ipif_ill->ill_name));
8949 
8950 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8951 		if (mctl_present)
8952 			io = (ipsec_out_t *)first_mp->b_rptr;
8953 
8954 		ipha = (ipha_t *)mp->b_rptr;
8955 
8956 		/*
8957 		 * Save the packet destination address, we may need it after
8958 		 * the packet has been consumed.
8959 		 */
8960 		ipha_dst = ipha->ipha_dst;
8961 
8962 		/*
8963 		 * If the interface is a pt-pt interface we look for an
8964 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8965 		 * local_address and the pt-pt destination address. Otherwise
8966 		 * we just match the local address.
8967 		 * NOTE: dst could be different than ipha->ipha_dst in case
8968 		 * of sending igmp multicast packets over a point-to-point
8969 		 * connection.
8970 		 * Thus we must be careful enough to check ipha_dst to be a
8971 		 * multicast address, otherwise it will take xmit_if path for
8972 		 * multicast packets resulting into kernel stack overflow by
8973 		 * repeated calls to ip_newroute_ipif from ire_send().
8974 		 */
8975 		if (CLASSD(ipha_dst) &&
8976 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8977 			goto err_ret;
8978 		}
8979 
8980 		/*
8981 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8982 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8983 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8984 		 * propagate its flags to the new ire.
8985 		 */
8986 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8987 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8988 			ip2dbg(("ip_newroute_ipif: "
8989 			    "ipif_lookup_multi_ire("
8990 			    "ipif %p, dst %08x) = fire %p\n",
8991 			    (void *)ipif, ntohl(dst), (void *)fire));
8992 		}
8993 
8994 		if (mctl_present && io->ipsec_out_attach_if) {
8995 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8996 			    io->ipsec_out_ill_index, B_FALSE, ipst);
8997 
8998 			/* Failure case frees things for us. */
8999 			if (attach_ill == NULL) {
9000 				ipif_refrele(ipif);
9001 				if (fire != NULL)
9002 					ire_refrele(fire);
9003 				return;
9004 			}
9005 
9006 			/*
9007 			 * Check if we need an ire that will not be
9008 			 * looked up by anybody else i.e. HIDDEN.
9009 			 */
9010 			if (ill_is_probeonly(attach_ill)) {
9011 				ire_marks = IRE_MARK_HIDDEN;
9012 			}
9013 			/*
9014 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9015 			 * case.
9016 			 */
9017 			dst_ill = ipif->ipif_ill;
9018 			/* attach_ill has been refheld by ip_grab_attach_ill */
9019 			ASSERT(dst_ill == attach_ill);
9020 		} else {
9021 			/*
9022 			 * If this is set by IP_XMIT_IF, then make sure that
9023 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9024 			 * specified ill.
9025 			 */
9026 			ASSERT((connp == NULL) ||
9027 			    (connp->conn_xmit_if_ill == NULL) ||
9028 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9029 			/*
9030 			 * If the interface belongs to an interface group,
9031 			 * make sure the next possible interface in the group
9032 			 * is used.  This encourages load spreading among
9033 			 * peers in an interface group.
9034 			 * Note: load spreading is disabled for RTF_MULTIRT
9035 			 * routes.
9036 			 */
9037 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9038 			    (fire->ire_flags & RTF_MULTIRT)) {
9039 				/*
9040 				 * Don't perform outbound load spreading
9041 				 * in the case of an RTF_MULTIRT issued route,
9042 				 * we actually typically want to replicate
9043 				 * outgoing packets through particular
9044 				 * interfaces.
9045 				 */
9046 				dst_ill = ipif->ipif_ill;
9047 				ill_refhold(dst_ill);
9048 			} else {
9049 				dst_ill = ip_newroute_get_dst_ill(
9050 				    ipif->ipif_ill);
9051 			}
9052 			if (dst_ill == NULL) {
9053 				if (ip_debug > 2) {
9054 					pr_addr_dbg("ip_newroute_ipif: "
9055 					    "no dst ill for dst %s\n",
9056 					    AF_INET, &dst);
9057 				}
9058 				goto err_ret;
9059 			}
9060 		}
9061 
9062 		/*
9063 		 * Pick a source address preferring non-deprecated ones.
9064 		 * Unlike ip_newroute, we don't do any source address
9065 		 * selection here since for multicast it really does not help
9066 		 * in inbound load spreading as in the unicast case.
9067 		 */
9068 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9069 		    (fire->ire_flags & RTF_SETSRC)) {
9070 			/*
9071 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9072 			 * on that interface. This ire has RTF_SETSRC flag, so
9073 			 * the source address of the packet must be changed.
9074 			 * Check that the ipif matching the requested source
9075 			 * address still exists.
9076 			 */
9077 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9078 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9079 		}
9080 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9081 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9082 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9083 		    (src_ipif == NULL)) {
9084 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9085 			if (src_ipif == NULL) {
9086 				if (ip_debug > 2) {
9087 					/* ip1dbg */
9088 					pr_addr_dbg("ip_newroute_ipif: "
9089 					    "no src for dst %s",
9090 					    AF_INET, &dst);
9091 				}
9092 				ip1dbg((" through interface %s\n",
9093 				    dst_ill->ill_name));
9094 				goto err_ret;
9095 			}
9096 			ipif_refrele(ipif);
9097 			ipif = src_ipif;
9098 			ipif_refhold(ipif);
9099 		}
9100 		if (src_ipif == NULL) {
9101 			src_ipif = ipif;
9102 			ipif_refhold(src_ipif);
9103 		}
9104 
9105 		/*
9106 		 * Assign a source address while we have the conn.
9107 		 * We can't have ip_wput_ire pick a source address when the
9108 		 * packet returns from arp since conn_unspec_src might be set
9109 		 * and we loose the conn when going through arp.
9110 		 */
9111 		if (ipha->ipha_src == INADDR_ANY &&
9112 		    (connp == NULL || !connp->conn_unspec_src)) {
9113 			ipha->ipha_src = src_ipif->ipif_src_addr;
9114 		}
9115 
9116 		/*
9117 		 * In the case of IP_XMIT_IF, it is possible that the
9118 		 * outgoing interface does not have an interface ire.
9119 		 */
9120 		if (CLASSD(ipha_dst) && (connp == NULL ||
9121 		    connp->conn_xmit_if_ill == NULL) &&
9122 		    infop->ip_opt_ill_index == 0) {
9123 			/* ipif_to_ire returns an held ire */
9124 			ire = ipif_to_ire(ipif);
9125 			if (ire == NULL)
9126 				goto err_ret;
9127 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9128 				goto err_ret;
9129 			/*
9130 			 * ihandle is needed when the ire is added to
9131 			 * cache table.
9132 			 */
9133 			save_ire = ire;
9134 			ihandle = save_ire->ire_ihandle;
9135 
9136 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9137 			    "flags %04x\n",
9138 			    (void *)ire, (void *)ipif, flags));
9139 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9140 			    (fire->ire_flags & RTF_MULTIRT)) {
9141 				/*
9142 				 * As requested by flags, an IRE_OFFSUBNET was
9143 				 * looked up on that interface. This ire has
9144 				 * RTF_MULTIRT flag, so the resolution loop will
9145 				 * be re-entered to resolve additional routes on
9146 				 * other interfaces. For that purpose, a copy of
9147 				 * the packet is performed at this point.
9148 				 */
9149 				fire->ire_last_used_time = lbolt;
9150 				copy_mp = copymsg(first_mp);
9151 				if (copy_mp) {
9152 					MULTIRT_DEBUG_TAG(copy_mp);
9153 				}
9154 			}
9155 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9156 			    (fire->ire_flags & RTF_SETSRC)) {
9157 				/*
9158 				 * As requested by flags, an IRE_OFFSUBET was
9159 				 * looked up on that interface. This ire has
9160 				 * RTF_SETSRC flag, so the source address of the
9161 				 * packet must be changed.
9162 				 */
9163 				ipha->ipha_src = fire->ire_src_addr;
9164 			}
9165 		} else {
9166 			ASSERT((connp == NULL) ||
9167 			    (connp->conn_xmit_if_ill != NULL) ||
9168 			    (connp->conn_dontroute) ||
9169 			    infop->ip_opt_ill_index != 0);
9170 			/*
9171 			 * The only ways we can come here are:
9172 			 * 1) IP_XMIT_IF socket option is set
9173 			 * 2) SO_DONTROUTE socket option is set
9174 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9175 			 * In all cases, the new ire will not be added
9176 			 * into cache table.
9177 			 */
9178 			ire_marks |= IRE_MARK_NOADD;
9179 		}
9180 
9181 		switch (ipif->ipif_net_type) {
9182 		case IRE_IF_NORESOLVER: {
9183 			/* We have what we need to build an IRE_CACHE. */
9184 
9185 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9186 			    (dst_ill->ill_resolver_mp == NULL)) {
9187 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9188 				    "for IRE_IF_NORESOLVER ire %p has "
9189 				    "no ill_resolver_mp\n",
9190 				    (void *)dst_ill, (void *)ire));
9191 				break;
9192 			}
9193 
9194 			/*
9195 			 * The new ire inherits the IRE_OFFSUBNET flags
9196 			 * and source address, if this was requested.
9197 			 */
9198 			ire = ire_create(
9199 			    (uchar_t *)&dst,		/* dest address */
9200 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9201 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9202 			    NULL,			/* gateway address */
9203 			    &ipif->ipif_mtu,
9204 			    NULL,			/* no src nce */
9205 			    dst_ill->ill_rq,		/* recv-from queue */
9206 			    dst_ill->ill_wq,		/* send-to queue */
9207 			    IRE_CACHE,
9208 			    src_ipif,
9209 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9210 			    (fire != NULL) ?		/* Parent handle */
9211 			    fire->ire_phandle : 0,
9212 			    ihandle,			/* Interface handle */
9213 			    (fire != NULL) ?
9214 			    (fire->ire_flags &
9215 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9216 			    (save_ire == NULL ? &ire_uinfo_null :
9217 			    &save_ire->ire_uinfo),
9218 			    NULL,
9219 			    NULL,
9220 			    ipst);
9221 
9222 			if (ire == NULL) {
9223 				if (save_ire != NULL)
9224 					ire_refrele(save_ire);
9225 				break;
9226 			}
9227 
9228 			ire->ire_marks |= ire_marks;
9229 
9230 			/*
9231 			 * If IRE_MARK_NOADD is set then we need to convert
9232 			 * the max_fragp to a useable value now. This is
9233 			 * normally done in ire_add_v[46]. We also need to
9234 			 * associate the ire with an nce (normally would be
9235 			 * done in ip_wput_nondata()).
9236 			 *
9237 			 * Note that IRE_MARK_NOADD packets created here
9238 			 * do not have a non-null ire_mp pointer. The null
9239 			 * value of ire_bucket indicates that they were
9240 			 * never added.
9241 			 */
9242 			if (ire->ire_marks & IRE_MARK_NOADD) {
9243 				uint_t  max_frag;
9244 
9245 				max_frag = *ire->ire_max_fragp;
9246 				ire->ire_max_fragp = NULL;
9247 				ire->ire_max_frag = max_frag;
9248 
9249 				if ((ire->ire_nce = ndp_lookup_v4(
9250 				    ire_to_ill(ire),
9251 				    (ire->ire_gateway_addr != INADDR_ANY ?
9252 				    &ire->ire_gateway_addr : &ire->ire_addr),
9253 				    B_FALSE)) == NULL) {
9254 					if (save_ire != NULL)
9255 						ire_refrele(save_ire);
9256 					break;
9257 				}
9258 				ASSERT(ire->ire_nce->nce_state ==
9259 				    ND_REACHABLE);
9260 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9261 			}
9262 
9263 			/* Prevent save_ire from getting deleted */
9264 			if (save_ire != NULL) {
9265 				IRB_REFHOLD(save_ire->ire_bucket);
9266 				/* Has it been removed already ? */
9267 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9268 					IRB_REFRELE(save_ire->ire_bucket);
9269 					ire_refrele(save_ire);
9270 					break;
9271 				}
9272 			}
9273 
9274 			ire_add_then_send(q, ire, first_mp);
9275 
9276 			/* Assert that save_ire is not deleted yet. */
9277 			if (save_ire != NULL) {
9278 				ASSERT(save_ire->ire_ptpn != NULL);
9279 				IRB_REFRELE(save_ire->ire_bucket);
9280 				ire_refrele(save_ire);
9281 				save_ire = NULL;
9282 			}
9283 			if (fire != NULL) {
9284 				ire_refrele(fire);
9285 				fire = NULL;
9286 			}
9287 
9288 			/*
9289 			 * the resolution loop is re-entered if this
9290 			 * was requested through flags and if we
9291 			 * actually are in a multirouting case.
9292 			 */
9293 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9294 				boolean_t need_resolve =
9295 				    ire_multirt_need_resolve(ipha_dst,
9296 				    MBLK_GETLABEL(copy_mp), ipst);
9297 				if (!need_resolve) {
9298 					MULTIRT_DEBUG_UNTAG(copy_mp);
9299 					freemsg(copy_mp);
9300 					copy_mp = NULL;
9301 				} else {
9302 					/*
9303 					 * ipif_lookup_group() calls
9304 					 * ire_lookup_multi() that uses
9305 					 * ire_ftable_lookup() to find
9306 					 * an IRE_INTERFACE for the group.
9307 					 * In the multirt case,
9308 					 * ire_lookup_multi() then invokes
9309 					 * ire_multirt_lookup() to find
9310 					 * the next resolvable ire.
9311 					 * As a result, we obtain an new
9312 					 * interface, derived from the
9313 					 * next ire.
9314 					 */
9315 					ipif_refrele(ipif);
9316 					ipif = ipif_lookup_group(ipha_dst,
9317 					    zoneid, ipst);
9318 					ip2dbg(("ip_newroute_ipif: "
9319 					    "multirt dst %08x, ipif %p\n",
9320 					    htonl(dst), (void *)ipif));
9321 					if (ipif != NULL) {
9322 						mp = copy_mp;
9323 						copy_mp = NULL;
9324 						multirt_resolve_next = B_TRUE;
9325 						continue;
9326 					} else {
9327 						freemsg(copy_mp);
9328 					}
9329 				}
9330 			}
9331 			if (ipif != NULL)
9332 				ipif_refrele(ipif);
9333 			ill_refrele(dst_ill);
9334 			ipif_refrele(src_ipif);
9335 			return;
9336 		}
9337 		case IRE_IF_RESOLVER:
9338 			/*
9339 			 * We can't build an IRE_CACHE yet, but at least
9340 			 * we found a resolver that can help.
9341 			 */
9342 			res_mp = dst_ill->ill_resolver_mp;
9343 			if (!OK_RESOLVER_MP(res_mp))
9344 				break;
9345 
9346 			/*
9347 			 * We obtain a partial IRE_CACHE which we will pass
9348 			 * along with the resolver query.  When the response
9349 			 * comes back it will be there ready for us to add.
9350 			 * The new ire inherits the IRE_OFFSUBNET flags
9351 			 * and source address, if this was requested.
9352 			 * The ire_max_frag is atomically set under the
9353 			 * irebucket lock in ire_add_v[46]. Only in the
9354 			 * case of IRE_MARK_NOADD, we set it here itself.
9355 			 */
9356 			ire = ire_create_mp(
9357 			    (uchar_t *)&dst,		/* dest address */
9358 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9359 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9360 			    NULL,			/* gateway address */
9361 			    (ire_marks & IRE_MARK_NOADD) ?
9362 			    ipif->ipif_mtu : 0,		/* max_frag */
9363 			    NULL,			/* no src nce */
9364 			    dst_ill->ill_rq,		/* recv-from queue */
9365 			    dst_ill->ill_wq,		/* send-to queue */
9366 			    IRE_CACHE,
9367 			    src_ipif,
9368 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9369 			    (fire != NULL) ?		/* Parent handle */
9370 			    fire->ire_phandle : 0,
9371 			    ihandle,			/* Interface handle */
9372 			    (fire != NULL) ?		/* flags if any */
9373 			    (fire->ire_flags &
9374 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9375 			    (save_ire == NULL ? &ire_uinfo_null :
9376 			    &save_ire->ire_uinfo),
9377 			    NULL,
9378 			    NULL,
9379 			    ipst);
9380 
9381 			if (save_ire != NULL) {
9382 				ire_refrele(save_ire);
9383 				save_ire = NULL;
9384 			}
9385 			if (ire == NULL)
9386 				break;
9387 
9388 			ire->ire_marks |= ire_marks;
9389 			/*
9390 			 * Construct message chain for the resolver of the
9391 			 * form:
9392 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9393 			 *
9394 			 * NOTE : ire will be added later when the response
9395 			 * comes back from ARP. If the response does not
9396 			 * come back, ARP frees the packet. For this reason,
9397 			 * we can't REFHOLD the bucket of save_ire to prevent
9398 			 * deletions. We may not be able to REFRELE the
9399 			 * bucket if the response never comes back.
9400 			 * Thus, before adding the ire, ire_add_v4 will make
9401 			 * sure that the interface route does not get deleted.
9402 			 * This is the only case unlike ip_newroute_v6,
9403 			 * ip_newroute_ipif_v6 where we can always prevent
9404 			 * deletions because ire_add_then_send is called after
9405 			 * creating the IRE.
9406 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9407 			 * does not add this IRE into the IRE CACHE.
9408 			 */
9409 			ASSERT(ire->ire_mp != NULL);
9410 			ire->ire_mp->b_cont = first_mp;
9411 			/* Have saved_mp handy, for cleanup if canput fails */
9412 			saved_mp = mp;
9413 			mp = copyb(res_mp);
9414 			if (mp == NULL) {
9415 				/* Prepare for cleanup */
9416 				mp = saved_mp; /* pkt */
9417 				ire_delete(ire); /* ire_mp */
9418 				ire = NULL;
9419 				if (copy_mp != NULL) {
9420 					MULTIRT_DEBUG_UNTAG(copy_mp);
9421 					freemsg(copy_mp);
9422 					copy_mp = NULL;
9423 				}
9424 				break;
9425 			}
9426 			linkb(mp, ire->ire_mp);
9427 
9428 			/*
9429 			 * Fill in the source and dest addrs for the resolver.
9430 			 * NOTE: this depends on memory layouts imposed by
9431 			 * ill_init().
9432 			 */
9433 			areq = (areq_t *)mp->b_rptr;
9434 			addrp = (ipaddr_t *)((char *)areq +
9435 			    areq->areq_sender_addr_offset);
9436 			*addrp = ire->ire_src_addr;
9437 			addrp = (ipaddr_t *)((char *)areq +
9438 			    areq->areq_target_addr_offset);
9439 			*addrp = dst;
9440 			/* Up to the resolver. */
9441 			if (canputnext(dst_ill->ill_rq) &&
9442 			    !(dst_ill->ill_arp_closing)) {
9443 				putnext(dst_ill->ill_rq, mp);
9444 				/*
9445 				 * The response will come back in ip_wput
9446 				 * with db_type IRE_DB_TYPE.
9447 				 */
9448 			} else {
9449 				mp->b_cont = NULL;
9450 				freeb(mp); /* areq */
9451 				ire_delete(ire); /* ire_mp */
9452 				saved_mp->b_next = NULL;
9453 				saved_mp->b_prev = NULL;
9454 				freemsg(first_mp); /* pkt */
9455 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9456 			}
9457 
9458 			if (fire != NULL) {
9459 				ire_refrele(fire);
9460 				fire = NULL;
9461 			}
9462 
9463 
9464 			/*
9465 			 * The resolution loop is re-entered if this was
9466 			 * requested through flags and we actually are
9467 			 * in a multirouting case.
9468 			 */
9469 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9470 				boolean_t need_resolve =
9471 				    ire_multirt_need_resolve(ipha_dst,
9472 				    MBLK_GETLABEL(copy_mp), ipst);
9473 				if (!need_resolve) {
9474 					MULTIRT_DEBUG_UNTAG(copy_mp);
9475 					freemsg(copy_mp);
9476 					copy_mp = NULL;
9477 				} else {
9478 					/*
9479 					 * ipif_lookup_group() calls
9480 					 * ire_lookup_multi() that uses
9481 					 * ire_ftable_lookup() to find
9482 					 * an IRE_INTERFACE for the group.
9483 					 * In the multirt case,
9484 					 * ire_lookup_multi() then invokes
9485 					 * ire_multirt_lookup() to find
9486 					 * the next resolvable ire.
9487 					 * As a result, we obtain an new
9488 					 * interface, derived from the
9489 					 * next ire.
9490 					 */
9491 					ipif_refrele(ipif);
9492 					ipif = ipif_lookup_group(ipha_dst,
9493 					    zoneid, ipst);
9494 					if (ipif != NULL) {
9495 						mp = copy_mp;
9496 						copy_mp = NULL;
9497 						multirt_resolve_next = B_TRUE;
9498 						continue;
9499 					} else {
9500 						freemsg(copy_mp);
9501 					}
9502 				}
9503 			}
9504 			if (ipif != NULL)
9505 				ipif_refrele(ipif);
9506 			ill_refrele(dst_ill);
9507 			ipif_refrele(src_ipif);
9508 			return;
9509 		default:
9510 			break;
9511 		}
9512 	} while (multirt_resolve_next);
9513 
9514 err_ret:
9515 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9516 	if (fire != NULL)
9517 		ire_refrele(fire);
9518 	ipif_refrele(ipif);
9519 	/* Did this packet originate externally? */
9520 	if (dst_ill != NULL)
9521 		ill_refrele(dst_ill);
9522 	if (src_ipif != NULL)
9523 		ipif_refrele(src_ipif);
9524 	if (mp->b_prev || mp->b_next) {
9525 		mp->b_next = NULL;
9526 		mp->b_prev = NULL;
9527 	} else {
9528 		/*
9529 		 * Since ip_wput() isn't close to finished, we fill
9530 		 * in enough of the header for credible error reporting.
9531 		 */
9532 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9533 			/* Failed */
9534 			freemsg(first_mp);
9535 			if (ire != NULL)
9536 				ire_refrele(ire);
9537 			return;
9538 		}
9539 	}
9540 	/*
9541 	 * At this point we will have ire only if RTF_BLACKHOLE
9542 	 * or RTF_REJECT flags are set on the IRE. It will not
9543 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9544 	 */
9545 	if (ire != NULL) {
9546 		if (ire->ire_flags & RTF_BLACKHOLE) {
9547 			ire_refrele(ire);
9548 			freemsg(first_mp);
9549 			return;
9550 		}
9551 		ire_refrele(ire);
9552 	}
9553 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9554 }
9555 
9556 /* Name/Value Table Lookup Routine */
9557 char *
9558 ip_nv_lookup(nv_t *nv, int value)
9559 {
9560 	if (!nv)
9561 		return (NULL);
9562 	for (; nv->nv_name; nv++) {
9563 		if (nv->nv_value == value)
9564 			return (nv->nv_name);
9565 	}
9566 	return ("unknown");
9567 }
9568 
9569 /*
9570  * This is a module open, i.e. this is a control stream for access
9571  * to a DLPI device.  We allocate an ill_t as the instance data in
9572  * this case.
9573  */
9574 int
9575 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9576 {
9577 	ill_t	*ill;
9578 	int	err;
9579 	zoneid_t zoneid;
9580 	netstack_t *ns;
9581 	ip_stack_t *ipst;
9582 
9583 	/*
9584 	 * Prevent unprivileged processes from pushing IP so that
9585 	 * they can't send raw IP.
9586 	 */
9587 	if (secpolicy_net_rawaccess(credp) != 0)
9588 		return (EPERM);
9589 
9590 	ns = netstack_find_by_cred(credp);
9591 	ASSERT(ns != NULL);
9592 	ipst = ns->netstack_ip;
9593 	ASSERT(ipst != NULL);
9594 
9595 	/*
9596 	 * For exclusive stacks we set the zoneid to zero
9597 	 * to make IP operate as if in the global zone.
9598 	 */
9599 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9600 		zoneid = GLOBAL_ZONEID;
9601 	else
9602 		zoneid = crgetzoneid(credp);
9603 
9604 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9605 	q->q_ptr = WR(q)->q_ptr = ill;
9606 	ill->ill_ipst = ipst;
9607 	ill->ill_zoneid = zoneid;
9608 
9609 	/*
9610 	 * ill_init initializes the ill fields and then sends down
9611 	 * down a DL_INFO_REQ after calling qprocson.
9612 	 */
9613 	err = ill_init(q, ill);
9614 	if (err != 0) {
9615 		mi_free(ill);
9616 		netstack_rele(ipst->ips_netstack);
9617 		q->q_ptr = NULL;
9618 		WR(q)->q_ptr = NULL;
9619 		return (err);
9620 	}
9621 
9622 	/* ill_init initializes the ipsq marking this thread as writer */
9623 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9624 	/* Wait for the DL_INFO_ACK */
9625 	mutex_enter(&ill->ill_lock);
9626 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9627 		/*
9628 		 * Return value of 0 indicates a pending signal.
9629 		 */
9630 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9631 		if (err == 0) {
9632 			mutex_exit(&ill->ill_lock);
9633 			(void) ip_close(q, 0);
9634 			return (EINTR);
9635 		}
9636 	}
9637 	mutex_exit(&ill->ill_lock);
9638 
9639 	/*
9640 	 * ip_rput_other could have set an error  in ill_error on
9641 	 * receipt of M_ERROR.
9642 	 */
9643 
9644 	err = ill->ill_error;
9645 	if (err != 0) {
9646 		(void) ip_close(q, 0);
9647 		return (err);
9648 	}
9649 
9650 	ill->ill_credp = credp;
9651 	crhold(credp);
9652 
9653 	mutex_enter(&ipst->ips_ip_mi_lock);
9654 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9655 	    credp);
9656 	mutex_exit(&ipst->ips_ip_mi_lock);
9657 	if (err) {
9658 		(void) ip_close(q, 0);
9659 		return (err);
9660 	}
9661 	return (0);
9662 }
9663 
9664 /* IP open routine. */
9665 int
9666 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9667 {
9668 	conn_t 		*connp;
9669 	major_t		maj;
9670 	zoneid_t	zoneid;
9671 	netstack_t	*ns;
9672 	ip_stack_t	*ipst;
9673 
9674 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9675 
9676 	/* Allow reopen. */
9677 	if (q->q_ptr != NULL)
9678 		return (0);
9679 
9680 	if (sflag & MODOPEN) {
9681 		/* This is a module open */
9682 		return (ip_modopen(q, devp, flag, sflag, credp));
9683 	}
9684 
9685 	ns = netstack_find_by_cred(credp);
9686 	ASSERT(ns != NULL);
9687 	ipst = ns->netstack_ip;
9688 	ASSERT(ipst != NULL);
9689 
9690 	/*
9691 	 * For exclusive stacks we set the zoneid to zero
9692 	 * to make IP operate as if in the global zone.
9693 	 */
9694 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9695 		zoneid = GLOBAL_ZONEID;
9696 	else
9697 		zoneid = crgetzoneid(credp);
9698 
9699 	/*
9700 	 * We are opening as a device. This is an IP client stream, and we
9701 	 * allocate an conn_t as the instance data.
9702 	 */
9703 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9704 
9705 	/*
9706 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9707 	 * done by netstack_find_by_cred()
9708 	 */
9709 	netstack_rele(ipst->ips_netstack);
9710 
9711 	connp->conn_zoneid = zoneid;
9712 
9713 	connp->conn_upq = q;
9714 	q->q_ptr = WR(q)->q_ptr = connp;
9715 
9716 	if (flag & SO_SOCKSTR)
9717 		connp->conn_flags |= IPCL_SOCKET;
9718 
9719 	/* Minor tells us which /dev entry was opened */
9720 	if (geteminor(*devp) == IPV6_MINOR) {
9721 		connp->conn_flags |= IPCL_ISV6;
9722 		connp->conn_af_isv6 = B_TRUE;
9723 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
9724 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9725 	} else {
9726 		connp->conn_af_isv6 = B_FALSE;
9727 		connp->conn_pkt_isv6 = B_FALSE;
9728 	}
9729 
9730 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9731 		/* CONN_DEC_REF takes care of netstack_rele() */
9732 		q->q_ptr = WR(q)->q_ptr = NULL;
9733 		CONN_DEC_REF(connp);
9734 		return (EBUSY);
9735 	}
9736 
9737 	maj = getemajor(*devp);
9738 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9739 
9740 	/*
9741 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9742 	 */
9743 	connp->conn_cred = credp;
9744 	crhold(connp->conn_cred);
9745 
9746 	/*
9747 	 * If the caller has the process-wide flag set, then default to MAC
9748 	 * exempt mode.  This allows read-down to unlabeled hosts.
9749 	 */
9750 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9751 		connp->conn_mac_exempt = B_TRUE;
9752 
9753 	/*
9754 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9755 	 * administrative ops.  In these cases, we just need a normal conn_t
9756 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9757 	 * an error will be returned.
9758 	 */
9759 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9760 		connp->conn_rq = q;
9761 		connp->conn_wq = WR(q);
9762 	} else {
9763 		connp->conn_ulp = IPPROTO_SCTP;
9764 		connp->conn_rq = connp->conn_wq = NULL;
9765 	}
9766 	/* Non-zero default values */
9767 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9768 
9769 	/*
9770 	 * Make the conn globally visible to walkers
9771 	 */
9772 	mutex_enter(&connp->conn_lock);
9773 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9774 	mutex_exit(&connp->conn_lock);
9775 	ASSERT(connp->conn_ref == 1);
9776 
9777 	qprocson(q);
9778 
9779 	return (0);
9780 }
9781 
9782 /*
9783  * Change q_qinfo based on the value of isv6.
9784  * This can not called on an ill queue.
9785  * Note that there is no race since either q_qinfo works for conn queues - it
9786  * is just an optimization to enter the best wput routine directly.
9787  */
9788 void
9789 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
9790 {
9791 	ASSERT(q->q_flag & QREADR);
9792 	ASSERT(WR(q)->q_next == NULL);
9793 	ASSERT(q->q_ptr != NULL);
9794 
9795 	if (minor == IPV6_MINOR)  {
9796 		if (bump_mib) {
9797 			BUMP_MIB(&ipst->ips_ip6_mib,
9798 			    ipIfStatsOutSwitchIPVersion);
9799 		}
9800 		q->q_qinfo = &rinit_ipv6;
9801 		WR(q)->q_qinfo = &winit_ipv6;
9802 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9803 	} else {
9804 		if (bump_mib) {
9805 			BUMP_MIB(&ipst->ips_ip_mib,
9806 			    ipIfStatsOutSwitchIPVersion);
9807 		}
9808 		q->q_qinfo = &iprinit;
9809 		WR(q)->q_qinfo = &ipwinit;
9810 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9811 	}
9812 
9813 }
9814 
9815 /*
9816  * See if IPsec needs loading because of the options in mp.
9817  */
9818 static boolean_t
9819 ipsec_opt_present(mblk_t *mp)
9820 {
9821 	uint8_t *optcp, *next_optcp, *opt_endcp;
9822 	struct opthdr *opt;
9823 	struct T_opthdr *topt;
9824 	int opthdr_len;
9825 	t_uscalar_t optname, optlevel;
9826 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9827 	ipsec_req_t *ipsr;
9828 
9829 	/*
9830 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9831 	 * return TRUE.
9832 	 */
9833 
9834 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9835 	opt_endcp = optcp + tor->OPT_length;
9836 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9837 		opthdr_len = sizeof (struct T_opthdr);
9838 	} else {		/* O_OPTMGMT_REQ */
9839 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9840 		opthdr_len = sizeof (struct opthdr);
9841 	}
9842 	for (; optcp < opt_endcp; optcp = next_optcp) {
9843 		if (optcp + opthdr_len > opt_endcp)
9844 			return (B_FALSE);	/* Not enough option header. */
9845 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9846 			topt = (struct T_opthdr *)optcp;
9847 			optlevel = topt->level;
9848 			optname = topt->name;
9849 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9850 		} else {
9851 			opt = (struct opthdr *)optcp;
9852 			optlevel = opt->level;
9853 			optname = opt->name;
9854 			next_optcp = optcp + opthdr_len +
9855 			    _TPI_ALIGN_OPT(opt->len);
9856 		}
9857 		if ((next_optcp < optcp) || /* wraparound pointer space */
9858 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9859 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9860 			return (B_FALSE); /* bad option buffer */
9861 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9862 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9863 			/*
9864 			 * Check to see if it's an all-bypass or all-zeroes
9865 			 * IPsec request.  Don't bother loading IPsec if
9866 			 * the socket doesn't want to use it.  (A good example
9867 			 * is a bypass request.)
9868 			 *
9869 			 * Basically, if any of the non-NEVER bits are set,
9870 			 * load IPsec.
9871 			 */
9872 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9873 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9874 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9875 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9876 			    != 0)
9877 				return (B_TRUE);
9878 		}
9879 	}
9880 	return (B_FALSE);
9881 }
9882 
9883 /*
9884  * If conn is is waiting for ipsec to finish loading, kick it.
9885  */
9886 /* ARGSUSED */
9887 static void
9888 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9889 {
9890 	t_scalar_t	optreq_prim;
9891 	mblk_t		*mp;
9892 	cred_t		*cr;
9893 	int		err = 0;
9894 
9895 	/*
9896 	 * This function is called, after ipsec loading is complete.
9897 	 * Since IP checks exclusively and atomically (i.e it prevents
9898 	 * ipsec load from completing until ip_optcom_req completes)
9899 	 * whether ipsec load is complete, there cannot be a race with IP
9900 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9901 	 */
9902 	mutex_enter(&connp->conn_lock);
9903 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9904 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9905 		mp = connp->conn_ipsec_opt_mp;
9906 		connp->conn_ipsec_opt_mp = NULL;
9907 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9908 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9909 		mutex_exit(&connp->conn_lock);
9910 
9911 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9912 
9913 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9914 		if (optreq_prim == T_OPTMGMT_REQ) {
9915 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9916 			    &ip_opt_obj);
9917 		} else {
9918 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9919 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9920 			    &ip_opt_obj);
9921 		}
9922 		if (err != EINPROGRESS)
9923 			CONN_OPER_PENDING_DONE(connp);
9924 		return;
9925 	}
9926 	mutex_exit(&connp->conn_lock);
9927 }
9928 
9929 /*
9930  * Called from the ipsec_loader thread, outside any perimeter, to tell
9931  * ip qenable any of the queues waiting for the ipsec loader to
9932  * complete.
9933  */
9934 void
9935 ip_ipsec_load_complete(ipsec_stack_t *ipss)
9936 {
9937 	netstack_t *ns = ipss->ipsec_netstack;
9938 
9939 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
9940 }
9941 
9942 /*
9943  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9944  * determines the grp on which it has to become exclusive, queues the mp
9945  * and sq draining restarts the optmgmt
9946  */
9947 static boolean_t
9948 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9949 {
9950 	conn_t *connp = Q_TO_CONN(q);
9951 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
9952 
9953 	/*
9954 	 * Take IPsec requests and treat them special.
9955 	 */
9956 	if (ipsec_opt_present(mp)) {
9957 		/* First check if IPsec is loaded. */
9958 		mutex_enter(&ipss->ipsec_loader_lock);
9959 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
9960 			mutex_exit(&ipss->ipsec_loader_lock);
9961 			return (B_FALSE);
9962 		}
9963 		mutex_enter(&connp->conn_lock);
9964 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9965 
9966 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9967 		connp->conn_ipsec_opt_mp = mp;
9968 		mutex_exit(&connp->conn_lock);
9969 		mutex_exit(&ipss->ipsec_loader_lock);
9970 
9971 		ipsec_loader_loadnow(ipss);
9972 		return (B_TRUE);
9973 	}
9974 	return (B_FALSE);
9975 }
9976 
9977 /*
9978  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9979  * all of them are copied to the conn_t. If the req is "zero", the policy is
9980  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9981  * fields.
9982  * We keep only the latest setting of the policy and thus policy setting
9983  * is not incremental/cumulative.
9984  *
9985  * Requests to set policies with multiple alternative actions will
9986  * go through a different API.
9987  */
9988 int
9989 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9990 {
9991 	uint_t ah_req = 0;
9992 	uint_t esp_req = 0;
9993 	uint_t se_req = 0;
9994 	ipsec_selkey_t sel;
9995 	ipsec_act_t *actp = NULL;
9996 	uint_t nact;
9997 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9998 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9999 	ipsec_policy_root_t *pr;
10000 	ipsec_policy_head_t *ph;
10001 	int fam;
10002 	boolean_t is_pol_reset;
10003 	int error = 0;
10004 	netstack_t	*ns = connp->conn_netstack;
10005 	ip_stack_t	*ipst = ns->netstack_ip;
10006 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10007 
10008 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10009 
10010 	/*
10011 	 * The IP_SEC_OPT option does not allow variable length parameters,
10012 	 * hence a request cannot be NULL.
10013 	 */
10014 	if (req == NULL)
10015 		return (EINVAL);
10016 
10017 	ah_req = req->ipsr_ah_req;
10018 	esp_req = req->ipsr_esp_req;
10019 	se_req = req->ipsr_self_encap_req;
10020 
10021 	/*
10022 	 * Are we dealing with a request to reset the policy (i.e.
10023 	 * zero requests).
10024 	 */
10025 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10026 	    (esp_req & REQ_MASK) == 0 &&
10027 	    (se_req & REQ_MASK) == 0);
10028 
10029 	if (!is_pol_reset) {
10030 		/*
10031 		 * If we couldn't load IPsec, fail with "protocol
10032 		 * not supported".
10033 		 * IPsec may not have been loaded for a request with zero
10034 		 * policies, so we don't fail in this case.
10035 		 */
10036 		mutex_enter(&ipss->ipsec_loader_lock);
10037 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10038 			mutex_exit(&ipss->ipsec_loader_lock);
10039 			return (EPROTONOSUPPORT);
10040 		}
10041 		mutex_exit(&ipss->ipsec_loader_lock);
10042 
10043 		/*
10044 		 * Test for valid requests. Invalid algorithms
10045 		 * need to be tested by IPSEC code because new
10046 		 * algorithms can be added dynamically.
10047 		 */
10048 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10049 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10050 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10051 			return (EINVAL);
10052 		}
10053 
10054 		/*
10055 		 * Only privileged users can issue these
10056 		 * requests.
10057 		 */
10058 		if (((ah_req & IPSEC_PREF_NEVER) ||
10059 		    (esp_req & IPSEC_PREF_NEVER) ||
10060 		    (se_req & IPSEC_PREF_NEVER)) &&
10061 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10062 			return (EPERM);
10063 		}
10064 
10065 		/*
10066 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10067 		 * are mutually exclusive.
10068 		 */
10069 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10070 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10071 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10072 			/* Both of them are set */
10073 			return (EINVAL);
10074 		}
10075 	}
10076 
10077 	mutex_enter(&connp->conn_lock);
10078 
10079 	/*
10080 	 * If we have already cached policies in ip_bind_connected*(), don't
10081 	 * let them change now. We cache policies for connections
10082 	 * whose src,dst [addr, port] is known.
10083 	 */
10084 	if (connp->conn_policy_cached) {
10085 		mutex_exit(&connp->conn_lock);
10086 		return (EINVAL);
10087 	}
10088 
10089 	/*
10090 	 * We have a zero policies, reset the connection policy if already
10091 	 * set. This will cause the connection to inherit the
10092 	 * global policy, if any.
10093 	 */
10094 	if (is_pol_reset) {
10095 		if (connp->conn_policy != NULL) {
10096 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10097 			connp->conn_policy = NULL;
10098 		}
10099 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10100 		connp->conn_in_enforce_policy = B_FALSE;
10101 		connp->conn_out_enforce_policy = B_FALSE;
10102 		mutex_exit(&connp->conn_lock);
10103 		return (0);
10104 	}
10105 
10106 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10107 	    ipst->ips_netstack);
10108 	if (ph == NULL)
10109 		goto enomem;
10110 
10111 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10112 	if (actp == NULL)
10113 		goto enomem;
10114 
10115 	/*
10116 	 * Always allocate IPv4 policy entries, since they can also
10117 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10118 	 */
10119 	bzero(&sel, sizeof (sel));
10120 	sel.ipsl_valid = IPSL_IPV4;
10121 
10122 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10123 	    ipst->ips_netstack);
10124 	if (pin4 == NULL)
10125 		goto enomem;
10126 
10127 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10128 	    ipst->ips_netstack);
10129 	if (pout4 == NULL)
10130 		goto enomem;
10131 
10132 	if (connp->conn_pkt_isv6) {
10133 		/*
10134 		 * We're looking at a v6 socket, also allocate the
10135 		 * v6-specific entries...
10136 		 */
10137 		sel.ipsl_valid = IPSL_IPV6;
10138 		pin6 = ipsec_policy_create(&sel, actp, nact,
10139 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10140 		if (pin6 == NULL)
10141 			goto enomem;
10142 
10143 		pout6 = ipsec_policy_create(&sel, actp, nact,
10144 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10145 		if (pout6 == NULL)
10146 			goto enomem;
10147 
10148 		/*
10149 		 * .. and file them away in the right place.
10150 		 */
10151 		fam = IPSEC_AF_V6;
10152 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10153 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10154 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10155 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10156 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10157 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10158 	}
10159 
10160 	ipsec_actvec_free(actp, nact);
10161 
10162 	/*
10163 	 * File the v4 policies.
10164 	 */
10165 	fam = IPSEC_AF_V4;
10166 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10167 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10168 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10169 
10170 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10171 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10172 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10173 
10174 	/*
10175 	 * If the requests need security, set enforce_policy.
10176 	 * If the requests are IPSEC_PREF_NEVER, one should
10177 	 * still set conn_out_enforce_policy so that an ipsec_out
10178 	 * gets attached in ip_wput. This is needed so that
10179 	 * for connections that we don't cache policy in ip_bind,
10180 	 * if global policy matches in ip_wput_attach_policy, we
10181 	 * don't wrongly inherit global policy. Similarly, we need
10182 	 * to set conn_in_enforce_policy also so that we don't verify
10183 	 * policy wrongly.
10184 	 */
10185 	if ((ah_req & REQ_MASK) != 0 ||
10186 	    (esp_req & REQ_MASK) != 0 ||
10187 	    (se_req & REQ_MASK) != 0) {
10188 		connp->conn_in_enforce_policy = B_TRUE;
10189 		connp->conn_out_enforce_policy = B_TRUE;
10190 		connp->conn_flags |= IPCL_CHECK_POLICY;
10191 	}
10192 
10193 	mutex_exit(&connp->conn_lock);
10194 	return (error);
10195 #undef REQ_MASK
10196 
10197 	/*
10198 	 * Common memory-allocation-failure exit path.
10199 	 */
10200 enomem:
10201 	mutex_exit(&connp->conn_lock);
10202 	if (actp != NULL)
10203 		ipsec_actvec_free(actp, nact);
10204 	if (pin4 != NULL)
10205 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10206 	if (pout4 != NULL)
10207 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10208 	if (pin6 != NULL)
10209 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10210 	if (pout6 != NULL)
10211 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10212 	return (ENOMEM);
10213 }
10214 
10215 /*
10216  * Only for options that pass in an IP addr. Currently only V4 options
10217  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10218  * So this function assumes level is IPPROTO_IP
10219  */
10220 int
10221 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10222     mblk_t *first_mp)
10223 {
10224 	ipif_t *ipif = NULL;
10225 	int error;
10226 	ill_t *ill;
10227 	int zoneid;
10228 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10229 
10230 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10231 
10232 	if (addr != INADDR_ANY || checkonly) {
10233 		ASSERT(connp != NULL);
10234 		zoneid = IPCL_ZONEID(connp);
10235 		if (option == IP_NEXTHOP) {
10236 			ipif = ipif_lookup_onlink_addr(addr,
10237 			    connp->conn_zoneid, ipst);
10238 		} else {
10239 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10240 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10241 			    &error, ipst);
10242 		}
10243 		if (ipif == NULL) {
10244 			if (error == EINPROGRESS)
10245 				return (error);
10246 			else if ((option == IP_MULTICAST_IF) ||
10247 			    (option == IP_NEXTHOP))
10248 				return (EHOSTUNREACH);
10249 			else
10250 				return (EINVAL);
10251 		} else if (checkonly) {
10252 			if (option == IP_MULTICAST_IF) {
10253 				ill = ipif->ipif_ill;
10254 				/* not supported by the virtual network iface */
10255 				if (IS_VNI(ill)) {
10256 					ipif_refrele(ipif);
10257 					return (EINVAL);
10258 				}
10259 			}
10260 			ipif_refrele(ipif);
10261 			return (0);
10262 		}
10263 		ill = ipif->ipif_ill;
10264 		mutex_enter(&connp->conn_lock);
10265 		mutex_enter(&ill->ill_lock);
10266 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10267 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10268 			mutex_exit(&ill->ill_lock);
10269 			mutex_exit(&connp->conn_lock);
10270 			ipif_refrele(ipif);
10271 			return (option == IP_MULTICAST_IF ?
10272 			    EHOSTUNREACH : EINVAL);
10273 		}
10274 	} else {
10275 		mutex_enter(&connp->conn_lock);
10276 	}
10277 
10278 	/* None of the options below are supported on the VNI */
10279 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10280 		mutex_exit(&ill->ill_lock);
10281 		mutex_exit(&connp->conn_lock);
10282 		ipif_refrele(ipif);
10283 		return (EINVAL);
10284 	}
10285 
10286 	switch (option) {
10287 	case IP_DONTFAILOVER_IF:
10288 		/*
10289 		 * This option is used by in.mpathd to ensure
10290 		 * that IPMP probe packets only go out on the
10291 		 * test interfaces. in.mpathd sets this option
10292 		 * on the non-failover interfaces.
10293 		 * For backward compatibility, this option
10294 		 * implicitly sets IP_MULTICAST_IF, as used
10295 		 * be done in bind(), so that ip_wput gets
10296 		 * this ipif to send mcast packets.
10297 		 */
10298 		if (ipif != NULL) {
10299 			ASSERT(addr != INADDR_ANY);
10300 			connp->conn_nofailover_ill = ipif->ipif_ill;
10301 			connp->conn_multicast_ipif = ipif;
10302 		} else {
10303 			ASSERT(addr == INADDR_ANY);
10304 			connp->conn_nofailover_ill = NULL;
10305 			connp->conn_multicast_ipif = NULL;
10306 		}
10307 		break;
10308 
10309 	case IP_MULTICAST_IF:
10310 		connp->conn_multicast_ipif = ipif;
10311 		break;
10312 	case IP_NEXTHOP:
10313 		connp->conn_nexthop_v4 = addr;
10314 		connp->conn_nexthop_set = B_TRUE;
10315 		break;
10316 	}
10317 
10318 	if (ipif != NULL) {
10319 		mutex_exit(&ill->ill_lock);
10320 		mutex_exit(&connp->conn_lock);
10321 		ipif_refrele(ipif);
10322 		return (0);
10323 	}
10324 	mutex_exit(&connp->conn_lock);
10325 	/* We succeded in cleared the option */
10326 	return (0);
10327 }
10328 
10329 /*
10330  * For options that pass in an ifindex specifying the ill. V6 options always
10331  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10332  */
10333 int
10334 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10335     int level, int option, mblk_t *first_mp)
10336 {
10337 	ill_t *ill = NULL;
10338 	int error = 0;
10339 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10340 
10341 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10342 	if (ifindex != 0) {
10343 		ASSERT(connp != NULL);
10344 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10345 		    first_mp, ip_restart_optmgmt, &error, ipst);
10346 		if (ill != NULL) {
10347 			if (checkonly) {
10348 				/* not supported by the virtual network iface */
10349 				if (IS_VNI(ill)) {
10350 					ill_refrele(ill);
10351 					return (EINVAL);
10352 				}
10353 				ill_refrele(ill);
10354 				return (0);
10355 			}
10356 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10357 			    0, NULL)) {
10358 				ill_refrele(ill);
10359 				ill = NULL;
10360 				mutex_enter(&connp->conn_lock);
10361 				goto setit;
10362 			}
10363 			mutex_enter(&connp->conn_lock);
10364 			mutex_enter(&ill->ill_lock);
10365 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10366 				mutex_exit(&ill->ill_lock);
10367 				mutex_exit(&connp->conn_lock);
10368 				ill_refrele(ill);
10369 				ill = NULL;
10370 				mutex_enter(&connp->conn_lock);
10371 			}
10372 			goto setit;
10373 		} else if (error == EINPROGRESS) {
10374 			return (error);
10375 		} else {
10376 			error = 0;
10377 		}
10378 	}
10379 	mutex_enter(&connp->conn_lock);
10380 setit:
10381 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10382 
10383 	/*
10384 	 * The options below assume that the ILL (if any) transmits and/or
10385 	 * receives traffic. Neither of which is true for the virtual network
10386 	 * interface, so fail setting these on a VNI.
10387 	 */
10388 	if (IS_VNI(ill)) {
10389 		ASSERT(ill != NULL);
10390 		mutex_exit(&ill->ill_lock);
10391 		mutex_exit(&connp->conn_lock);
10392 		ill_refrele(ill);
10393 		return (EINVAL);
10394 	}
10395 
10396 	if (level == IPPROTO_IP) {
10397 		switch (option) {
10398 		case IP_BOUND_IF:
10399 			connp->conn_incoming_ill = ill;
10400 			connp->conn_outgoing_ill = ill;
10401 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10402 			    0 : ifindex;
10403 			break;
10404 
10405 		case IP_XMIT_IF:
10406 			/*
10407 			 * Similar to IP_BOUND_IF, but this only
10408 			 * determines the outgoing interface for
10409 			 * unicast packets. Also no IRE_CACHE entry
10410 			 * is added for the destination of the
10411 			 * outgoing packets.
10412 			 */
10413 			connp->conn_xmit_if_ill = ill;
10414 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10415 			    0 : ifindex;
10416 			break;
10417 
10418 		case IP_MULTICAST_IF:
10419 			/*
10420 			 * This option is an internal special. The socket
10421 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10422 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10423 			 * specifies an ifindex and we try first on V6 ill's.
10424 			 * If we don't find one, we they try using on v4 ill's
10425 			 * intenally and we come here.
10426 			 */
10427 			if (!checkonly && ill != NULL) {
10428 				ipif_t	*ipif;
10429 				ipif = ill->ill_ipif;
10430 
10431 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10432 					mutex_exit(&ill->ill_lock);
10433 					mutex_exit(&connp->conn_lock);
10434 					ill_refrele(ill);
10435 					ill = NULL;
10436 					mutex_enter(&connp->conn_lock);
10437 				} else {
10438 					connp->conn_multicast_ipif = ipif;
10439 				}
10440 			}
10441 			break;
10442 		}
10443 	} else {
10444 		switch (option) {
10445 		case IPV6_BOUND_IF:
10446 			connp->conn_incoming_ill = ill;
10447 			connp->conn_outgoing_ill = ill;
10448 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10449 			    0 : ifindex;
10450 			break;
10451 
10452 		case IPV6_BOUND_PIF:
10453 			/*
10454 			 * Limit all transmit to this ill.
10455 			 * Unlike IPV6_BOUND_IF, using this option
10456 			 * prevents load spreading and failover from
10457 			 * happening when the interface is part of the
10458 			 * group. That's why we don't need to remember
10459 			 * the ifindex in orig_bound_ifindex as in
10460 			 * IPV6_BOUND_IF.
10461 			 */
10462 			connp->conn_outgoing_pill = ill;
10463 			break;
10464 
10465 		case IPV6_DONTFAILOVER_IF:
10466 			/*
10467 			 * This option is used by in.mpathd to ensure
10468 			 * that IPMP probe packets only go out on the
10469 			 * test interfaces. in.mpathd sets this option
10470 			 * on the non-failover interfaces.
10471 			 */
10472 			connp->conn_nofailover_ill = ill;
10473 			/*
10474 			 * For backward compatibility, this option
10475 			 * implicitly sets ip_multicast_ill as used in
10476 			 * IP_MULTICAST_IF so that ip_wput gets
10477 			 * this ipif to send mcast packets.
10478 			 */
10479 			connp->conn_multicast_ill = ill;
10480 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10481 			    0 : ifindex;
10482 			break;
10483 
10484 		case IPV6_MULTICAST_IF:
10485 			/*
10486 			 * Set conn_multicast_ill to be the IPv6 ill.
10487 			 * Set conn_multicast_ipif to be an IPv4 ipif
10488 			 * for ifindex to make IPv4 mapped addresses
10489 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10490 			 * Even if no IPv6 ill exists for the ifindex
10491 			 * we need to check for an IPv4 ifindex in order
10492 			 * for this to work with mapped addresses. In that
10493 			 * case only set conn_multicast_ipif.
10494 			 */
10495 			if (!checkonly) {
10496 				if (ifindex == 0) {
10497 					connp->conn_multicast_ill = NULL;
10498 					connp->conn_orig_multicast_ifindex = 0;
10499 					connp->conn_multicast_ipif = NULL;
10500 				} else if (ill != NULL) {
10501 					connp->conn_multicast_ill = ill;
10502 					connp->conn_orig_multicast_ifindex =
10503 					    ifindex;
10504 				}
10505 			}
10506 			break;
10507 		}
10508 	}
10509 
10510 	if (ill != NULL) {
10511 		mutex_exit(&ill->ill_lock);
10512 		mutex_exit(&connp->conn_lock);
10513 		ill_refrele(ill);
10514 		return (0);
10515 	}
10516 	mutex_exit(&connp->conn_lock);
10517 	/*
10518 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10519 	 * locate the ill and could not set the option (ifindex != 0)
10520 	 */
10521 	return (ifindex == 0 ? 0 : EINVAL);
10522 }
10523 
10524 /* This routine sets socket options. */
10525 /* ARGSUSED */
10526 int
10527 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10528     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10529     void *dummy, cred_t *cr, mblk_t *first_mp)
10530 {
10531 	int		*i1 = (int *)invalp;
10532 	conn_t		*connp = Q_TO_CONN(q);
10533 	int		error = 0;
10534 	boolean_t	checkonly;
10535 	ire_t		*ire;
10536 	boolean_t	found;
10537 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10538 
10539 	switch (optset_context) {
10540 
10541 	case SETFN_OPTCOM_CHECKONLY:
10542 		checkonly = B_TRUE;
10543 		/*
10544 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10545 		 * inlen != 0 implies value supplied and
10546 		 * 	we have to "pretend" to set it.
10547 		 * inlen == 0 implies that there is no
10548 		 * 	value part in T_CHECK request and just validation
10549 		 * done elsewhere should be enough, we just return here.
10550 		 */
10551 		if (inlen == 0) {
10552 			*outlenp = 0;
10553 			return (0);
10554 		}
10555 		break;
10556 	case SETFN_OPTCOM_NEGOTIATE:
10557 	case SETFN_UD_NEGOTIATE:
10558 	case SETFN_CONN_NEGOTIATE:
10559 		checkonly = B_FALSE;
10560 		break;
10561 	default:
10562 		/*
10563 		 * We should never get here
10564 		 */
10565 		*outlenp = 0;
10566 		return (EINVAL);
10567 	}
10568 
10569 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10570 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10571 
10572 	/*
10573 	 * For fixed length options, no sanity check
10574 	 * of passed in length is done. It is assumed *_optcom_req()
10575 	 * routines do the right thing.
10576 	 */
10577 
10578 	switch (level) {
10579 	case SOL_SOCKET:
10580 		/*
10581 		 * conn_lock protects the bitfields, and is used to
10582 		 * set the fields atomically.
10583 		 */
10584 		switch (name) {
10585 		case SO_BROADCAST:
10586 			if (!checkonly) {
10587 				/* TODO: use value someplace? */
10588 				mutex_enter(&connp->conn_lock);
10589 				connp->conn_broadcast = *i1 ? 1 : 0;
10590 				mutex_exit(&connp->conn_lock);
10591 			}
10592 			break;	/* goto sizeof (int) option return */
10593 		case SO_USELOOPBACK:
10594 			if (!checkonly) {
10595 				/* TODO: use value someplace? */
10596 				mutex_enter(&connp->conn_lock);
10597 				connp->conn_loopback = *i1 ? 1 : 0;
10598 				mutex_exit(&connp->conn_lock);
10599 			}
10600 			break;	/* goto sizeof (int) option return */
10601 		case SO_DONTROUTE:
10602 			if (!checkonly) {
10603 				mutex_enter(&connp->conn_lock);
10604 				connp->conn_dontroute = *i1 ? 1 : 0;
10605 				mutex_exit(&connp->conn_lock);
10606 			}
10607 			break;	/* goto sizeof (int) option return */
10608 		case SO_REUSEADDR:
10609 			if (!checkonly) {
10610 				mutex_enter(&connp->conn_lock);
10611 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10612 				mutex_exit(&connp->conn_lock);
10613 			}
10614 			break;	/* goto sizeof (int) option return */
10615 		case SO_PROTOTYPE:
10616 			if (!checkonly) {
10617 				mutex_enter(&connp->conn_lock);
10618 				connp->conn_proto = *i1;
10619 				mutex_exit(&connp->conn_lock);
10620 			}
10621 			break;	/* goto sizeof (int) option return */
10622 		case SO_ALLZONES:
10623 			if (!checkonly) {
10624 				mutex_enter(&connp->conn_lock);
10625 				if (IPCL_IS_BOUND(connp)) {
10626 					mutex_exit(&connp->conn_lock);
10627 					return (EINVAL);
10628 				}
10629 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10630 				mutex_exit(&connp->conn_lock);
10631 			}
10632 			break;	/* goto sizeof (int) option return */
10633 		case SO_ANON_MLP:
10634 			if (!checkonly) {
10635 				mutex_enter(&connp->conn_lock);
10636 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10637 				mutex_exit(&connp->conn_lock);
10638 			}
10639 			break;	/* goto sizeof (int) option return */
10640 		case SO_MAC_EXEMPT:
10641 			if (secpolicy_net_mac_aware(cr) != 0 ||
10642 			    IPCL_IS_BOUND(connp))
10643 				return (EACCES);
10644 			if (!checkonly) {
10645 				mutex_enter(&connp->conn_lock);
10646 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10647 				mutex_exit(&connp->conn_lock);
10648 			}
10649 			break;	/* goto sizeof (int) option return */
10650 		default:
10651 			/*
10652 			 * "soft" error (negative)
10653 			 * option not handled at this level
10654 			 * Note: Do not modify *outlenp
10655 			 */
10656 			return (-EINVAL);
10657 		}
10658 		break;
10659 	case IPPROTO_IP:
10660 		switch (name) {
10661 		case IP_NEXTHOP:
10662 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10663 				return (EPERM);
10664 			/* FALLTHRU */
10665 		case IP_MULTICAST_IF:
10666 		case IP_DONTFAILOVER_IF: {
10667 			ipaddr_t addr = *i1;
10668 
10669 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10670 			    first_mp);
10671 			if (error != 0)
10672 				return (error);
10673 			break;	/* goto sizeof (int) option return */
10674 		}
10675 
10676 		case IP_MULTICAST_TTL:
10677 			/* Recorded in transport above IP */
10678 			*outvalp = *invalp;
10679 			*outlenp = sizeof (uchar_t);
10680 			return (0);
10681 		case IP_MULTICAST_LOOP:
10682 			if (!checkonly) {
10683 				mutex_enter(&connp->conn_lock);
10684 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10685 				mutex_exit(&connp->conn_lock);
10686 			}
10687 			*outvalp = *invalp;
10688 			*outlenp = sizeof (uchar_t);
10689 			return (0);
10690 		case IP_ADD_MEMBERSHIP:
10691 		case MCAST_JOIN_GROUP:
10692 		case IP_DROP_MEMBERSHIP:
10693 		case MCAST_LEAVE_GROUP: {
10694 			struct ip_mreq *mreqp;
10695 			struct group_req *greqp;
10696 			ire_t *ire;
10697 			boolean_t done = B_FALSE;
10698 			ipaddr_t group, ifaddr;
10699 			struct sockaddr_in *sin;
10700 			uint32_t *ifindexp;
10701 			boolean_t mcast_opt = B_TRUE;
10702 			mcast_record_t fmode;
10703 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10704 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10705 
10706 			switch (name) {
10707 			case IP_ADD_MEMBERSHIP:
10708 				mcast_opt = B_FALSE;
10709 				/* FALLTHRU */
10710 			case MCAST_JOIN_GROUP:
10711 				fmode = MODE_IS_EXCLUDE;
10712 				optfn = ip_opt_add_group;
10713 				break;
10714 
10715 			case IP_DROP_MEMBERSHIP:
10716 				mcast_opt = B_FALSE;
10717 				/* FALLTHRU */
10718 			case MCAST_LEAVE_GROUP:
10719 				fmode = MODE_IS_INCLUDE;
10720 				optfn = ip_opt_delete_group;
10721 				break;
10722 			}
10723 
10724 			if (mcast_opt) {
10725 				greqp = (struct group_req *)i1;
10726 				sin = (struct sockaddr_in *)&greqp->gr_group;
10727 				if (sin->sin_family != AF_INET) {
10728 					*outlenp = 0;
10729 					return (ENOPROTOOPT);
10730 				}
10731 				group = (ipaddr_t)sin->sin_addr.s_addr;
10732 				ifaddr = INADDR_ANY;
10733 				ifindexp = &greqp->gr_interface;
10734 			} else {
10735 				mreqp = (struct ip_mreq *)i1;
10736 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10737 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10738 				ifindexp = NULL;
10739 			}
10740 
10741 			/*
10742 			 * In the multirouting case, we need to replicate
10743 			 * the request on all interfaces that will take part
10744 			 * in replication.  We do so because multirouting is
10745 			 * reflective, thus we will probably receive multi-
10746 			 * casts on those interfaces.
10747 			 * The ip_multirt_apply_membership() succeeds if the
10748 			 * operation succeeds on at least one interface.
10749 			 */
10750 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10751 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10752 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10753 			if (ire != NULL) {
10754 				if (ire->ire_flags & RTF_MULTIRT) {
10755 					error = ip_multirt_apply_membership(
10756 					    optfn, ire, connp, checkonly, group,
10757 					    fmode, INADDR_ANY, first_mp);
10758 					done = B_TRUE;
10759 				}
10760 				ire_refrele(ire);
10761 			}
10762 			if (!done) {
10763 				error = optfn(connp, checkonly, group, ifaddr,
10764 				    ifindexp, fmode, INADDR_ANY, first_mp);
10765 			}
10766 			if (error) {
10767 				/*
10768 				 * EINPROGRESS is a soft error, needs retry
10769 				 * so don't make *outlenp zero.
10770 				 */
10771 				if (error != EINPROGRESS)
10772 					*outlenp = 0;
10773 				return (error);
10774 			}
10775 			/* OK return - copy input buffer into output buffer */
10776 			if (invalp != outvalp) {
10777 				/* don't trust bcopy for identical src/dst */
10778 				bcopy(invalp, outvalp, inlen);
10779 			}
10780 			*outlenp = inlen;
10781 			return (0);
10782 		}
10783 		case IP_BLOCK_SOURCE:
10784 		case IP_UNBLOCK_SOURCE:
10785 		case IP_ADD_SOURCE_MEMBERSHIP:
10786 		case IP_DROP_SOURCE_MEMBERSHIP:
10787 		case MCAST_BLOCK_SOURCE:
10788 		case MCAST_UNBLOCK_SOURCE:
10789 		case MCAST_JOIN_SOURCE_GROUP:
10790 		case MCAST_LEAVE_SOURCE_GROUP: {
10791 			struct ip_mreq_source *imreqp;
10792 			struct group_source_req *gsreqp;
10793 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10794 			uint32_t ifindex = 0;
10795 			mcast_record_t fmode;
10796 			struct sockaddr_in *sin;
10797 			ire_t *ire;
10798 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10799 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10800 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10801 
10802 			switch (name) {
10803 			case IP_BLOCK_SOURCE:
10804 				mcast_opt = B_FALSE;
10805 				/* FALLTHRU */
10806 			case MCAST_BLOCK_SOURCE:
10807 				fmode = MODE_IS_EXCLUDE;
10808 				optfn = ip_opt_add_group;
10809 				break;
10810 
10811 			case IP_UNBLOCK_SOURCE:
10812 				mcast_opt = B_FALSE;
10813 				/* FALLTHRU */
10814 			case MCAST_UNBLOCK_SOURCE:
10815 				fmode = MODE_IS_EXCLUDE;
10816 				optfn = ip_opt_delete_group;
10817 				break;
10818 
10819 			case IP_ADD_SOURCE_MEMBERSHIP:
10820 				mcast_opt = B_FALSE;
10821 				/* FALLTHRU */
10822 			case MCAST_JOIN_SOURCE_GROUP:
10823 				fmode = MODE_IS_INCLUDE;
10824 				optfn = ip_opt_add_group;
10825 				break;
10826 
10827 			case IP_DROP_SOURCE_MEMBERSHIP:
10828 				mcast_opt = B_FALSE;
10829 				/* FALLTHRU */
10830 			case MCAST_LEAVE_SOURCE_GROUP:
10831 				fmode = MODE_IS_INCLUDE;
10832 				optfn = ip_opt_delete_group;
10833 				break;
10834 			}
10835 
10836 			if (mcast_opt) {
10837 				gsreqp = (struct group_source_req *)i1;
10838 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10839 					*outlenp = 0;
10840 					return (ENOPROTOOPT);
10841 				}
10842 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10843 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10844 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10845 				src = (ipaddr_t)sin->sin_addr.s_addr;
10846 				ifindex = gsreqp->gsr_interface;
10847 			} else {
10848 				imreqp = (struct ip_mreq_source *)i1;
10849 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10850 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10851 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10852 			}
10853 
10854 			/*
10855 			 * In the multirouting case, we need to replicate
10856 			 * the request as noted in the mcast cases above.
10857 			 */
10858 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10859 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10860 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10861 			if (ire != NULL) {
10862 				if (ire->ire_flags & RTF_MULTIRT) {
10863 					error = ip_multirt_apply_membership(
10864 					    optfn, ire, connp, checkonly, grp,
10865 					    fmode, src, first_mp);
10866 					done = B_TRUE;
10867 				}
10868 				ire_refrele(ire);
10869 			}
10870 			if (!done) {
10871 				error = optfn(connp, checkonly, grp, ifaddr,
10872 				    &ifindex, fmode, src, first_mp);
10873 			}
10874 			if (error != 0) {
10875 				/*
10876 				 * EINPROGRESS is a soft error, needs retry
10877 				 * so don't make *outlenp zero.
10878 				 */
10879 				if (error != EINPROGRESS)
10880 					*outlenp = 0;
10881 				return (error);
10882 			}
10883 			/* OK return - copy input buffer into output buffer */
10884 			if (invalp != outvalp) {
10885 				bcopy(invalp, outvalp, inlen);
10886 			}
10887 			*outlenp = inlen;
10888 			return (0);
10889 		}
10890 		case IP_SEC_OPT:
10891 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10892 			if (error != 0) {
10893 				*outlenp = 0;
10894 				return (error);
10895 			}
10896 			break;
10897 		case IP_HDRINCL:
10898 		case IP_OPTIONS:
10899 		case T_IP_OPTIONS:
10900 		case IP_TOS:
10901 		case T_IP_TOS:
10902 		case IP_TTL:
10903 		case IP_RECVDSTADDR:
10904 		case IP_RECVOPTS:
10905 			/* OK return - copy input buffer into output buffer */
10906 			if (invalp != outvalp) {
10907 				/* don't trust bcopy for identical src/dst */
10908 				bcopy(invalp, outvalp, inlen);
10909 			}
10910 			*outlenp = inlen;
10911 			return (0);
10912 		case IP_RECVIF:
10913 			/* Retrieve the inbound interface index */
10914 			if (!checkonly) {
10915 				mutex_enter(&connp->conn_lock);
10916 				connp->conn_recvif = *i1 ? 1 : 0;
10917 				mutex_exit(&connp->conn_lock);
10918 			}
10919 			break;	/* goto sizeof (int) option return */
10920 		case IP_RECVPKTINFO:
10921 			if (!checkonly) {
10922 				mutex_enter(&connp->conn_lock);
10923 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10924 				mutex_exit(&connp->conn_lock);
10925 			}
10926 			break;	/* goto sizeof (int) option return */
10927 		case IP_RECVSLLA:
10928 			/* Retrieve the source link layer address */
10929 			if (!checkonly) {
10930 				mutex_enter(&connp->conn_lock);
10931 				connp->conn_recvslla = *i1 ? 1 : 0;
10932 				mutex_exit(&connp->conn_lock);
10933 			}
10934 			break;	/* goto sizeof (int) option return */
10935 		case MRT_INIT:
10936 		case MRT_DONE:
10937 		case MRT_ADD_VIF:
10938 		case MRT_DEL_VIF:
10939 		case MRT_ADD_MFC:
10940 		case MRT_DEL_MFC:
10941 		case MRT_ASSERT:
10942 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10943 				*outlenp = 0;
10944 				return (error);
10945 			}
10946 			error = ip_mrouter_set((int)name, q, checkonly,
10947 			    (uchar_t *)invalp, inlen, first_mp);
10948 			if (error) {
10949 				*outlenp = 0;
10950 				return (error);
10951 			}
10952 			/* OK return - copy input buffer into output buffer */
10953 			if (invalp != outvalp) {
10954 				/* don't trust bcopy for identical src/dst */
10955 				bcopy(invalp, outvalp, inlen);
10956 			}
10957 			*outlenp = inlen;
10958 			return (0);
10959 		case IP_BOUND_IF:
10960 		case IP_XMIT_IF:
10961 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10962 			    level, name, first_mp);
10963 			if (error != 0)
10964 				return (error);
10965 			break; 		/* goto sizeof (int) option return */
10966 
10967 		case IP_UNSPEC_SRC:
10968 			/* Allow sending with a zero source address */
10969 			if (!checkonly) {
10970 				mutex_enter(&connp->conn_lock);
10971 				connp->conn_unspec_src = *i1 ? 1 : 0;
10972 				mutex_exit(&connp->conn_lock);
10973 			}
10974 			break;	/* goto sizeof (int) option return */
10975 		default:
10976 			/*
10977 			 * "soft" error (negative)
10978 			 * option not handled at this level
10979 			 * Note: Do not modify *outlenp
10980 			 */
10981 			return (-EINVAL);
10982 		}
10983 		break;
10984 	case IPPROTO_IPV6:
10985 		switch (name) {
10986 		case IPV6_BOUND_IF:
10987 		case IPV6_BOUND_PIF:
10988 		case IPV6_DONTFAILOVER_IF:
10989 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10990 			    level, name, first_mp);
10991 			if (error != 0)
10992 				return (error);
10993 			break; 		/* goto sizeof (int) option return */
10994 
10995 		case IPV6_MULTICAST_IF:
10996 			/*
10997 			 * The only possible errors are EINPROGRESS and
10998 			 * EINVAL. EINPROGRESS will be restarted and is not
10999 			 * a hard error. We call this option on both V4 and V6
11000 			 * If both return EINVAL, then this call returns
11001 			 * EINVAL. If at least one of them succeeds we
11002 			 * return success.
11003 			 */
11004 			found = B_FALSE;
11005 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11006 			    level, name, first_mp);
11007 			if (error == EINPROGRESS)
11008 				return (error);
11009 			if (error == 0)
11010 				found = B_TRUE;
11011 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11012 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11013 			if (error == 0)
11014 				found = B_TRUE;
11015 			if (!found)
11016 				return (error);
11017 			break; 		/* goto sizeof (int) option return */
11018 
11019 		case IPV6_MULTICAST_HOPS:
11020 			/* Recorded in transport above IP */
11021 			break;	/* goto sizeof (int) option return */
11022 		case IPV6_MULTICAST_LOOP:
11023 			if (!checkonly) {
11024 				mutex_enter(&connp->conn_lock);
11025 				connp->conn_multicast_loop = *i1;
11026 				mutex_exit(&connp->conn_lock);
11027 			}
11028 			break;	/* goto sizeof (int) option return */
11029 		case IPV6_JOIN_GROUP:
11030 		case MCAST_JOIN_GROUP:
11031 		case IPV6_LEAVE_GROUP:
11032 		case MCAST_LEAVE_GROUP: {
11033 			struct ipv6_mreq *ip_mreqp;
11034 			struct group_req *greqp;
11035 			ire_t *ire;
11036 			boolean_t done = B_FALSE;
11037 			in6_addr_t groupv6;
11038 			uint32_t ifindex;
11039 			boolean_t mcast_opt = B_TRUE;
11040 			mcast_record_t fmode;
11041 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11042 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11043 
11044 			switch (name) {
11045 			case IPV6_JOIN_GROUP:
11046 				mcast_opt = B_FALSE;
11047 				/* FALLTHRU */
11048 			case MCAST_JOIN_GROUP:
11049 				fmode = MODE_IS_EXCLUDE;
11050 				optfn = ip_opt_add_group_v6;
11051 				break;
11052 
11053 			case IPV6_LEAVE_GROUP:
11054 				mcast_opt = B_FALSE;
11055 				/* FALLTHRU */
11056 			case MCAST_LEAVE_GROUP:
11057 				fmode = MODE_IS_INCLUDE;
11058 				optfn = ip_opt_delete_group_v6;
11059 				break;
11060 			}
11061 
11062 			if (mcast_opt) {
11063 				struct sockaddr_in *sin;
11064 				struct sockaddr_in6 *sin6;
11065 				greqp = (struct group_req *)i1;
11066 				if (greqp->gr_group.ss_family == AF_INET) {
11067 					sin = (struct sockaddr_in *)
11068 					    &(greqp->gr_group);
11069 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11070 					    &groupv6);
11071 				} else {
11072 					sin6 = (struct sockaddr_in6 *)
11073 					    &(greqp->gr_group);
11074 					groupv6 = sin6->sin6_addr;
11075 				}
11076 				ifindex = greqp->gr_interface;
11077 			} else {
11078 				ip_mreqp = (struct ipv6_mreq *)i1;
11079 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11080 				ifindex = ip_mreqp->ipv6mr_interface;
11081 			}
11082 			/*
11083 			 * In the multirouting case, we need to replicate
11084 			 * the request on all interfaces that will take part
11085 			 * in replication.  We do so because multirouting is
11086 			 * reflective, thus we will probably receive multi-
11087 			 * casts on those interfaces.
11088 			 * The ip_multirt_apply_membership_v6() succeeds if
11089 			 * the operation succeeds on at least one interface.
11090 			 */
11091 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11092 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11093 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11094 			if (ire != NULL) {
11095 				if (ire->ire_flags & RTF_MULTIRT) {
11096 					error = ip_multirt_apply_membership_v6(
11097 					    optfn, ire, connp, checkonly,
11098 					    &groupv6, fmode, &ipv6_all_zeros,
11099 					    first_mp);
11100 					done = B_TRUE;
11101 				}
11102 				ire_refrele(ire);
11103 			}
11104 			if (!done) {
11105 				error = optfn(connp, checkonly, &groupv6,
11106 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11107 			}
11108 			if (error) {
11109 				/*
11110 				 * EINPROGRESS is a soft error, needs retry
11111 				 * so don't make *outlenp zero.
11112 				 */
11113 				if (error != EINPROGRESS)
11114 					*outlenp = 0;
11115 				return (error);
11116 			}
11117 			/* OK return - copy input buffer into output buffer */
11118 			if (invalp != outvalp) {
11119 				/* don't trust bcopy for identical src/dst */
11120 				bcopy(invalp, outvalp, inlen);
11121 			}
11122 			*outlenp = inlen;
11123 			return (0);
11124 		}
11125 		case MCAST_BLOCK_SOURCE:
11126 		case MCAST_UNBLOCK_SOURCE:
11127 		case MCAST_JOIN_SOURCE_GROUP:
11128 		case MCAST_LEAVE_SOURCE_GROUP: {
11129 			struct group_source_req *gsreqp;
11130 			in6_addr_t v6grp, v6src;
11131 			uint32_t ifindex;
11132 			mcast_record_t fmode;
11133 			ire_t *ire;
11134 			boolean_t done = B_FALSE;
11135 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11136 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11137 
11138 			switch (name) {
11139 			case MCAST_BLOCK_SOURCE:
11140 				fmode = MODE_IS_EXCLUDE;
11141 				optfn = ip_opt_add_group_v6;
11142 				break;
11143 			case MCAST_UNBLOCK_SOURCE:
11144 				fmode = MODE_IS_EXCLUDE;
11145 				optfn = ip_opt_delete_group_v6;
11146 				break;
11147 			case MCAST_JOIN_SOURCE_GROUP:
11148 				fmode = MODE_IS_INCLUDE;
11149 				optfn = ip_opt_add_group_v6;
11150 				break;
11151 			case MCAST_LEAVE_SOURCE_GROUP:
11152 				fmode = MODE_IS_INCLUDE;
11153 				optfn = ip_opt_delete_group_v6;
11154 				break;
11155 			}
11156 
11157 			gsreqp = (struct group_source_req *)i1;
11158 			ifindex = gsreqp->gsr_interface;
11159 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11160 				struct sockaddr_in *s;
11161 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11162 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11163 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11164 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11165 			} else {
11166 				struct sockaddr_in6 *s6;
11167 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11168 				v6grp = s6->sin6_addr;
11169 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11170 				v6src = s6->sin6_addr;
11171 			}
11172 
11173 			/*
11174 			 * In the multirouting case, we need to replicate
11175 			 * the request as noted in the mcast cases above.
11176 			 */
11177 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11178 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11179 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11180 			if (ire != NULL) {
11181 				if (ire->ire_flags & RTF_MULTIRT) {
11182 					error = ip_multirt_apply_membership_v6(
11183 					    optfn, ire, connp, checkonly,
11184 					    &v6grp, fmode, &v6src, first_mp);
11185 					done = B_TRUE;
11186 				}
11187 				ire_refrele(ire);
11188 			}
11189 			if (!done) {
11190 				error = optfn(connp, checkonly, &v6grp,
11191 				    ifindex, fmode, &v6src, first_mp);
11192 			}
11193 			if (error != 0) {
11194 				/*
11195 				 * EINPROGRESS is a soft error, needs retry
11196 				 * so don't make *outlenp zero.
11197 				 */
11198 				if (error != EINPROGRESS)
11199 					*outlenp = 0;
11200 				return (error);
11201 			}
11202 			/* OK return - copy input buffer into output buffer */
11203 			if (invalp != outvalp) {
11204 				bcopy(invalp, outvalp, inlen);
11205 			}
11206 			*outlenp = inlen;
11207 			return (0);
11208 		}
11209 		case IPV6_UNICAST_HOPS:
11210 			/* Recorded in transport above IP */
11211 			break;	/* goto sizeof (int) option return */
11212 		case IPV6_UNSPEC_SRC:
11213 			/* Allow sending with a zero source address */
11214 			if (!checkonly) {
11215 				mutex_enter(&connp->conn_lock);
11216 				connp->conn_unspec_src = *i1 ? 1 : 0;
11217 				mutex_exit(&connp->conn_lock);
11218 			}
11219 			break;	/* goto sizeof (int) option return */
11220 		case IPV6_RECVPKTINFO:
11221 			if (!checkonly) {
11222 				mutex_enter(&connp->conn_lock);
11223 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11224 				mutex_exit(&connp->conn_lock);
11225 			}
11226 			break;	/* goto sizeof (int) option return */
11227 		case IPV6_RECVTCLASS:
11228 			if (!checkonly) {
11229 				if (*i1 < 0 || *i1 > 1) {
11230 					return (EINVAL);
11231 				}
11232 				mutex_enter(&connp->conn_lock);
11233 				connp->conn_ipv6_recvtclass = *i1;
11234 				mutex_exit(&connp->conn_lock);
11235 			}
11236 			break;
11237 		case IPV6_RECVPATHMTU:
11238 			if (!checkonly) {
11239 				if (*i1 < 0 || *i1 > 1) {
11240 					return (EINVAL);
11241 				}
11242 				mutex_enter(&connp->conn_lock);
11243 				connp->conn_ipv6_recvpathmtu = *i1;
11244 				mutex_exit(&connp->conn_lock);
11245 			}
11246 			break;
11247 		case IPV6_RECVHOPLIMIT:
11248 			if (!checkonly) {
11249 				mutex_enter(&connp->conn_lock);
11250 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11251 				mutex_exit(&connp->conn_lock);
11252 			}
11253 			break;	/* goto sizeof (int) option return */
11254 		case IPV6_RECVHOPOPTS:
11255 			if (!checkonly) {
11256 				mutex_enter(&connp->conn_lock);
11257 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11258 				mutex_exit(&connp->conn_lock);
11259 			}
11260 			break;	/* goto sizeof (int) option return */
11261 		case IPV6_RECVDSTOPTS:
11262 			if (!checkonly) {
11263 				mutex_enter(&connp->conn_lock);
11264 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11265 				mutex_exit(&connp->conn_lock);
11266 			}
11267 			break;	/* goto sizeof (int) option return */
11268 		case IPV6_RECVRTHDR:
11269 			if (!checkonly) {
11270 				mutex_enter(&connp->conn_lock);
11271 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11272 				mutex_exit(&connp->conn_lock);
11273 			}
11274 			break;	/* goto sizeof (int) option return */
11275 		case IPV6_RECVRTHDRDSTOPTS:
11276 			if (!checkonly) {
11277 				mutex_enter(&connp->conn_lock);
11278 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11279 				mutex_exit(&connp->conn_lock);
11280 			}
11281 			break;	/* goto sizeof (int) option return */
11282 		case IPV6_PKTINFO:
11283 			if (inlen == 0)
11284 				return (-EINVAL);	/* clearing option */
11285 			error = ip6_set_pktinfo(cr, connp,
11286 			    (struct in6_pktinfo *)invalp, first_mp);
11287 			if (error != 0)
11288 				*outlenp = 0;
11289 			else
11290 				*outlenp = inlen;
11291 			return (error);
11292 		case IPV6_NEXTHOP: {
11293 			struct sockaddr_in6 *sin6;
11294 
11295 			/* Verify that the nexthop is reachable */
11296 			if (inlen == 0)
11297 				return (-EINVAL);	/* clearing option */
11298 
11299 			sin6 = (struct sockaddr_in6 *)invalp;
11300 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11301 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11302 			    NULL, MATCH_IRE_DEFAULT, ipst);
11303 
11304 			if (ire == NULL) {
11305 				*outlenp = 0;
11306 				return (EHOSTUNREACH);
11307 			}
11308 			ire_refrele(ire);
11309 			return (-EINVAL);
11310 		}
11311 		case IPV6_SEC_OPT:
11312 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11313 			if (error != 0) {
11314 				*outlenp = 0;
11315 				return (error);
11316 			}
11317 			break;
11318 		case IPV6_SRC_PREFERENCES: {
11319 			/*
11320 			 * This is implemented strictly in the ip module
11321 			 * (here and in tcp_opt_*() to accomodate tcp
11322 			 * sockets).  Modules above ip pass this option
11323 			 * down here since ip is the only one that needs to
11324 			 * be aware of source address preferences.
11325 			 *
11326 			 * This socket option only affects connected
11327 			 * sockets that haven't already bound to a specific
11328 			 * IPv6 address.  In other words, sockets that
11329 			 * don't call bind() with an address other than the
11330 			 * unspecified address and that call connect().
11331 			 * ip_bind_connected_v6() passes these preferences
11332 			 * to the ipif_select_source_v6() function.
11333 			 */
11334 			if (inlen != sizeof (uint32_t))
11335 				return (EINVAL);
11336 			error = ip6_set_src_preferences(connp,
11337 			    *(uint32_t *)invalp);
11338 			if (error != 0) {
11339 				*outlenp = 0;
11340 				return (error);
11341 			} else {
11342 				*outlenp = sizeof (uint32_t);
11343 			}
11344 			break;
11345 		}
11346 		case IPV6_V6ONLY:
11347 			if (*i1 < 0 || *i1 > 1) {
11348 				return (EINVAL);
11349 			}
11350 			mutex_enter(&connp->conn_lock);
11351 			connp->conn_ipv6_v6only = *i1;
11352 			mutex_exit(&connp->conn_lock);
11353 			break;
11354 		default:
11355 			return (-EINVAL);
11356 		}
11357 		break;
11358 	default:
11359 		/*
11360 		 * "soft" error (negative)
11361 		 * option not handled at this level
11362 		 * Note: Do not modify *outlenp
11363 		 */
11364 		return (-EINVAL);
11365 	}
11366 	/*
11367 	 * Common case of return from an option that is sizeof (int)
11368 	 */
11369 	*(int *)outvalp = *i1;
11370 	*outlenp = sizeof (int);
11371 	return (0);
11372 }
11373 
11374 /*
11375  * This routine gets default values of certain options whose default
11376  * values are maintained by protocol specific code
11377  */
11378 /* ARGSUSED */
11379 int
11380 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11381 {
11382 	int *i1 = (int *)ptr;
11383 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11384 
11385 	switch (level) {
11386 	case IPPROTO_IP:
11387 		switch (name) {
11388 		case IP_MULTICAST_TTL:
11389 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11390 			return (sizeof (uchar_t));
11391 		case IP_MULTICAST_LOOP:
11392 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11393 			return (sizeof (uchar_t));
11394 		default:
11395 			return (-1);
11396 		}
11397 	case IPPROTO_IPV6:
11398 		switch (name) {
11399 		case IPV6_UNICAST_HOPS:
11400 			*i1 = ipst->ips_ipv6_def_hops;
11401 			return (sizeof (int));
11402 		case IPV6_MULTICAST_HOPS:
11403 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11404 			return (sizeof (int));
11405 		case IPV6_MULTICAST_LOOP:
11406 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11407 			return (sizeof (int));
11408 		case IPV6_V6ONLY:
11409 			*i1 = 1;
11410 			return (sizeof (int));
11411 		default:
11412 			return (-1);
11413 		}
11414 	default:
11415 		return (-1);
11416 	}
11417 	/* NOTREACHED */
11418 }
11419 
11420 /*
11421  * Given a destination address and a pointer to where to put the information
11422  * this routine fills in the mtuinfo.
11423  */
11424 int
11425 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11426     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11427 {
11428 	ire_t *ire;
11429 	ip_stack_t	*ipst = ns->netstack_ip;
11430 
11431 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11432 		return (-1);
11433 
11434 	bzero(mtuinfo, sizeof (*mtuinfo));
11435 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11436 	mtuinfo->ip6m_addr.sin6_port = port;
11437 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11438 
11439 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11440 	if (ire != NULL) {
11441 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11442 		ire_refrele(ire);
11443 	} else {
11444 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11445 	}
11446 	return (sizeof (struct ip6_mtuinfo));
11447 }
11448 
11449 /*
11450  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11451  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11452  * isn't.  This doesn't matter as the error checking is done properly for the
11453  * other MRT options coming in through ip_opt_set.
11454  */
11455 int
11456 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11457 {
11458 	conn_t		*connp = Q_TO_CONN(q);
11459 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11460 
11461 	switch (level) {
11462 	case IPPROTO_IP:
11463 		switch (name) {
11464 		case MRT_VERSION:
11465 		case MRT_ASSERT:
11466 			(void) ip_mrouter_get(name, q, ptr);
11467 			return (sizeof (int));
11468 		case IP_SEC_OPT:
11469 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11470 		case IP_NEXTHOP:
11471 			if (connp->conn_nexthop_set) {
11472 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11473 				return (sizeof (ipaddr_t));
11474 			} else
11475 				return (0);
11476 		case IP_RECVPKTINFO:
11477 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11478 			return (sizeof (int));
11479 		default:
11480 			break;
11481 		}
11482 		break;
11483 	case IPPROTO_IPV6:
11484 		switch (name) {
11485 		case IPV6_SEC_OPT:
11486 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11487 		case IPV6_SRC_PREFERENCES: {
11488 			return (ip6_get_src_preferences(connp,
11489 			    (uint32_t *)ptr));
11490 		}
11491 		case IPV6_V6ONLY:
11492 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11493 			return (sizeof (int));
11494 		case IPV6_PATHMTU:
11495 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11496 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11497 		default:
11498 			break;
11499 		}
11500 		break;
11501 	default:
11502 		break;
11503 	}
11504 	return (-1);
11505 }
11506 
11507 /* Named Dispatch routine to get a current value out of our parameter table. */
11508 /* ARGSUSED */
11509 static int
11510 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11511 {
11512 	ipparam_t *ippa = (ipparam_t *)cp;
11513 
11514 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11515 	return (0);
11516 }
11517 
11518 /* ARGSUSED */
11519 static int
11520 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11521 {
11522 
11523 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11524 	return (0);
11525 }
11526 
11527 /*
11528  * Set ip{,6}_forwarding values.  This means walking through all of the
11529  * ill's and toggling their forwarding values.
11530  */
11531 /* ARGSUSED */
11532 static int
11533 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11534 {
11535 	long new_value;
11536 	int *forwarding_value = (int *)cp;
11537 	ill_t *ill;
11538 	boolean_t isv6;
11539 	ill_walk_context_t ctx;
11540 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11541 
11542 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11543 
11544 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11545 	    new_value < 0 || new_value > 1) {
11546 		return (EINVAL);
11547 	}
11548 
11549 	*forwarding_value = new_value;
11550 
11551 	/*
11552 	 * Regardless of the current value of ip_forwarding, set all per-ill
11553 	 * values of ip_forwarding to the value being set.
11554 	 *
11555 	 * Bring all the ill's up to date with the new global value.
11556 	 */
11557 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11558 
11559 	if (isv6)
11560 		ill = ILL_START_WALK_V6(&ctx, ipst);
11561 	else
11562 		ill = ILL_START_WALK_V4(&ctx, ipst);
11563 
11564 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11565 		(void) ill_forward_set(ill, new_value != 0);
11566 
11567 	rw_exit(&ipst->ips_ill_g_lock);
11568 	return (0);
11569 }
11570 
11571 /*
11572  * Walk through the param array specified registering each element with the
11573  * Named Dispatch handler. This is called only during init. So it is ok
11574  * not to acquire any locks
11575  */
11576 static boolean_t
11577 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11578     ipndp_t *ipnd, size_t ipnd_cnt)
11579 {
11580 	for (; ippa_cnt-- > 0; ippa++) {
11581 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11582 			if (!nd_load(ndp, ippa->ip_param_name,
11583 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11584 				nd_free(ndp);
11585 				return (B_FALSE);
11586 			}
11587 		}
11588 	}
11589 
11590 	for (; ipnd_cnt-- > 0; ipnd++) {
11591 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11592 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11593 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11594 			    ipnd->ip_ndp_data)) {
11595 				nd_free(ndp);
11596 				return (B_FALSE);
11597 			}
11598 		}
11599 	}
11600 
11601 	return (B_TRUE);
11602 }
11603 
11604 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11605 /* ARGSUSED */
11606 static int
11607 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11608 {
11609 	long		new_value;
11610 	ipparam_t	*ippa = (ipparam_t *)cp;
11611 
11612 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11613 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11614 		return (EINVAL);
11615 	}
11616 	ippa->ip_param_value = new_value;
11617 	return (0);
11618 }
11619 
11620 /*
11621  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11622  * When an ipf is passed here for the first time, if
11623  * we already have in-order fragments on the queue, we convert from the fast-
11624  * path reassembly scheme to the hard-case scheme.  From then on, additional
11625  * fragments are reassembled here.  We keep track of the start and end offsets
11626  * of each piece, and the number of holes in the chain.  When the hole count
11627  * goes to zero, we are done!
11628  *
11629  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11630  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11631  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11632  * after the call to ip_reassemble().
11633  */
11634 int
11635 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11636     size_t msg_len)
11637 {
11638 	uint_t	end;
11639 	mblk_t	*next_mp;
11640 	mblk_t	*mp1;
11641 	uint_t	offset;
11642 	boolean_t incr_dups = B_TRUE;
11643 	boolean_t offset_zero_seen = B_FALSE;
11644 	boolean_t pkt_boundary_checked = B_FALSE;
11645 
11646 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11647 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11648 
11649 	/* Add in byte count */
11650 	ipf->ipf_count += msg_len;
11651 	if (ipf->ipf_end) {
11652 		/*
11653 		 * We were part way through in-order reassembly, but now there
11654 		 * is a hole.  We walk through messages already queued, and
11655 		 * mark them for hard case reassembly.  We know that up till
11656 		 * now they were in order starting from offset zero.
11657 		 */
11658 		offset = 0;
11659 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11660 			IP_REASS_SET_START(mp1, offset);
11661 			if (offset == 0) {
11662 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11663 				offset = -ipf->ipf_nf_hdr_len;
11664 			}
11665 			offset += mp1->b_wptr - mp1->b_rptr;
11666 			IP_REASS_SET_END(mp1, offset);
11667 		}
11668 		/* One hole at the end. */
11669 		ipf->ipf_hole_cnt = 1;
11670 		/* Brand it as a hard case, forever. */
11671 		ipf->ipf_end = 0;
11672 	}
11673 	/* Walk through all the new pieces. */
11674 	do {
11675 		end = start + (mp->b_wptr - mp->b_rptr);
11676 		/*
11677 		 * If start is 0, decrease 'end' only for the first mblk of
11678 		 * the fragment. Otherwise 'end' can get wrong value in the
11679 		 * second pass of the loop if first mblk is exactly the
11680 		 * size of ipf_nf_hdr_len.
11681 		 */
11682 		if (start == 0 && !offset_zero_seen) {
11683 			/* First segment */
11684 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11685 			end -= ipf->ipf_nf_hdr_len;
11686 			offset_zero_seen = B_TRUE;
11687 		}
11688 		next_mp = mp->b_cont;
11689 		/*
11690 		 * We are checking to see if there is any interesing data
11691 		 * to process.  If there isn't and the mblk isn't the
11692 		 * one which carries the unfragmentable header then we
11693 		 * drop it.  It's possible to have just the unfragmentable
11694 		 * header come through without any data.  That needs to be
11695 		 * saved.
11696 		 *
11697 		 * If the assert at the top of this function holds then the
11698 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11699 		 * is infrequently traveled enough that the test is left in
11700 		 * to protect against future code changes which break that
11701 		 * invariant.
11702 		 */
11703 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11704 			/* Empty.  Blast it. */
11705 			IP_REASS_SET_START(mp, 0);
11706 			IP_REASS_SET_END(mp, 0);
11707 			/*
11708 			 * If the ipf points to the mblk we are about to free,
11709 			 * update ipf to point to the next mblk (or NULL
11710 			 * if none).
11711 			 */
11712 			if (ipf->ipf_mp->b_cont == mp)
11713 				ipf->ipf_mp->b_cont = next_mp;
11714 			freeb(mp);
11715 			continue;
11716 		}
11717 		mp->b_cont = NULL;
11718 		IP_REASS_SET_START(mp, start);
11719 		IP_REASS_SET_END(mp, end);
11720 		if (!ipf->ipf_tail_mp) {
11721 			ipf->ipf_tail_mp = mp;
11722 			ipf->ipf_mp->b_cont = mp;
11723 			if (start == 0 || !more) {
11724 				ipf->ipf_hole_cnt = 1;
11725 				/*
11726 				 * if the first fragment comes in more than one
11727 				 * mblk, this loop will be executed for each
11728 				 * mblk. Need to adjust hole count so exiting
11729 				 * this routine will leave hole count at 1.
11730 				 */
11731 				if (next_mp)
11732 					ipf->ipf_hole_cnt++;
11733 			} else
11734 				ipf->ipf_hole_cnt = 2;
11735 			continue;
11736 		} else if (ipf->ipf_last_frag_seen && !more &&
11737 		    !pkt_boundary_checked) {
11738 			/*
11739 			 * We check datagram boundary only if this fragment
11740 			 * claims to be the last fragment and we have seen a
11741 			 * last fragment in the past too. We do this only
11742 			 * once for a given fragment.
11743 			 *
11744 			 * start cannot be 0 here as fragments with start=0
11745 			 * and MF=0 gets handled as a complete packet. These
11746 			 * fragments should not reach here.
11747 			 */
11748 
11749 			if (start + msgdsize(mp) !=
11750 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11751 				/*
11752 				 * We have two fragments both of which claim
11753 				 * to be the last fragment but gives conflicting
11754 				 * information about the whole datagram size.
11755 				 * Something fishy is going on. Drop the
11756 				 * fragment and free up the reassembly list.
11757 				 */
11758 				return (IP_REASS_FAILED);
11759 			}
11760 
11761 			/*
11762 			 * We shouldn't come to this code block again for this
11763 			 * particular fragment.
11764 			 */
11765 			pkt_boundary_checked = B_TRUE;
11766 		}
11767 
11768 		/* New stuff at or beyond tail? */
11769 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11770 		if (start >= offset) {
11771 			if (ipf->ipf_last_frag_seen) {
11772 				/* current fragment is beyond last fragment */
11773 				return (IP_REASS_FAILED);
11774 			}
11775 			/* Link it on end. */
11776 			ipf->ipf_tail_mp->b_cont = mp;
11777 			ipf->ipf_tail_mp = mp;
11778 			if (more) {
11779 				if (start != offset)
11780 					ipf->ipf_hole_cnt++;
11781 			} else if (start == offset && next_mp == NULL)
11782 					ipf->ipf_hole_cnt--;
11783 			continue;
11784 		}
11785 		mp1 = ipf->ipf_mp->b_cont;
11786 		offset = IP_REASS_START(mp1);
11787 		/* New stuff at the front? */
11788 		if (start < offset) {
11789 			if (start == 0) {
11790 				if (end >= offset) {
11791 					/* Nailed the hole at the begining. */
11792 					ipf->ipf_hole_cnt--;
11793 				}
11794 			} else if (end < offset) {
11795 				/*
11796 				 * A hole, stuff, and a hole where there used
11797 				 * to be just a hole.
11798 				 */
11799 				ipf->ipf_hole_cnt++;
11800 			}
11801 			mp->b_cont = mp1;
11802 			/* Check for overlap. */
11803 			while (end > offset) {
11804 				if (end < IP_REASS_END(mp1)) {
11805 					mp->b_wptr -= end - offset;
11806 					IP_REASS_SET_END(mp, offset);
11807 					BUMP_MIB(ill->ill_ip_mib,
11808 					    ipIfStatsReasmPartDups);
11809 					break;
11810 				}
11811 				/* Did we cover another hole? */
11812 				if ((mp1->b_cont &&
11813 				    IP_REASS_END(mp1) !=
11814 				    IP_REASS_START(mp1->b_cont) &&
11815 				    end >= IP_REASS_START(mp1->b_cont)) ||
11816 				    (!ipf->ipf_last_frag_seen && !more)) {
11817 					ipf->ipf_hole_cnt--;
11818 				}
11819 				/* Clip out mp1. */
11820 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11821 					/*
11822 					 * After clipping out mp1, this guy
11823 					 * is now hanging off the end.
11824 					 */
11825 					ipf->ipf_tail_mp = mp;
11826 				}
11827 				IP_REASS_SET_START(mp1, 0);
11828 				IP_REASS_SET_END(mp1, 0);
11829 				/* Subtract byte count */
11830 				ipf->ipf_count -= mp1->b_datap->db_lim -
11831 				    mp1->b_datap->db_base;
11832 				freeb(mp1);
11833 				BUMP_MIB(ill->ill_ip_mib,
11834 				    ipIfStatsReasmPartDups);
11835 				mp1 = mp->b_cont;
11836 				if (!mp1)
11837 					break;
11838 				offset = IP_REASS_START(mp1);
11839 			}
11840 			ipf->ipf_mp->b_cont = mp;
11841 			continue;
11842 		}
11843 		/*
11844 		 * The new piece starts somewhere between the start of the head
11845 		 * and before the end of the tail.
11846 		 */
11847 		for (; mp1; mp1 = mp1->b_cont) {
11848 			offset = IP_REASS_END(mp1);
11849 			if (start < offset) {
11850 				if (end <= offset) {
11851 					/* Nothing new. */
11852 					IP_REASS_SET_START(mp, 0);
11853 					IP_REASS_SET_END(mp, 0);
11854 					/* Subtract byte count */
11855 					ipf->ipf_count -= mp->b_datap->db_lim -
11856 					    mp->b_datap->db_base;
11857 					if (incr_dups) {
11858 						ipf->ipf_num_dups++;
11859 						incr_dups = B_FALSE;
11860 					}
11861 					freeb(mp);
11862 					BUMP_MIB(ill->ill_ip_mib,
11863 					    ipIfStatsReasmDuplicates);
11864 					break;
11865 				}
11866 				/*
11867 				 * Trim redundant stuff off beginning of new
11868 				 * piece.
11869 				 */
11870 				IP_REASS_SET_START(mp, offset);
11871 				mp->b_rptr += offset - start;
11872 				BUMP_MIB(ill->ill_ip_mib,
11873 				    ipIfStatsReasmPartDups);
11874 				start = offset;
11875 				if (!mp1->b_cont) {
11876 					/*
11877 					 * After trimming, this guy is now
11878 					 * hanging off the end.
11879 					 */
11880 					mp1->b_cont = mp;
11881 					ipf->ipf_tail_mp = mp;
11882 					if (!more) {
11883 						ipf->ipf_hole_cnt--;
11884 					}
11885 					break;
11886 				}
11887 			}
11888 			if (start >= IP_REASS_START(mp1->b_cont))
11889 				continue;
11890 			/* Fill a hole */
11891 			if (start > offset)
11892 				ipf->ipf_hole_cnt++;
11893 			mp->b_cont = mp1->b_cont;
11894 			mp1->b_cont = mp;
11895 			mp1 = mp->b_cont;
11896 			offset = IP_REASS_START(mp1);
11897 			if (end >= offset) {
11898 				ipf->ipf_hole_cnt--;
11899 				/* Check for overlap. */
11900 				while (end > offset) {
11901 					if (end < IP_REASS_END(mp1)) {
11902 						mp->b_wptr -= end - offset;
11903 						IP_REASS_SET_END(mp, offset);
11904 						/*
11905 						 * TODO we might bump
11906 						 * this up twice if there is
11907 						 * overlap at both ends.
11908 						 */
11909 						BUMP_MIB(ill->ill_ip_mib,
11910 						    ipIfStatsReasmPartDups);
11911 						break;
11912 					}
11913 					/* Did we cover another hole? */
11914 					if ((mp1->b_cont &&
11915 					    IP_REASS_END(mp1)
11916 					    != IP_REASS_START(mp1->b_cont) &&
11917 					    end >=
11918 					    IP_REASS_START(mp1->b_cont)) ||
11919 					    (!ipf->ipf_last_frag_seen &&
11920 					    !more)) {
11921 						ipf->ipf_hole_cnt--;
11922 					}
11923 					/* Clip out mp1. */
11924 					if ((mp->b_cont = mp1->b_cont) ==
11925 					    NULL) {
11926 						/*
11927 						 * After clipping out mp1,
11928 						 * this guy is now hanging
11929 						 * off the end.
11930 						 */
11931 						ipf->ipf_tail_mp = mp;
11932 					}
11933 					IP_REASS_SET_START(mp1, 0);
11934 					IP_REASS_SET_END(mp1, 0);
11935 					/* Subtract byte count */
11936 					ipf->ipf_count -=
11937 					    mp1->b_datap->db_lim -
11938 					    mp1->b_datap->db_base;
11939 					freeb(mp1);
11940 					BUMP_MIB(ill->ill_ip_mib,
11941 					    ipIfStatsReasmPartDups);
11942 					mp1 = mp->b_cont;
11943 					if (!mp1)
11944 						break;
11945 					offset = IP_REASS_START(mp1);
11946 				}
11947 			}
11948 			break;
11949 		}
11950 	} while (start = end, mp = next_mp);
11951 
11952 	/* Fragment just processed could be the last one. Remember this fact */
11953 	if (!more)
11954 		ipf->ipf_last_frag_seen = B_TRUE;
11955 
11956 	/* Still got holes? */
11957 	if (ipf->ipf_hole_cnt)
11958 		return (IP_REASS_PARTIAL);
11959 	/* Clean up overloaded fields to avoid upstream disasters. */
11960 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11961 		IP_REASS_SET_START(mp1, 0);
11962 		IP_REASS_SET_END(mp1, 0);
11963 	}
11964 	return (IP_REASS_COMPLETE);
11965 }
11966 
11967 /*
11968  * ipsec processing for the fast path, used for input UDP Packets
11969  */
11970 static boolean_t
11971 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11972     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11973 {
11974 	uint32_t	ill_index;
11975 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11976 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
11977 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
11978 
11979 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11980 	/* The ill_index of the incoming ILL */
11981 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11982 
11983 	/* pass packet up to the transport */
11984 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
11985 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11986 		    NULL, mctl_present);
11987 		if (*first_mpp == NULL) {
11988 			return (B_FALSE);
11989 		}
11990 	}
11991 
11992 	/* Initiate IPPF processing for fastpath UDP */
11993 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
11994 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11995 		if (*mpp == NULL) {
11996 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11997 			    "deferred/dropped during IPPF processing\n"));
11998 			return (B_FALSE);
11999 		}
12000 	}
12001 	/*
12002 	 * We make the checks as below since we are in the fast path
12003 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12004 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12005 	 */
12006 	if (connp->conn_recvif || connp->conn_recvslla ||
12007 	    connp->conn_ip_recvpktinfo) {
12008 		if (connp->conn_recvif) {
12009 			in_flags = IPF_RECVIF;
12010 		}
12011 		/*
12012 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12013 		 * so the flag passed to ip_add_info is based on IP version
12014 		 * of connp.
12015 		 */
12016 		if (connp->conn_ip_recvpktinfo) {
12017 			if (connp->conn_af_isv6) {
12018 				/*
12019 				 * V6 only needs index
12020 				 */
12021 				in_flags |= IPF_RECVIF;
12022 			} else {
12023 				/*
12024 				 * V4 needs index + matching address.
12025 				 */
12026 				in_flags |= IPF_RECVADDR;
12027 			}
12028 		}
12029 		if (connp->conn_recvslla) {
12030 			in_flags |= IPF_RECVSLLA;
12031 		}
12032 		/*
12033 		 * since in_flags are being set ill will be
12034 		 * referenced in ip_add_info, so it better not
12035 		 * be NULL.
12036 		 */
12037 		/*
12038 		 * the actual data will be contained in b_cont
12039 		 * upon successful return of the following call.
12040 		 * If the call fails then the original mblk is
12041 		 * returned.
12042 		 */
12043 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12044 		    ipst);
12045 	}
12046 
12047 	return (B_TRUE);
12048 }
12049 
12050 /*
12051  * Fragmentation reassembly.  Each ILL has a hash table for
12052  * queuing packets undergoing reassembly for all IPIFs
12053  * associated with the ILL.  The hash is based on the packet
12054  * IP ident field.  The ILL frag hash table was allocated
12055  * as a timer block at the time the ILL was created.  Whenever
12056  * there is anything on the reassembly queue, the timer will
12057  * be running.  Returns B_TRUE if successful else B_FALSE;
12058  * frees mp on failure.
12059  */
12060 static boolean_t
12061 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12062     uint32_t *cksum_val, uint16_t *cksum_flags)
12063 {
12064 	uint32_t	frag_offset_flags;
12065 	ill_t		*ill = (ill_t *)q->q_ptr;
12066 	mblk_t		*mp = *mpp;
12067 	mblk_t		*t_mp;
12068 	ipaddr_t	dst;
12069 	uint8_t		proto = ipha->ipha_protocol;
12070 	uint32_t	sum_val;
12071 	uint16_t	sum_flags;
12072 	ipf_t		*ipf;
12073 	ipf_t		**ipfp;
12074 	ipfb_t		*ipfb;
12075 	uint16_t	ident;
12076 	uint32_t	offset;
12077 	ipaddr_t	src;
12078 	uint_t		hdr_length;
12079 	uint32_t	end;
12080 	mblk_t		*mp1;
12081 	mblk_t		*tail_mp;
12082 	size_t		count;
12083 	size_t		msg_len;
12084 	uint8_t		ecn_info = 0;
12085 	uint32_t	packet_size;
12086 	boolean_t	pruned = B_FALSE;
12087 	ip_stack_t *ipst = ill->ill_ipst;
12088 
12089 	if (cksum_val != NULL)
12090 		*cksum_val = 0;
12091 	if (cksum_flags != NULL)
12092 		*cksum_flags = 0;
12093 
12094 	/*
12095 	 * Drop the fragmented as early as possible, if
12096 	 * we don't have resource(s) to re-assemble.
12097 	 */
12098 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12099 		freemsg(mp);
12100 		return (B_FALSE);
12101 	}
12102 
12103 	/* Check for fragmentation offset; return if there's none */
12104 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12105 	    (IPH_MF | IPH_OFFSET)) == 0)
12106 		return (B_TRUE);
12107 
12108 	/*
12109 	 * We utilize hardware computed checksum info only for UDP since
12110 	 * IP fragmentation is a normal occurence for the protocol.  In
12111 	 * addition, checksum offload support for IP fragments carrying
12112 	 * UDP payload is commonly implemented across network adapters.
12113 	 */
12114 	ASSERT(ill != NULL);
12115 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12116 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12117 		mblk_t *mp1 = mp->b_cont;
12118 		int32_t len;
12119 
12120 		/* Record checksum information from the packet */
12121 		sum_val = (uint32_t)DB_CKSUM16(mp);
12122 		sum_flags = DB_CKSUMFLAGS(mp);
12123 
12124 		/* IP payload offset from beginning of mblk */
12125 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12126 
12127 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12128 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12129 		    offset >= DB_CKSUMSTART(mp) &&
12130 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12131 			uint32_t adj;
12132 			/*
12133 			 * Partial checksum has been calculated by hardware
12134 			 * and attached to the packet; in addition, any
12135 			 * prepended extraneous data is even byte aligned.
12136 			 * If any such data exists, we adjust the checksum;
12137 			 * this would also handle any postpended data.
12138 			 */
12139 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12140 			    mp, mp1, len, adj);
12141 
12142 			/* One's complement subtract extraneous checksum */
12143 			if (adj >= sum_val)
12144 				sum_val = ~(adj - sum_val) & 0xFFFF;
12145 			else
12146 				sum_val -= adj;
12147 		}
12148 	} else {
12149 		sum_val = 0;
12150 		sum_flags = 0;
12151 	}
12152 
12153 	/* Clear hardware checksumming flag */
12154 	DB_CKSUMFLAGS(mp) = 0;
12155 
12156 	ident = ipha->ipha_ident;
12157 	offset = (frag_offset_flags << 3) & 0xFFFF;
12158 	src = ipha->ipha_src;
12159 	dst = ipha->ipha_dst;
12160 	hdr_length = IPH_HDR_LENGTH(ipha);
12161 	end = ntohs(ipha->ipha_length) - hdr_length;
12162 
12163 	/* If end == 0 then we have a packet with no data, so just free it */
12164 	if (end == 0) {
12165 		freemsg(mp);
12166 		return (B_FALSE);
12167 	}
12168 
12169 	/* Record the ECN field info. */
12170 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12171 	if (offset != 0) {
12172 		/*
12173 		 * If this isn't the first piece, strip the header, and
12174 		 * add the offset to the end value.
12175 		 */
12176 		mp->b_rptr += hdr_length;
12177 		end += offset;
12178 	}
12179 
12180 	msg_len = MBLKSIZE(mp);
12181 	tail_mp = mp;
12182 	while (tail_mp->b_cont != NULL) {
12183 		tail_mp = tail_mp->b_cont;
12184 		msg_len += MBLKSIZE(tail_mp);
12185 	}
12186 
12187 	/* If the reassembly list for this ILL will get too big, prune it */
12188 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12189 	    ipst->ips_ip_reass_queue_bytes) {
12190 		ill_frag_prune(ill,
12191 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12192 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12193 		pruned = B_TRUE;
12194 	}
12195 
12196 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12197 	mutex_enter(&ipfb->ipfb_lock);
12198 
12199 	ipfp = &ipfb->ipfb_ipf;
12200 	/* Try to find an existing fragment queue for this packet. */
12201 	for (;;) {
12202 		ipf = ipfp[0];
12203 		if (ipf != NULL) {
12204 			/*
12205 			 * It has to match on ident and src/dst address.
12206 			 */
12207 			if (ipf->ipf_ident == ident &&
12208 			    ipf->ipf_src == src &&
12209 			    ipf->ipf_dst == dst &&
12210 			    ipf->ipf_protocol == proto) {
12211 				/*
12212 				 * If we have received too many
12213 				 * duplicate fragments for this packet
12214 				 * free it.
12215 				 */
12216 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12217 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12218 					freemsg(mp);
12219 					mutex_exit(&ipfb->ipfb_lock);
12220 					return (B_FALSE);
12221 				}
12222 				/* Found it. */
12223 				break;
12224 			}
12225 			ipfp = &ipf->ipf_hash_next;
12226 			continue;
12227 		}
12228 
12229 		/*
12230 		 * If we pruned the list, do we want to store this new
12231 		 * fragment?. We apply an optimization here based on the
12232 		 * fact that most fragments will be received in order.
12233 		 * So if the offset of this incoming fragment is zero,
12234 		 * it is the first fragment of a new packet. We will
12235 		 * keep it.  Otherwise drop the fragment, as we have
12236 		 * probably pruned the packet already (since the
12237 		 * packet cannot be found).
12238 		 */
12239 		if (pruned && offset != 0) {
12240 			mutex_exit(&ipfb->ipfb_lock);
12241 			freemsg(mp);
12242 			return (B_FALSE);
12243 		}
12244 
12245 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12246 			/*
12247 			 * Too many fragmented packets in this hash
12248 			 * bucket. Free the oldest.
12249 			 */
12250 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12251 		}
12252 
12253 		/* New guy.  Allocate a frag message. */
12254 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12255 		if (mp1 == NULL) {
12256 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12257 			freemsg(mp);
12258 reass_done:
12259 			mutex_exit(&ipfb->ipfb_lock);
12260 			return (B_FALSE);
12261 		}
12262 
12263 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12264 		mp1->b_cont = mp;
12265 
12266 		/* Initialize the fragment header. */
12267 		ipf = (ipf_t *)mp1->b_rptr;
12268 		ipf->ipf_mp = mp1;
12269 		ipf->ipf_ptphn = ipfp;
12270 		ipfp[0] = ipf;
12271 		ipf->ipf_hash_next = NULL;
12272 		ipf->ipf_ident = ident;
12273 		ipf->ipf_protocol = proto;
12274 		ipf->ipf_src = src;
12275 		ipf->ipf_dst = dst;
12276 		ipf->ipf_nf_hdr_len = 0;
12277 		/* Record reassembly start time. */
12278 		ipf->ipf_timestamp = gethrestime_sec();
12279 		/* Record ipf generation and account for frag header */
12280 		ipf->ipf_gen = ill->ill_ipf_gen++;
12281 		ipf->ipf_count = MBLKSIZE(mp1);
12282 		ipf->ipf_last_frag_seen = B_FALSE;
12283 		ipf->ipf_ecn = ecn_info;
12284 		ipf->ipf_num_dups = 0;
12285 		ipfb->ipfb_frag_pkts++;
12286 		ipf->ipf_checksum = 0;
12287 		ipf->ipf_checksum_flags = 0;
12288 
12289 		/* Store checksum value in fragment header */
12290 		if (sum_flags != 0) {
12291 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12292 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12293 			ipf->ipf_checksum = sum_val;
12294 			ipf->ipf_checksum_flags = sum_flags;
12295 		}
12296 
12297 		/*
12298 		 * We handle reassembly two ways.  In the easy case,
12299 		 * where all the fragments show up in order, we do
12300 		 * minimal bookkeeping, and just clip new pieces on
12301 		 * the end.  If we ever see a hole, then we go off
12302 		 * to ip_reassemble which has to mark the pieces and
12303 		 * keep track of the number of holes, etc.  Obviously,
12304 		 * the point of having both mechanisms is so we can
12305 		 * handle the easy case as efficiently as possible.
12306 		 */
12307 		if (offset == 0) {
12308 			/* Easy case, in-order reassembly so far. */
12309 			ipf->ipf_count += msg_len;
12310 			ipf->ipf_tail_mp = tail_mp;
12311 			/*
12312 			 * Keep track of next expected offset in
12313 			 * ipf_end.
12314 			 */
12315 			ipf->ipf_end = end;
12316 			ipf->ipf_nf_hdr_len = hdr_length;
12317 		} else {
12318 			/* Hard case, hole at the beginning. */
12319 			ipf->ipf_tail_mp = NULL;
12320 			/*
12321 			 * ipf_end == 0 means that we have given up
12322 			 * on easy reassembly.
12323 			 */
12324 			ipf->ipf_end = 0;
12325 
12326 			/* Forget checksum offload from now on */
12327 			ipf->ipf_checksum_flags = 0;
12328 
12329 			/*
12330 			 * ipf_hole_cnt is set by ip_reassemble.
12331 			 * ipf_count is updated by ip_reassemble.
12332 			 * No need to check for return value here
12333 			 * as we don't expect reassembly to complete
12334 			 * or fail for the first fragment itself.
12335 			 */
12336 			(void) ip_reassemble(mp, ipf,
12337 			    (frag_offset_flags & IPH_OFFSET) << 3,
12338 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12339 		}
12340 		/* Update per ipfb and ill byte counts */
12341 		ipfb->ipfb_count += ipf->ipf_count;
12342 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12343 		ill->ill_frag_count += ipf->ipf_count;
12344 		/* If the frag timer wasn't already going, start it. */
12345 		mutex_enter(&ill->ill_lock);
12346 		ill_frag_timer_start(ill);
12347 		mutex_exit(&ill->ill_lock);
12348 		goto reass_done;
12349 	}
12350 
12351 	/*
12352 	 * If the packet's flag has changed (it could be coming up
12353 	 * from an interface different than the previous, therefore
12354 	 * possibly different checksum capability), then forget about
12355 	 * any stored checksum states.  Otherwise add the value to
12356 	 * the existing one stored in the fragment header.
12357 	 */
12358 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12359 		sum_val += ipf->ipf_checksum;
12360 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12361 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12362 		ipf->ipf_checksum = sum_val;
12363 	} else if (ipf->ipf_checksum_flags != 0) {
12364 		/* Forget checksum offload from now on */
12365 		ipf->ipf_checksum_flags = 0;
12366 	}
12367 
12368 	/*
12369 	 * We have a new piece of a datagram which is already being
12370 	 * reassembled.  Update the ECN info if all IP fragments
12371 	 * are ECN capable.  If there is one which is not, clear
12372 	 * all the info.  If there is at least one which has CE
12373 	 * code point, IP needs to report that up to transport.
12374 	 */
12375 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12376 		if (ecn_info == IPH_ECN_CE)
12377 			ipf->ipf_ecn = IPH_ECN_CE;
12378 	} else {
12379 		ipf->ipf_ecn = IPH_ECN_NECT;
12380 	}
12381 	if (offset && ipf->ipf_end == offset) {
12382 		/* The new fragment fits at the end */
12383 		ipf->ipf_tail_mp->b_cont = mp;
12384 		/* Update the byte count */
12385 		ipf->ipf_count += msg_len;
12386 		/* Update per ipfb and ill byte counts */
12387 		ipfb->ipfb_count += msg_len;
12388 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12389 		ill->ill_frag_count += msg_len;
12390 		if (frag_offset_flags & IPH_MF) {
12391 			/* More to come. */
12392 			ipf->ipf_end = end;
12393 			ipf->ipf_tail_mp = tail_mp;
12394 			goto reass_done;
12395 		}
12396 	} else {
12397 		/* Go do the hard cases. */
12398 		int ret;
12399 
12400 		if (offset == 0)
12401 			ipf->ipf_nf_hdr_len = hdr_length;
12402 
12403 		/* Save current byte count */
12404 		count = ipf->ipf_count;
12405 		ret = ip_reassemble(mp, ipf,
12406 		    (frag_offset_flags & IPH_OFFSET) << 3,
12407 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12408 		/* Count of bytes added and subtracted (freeb()ed) */
12409 		count = ipf->ipf_count - count;
12410 		if (count) {
12411 			/* Update per ipfb and ill byte counts */
12412 			ipfb->ipfb_count += count;
12413 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12414 			ill->ill_frag_count += count;
12415 		}
12416 		if (ret == IP_REASS_PARTIAL) {
12417 			goto reass_done;
12418 		} else if (ret == IP_REASS_FAILED) {
12419 			/* Reassembly failed. Free up all resources */
12420 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12421 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12422 				IP_REASS_SET_START(t_mp, 0);
12423 				IP_REASS_SET_END(t_mp, 0);
12424 			}
12425 			freemsg(mp);
12426 			goto reass_done;
12427 		}
12428 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12429 	}
12430 	/*
12431 	 * We have completed reassembly.  Unhook the frag header from
12432 	 * the reassembly list.
12433 	 *
12434 	 * Before we free the frag header, record the ECN info
12435 	 * to report back to the transport.
12436 	 */
12437 	ecn_info = ipf->ipf_ecn;
12438 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12439 	ipfp = ipf->ipf_ptphn;
12440 
12441 	/* We need to supply these to caller */
12442 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12443 		sum_val = ipf->ipf_checksum;
12444 	else
12445 		sum_val = 0;
12446 
12447 	mp1 = ipf->ipf_mp;
12448 	count = ipf->ipf_count;
12449 	ipf = ipf->ipf_hash_next;
12450 	if (ipf != NULL)
12451 		ipf->ipf_ptphn = ipfp;
12452 	ipfp[0] = ipf;
12453 	ill->ill_frag_count -= count;
12454 	ASSERT(ipfb->ipfb_count >= count);
12455 	ipfb->ipfb_count -= count;
12456 	ipfb->ipfb_frag_pkts--;
12457 	mutex_exit(&ipfb->ipfb_lock);
12458 	/* Ditch the frag header. */
12459 	mp = mp1->b_cont;
12460 
12461 	freeb(mp1);
12462 
12463 	/* Restore original IP length in header. */
12464 	packet_size = (uint32_t)msgdsize(mp);
12465 	if (packet_size > IP_MAXPACKET) {
12466 		freemsg(mp);
12467 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12468 		return (B_FALSE);
12469 	}
12470 
12471 	if (DB_REF(mp) > 1) {
12472 		mblk_t *mp2 = copymsg(mp);
12473 
12474 		freemsg(mp);
12475 		if (mp2 == NULL) {
12476 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12477 			return (B_FALSE);
12478 		}
12479 		mp = mp2;
12480 	}
12481 	ipha = (ipha_t *)mp->b_rptr;
12482 
12483 	ipha->ipha_length = htons((uint16_t)packet_size);
12484 	/* We're now complete, zip the frag state */
12485 	ipha->ipha_fragment_offset_and_flags = 0;
12486 	/* Record the ECN info. */
12487 	ipha->ipha_type_of_service &= 0xFC;
12488 	ipha->ipha_type_of_service |= ecn_info;
12489 	*mpp = mp;
12490 
12491 	/* Reassembly is successful; return checksum information if needed */
12492 	if (cksum_val != NULL)
12493 		*cksum_val = sum_val;
12494 	if (cksum_flags != NULL)
12495 		*cksum_flags = sum_flags;
12496 
12497 	return (B_TRUE);
12498 }
12499 
12500 /*
12501  * Perform ip header check sum update local options.
12502  * return B_TRUE if all is well, else return B_FALSE and release
12503  * the mp. caller is responsible for decrementing ire ref cnt.
12504  */
12505 static boolean_t
12506 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12507     ip_stack_t *ipst)
12508 {
12509 	mblk_t		*first_mp;
12510 	boolean_t	mctl_present;
12511 	uint16_t	sum;
12512 
12513 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12514 	/*
12515 	 * Don't do the checksum if it has gone through AH/ESP
12516 	 * processing.
12517 	 */
12518 	if (!mctl_present) {
12519 		sum = ip_csum_hdr(ipha);
12520 		if (sum != 0) {
12521 			if (ill != NULL) {
12522 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12523 			} else {
12524 				BUMP_MIB(&ipst->ips_ip_mib,
12525 				    ipIfStatsInCksumErrs);
12526 			}
12527 			freemsg(first_mp);
12528 			return (B_FALSE);
12529 		}
12530 	}
12531 
12532 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12533 		if (mctl_present)
12534 			freeb(first_mp);
12535 		return (B_FALSE);
12536 	}
12537 
12538 	return (B_TRUE);
12539 }
12540 
12541 /*
12542  * All udp packet are delivered to the local host via this routine.
12543  */
12544 void
12545 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12546     ill_t *recv_ill)
12547 {
12548 	uint32_t	sum;
12549 	uint32_t	u1;
12550 	boolean_t	mctl_present;
12551 	conn_t		*connp;
12552 	mblk_t		*first_mp;
12553 	uint16_t	*up;
12554 	ill_t		*ill = (ill_t *)q->q_ptr;
12555 	uint16_t	reass_hck_flags = 0;
12556 	ip_stack_t	*ipst;
12557 
12558 	ASSERT(recv_ill != NULL);
12559 	ipst = recv_ill->ill_ipst;
12560 
12561 #define	rptr    ((uchar_t *)ipha)
12562 
12563 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12564 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12565 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12566 	ASSERT(ill != NULL);
12567 
12568 	/*
12569 	 * FAST PATH for udp packets
12570 	 */
12571 
12572 	/* u1 is # words of IP options */
12573 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12574 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12575 
12576 	/* IP options present */
12577 	if (u1 != 0)
12578 		goto ipoptions;
12579 
12580 	/* Check the IP header checksum.  */
12581 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12582 		/* Clear the IP header h/w cksum flag */
12583 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12584 	} else {
12585 #define	uph	((uint16_t *)ipha)
12586 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12587 		    uph[6] + uph[7] + uph[8] + uph[9];
12588 #undef	uph
12589 		/* finish doing IP checksum */
12590 		sum = (sum & 0xFFFF) + (sum >> 16);
12591 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12592 		/*
12593 		 * Don't verify header checksum if this packet is coming
12594 		 * back from AH/ESP as we already did it.
12595 		 */
12596 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12597 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12598 			freemsg(first_mp);
12599 			return;
12600 		}
12601 	}
12602 
12603 	/*
12604 	 * Count for SNMP of inbound packets for ire.
12605 	 * if mctl is present this might be a secure packet and
12606 	 * has already been counted for in ip_proto_input().
12607 	 */
12608 	if (!mctl_present) {
12609 		UPDATE_IB_PKT_COUNT(ire);
12610 		ire->ire_last_used_time = lbolt;
12611 	}
12612 
12613 	/* packet part of fragmented IP packet? */
12614 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12615 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12616 		goto fragmented;
12617 	}
12618 
12619 	/* u1 = IP header length (20 bytes) */
12620 	u1 = IP_SIMPLE_HDR_LENGTH;
12621 
12622 	/* packet does not contain complete IP & UDP headers */
12623 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12624 		goto udppullup;
12625 
12626 	/* up points to UDP header */
12627 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12628 #define	iphs    ((uint16_t *)ipha)
12629 
12630 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12631 	if (up[3] != 0) {
12632 		mblk_t *mp1 = mp->b_cont;
12633 		boolean_t cksum_err;
12634 		uint16_t hck_flags = 0;
12635 
12636 		/* Pseudo-header checksum */
12637 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12638 		    iphs[9] + up[2];
12639 
12640 		/*
12641 		 * Revert to software checksum calculation if the interface
12642 		 * isn't capable of checksum offload or if IPsec is present.
12643 		 */
12644 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12645 			hck_flags = DB_CKSUMFLAGS(mp);
12646 
12647 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12648 			IP_STAT(ipst, ip_in_sw_cksum);
12649 
12650 		IP_CKSUM_RECV(hck_flags, u1,
12651 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12652 		    (int32_t)((uchar_t *)up - rptr),
12653 		    mp, mp1, cksum_err);
12654 
12655 		if (cksum_err) {
12656 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12657 			if (hck_flags & HCK_FULLCKSUM)
12658 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12659 			else if (hck_flags & HCK_PARTIALCKSUM)
12660 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12661 			else
12662 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12663 
12664 			freemsg(first_mp);
12665 			return;
12666 		}
12667 	}
12668 
12669 	/* Non-fragmented broadcast or multicast packet? */
12670 	if (ire->ire_type == IRE_BROADCAST)
12671 		goto udpslowpath;
12672 
12673 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12674 	    ire->ire_zoneid, ipst)) != NULL) {
12675 		ASSERT(connp->conn_upq != NULL);
12676 		IP_STAT(ipst, ip_udp_fast_path);
12677 
12678 		if (CONN_UDP_FLOWCTLD(connp)) {
12679 			freemsg(mp);
12680 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12681 		} else {
12682 			if (!mctl_present) {
12683 				BUMP_MIB(ill->ill_ip_mib,
12684 				    ipIfStatsHCInDelivers);
12685 			}
12686 			/*
12687 			 * mp and first_mp can change.
12688 			 */
12689 			if (ip_udp_check(q, connp, recv_ill,
12690 			    ipha, &mp, &first_mp, mctl_present)) {
12691 				/* Send it upstream */
12692 				CONN_UDP_RECV(connp, mp);
12693 			}
12694 		}
12695 		/*
12696 		 * freeb() cannot deal with null mblk being passed
12697 		 * in and first_mp can be set to null in the call
12698 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12699 		 */
12700 		if (mctl_present && first_mp != NULL) {
12701 			freeb(first_mp);
12702 		}
12703 		CONN_DEC_REF(connp);
12704 		return;
12705 	}
12706 
12707 	/*
12708 	 * if we got here we know the packet is not fragmented and
12709 	 * has no options. The classifier could not find a conn_t and
12710 	 * most likely its an icmp packet so send it through slow path.
12711 	 */
12712 
12713 	goto udpslowpath;
12714 
12715 ipoptions:
12716 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12717 		goto slow_done;
12718 	}
12719 
12720 	UPDATE_IB_PKT_COUNT(ire);
12721 	ire->ire_last_used_time = lbolt;
12722 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12723 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12724 fragmented:
12725 		/*
12726 		 * "sum" and "reass_hck_flags" are non-zero if the
12727 		 * reassembled packet has a valid hardware computed
12728 		 * checksum information associated with it.
12729 		 */
12730 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12731 			goto slow_done;
12732 		/*
12733 		 * Make sure that first_mp points back to mp as
12734 		 * the mp we came in with could have changed in
12735 		 * ip_rput_fragment().
12736 		 */
12737 		ASSERT(!mctl_present);
12738 		ipha = (ipha_t *)mp->b_rptr;
12739 		first_mp = mp;
12740 	}
12741 
12742 	/* Now we have a complete datagram, destined for this machine. */
12743 	u1 = IPH_HDR_LENGTH(ipha);
12744 	/* Pull up the UDP header, if necessary. */
12745 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12746 udppullup:
12747 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12748 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12749 			freemsg(first_mp);
12750 			goto slow_done;
12751 		}
12752 		ipha = (ipha_t *)mp->b_rptr;
12753 	}
12754 
12755 	/*
12756 	 * Validate the checksum for the reassembled packet; for the
12757 	 * pullup case we calculate the payload checksum in software.
12758 	 */
12759 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12760 	if (up[3] != 0) {
12761 		boolean_t cksum_err;
12762 
12763 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12764 			IP_STAT(ipst, ip_in_sw_cksum);
12765 
12766 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12767 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12768 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12769 		    iphs[9] + up[2], sum, cksum_err);
12770 
12771 		if (cksum_err) {
12772 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12773 
12774 			if (reass_hck_flags & HCK_FULLCKSUM)
12775 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12776 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12777 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12778 			else
12779 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12780 
12781 			freemsg(first_mp);
12782 			goto slow_done;
12783 		}
12784 	}
12785 udpslowpath:
12786 
12787 	/* Clear hardware checksum flag to be safe */
12788 	DB_CKSUMFLAGS(mp) = 0;
12789 
12790 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12791 	    (ire->ire_type == IRE_BROADCAST),
12792 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12793 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12794 
12795 slow_done:
12796 	IP_STAT(ipst, ip_udp_slow_path);
12797 	return;
12798 
12799 #undef  iphs
12800 #undef  rptr
12801 }
12802 
12803 /* ARGSUSED */
12804 static mblk_t *
12805 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12806     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12807     ill_rx_ring_t *ill_ring)
12808 {
12809 	conn_t		*connp;
12810 	uint32_t	sum;
12811 	uint32_t	u1;
12812 	uint16_t	*up;
12813 	int		offset;
12814 	ssize_t		len;
12815 	mblk_t		*mp1;
12816 	boolean_t	syn_present = B_FALSE;
12817 	tcph_t		*tcph;
12818 	uint_t		ip_hdr_len;
12819 	ill_t		*ill = (ill_t *)q->q_ptr;
12820 	zoneid_t	zoneid = ire->ire_zoneid;
12821 	boolean_t	cksum_err;
12822 	uint16_t	hck_flags = 0;
12823 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12824 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12825 
12826 #define	rptr	((uchar_t *)ipha)
12827 
12828 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12829 	ASSERT(ill != NULL);
12830 
12831 	/*
12832 	 * FAST PATH for tcp packets
12833 	 */
12834 
12835 	/* u1 is # words of IP options */
12836 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12837 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12838 
12839 	/* IP options present */
12840 	if (u1) {
12841 		goto ipoptions;
12842 	} else {
12843 		/* Check the IP header checksum.  */
12844 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12845 			/* Clear the IP header h/w cksum flag */
12846 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12847 		} else {
12848 #define	uph	((uint16_t *)ipha)
12849 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12850 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12851 #undef	uph
12852 			/* finish doing IP checksum */
12853 			sum = (sum & 0xFFFF) + (sum >> 16);
12854 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12855 			/*
12856 			 * Don't verify header checksum if this packet
12857 			 * is coming back from AH/ESP as we already did it.
12858 			 */
12859 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12860 				BUMP_MIB(ill->ill_ip_mib,
12861 				    ipIfStatsInCksumErrs);
12862 				goto error;
12863 			}
12864 		}
12865 	}
12866 
12867 	if (!mctl_present) {
12868 		UPDATE_IB_PKT_COUNT(ire);
12869 		ire->ire_last_used_time = lbolt;
12870 	}
12871 
12872 	/* packet part of fragmented IP packet? */
12873 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12874 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12875 		goto fragmented;
12876 	}
12877 
12878 	/* u1 = IP header length (20 bytes) */
12879 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12880 
12881 	/* does packet contain IP+TCP headers? */
12882 	len = mp->b_wptr - rptr;
12883 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12884 		IP_STAT(ipst, ip_tcppullup);
12885 		goto tcppullup;
12886 	}
12887 
12888 	/* TCP options present? */
12889 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12890 
12891 	/*
12892 	 * If options need to be pulled up, then goto tcpoptions.
12893 	 * otherwise we are still in the fast path
12894 	 */
12895 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12896 		IP_STAT(ipst, ip_tcpoptions);
12897 		goto tcpoptions;
12898 	}
12899 
12900 	/* multiple mblks of tcp data? */
12901 	if ((mp1 = mp->b_cont) != NULL) {
12902 		/* more then two? */
12903 		if (mp1->b_cont != NULL) {
12904 			IP_STAT(ipst, ip_multipkttcp);
12905 			goto multipkttcp;
12906 		}
12907 		len += mp1->b_wptr - mp1->b_rptr;
12908 	}
12909 
12910 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12911 
12912 	/* part of pseudo checksum */
12913 
12914 	/* TCP datagram length */
12915 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12916 
12917 #define	iphs    ((uint16_t *)ipha)
12918 
12919 #ifdef	_BIG_ENDIAN
12920 	u1 += IPPROTO_TCP;
12921 #else
12922 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12923 #endif
12924 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12925 
12926 	/*
12927 	 * Revert to software checksum calculation if the interface
12928 	 * isn't capable of checksum offload or if IPsec is present.
12929 	 */
12930 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12931 		hck_flags = DB_CKSUMFLAGS(mp);
12932 
12933 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12934 		IP_STAT(ipst, ip_in_sw_cksum);
12935 
12936 	IP_CKSUM_RECV(hck_flags, u1,
12937 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12938 	    (int32_t)((uchar_t *)up - rptr),
12939 	    mp, mp1, cksum_err);
12940 
12941 	if (cksum_err) {
12942 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12943 
12944 		if (hck_flags & HCK_FULLCKSUM)
12945 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
12946 		else if (hck_flags & HCK_PARTIALCKSUM)
12947 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
12948 		else
12949 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
12950 
12951 		goto error;
12952 	}
12953 
12954 try_again:
12955 
12956 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
12957 	    zoneid, ipst)) == NULL) {
12958 		/* Send the TH_RST */
12959 		goto no_conn;
12960 	}
12961 
12962 	/*
12963 	 * TCP FAST PATH for AF_INET socket.
12964 	 *
12965 	 * TCP fast path to avoid extra work. An AF_INET socket type
12966 	 * does not have facility to receive extra information via
12967 	 * ip_process or ip_add_info. Also, when the connection was
12968 	 * established, we made a check if this connection is impacted
12969 	 * by any global IPSec policy or per connection policy (a
12970 	 * policy that comes in effect later will not apply to this
12971 	 * connection). Since all this can be determined at the
12972 	 * connection establishment time, a quick check of flags
12973 	 * can avoid extra work.
12974 	 */
12975 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12976 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12977 		ASSERT(first_mp == mp);
12978 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12979 		SET_SQUEUE(mp, tcp_rput_data, connp);
12980 		return (mp);
12981 	}
12982 
12983 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12984 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12985 		if (IPCL_IS_TCP(connp)) {
12986 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12987 			DB_CKSUMSTART(mp) =
12988 			    (intptr_t)ip_squeue_get(ill_ring);
12989 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12990 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
12991 				BUMP_MIB(ill->ill_ip_mib,
12992 				    ipIfStatsHCInDelivers);
12993 				SET_SQUEUE(mp, connp->conn_recv, connp);
12994 				return (mp);
12995 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12996 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
12997 				BUMP_MIB(ill->ill_ip_mib,
12998 				    ipIfStatsHCInDelivers);
12999 				ip_squeue_enter_unbound++;
13000 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13001 				    connp);
13002 				return (mp);
13003 			}
13004 			syn_present = B_TRUE;
13005 		}
13006 
13007 	}
13008 
13009 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13010 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13011 
13012 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13013 		/* No need to send this packet to TCP */
13014 		if ((flags & TH_RST) || (flags & TH_URG)) {
13015 			CONN_DEC_REF(connp);
13016 			freemsg(first_mp);
13017 			return (NULL);
13018 		}
13019 		if (flags & TH_ACK) {
13020 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13021 			    ipst->ips_netstack->netstack_tcp);
13022 			CONN_DEC_REF(connp);
13023 			return (NULL);
13024 		}
13025 
13026 		CONN_DEC_REF(connp);
13027 		freemsg(first_mp);
13028 		return (NULL);
13029 	}
13030 
13031 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13032 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13033 		    ipha, NULL, mctl_present);
13034 		if (first_mp == NULL) {
13035 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13036 			CONN_DEC_REF(connp);
13037 			return (NULL);
13038 		}
13039 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13040 			ASSERT(syn_present);
13041 			if (mctl_present) {
13042 				ASSERT(first_mp != mp);
13043 				first_mp->b_datap->db_struioflag |=
13044 				    STRUIO_POLICY;
13045 			} else {
13046 				ASSERT(first_mp == mp);
13047 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13048 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13049 			}
13050 		} else {
13051 			/*
13052 			 * Discard first_mp early since we're dealing with a
13053 			 * fully-connected conn_t and tcp doesn't do policy in
13054 			 * this case.
13055 			 */
13056 			if (mctl_present) {
13057 				freeb(first_mp);
13058 				mctl_present = B_FALSE;
13059 			}
13060 			first_mp = mp;
13061 		}
13062 	}
13063 
13064 	/* Initiate IPPF processing for fastpath */
13065 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13066 		uint32_t	ill_index;
13067 
13068 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13069 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13070 		if (mp == NULL) {
13071 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13072 			    "deferred/dropped during IPPF processing\n"));
13073 			CONN_DEC_REF(connp);
13074 			if (mctl_present)
13075 				freeb(first_mp);
13076 			return (NULL);
13077 		} else if (mctl_present) {
13078 			/*
13079 			 * ip_process might return a new mp.
13080 			 */
13081 			ASSERT(first_mp != mp);
13082 			first_mp->b_cont = mp;
13083 		} else {
13084 			first_mp = mp;
13085 		}
13086 
13087 	}
13088 
13089 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13090 		/*
13091 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13092 		 * make sure IPF_RECVIF is passed to ip_add_info.
13093 		 */
13094 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13095 		    IPCL_ZONEID(connp), ipst);
13096 		if (mp == NULL) {
13097 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13098 			CONN_DEC_REF(connp);
13099 			if (mctl_present)
13100 				freeb(first_mp);
13101 			return (NULL);
13102 		} else if (mctl_present) {
13103 			/*
13104 			 * ip_add_info might return a new mp.
13105 			 */
13106 			ASSERT(first_mp != mp);
13107 			first_mp->b_cont = mp;
13108 		} else {
13109 			first_mp = mp;
13110 		}
13111 	}
13112 
13113 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13114 	if (IPCL_IS_TCP(connp)) {
13115 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13116 		return (first_mp);
13117 	} else {
13118 		putnext(connp->conn_rq, first_mp);
13119 		CONN_DEC_REF(connp);
13120 		return (NULL);
13121 	}
13122 
13123 no_conn:
13124 	/* Initiate IPPf processing, if needed. */
13125 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13126 		uint32_t ill_index;
13127 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13128 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13129 		if (first_mp == NULL) {
13130 			return (NULL);
13131 		}
13132 	}
13133 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13134 
13135 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13136 	    ipst->ips_netstack->netstack_tcp);
13137 	return (NULL);
13138 ipoptions:
13139 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13140 		goto slow_done;
13141 	}
13142 
13143 	UPDATE_IB_PKT_COUNT(ire);
13144 	ire->ire_last_used_time = lbolt;
13145 
13146 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13147 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13148 fragmented:
13149 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13150 			if (mctl_present)
13151 				freeb(first_mp);
13152 			goto slow_done;
13153 		}
13154 		/*
13155 		 * Make sure that first_mp points back to mp as
13156 		 * the mp we came in with could have changed in
13157 		 * ip_rput_fragment().
13158 		 */
13159 		ASSERT(!mctl_present);
13160 		ipha = (ipha_t *)mp->b_rptr;
13161 		first_mp = mp;
13162 	}
13163 
13164 	/* Now we have a complete datagram, destined for this machine. */
13165 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13166 
13167 	len = mp->b_wptr - mp->b_rptr;
13168 	/* Pull up a minimal TCP header, if necessary. */
13169 	if (len < (u1 + 20)) {
13170 tcppullup:
13171 		if (!pullupmsg(mp, u1 + 20)) {
13172 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13173 			goto error;
13174 		}
13175 		ipha = (ipha_t *)mp->b_rptr;
13176 		len = mp->b_wptr - mp->b_rptr;
13177 	}
13178 
13179 	/*
13180 	 * Extract the offset field from the TCP header.  As usual, we
13181 	 * try to help the compiler more than the reader.
13182 	 */
13183 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13184 	if (offset != 5) {
13185 tcpoptions:
13186 		if (offset < 5) {
13187 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13188 			goto error;
13189 		}
13190 		/*
13191 		 * There must be TCP options.
13192 		 * Make sure we can grab them.
13193 		 */
13194 		offset <<= 2;
13195 		offset += u1;
13196 		if (len < offset) {
13197 			if (!pullupmsg(mp, offset)) {
13198 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13199 				goto error;
13200 			}
13201 			ipha = (ipha_t *)mp->b_rptr;
13202 			len = mp->b_wptr - rptr;
13203 		}
13204 	}
13205 
13206 	/* Get the total packet length in len, including headers. */
13207 	if (mp->b_cont) {
13208 multipkttcp:
13209 		len = msgdsize(mp);
13210 	}
13211 
13212 	/*
13213 	 * Check the TCP checksum by pulling together the pseudo-
13214 	 * header checksum, and passing it to ip_csum to be added in
13215 	 * with the TCP datagram.
13216 	 *
13217 	 * Since we are not using the hwcksum if available we must
13218 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13219 	 * If either of these fails along the way the mblk is freed.
13220 	 * If this logic ever changes and mblk is reused to say send
13221 	 * ICMP's back, then this flag may need to be cleared in
13222 	 * other places as well.
13223 	 */
13224 	DB_CKSUMFLAGS(mp) = 0;
13225 
13226 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13227 
13228 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13229 #ifdef	_BIG_ENDIAN
13230 	u1 += IPPROTO_TCP;
13231 #else
13232 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13233 #endif
13234 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13235 	/*
13236 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13237 	 */
13238 	IP_STAT(ipst, ip_in_sw_cksum);
13239 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13240 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13241 		goto error;
13242 	}
13243 
13244 	IP_STAT(ipst, ip_tcp_slow_path);
13245 	goto try_again;
13246 #undef  iphs
13247 #undef  rptr
13248 
13249 error:
13250 	freemsg(first_mp);
13251 slow_done:
13252 	return (NULL);
13253 }
13254 
13255 /* ARGSUSED */
13256 static void
13257 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13258     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13259 {
13260 	conn_t		*connp;
13261 	uint32_t	sum;
13262 	uint32_t	u1;
13263 	ssize_t		len;
13264 	sctp_hdr_t	*sctph;
13265 	zoneid_t	zoneid = ire->ire_zoneid;
13266 	uint32_t	pktsum;
13267 	uint32_t	calcsum;
13268 	uint32_t	ports;
13269 	in6_addr_t	map_src, map_dst;
13270 	ill_t		*ill = (ill_t *)q->q_ptr;
13271 	ip_stack_t	*ipst;
13272 	sctp_stack_t	*sctps;
13273 
13274 	ASSERT(recv_ill != NULL);
13275 	ipst = recv_ill->ill_ipst;
13276 	sctps = ipst->ips_netstack->netstack_sctp;
13277 
13278 #define	rptr	((uchar_t *)ipha)
13279 
13280 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13281 	ASSERT(ill != NULL);
13282 
13283 	/* u1 is # words of IP options */
13284 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13285 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13286 
13287 	/* IP options present */
13288 	if (u1 > 0) {
13289 		goto ipoptions;
13290 	} else {
13291 		/* Check the IP header checksum.  */
13292 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13293 #define	uph	((uint16_t *)ipha)
13294 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13295 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13296 #undef	uph
13297 			/* finish doing IP checksum */
13298 			sum = (sum & 0xFFFF) + (sum >> 16);
13299 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13300 			/*
13301 			 * Don't verify header checksum if this packet
13302 			 * is coming back from AH/ESP as we already did it.
13303 			 */
13304 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13305 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13306 				goto error;
13307 			}
13308 		}
13309 		/*
13310 		 * Since there is no SCTP h/w cksum support yet, just
13311 		 * clear the flag.
13312 		 */
13313 		DB_CKSUMFLAGS(mp) = 0;
13314 	}
13315 
13316 	/*
13317 	 * Don't verify header checksum if this packet is coming
13318 	 * back from AH/ESP as we already did it.
13319 	 */
13320 	if (!mctl_present) {
13321 		UPDATE_IB_PKT_COUNT(ire);
13322 		ire->ire_last_used_time = lbolt;
13323 	}
13324 
13325 	/* packet part of fragmented IP packet? */
13326 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13327 	if (u1 & (IPH_MF | IPH_OFFSET))
13328 		goto fragmented;
13329 
13330 	/* u1 = IP header length (20 bytes) */
13331 	u1 = IP_SIMPLE_HDR_LENGTH;
13332 
13333 find_sctp_client:
13334 	/* Pullup if we don't have the sctp common header. */
13335 	len = MBLKL(mp);
13336 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13337 		if (mp->b_cont == NULL ||
13338 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13339 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13340 			goto error;
13341 		}
13342 		ipha = (ipha_t *)mp->b_rptr;
13343 		len = MBLKL(mp);
13344 	}
13345 
13346 	sctph = (sctp_hdr_t *)(rptr + u1);
13347 #ifdef	DEBUG
13348 	if (!skip_sctp_cksum) {
13349 #endif
13350 		pktsum = sctph->sh_chksum;
13351 		sctph->sh_chksum = 0;
13352 		calcsum = sctp_cksum(mp, u1);
13353 		if (calcsum != pktsum) {
13354 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13355 			goto error;
13356 		}
13357 		sctph->sh_chksum = pktsum;
13358 #ifdef	DEBUG	/* skip_sctp_cksum */
13359 	}
13360 #endif
13361 	/* get the ports */
13362 	ports = *(uint32_t *)&sctph->sh_sport;
13363 
13364 	IRE_REFRELE(ire);
13365 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13366 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13367 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13368 	    sctps)) == NULL) {
13369 		/* Check for raw socket or OOTB handling */
13370 		goto no_conn;
13371 	}
13372 
13373 	/* Found a client; up it goes */
13374 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13375 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13376 	return;
13377 
13378 no_conn:
13379 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13380 	    ports, mctl_present, flags, B_TRUE, zoneid);
13381 	return;
13382 
13383 ipoptions:
13384 	DB_CKSUMFLAGS(mp) = 0;
13385 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13386 		goto slow_done;
13387 
13388 	UPDATE_IB_PKT_COUNT(ire);
13389 	ire->ire_last_used_time = lbolt;
13390 
13391 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13392 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13393 fragmented:
13394 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13395 			goto slow_done;
13396 		/*
13397 		 * Make sure that first_mp points back to mp as
13398 		 * the mp we came in with could have changed in
13399 		 * ip_rput_fragment().
13400 		 */
13401 		ASSERT(!mctl_present);
13402 		ipha = (ipha_t *)mp->b_rptr;
13403 		first_mp = mp;
13404 	}
13405 
13406 	/* Now we have a complete datagram, destined for this machine. */
13407 	u1 = IPH_HDR_LENGTH(ipha);
13408 	goto find_sctp_client;
13409 #undef  iphs
13410 #undef  rptr
13411 
13412 error:
13413 	freemsg(first_mp);
13414 slow_done:
13415 	IRE_REFRELE(ire);
13416 }
13417 
13418 #define	VER_BITS	0xF0
13419 #define	VERSION_6	0x60
13420 
13421 static boolean_t
13422 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13423     ipaddr_t *dstp, ip_stack_t *ipst)
13424 {
13425 	uint_t	opt_len;
13426 	ipha_t *ipha;
13427 	ssize_t len;
13428 	uint_t	pkt_len;
13429 
13430 	ASSERT(ill != NULL);
13431 	IP_STAT(ipst, ip_ipoptions);
13432 	ipha = *iphapp;
13433 
13434 #define	rptr    ((uchar_t *)ipha)
13435 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13436 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13437 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13438 		freemsg(mp);
13439 		return (B_FALSE);
13440 	}
13441 
13442 	/* multiple mblk or too short */
13443 	pkt_len = ntohs(ipha->ipha_length);
13444 
13445 	/* Get the number of words of IP options in the IP header. */
13446 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13447 	if (opt_len) {
13448 		/* IP Options present!  Validate and process. */
13449 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13450 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13451 			goto done;
13452 		}
13453 		/*
13454 		 * Recompute complete header length and make sure we
13455 		 * have access to all of it.
13456 		 */
13457 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13458 		if (len > (mp->b_wptr - rptr)) {
13459 			if (len > pkt_len) {
13460 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13461 				goto done;
13462 			}
13463 			if (!pullupmsg(mp, len)) {
13464 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13465 				goto done;
13466 			}
13467 			ipha = (ipha_t *)mp->b_rptr;
13468 		}
13469 		/*
13470 		 * Go off to ip_rput_options which returns the next hop
13471 		 * destination address, which may have been affected
13472 		 * by source routing.
13473 		 */
13474 		IP_STAT(ipst, ip_opt);
13475 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13476 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13477 			return (B_FALSE);
13478 		}
13479 	}
13480 	*iphapp = ipha;
13481 	return (B_TRUE);
13482 done:
13483 	/* clear b_prev - used by ip_mroute_decap */
13484 	mp->b_prev = NULL;
13485 	freemsg(mp);
13486 	return (B_FALSE);
13487 #undef  rptr
13488 }
13489 
13490 /*
13491  * Deal with the fact that there is no ire for the destination.
13492  */
13493 static ire_t *
13494 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13495 {
13496 	ipha_t	*ipha;
13497 	ill_t	*ill;
13498 	ire_t	*ire;
13499 	boolean_t	check_multirt = B_FALSE;
13500 	ip_stack_t *ipst;
13501 
13502 	ipha = (ipha_t *)mp->b_rptr;
13503 	ill = (ill_t *)q->q_ptr;
13504 
13505 	ASSERT(ill != NULL);
13506 	ipst = ill->ill_ipst;
13507 
13508 	/*
13509 	 * No IRE for this destination, so it can't be for us.
13510 	 * Unless we are forwarding, drop the packet.
13511 	 * We have to let source routed packets through
13512 	 * since we don't yet know if they are 'ping -l'
13513 	 * packets i.e. if they will go out over the
13514 	 * same interface as they came in on.
13515 	 */
13516 	if (ll_multicast) {
13517 		freemsg(mp);
13518 		return (NULL);
13519 	}
13520 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13521 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13522 		freemsg(mp);
13523 		return (NULL);
13524 	}
13525 
13526 	/*
13527 	 * Mark this packet as having originated externally.
13528 	 *
13529 	 * For non-forwarding code path, ire_send later double
13530 	 * checks this interface to see if it is still exists
13531 	 * post-ARP resolution.
13532 	 *
13533 	 * Also, IPQOS uses this to differentiate between
13534 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13535 	 * QOS packet processing in ip_wput_attach_llhdr().
13536 	 * The QoS module can mark the b_band for a fastpath message
13537 	 * or the dl_priority field in a unitdata_req header for
13538 	 * CoS marking. This info can only be found in
13539 	 * ip_wput_attach_llhdr().
13540 	 */
13541 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13542 	/*
13543 	 * Clear the indication that this may have a hardware checksum
13544 	 * as we are not using it
13545 	 */
13546 	DB_CKSUMFLAGS(mp) = 0;
13547 
13548 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13549 	    MBLK_GETLABEL(mp), ipst);
13550 
13551 	if (ire == NULL && check_multirt) {
13552 		/* Let ip_newroute handle CGTP  */
13553 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13554 		return (NULL);
13555 	}
13556 
13557 	if (ire != NULL)
13558 		return (ire);
13559 
13560 	mp->b_prev = mp->b_next = 0;
13561 	/* send icmp unreachable */
13562 	q = WR(q);
13563 	/* Sent by forwarding path, and router is global zone */
13564 	if (ip_source_routed(ipha, ipst)) {
13565 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13566 		    GLOBAL_ZONEID, ipst);
13567 	} else {
13568 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13569 		    ipst);
13570 	}
13571 
13572 	return (NULL);
13573 
13574 }
13575 
13576 /*
13577  * check ip header length and align it.
13578  */
13579 static boolean_t
13580 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13581 {
13582 	ssize_t len;
13583 	ill_t *ill;
13584 	ipha_t	*ipha;
13585 
13586 	len = MBLKL(mp);
13587 
13588 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13589 		ill = (ill_t *)q->q_ptr;
13590 
13591 		if (!OK_32PTR(mp->b_rptr))
13592 			IP_STAT(ipst, ip_notaligned1);
13593 		else
13594 			IP_STAT(ipst, ip_notaligned2);
13595 		/* Guard against bogus device drivers */
13596 		if (len < 0) {
13597 			/* clear b_prev - used by ip_mroute_decap */
13598 			mp->b_prev = NULL;
13599 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13600 			freemsg(mp);
13601 			return (B_FALSE);
13602 		}
13603 
13604 		if (ip_rput_pullups++ == 0) {
13605 			ipha = (ipha_t *)mp->b_rptr;
13606 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13607 			    "ip_check_and_align_header: %s forced us to "
13608 			    " pullup pkt, hdr len %ld, hdr addr %p",
13609 			    ill->ill_name, len, ipha);
13610 		}
13611 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13612 			/* clear b_prev - used by ip_mroute_decap */
13613 			mp->b_prev = NULL;
13614 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13615 			freemsg(mp);
13616 			return (B_FALSE);
13617 		}
13618 	}
13619 	return (B_TRUE);
13620 }
13621 
13622 ire_t *
13623 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13624 {
13625 	ire_t		*new_ire;
13626 	ill_t		*ire_ill;
13627 	uint_t		ifindex;
13628 	ip_stack_t	*ipst = ill->ill_ipst;
13629 	boolean_t	strict_check = B_FALSE;
13630 
13631 	/*
13632 	 * This packet came in on an interface other than the one associated
13633 	 * with the first ire we found for the destination address. We do
13634 	 * another ire lookup here, using the ingress ill, to see if the
13635 	 * interface is in an interface group.
13636 	 * As long as the ills belong to the same group, we don't consider
13637 	 * them to be arriving on the wrong interface. Thus, if the switch
13638 	 * is doing inbound load spreading, we won't drop packets when the
13639 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13640 	 * for 'usesrc groups' where the destination address may belong to
13641 	 * another interface to allow multipathing to happen.
13642 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13643 	 * where the local address may not be unique. In this case we were
13644 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13645 	 * actually returned. The new lookup, which is more specific, should
13646 	 * only find the IRE_LOCAL associated with the ingress ill if one
13647 	 * exists.
13648 	 */
13649 
13650 	if (ire->ire_ipversion == IPV4_VERSION) {
13651 		if (ipst->ips_ip_strict_dst_multihoming)
13652 			strict_check = B_TRUE;
13653 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13654 		    ill->ill_ipif, ALL_ZONES, NULL,
13655 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13656 	} else {
13657 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13658 		if (ipst->ips_ipv6_strict_dst_multihoming)
13659 			strict_check = B_TRUE;
13660 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13661 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13662 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13663 	}
13664 	/*
13665 	 * If the same ire that was returned in ip_input() is found then this
13666 	 * is an indication that interface groups are in use. The packet
13667 	 * arrived on a different ill in the group than the one associated with
13668 	 * the destination address.  If a different ire was found then the same
13669 	 * IP address must be hosted on multiple ills. This is possible with
13670 	 * unnumbered point2point interfaces. We switch to use this new ire in
13671 	 * order to have accurate interface statistics.
13672 	 */
13673 	if (new_ire != NULL) {
13674 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13675 			ire_refrele(ire);
13676 			ire = new_ire;
13677 		} else {
13678 			ire_refrele(new_ire);
13679 		}
13680 		return (ire);
13681 	} else if ((ire->ire_rfq == NULL) &&
13682 	    (ire->ire_ipversion == IPV4_VERSION)) {
13683 		/*
13684 		 * The best match could have been the original ire which
13685 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13686 		 * the strict multihoming checks are irrelevant as we consider
13687 		 * local addresses hosted on lo0 to be interface agnostic. We
13688 		 * only expect a null ire_rfq on IREs which are associated with
13689 		 * lo0 hence we can return now.
13690 		 */
13691 		return (ire);
13692 	}
13693 
13694 	/*
13695 	 * Chase pointers once and store locally.
13696 	 */
13697 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13698 	    (ill_t *)(ire->ire_rfq->q_ptr);
13699 	ifindex = ill->ill_usesrc_ifindex;
13700 
13701 	/*
13702 	 * Check if it's a legal address on the 'usesrc' interface.
13703 	 */
13704 	if ((ifindex != 0) && (ire_ill != NULL) &&
13705 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13706 		return (ire);
13707 	}
13708 
13709 	/*
13710 	 * If the ip*_strict_dst_multihoming switch is on then we can
13711 	 * only accept this packet if the interface is marked as routing.
13712 	 */
13713 	if (!(strict_check))
13714 		return (ire);
13715 
13716 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13717 	    ILLF_ROUTER) != 0) {
13718 		return (ire);
13719 	}
13720 
13721 	ire_refrele(ire);
13722 	return (NULL);
13723 }
13724 
13725 ire_t *
13726 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13727 {
13728 	ipha_t	*ipha;
13729 	ipaddr_t ip_dst, ip_src;
13730 	ire_t	*src_ire = NULL;
13731 	ill_t	*stq_ill;
13732 	uint_t	hlen;
13733 	uint_t	pkt_len;
13734 	uint32_t sum;
13735 	queue_t	*dev_q;
13736 	boolean_t check_multirt = B_FALSE;
13737 	ip_stack_t *ipst = ill->ill_ipst;
13738 
13739 	ipha = (ipha_t *)mp->b_rptr;
13740 
13741 	/*
13742 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13743 	 * The loopback address check for both src and dst has already
13744 	 * been checked in ip_input
13745 	 */
13746 	ip_dst = ntohl(dst);
13747 	ip_src = ntohl(ipha->ipha_src);
13748 
13749 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13750 	    IN_CLASSD(ip_src)) {
13751 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13752 		goto drop;
13753 	}
13754 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13755 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13756 
13757 	if (src_ire != NULL) {
13758 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13759 		goto drop;
13760 	}
13761 
13762 
13763 	/* No ire cache of nexthop. So first create one  */
13764 	if (ire == NULL) {
13765 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13766 		/*
13767 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13768 		 * is not set. So upon return from ire_forward
13769 		 * check_multirt should remain as false.
13770 		 */
13771 		ASSERT(!check_multirt);
13772 		if (ire == NULL) {
13773 			/* An attempt was made to forward the packet */
13774 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13775 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13776 			mp->b_prev = mp->b_next = 0;
13777 			/* send icmp unreachable */
13778 			/* Sent by forwarding path, and router is global zone */
13779 			if (ip_source_routed(ipha, ipst)) {
13780 				icmp_unreachable(ill->ill_wq, mp,
13781 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13782 				    ipst);
13783 			} else {
13784 				icmp_unreachable(ill->ill_wq, mp,
13785 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13786 				    ipst);
13787 			}
13788 			return (ire);
13789 		}
13790 	}
13791 
13792 	/*
13793 	 * Forwarding fastpath exception case:
13794 	 * If either of the follwoing case is true, we take
13795 	 * the slowpath
13796 	 *	o forwarding is not enabled
13797 	 *	o incoming and outgoing interface are the same, or the same
13798 	 *	  IPMP group
13799 	 *	o corresponding ire is in incomplete state
13800 	 *	o packet needs fragmentation
13801 	 *
13802 	 * The codeflow from here on is thus:
13803 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13804 	 */
13805 	pkt_len = ntohs(ipha->ipha_length);
13806 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13807 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13808 	    !(ill->ill_flags & ILLF_ROUTER) ||
13809 	    (ill == stq_ill) ||
13810 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13811 	    (ire->ire_nce == NULL) ||
13812 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13813 	    (pkt_len > ire->ire_max_frag) ||
13814 	    ipha->ipha_ttl <= 1) {
13815 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13816 		    ipha, ill, B_FALSE);
13817 		return (ire);
13818 	}
13819 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13820 
13821 	DTRACE_PROBE4(ip4__forwarding__start,
13822 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13823 
13824 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13825 	    ipst->ips_ipv4firewall_forwarding,
13826 	    ill, stq_ill, ipha, mp, mp, ipst);
13827 
13828 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13829 
13830 	if (mp == NULL)
13831 		goto drop;
13832 
13833 	mp->b_datap->db_struioun.cksum.flags = 0;
13834 	/* Adjust the checksum to reflect the ttl decrement. */
13835 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13836 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13837 	ipha->ipha_ttl--;
13838 
13839 	dev_q = ire->ire_stq->q_next;
13840 	if ((dev_q->q_next != NULL ||
13841 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13842 		goto indiscard;
13843 	}
13844 
13845 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13846 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13847 
13848 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13849 		mblk_t *mpip = mp;
13850 
13851 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13852 		if (mp != NULL) {
13853 			DTRACE_PROBE4(ip4__physical__out__start,
13854 			    ill_t *, NULL, ill_t *, stq_ill,
13855 			    ipha_t *, ipha, mblk_t *, mp);
13856 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
13857 			    ipst->ips_ipv4firewall_physical_out,
13858 			    NULL, stq_ill, ipha, mp, mpip, ipst);
13859 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13860 			    mp);
13861 			if (mp == NULL)
13862 				goto drop;
13863 
13864 			UPDATE_IB_PKT_COUNT(ire);
13865 			ire->ire_last_used_time = lbolt;
13866 			BUMP_MIB(stq_ill->ill_ip_mib,
13867 			    ipIfStatsHCOutForwDatagrams);
13868 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13869 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
13870 			    pkt_len);
13871 			putnext(ire->ire_stq, mp);
13872 			return (ire);
13873 		}
13874 	}
13875 
13876 indiscard:
13877 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13878 drop:
13879 	if (mp != NULL)
13880 		freemsg(mp);
13881 	if (src_ire != NULL)
13882 		ire_refrele(src_ire);
13883 	return (ire);
13884 
13885 }
13886 
13887 /*
13888  * This function is called in the forwarding slowpath, when
13889  * either the ire lacks the link-layer address, or the packet needs
13890  * further processing(eg. fragmentation), before transmission.
13891  */
13892 
13893 static void
13894 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13895     ill_t *ill, boolean_t ll_multicast)
13896 {
13897 	ill_group_t	*ill_group;
13898 	ill_group_t	*ire_group;
13899 	queue_t		*dev_q;
13900 	ire_t		*src_ire;
13901 	ip_stack_t	*ipst = ill->ill_ipst;
13902 
13903 	ASSERT(ire->ire_stq != NULL);
13904 
13905 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13906 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13907 
13908 	if (ll_multicast != 0) {
13909 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13910 		goto drop_pkt;
13911 	}
13912 
13913 	/*
13914 	 * check if ipha_src is a broadcast address. Note that this
13915 	 * check is redundant when we get here from ip_fast_forward()
13916 	 * which has already done this check. However, since we can
13917 	 * also get here from ip_rput_process_broadcast() or, for
13918 	 * for the slow path through ip_fast_forward(), we perform
13919 	 * the check again for code-reusability
13920 	 */
13921 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13922 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13923 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13924 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13925 		if (src_ire != NULL)
13926 			ire_refrele(src_ire);
13927 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13928 		ip2dbg(("ip_rput_process_forward: Received packet with"
13929 		    " bad src/dst address on %s\n", ill->ill_name));
13930 		goto drop_pkt;
13931 	}
13932 
13933 	ill_group = ill->ill_group;
13934 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13935 	/*
13936 	 * Check if we want to forward this one at this time.
13937 	 * We allow source routed packets on a host provided that
13938 	 * they go out the same interface or same interface group
13939 	 * as they came in on.
13940 	 *
13941 	 * XXX To be quicker, we may wish to not chase pointers to
13942 	 * get the ILLF_ROUTER flag and instead store the
13943 	 * forwarding policy in the ire.  An unfortunate
13944 	 * side-effect of that would be requiring an ire flush
13945 	 * whenever the ILLF_ROUTER flag changes.
13946 	 */
13947 	if (((ill->ill_flags &
13948 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13949 	    ILLF_ROUTER) == 0) &&
13950 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
13951 	    (ill_group != NULL && ill_group == ire_group)))) {
13952 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13953 		if (ip_source_routed(ipha, ipst)) {
13954 			q = WR(q);
13955 			/*
13956 			 * Clear the indication that this may have
13957 			 * hardware checksum as we are not using it.
13958 			 */
13959 			DB_CKSUMFLAGS(mp) = 0;
13960 			/* Sent by forwarding path, and router is global zone */
13961 			icmp_unreachable(q, mp,
13962 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
13963 			return;
13964 		}
13965 		goto drop_pkt;
13966 	}
13967 
13968 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13969 
13970 	/* Packet is being forwarded. Turning off hwcksum flag. */
13971 	DB_CKSUMFLAGS(mp) = 0;
13972 	if (ipst->ips_ip_g_send_redirects) {
13973 		/*
13974 		 * Check whether the incoming interface and outgoing
13975 		 * interface is part of the same group. If so,
13976 		 * send redirects.
13977 		 *
13978 		 * Check the source address to see if it originated
13979 		 * on the same logical subnet it is going back out on.
13980 		 * If so, we should be able to send it a redirect.
13981 		 * Avoid sending a redirect if the destination
13982 		 * is directly connected (i.e., ipha_dst is the same
13983 		 * as ire_gateway_addr or the ire_addr of the
13984 		 * nexthop IRE_CACHE ), or if the packet was source
13985 		 * routed out this interface.
13986 		 */
13987 		ipaddr_t src, nhop;
13988 		mblk_t	*mp1;
13989 		ire_t	*nhop_ire = NULL;
13990 
13991 		/*
13992 		 * Check whether ire_rfq and q are from the same ill
13993 		 * or if they are not same, they at least belong
13994 		 * to the same group. If so, send redirects.
13995 		 */
13996 		if ((ire->ire_rfq == q ||
13997 		    (ill_group != NULL && ill_group == ire_group)) &&
13998 		    !ip_source_routed(ipha, ipst)) {
13999 
14000 			nhop = (ire->ire_gateway_addr != 0 ?
14001 			    ire->ire_gateway_addr : ire->ire_addr);
14002 
14003 			if (ipha->ipha_dst == nhop) {
14004 				/*
14005 				 * We avoid sending a redirect if the
14006 				 * destination is directly connected
14007 				 * because it is possible that multiple
14008 				 * IP subnets may have been configured on
14009 				 * the link, and the source may not
14010 				 * be on the same subnet as ip destination,
14011 				 * even though they are on the same
14012 				 * physical link.
14013 				 */
14014 				goto sendit;
14015 			}
14016 
14017 			src = ipha->ipha_src;
14018 
14019 			/*
14020 			 * We look up the interface ire for the nexthop,
14021 			 * to see if ipha_src is in the same subnet
14022 			 * as the nexthop.
14023 			 *
14024 			 * Note that, if, in the future, IRE_CACHE entries
14025 			 * are obsoleted,  this lookup will not be needed,
14026 			 * as the ire passed to this function will be the
14027 			 * same as the nhop_ire computed below.
14028 			 */
14029 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14030 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14031 			    0, NULL, MATCH_IRE_TYPE, ipst);
14032 
14033 			if (nhop_ire != NULL) {
14034 				if ((src & nhop_ire->ire_mask) ==
14035 				    (nhop & nhop_ire->ire_mask)) {
14036 					/*
14037 					 * The source is directly connected.
14038 					 * Just copy the ip header (which is
14039 					 * in the first mblk)
14040 					 */
14041 					mp1 = copyb(mp);
14042 					if (mp1 != NULL) {
14043 						icmp_send_redirect(WR(q), mp1,
14044 						    nhop, ipst);
14045 					}
14046 				}
14047 				ire_refrele(nhop_ire);
14048 			}
14049 		}
14050 	}
14051 sendit:
14052 	dev_q = ire->ire_stq->q_next;
14053 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14054 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14055 		freemsg(mp);
14056 		return;
14057 	}
14058 
14059 	ip_rput_forward(ire, ipha, mp, ill);
14060 	return;
14061 
14062 drop_pkt:
14063 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14064 	freemsg(mp);
14065 }
14066 
14067 ire_t *
14068 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14069     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14070 {
14071 	queue_t		*q;
14072 	uint16_t	hcksumflags;
14073 	ip_stack_t	*ipst = ill->ill_ipst;
14074 
14075 	q = *qp;
14076 
14077 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14078 
14079 	/*
14080 	 * Clear the indication that this may have hardware
14081 	 * checksum as we are not using it for forwarding.
14082 	 */
14083 	hcksumflags = DB_CKSUMFLAGS(mp);
14084 	DB_CKSUMFLAGS(mp) = 0;
14085 
14086 	/*
14087 	 * Directed broadcast forwarding: if the packet came in over a
14088 	 * different interface then it is routed out over we can forward it.
14089 	 */
14090 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14091 		ire_refrele(ire);
14092 		freemsg(mp);
14093 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14094 		return (NULL);
14095 	}
14096 	/*
14097 	 * For multicast we have set dst to be INADDR_BROADCAST
14098 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14099 	 * only for broadcast packets.
14100 	 */
14101 	if (!CLASSD(ipha->ipha_dst)) {
14102 		ire_t *new_ire;
14103 		ipif_t *ipif;
14104 		/*
14105 		 * For ill groups, as the switch duplicates broadcasts
14106 		 * across all the ports, we need to filter out and
14107 		 * send up only one copy. There is one copy for every
14108 		 * broadcast address on each ill. Thus, we look for a
14109 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14110 		 * later to see whether this ill is eligible to receive
14111 		 * them or not. ill_nominate_bcast_rcv() nominates only
14112 		 * one set of IREs for receiving.
14113 		 */
14114 
14115 		ipif = ipif_get_next_ipif(NULL, ill);
14116 		if (ipif == NULL) {
14117 			ire_refrele(ire);
14118 			freemsg(mp);
14119 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14120 			return (NULL);
14121 		}
14122 		new_ire = ire_ctable_lookup(dst, 0, 0,
14123 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14124 		ipif_refrele(ipif);
14125 
14126 		if (new_ire != NULL) {
14127 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14128 				ire_refrele(ire);
14129 				ire_refrele(new_ire);
14130 				freemsg(mp);
14131 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14132 				return (NULL);
14133 			}
14134 			/*
14135 			 * In the special case of multirouted broadcast
14136 			 * packets, we unconditionally need to "gateway"
14137 			 * them to the appropriate interface here.
14138 			 * In the normal case, this cannot happen, because
14139 			 * there is no broadcast IRE tagged with the
14140 			 * RTF_MULTIRT flag.
14141 			 */
14142 			if (new_ire->ire_flags & RTF_MULTIRT) {
14143 				ire_refrele(new_ire);
14144 				if (ire->ire_rfq != NULL) {
14145 					q = ire->ire_rfq;
14146 					*qp = q;
14147 				}
14148 			} else {
14149 				ire_refrele(ire);
14150 				ire = new_ire;
14151 			}
14152 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14153 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14154 				/*
14155 				 * Free the message if
14156 				 * ip_g_forward_directed_bcast is turned
14157 				 * off for non-local broadcast.
14158 				 */
14159 				ire_refrele(ire);
14160 				freemsg(mp);
14161 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14162 				return (NULL);
14163 			}
14164 		} else {
14165 			/*
14166 			 * This CGTP packet successfully passed the
14167 			 * CGTP filter, but the related CGTP
14168 			 * broadcast IRE has not been found,
14169 			 * meaning that the redundant ipif is
14170 			 * probably down. However, if we discarded
14171 			 * this packet, its duplicate would be
14172 			 * filtered out by the CGTP filter so none
14173 			 * of them would get through. So we keep
14174 			 * going with this one.
14175 			 */
14176 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14177 			if (ire->ire_rfq != NULL) {
14178 				q = ire->ire_rfq;
14179 				*qp = q;
14180 			}
14181 		}
14182 	}
14183 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14184 		/*
14185 		 * Verify that there are not more then one
14186 		 * IRE_BROADCAST with this broadcast address which
14187 		 * has ire_stq set.
14188 		 * TODO: simplify, loop over all IRE's
14189 		 */
14190 		ire_t	*ire1;
14191 		int	num_stq = 0;
14192 		mblk_t	*mp1;
14193 
14194 		/* Find the first one with ire_stq set */
14195 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14196 		for (ire1 = ire; ire1 &&
14197 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14198 		    ire1 = ire1->ire_next)
14199 			;
14200 		if (ire1) {
14201 			ire_refrele(ire);
14202 			ire = ire1;
14203 			IRE_REFHOLD(ire);
14204 		}
14205 
14206 		/* Check if there are additional ones with stq set */
14207 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14208 			if (ire->ire_addr != ire1->ire_addr)
14209 				break;
14210 			if (ire1->ire_stq) {
14211 				num_stq++;
14212 				break;
14213 			}
14214 		}
14215 		rw_exit(&ire->ire_bucket->irb_lock);
14216 		if (num_stq == 1 && ire->ire_stq != NULL) {
14217 			ip1dbg(("ip_rput_process_broadcast: directed "
14218 			    "broadcast to 0x%x\n",
14219 			    ntohl(ire->ire_addr)));
14220 			mp1 = copymsg(mp);
14221 			if (mp1) {
14222 				switch (ipha->ipha_protocol) {
14223 				case IPPROTO_UDP:
14224 					ip_udp_input(q, mp1, ipha, ire, ill);
14225 					break;
14226 				default:
14227 					ip_proto_input(q, mp1, ipha, ire, ill);
14228 					break;
14229 				}
14230 			}
14231 			/*
14232 			 * Adjust ttl to 2 (1+1 - the forward engine
14233 			 * will decrement it by one.
14234 			 */
14235 			if (ip_csum_hdr(ipha)) {
14236 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14237 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14238 				freemsg(mp);
14239 				ire_refrele(ire);
14240 				return (NULL);
14241 			}
14242 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14243 			ipha->ipha_hdr_checksum = 0;
14244 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14245 			ip_rput_process_forward(q, mp, ire, ipha,
14246 			    ill, ll_multicast);
14247 			ire_refrele(ire);
14248 			return (NULL);
14249 		}
14250 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14251 		    ntohl(ire->ire_addr)));
14252 	}
14253 
14254 
14255 	/* Restore any hardware checksum flags */
14256 	DB_CKSUMFLAGS(mp) = hcksumflags;
14257 	return (ire);
14258 }
14259 
14260 /* ARGSUSED */
14261 static boolean_t
14262 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14263     int *ll_multicast, ipaddr_t *dstp)
14264 {
14265 	ip_stack_t	*ipst = ill->ill_ipst;
14266 
14267 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14268 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14269 	    ntohs(ipha->ipha_length));
14270 
14271 	/*
14272 	 * Forward packets only if we have joined the allmulti
14273 	 * group on this interface.
14274 	 */
14275 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14276 		int retval;
14277 
14278 		/*
14279 		 * Clear the indication that this may have hardware
14280 		 * checksum as we are not using it.
14281 		 */
14282 		DB_CKSUMFLAGS(mp) = 0;
14283 		retval = ip_mforward(ill, ipha, mp);
14284 		/* ip_mforward updates mib variables if needed */
14285 		/* clear b_prev - used by ip_mroute_decap */
14286 		mp->b_prev = NULL;
14287 
14288 		switch (retval) {
14289 		case 0:
14290 			/*
14291 			 * pkt is okay and arrived on phyint.
14292 			 *
14293 			 * If we are running as a multicast router
14294 			 * we need to see all IGMP and/or PIM packets.
14295 			 */
14296 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14297 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14298 				goto done;
14299 			}
14300 			break;
14301 		case -1:
14302 			/* pkt is mal-formed, toss it */
14303 			goto drop_pkt;
14304 		case 1:
14305 			/* pkt is okay and arrived on a tunnel */
14306 			/*
14307 			 * If we are running a multicast router
14308 			 *  we need to see all igmp packets.
14309 			 */
14310 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14311 				*dstp = INADDR_BROADCAST;
14312 				*ll_multicast = 1;
14313 				return (B_FALSE);
14314 			}
14315 
14316 			goto drop_pkt;
14317 		}
14318 	}
14319 
14320 	ILM_WALKER_HOLD(ill);
14321 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14322 		/*
14323 		 * This might just be caused by the fact that
14324 		 * multiple IP Multicast addresses map to the same
14325 		 * link layer multicast - no need to increment counter!
14326 		 */
14327 		ILM_WALKER_RELE(ill);
14328 		freemsg(mp);
14329 		return (B_TRUE);
14330 	}
14331 	ILM_WALKER_RELE(ill);
14332 done:
14333 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14334 	/*
14335 	 * This assumes the we deliver to all streams for multicast
14336 	 * and broadcast packets.
14337 	 */
14338 	*dstp = INADDR_BROADCAST;
14339 	*ll_multicast = 1;
14340 	return (B_FALSE);
14341 drop_pkt:
14342 	ip2dbg(("ip_rput: drop pkt\n"));
14343 	freemsg(mp);
14344 	return (B_TRUE);
14345 }
14346 
14347 static boolean_t
14348 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14349     int *ll_multicast, mblk_t **mpp)
14350 {
14351 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14352 	boolean_t must_copy = B_FALSE;
14353 	struct iocblk   *iocp;
14354 	ipha_t		*ipha;
14355 	ip_stack_t	*ipst = ill->ill_ipst;
14356 
14357 #define	rptr    ((uchar_t *)ipha)
14358 
14359 	first_mp = *first_mpp;
14360 	mp = *mpp;
14361 
14362 	ASSERT(first_mp == mp);
14363 
14364 	/*
14365 	 * if db_ref > 1 then copymsg and free original. Packet may be
14366 	 * changed and do not want other entity who has a reference to this
14367 	 * message to trip over the changes. This is a blind change because
14368 	 * trying to catch all places that might change packet is too
14369 	 * difficult (since it may be a module above this one)
14370 	 *
14371 	 * This corresponds to the non-fast path case. We walk down the full
14372 	 * chain in this case, and check the db_ref count of all the dblks,
14373 	 * and do a copymsg if required. It is possible that the db_ref counts
14374 	 * of the data blocks in the mblk chain can be different.
14375 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14376 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14377 	 * 'snoop' is running.
14378 	 */
14379 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14380 		if (mp1->b_datap->db_ref > 1) {
14381 			must_copy = B_TRUE;
14382 			break;
14383 		}
14384 	}
14385 
14386 	if (must_copy) {
14387 		mp1 = copymsg(mp);
14388 		if (mp1 == NULL) {
14389 			for (mp1 = mp; mp1 != NULL;
14390 			    mp1 = mp1->b_cont) {
14391 				mp1->b_next = NULL;
14392 				mp1->b_prev = NULL;
14393 			}
14394 			freemsg(mp);
14395 			if (ill != NULL) {
14396 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14397 			} else {
14398 				BUMP_MIB(&ipst->ips_ip_mib,
14399 				    ipIfStatsInDiscards);
14400 			}
14401 			return (B_TRUE);
14402 		}
14403 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14404 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14405 			/* Copy b_prev - used by ip_mroute_decap */
14406 			to_mp->b_prev = from_mp->b_prev;
14407 			from_mp->b_prev = NULL;
14408 		}
14409 		*first_mpp = first_mp = mp1;
14410 		freemsg(mp);
14411 		mp = mp1;
14412 		*mpp = mp1;
14413 	}
14414 
14415 	ipha = (ipha_t *)mp->b_rptr;
14416 
14417 	/*
14418 	 * previous code has a case for M_DATA.
14419 	 * We want to check how that happens.
14420 	 */
14421 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14422 	switch (first_mp->b_datap->db_type) {
14423 	case M_PROTO:
14424 	case M_PCPROTO:
14425 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14426 		    DL_UNITDATA_IND) {
14427 			/* Go handle anything other than data elsewhere. */
14428 			ip_rput_dlpi(q, mp);
14429 			return (B_TRUE);
14430 		}
14431 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14432 		/* Ditch the DLPI header. */
14433 		mp1 = mp->b_cont;
14434 		ASSERT(first_mp == mp);
14435 		*first_mpp = mp1;
14436 		freeb(mp);
14437 		*mpp = mp1;
14438 		return (B_FALSE);
14439 	case M_IOCACK:
14440 		ip1dbg(("got iocack "));
14441 		iocp = (struct iocblk *)mp->b_rptr;
14442 		switch (iocp->ioc_cmd) {
14443 		case DL_IOC_HDR_INFO:
14444 			ill = (ill_t *)q->q_ptr;
14445 			ill_fastpath_ack(ill, mp);
14446 			return (B_TRUE);
14447 		case SIOCSTUNPARAM:
14448 		case OSIOCSTUNPARAM:
14449 			/* Go through qwriter_ip */
14450 			break;
14451 		case SIOCGTUNPARAM:
14452 		case OSIOCGTUNPARAM:
14453 			ip_rput_other(NULL, q, mp, NULL);
14454 			return (B_TRUE);
14455 		default:
14456 			putnext(q, mp);
14457 			return (B_TRUE);
14458 		}
14459 		/* FALLTHRU */
14460 	case M_ERROR:
14461 	case M_HANGUP:
14462 		/*
14463 		 * Since this is on the ill stream we unconditionally
14464 		 * bump up the refcount
14465 		 */
14466 		ill_refhold(ill);
14467 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14468 		return (B_TRUE);
14469 	case M_CTL:
14470 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14471 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14472 		    IPHADA_M_CTL)) {
14473 			/*
14474 			 * It's an IPsec accelerated packet.
14475 			 * Make sure that the ill from which we received the
14476 			 * packet has enabled IPsec hardware acceleration.
14477 			 */
14478 			if (!(ill->ill_capabilities &
14479 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14480 				/* IPsec kstats: bean counter */
14481 				freemsg(mp);
14482 				return (B_TRUE);
14483 			}
14484 
14485 			/*
14486 			 * Make mp point to the mblk following the M_CTL,
14487 			 * then process according to type of mp.
14488 			 * After this processing, first_mp will point to
14489 			 * the data-attributes and mp to the pkt following
14490 			 * the M_CTL.
14491 			 */
14492 			mp = first_mp->b_cont;
14493 			if (mp == NULL) {
14494 				freemsg(first_mp);
14495 				return (B_TRUE);
14496 			}
14497 			/*
14498 			 * A Hardware Accelerated packet can only be M_DATA
14499 			 * ESP or AH packet.
14500 			 */
14501 			if (mp->b_datap->db_type != M_DATA) {
14502 				/* non-M_DATA IPsec accelerated packet */
14503 				IPSECHW_DEBUG(IPSECHW_PKT,
14504 				    ("non-M_DATA IPsec accelerated pkt\n"));
14505 				freemsg(first_mp);
14506 				return (B_TRUE);
14507 			}
14508 			ipha = (ipha_t *)mp->b_rptr;
14509 			if (ipha->ipha_protocol != IPPROTO_AH &&
14510 			    ipha->ipha_protocol != IPPROTO_ESP) {
14511 				IPSECHW_DEBUG(IPSECHW_PKT,
14512 				    ("non-M_DATA IPsec accelerated pkt\n"));
14513 				freemsg(first_mp);
14514 				return (B_TRUE);
14515 			}
14516 			*mpp = mp;
14517 			return (B_FALSE);
14518 		}
14519 		putnext(q, mp);
14520 		return (B_TRUE);
14521 	case M_IOCNAK:
14522 		ip1dbg(("got iocnak "));
14523 		iocp = (struct iocblk *)mp->b_rptr;
14524 		switch (iocp->ioc_cmd) {
14525 		case SIOCSTUNPARAM:
14526 		case OSIOCSTUNPARAM:
14527 			/*
14528 			 * Since this is on the ill stream we unconditionally
14529 			 * bump up the refcount
14530 			 */
14531 			ill_refhold(ill);
14532 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14533 			return (B_TRUE);
14534 		case DL_IOC_HDR_INFO:
14535 		case SIOCGTUNPARAM:
14536 		case OSIOCGTUNPARAM:
14537 			ip_rput_other(NULL, q, mp, NULL);
14538 			return (B_TRUE);
14539 		default:
14540 			break;
14541 		}
14542 		/* FALLTHRU */
14543 	default:
14544 		putnext(q, mp);
14545 		return (B_TRUE);
14546 	}
14547 }
14548 
14549 /* Read side put procedure.  Packets coming from the wire arrive here. */
14550 void
14551 ip_rput(queue_t *q, mblk_t *mp)
14552 {
14553 	ill_t		*ill = (ill_t *)q->q_ptr;
14554 	ip_stack_t	*ipst = ill->ill_ipst;
14555 	union DL_primitives *dl;
14556 
14557 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14558 
14559 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14560 		/*
14561 		 * If things are opening or closing, only accept high-priority
14562 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14563 		 * created; on close, things hanging off the ill may have been
14564 		 * freed already.)
14565 		 */
14566 		dl = (union DL_primitives *)mp->b_rptr;
14567 		if (DB_TYPE(mp) != M_PCPROTO ||
14568 		    dl->dl_primitive == DL_UNITDATA_IND) {
14569 			/*
14570 			 * SIOC[GS]TUNPARAM ioctls can come here.
14571 			 */
14572 			inet_freemsg(mp);
14573 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14574 			    "ip_rput_end: q %p (%S)", q, "uninit");
14575 			return;
14576 		}
14577 	}
14578 
14579 	/*
14580 	 * if db_ref > 1 then copymsg and free original. Packet may be
14581 	 * changed and we do not want the other entity who has a reference to
14582 	 * this message to trip over the changes. This is a blind change because
14583 	 * trying to catch all places that might change the packet is too
14584 	 * difficult.
14585 	 *
14586 	 * This corresponds to the fast path case, where we have a chain of
14587 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14588 	 * in the mblk chain. There doesn't seem to be a reason why a device
14589 	 * driver would send up data with varying db_ref counts in the mblk
14590 	 * chain. In any case the Fast path is a private interface, and our
14591 	 * drivers don't do such a thing. Given the above assumption, there is
14592 	 * no need to walk down the entire mblk chain (which could have a
14593 	 * potential performance problem)
14594 	 */
14595 	if (mp->b_datap->db_ref > 1) {
14596 		mblk_t  *mp1;
14597 		boolean_t adjusted = B_FALSE;
14598 		IP_STAT(ipst, ip_db_ref);
14599 
14600 		/*
14601 		 * The IP_RECVSLLA option depends on having the link layer
14602 		 * header. First check that:
14603 		 * a> the underlying device is of type ether, since this
14604 		 * option is currently supported only over ethernet.
14605 		 * b> there is enough room to copy over the link layer header.
14606 		 *
14607 		 * Once the checks are done, adjust rptr so that the link layer
14608 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14609 		 * be returned by some non-ethernet drivers but in this case the
14610 		 * second check will fail.
14611 		 */
14612 		if (ill->ill_type == IFT_ETHER &&
14613 		    (mp->b_rptr - mp->b_datap->db_base) >=
14614 		    sizeof (struct ether_header)) {
14615 			mp->b_rptr -= sizeof (struct ether_header);
14616 			adjusted = B_TRUE;
14617 		}
14618 		mp1 = copymsg(mp);
14619 		if (mp1 == NULL) {
14620 			mp->b_next = NULL;
14621 			/* clear b_prev - used by ip_mroute_decap */
14622 			mp->b_prev = NULL;
14623 			freemsg(mp);
14624 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14625 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14626 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14627 			return;
14628 		}
14629 		if (adjusted) {
14630 			/*
14631 			 * Copy is done. Restore the pointer in the _new_ mblk
14632 			 */
14633 			mp1->b_rptr += sizeof (struct ether_header);
14634 		}
14635 		/* Copy b_prev - used by ip_mroute_decap */
14636 		mp1->b_prev = mp->b_prev;
14637 		mp->b_prev = NULL;
14638 		freemsg(mp);
14639 		mp = mp1;
14640 	}
14641 
14642 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14643 	    "ip_rput_end: q %p (%S)", q, "end");
14644 
14645 	ip_input(ill, NULL, mp, NULL);
14646 }
14647 
14648 /*
14649  * Direct read side procedure capable of dealing with chains. GLDv3 based
14650  * drivers call this function directly with mblk chains while STREAMS
14651  * read side procedure ip_rput() calls this for single packet with ip_ring
14652  * set to NULL to process one packet at a time.
14653  *
14654  * The ill will always be valid if this function is called directly from
14655  * the driver.
14656  *
14657  * If ip_input() is called from GLDv3:
14658  *
14659  *   - This must be a non-VLAN IP stream.
14660  *   - 'mp' is either an untagged or a special priority-tagged packet.
14661  *   - Any VLAN tag that was in the MAC header has been stripped.
14662  *
14663  * If the IP header in packet is not 32-bit aligned, every message in the
14664  * chain will be aligned before further operations. This is required on SPARC
14665  * platform.
14666  */
14667 /* ARGSUSED */
14668 void
14669 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14670     struct mac_header_info_s *mhip)
14671 {
14672 	ipaddr_t		dst = NULL;
14673 	ipaddr_t		prev_dst;
14674 	ire_t			*ire = NULL;
14675 	ipha_t			*ipha;
14676 	uint_t			pkt_len;
14677 	ssize_t			len;
14678 	uint_t			opt_len;
14679 	int			ll_multicast;
14680 	int			cgtp_flt_pkt;
14681 	queue_t			*q = ill->ill_rq;
14682 	squeue_t		*curr_sqp = NULL;
14683 	mblk_t 			*head = NULL;
14684 	mblk_t			*tail = NULL;
14685 	mblk_t			*first_mp;
14686 	mblk_t 			*mp;
14687 	mblk_t			*dmp;
14688 	int			cnt = 0;
14689 	ip_stack_t		*ipst = ill->ill_ipst;
14690 
14691 	ASSERT(mp_chain != NULL);
14692 	ASSERT(ill != NULL);
14693 
14694 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14695 
14696 #define	rptr	((uchar_t *)ipha)
14697 
14698 	while (mp_chain != NULL) {
14699 		first_mp = mp = mp_chain;
14700 		mp_chain = mp_chain->b_next;
14701 		mp->b_next = NULL;
14702 		ll_multicast = 0;
14703 
14704 		/*
14705 		 * We do ire caching from one iteration to
14706 		 * another. In the event the packet chain contains
14707 		 * all packets from the same dst, this caching saves
14708 		 * an ire_cache_lookup for each of the succeeding
14709 		 * packets in a packet chain.
14710 		 */
14711 		prev_dst = dst;
14712 
14713 		/*
14714 		 * Check and align the IP header.
14715 		 */
14716 		if (DB_TYPE(mp) == M_DATA) {
14717 			dmp = mp;
14718 		} else if (DB_TYPE(mp) == M_PROTO &&
14719 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14720 			dmp = mp->b_cont;
14721 		} else {
14722 			dmp = NULL;
14723 		}
14724 		if (dmp != NULL) {
14725 			/*
14726 			 * IP header ptr not aligned?
14727 			 * OR IP header not complete in first mblk
14728 			 */
14729 			if (!OK_32PTR(dmp->b_rptr) ||
14730 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14731 				if (!ip_check_and_align_header(q, dmp, ipst))
14732 					continue;
14733 			}
14734 		}
14735 
14736 		/*
14737 		 * ip_input fast path
14738 		 */
14739 
14740 		/* mblk type is not M_DATA */
14741 		if (DB_TYPE(mp) != M_DATA) {
14742 			if (ip_rput_process_notdata(q, &first_mp, ill,
14743 			    &ll_multicast, &mp))
14744 				continue;
14745 		}
14746 
14747 		/* Make sure its an M_DATA and that its aligned */
14748 		ASSERT(DB_TYPE(mp) == M_DATA);
14749 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14750 
14751 		ipha = (ipha_t *)mp->b_rptr;
14752 		len = mp->b_wptr - rptr;
14753 		pkt_len = ntohs(ipha->ipha_length);
14754 
14755 		/*
14756 		 * We must count all incoming packets, even if they end
14757 		 * up being dropped later on.
14758 		 */
14759 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14760 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14761 
14762 		/* multiple mblk or too short */
14763 		len -= pkt_len;
14764 		if (len != 0) {
14765 			/*
14766 			 * Make sure we have data length consistent
14767 			 * with the IP header.
14768 			 */
14769 			if (mp->b_cont == NULL) {
14770 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14771 					BUMP_MIB(ill->ill_ip_mib,
14772 					    ipIfStatsInHdrErrors);
14773 					ip2dbg(("ip_input: drop pkt\n"));
14774 					freemsg(mp);
14775 					continue;
14776 				}
14777 				mp->b_wptr = rptr + pkt_len;
14778 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14779 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14780 					BUMP_MIB(ill->ill_ip_mib,
14781 					    ipIfStatsInHdrErrors);
14782 					ip2dbg(("ip_input: drop pkt\n"));
14783 					freemsg(mp);
14784 					continue;
14785 				}
14786 				(void) adjmsg(mp, -len);
14787 				IP_STAT(ipst, ip_multimblk3);
14788 			}
14789 		}
14790 
14791 		/* Obtain the dst of the current packet */
14792 		dst = ipha->ipha_dst;
14793 
14794 		if (IP_LOOPBACK_ADDR(dst) ||
14795 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14796 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14797 			cmn_err(CE_CONT, "dst %X src %X\n",
14798 			    dst, ipha->ipha_src);
14799 			freemsg(mp);
14800 			continue;
14801 		}
14802 
14803 		/*
14804 		 * The event for packets being received from a 'physical'
14805 		 * interface is placed after validation of the source and/or
14806 		 * destination address as being local so that packets can be
14807 		 * redirected to loopback addresses using ipnat.
14808 		 */
14809 		DTRACE_PROBE4(ip4__physical__in__start,
14810 		    ill_t *, ill, ill_t *, NULL,
14811 		    ipha_t *, ipha, mblk_t *, first_mp);
14812 
14813 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14814 		    ipst->ips_ipv4firewall_physical_in,
14815 		    ill, NULL, ipha, first_mp, mp, ipst);
14816 
14817 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14818 
14819 		if (first_mp == NULL) {
14820 			continue;
14821 		}
14822 		dst = ipha->ipha_dst;
14823 
14824 		/*
14825 		 * Attach any necessary label information to
14826 		 * this packet
14827 		 */
14828 		if (is_system_labeled() &&
14829 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14830 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14831 			freemsg(mp);
14832 			continue;
14833 		}
14834 
14835 		/*
14836 		 * Reuse the cached ire only if the ipha_dst of the previous
14837 		 * packet is the same as the current packet AND it is not
14838 		 * INADDR_ANY.
14839 		 */
14840 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14841 		    (ire != NULL)) {
14842 			ire_refrele(ire);
14843 			ire = NULL;
14844 		}
14845 		opt_len = ipha->ipha_version_and_hdr_length -
14846 		    IP_SIMPLE_HDR_VERSION;
14847 
14848 		/*
14849 		 * Check to see if we can take the fastpath.
14850 		 * That is possible if the following conditions are met
14851 		 *	o Tsol disabled
14852 		 *	o CGTP disabled
14853 		 *	o ipp_action_count is 0
14854 		 *	o no options in the packet
14855 		 *	o not a RSVP packet
14856 		 * 	o not a multicast packet
14857 		 */
14858 		if (!is_system_labeled() &&
14859 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14860 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14861 		    !ll_multicast && !CLASSD(dst)) {
14862 			if (ire == NULL)
14863 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
14864 				    ipst);
14865 
14866 			/* incoming packet is for forwarding */
14867 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14868 				ire = ip_fast_forward(ire, dst, ill, mp);
14869 				continue;
14870 			}
14871 			/* incoming packet is for local consumption */
14872 			if (ire->ire_type & IRE_LOCAL)
14873 				goto local;
14874 		}
14875 
14876 		/*
14877 		 * Disable ire caching for anything more complex
14878 		 * than the simple fast path case we checked for above.
14879 		 */
14880 		if (ire != NULL) {
14881 			ire_refrele(ire);
14882 			ire = NULL;
14883 		}
14884 
14885 		/* Full-blown slow path */
14886 		if (opt_len != 0) {
14887 			if (len != 0)
14888 				IP_STAT(ipst, ip_multimblk4);
14889 			else
14890 				IP_STAT(ipst, ip_ipoptions);
14891 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
14892 			    &dst, ipst))
14893 				continue;
14894 		}
14895 
14896 		/*
14897 		 * Invoke the CGTP (multirouting) filtering module to process
14898 		 * the incoming packet. Packets identified as duplicates
14899 		 * must be discarded. Filtering is active only if the
14900 		 * the ip_cgtp_filter ndd variable is non-zero.
14901 		 *
14902 		 * Only applies to the shared stack since the filter_ops
14903 		 * do not carry an ip_stack_t or zoneid.
14904 		 */
14905 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14906 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
14907 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
14908 			cgtp_flt_pkt =
14909 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14910 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14911 				freemsg(first_mp);
14912 				continue;
14913 			}
14914 		}
14915 
14916 		/*
14917 		 * If rsvpd is running, let RSVP daemon handle its processing
14918 		 * and forwarding of RSVP multicast/unicast packets.
14919 		 * If rsvpd is not running but mrouted is running, RSVP
14920 		 * multicast packets are forwarded as multicast traffic
14921 		 * and RSVP unicast packets are forwarded by unicast router.
14922 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14923 		 * packets are not forwarded, but the unicast packets are
14924 		 * forwarded like unicast traffic.
14925 		 */
14926 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14927 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
14928 		    NULL) {
14929 			/* RSVP packet and rsvpd running. Treat as ours */
14930 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14931 			/*
14932 			 * This assumes that we deliver to all streams for
14933 			 * multicast and broadcast packets.
14934 			 * We have to force ll_multicast to 1 to handle the
14935 			 * M_DATA messages passed in from ip_mroute_decap.
14936 			 */
14937 			dst = INADDR_BROADCAST;
14938 			ll_multicast = 1;
14939 		} else if (CLASSD(dst)) {
14940 			/* packet is multicast */
14941 			mp->b_next = NULL;
14942 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14943 			    &ll_multicast, &dst))
14944 				continue;
14945 		}
14946 
14947 		if (ire == NULL) {
14948 			ire = ire_cache_lookup(dst, ALL_ZONES,
14949 			    MBLK_GETLABEL(mp), ipst);
14950 		}
14951 
14952 		if (ire == NULL) {
14953 			/*
14954 			 * No IRE for this destination, so it can't be for us.
14955 			 * Unless we are forwarding, drop the packet.
14956 			 * We have to let source routed packets through
14957 			 * since we don't yet know if they are 'ping -l'
14958 			 * packets i.e. if they will go out over the
14959 			 * same interface as they came in on.
14960 			 */
14961 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
14962 			if (ire == NULL)
14963 				continue;
14964 		}
14965 
14966 		/*
14967 		 * Broadcast IRE may indicate either broadcast or
14968 		 * multicast packet
14969 		 */
14970 		if (ire->ire_type == IRE_BROADCAST) {
14971 			/*
14972 			 * Skip broadcast checks if packet is UDP multicast;
14973 			 * we'd rather not enter ip_rput_process_broadcast()
14974 			 * unless the packet is broadcast for real, since
14975 			 * that routine is a no-op for multicast.
14976 			 */
14977 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14978 			    !CLASSD(ipha->ipha_dst)) {
14979 				ire = ip_rput_process_broadcast(&q, mp,
14980 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14981 				    ll_multicast);
14982 				if (ire == NULL)
14983 					continue;
14984 			}
14985 		} else if (ire->ire_stq != NULL) {
14986 			/* fowarding? */
14987 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14988 			    ll_multicast);
14989 			/* ip_rput_process_forward consumed the packet */
14990 			continue;
14991 		}
14992 
14993 local:
14994 		/*
14995 		 * If the queue in the ire is different to the ingress queue
14996 		 * then we need to check to see if we can accept the packet.
14997 		 * Note that for multicast packets and broadcast packets sent
14998 		 * to a broadcast address which is shared between multiple
14999 		 * interfaces we should not do this since we just got a random
15000 		 * broadcast ire.
15001 		 */
15002 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15003 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15004 			    ill)) == NULL) {
15005 				/* Drop packet */
15006 				BUMP_MIB(ill->ill_ip_mib,
15007 				    ipIfStatsForwProhibits);
15008 				freemsg(mp);
15009 				continue;
15010 			}
15011 			if (ire->ire_rfq != NULL)
15012 				q = ire->ire_rfq;
15013 		}
15014 
15015 		switch (ipha->ipha_protocol) {
15016 		case IPPROTO_TCP:
15017 			ASSERT(first_mp == mp);
15018 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15019 			    mp, 0, q, ip_ring)) != NULL) {
15020 				if (curr_sqp == NULL) {
15021 					curr_sqp = GET_SQUEUE(mp);
15022 					ASSERT(cnt == 0);
15023 					cnt++;
15024 					head = tail = mp;
15025 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15026 					ASSERT(tail != NULL);
15027 					cnt++;
15028 					tail->b_next = mp;
15029 					tail = mp;
15030 				} else {
15031 					/*
15032 					 * A different squeue. Send the
15033 					 * chain for the previous squeue on
15034 					 * its way. This shouldn't happen
15035 					 * often unless interrupt binding
15036 					 * changes.
15037 					 */
15038 					IP_STAT(ipst, ip_input_multi_squeue);
15039 					squeue_enter_chain(curr_sqp, head,
15040 					    tail, cnt, SQTAG_IP_INPUT);
15041 					curr_sqp = GET_SQUEUE(mp);
15042 					head = mp;
15043 					tail = mp;
15044 					cnt = 1;
15045 				}
15046 			}
15047 			continue;
15048 		case IPPROTO_UDP:
15049 			ASSERT(first_mp == mp);
15050 			ip_udp_input(q, mp, ipha, ire, ill);
15051 			continue;
15052 		case IPPROTO_SCTP:
15053 			ASSERT(first_mp == mp);
15054 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15055 			    q, dst);
15056 			/* ire has been released by ip_sctp_input */
15057 			ire = NULL;
15058 			continue;
15059 		default:
15060 			ip_proto_input(q, first_mp, ipha, ire, ill);
15061 			continue;
15062 		}
15063 	}
15064 
15065 	if (ire != NULL)
15066 		ire_refrele(ire);
15067 
15068 	if (head != NULL)
15069 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15070 
15071 	/*
15072 	 * This code is there just to make netperf/ttcp look good.
15073 	 *
15074 	 * Its possible that after being in polling mode (and having cleared
15075 	 * the backlog), squeues have turned the interrupt frequency higher
15076 	 * to improve latency at the expense of more CPU utilization (less
15077 	 * packets per interrupts or more number of interrupts). Workloads
15078 	 * like ttcp/netperf do manage to tickle polling once in a while
15079 	 * but for the remaining time, stay in higher interrupt mode since
15080 	 * their packet arrival rate is pretty uniform and this shows up
15081 	 * as higher CPU utilization. Since people care about CPU utilization
15082 	 * while running netperf/ttcp, turn the interrupt frequency back to
15083 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15084 	 */
15085 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15086 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15087 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15088 			ip_ring->rr_blank(ip_ring->rr_handle,
15089 			    ip_ring->rr_normal_blank_time,
15090 			    ip_ring->rr_normal_pkt_cnt);
15091 		}
15092 		}
15093 
15094 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15095 	    "ip_input_end: q %p (%S)", q, "end");
15096 #undef  rptr
15097 }
15098 
15099 static void
15100 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15101     t_uscalar_t err)
15102 {
15103 	if (dl_err == DL_SYSERR) {
15104 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15105 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15106 		    ill->ill_name, dlpi_prim_str(prim), err);
15107 		return;
15108 	}
15109 
15110 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15111 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15112 	    dlpi_err_str(dl_err));
15113 }
15114 
15115 /*
15116  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15117  * than DL_UNITDATA_IND messages. If we need to process this message
15118  * exclusively, we call qwriter_ip, in which case we also need to call
15119  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15120  */
15121 void
15122 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15123 {
15124 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15125 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15126 	ill_t		*ill = (ill_t *)q->q_ptr;
15127 	boolean_t	pending;
15128 
15129 	ip1dbg(("ip_rput_dlpi"));
15130 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15131 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15132 		    "%s (0x%x), unix %u\n", ill->ill_name,
15133 		    dlpi_prim_str(dlea->dl_error_primitive),
15134 		    dlea->dl_error_primitive,
15135 		    dlpi_err_str(dlea->dl_errno),
15136 		    dlea->dl_errno,
15137 		    dlea->dl_unix_errno));
15138 	}
15139 
15140 	/*
15141 	 * If we received an ACK but didn't send a request for it, then it
15142 	 * can't be part of any pending operation; discard up-front.
15143 	 */
15144 	switch (dloa->dl_primitive) {
15145 	case DL_NOTIFY_IND:
15146 		pending = B_TRUE;
15147 		break;
15148 	case DL_ERROR_ACK:
15149 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15150 		break;
15151 	case DL_OK_ACK:
15152 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15153 		break;
15154 	case DL_INFO_ACK:
15155 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15156 		break;
15157 	case DL_BIND_ACK:
15158 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15159 		break;
15160 	case DL_PHYS_ADDR_ACK:
15161 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15162 		break;
15163 	case DL_NOTIFY_ACK:
15164 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15165 		break;
15166 	case DL_CONTROL_ACK:
15167 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15168 		break;
15169 	case DL_CAPABILITY_ACK:
15170 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15171 		break;
15172 	default:
15173 		/* Not a DLPI message we support or were expecting */
15174 		freemsg(mp);
15175 		return;
15176 	}
15177 
15178 	if (!pending) {
15179 		freemsg(mp);
15180 		return;
15181 	}
15182 
15183 	switch (dloa->dl_primitive) {
15184 	case DL_ERROR_ACK:
15185 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15186 			mutex_enter(&ill->ill_lock);
15187 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15188 			cv_signal(&ill->ill_cv);
15189 			mutex_exit(&ill->ill_lock);
15190 		}
15191 		break;
15192 
15193 	case DL_OK_ACK:
15194 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15195 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15196 		switch (dloa->dl_correct_primitive) {
15197 		case DL_UNBIND_REQ:
15198 			mutex_enter(&ill->ill_lock);
15199 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15200 			cv_signal(&ill->ill_cv);
15201 			mutex_exit(&ill->ill_lock);
15202 			break;
15203 
15204 		case DL_ENABMULTI_REQ:
15205 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15206 				ill->ill_dlpi_multicast_state = IDS_OK;
15207 			break;
15208 		}
15209 		break;
15210 	default:
15211 		break;
15212 	}
15213 
15214 	/*
15215 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15216 	 * and we need to become writer to continue to process it. If it's not
15217 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15218 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15219 	 * some work as part of the current exclusive operation that actually
15220 	 * is not part of it -- which is wrong, but better than the
15221 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15222 	 * should track which DLPI requests have ACKs that we wait on
15223 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15224 	 *
15225 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15226 	 * Since this is on the ill stream we unconditionally bump up the
15227 	 * refcount without doing ILL_CAN_LOOKUP().
15228 	 */
15229 	ill_refhold(ill);
15230 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15231 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15232 	else
15233 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15234 }
15235 
15236 /*
15237  * Handling of DLPI messages that require exclusive access to the ipsq.
15238  *
15239  * Need to do ill_pending_mp_release on ioctl completion, which could
15240  * happen here. (along with mi_copy_done)
15241  */
15242 /* ARGSUSED */
15243 static void
15244 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15245 {
15246 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15247 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15248 	int		err = 0;
15249 	ill_t		*ill;
15250 	ipif_t		*ipif = NULL;
15251 	mblk_t		*mp1 = NULL;
15252 	conn_t		*connp = NULL;
15253 	t_uscalar_t	paddrreq;
15254 	mblk_t		*mp_hw;
15255 	boolean_t	success;
15256 	boolean_t	ioctl_aborted = B_FALSE;
15257 	boolean_t	log = B_TRUE;
15258 	hook_nic_event_t	*info;
15259 	ip_stack_t		*ipst;
15260 
15261 	ip1dbg(("ip_rput_dlpi_writer .."));
15262 	ill = (ill_t *)q->q_ptr;
15263 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15264 
15265 	ASSERT(IAM_WRITER_ILL(ill));
15266 
15267 	ipst = ill->ill_ipst;
15268 
15269 	/*
15270 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15271 	 * both are null or non-null. However we can assert that only
15272 	 * after grabbing the ipsq_lock. So we don't make any assertion
15273 	 * here and in other places in the code.
15274 	 */
15275 	ipif = ipsq->ipsq_pending_ipif;
15276 	/*
15277 	 * The current ioctl could have been aborted by the user and a new
15278 	 * ioctl to bring up another ill could have started. We could still
15279 	 * get a response from the driver later.
15280 	 */
15281 	if (ipif != NULL && ipif->ipif_ill != ill)
15282 		ioctl_aborted = B_TRUE;
15283 
15284 	switch (dloa->dl_primitive) {
15285 	case DL_ERROR_ACK:
15286 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15287 		    dlpi_prim_str(dlea->dl_error_primitive)));
15288 
15289 		switch (dlea->dl_error_primitive) {
15290 		case DL_PROMISCON_REQ:
15291 		case DL_PROMISCOFF_REQ:
15292 		case DL_DISABMULTI_REQ:
15293 		case DL_UNBIND_REQ:
15294 		case DL_ATTACH_REQ:
15295 		case DL_INFO_REQ:
15296 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15297 			break;
15298 		case DL_NOTIFY_REQ:
15299 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15300 			log = B_FALSE;
15301 			break;
15302 		case DL_PHYS_ADDR_REQ:
15303 			/*
15304 			 * For IPv6 only, there are two additional
15305 			 * phys_addr_req's sent to the driver to get the
15306 			 * IPv6 token and lla. This allows IP to acquire
15307 			 * the hardware address format for a given interface
15308 			 * without having built in knowledge of the hardware
15309 			 * address. ill_phys_addr_pend keeps track of the last
15310 			 * DL_PAR sent so we know which response we are
15311 			 * dealing with. ill_dlpi_done will update
15312 			 * ill_phys_addr_pend when it sends the next req.
15313 			 * We don't complete the IOCTL until all three DL_PARs
15314 			 * have been attempted, so set *_len to 0 and break.
15315 			 */
15316 			paddrreq = ill->ill_phys_addr_pend;
15317 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15318 			if (paddrreq == DL_IPV6_TOKEN) {
15319 				ill->ill_token_length = 0;
15320 				log = B_FALSE;
15321 				break;
15322 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15323 				ill->ill_nd_lla_len = 0;
15324 				log = B_FALSE;
15325 				break;
15326 			}
15327 			/*
15328 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15329 			 * We presumably have an IOCTL hanging out waiting
15330 			 * for completion. Find it and complete the IOCTL
15331 			 * with the error noted.
15332 			 * However, ill_dl_phys was called on an ill queue
15333 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15334 			 * set. But the ioctl is known to be pending on ill_wq.
15335 			 */
15336 			if (!ill->ill_ifname_pending)
15337 				break;
15338 			ill->ill_ifname_pending = 0;
15339 			if (!ioctl_aborted)
15340 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15341 			if (mp1 != NULL) {
15342 				/*
15343 				 * This operation (SIOCSLIFNAME) must have
15344 				 * happened on the ill. Assert there is no conn
15345 				 */
15346 				ASSERT(connp == NULL);
15347 				q = ill->ill_wq;
15348 			}
15349 			break;
15350 		case DL_BIND_REQ:
15351 			ill_dlpi_done(ill, DL_BIND_REQ);
15352 			if (ill->ill_ifname_pending)
15353 				break;
15354 			/*
15355 			 * Something went wrong with the bind.  We presumably
15356 			 * have an IOCTL hanging out waiting for completion.
15357 			 * Find it, take down the interface that was coming
15358 			 * up, and complete the IOCTL with the error noted.
15359 			 */
15360 			if (!ioctl_aborted)
15361 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15362 			if (mp1 != NULL) {
15363 				/*
15364 				 * This operation (SIOCSLIFFLAGS) must have
15365 				 * happened from a conn.
15366 				 */
15367 				ASSERT(connp != NULL);
15368 				q = CONNP_TO_WQ(connp);
15369 				if (ill->ill_move_in_progress) {
15370 					ILL_CLEAR_MOVE(ill);
15371 				}
15372 				(void) ipif_down(ipif, NULL, NULL);
15373 				/* error is set below the switch */
15374 			}
15375 			break;
15376 		case DL_ENABMULTI_REQ:
15377 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15378 
15379 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15380 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15381 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15382 				ipif_t *ipif;
15383 
15384 				printf("ip: joining multicasts failed (%d)"
15385 				    " on %s - will use link layer "
15386 				    "broadcasts for multicast\n",
15387 				    dlea->dl_errno, ill->ill_name);
15388 
15389 				/*
15390 				 * Set up the multicast mapping alone.
15391 				 * writer, so ok to access ill->ill_ipif
15392 				 * without any lock.
15393 				 */
15394 				ipif = ill->ill_ipif;
15395 				mutex_enter(&ill->ill_phyint->phyint_lock);
15396 				ill->ill_phyint->phyint_flags |=
15397 				    PHYI_MULTI_BCAST;
15398 				mutex_exit(&ill->ill_phyint->phyint_lock);
15399 
15400 				if (!ill->ill_isv6) {
15401 					(void) ipif_arp_setup_multicast(ipif,
15402 					    NULL);
15403 				} else {
15404 					(void) ipif_ndp_setup_multicast(ipif,
15405 					    NULL);
15406 				}
15407 			}
15408 			freemsg(mp);	/* Don't want to pass this up */
15409 			return;
15410 
15411 		case DL_CAPABILITY_REQ:
15412 		case DL_CONTROL_REQ:
15413 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15414 			ill->ill_dlpi_capab_state = IDS_FAILED;
15415 			freemsg(mp);
15416 			return;
15417 		}
15418 		/*
15419 		 * Note the error for IOCTL completion (mp1 is set when
15420 		 * ready to complete ioctl). If ill_ifname_pending_err is
15421 		 * set, an error occured during plumbing (ill_ifname_pending),
15422 		 * so we want to report that error.
15423 		 *
15424 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15425 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15426 		 * expected to get errack'd if the driver doesn't support
15427 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15428 		 * if these error conditions are encountered.
15429 		 */
15430 		if (mp1 != NULL) {
15431 			if (ill->ill_ifname_pending_err != 0)  {
15432 				err = ill->ill_ifname_pending_err;
15433 				ill->ill_ifname_pending_err = 0;
15434 			} else {
15435 				err = dlea->dl_unix_errno ?
15436 				    dlea->dl_unix_errno : ENXIO;
15437 			}
15438 		/*
15439 		 * If we're plumbing an interface and an error hasn't already
15440 		 * been saved, set ill_ifname_pending_err to the error passed
15441 		 * up. Ignore the error if log is B_FALSE (see comment above).
15442 		 */
15443 		} else if (log && ill->ill_ifname_pending &&
15444 		    ill->ill_ifname_pending_err == 0) {
15445 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15446 			    dlea->dl_unix_errno : ENXIO;
15447 		}
15448 
15449 		if (log)
15450 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15451 			    dlea->dl_errno, dlea->dl_unix_errno);
15452 		break;
15453 	case DL_CAPABILITY_ACK: {
15454 		boolean_t reneg_flag = B_FALSE;
15455 		/* Call a routine to handle this one. */
15456 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15457 		/*
15458 		 * Check if the ACK is due to renegotiation case since we
15459 		 * will need to send a new CAPABILITY_REQ later.
15460 		 */
15461 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15462 			/* This is the ack for a renogiation case */
15463 			reneg_flag = B_TRUE;
15464 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15465 		}
15466 		ill_capability_ack(ill, mp);
15467 		if (reneg_flag)
15468 			ill_capability_probe(ill);
15469 		break;
15470 	}
15471 	case DL_CONTROL_ACK:
15472 		/* We treat all of these as "fire and forget" */
15473 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15474 		break;
15475 	case DL_INFO_ACK:
15476 		/* Call a routine to handle this one. */
15477 		ill_dlpi_done(ill, DL_INFO_REQ);
15478 		ip_ll_subnet_defaults(ill, mp);
15479 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15480 		return;
15481 	case DL_BIND_ACK:
15482 		/*
15483 		 * We should have an IOCTL waiting on this unless
15484 		 * sent by ill_dl_phys, in which case just return
15485 		 */
15486 		ill_dlpi_done(ill, DL_BIND_REQ);
15487 		if (ill->ill_ifname_pending)
15488 			break;
15489 
15490 		if (!ioctl_aborted)
15491 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15492 		if (mp1 == NULL)
15493 			break;
15494 		/*
15495 		 * Because mp1 was added by ill_dl_up(), and it always
15496 		 * passes a valid connp, connp must be valid here.
15497 		 */
15498 		ASSERT(connp != NULL);
15499 		q = CONNP_TO_WQ(connp);
15500 
15501 		/*
15502 		 * We are exclusive. So nothing can change even after
15503 		 * we get the pending mp. If need be we can put it back
15504 		 * and restart, as in calling ipif_arp_up()  below.
15505 		 */
15506 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15507 
15508 		mutex_enter(&ill->ill_lock);
15509 
15510 		ill->ill_dl_up = 1;
15511 
15512 		if ((info = ill->ill_nic_event_info) != NULL) {
15513 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15514 			    "attached for %s\n", info->hne_event,
15515 			    ill->ill_name));
15516 			if (info->hne_data != NULL)
15517 				kmem_free(info->hne_data, info->hne_datalen);
15518 			kmem_free(info, sizeof (hook_nic_event_t));
15519 		}
15520 
15521 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15522 		if (info != NULL) {
15523 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15524 			info->hne_lif = 0;
15525 			info->hne_event = NE_UP;
15526 			info->hne_data = NULL;
15527 			info->hne_datalen = 0;
15528 			info->hne_family = ill->ill_isv6 ?
15529 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15530 		} else
15531 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15532 			    "event information for %s (ENOMEM)\n",
15533 			    ill->ill_name));
15534 
15535 		ill->ill_nic_event_info = info;
15536 
15537 		mutex_exit(&ill->ill_lock);
15538 
15539 		/*
15540 		 * Now bring up the resolver; when that is complete, we'll
15541 		 * create IREs.  Note that we intentionally mirror what
15542 		 * ipif_up() would have done, because we got here by way of
15543 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15544 		 */
15545 		if (ill->ill_isv6) {
15546 			/*
15547 			 * v6 interfaces.
15548 			 * Unlike ARP which has to do another bind
15549 			 * and attach, once we get here we are
15550 			 * done with NDP. Except in the case of
15551 			 * ILLF_XRESOLV, in which case we send an
15552 			 * AR_INTERFACE_UP to the external resolver.
15553 			 * If all goes well, the ioctl will complete
15554 			 * in ip_rput(). If there's an error, we
15555 			 * complete it here.
15556 			 */
15557 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
15558 			if (err == 0) {
15559 				if (ill->ill_flags & ILLF_XRESOLV) {
15560 					mutex_enter(&connp->conn_lock);
15561 					mutex_enter(&ill->ill_lock);
15562 					success = ipsq_pending_mp_add(
15563 					    connp, ipif, q, mp1, 0);
15564 					mutex_exit(&ill->ill_lock);
15565 					mutex_exit(&connp->conn_lock);
15566 					if (success) {
15567 						err = ipif_resolver_up(ipif,
15568 						    Res_act_initial);
15569 						if (err == EINPROGRESS) {
15570 							freemsg(mp);
15571 							return;
15572 						}
15573 						ASSERT(err != 0);
15574 						mp1 = ipsq_pending_mp_get(ipsq,
15575 						    &connp);
15576 						ASSERT(mp1 != NULL);
15577 					} else {
15578 						/* conn has started closing */
15579 						err = EINTR;
15580 					}
15581 				} else { /* Non XRESOLV interface */
15582 					(void) ipif_resolver_up(ipif,
15583 					    Res_act_initial);
15584 					err = ipif_up_done_v6(ipif);
15585 				}
15586 			}
15587 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15588 			/*
15589 			 * ARP and other v4 external resolvers.
15590 			 * Leave the pending mblk intact so that
15591 			 * the ioctl completes in ip_rput().
15592 			 */
15593 			mutex_enter(&connp->conn_lock);
15594 			mutex_enter(&ill->ill_lock);
15595 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15596 			mutex_exit(&ill->ill_lock);
15597 			mutex_exit(&connp->conn_lock);
15598 			if (success) {
15599 				err = ipif_resolver_up(ipif, Res_act_initial);
15600 				if (err == EINPROGRESS) {
15601 					freemsg(mp);
15602 					return;
15603 				}
15604 				ASSERT(err != 0);
15605 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15606 			} else {
15607 				/* The conn has started closing */
15608 				err = EINTR;
15609 			}
15610 		} else {
15611 			/*
15612 			 * This one is complete. Reply to pending ioctl.
15613 			 */
15614 			(void) ipif_resolver_up(ipif, Res_act_initial);
15615 			err = ipif_up_done(ipif);
15616 		}
15617 
15618 		if ((err == 0) && (ill->ill_up_ipifs)) {
15619 			err = ill_up_ipifs(ill, q, mp1);
15620 			if (err == EINPROGRESS) {
15621 				freemsg(mp);
15622 				return;
15623 			}
15624 		}
15625 
15626 		if (ill->ill_up_ipifs) {
15627 			ill_group_cleanup(ill);
15628 		}
15629 
15630 		break;
15631 	case DL_NOTIFY_IND: {
15632 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15633 		ire_t *ire;
15634 		boolean_t need_ire_walk_v4 = B_FALSE;
15635 		boolean_t need_ire_walk_v6 = B_FALSE;
15636 
15637 		switch (notify->dl_notification) {
15638 		case DL_NOTE_PHYS_ADDR:
15639 			err = ill_set_phys_addr(ill, mp);
15640 			break;
15641 
15642 		case DL_NOTE_FASTPATH_FLUSH:
15643 			ill_fastpath_flush(ill);
15644 			break;
15645 
15646 		case DL_NOTE_SDU_SIZE:
15647 			/*
15648 			 * Change the MTU size of the interface, of all
15649 			 * attached ipif's, and of all relevant ire's.  The
15650 			 * new value's a uint32_t at notify->dl_data.
15651 			 * Mtu change Vs. new ire creation - protocol below.
15652 			 *
15653 			 * a Mark the ipif as IPIF_CHANGING.
15654 			 * b Set the new mtu in the ipif.
15655 			 * c Change the ire_max_frag on all affected ires
15656 			 * d Unmark the IPIF_CHANGING
15657 			 *
15658 			 * To see how the protocol works, assume an interface
15659 			 * route is also being added simultaneously by
15660 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15661 			 * the ire. If the ire is created before step a,
15662 			 * it will be cleaned up by step c. If the ire is
15663 			 * created after step d, it will see the new value of
15664 			 * ipif_mtu. Any attempt to create the ire between
15665 			 * steps a to d will fail because of the IPIF_CHANGING
15666 			 * flag. Note that ire_create() is passed a pointer to
15667 			 * the ipif_mtu, and not the value. During ire_add
15668 			 * under the bucket lock, the ire_max_frag of the
15669 			 * new ire being created is set from the ipif/ire from
15670 			 * which it is being derived.
15671 			 */
15672 			mutex_enter(&ill->ill_lock);
15673 			ill->ill_max_frag = (uint_t)notify->dl_data;
15674 
15675 			/*
15676 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15677 			 * leave it alone
15678 			 */
15679 			if (ill->ill_mtu_userspecified) {
15680 				mutex_exit(&ill->ill_lock);
15681 				break;
15682 			}
15683 			ill->ill_max_mtu = ill->ill_max_frag;
15684 			if (ill->ill_isv6) {
15685 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15686 					ill->ill_max_mtu = IPV6_MIN_MTU;
15687 			} else {
15688 				if (ill->ill_max_mtu < IP_MIN_MTU)
15689 					ill->ill_max_mtu = IP_MIN_MTU;
15690 			}
15691 			for (ipif = ill->ill_ipif; ipif != NULL;
15692 			    ipif = ipif->ipif_next) {
15693 				/*
15694 				 * Don't override the mtu if the user
15695 				 * has explicitly set it.
15696 				 */
15697 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15698 					continue;
15699 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15700 				if (ipif->ipif_isv6)
15701 					ire = ipif_to_ire_v6(ipif);
15702 				else
15703 					ire = ipif_to_ire(ipif);
15704 				if (ire != NULL) {
15705 					ire->ire_max_frag = ipif->ipif_mtu;
15706 					ire_refrele(ire);
15707 				}
15708 				if (ipif->ipif_flags & IPIF_UP) {
15709 					if (ill->ill_isv6)
15710 						need_ire_walk_v6 = B_TRUE;
15711 					else
15712 						need_ire_walk_v4 = B_TRUE;
15713 				}
15714 			}
15715 			mutex_exit(&ill->ill_lock);
15716 			if (need_ire_walk_v4)
15717 				ire_walk_v4(ill_mtu_change, (char *)ill,
15718 				    ALL_ZONES, ipst);
15719 			if (need_ire_walk_v6)
15720 				ire_walk_v6(ill_mtu_change, (char *)ill,
15721 				    ALL_ZONES, ipst);
15722 			break;
15723 		case DL_NOTE_LINK_UP:
15724 		case DL_NOTE_LINK_DOWN: {
15725 			/*
15726 			 * We are writer. ill / phyint / ipsq assocs stable.
15727 			 * The RUNNING flag reflects the state of the link.
15728 			 */
15729 			phyint_t *phyint = ill->ill_phyint;
15730 			uint64_t new_phyint_flags;
15731 			boolean_t changed = B_FALSE;
15732 			boolean_t went_up;
15733 
15734 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15735 			mutex_enter(&phyint->phyint_lock);
15736 			new_phyint_flags = went_up ?
15737 			    phyint->phyint_flags | PHYI_RUNNING :
15738 			    phyint->phyint_flags & ~PHYI_RUNNING;
15739 			if (new_phyint_flags != phyint->phyint_flags) {
15740 				phyint->phyint_flags = new_phyint_flags;
15741 				changed = B_TRUE;
15742 			}
15743 			mutex_exit(&phyint->phyint_lock);
15744 			/*
15745 			 * ill_restart_dad handles the DAD restart and routing
15746 			 * socket notification logic.
15747 			 */
15748 			if (changed) {
15749 				ill_restart_dad(phyint->phyint_illv4, went_up);
15750 				ill_restart_dad(phyint->phyint_illv6, went_up);
15751 			}
15752 			break;
15753 		}
15754 		case DL_NOTE_PROMISC_ON_PHYS:
15755 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15756 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15757 			mutex_enter(&ill->ill_lock);
15758 			ill->ill_promisc_on_phys = B_TRUE;
15759 			mutex_exit(&ill->ill_lock);
15760 			break;
15761 		case DL_NOTE_PROMISC_OFF_PHYS:
15762 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15763 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15764 			mutex_enter(&ill->ill_lock);
15765 			ill->ill_promisc_on_phys = B_FALSE;
15766 			mutex_exit(&ill->ill_lock);
15767 			break;
15768 		case DL_NOTE_CAPAB_RENEG:
15769 			/*
15770 			 * Something changed on the driver side.
15771 			 * It wants us to renegotiate the capabilities
15772 			 * on this ill. The most likely cause is the
15773 			 * aggregation interface under us where a
15774 			 * port got added or went away.
15775 			 *
15776 			 * We reset the capabilities and set the
15777 			 * state to IDS_RENG so that when the ack
15778 			 * comes back, we can start the
15779 			 * renegotiation process.
15780 			 */
15781 			ill_capability_reset(ill);
15782 			ill->ill_dlpi_capab_state = IDS_RENEG;
15783 			break;
15784 		default:
15785 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15786 			    "type 0x%x for DL_NOTIFY_IND\n",
15787 			    notify->dl_notification));
15788 			break;
15789 		}
15790 
15791 		/*
15792 		 * As this is an asynchronous operation, we
15793 		 * should not call ill_dlpi_done
15794 		 */
15795 		break;
15796 	}
15797 	case DL_NOTIFY_ACK: {
15798 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15799 
15800 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15801 			ill->ill_note_link = 1;
15802 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15803 		break;
15804 	}
15805 	case DL_PHYS_ADDR_ACK: {
15806 		/*
15807 		 * As part of plumbing the interface via SIOCSLIFNAME,
15808 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
15809 		 * whose answers we receive here.  As each answer is received,
15810 		 * we call ill_dlpi_done() to dispatch the next request as
15811 		 * we're processing the current one.  Once all answers have
15812 		 * been received, we use ipsq_pending_mp_get() to dequeue the
15813 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
15814 		 * is invoked from an ill queue, conn_oper_pending_ill is not
15815 		 * available, but we know the ioctl is pending on ill_wq.)
15816 		 */
15817 		uint_t paddrlen, paddroff;
15818 
15819 		paddrreq = ill->ill_phys_addr_pend;
15820 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
15821 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
15822 
15823 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15824 		if (paddrreq == DL_IPV6_TOKEN) {
15825 			/*
15826 			 * bcopy to low-order bits of ill_token
15827 			 *
15828 			 * XXX Temporary hack - currently, all known tokens
15829 			 * are 64 bits, so I'll cheat for the moment.
15830 			 */
15831 			bcopy(mp->b_rptr + paddroff,
15832 			    &ill->ill_token.s6_addr32[2], paddrlen);
15833 			ill->ill_token_length = paddrlen;
15834 			break;
15835 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15836 			ASSERT(ill->ill_nd_lla_mp == NULL);
15837 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
15838 			mp = NULL;
15839 			break;
15840 		}
15841 
15842 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
15843 		ASSERT(ill->ill_phys_addr_mp == NULL);
15844 		if (!ill->ill_ifname_pending)
15845 			break;
15846 		ill->ill_ifname_pending = 0;
15847 		if (!ioctl_aborted)
15848 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15849 		if (mp1 != NULL) {
15850 			ASSERT(connp == NULL);
15851 			q = ill->ill_wq;
15852 		}
15853 		/*
15854 		 * If any error acks received during the plumbing sequence,
15855 		 * ill_ifname_pending_err will be set. Break out and send up
15856 		 * the error to the pending ioctl.
15857 		 */
15858 		if (ill->ill_ifname_pending_err != 0) {
15859 			err = ill->ill_ifname_pending_err;
15860 			ill->ill_ifname_pending_err = 0;
15861 			break;
15862 		}
15863 
15864 		ill->ill_phys_addr_mp = mp;
15865 		ill->ill_phys_addr = mp->b_rptr + paddroff;
15866 		mp = NULL;
15867 
15868 		/*
15869 		 * If paddrlen is zero, the DLPI provider doesn't support
15870 		 * physical addresses.  The other two tests were historical
15871 		 * workarounds for bugs in our former PPP implementation, but
15872 		 * now other things have grown dependencies on them -- e.g.,
15873 		 * the tun module specifies a dl_addr_length of zero in its
15874 		 * DL_BIND_ACK, but then specifies an incorrect value in its
15875 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
15876 		 * but only after careful testing ensures that all dependent
15877 		 * broken DLPI providers have been fixed.
15878 		 */
15879 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
15880 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15881 			ill->ill_phys_addr = NULL;
15882 		} else if (paddrlen != ill->ill_phys_addr_length) {
15883 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
15884 			    paddrlen, ill->ill_phys_addr_length));
15885 			err = EINVAL;
15886 			break;
15887 		}
15888 
15889 		if (ill->ill_nd_lla_mp == NULL) {
15890 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
15891 				err = ENOMEM;
15892 				break;
15893 			}
15894 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
15895 		}
15896 
15897 		/*
15898 		 * Set the interface token.  If the zeroth interface address
15899 		 * is unspecified, then set it to the link local address.
15900 		 */
15901 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15902 			(void) ill_setdefaulttoken(ill);
15903 
15904 		ASSERT(ill->ill_ipif->ipif_id == 0);
15905 		if (ipif != NULL &&
15906 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
15907 			(void) ipif_setlinklocal(ipif);
15908 		}
15909 		break;
15910 	}
15911 	case DL_OK_ACK:
15912 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15913 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15914 		    dloa->dl_correct_primitive));
15915 		switch (dloa->dl_correct_primitive) {
15916 		case DL_PROMISCON_REQ:
15917 		case DL_PROMISCOFF_REQ:
15918 		case DL_ENABMULTI_REQ:
15919 		case DL_DISABMULTI_REQ:
15920 		case DL_UNBIND_REQ:
15921 		case DL_ATTACH_REQ:
15922 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15923 			break;
15924 		}
15925 		break;
15926 	default:
15927 		break;
15928 	}
15929 
15930 	freemsg(mp);
15931 	if (mp1 != NULL) {
15932 		/*
15933 		 * The operation must complete without EINPROGRESS
15934 		 * since ipsq_pending_mp_get() has removed the mblk
15935 		 * from ipsq_pending_mp.  Otherwise, the operation
15936 		 * will be stuck forever in the ipsq.
15937 		 */
15938 		ASSERT(err != EINPROGRESS);
15939 
15940 		switch (ipsq->ipsq_current_ioctl) {
15941 		case 0:
15942 			ipsq_current_finish(ipsq);
15943 			break;
15944 
15945 		case SIOCLIFADDIF:
15946 		case SIOCSLIFNAME:
15947 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
15948 			break;
15949 
15950 		default:
15951 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
15952 			break;
15953 		}
15954 	}
15955 }
15956 
15957 /*
15958  * ip_rput_other is called by ip_rput to handle messages modifying the global
15959  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15960  */
15961 /* ARGSUSED */
15962 void
15963 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15964 {
15965 	ill_t		*ill;
15966 	struct iocblk	*iocp;
15967 	mblk_t		*mp1;
15968 	conn_t		*connp = NULL;
15969 
15970 	ip1dbg(("ip_rput_other "));
15971 	ill = (ill_t *)q->q_ptr;
15972 	/*
15973 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15974 	 * in which case ipsq is NULL.
15975 	 */
15976 	if (ipsq != NULL) {
15977 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15978 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15979 	}
15980 
15981 	switch (mp->b_datap->db_type) {
15982 	case M_ERROR:
15983 	case M_HANGUP:
15984 		/*
15985 		 * The device has a problem.  We force the ILL down.  It can
15986 		 * be brought up again manually using SIOCSIFFLAGS (via
15987 		 * ifconfig or equivalent).
15988 		 */
15989 		ASSERT(ipsq != NULL);
15990 		if (mp->b_rptr < mp->b_wptr)
15991 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15992 		if (ill->ill_error == 0)
15993 			ill->ill_error = ENXIO;
15994 		if (!ill_down_start(q, mp))
15995 			return;
15996 		ipif_all_down_tail(ipsq, q, mp, NULL);
15997 		break;
15998 	case M_IOCACK:
15999 		iocp = (struct iocblk *)mp->b_rptr;
16000 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16001 		switch (iocp->ioc_cmd) {
16002 		case SIOCSTUNPARAM:
16003 		case OSIOCSTUNPARAM:
16004 			ASSERT(ipsq != NULL);
16005 			/*
16006 			 * Finish socket ioctl passed through to tun.
16007 			 * We should have an IOCTL waiting on this.
16008 			 */
16009 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16010 			if (ill->ill_isv6) {
16011 				struct iftun_req *ta;
16012 
16013 				/*
16014 				 * if a source or destination is
16015 				 * being set, try and set the link
16016 				 * local address for the tunnel
16017 				 */
16018 				ta = (struct iftun_req *)mp->b_cont->
16019 				    b_cont->b_rptr;
16020 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16021 					ipif_set_tun_llink(ill, ta);
16022 				}
16023 
16024 			}
16025 			if (mp1 != NULL) {
16026 				/*
16027 				 * Now copy back the b_next/b_prev used by
16028 				 * mi code for the mi_copy* functions.
16029 				 * See ip_sioctl_tunparam() for the reason.
16030 				 * Also protect against missing b_cont.
16031 				 */
16032 				if (mp->b_cont != NULL) {
16033 					mp->b_cont->b_next =
16034 					    mp1->b_cont->b_next;
16035 					mp->b_cont->b_prev =
16036 					    mp1->b_cont->b_prev;
16037 				}
16038 				inet_freemsg(mp1);
16039 				ASSERT(connp != NULL);
16040 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16041 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16042 			} else {
16043 				ASSERT(connp == NULL);
16044 				putnext(q, mp);
16045 			}
16046 			break;
16047 		case SIOCGTUNPARAM:
16048 		case OSIOCGTUNPARAM:
16049 			/*
16050 			 * This is really M_IOCDATA from the tunnel driver.
16051 			 * convert back and complete the ioctl.
16052 			 * We should have an IOCTL waiting on this.
16053 			 */
16054 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16055 			if (mp1) {
16056 				/*
16057 				 * Now copy back the b_next/b_prev used by
16058 				 * mi code for the mi_copy* functions.
16059 				 * See ip_sioctl_tunparam() for the reason.
16060 				 * Also protect against missing b_cont.
16061 				 */
16062 				if (mp->b_cont != NULL) {
16063 					mp->b_cont->b_next =
16064 					    mp1->b_cont->b_next;
16065 					mp->b_cont->b_prev =
16066 					    mp1->b_cont->b_prev;
16067 				}
16068 				inet_freemsg(mp1);
16069 				if (iocp->ioc_error == 0)
16070 					mp->b_datap->db_type = M_IOCDATA;
16071 				ASSERT(connp != NULL);
16072 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16073 				    iocp->ioc_error, COPYOUT, NULL);
16074 			} else {
16075 				ASSERT(connp == NULL);
16076 				putnext(q, mp);
16077 			}
16078 			break;
16079 		default:
16080 			break;
16081 		}
16082 		break;
16083 	case M_IOCNAK:
16084 		iocp = (struct iocblk *)mp->b_rptr;
16085 
16086 		switch (iocp->ioc_cmd) {
16087 		int mode;
16088 
16089 		case DL_IOC_HDR_INFO:
16090 			/*
16091 			 * If this was the first attempt turn of the
16092 			 * fastpath probing.
16093 			 */
16094 			mutex_enter(&ill->ill_lock);
16095 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16096 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16097 				mutex_exit(&ill->ill_lock);
16098 				ill_fastpath_nack(ill);
16099 				ip1dbg(("ip_rput: DLPI fastpath off on "
16100 				    "interface %s\n",
16101 				    ill->ill_name));
16102 			} else {
16103 				mutex_exit(&ill->ill_lock);
16104 			}
16105 			freemsg(mp);
16106 			break;
16107 		case SIOCSTUNPARAM:
16108 		case OSIOCSTUNPARAM:
16109 			ASSERT(ipsq != NULL);
16110 			/*
16111 			 * Finish socket ioctl passed through to tun
16112 			 * We should have an IOCTL waiting on this.
16113 			 */
16114 			/* FALLTHRU */
16115 		case SIOCGTUNPARAM:
16116 		case OSIOCGTUNPARAM:
16117 			/*
16118 			 * This is really M_IOCDATA from the tunnel driver.
16119 			 * convert back and complete the ioctl.
16120 			 * We should have an IOCTL waiting on this.
16121 			 */
16122 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16123 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16124 				mp1 = ill_pending_mp_get(ill, &connp,
16125 				    iocp->ioc_id);
16126 				mode = COPYOUT;
16127 				ipsq = NULL;
16128 			} else {
16129 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16130 				mode = NO_COPYOUT;
16131 			}
16132 			if (mp1 != NULL) {
16133 				/*
16134 				 * Now copy back the b_next/b_prev used by
16135 				 * mi code for the mi_copy* functions.
16136 				 * See ip_sioctl_tunparam() for the reason.
16137 				 * Also protect against missing b_cont.
16138 				 */
16139 				if (mp->b_cont != NULL) {
16140 					mp->b_cont->b_next =
16141 					    mp1->b_cont->b_next;
16142 					mp->b_cont->b_prev =
16143 					    mp1->b_cont->b_prev;
16144 				}
16145 				inet_freemsg(mp1);
16146 				if (iocp->ioc_error == 0)
16147 					iocp->ioc_error = EINVAL;
16148 				ASSERT(connp != NULL);
16149 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16150 				    iocp->ioc_error, mode, ipsq);
16151 			} else {
16152 				ASSERT(connp == NULL);
16153 				putnext(q, mp);
16154 			}
16155 			break;
16156 		default:
16157 			break;
16158 		}
16159 	default:
16160 		break;
16161 	}
16162 }
16163 
16164 /*
16165  * NOTE : This function does not ire_refrele the ire argument passed in.
16166  *
16167  * IPQoS notes
16168  * IP policy is invoked twice for a forwarded packet, once on the read side
16169  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16170  * enabled. An additional parameter, in_ill, has been added for this purpose.
16171  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16172  * because ip_mroute drops this information.
16173  *
16174  */
16175 void
16176 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16177 {
16178 	uint32_t	old_pkt_len;
16179 	uint32_t	pkt_len;
16180 	queue_t	*q;
16181 	uint32_t	sum;
16182 #define	rptr	((uchar_t *)ipha)
16183 	uint32_t	max_frag;
16184 	uint32_t	ill_index;
16185 	ill_t		*out_ill;
16186 	mib2_ipIfStatsEntry_t *mibptr;
16187 	ip_stack_t	*ipst = in_ill->ill_ipst;
16188 
16189 	/* Get the ill_index of the incoming ILL */
16190 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16191 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16192 
16193 	/* Initiate Read side IPPF processing */
16194 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16195 		ip_process(IPP_FWD_IN, &mp, ill_index);
16196 		if (mp == NULL) {
16197 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16198 			    "during IPPF processing\n"));
16199 			return;
16200 		}
16201 	}
16202 
16203 	/* Adjust the checksum to reflect the ttl decrement. */
16204 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16205 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16206 
16207 	if (ipha->ipha_ttl-- <= 1) {
16208 		if (ip_csum_hdr(ipha)) {
16209 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16210 			goto drop_pkt;
16211 		}
16212 		/*
16213 		 * Note: ire_stq this will be NULL for multicast
16214 		 * datagrams using the long path through arp (the IRE
16215 		 * is not an IRE_CACHE). This should not cause
16216 		 * problems since we don't generate ICMP errors for
16217 		 * multicast packets.
16218 		 */
16219 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16220 		q = ire->ire_stq;
16221 		if (q != NULL) {
16222 			/* Sent by forwarding path, and router is global zone */
16223 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16224 			    GLOBAL_ZONEID, ipst);
16225 		} else
16226 			freemsg(mp);
16227 		return;
16228 	}
16229 
16230 	/*
16231 	 * Don't forward if the interface is down
16232 	 */
16233 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16234 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16235 		ip2dbg(("ip_rput_forward:interface is down\n"));
16236 		goto drop_pkt;
16237 	}
16238 
16239 	/* Get the ill_index of the outgoing ILL */
16240 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16241 
16242 	out_ill = ire->ire_ipif->ipif_ill;
16243 
16244 	DTRACE_PROBE4(ip4__forwarding__start,
16245 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16246 
16247 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16248 	    ipst->ips_ipv4firewall_forwarding,
16249 	    in_ill, out_ill, ipha, mp, mp, ipst);
16250 
16251 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16252 
16253 	if (mp == NULL)
16254 		return;
16255 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16256 
16257 	if (is_system_labeled()) {
16258 		mblk_t *mp1;
16259 
16260 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16261 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16262 			goto drop_pkt;
16263 		}
16264 		/* Size may have changed */
16265 		mp = mp1;
16266 		ipha = (ipha_t *)mp->b_rptr;
16267 		pkt_len = ntohs(ipha->ipha_length);
16268 	}
16269 
16270 	/* Check if there are options to update */
16271 	if (!IS_SIMPLE_IPH(ipha)) {
16272 		if (ip_csum_hdr(ipha)) {
16273 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16274 			goto drop_pkt;
16275 		}
16276 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16277 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16278 			return;
16279 		}
16280 
16281 		ipha->ipha_hdr_checksum = 0;
16282 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16283 	}
16284 	max_frag = ire->ire_max_frag;
16285 	if (pkt_len > max_frag) {
16286 		/*
16287 		 * It needs fragging on its way out.  We haven't
16288 		 * verified the header checksum yet.  Since we
16289 		 * are going to put a surely good checksum in the
16290 		 * outgoing header, we have to make sure that it
16291 		 * was good coming in.
16292 		 */
16293 		if (ip_csum_hdr(ipha)) {
16294 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16295 			goto drop_pkt;
16296 		}
16297 		/* Initiate Write side IPPF processing */
16298 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16299 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16300 			if (mp == NULL) {
16301 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16302 				    " during IPPF processing\n"));
16303 				return;
16304 			}
16305 		}
16306 		/*
16307 		 * Handle labeled packet resizing.
16308 		 *
16309 		 * If we have added a label, inform ip_wput_frag() of its
16310 		 * effect on the MTU for ICMP messages.
16311 		 */
16312 		if (pkt_len > old_pkt_len) {
16313 			uint32_t secopt_size;
16314 
16315 			secopt_size = pkt_len - old_pkt_len;
16316 			if (secopt_size < max_frag)
16317 				max_frag -= secopt_size;
16318 		}
16319 
16320 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16321 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16322 		return;
16323 	}
16324 
16325 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16326 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16327 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16328 	    ipst->ips_ipv4firewall_physical_out,
16329 	    NULL, out_ill, ipha, mp, mp, ipst);
16330 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16331 	if (mp == NULL)
16332 		return;
16333 
16334 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16335 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16336 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16337 	/* ip_xmit_v4 always consumes the packet */
16338 	return;
16339 
16340 drop_pkt:;
16341 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16342 	freemsg(mp);
16343 #undef	rptr
16344 }
16345 
16346 void
16347 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16348 {
16349 	ire_t	*ire;
16350 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16351 
16352 	ASSERT(!ipif->ipif_isv6);
16353 	/*
16354 	 * Find an IRE which matches the destination and the outgoing
16355 	 * queue in the cache table. All we need is an IRE_CACHE which
16356 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16357 	 * then it is enough to have some IRE_CACHE in the group.
16358 	 */
16359 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16360 		dst = ipif->ipif_pp_dst_addr;
16361 
16362 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16363 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16364 	if (ire == NULL) {
16365 		/*
16366 		 * Mark this packet to make it be delivered to
16367 		 * ip_rput_forward after the new ire has been
16368 		 * created.
16369 		 */
16370 		mp->b_prev = NULL;
16371 		mp->b_next = mp;
16372 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16373 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16374 	} else {
16375 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16376 		IRE_REFRELE(ire);
16377 	}
16378 }
16379 
16380 /* Update any source route, record route or timestamp options */
16381 static int
16382 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16383 {
16384 	ipoptp_t	opts;
16385 	uchar_t		*opt;
16386 	uint8_t		optval;
16387 	uint8_t		optlen;
16388 	ipaddr_t	dst;
16389 	uint32_t	ts;
16390 	ire_t		*dst_ire = NULL;
16391 	ire_t		*tmp_ire = NULL;
16392 	timestruc_t	now;
16393 
16394 	ip2dbg(("ip_rput_forward_options\n"));
16395 	dst = ipha->ipha_dst;
16396 	for (optval = ipoptp_first(&opts, ipha);
16397 	    optval != IPOPT_EOL;
16398 	    optval = ipoptp_next(&opts)) {
16399 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16400 		opt = opts.ipoptp_cur;
16401 		optlen = opts.ipoptp_len;
16402 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16403 		    optval, opts.ipoptp_len));
16404 		switch (optval) {
16405 			uint32_t off;
16406 		case IPOPT_SSRR:
16407 		case IPOPT_LSRR:
16408 			/* Check if adminstratively disabled */
16409 			if (!ipst->ips_ip_forward_src_routed) {
16410 				if (ire->ire_stq != NULL) {
16411 					/*
16412 					 * Sent by forwarding path, and router
16413 					 * is global zone
16414 					 */
16415 					icmp_unreachable(ire->ire_stq, mp,
16416 					    ICMP_SOURCE_ROUTE_FAILED,
16417 					    GLOBAL_ZONEID, ipst);
16418 				} else {
16419 					ip0dbg(("ip_rput_forward_options: "
16420 					    "unable to send unreach\n"));
16421 					freemsg(mp);
16422 				}
16423 				return (-1);
16424 			}
16425 
16426 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16427 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16428 			if (dst_ire == NULL) {
16429 				/*
16430 				 * Must be partial since ip_rput_options
16431 				 * checked for strict.
16432 				 */
16433 				break;
16434 			}
16435 			off = opt[IPOPT_OFFSET];
16436 			off--;
16437 		redo_srr:
16438 			if (optlen < IP_ADDR_LEN ||
16439 			    off > optlen - IP_ADDR_LEN) {
16440 				/* End of source route */
16441 				ip1dbg((
16442 				    "ip_rput_forward_options: end of SR\n"));
16443 				ire_refrele(dst_ire);
16444 				break;
16445 			}
16446 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16447 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16448 			    IP_ADDR_LEN);
16449 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16450 			    ntohl(dst)));
16451 
16452 			/*
16453 			 * Check if our address is present more than
16454 			 * once as consecutive hops in source route.
16455 			 */
16456 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16457 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16458 			if (tmp_ire != NULL) {
16459 				ire_refrele(tmp_ire);
16460 				off += IP_ADDR_LEN;
16461 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16462 				goto redo_srr;
16463 			}
16464 			ipha->ipha_dst = dst;
16465 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16466 			ire_refrele(dst_ire);
16467 			break;
16468 		case IPOPT_RR:
16469 			off = opt[IPOPT_OFFSET];
16470 			off--;
16471 			if (optlen < IP_ADDR_LEN ||
16472 			    off > optlen - IP_ADDR_LEN) {
16473 				/* No more room - ignore */
16474 				ip1dbg((
16475 				    "ip_rput_forward_options: end of RR\n"));
16476 				break;
16477 			}
16478 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16479 			    IP_ADDR_LEN);
16480 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16481 			break;
16482 		case IPOPT_TS:
16483 			/* Insert timestamp if there is room */
16484 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16485 			case IPOPT_TS_TSONLY:
16486 				off = IPOPT_TS_TIMELEN;
16487 				break;
16488 			case IPOPT_TS_PRESPEC:
16489 			case IPOPT_TS_PRESPEC_RFC791:
16490 				/* Verify that the address matched */
16491 				off = opt[IPOPT_OFFSET] - 1;
16492 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16493 				dst_ire = ire_ctable_lookup(dst, 0,
16494 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16495 				    MATCH_IRE_TYPE, ipst);
16496 				if (dst_ire == NULL) {
16497 					/* Not for us */
16498 					break;
16499 				}
16500 				ire_refrele(dst_ire);
16501 				/* FALLTHRU */
16502 			case IPOPT_TS_TSANDADDR:
16503 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16504 				break;
16505 			default:
16506 				/*
16507 				 * ip_*put_options should have already
16508 				 * dropped this packet.
16509 				 */
16510 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16511 				    "unknown IT - bug in ip_rput_options?\n");
16512 				return (0);	/* Keep "lint" happy */
16513 			}
16514 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16515 				/* Increase overflow counter */
16516 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16517 				opt[IPOPT_POS_OV_FLG] =
16518 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16519 				    (off << 4));
16520 				break;
16521 			}
16522 			off = opt[IPOPT_OFFSET] - 1;
16523 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16524 			case IPOPT_TS_PRESPEC:
16525 			case IPOPT_TS_PRESPEC_RFC791:
16526 			case IPOPT_TS_TSANDADDR:
16527 				bcopy(&ire->ire_src_addr,
16528 				    (char *)opt + off, IP_ADDR_LEN);
16529 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16530 				/* FALLTHRU */
16531 			case IPOPT_TS_TSONLY:
16532 				off = opt[IPOPT_OFFSET] - 1;
16533 				/* Compute # of milliseconds since midnight */
16534 				gethrestime(&now);
16535 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16536 				    now.tv_nsec / (NANOSEC / MILLISEC);
16537 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16538 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16539 				break;
16540 			}
16541 			break;
16542 		}
16543 	}
16544 	return (0);
16545 }
16546 
16547 /*
16548  * This is called after processing at least one of AH/ESP headers.
16549  *
16550  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16551  * the actual, physical interface on which the packet was received,
16552  * but, when ip_strict_dst_multihoming is set to 1, could be the
16553  * interface which had the ipha_dst configured when the packet went
16554  * through ip_rput. The ill_index corresponding to the recv_ill
16555  * is saved in ipsec_in_rill_index
16556  *
16557  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16558  * cannot assume "ire" points to valid data for any IPv6 cases.
16559  */
16560 void
16561 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16562 {
16563 	mblk_t *mp;
16564 	ipaddr_t dst;
16565 	in6_addr_t *v6dstp;
16566 	ipha_t *ipha;
16567 	ip6_t *ip6h;
16568 	ipsec_in_t *ii;
16569 	boolean_t ill_need_rele = B_FALSE;
16570 	boolean_t rill_need_rele = B_FALSE;
16571 	boolean_t ire_need_rele = B_FALSE;
16572 	netstack_t	*ns;
16573 	ip_stack_t	*ipst;
16574 
16575 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16576 	ASSERT(ii->ipsec_in_ill_index != 0);
16577 	ns = ii->ipsec_in_ns;
16578 	ASSERT(ii->ipsec_in_ns != NULL);
16579 	ipst = ns->netstack_ip;
16580 
16581 	mp = ipsec_mp->b_cont;
16582 	ASSERT(mp != NULL);
16583 
16584 
16585 	if (ill == NULL) {
16586 		ASSERT(recv_ill == NULL);
16587 		/*
16588 		 * We need to get the original queue on which ip_rput_local
16589 		 * or ip_rput_data_v6 was called.
16590 		 */
16591 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16592 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16593 		ill_need_rele = B_TRUE;
16594 
16595 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16596 			recv_ill = ill_lookup_on_ifindex(
16597 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16598 			    NULL, NULL, NULL, NULL, ipst);
16599 			rill_need_rele = B_TRUE;
16600 		} else {
16601 			recv_ill = ill;
16602 		}
16603 
16604 		if ((ill == NULL) || (recv_ill == NULL)) {
16605 			ip0dbg(("ip_fanout_proto_again: interface "
16606 			    "disappeared\n"));
16607 			if (ill != NULL)
16608 				ill_refrele(ill);
16609 			if (recv_ill != NULL)
16610 				ill_refrele(recv_ill);
16611 			freemsg(ipsec_mp);
16612 			return;
16613 		}
16614 	}
16615 
16616 	ASSERT(ill != NULL && recv_ill != NULL);
16617 
16618 	if (mp->b_datap->db_type == M_CTL) {
16619 		/*
16620 		 * AH/ESP is returning the ICMP message after
16621 		 * removing their headers. Fanout again till
16622 		 * it gets to the right protocol.
16623 		 */
16624 		if (ii->ipsec_in_v4) {
16625 			icmph_t *icmph;
16626 			int iph_hdr_length;
16627 			int hdr_length;
16628 
16629 			ipha = (ipha_t *)mp->b_rptr;
16630 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16631 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16632 			ipha = (ipha_t *)&icmph[1];
16633 			hdr_length = IPH_HDR_LENGTH(ipha);
16634 			/*
16635 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16636 			 * Reset the type to M_DATA.
16637 			 */
16638 			mp->b_datap->db_type = M_DATA;
16639 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16640 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16641 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16642 		} else {
16643 			icmp6_t *icmp6;
16644 			int hdr_length;
16645 
16646 			ip6h = (ip6_t *)mp->b_rptr;
16647 			/* Don't call hdr_length_v6() unless you have to. */
16648 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16649 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16650 			else
16651 				hdr_length = IPV6_HDR_LEN;
16652 
16653 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16654 			/*
16655 			 * icmp_inbound_error_fanout_v6 may need to do
16656 			 * pullupmsg.  Reset the type to M_DATA.
16657 			 */
16658 			mp->b_datap->db_type = M_DATA;
16659 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16660 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16661 		}
16662 		if (ill_need_rele)
16663 			ill_refrele(ill);
16664 		if (rill_need_rele)
16665 			ill_refrele(recv_ill);
16666 		return;
16667 	}
16668 
16669 	if (ii->ipsec_in_v4) {
16670 		ipha = (ipha_t *)mp->b_rptr;
16671 		dst = ipha->ipha_dst;
16672 		if (CLASSD(dst)) {
16673 			/*
16674 			 * Multicast has to be delivered to all streams.
16675 			 */
16676 			dst = INADDR_BROADCAST;
16677 		}
16678 
16679 		if (ire == NULL) {
16680 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16681 			    MBLK_GETLABEL(mp), ipst);
16682 			if (ire == NULL) {
16683 				if (ill_need_rele)
16684 					ill_refrele(ill);
16685 				if (rill_need_rele)
16686 					ill_refrele(recv_ill);
16687 				ip1dbg(("ip_fanout_proto_again: "
16688 				    "IRE not found"));
16689 				freemsg(ipsec_mp);
16690 				return;
16691 			}
16692 			ire_need_rele = B_TRUE;
16693 		}
16694 
16695 		switch (ipha->ipha_protocol) {
16696 			case IPPROTO_UDP:
16697 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16698 				    recv_ill);
16699 				if (ire_need_rele)
16700 					ire_refrele(ire);
16701 				break;
16702 			case IPPROTO_TCP:
16703 				if (!ire_need_rele)
16704 					IRE_REFHOLD(ire);
16705 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16706 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16707 				IRE_REFRELE(ire);
16708 				if (mp != NULL)
16709 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16710 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16711 				break;
16712 			case IPPROTO_SCTP:
16713 				if (!ire_need_rele)
16714 					IRE_REFHOLD(ire);
16715 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16716 				    ipsec_mp, 0, ill->ill_rq, dst);
16717 				break;
16718 			default:
16719 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16720 				    recv_ill);
16721 				if (ire_need_rele)
16722 					ire_refrele(ire);
16723 				break;
16724 		}
16725 	} else {
16726 		uint32_t rput_flags = 0;
16727 
16728 		ip6h = (ip6_t *)mp->b_rptr;
16729 		v6dstp = &ip6h->ip6_dst;
16730 		/*
16731 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16732 		 * address.
16733 		 *
16734 		 * Currently, we don't store that state in the IPSEC_IN
16735 		 * message, and we may need to.
16736 		 */
16737 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16738 		    IP6_IN_LLMCAST : 0);
16739 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16740 		    NULL, NULL);
16741 	}
16742 	if (ill_need_rele)
16743 		ill_refrele(ill);
16744 	if (rill_need_rele)
16745 		ill_refrele(recv_ill);
16746 }
16747 
16748 /*
16749  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16750  * returns 'true' if there are still fragments left on the queue, in
16751  * which case we restart the timer.
16752  */
16753 void
16754 ill_frag_timer(void *arg)
16755 {
16756 	ill_t	*ill = (ill_t *)arg;
16757 	boolean_t frag_pending;
16758 	ip_stack_t	*ipst = ill->ill_ipst;
16759 
16760 	mutex_enter(&ill->ill_lock);
16761 	ASSERT(!ill->ill_fragtimer_executing);
16762 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16763 		ill->ill_frag_timer_id = 0;
16764 		mutex_exit(&ill->ill_lock);
16765 		return;
16766 	}
16767 	ill->ill_fragtimer_executing = 1;
16768 	mutex_exit(&ill->ill_lock);
16769 
16770 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16771 
16772 	/*
16773 	 * Restart the timer, if we have fragments pending or if someone
16774 	 * wanted us to be scheduled again.
16775 	 */
16776 	mutex_enter(&ill->ill_lock);
16777 	ill->ill_fragtimer_executing = 0;
16778 	ill->ill_frag_timer_id = 0;
16779 	if (frag_pending || ill->ill_fragtimer_needrestart)
16780 		ill_frag_timer_start(ill);
16781 	mutex_exit(&ill->ill_lock);
16782 }
16783 
16784 void
16785 ill_frag_timer_start(ill_t *ill)
16786 {
16787 	ip_stack_t	*ipst = ill->ill_ipst;
16788 
16789 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16790 
16791 	/* If the ill is closing or opening don't proceed */
16792 	if (ill->ill_state_flags & ILL_CONDEMNED)
16793 		return;
16794 
16795 	if (ill->ill_fragtimer_executing) {
16796 		/*
16797 		 * ill_frag_timer is currently executing. Just record the
16798 		 * the fact that we want the timer to be restarted.
16799 		 * ill_frag_timer will post a timeout before it returns,
16800 		 * ensuring it will be called again.
16801 		 */
16802 		ill->ill_fragtimer_needrestart = 1;
16803 		return;
16804 	}
16805 
16806 	if (ill->ill_frag_timer_id == 0) {
16807 		/*
16808 		 * The timer is neither running nor is the timeout handler
16809 		 * executing. Post a timeout so that ill_frag_timer will be
16810 		 * called
16811 		 */
16812 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16813 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
16814 		ill->ill_fragtimer_needrestart = 0;
16815 	}
16816 }
16817 
16818 /*
16819  * This routine is needed for loopback when forwarding multicasts.
16820  *
16821  * IPQoS Notes:
16822  * IPPF processing is done in fanout routines.
16823  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16824  * processing for IPSec packets is done when it comes back in clear.
16825  * NOTE : The callers of this function need to do the ire_refrele for the
16826  *	  ire that is being passed in.
16827  */
16828 void
16829 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16830     ill_t *recv_ill)
16831 {
16832 	ill_t	*ill = (ill_t *)q->q_ptr;
16833 	uint32_t	sum;
16834 	uint32_t	u1;
16835 	uint32_t	u2;
16836 	int		hdr_length;
16837 	boolean_t	mctl_present;
16838 	mblk_t		*first_mp = mp;
16839 	mblk_t		*hada_mp = NULL;
16840 	ipha_t		*inner_ipha;
16841 	ip_stack_t	*ipst;
16842 
16843 	ASSERT(recv_ill != NULL);
16844 	ipst = recv_ill->ill_ipst;
16845 
16846 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16847 	    "ip_rput_locl_start: q %p", q);
16848 
16849 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16850 	ASSERT(ill != NULL);
16851 
16852 
16853 #define	rptr	((uchar_t *)ipha)
16854 #define	iphs	((uint16_t *)ipha)
16855 
16856 	/*
16857 	 * no UDP or TCP packet should come here anymore.
16858 	 */
16859 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16860 	    (ipha->ipha_protocol != IPPROTO_UDP));
16861 
16862 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16863 	if (mctl_present &&
16864 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16865 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16866 
16867 		/*
16868 		 * It's an IPsec accelerated packet.
16869 		 * Keep a pointer to the data attributes around until
16870 		 * we allocate the ipsec_info_t.
16871 		 */
16872 		IPSECHW_DEBUG(IPSECHW_PKT,
16873 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16874 		hada_mp = first_mp;
16875 		hada_mp->b_cont = NULL;
16876 		/*
16877 		 * Since it is accelerated, it comes directly from
16878 		 * the ill and the data attributes is followed by
16879 		 * the packet data.
16880 		 */
16881 		ASSERT(mp->b_datap->db_type != M_CTL);
16882 		first_mp = mp;
16883 		mctl_present = B_FALSE;
16884 	}
16885 
16886 	/*
16887 	 * IF M_CTL is not present, then ipsec_in_is_secure
16888 	 * should return B_TRUE. There is a case where loopback
16889 	 * packets has an M_CTL in the front with all the
16890 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16891 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16892 	 * packets never comes here, it is safe to ASSERT the
16893 	 * following.
16894 	 */
16895 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16896 
16897 
16898 	/* u1 is # words of IP options */
16899 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16900 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16901 
16902 	if (u1) {
16903 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
16904 			if (hada_mp != NULL)
16905 				freemsg(hada_mp);
16906 			return;
16907 		}
16908 	} else {
16909 		/* Check the IP header checksum.  */
16910 #define	uph	((uint16_t *)ipha)
16911 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16912 		    uph[6] + uph[7] + uph[8] + uph[9];
16913 #undef  uph
16914 		/* finish doing IP checksum */
16915 		sum = (sum & 0xFFFF) + (sum >> 16);
16916 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16917 		/*
16918 		 * Don't verify header checksum if this packet is coming
16919 		 * back from AH/ESP as we already did it.
16920 		 */
16921 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16922 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
16923 			goto drop_pkt;
16924 		}
16925 	}
16926 
16927 	/*
16928 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16929 	 * might be called more than once for secure packets, count only
16930 	 * the first time.
16931 	 */
16932 	if (!mctl_present) {
16933 		UPDATE_IB_PKT_COUNT(ire);
16934 		ire->ire_last_used_time = lbolt;
16935 	}
16936 
16937 	/* Check for fragmentation offset. */
16938 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16939 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16940 	if (u1) {
16941 		/*
16942 		 * We re-assemble fragments before we do the AH/ESP
16943 		 * processing. Thus, M_CTL should not be present
16944 		 * while we are re-assembling.
16945 		 */
16946 		ASSERT(!mctl_present);
16947 		ASSERT(first_mp == mp);
16948 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16949 			return;
16950 		}
16951 		/*
16952 		 * Make sure that first_mp points back to mp as
16953 		 * the mp we came in with could have changed in
16954 		 * ip_rput_fragment().
16955 		 */
16956 		ipha = (ipha_t *)mp->b_rptr;
16957 		first_mp = mp;
16958 	}
16959 
16960 	/*
16961 	 * Clear hardware checksumming flag as it is currently only
16962 	 * used by TCP and UDP.
16963 	 */
16964 	DB_CKSUMFLAGS(mp) = 0;
16965 
16966 	/* Now we have a complete datagram, destined for this machine. */
16967 	u1 = IPH_HDR_LENGTH(ipha);
16968 	switch (ipha->ipha_protocol) {
16969 	case IPPROTO_ICMP: {
16970 		ire_t		*ire_zone;
16971 		ilm_t		*ilm;
16972 		mblk_t		*mp1;
16973 		zoneid_t	last_zoneid;
16974 
16975 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
16976 			ASSERT(ire->ire_type == IRE_BROADCAST);
16977 			/*
16978 			 * In the multicast case, applications may have joined
16979 			 * the group from different zones, so we need to deliver
16980 			 * the packet to each of them. Loop through the
16981 			 * multicast memberships structures (ilm) on the receive
16982 			 * ill and send a copy of the packet up each matching
16983 			 * one. However, we don't do this for multicasts sent on
16984 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16985 			 * they must stay in the sender's zone.
16986 			 *
16987 			 * ilm_add_v6() ensures that ilms in the same zone are
16988 			 * contiguous in the ill_ilm list. We use this property
16989 			 * to avoid sending duplicates needed when two
16990 			 * applications in the same zone join the same group on
16991 			 * different logical interfaces: we ignore the ilm if
16992 			 * its zoneid is the same as the last matching one.
16993 			 * In addition, the sending of the packet for
16994 			 * ire_zoneid is delayed until all of the other ilms
16995 			 * have been exhausted.
16996 			 */
16997 			last_zoneid = -1;
16998 			ILM_WALKER_HOLD(recv_ill);
16999 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17000 			    ilm = ilm->ilm_next) {
17001 				if ((ilm->ilm_flags & ILM_DELETED) ||
17002 				    ipha->ipha_dst != ilm->ilm_addr ||
17003 				    ilm->ilm_zoneid == last_zoneid ||
17004 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17005 				    ilm->ilm_zoneid == ALL_ZONES ||
17006 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17007 					continue;
17008 				mp1 = ip_copymsg(first_mp);
17009 				if (mp1 == NULL)
17010 					continue;
17011 				icmp_inbound(q, mp1, B_TRUE, ill,
17012 				    0, sum, mctl_present, B_TRUE,
17013 				    recv_ill, ilm->ilm_zoneid);
17014 				last_zoneid = ilm->ilm_zoneid;
17015 			}
17016 			ILM_WALKER_RELE(recv_ill);
17017 		} else if (ire->ire_type == IRE_BROADCAST) {
17018 			/*
17019 			 * In the broadcast case, there may be many zones
17020 			 * which need a copy of the packet delivered to them.
17021 			 * There is one IRE_BROADCAST per broadcast address
17022 			 * and per zone; we walk those using a helper function.
17023 			 * In addition, the sending of the packet for ire is
17024 			 * delayed until all of the other ires have been
17025 			 * processed.
17026 			 */
17027 			IRB_REFHOLD(ire->ire_bucket);
17028 			ire_zone = NULL;
17029 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17030 			    ire)) != NULL) {
17031 				mp1 = ip_copymsg(first_mp);
17032 				if (mp1 == NULL)
17033 					continue;
17034 
17035 				UPDATE_IB_PKT_COUNT(ire_zone);
17036 				ire_zone->ire_last_used_time = lbolt;
17037 				icmp_inbound(q, mp1, B_TRUE, ill,
17038 				    0, sum, mctl_present, B_TRUE,
17039 				    recv_ill, ire_zone->ire_zoneid);
17040 			}
17041 			IRB_REFRELE(ire->ire_bucket);
17042 		}
17043 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17044 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17045 		    ire->ire_zoneid);
17046 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17047 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17048 		return;
17049 	}
17050 	case IPPROTO_IGMP:
17051 		/*
17052 		 * If we are not willing to accept IGMP packets in clear,
17053 		 * then check with global policy.
17054 		 */
17055 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17056 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17057 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17058 			if (first_mp == NULL)
17059 				return;
17060 		}
17061 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17062 			freemsg(first_mp);
17063 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17064 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17065 			return;
17066 		}
17067 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17068 			/* Bad packet - discarded by igmp_input */
17069 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17070 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17071 			if (mctl_present)
17072 				freeb(first_mp);
17073 			return;
17074 		}
17075 		/*
17076 		 * igmp_input() may have returned the pulled up message.
17077 		 * So first_mp and ipha need to be reinitialized.
17078 		 */
17079 		ipha = (ipha_t *)mp->b_rptr;
17080 		if (mctl_present)
17081 			first_mp->b_cont = mp;
17082 		else
17083 			first_mp = mp;
17084 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17085 		    connf_head != NULL) {
17086 			/* No user-level listener for IGMP packets */
17087 			goto drop_pkt;
17088 		}
17089 		/* deliver to local raw users */
17090 		break;
17091 	case IPPROTO_PIM:
17092 		/*
17093 		 * If we are not willing to accept PIM packets in clear,
17094 		 * then check with global policy.
17095 		 */
17096 		if (ipst->ips_pim_accept_clear_messages == 0) {
17097 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17098 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17099 			if (first_mp == NULL)
17100 				return;
17101 		}
17102 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17103 			freemsg(first_mp);
17104 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17105 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17106 			return;
17107 		}
17108 		if (pim_input(q, mp, ill) != 0) {
17109 			/* Bad packet - discarded by pim_input */
17110 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17111 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17112 			if (mctl_present)
17113 				freeb(first_mp);
17114 			return;
17115 		}
17116 
17117 		/*
17118 		 * pim_input() may have pulled up the message so ipha needs to
17119 		 * be reinitialized.
17120 		 */
17121 		ipha = (ipha_t *)mp->b_rptr;
17122 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17123 		    connf_head != NULL) {
17124 			/* No user-level listener for PIM packets */
17125 			goto drop_pkt;
17126 		}
17127 		/* deliver to local raw users */
17128 		break;
17129 	case IPPROTO_ENCAP:
17130 		/*
17131 		 * Handle self-encapsulated packets (IP-in-IP where
17132 		 * the inner addresses == the outer addresses).
17133 		 */
17134 		hdr_length = IPH_HDR_LENGTH(ipha);
17135 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17136 		    mp->b_wptr) {
17137 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17138 			    sizeof (ipha_t) - mp->b_rptr)) {
17139 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17140 				freemsg(first_mp);
17141 				return;
17142 			}
17143 			ipha = (ipha_t *)mp->b_rptr;
17144 		}
17145 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17146 		/*
17147 		 * Check the sanity of the inner IP header.
17148 		 */
17149 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17150 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17151 			freemsg(first_mp);
17152 			return;
17153 		}
17154 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17155 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17156 			freemsg(first_mp);
17157 			return;
17158 		}
17159 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17160 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17161 			ipsec_in_t *ii;
17162 
17163 			/*
17164 			 * Self-encapsulated tunnel packet. Remove
17165 			 * the outer IP header and fanout again.
17166 			 * We also need to make sure that the inner
17167 			 * header is pulled up until options.
17168 			 */
17169 			mp->b_rptr = (uchar_t *)inner_ipha;
17170 			ipha = inner_ipha;
17171 			hdr_length = IPH_HDR_LENGTH(ipha);
17172 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17173 				if (!pullupmsg(mp, (uchar_t *)ipha +
17174 				    + hdr_length - mp->b_rptr)) {
17175 					freemsg(first_mp);
17176 					return;
17177 				}
17178 				ipha = (ipha_t *)mp->b_rptr;
17179 			}
17180 			if (!mctl_present) {
17181 				ASSERT(first_mp == mp);
17182 				/*
17183 				 * This means that somebody is sending
17184 				 * Self-encapsualted packets without AH/ESP.
17185 				 * If AH/ESP was present, we would have already
17186 				 * allocated the first_mp.
17187 				 */
17188 				first_mp = ipsec_in_alloc(B_TRUE,
17189 				    ipst->ips_netstack);
17190 				if (first_mp == NULL) {
17191 					ip1dbg(("ip_proto_input: IPSEC_IN "
17192 					    "allocation failure.\n"));
17193 					BUMP_MIB(ill->ill_ip_mib,
17194 					    ipIfStatsInDiscards);
17195 					freemsg(mp);
17196 					return;
17197 				}
17198 				first_mp->b_cont = mp;
17199 			}
17200 			/*
17201 			 * We generally store the ill_index if we need to
17202 			 * do IPSEC processing as we lose the ill queue when
17203 			 * we come back. But in this case, we never should
17204 			 * have to store the ill_index here as it should have
17205 			 * been stored previously when we processed the
17206 			 * AH/ESP header in this routine or for non-ipsec
17207 			 * cases, we still have the queue. But for some bad
17208 			 * packets from the wire, we can get to IPSEC after
17209 			 * this and we better store the index for that case.
17210 			 */
17211 			ill = (ill_t *)q->q_ptr;
17212 			ii = (ipsec_in_t *)first_mp->b_rptr;
17213 			ii->ipsec_in_ill_index =
17214 			    ill->ill_phyint->phyint_ifindex;
17215 			ii->ipsec_in_rill_index =
17216 			    recv_ill->ill_phyint->phyint_ifindex;
17217 			if (ii->ipsec_in_decaps) {
17218 				/*
17219 				 * This packet is self-encapsulated multiple
17220 				 * times. We don't want to recurse infinitely.
17221 				 * To keep it simple, drop the packet.
17222 				 */
17223 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17224 				freemsg(first_mp);
17225 				return;
17226 			}
17227 			ii->ipsec_in_decaps = B_TRUE;
17228 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17229 			    ire);
17230 			return;
17231 		}
17232 		break;
17233 	case IPPROTO_AH:
17234 	case IPPROTO_ESP: {
17235 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17236 
17237 		/*
17238 		 * Fast path for AH/ESP. If this is the first time
17239 		 * we are sending a datagram to AH/ESP, allocate
17240 		 * a IPSEC_IN message and prepend it. Otherwise,
17241 		 * just fanout.
17242 		 */
17243 
17244 		int ipsec_rc;
17245 		ipsec_in_t *ii;
17246 		netstack_t *ns = ipst->ips_netstack;
17247 
17248 		IP_STAT(ipst, ipsec_proto_ahesp);
17249 		if (!mctl_present) {
17250 			ASSERT(first_mp == mp);
17251 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17252 			if (first_mp == NULL) {
17253 				ip1dbg(("ip_proto_input: IPSEC_IN "
17254 				    "allocation failure.\n"));
17255 				freemsg(hada_mp); /* okay ifnull */
17256 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17257 				freemsg(mp);
17258 				return;
17259 			}
17260 			/*
17261 			 * Store the ill_index so that when we come back
17262 			 * from IPSEC we ride on the same queue.
17263 			 */
17264 			ill = (ill_t *)q->q_ptr;
17265 			ii = (ipsec_in_t *)first_mp->b_rptr;
17266 			ii->ipsec_in_ill_index =
17267 			    ill->ill_phyint->phyint_ifindex;
17268 			ii->ipsec_in_rill_index =
17269 			    recv_ill->ill_phyint->phyint_ifindex;
17270 			first_mp->b_cont = mp;
17271 			/*
17272 			 * Cache hardware acceleration info.
17273 			 */
17274 			if (hada_mp != NULL) {
17275 				IPSECHW_DEBUG(IPSECHW_PKT,
17276 				    ("ip_rput_local: caching data attr.\n"));
17277 				ii->ipsec_in_accelerated = B_TRUE;
17278 				ii->ipsec_in_da = hada_mp;
17279 				hada_mp = NULL;
17280 			}
17281 		} else {
17282 			ii = (ipsec_in_t *)first_mp->b_rptr;
17283 		}
17284 
17285 		if (!ipsec_loaded(ipss)) {
17286 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17287 			    ire->ire_zoneid, ipst);
17288 			return;
17289 		}
17290 
17291 		ns = ipst->ips_netstack;
17292 		/* select inbound SA and have IPsec process the pkt */
17293 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17294 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17295 			if (esph == NULL)
17296 				return;
17297 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17298 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17299 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17300 			    first_mp, esph);
17301 		} else {
17302 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17303 			if (ah == NULL)
17304 				return;
17305 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17306 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17307 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17308 			    first_mp, ah);
17309 		}
17310 
17311 		switch (ipsec_rc) {
17312 		case IPSEC_STATUS_SUCCESS:
17313 			break;
17314 		case IPSEC_STATUS_FAILED:
17315 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17316 			/* FALLTHRU */
17317 		case IPSEC_STATUS_PENDING:
17318 			return;
17319 		}
17320 		/* we're done with IPsec processing, send it up */
17321 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17322 		return;
17323 	}
17324 	default:
17325 		break;
17326 	}
17327 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17328 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17329 		    ire->ire_zoneid));
17330 		goto drop_pkt;
17331 	}
17332 	/*
17333 	 * Handle protocols with which IP is less intimate.  There
17334 	 * can be more than one stream bound to a particular
17335 	 * protocol.  When this is the case, each one gets a copy
17336 	 * of any incoming packets.
17337 	 */
17338 	ip_fanout_proto(q, first_mp, ill, ipha,
17339 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17340 	    B_TRUE, recv_ill, ire->ire_zoneid);
17341 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17342 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17343 	return;
17344 
17345 drop_pkt:
17346 	freemsg(first_mp);
17347 	if (hada_mp != NULL)
17348 		freeb(hada_mp);
17349 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17350 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17351 #undef	rptr
17352 #undef  iphs
17353 
17354 }
17355 
17356 /*
17357  * Update any source route, record route or timestamp options.
17358  * Check that we are at end of strict source route.
17359  * The options have already been checked for sanity in ip_rput_options().
17360  */
17361 static boolean_t
17362 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17363     ip_stack_t *ipst)
17364 {
17365 	ipoptp_t	opts;
17366 	uchar_t		*opt;
17367 	uint8_t		optval;
17368 	uint8_t		optlen;
17369 	ipaddr_t	dst;
17370 	uint32_t	ts;
17371 	ire_t		*dst_ire;
17372 	timestruc_t	now;
17373 	zoneid_t	zoneid;
17374 	ill_t		*ill;
17375 
17376 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17377 
17378 	ip2dbg(("ip_rput_local_options\n"));
17379 
17380 	for (optval = ipoptp_first(&opts, ipha);
17381 	    optval != IPOPT_EOL;
17382 	    optval = ipoptp_next(&opts)) {
17383 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17384 		opt = opts.ipoptp_cur;
17385 		optlen = opts.ipoptp_len;
17386 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17387 		    optval, optlen));
17388 		switch (optval) {
17389 			uint32_t off;
17390 		case IPOPT_SSRR:
17391 		case IPOPT_LSRR:
17392 			off = opt[IPOPT_OFFSET];
17393 			off--;
17394 			if (optlen < IP_ADDR_LEN ||
17395 			    off > optlen - IP_ADDR_LEN) {
17396 				/* End of source route */
17397 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17398 				break;
17399 			}
17400 			/*
17401 			 * This will only happen if two consecutive entries
17402 			 * in the source route contains our address or if
17403 			 * it is a packet with a loose source route which
17404 			 * reaches us before consuming the whole source route
17405 			 */
17406 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17407 			if (optval == IPOPT_SSRR) {
17408 				goto bad_src_route;
17409 			}
17410 			/*
17411 			 * Hack: instead of dropping the packet truncate the
17412 			 * source route to what has been used by filling the
17413 			 * rest with IPOPT_NOP.
17414 			 */
17415 			opt[IPOPT_OLEN] = (uint8_t)off;
17416 			while (off < optlen) {
17417 				opt[off++] = IPOPT_NOP;
17418 			}
17419 			break;
17420 		case IPOPT_RR:
17421 			off = opt[IPOPT_OFFSET];
17422 			off--;
17423 			if (optlen < IP_ADDR_LEN ||
17424 			    off > optlen - IP_ADDR_LEN) {
17425 				/* No more room - ignore */
17426 				ip1dbg((
17427 				    "ip_rput_local_options: end of RR\n"));
17428 				break;
17429 			}
17430 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17431 			    IP_ADDR_LEN);
17432 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17433 			break;
17434 		case IPOPT_TS:
17435 			/* Insert timestamp if there is romm */
17436 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17437 			case IPOPT_TS_TSONLY:
17438 				off = IPOPT_TS_TIMELEN;
17439 				break;
17440 			case IPOPT_TS_PRESPEC:
17441 			case IPOPT_TS_PRESPEC_RFC791:
17442 				/* Verify that the address matched */
17443 				off = opt[IPOPT_OFFSET] - 1;
17444 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17445 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17446 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17447 				    ipst);
17448 				if (dst_ire == NULL) {
17449 					/* Not for us */
17450 					break;
17451 				}
17452 				ire_refrele(dst_ire);
17453 				/* FALLTHRU */
17454 			case IPOPT_TS_TSANDADDR:
17455 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17456 				break;
17457 			default:
17458 				/*
17459 				 * ip_*put_options should have already
17460 				 * dropped this packet.
17461 				 */
17462 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17463 				    "unknown IT - bug in ip_rput_options?\n");
17464 				return (B_TRUE);	/* Keep "lint" happy */
17465 			}
17466 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17467 				/* Increase overflow counter */
17468 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17469 				opt[IPOPT_POS_OV_FLG] =
17470 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17471 				    (off << 4));
17472 				break;
17473 			}
17474 			off = opt[IPOPT_OFFSET] - 1;
17475 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17476 			case IPOPT_TS_PRESPEC:
17477 			case IPOPT_TS_PRESPEC_RFC791:
17478 			case IPOPT_TS_TSANDADDR:
17479 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17480 				    IP_ADDR_LEN);
17481 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17482 				/* FALLTHRU */
17483 			case IPOPT_TS_TSONLY:
17484 				off = opt[IPOPT_OFFSET] - 1;
17485 				/* Compute # of milliseconds since midnight */
17486 				gethrestime(&now);
17487 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17488 				    now.tv_nsec / (NANOSEC / MILLISEC);
17489 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17490 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17491 				break;
17492 			}
17493 			break;
17494 		}
17495 	}
17496 	return (B_TRUE);
17497 
17498 bad_src_route:
17499 	q = WR(q);
17500 	if (q->q_next != NULL)
17501 		ill = q->q_ptr;
17502 	else
17503 		ill = NULL;
17504 
17505 	/* make sure we clear any indication of a hardware checksum */
17506 	DB_CKSUMFLAGS(mp) = 0;
17507 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17508 	if (zoneid == ALL_ZONES)
17509 		freemsg(mp);
17510 	else
17511 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17512 	return (B_FALSE);
17513 
17514 }
17515 
17516 /*
17517  * Process IP options in an inbound packet.  If an option affects the
17518  * effective destination address, return the next hop address via dstp.
17519  * Returns -1 if something fails in which case an ICMP error has been sent
17520  * and mp freed.
17521  */
17522 static int
17523 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17524     ip_stack_t *ipst)
17525 {
17526 	ipoptp_t	opts;
17527 	uchar_t		*opt;
17528 	uint8_t		optval;
17529 	uint8_t		optlen;
17530 	ipaddr_t	dst;
17531 	intptr_t	code = 0;
17532 	ire_t		*ire = NULL;
17533 	zoneid_t	zoneid;
17534 	ill_t		*ill;
17535 
17536 	ip2dbg(("ip_rput_options\n"));
17537 	dst = ipha->ipha_dst;
17538 	for (optval = ipoptp_first(&opts, ipha);
17539 	    optval != IPOPT_EOL;
17540 	    optval = ipoptp_next(&opts)) {
17541 		opt = opts.ipoptp_cur;
17542 		optlen = opts.ipoptp_len;
17543 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17544 		    optval, optlen));
17545 		/*
17546 		 * Note: we need to verify the checksum before we
17547 		 * modify anything thus this routine only extracts the next
17548 		 * hop dst from any source route.
17549 		 */
17550 		switch (optval) {
17551 			uint32_t off;
17552 		case IPOPT_SSRR:
17553 		case IPOPT_LSRR:
17554 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17555 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17556 			if (ire == NULL) {
17557 				if (optval == IPOPT_SSRR) {
17558 					ip1dbg(("ip_rput_options: not next"
17559 					    " strict source route 0x%x\n",
17560 					    ntohl(dst)));
17561 					code = (char *)&ipha->ipha_dst -
17562 					    (char *)ipha;
17563 					goto param_prob; /* RouterReq's */
17564 				}
17565 				ip2dbg(("ip_rput_options: "
17566 				    "not next source route 0x%x\n",
17567 				    ntohl(dst)));
17568 				break;
17569 			}
17570 			ire_refrele(ire);
17571 
17572 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17573 				ip1dbg((
17574 				    "ip_rput_options: bad option offset\n"));
17575 				code = (char *)&opt[IPOPT_OLEN] -
17576 				    (char *)ipha;
17577 				goto param_prob;
17578 			}
17579 			off = opt[IPOPT_OFFSET];
17580 			off--;
17581 		redo_srr:
17582 			if (optlen < IP_ADDR_LEN ||
17583 			    off > optlen - IP_ADDR_LEN) {
17584 				/* End of source route */
17585 				ip1dbg(("ip_rput_options: end of SR\n"));
17586 				break;
17587 			}
17588 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17589 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17590 			    ntohl(dst)));
17591 
17592 			/*
17593 			 * Check if our address is present more than
17594 			 * once as consecutive hops in source route.
17595 			 * XXX verify per-interface ip_forwarding
17596 			 * for source route?
17597 			 */
17598 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17599 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17600 
17601 			if (ire != NULL) {
17602 				ire_refrele(ire);
17603 				off += IP_ADDR_LEN;
17604 				goto redo_srr;
17605 			}
17606 
17607 			if (dst == htonl(INADDR_LOOPBACK)) {
17608 				ip1dbg(("ip_rput_options: loopback addr in "
17609 				    "source route!\n"));
17610 				goto bad_src_route;
17611 			}
17612 			/*
17613 			 * For strict: verify that dst is directly
17614 			 * reachable.
17615 			 */
17616 			if (optval == IPOPT_SSRR) {
17617 				ire = ire_ftable_lookup(dst, 0, 0,
17618 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17619 				    MBLK_GETLABEL(mp),
17620 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17621 				if (ire == NULL) {
17622 					ip1dbg(("ip_rput_options: SSRR not "
17623 					    "directly reachable: 0x%x\n",
17624 					    ntohl(dst)));
17625 					goto bad_src_route;
17626 				}
17627 				ire_refrele(ire);
17628 			}
17629 			/*
17630 			 * Defer update of the offset and the record route
17631 			 * until the packet is forwarded.
17632 			 */
17633 			break;
17634 		case IPOPT_RR:
17635 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17636 				ip1dbg((
17637 				    "ip_rput_options: bad option offset\n"));
17638 				code = (char *)&opt[IPOPT_OLEN] -
17639 				    (char *)ipha;
17640 				goto param_prob;
17641 			}
17642 			break;
17643 		case IPOPT_TS:
17644 			/*
17645 			 * Verify that length >= 5 and that there is either
17646 			 * room for another timestamp or that the overflow
17647 			 * counter is not maxed out.
17648 			 */
17649 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17650 			if (optlen < IPOPT_MINLEN_IT) {
17651 				goto param_prob;
17652 			}
17653 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17654 				ip1dbg((
17655 				    "ip_rput_options: bad option offset\n"));
17656 				code = (char *)&opt[IPOPT_OFFSET] -
17657 				    (char *)ipha;
17658 				goto param_prob;
17659 			}
17660 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17661 			case IPOPT_TS_TSONLY:
17662 				off = IPOPT_TS_TIMELEN;
17663 				break;
17664 			case IPOPT_TS_TSANDADDR:
17665 			case IPOPT_TS_PRESPEC:
17666 			case IPOPT_TS_PRESPEC_RFC791:
17667 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17668 				break;
17669 			default:
17670 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17671 				    (char *)ipha;
17672 				goto param_prob;
17673 			}
17674 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17675 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17676 				/*
17677 				 * No room and the overflow counter is 15
17678 				 * already.
17679 				 */
17680 				goto param_prob;
17681 			}
17682 			break;
17683 		}
17684 	}
17685 
17686 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17687 		*dstp = dst;
17688 		return (0);
17689 	}
17690 
17691 	ip1dbg(("ip_rput_options: error processing IP options."));
17692 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17693 
17694 param_prob:
17695 	q = WR(q);
17696 	if (q->q_next != NULL)
17697 		ill = q->q_ptr;
17698 	else
17699 		ill = NULL;
17700 
17701 	/* make sure we clear any indication of a hardware checksum */
17702 	DB_CKSUMFLAGS(mp) = 0;
17703 	/* Don't know whether this is for non-global or global/forwarding */
17704 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17705 	if (zoneid == ALL_ZONES)
17706 		freemsg(mp);
17707 	else
17708 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17709 	return (-1);
17710 
17711 bad_src_route:
17712 	q = WR(q);
17713 	if (q->q_next != NULL)
17714 		ill = q->q_ptr;
17715 	else
17716 		ill = NULL;
17717 
17718 	/* make sure we clear any indication of a hardware checksum */
17719 	DB_CKSUMFLAGS(mp) = 0;
17720 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17721 	if (zoneid == ALL_ZONES)
17722 		freemsg(mp);
17723 	else
17724 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17725 	return (-1);
17726 }
17727 
17728 /*
17729  * IP & ICMP info in >=14 msg's ...
17730  *  - ip fixed part (mib2_ip_t)
17731  *  - icmp fixed part (mib2_icmp_t)
17732  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17733  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17734  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17735  *  - ipRouteAttributeTable (ip 102)	labeled routes
17736  *  - ip multicast membership (ip_member_t)
17737  *  - ip multicast source filtering (ip_grpsrc_t)
17738  *  - igmp fixed part (struct igmpstat)
17739  *  - multicast routing stats (struct mrtstat)
17740  *  - multicast routing vifs (array of struct vifctl)
17741  *  - multicast routing routes (array of struct mfcctl)
17742  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17743  *					One per ill plus one generic
17744  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17745  *					One per ill plus one generic
17746  *  - ipv6RouteEntry			all IPv6 IREs
17747  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17748  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17749  *  - ipv6AddrEntry			all IPv6 ipifs
17750  *  - ipv6 multicast membership (ipv6_member_t)
17751  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17752  *
17753  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17754  *
17755  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17756  * already filled in by the caller.
17757  * Return value of 0 indicates that no messages were sent and caller
17758  * should free mpctl.
17759  */
17760 int
17761 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17762 {
17763 	ip_stack_t *ipst;
17764 	sctp_stack_t *sctps;
17765 
17766 
17767 	if (q->q_next != NULL) {
17768 		ipst = ILLQ_TO_IPST(q);
17769 	} else {
17770 		ipst = CONNQ_TO_IPST(q);
17771 	}
17772 	ASSERT(ipst != NULL);
17773 	sctps = ipst->ips_netstack->netstack_sctp;
17774 
17775 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17776 		return (0);
17777 	}
17778 
17779 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
17780 	    ipst)) == NULL) {
17781 		return (1);
17782 	}
17783 
17784 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
17785 		return (1);
17786 	}
17787 
17788 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
17789 		return (1);
17790 	}
17791 
17792 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
17793 		return (1);
17794 	}
17795 
17796 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
17797 		return (1);
17798 	}
17799 
17800 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
17801 		return (1);
17802 	}
17803 
17804 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
17805 		return (1);
17806 	}
17807 
17808 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
17809 		return (1);
17810 	}
17811 
17812 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
17813 		return (1);
17814 	}
17815 
17816 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
17817 		return (1);
17818 	}
17819 
17820 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
17821 		return (1);
17822 	}
17823 
17824 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
17825 		return (1);
17826 	}
17827 
17828 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
17829 		return (1);
17830 	}
17831 
17832 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
17833 		return (1);
17834 	}
17835 
17836 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
17837 		return (1);
17838 	}
17839 
17840 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
17841 	if (mpctl == NULL) {
17842 		return (1);
17843 	}
17844 
17845 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
17846 		return (1);
17847 	}
17848 	freemsg(mpctl);
17849 	return (1);
17850 }
17851 
17852 
17853 /* Get global (legacy) IPv4 statistics */
17854 static mblk_t *
17855 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
17856     ip_stack_t *ipst)
17857 {
17858 	mib2_ip_t		old_ip_mib;
17859 	struct opthdr		*optp;
17860 	mblk_t			*mp2ctl;
17861 
17862 	/*
17863 	 * make a copy of the original message
17864 	 */
17865 	mp2ctl = copymsg(mpctl);
17866 
17867 	/* fixed length IP structure... */
17868 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17869 	optp->level = MIB2_IP;
17870 	optp->name = 0;
17871 	SET_MIB(old_ip_mib.ipForwarding,
17872 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
17873 	SET_MIB(old_ip_mib.ipDefaultTTL,
17874 	    (uint32_t)ipst->ips_ip_def_ttl);
17875 	SET_MIB(old_ip_mib.ipReasmTimeout,
17876 	    ipst->ips_ip_g_frag_timeout);
17877 	SET_MIB(old_ip_mib.ipAddrEntrySize,
17878 	    sizeof (mib2_ipAddrEntry_t));
17879 	SET_MIB(old_ip_mib.ipRouteEntrySize,
17880 	    sizeof (mib2_ipRouteEntry_t));
17881 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
17882 	    sizeof (mib2_ipNetToMediaEntry_t));
17883 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17884 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17885 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
17886 	    sizeof (mib2_ipAttributeEntry_t));
17887 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17888 
17889 	/*
17890 	 * Grab the statistics from the new IP MIB
17891 	 */
17892 	SET_MIB(old_ip_mib.ipInReceives,
17893 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
17894 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
17895 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
17896 	SET_MIB(old_ip_mib.ipForwDatagrams,
17897 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
17898 	SET_MIB(old_ip_mib.ipInUnknownProtos,
17899 	    ipmib->ipIfStatsInUnknownProtos);
17900 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
17901 	SET_MIB(old_ip_mib.ipInDelivers,
17902 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
17903 	SET_MIB(old_ip_mib.ipOutRequests,
17904 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
17905 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
17906 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
17907 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
17908 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
17909 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
17910 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
17911 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
17912 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
17913 
17914 	/* ipRoutingDiscards is not being used */
17915 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
17916 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
17917 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
17918 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
17919 	SET_MIB(old_ip_mib.ipReasmDuplicates,
17920 	    ipmib->ipIfStatsReasmDuplicates);
17921 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
17922 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
17923 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
17924 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
17925 	SET_MIB(old_ip_mib.rawipInOverflows,
17926 	    ipmib->rawipIfStatsInOverflows);
17927 
17928 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
17929 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
17930 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
17931 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
17932 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
17933 	    ipmib->ipIfStatsOutSwitchIPVersion);
17934 
17935 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
17936 	    (int)sizeof (old_ip_mib))) {
17937 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17938 		    (uint_t)sizeof (old_ip_mib)));
17939 	}
17940 
17941 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17942 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17943 	    (int)optp->level, (int)optp->name, (int)optp->len));
17944 	qreply(q, mpctl);
17945 	return (mp2ctl);
17946 }
17947 
17948 /* Per interface IPv4 statistics */
17949 static mblk_t *
17950 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
17951 {
17952 	struct opthdr		*optp;
17953 	mblk_t			*mp2ctl;
17954 	ill_t			*ill;
17955 	ill_walk_context_t	ctx;
17956 	mblk_t			*mp_tail = NULL;
17957 	mib2_ipIfStatsEntry_t	global_ip_mib;
17958 
17959 	/*
17960 	 * Make a copy of the original message
17961 	 */
17962 	mp2ctl = copymsg(mpctl);
17963 
17964 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17965 	optp->level = MIB2_IP;
17966 	optp->name = MIB2_IP_TRAFFIC_STATS;
17967 	/* Include "unknown interface" ip_mib */
17968 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
17969 	ipst->ips_ip_mib.ipIfStatsIfIndex =
17970 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
17971 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
17972 	    (ipst->ips_ip_g_forward ? 1 : 2));
17973 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
17974 	    (uint32_t)ipst->ips_ip_def_ttl);
17975 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
17976 	    sizeof (mib2_ipIfStatsEntry_t));
17977 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
17978 	    sizeof (mib2_ipAddrEntry_t));
17979 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
17980 	    sizeof (mib2_ipRouteEntry_t));
17981 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
17982 	    sizeof (mib2_ipNetToMediaEntry_t));
17983 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
17984 	    sizeof (ip_member_t));
17985 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
17986 	    sizeof (ip_grpsrc_t));
17987 
17988 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17989 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
17990 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
17991 		    "failed to allocate %u bytes\n",
17992 		    (uint_t)sizeof (ipst->ips_ip_mib)));
17993 	}
17994 
17995 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
17996 
17997 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
17998 	ill = ILL_START_WALK_V4(&ctx, ipst);
17999 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18000 		ill->ill_ip_mib->ipIfStatsIfIndex =
18001 		    ill->ill_phyint->phyint_ifindex;
18002 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18003 		    (ipst->ips_ip_g_forward ? 1 : 2));
18004 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18005 		    (uint32_t)ipst->ips_ip_def_ttl);
18006 
18007 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18008 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18009 		    (char *)ill->ill_ip_mib,
18010 		    (int)sizeof (*ill->ill_ip_mib))) {
18011 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18012 			    "failed to allocate %u bytes\n",
18013 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18014 		}
18015 	}
18016 	rw_exit(&ipst->ips_ill_g_lock);
18017 
18018 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18019 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18020 	    "level %d, name %d, len %d\n",
18021 	    (int)optp->level, (int)optp->name, (int)optp->len));
18022 	qreply(q, mpctl);
18023 
18024 	if (mp2ctl == NULL)
18025 		return (NULL);
18026 
18027 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18028 }
18029 
18030 /* Global IPv4 ICMP statistics */
18031 static mblk_t *
18032 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18033 {
18034 	struct opthdr		*optp;
18035 	mblk_t			*mp2ctl;
18036 
18037 	/*
18038 	 * Make a copy of the original message
18039 	 */
18040 	mp2ctl = copymsg(mpctl);
18041 
18042 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18043 	optp->level = MIB2_ICMP;
18044 	optp->name = 0;
18045 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18046 	    (int)sizeof (ipst->ips_icmp_mib))) {
18047 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18048 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18049 	}
18050 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18051 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18052 	    (int)optp->level, (int)optp->name, (int)optp->len));
18053 	qreply(q, mpctl);
18054 	return (mp2ctl);
18055 }
18056 
18057 /* Global IPv4 IGMP statistics */
18058 static mblk_t *
18059 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18060 {
18061 	struct opthdr		*optp;
18062 	mblk_t			*mp2ctl;
18063 
18064 	/*
18065 	 * make a copy of the original message
18066 	 */
18067 	mp2ctl = copymsg(mpctl);
18068 
18069 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18070 	optp->level = EXPER_IGMP;
18071 	optp->name = 0;
18072 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18073 	    (int)sizeof (ipst->ips_igmpstat))) {
18074 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18075 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18076 	}
18077 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18078 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18079 	    (int)optp->level, (int)optp->name, (int)optp->len));
18080 	qreply(q, mpctl);
18081 	return (mp2ctl);
18082 }
18083 
18084 /* Global IPv4 Multicast Routing statistics */
18085 static mblk_t *
18086 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18087 {
18088 	struct opthdr		*optp;
18089 	mblk_t			*mp2ctl;
18090 
18091 	/*
18092 	 * make a copy of the original message
18093 	 */
18094 	mp2ctl = copymsg(mpctl);
18095 
18096 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18097 	optp->level = EXPER_DVMRP;
18098 	optp->name = 0;
18099 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18100 		ip0dbg(("ip_mroute_stats: failed\n"));
18101 	}
18102 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18103 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18104 	    (int)optp->level, (int)optp->name, (int)optp->len));
18105 	qreply(q, mpctl);
18106 	return (mp2ctl);
18107 }
18108 
18109 /* IPv4 address information */
18110 static mblk_t *
18111 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18112 {
18113 	struct opthdr		*optp;
18114 	mblk_t			*mp2ctl;
18115 	mblk_t			*mp_tail = NULL;
18116 	ill_t			*ill;
18117 	ipif_t			*ipif;
18118 	uint_t			bitval;
18119 	mib2_ipAddrEntry_t	mae;
18120 	zoneid_t		zoneid;
18121 	ill_walk_context_t ctx;
18122 
18123 	/*
18124 	 * make a copy of the original message
18125 	 */
18126 	mp2ctl = copymsg(mpctl);
18127 
18128 	/* ipAddrEntryTable */
18129 
18130 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18131 	optp->level = MIB2_IP;
18132 	optp->name = MIB2_IP_ADDR;
18133 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18134 
18135 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18136 	ill = ILL_START_WALK_V4(&ctx, ipst);
18137 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18138 		for (ipif = ill->ill_ipif; ipif != NULL;
18139 		    ipif = ipif->ipif_next) {
18140 			if (ipif->ipif_zoneid != zoneid &&
18141 			    ipif->ipif_zoneid != ALL_ZONES)
18142 				continue;
18143 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18144 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18145 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18146 
18147 			(void) ipif_get_name(ipif,
18148 			    mae.ipAdEntIfIndex.o_bytes,
18149 			    OCTET_LENGTH);
18150 			mae.ipAdEntIfIndex.o_length =
18151 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18152 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18153 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18154 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18155 			mae.ipAdEntInfo.ae_subnet_len =
18156 			    ip_mask_to_plen(ipif->ipif_net_mask);
18157 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18158 			for (bitval = 1;
18159 			    bitval &&
18160 			    !(bitval & ipif->ipif_brd_addr);
18161 			    bitval <<= 1)
18162 				noop;
18163 			mae.ipAdEntBcastAddr = bitval;
18164 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18165 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18166 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18167 			mae.ipAdEntInfo.ae_broadcast_addr =
18168 			    ipif->ipif_brd_addr;
18169 			mae.ipAdEntInfo.ae_pp_dst_addr =
18170 			    ipif->ipif_pp_dst_addr;
18171 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18172 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18173 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18174 
18175 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18176 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18177 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18178 				    "allocate %u bytes\n",
18179 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18180 			}
18181 		}
18182 	}
18183 	rw_exit(&ipst->ips_ill_g_lock);
18184 
18185 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18186 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18187 	    (int)optp->level, (int)optp->name, (int)optp->len));
18188 	qreply(q, mpctl);
18189 	return (mp2ctl);
18190 }
18191 
18192 /* IPv6 address information */
18193 static mblk_t *
18194 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18195 {
18196 	struct opthdr		*optp;
18197 	mblk_t			*mp2ctl;
18198 	mblk_t			*mp_tail = NULL;
18199 	ill_t			*ill;
18200 	ipif_t			*ipif;
18201 	mib2_ipv6AddrEntry_t	mae6;
18202 	zoneid_t		zoneid;
18203 	ill_walk_context_t	ctx;
18204 
18205 	/*
18206 	 * make a copy of the original message
18207 	 */
18208 	mp2ctl = copymsg(mpctl);
18209 
18210 	/* ipv6AddrEntryTable */
18211 
18212 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18213 	optp->level = MIB2_IP6;
18214 	optp->name = MIB2_IP6_ADDR;
18215 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18216 
18217 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18218 	ill = ILL_START_WALK_V6(&ctx, ipst);
18219 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18220 		for (ipif = ill->ill_ipif; ipif != NULL;
18221 		    ipif = ipif->ipif_next) {
18222 			if (ipif->ipif_zoneid != zoneid &&
18223 			    ipif->ipif_zoneid != ALL_ZONES)
18224 				continue;
18225 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18226 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18227 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18228 
18229 			(void) ipif_get_name(ipif,
18230 			    mae6.ipv6AddrIfIndex.o_bytes,
18231 			    OCTET_LENGTH);
18232 			mae6.ipv6AddrIfIndex.o_length =
18233 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18234 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18235 			mae6.ipv6AddrPfxLength =
18236 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18237 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18238 			mae6.ipv6AddrInfo.ae_subnet_len =
18239 			    mae6.ipv6AddrPfxLength;
18240 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18241 
18242 			/* Type: stateless(1), stateful(2), unknown(3) */
18243 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18244 				mae6.ipv6AddrType = 1;
18245 			else
18246 				mae6.ipv6AddrType = 2;
18247 			/* Anycast: true(1), false(2) */
18248 			if (ipif->ipif_flags & IPIF_ANYCAST)
18249 				mae6.ipv6AddrAnycastFlag = 1;
18250 			else
18251 				mae6.ipv6AddrAnycastFlag = 2;
18252 
18253 			/*
18254 			 * Address status: preferred(1), deprecated(2),
18255 			 * invalid(3), inaccessible(4), unknown(5)
18256 			 */
18257 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18258 				mae6.ipv6AddrStatus = 3;
18259 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18260 				mae6.ipv6AddrStatus = 2;
18261 			else
18262 				mae6.ipv6AddrStatus = 1;
18263 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18264 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18265 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18266 			    ipif->ipif_v6pp_dst_addr;
18267 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18268 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18269 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18270 			mae6.ipv6AddrIdentifier = ill->ill_token;
18271 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18272 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18273 			mae6.ipv6AddrRetransmitTime =
18274 			    ill->ill_reachable_retrans_time;
18275 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18276 			    (char *)&mae6,
18277 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18278 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18279 				    "allocate %u bytes\n",
18280 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18281 			}
18282 		}
18283 	}
18284 	rw_exit(&ipst->ips_ill_g_lock);
18285 
18286 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18287 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: 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 multicast group membership. */
18294 static mblk_t *
18295 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18296 {
18297 	struct opthdr		*optp;
18298 	mblk_t			*mp2ctl;
18299 	ill_t			*ill;
18300 	ipif_t			*ipif;
18301 	ilm_t			*ilm;
18302 	ip_member_t		ipm;
18303 	mblk_t			*mp_tail = NULL;
18304 	ill_walk_context_t	ctx;
18305 	zoneid_t		zoneid;
18306 
18307 	/*
18308 	 * make a copy of the original message
18309 	 */
18310 	mp2ctl = copymsg(mpctl);
18311 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18312 
18313 	/* ipGroupMember table */
18314 	optp = (struct opthdr *)&mpctl->b_rptr[
18315 	    sizeof (struct T_optmgmt_ack)];
18316 	optp->level = MIB2_IP;
18317 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
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 		ILM_WALKER_HOLD(ill);
18323 		for (ipif = ill->ill_ipif; ipif != NULL;
18324 		    ipif = ipif->ipif_next) {
18325 			if (ipif->ipif_zoneid != zoneid &&
18326 			    ipif->ipif_zoneid != ALL_ZONES)
18327 				continue;	/* not this zone */
18328 			(void) ipif_get_name(ipif,
18329 			    ipm.ipGroupMemberIfIndex.o_bytes,
18330 			    OCTET_LENGTH);
18331 			ipm.ipGroupMemberIfIndex.o_length =
18332 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18333 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18334 				ASSERT(ilm->ilm_ipif != NULL);
18335 				ASSERT(ilm->ilm_ill == NULL);
18336 				if (ilm->ilm_ipif != ipif)
18337 					continue;
18338 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18339 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18340 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18341 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18342 				    (char *)&ipm, (int)sizeof (ipm))) {
18343 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18344 					    "failed to allocate %u bytes\n",
18345 					    (uint_t)sizeof (ipm)));
18346 				}
18347 			}
18348 		}
18349 		ILM_WALKER_RELE(ill);
18350 	}
18351 	rw_exit(&ipst->ips_ill_g_lock);
18352 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18353 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18354 	    (int)optp->level, (int)optp->name, (int)optp->len));
18355 	qreply(q, mpctl);
18356 	return (mp2ctl);
18357 }
18358 
18359 /* IPv6 multicast group membership. */
18360 static mblk_t *
18361 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18362 {
18363 	struct opthdr		*optp;
18364 	mblk_t			*mp2ctl;
18365 	ill_t			*ill;
18366 	ilm_t			*ilm;
18367 	ipv6_member_t		ipm6;
18368 	mblk_t			*mp_tail = NULL;
18369 	ill_walk_context_t	ctx;
18370 	zoneid_t		zoneid;
18371 
18372 	/*
18373 	 * make a copy of the original message
18374 	 */
18375 	mp2ctl = copymsg(mpctl);
18376 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18377 
18378 	/* ip6GroupMember table */
18379 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18380 	optp->level = MIB2_IP6;
18381 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18382 
18383 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18384 	ill = ILL_START_WALK_V6(&ctx, ipst);
18385 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18386 		ILM_WALKER_HOLD(ill);
18387 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18388 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18389 			ASSERT(ilm->ilm_ipif == NULL);
18390 			ASSERT(ilm->ilm_ill != NULL);
18391 			if (ilm->ilm_zoneid != zoneid)
18392 				continue;	/* not this zone */
18393 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18394 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18395 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18396 			if (!snmp_append_data2(mpctl->b_cont,
18397 			    &mp_tail,
18398 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18399 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18400 				    "failed to allocate %u bytes\n",
18401 				    (uint_t)sizeof (ipm6)));
18402 			}
18403 		}
18404 		ILM_WALKER_RELE(ill);
18405 	}
18406 	rw_exit(&ipst->ips_ill_g_lock);
18407 
18408 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18409 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18410 	    (int)optp->level, (int)optp->name, (int)optp->len));
18411 	qreply(q, mpctl);
18412 	return (mp2ctl);
18413 }
18414 
18415 /* IP multicast filtered sources */
18416 static mblk_t *
18417 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18418 {
18419 	struct opthdr		*optp;
18420 	mblk_t			*mp2ctl;
18421 	ill_t			*ill;
18422 	ipif_t			*ipif;
18423 	ilm_t			*ilm;
18424 	ip_grpsrc_t		ips;
18425 	mblk_t			*mp_tail = NULL;
18426 	ill_walk_context_t	ctx;
18427 	zoneid_t		zoneid;
18428 	int			i;
18429 	slist_t			*sl;
18430 
18431 	/*
18432 	 * make a copy of the original message
18433 	 */
18434 	mp2ctl = copymsg(mpctl);
18435 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18436 
18437 	/* ipGroupSource table */
18438 	optp = (struct opthdr *)&mpctl->b_rptr[
18439 	    sizeof (struct T_optmgmt_ack)];
18440 	optp->level = MIB2_IP;
18441 	optp->name = EXPER_IP_GROUP_SOURCES;
18442 
18443 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18444 	ill = ILL_START_WALK_V4(&ctx, ipst);
18445 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18446 		ILM_WALKER_HOLD(ill);
18447 		for (ipif = ill->ill_ipif; ipif != NULL;
18448 		    ipif = ipif->ipif_next) {
18449 			if (ipif->ipif_zoneid != zoneid)
18450 				continue;	/* not this zone */
18451 			(void) ipif_get_name(ipif,
18452 			    ips.ipGroupSourceIfIndex.o_bytes,
18453 			    OCTET_LENGTH);
18454 			ips.ipGroupSourceIfIndex.o_length =
18455 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18456 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18457 				ASSERT(ilm->ilm_ipif != NULL);
18458 				ASSERT(ilm->ilm_ill == NULL);
18459 				sl = ilm->ilm_filter;
18460 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18461 					continue;
18462 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18463 				for (i = 0; i < sl->sl_numsrc; i++) {
18464 					if (!IN6_IS_ADDR_V4MAPPED(
18465 					    &sl->sl_addr[i]))
18466 						continue;
18467 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18468 					    ips.ipGroupSourceAddress);
18469 					if (snmp_append_data2(mpctl->b_cont,
18470 					    &mp_tail, (char *)&ips,
18471 					    (int)sizeof (ips)) == 0) {
18472 						ip1dbg(("ip_snmp_get_mib2_"
18473 						    "ip_group_src: failed to "
18474 						    "allocate %u bytes\n",
18475 						    (uint_t)sizeof (ips)));
18476 					}
18477 				}
18478 			}
18479 		}
18480 		ILM_WALKER_RELE(ill);
18481 	}
18482 	rw_exit(&ipst->ips_ill_g_lock);
18483 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18484 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18485 	    (int)optp->level, (int)optp->name, (int)optp->len));
18486 	qreply(q, mpctl);
18487 	return (mp2ctl);
18488 }
18489 
18490 /* IPv6 multicast filtered sources. */
18491 static mblk_t *
18492 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18493 {
18494 	struct opthdr		*optp;
18495 	mblk_t			*mp2ctl;
18496 	ill_t			*ill;
18497 	ilm_t			*ilm;
18498 	ipv6_grpsrc_t		ips6;
18499 	mblk_t			*mp_tail = NULL;
18500 	ill_walk_context_t	ctx;
18501 	zoneid_t		zoneid;
18502 	int			i;
18503 	slist_t			*sl;
18504 
18505 	/*
18506 	 * make a copy of the original message
18507 	 */
18508 	mp2ctl = copymsg(mpctl);
18509 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18510 
18511 	/* ip6GroupMember table */
18512 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18513 	optp->level = MIB2_IP6;
18514 	optp->name = EXPER_IP6_GROUP_SOURCES;
18515 
18516 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18517 	ill = ILL_START_WALK_V6(&ctx, ipst);
18518 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18519 		ILM_WALKER_HOLD(ill);
18520 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18521 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18522 			ASSERT(ilm->ilm_ipif == NULL);
18523 			ASSERT(ilm->ilm_ill != NULL);
18524 			sl = ilm->ilm_filter;
18525 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18526 				continue;
18527 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18528 			for (i = 0; i < sl->sl_numsrc; i++) {
18529 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18530 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18531 				    (char *)&ips6, (int)sizeof (ips6))) {
18532 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18533 					    "group_src: failed to allocate "
18534 					    "%u bytes\n",
18535 					    (uint_t)sizeof (ips6)));
18536 				}
18537 			}
18538 		}
18539 		ILM_WALKER_RELE(ill);
18540 	}
18541 	rw_exit(&ipst->ips_ill_g_lock);
18542 
18543 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18544 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18545 	    (int)optp->level, (int)optp->name, (int)optp->len));
18546 	qreply(q, mpctl);
18547 	return (mp2ctl);
18548 }
18549 
18550 /* Multicast routing virtual interface table. */
18551 static mblk_t *
18552 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18553 {
18554 	struct opthdr		*optp;
18555 	mblk_t			*mp2ctl;
18556 
18557 	/*
18558 	 * make a copy of the original message
18559 	 */
18560 	mp2ctl = copymsg(mpctl);
18561 
18562 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18563 	optp->level = EXPER_DVMRP;
18564 	optp->name = EXPER_DVMRP_VIF;
18565 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18566 		ip0dbg(("ip_mroute_vif: failed\n"));
18567 	}
18568 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18569 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18570 	    (int)optp->level, (int)optp->name, (int)optp->len));
18571 	qreply(q, mpctl);
18572 	return (mp2ctl);
18573 }
18574 
18575 /* Multicast routing table. */
18576 static mblk_t *
18577 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18578 {
18579 	struct opthdr		*optp;
18580 	mblk_t			*mp2ctl;
18581 
18582 	/*
18583 	 * make a copy of the original message
18584 	 */
18585 	mp2ctl = copymsg(mpctl);
18586 
18587 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18588 	optp->level = EXPER_DVMRP;
18589 	optp->name = EXPER_DVMRP_MRT;
18590 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18591 		ip0dbg(("ip_mroute_mrt: failed\n"));
18592 	}
18593 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18594 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18595 	    (int)optp->level, (int)optp->name, (int)optp->len));
18596 	qreply(q, mpctl);
18597 	return (mp2ctl);
18598 }
18599 
18600 /*
18601  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18602  * in one IRE walk.
18603  */
18604 static mblk_t *
18605 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18606 {
18607 	struct opthdr	*optp;
18608 	mblk_t		*mp2ctl;	/* Returned */
18609 	mblk_t		*mp3ctl;	/* nettomedia */
18610 	mblk_t		*mp4ctl;	/* routeattrs */
18611 	iproutedata_t	ird;
18612 	zoneid_t	zoneid;
18613 
18614 	/*
18615 	 * make copies of the original message
18616 	 *	- mp2ctl is returned unchanged to the caller for his use
18617 	 *	- mpctl is sent upstream as ipRouteEntryTable
18618 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18619 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18620 	 */
18621 	mp2ctl = copymsg(mpctl);
18622 	mp3ctl = copymsg(mpctl);
18623 	mp4ctl = copymsg(mpctl);
18624 	if (mp3ctl == NULL || mp4ctl == NULL) {
18625 		freemsg(mp4ctl);
18626 		freemsg(mp3ctl);
18627 		freemsg(mp2ctl);
18628 		freemsg(mpctl);
18629 		return (NULL);
18630 	}
18631 
18632 	bzero(&ird, sizeof (ird));
18633 
18634 	ird.ird_route.lp_head = mpctl->b_cont;
18635 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18636 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18637 
18638 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18639 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18640 
18641 	/* ipRouteEntryTable in mpctl */
18642 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18643 	optp->level = MIB2_IP;
18644 	optp->name = MIB2_IP_ROUTE;
18645 	optp->len = msgdsize(ird.ird_route.lp_head);
18646 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18647 	    (int)optp->level, (int)optp->name, (int)optp->len));
18648 	qreply(q, mpctl);
18649 
18650 	/* ipNetToMediaEntryTable in mp3ctl */
18651 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18652 	optp->level = MIB2_IP;
18653 	optp->name = MIB2_IP_MEDIA;
18654 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18655 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18656 	    (int)optp->level, (int)optp->name, (int)optp->len));
18657 	qreply(q, mp3ctl);
18658 
18659 	/* ipRouteAttributeTable in mp4ctl */
18660 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18661 	optp->level = MIB2_IP;
18662 	optp->name = EXPER_IP_RTATTR;
18663 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18664 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18665 	    (int)optp->level, (int)optp->name, (int)optp->len));
18666 	if (optp->len == 0)
18667 		freemsg(mp4ctl);
18668 	else
18669 		qreply(q, mp4ctl);
18670 
18671 	return (mp2ctl);
18672 }
18673 
18674 /*
18675  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18676  * ipv6NetToMediaEntryTable in an NDP walk.
18677  */
18678 static mblk_t *
18679 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18680 {
18681 	struct opthdr	*optp;
18682 	mblk_t		*mp2ctl;	/* Returned */
18683 	mblk_t		*mp3ctl;	/* nettomedia */
18684 	mblk_t		*mp4ctl;	/* routeattrs */
18685 	iproutedata_t	ird;
18686 	zoneid_t	zoneid;
18687 
18688 	/*
18689 	 * make copies of the original message
18690 	 *	- mp2ctl is returned unchanged to the caller for his use
18691 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18692 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18693 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18694 	 */
18695 	mp2ctl = copymsg(mpctl);
18696 	mp3ctl = copymsg(mpctl);
18697 	mp4ctl = copymsg(mpctl);
18698 	if (mp3ctl == NULL || mp4ctl == NULL) {
18699 		freemsg(mp4ctl);
18700 		freemsg(mp3ctl);
18701 		freemsg(mp2ctl);
18702 		freemsg(mpctl);
18703 		return (NULL);
18704 	}
18705 
18706 	bzero(&ird, sizeof (ird));
18707 
18708 	ird.ird_route.lp_head = mpctl->b_cont;
18709 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18710 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18711 
18712 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18713 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18714 
18715 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18716 	optp->level = MIB2_IP6;
18717 	optp->name = MIB2_IP6_ROUTE;
18718 	optp->len = msgdsize(ird.ird_route.lp_head);
18719 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18720 	    (int)optp->level, (int)optp->name, (int)optp->len));
18721 	qreply(q, mpctl);
18722 
18723 	/* ipv6NetToMediaEntryTable in mp3ctl */
18724 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18725 
18726 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18727 	optp->level = MIB2_IP6;
18728 	optp->name = MIB2_IP6_MEDIA;
18729 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18730 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18731 	    (int)optp->level, (int)optp->name, (int)optp->len));
18732 	qreply(q, mp3ctl);
18733 
18734 	/* ipv6RouteAttributeTable in mp4ctl */
18735 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18736 	optp->level = MIB2_IP6;
18737 	optp->name = EXPER_IP_RTATTR;
18738 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18739 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18740 	    (int)optp->level, (int)optp->name, (int)optp->len));
18741 	if (optp->len == 0)
18742 		freemsg(mp4ctl);
18743 	else
18744 		qreply(q, mp4ctl);
18745 
18746 	return (mp2ctl);
18747 }
18748 
18749 /*
18750  * IPv6 mib: One per ill
18751  */
18752 static mblk_t *
18753 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18754 {
18755 	struct opthdr		*optp;
18756 	mblk_t			*mp2ctl;
18757 	ill_t			*ill;
18758 	ill_walk_context_t	ctx;
18759 	mblk_t			*mp_tail = NULL;
18760 
18761 	/*
18762 	 * Make a copy of the original message
18763 	 */
18764 	mp2ctl = copymsg(mpctl);
18765 
18766 	/* fixed length IPv6 structure ... */
18767 
18768 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18769 	optp->level = MIB2_IP6;
18770 	optp->name = 0;
18771 	/* Include "unknown interface" ip6_mib */
18772 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
18773 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
18774 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18775 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
18776 	    ipst->ips_ipv6_forward ? 1 : 2);
18777 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
18778 	    ipst->ips_ipv6_def_hops);
18779 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
18780 	    sizeof (mib2_ipIfStatsEntry_t));
18781 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
18782 	    sizeof (mib2_ipv6AddrEntry_t));
18783 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
18784 	    sizeof (mib2_ipv6RouteEntry_t));
18785 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
18786 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18787 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
18788 	    sizeof (ipv6_member_t));
18789 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
18790 	    sizeof (ipv6_grpsrc_t));
18791 
18792 	/*
18793 	 * Synchronize 64- and 32-bit counters
18794 	 */
18795 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
18796 	    ipIfStatsHCInReceives);
18797 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
18798 	    ipIfStatsHCInDelivers);
18799 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
18800 	    ipIfStatsHCOutRequests);
18801 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
18802 	    ipIfStatsHCOutForwDatagrams);
18803 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
18804 	    ipIfStatsHCOutMcastPkts);
18805 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
18806 	    ipIfStatsHCInMcastPkts);
18807 
18808 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18809 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
18810 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18811 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
18812 	}
18813 
18814 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18815 	ill = ILL_START_WALK_V6(&ctx, ipst);
18816 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18817 		ill->ill_ip_mib->ipIfStatsIfIndex =
18818 		    ill->ill_phyint->phyint_ifindex;
18819 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18820 		    ipst->ips_ipv6_forward ? 1 : 2);
18821 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
18822 		    ill->ill_max_hops);
18823 
18824 		/*
18825 		 * Synchronize 64- and 32-bit counters
18826 		 */
18827 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
18828 		    ipIfStatsHCInReceives);
18829 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
18830 		    ipIfStatsHCInDelivers);
18831 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
18832 		    ipIfStatsHCOutRequests);
18833 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
18834 		    ipIfStatsHCOutForwDatagrams);
18835 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
18836 		    ipIfStatsHCOutMcastPkts);
18837 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
18838 		    ipIfStatsHCInMcastPkts);
18839 
18840 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18841 		    (char *)ill->ill_ip_mib,
18842 		    (int)sizeof (*ill->ill_ip_mib))) {
18843 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18844 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
18845 		}
18846 	}
18847 	rw_exit(&ipst->ips_ill_g_lock);
18848 
18849 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18850 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18851 	    (int)optp->level, (int)optp->name, (int)optp->len));
18852 	qreply(q, mpctl);
18853 	return (mp2ctl);
18854 }
18855 
18856 /*
18857  * ICMPv6 mib: One per ill
18858  */
18859 static mblk_t *
18860 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18861 {
18862 	struct opthdr		*optp;
18863 	mblk_t			*mp2ctl;
18864 	ill_t			*ill;
18865 	ill_walk_context_t	ctx;
18866 	mblk_t			*mp_tail = NULL;
18867 	/*
18868 	 * Make a copy of the original message
18869 	 */
18870 	mp2ctl = copymsg(mpctl);
18871 
18872 	/* fixed length ICMPv6 structure ... */
18873 
18874 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18875 	optp->level = MIB2_ICMP6;
18876 	optp->name = 0;
18877 	/* Include "unknown interface" icmp6_mib */
18878 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
18879 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
18880 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
18881 	    sizeof (mib2_ipv6IfIcmpEntry_t);
18882 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18883 	    (char *)&ipst->ips_icmp6_mib,
18884 	    (int)sizeof (ipst->ips_icmp6_mib))) {
18885 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18886 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
18887 	}
18888 
18889 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18890 	ill = ILL_START_WALK_V6(&ctx, ipst);
18891 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18892 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18893 		    ill->ill_phyint->phyint_ifindex;
18894 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18895 		    (char *)ill->ill_icmp6_mib,
18896 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18897 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18898 			    "%u bytes\n",
18899 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18900 		}
18901 	}
18902 	rw_exit(&ipst->ips_ill_g_lock);
18903 
18904 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18905 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18906 	    (int)optp->level, (int)optp->name, (int)optp->len));
18907 	qreply(q, mpctl);
18908 	return (mp2ctl);
18909 }
18910 
18911 /*
18912  * ire_walk routine to create both ipRouteEntryTable and
18913  * ipRouteAttributeTable in one IRE walk
18914  */
18915 static void
18916 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18917 {
18918 	ill_t				*ill;
18919 	ipif_t				*ipif;
18920 	mib2_ipRouteEntry_t		*re;
18921 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18922 	ipaddr_t			gw_addr;
18923 	tsol_ire_gw_secattr_t		*attrp;
18924 	tsol_gc_t			*gc = NULL;
18925 	tsol_gcgrp_t			*gcgrp = NULL;
18926 	uint_t				sacnt = 0;
18927 	int				i;
18928 
18929 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18930 
18931 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18932 		return;
18933 
18934 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18935 		mutex_enter(&attrp->igsa_lock);
18936 		if ((gc = attrp->igsa_gc) != NULL) {
18937 			gcgrp = gc->gc_grp;
18938 			ASSERT(gcgrp != NULL);
18939 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18940 			sacnt = 1;
18941 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18942 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18943 			gc = gcgrp->gcgrp_head;
18944 			sacnt = gcgrp->gcgrp_count;
18945 		}
18946 		mutex_exit(&attrp->igsa_lock);
18947 
18948 		/* do nothing if there's no gc to report */
18949 		if (gc == NULL) {
18950 			ASSERT(sacnt == 0);
18951 			if (gcgrp != NULL) {
18952 				/* we might as well drop the lock now */
18953 				rw_exit(&gcgrp->gcgrp_rwlock);
18954 				gcgrp = NULL;
18955 			}
18956 			attrp = NULL;
18957 		}
18958 
18959 		ASSERT(gc == NULL || (gcgrp != NULL &&
18960 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18961 	}
18962 	ASSERT(sacnt == 0 || gc != NULL);
18963 
18964 	if (sacnt != 0 &&
18965 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18966 		kmem_free(re, sizeof (*re));
18967 		rw_exit(&gcgrp->gcgrp_rwlock);
18968 		return;
18969 	}
18970 
18971 	/*
18972 	 * Return all IRE types for route table... let caller pick and choose
18973 	 */
18974 	re->ipRouteDest = ire->ire_addr;
18975 	ipif = ire->ire_ipif;
18976 	re->ipRouteIfIndex.o_length = 0;
18977 	if (ire->ire_type == IRE_CACHE) {
18978 		ill = (ill_t *)ire->ire_stq->q_ptr;
18979 		re->ipRouteIfIndex.o_length =
18980 		    ill->ill_name_length == 0 ? 0 :
18981 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18982 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18983 		    re->ipRouteIfIndex.o_length);
18984 	} else if (ipif != NULL) {
18985 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18986 		    OCTET_LENGTH);
18987 		re->ipRouteIfIndex.o_length =
18988 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18989 	}
18990 	re->ipRouteMetric1 = -1;
18991 	re->ipRouteMetric2 = -1;
18992 	re->ipRouteMetric3 = -1;
18993 	re->ipRouteMetric4 = -1;
18994 
18995 	gw_addr = ire->ire_gateway_addr;
18996 
18997 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18998 		re->ipRouteNextHop = ire->ire_src_addr;
18999 	else
19000 		re->ipRouteNextHop = gw_addr;
19001 	/* indirect(4), direct(3), or invalid(2) */
19002 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19003 		re->ipRouteType = 2;
19004 	else
19005 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19006 	re->ipRouteProto = -1;
19007 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19008 	re->ipRouteMask = ire->ire_mask;
19009 	re->ipRouteMetric5 = -1;
19010 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19011 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19012 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19013 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19014 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19015 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19016 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19017 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19018 
19019 	if (ire->ire_flags & RTF_DYNAMIC) {
19020 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19021 	} else {
19022 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19023 	}
19024 
19025 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19026 	    (char *)re, (int)sizeof (*re))) {
19027 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19028 		    (uint_t)sizeof (*re)));
19029 	}
19030 
19031 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19032 		iaeptr->iae_routeidx = ird->ird_idx;
19033 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19034 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19035 	}
19036 
19037 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19038 	    (char *)iae, sacnt * sizeof (*iae))) {
19039 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19040 		    (unsigned)(sacnt * sizeof (*iae))));
19041 	}
19042 
19043 	/* bump route index for next pass */
19044 	ird->ird_idx++;
19045 
19046 	kmem_free(re, sizeof (*re));
19047 	if (sacnt != 0)
19048 		kmem_free(iae, sacnt * sizeof (*iae));
19049 
19050 	if (gcgrp != NULL)
19051 		rw_exit(&gcgrp->gcgrp_rwlock);
19052 }
19053 
19054 /*
19055  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19056  */
19057 static void
19058 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19059 {
19060 	ill_t				*ill;
19061 	ipif_t				*ipif;
19062 	mib2_ipv6RouteEntry_t		*re;
19063 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19064 	in6_addr_t			gw_addr_v6;
19065 	tsol_ire_gw_secattr_t		*attrp;
19066 	tsol_gc_t			*gc = NULL;
19067 	tsol_gcgrp_t			*gcgrp = NULL;
19068 	uint_t				sacnt = 0;
19069 	int				i;
19070 
19071 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19072 
19073 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19074 		return;
19075 
19076 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19077 		mutex_enter(&attrp->igsa_lock);
19078 		if ((gc = attrp->igsa_gc) != NULL) {
19079 			gcgrp = gc->gc_grp;
19080 			ASSERT(gcgrp != NULL);
19081 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19082 			sacnt = 1;
19083 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19084 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19085 			gc = gcgrp->gcgrp_head;
19086 			sacnt = gcgrp->gcgrp_count;
19087 		}
19088 		mutex_exit(&attrp->igsa_lock);
19089 
19090 		/* do nothing if there's no gc to report */
19091 		if (gc == NULL) {
19092 			ASSERT(sacnt == 0);
19093 			if (gcgrp != NULL) {
19094 				/* we might as well drop the lock now */
19095 				rw_exit(&gcgrp->gcgrp_rwlock);
19096 				gcgrp = NULL;
19097 			}
19098 			attrp = NULL;
19099 		}
19100 
19101 		ASSERT(gc == NULL || (gcgrp != NULL &&
19102 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19103 	}
19104 	ASSERT(sacnt == 0 || gc != NULL);
19105 
19106 	if (sacnt != 0 &&
19107 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19108 		kmem_free(re, sizeof (*re));
19109 		rw_exit(&gcgrp->gcgrp_rwlock);
19110 		return;
19111 	}
19112 
19113 	/*
19114 	 * Return all IRE types for route table... let caller pick and choose
19115 	 */
19116 	re->ipv6RouteDest = ire->ire_addr_v6;
19117 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19118 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19119 	re->ipv6RouteIfIndex.o_length = 0;
19120 	ipif = ire->ire_ipif;
19121 	if (ire->ire_type == IRE_CACHE) {
19122 		ill = (ill_t *)ire->ire_stq->q_ptr;
19123 		re->ipv6RouteIfIndex.o_length =
19124 		    ill->ill_name_length == 0 ? 0 :
19125 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19126 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19127 		    re->ipv6RouteIfIndex.o_length);
19128 	} else if (ipif != NULL) {
19129 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19130 		    OCTET_LENGTH);
19131 		re->ipv6RouteIfIndex.o_length =
19132 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19133 	}
19134 
19135 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19136 
19137 	mutex_enter(&ire->ire_lock);
19138 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19139 	mutex_exit(&ire->ire_lock);
19140 
19141 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19142 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19143 	else
19144 		re->ipv6RouteNextHop = gw_addr_v6;
19145 
19146 	/* remote(4), local(3), or discard(2) */
19147 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19148 		re->ipv6RouteType = 2;
19149 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19150 		re->ipv6RouteType = 3;
19151 	else
19152 		re->ipv6RouteType = 4;
19153 
19154 	re->ipv6RouteProtocol	= -1;
19155 	re->ipv6RoutePolicy	= 0;
19156 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19157 	re->ipv6RouteNextHopRDI	= 0;
19158 	re->ipv6RouteWeight	= 0;
19159 	re->ipv6RouteMetric	= 0;
19160 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19161 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19162 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19163 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19164 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19165 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19166 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19167 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19168 
19169 	if (ire->ire_flags & RTF_DYNAMIC) {
19170 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19171 	} else {
19172 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19173 	}
19174 
19175 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19176 	    (char *)re, (int)sizeof (*re))) {
19177 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19178 		    (uint_t)sizeof (*re)));
19179 	}
19180 
19181 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19182 		iaeptr->iae_routeidx = ird->ird_idx;
19183 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19184 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19185 	}
19186 
19187 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19188 	    (char *)iae, sacnt * sizeof (*iae))) {
19189 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19190 		    (unsigned)(sacnt * sizeof (*iae))));
19191 	}
19192 
19193 	/* bump route index for next pass */
19194 	ird->ird_idx++;
19195 
19196 	kmem_free(re, sizeof (*re));
19197 	if (sacnt != 0)
19198 		kmem_free(iae, sacnt * sizeof (*iae));
19199 
19200 	if (gcgrp != NULL)
19201 		rw_exit(&gcgrp->gcgrp_rwlock);
19202 }
19203 
19204 /*
19205  * ndp_walk routine to create ipv6NetToMediaEntryTable
19206  */
19207 static int
19208 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19209 {
19210 	ill_t				*ill;
19211 	mib2_ipv6NetToMediaEntry_t	ntme;
19212 	dl_unitdata_req_t		*dl;
19213 
19214 	ill = nce->nce_ill;
19215 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19216 		return (0);
19217 
19218 	/*
19219 	 * Neighbor cache entry attached to IRE with on-link
19220 	 * destination.
19221 	 */
19222 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19223 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19224 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19225 	    (nce->nce_res_mp != NULL)) {
19226 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19227 		ntme.ipv6NetToMediaPhysAddress.o_length =
19228 		    dl->dl_dest_addr_length;
19229 	} else {
19230 		ntme.ipv6NetToMediaPhysAddress.o_length =
19231 		    ill->ill_phys_addr_length;
19232 	}
19233 	if (nce->nce_res_mp != NULL) {
19234 		bcopy((char *)nce->nce_res_mp->b_rptr +
19235 		    NCE_LL_ADDR_OFFSET(ill),
19236 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19237 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19238 	} else {
19239 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19240 		    ill->ill_phys_addr_length);
19241 	}
19242 	/*
19243 	 * Note: Returns ND_* states. Should be:
19244 	 * reachable(1), stale(2), delay(3), probe(4),
19245 	 * invalid(5), unknown(6)
19246 	 */
19247 	ntme.ipv6NetToMediaState = nce->nce_state;
19248 	ntme.ipv6NetToMediaLastUpdated = 0;
19249 
19250 	/* other(1), dynamic(2), static(3), local(4) */
19251 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19252 		ntme.ipv6NetToMediaType = 4;
19253 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19254 		ntme.ipv6NetToMediaType = 1;
19255 	} else {
19256 		ntme.ipv6NetToMediaType = 2;
19257 	}
19258 
19259 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19260 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19261 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19262 		    (uint_t)sizeof (ntme)));
19263 	}
19264 	return (0);
19265 }
19266 
19267 /*
19268  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19269  */
19270 /* ARGSUSED */
19271 int
19272 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19273 {
19274 	switch (level) {
19275 	case MIB2_IP:
19276 	case MIB2_ICMP:
19277 		switch (name) {
19278 		default:
19279 			break;
19280 		}
19281 		return (1);
19282 	default:
19283 		return (1);
19284 	}
19285 }
19286 
19287 /*
19288  * When there exists both a 64- and 32-bit counter of a particular type
19289  * (i.e., InReceives), only the 64-bit counters are added.
19290  */
19291 void
19292 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19293 {
19294 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19295 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19296 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19297 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19298 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19299 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19300 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19301 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19302 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19303 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19304 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19305 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19306 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19307 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19308 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19309 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19310 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19311 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19312 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19313 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19314 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19315 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19316 	    o2->ipIfStatsInWrongIPVersion);
19317 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19318 	    o2->ipIfStatsInWrongIPVersion);
19319 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19320 	    o2->ipIfStatsOutSwitchIPVersion);
19321 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19322 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19323 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19324 	    o2->ipIfStatsHCInForwDatagrams);
19325 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19326 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19327 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19328 	    o2->ipIfStatsHCOutForwDatagrams);
19329 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19330 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19331 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19332 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19333 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19334 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19335 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19336 	    o2->ipIfStatsHCOutMcastOctets);
19337 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19338 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19339 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19340 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19341 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19342 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19343 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19344 }
19345 
19346 void
19347 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19348 {
19349 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19350 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19351 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19352 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19353 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19354 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19355 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19356 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19357 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19358 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19359 	    o2->ipv6IfIcmpInRouterSolicits);
19360 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19361 	    o2->ipv6IfIcmpInRouterAdvertisements);
19362 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19363 	    o2->ipv6IfIcmpInNeighborSolicits);
19364 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19365 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19366 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19367 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19368 	    o2->ipv6IfIcmpInGroupMembQueries);
19369 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19370 	    o2->ipv6IfIcmpInGroupMembResponses);
19371 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19372 	    o2->ipv6IfIcmpInGroupMembReductions);
19373 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19374 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19375 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19376 	    o2->ipv6IfIcmpOutDestUnreachs);
19377 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19378 	    o2->ipv6IfIcmpOutAdminProhibs);
19379 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19380 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19381 	    o2->ipv6IfIcmpOutParmProblems);
19382 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19383 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19384 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19385 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19386 	    o2->ipv6IfIcmpOutRouterSolicits);
19387 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19388 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19389 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19390 	    o2->ipv6IfIcmpOutNeighborSolicits);
19391 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19392 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19393 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19394 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19395 	    o2->ipv6IfIcmpOutGroupMembQueries);
19396 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19397 	    o2->ipv6IfIcmpOutGroupMembResponses);
19398 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19399 	    o2->ipv6IfIcmpOutGroupMembReductions);
19400 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19401 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19402 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19403 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19404 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19405 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19406 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19407 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19408 	    o2->ipv6IfIcmpInGroupMembTotal);
19409 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19410 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19411 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19412 	    o2->ipv6IfIcmpInGroupMembBadReports);
19413 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19414 	    o2->ipv6IfIcmpInGroupMembOurReports);
19415 }
19416 
19417 /*
19418  * Called before the options are updated to check if this packet will
19419  * be source routed from here.
19420  * This routine assumes that the options are well formed i.e. that they
19421  * have already been checked.
19422  */
19423 static boolean_t
19424 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19425 {
19426 	ipoptp_t	opts;
19427 	uchar_t		*opt;
19428 	uint8_t		optval;
19429 	uint8_t		optlen;
19430 	ipaddr_t	dst;
19431 	ire_t		*ire;
19432 
19433 	if (IS_SIMPLE_IPH(ipha)) {
19434 		ip2dbg(("not source routed\n"));
19435 		return (B_FALSE);
19436 	}
19437 	dst = ipha->ipha_dst;
19438 	for (optval = ipoptp_first(&opts, ipha);
19439 	    optval != IPOPT_EOL;
19440 	    optval = ipoptp_next(&opts)) {
19441 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19442 		opt = opts.ipoptp_cur;
19443 		optlen = opts.ipoptp_len;
19444 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19445 		    optval, optlen));
19446 		switch (optval) {
19447 			uint32_t off;
19448 		case IPOPT_SSRR:
19449 		case IPOPT_LSRR:
19450 			/*
19451 			 * If dst is one of our addresses and there are some
19452 			 * entries left in the source route return (true).
19453 			 */
19454 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19455 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19456 			if (ire == NULL) {
19457 				ip2dbg(("ip_source_routed: not next"
19458 				    " source route 0x%x\n",
19459 				    ntohl(dst)));
19460 				return (B_FALSE);
19461 			}
19462 			ire_refrele(ire);
19463 			off = opt[IPOPT_OFFSET];
19464 			off--;
19465 			if (optlen < IP_ADDR_LEN ||
19466 			    off > optlen - IP_ADDR_LEN) {
19467 				/* End of source route */
19468 				ip1dbg(("ip_source_routed: end of SR\n"));
19469 				return (B_FALSE);
19470 			}
19471 			return (B_TRUE);
19472 		}
19473 	}
19474 	ip2dbg(("not source routed\n"));
19475 	return (B_FALSE);
19476 }
19477 
19478 /*
19479  * Check if the packet contains any source route.
19480  */
19481 static boolean_t
19482 ip_source_route_included(ipha_t *ipha)
19483 {
19484 	ipoptp_t	opts;
19485 	uint8_t		optval;
19486 
19487 	if (IS_SIMPLE_IPH(ipha))
19488 		return (B_FALSE);
19489 	for (optval = ipoptp_first(&opts, ipha);
19490 	    optval != IPOPT_EOL;
19491 	    optval = ipoptp_next(&opts)) {
19492 		switch (optval) {
19493 		case IPOPT_SSRR:
19494 		case IPOPT_LSRR:
19495 			return (B_TRUE);
19496 		}
19497 	}
19498 	return (B_FALSE);
19499 }
19500 
19501 /*
19502  * Called when the IRE expiration timer fires.
19503  */
19504 void
19505 ip_trash_timer_expire(void *args)
19506 {
19507 	int			flush_flag = 0;
19508 	ire_expire_arg_t	iea;
19509 	ip_stack_t		*ipst = (ip_stack_t *)args;
19510 
19511 	iea.iea_ipst = ipst;	/* No netstack_hold */
19512 
19513 	/*
19514 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19515 	 * This lock makes sure that a new invocation of this function
19516 	 * that occurs due to an almost immediate timer firing will not
19517 	 * progress beyond this point until the current invocation is done
19518 	 */
19519 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19520 	ipst->ips_ip_ire_expire_id = 0;
19521 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19522 
19523 	/* Periodic timer */
19524 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19525 	    ipst->ips_ip_ire_arp_interval) {
19526 		/*
19527 		 * Remove all IRE_CACHE entries since they might
19528 		 * contain arp information.
19529 		 */
19530 		flush_flag |= FLUSH_ARP_TIME;
19531 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19532 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19533 	}
19534 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19535 	    ipst->ips_ip_ire_redir_interval) {
19536 		/* Remove all redirects */
19537 		flush_flag |= FLUSH_REDIRECT_TIME;
19538 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19539 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19540 	}
19541 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19542 	    ipst->ips_ip_ire_pathmtu_interval) {
19543 		/* Increase path mtu */
19544 		flush_flag |= FLUSH_MTU_TIME;
19545 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19546 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19547 	}
19548 
19549 	/*
19550 	 * Optimize for the case when there are no redirects in the
19551 	 * ftable, that is, no need to walk the ftable in that case.
19552 	 */
19553 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19554 		iea.iea_flush_flag = flush_flag;
19555 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19556 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19557 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19558 		    NULL, ALL_ZONES, ipst);
19559 	}
19560 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19561 	    ipst->ips_ip_redirect_cnt > 0) {
19562 		iea.iea_flush_flag = flush_flag;
19563 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19564 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19565 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19566 	}
19567 	if (flush_flag & FLUSH_MTU_TIME) {
19568 		/*
19569 		 * Walk all IPv6 IRE's and update them
19570 		 * Note that ARP and redirect timers are not
19571 		 * needed since NUD handles stale entries.
19572 		 */
19573 		flush_flag = FLUSH_MTU_TIME;
19574 		iea.iea_flush_flag = flush_flag;
19575 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19576 		    ALL_ZONES, ipst);
19577 	}
19578 
19579 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19580 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19581 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19582 
19583 	/*
19584 	 * Hold the lock to serialize timeout calls and prevent
19585 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19586 	 * for the timer to fire and a new invocation of this function
19587 	 * to start before the return value of timeout has been stored
19588 	 * in ip_ire_expire_id by the current invocation.
19589 	 */
19590 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19591 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19592 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19593 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19594 }
19595 
19596 /*
19597  * Called by the memory allocator subsystem directly, when the system
19598  * is running low on memory.
19599  */
19600 /* ARGSUSED */
19601 void
19602 ip_trash_ire_reclaim(void *args)
19603 {
19604 	netstack_handle_t nh;
19605 	netstack_t *ns;
19606 
19607 	netstack_next_init(&nh);
19608 	while ((ns = netstack_next(&nh)) != NULL) {
19609 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19610 		netstack_rele(ns);
19611 	}
19612 	netstack_next_fini(&nh);
19613 }
19614 
19615 static void
19616 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19617 {
19618 	ire_cache_count_t icc;
19619 	ire_cache_reclaim_t icr;
19620 	ncc_cache_count_t ncc;
19621 	nce_cache_reclaim_t ncr;
19622 	uint_t delete_cnt;
19623 	/*
19624 	 * Memory reclaim call back.
19625 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19626 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19627 	 * entries, determine what fraction to free for
19628 	 * each category of IRE_CACHE entries giving absolute priority
19629 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19630 	 * entry will be freed unless all offlink entries are freed).
19631 	 */
19632 	icc.icc_total = 0;
19633 	icc.icc_unused = 0;
19634 	icc.icc_offlink = 0;
19635 	icc.icc_pmtu = 0;
19636 	icc.icc_onlink = 0;
19637 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19638 
19639 	/*
19640 	 * Free NCEs for IPv6 like the onlink ires.
19641 	 */
19642 	ncc.ncc_total = 0;
19643 	ncc.ncc_host = 0;
19644 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19645 
19646 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19647 	    icc.icc_pmtu + icc.icc_onlink);
19648 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19649 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19650 	if (delete_cnt == 0)
19651 		return;
19652 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19653 	/* Always delete all unused offlink entries */
19654 	icr.icr_ipst = ipst;
19655 	icr.icr_unused = 1;
19656 	if (delete_cnt <= icc.icc_unused) {
19657 		/*
19658 		 * Only need to free unused entries.  In other words,
19659 		 * there are enough unused entries to free to meet our
19660 		 * target number of freed ire cache entries.
19661 		 */
19662 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19663 		ncr.ncr_host = 0;
19664 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19665 		/*
19666 		 * Only need to free unused entries, plus a fraction of offlink
19667 		 * entries.  It follows from the first if statement that
19668 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19669 		 */
19670 		delete_cnt -= icc.icc_unused;
19671 		/* Round up # deleted by truncating fraction */
19672 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19673 		icr.icr_pmtu = icr.icr_onlink = 0;
19674 		ncr.ncr_host = 0;
19675 	} else if (delete_cnt <=
19676 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19677 		/*
19678 		 * Free all unused and offlink entries, plus a fraction of
19679 		 * pmtu entries.  It follows from the previous if statement
19680 		 * that icc_pmtu is non-zero, and that
19681 		 * delete_cnt != icc_unused + icc_offlink.
19682 		 */
19683 		icr.icr_offlink = 1;
19684 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19685 		/* Round up # deleted by truncating fraction */
19686 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19687 		icr.icr_onlink = 0;
19688 		ncr.ncr_host = 0;
19689 	} else {
19690 		/*
19691 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19692 		 * of onlink entries.  If we're here, then we know that
19693 		 * icc_onlink is non-zero, and that
19694 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19695 		 */
19696 		icr.icr_offlink = icr.icr_pmtu = 1;
19697 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19698 		    icc.icc_pmtu;
19699 		/* Round up # deleted by truncating fraction */
19700 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19701 		/* Using the same delete fraction as for onlink IREs */
19702 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19703 	}
19704 #ifdef DEBUG
19705 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19706 	    "fractions %d/%d/%d/%d\n",
19707 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19708 	    icc.icc_unused, icc.icc_offlink,
19709 	    icc.icc_pmtu, icc.icc_onlink,
19710 	    icr.icr_unused, icr.icr_offlink,
19711 	    icr.icr_pmtu, icr.icr_onlink));
19712 #endif
19713 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19714 	if (ncr.ncr_host != 0)
19715 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19716 		    (uchar_t *)&ncr, ipst);
19717 #ifdef DEBUG
19718 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19719 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19720 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19721 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19722 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19723 	    icc.icc_pmtu, icc.icc_onlink));
19724 #endif
19725 }
19726 
19727 /*
19728  * ip_unbind is called when a copy of an unbind request is received from the
19729  * upper level protocol.  We remove this conn from any fanout hash list it is
19730  * on, and zero out the bind information.  No reply is expected up above.
19731  */
19732 mblk_t *
19733 ip_unbind(queue_t *q, mblk_t *mp)
19734 {
19735 	conn_t	*connp = Q_TO_CONN(q);
19736 
19737 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19738 
19739 	if (is_system_labeled() && connp->conn_anon_port) {
19740 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19741 		    connp->conn_mlp_type, connp->conn_ulp,
19742 		    ntohs(connp->conn_lport), B_FALSE);
19743 		connp->conn_anon_port = 0;
19744 	}
19745 	connp->conn_mlp_type = mlptSingle;
19746 
19747 	ipcl_hash_remove(connp);
19748 
19749 	ASSERT(mp->b_cont == NULL);
19750 	/*
19751 	 * Convert mp into a T_OK_ACK
19752 	 */
19753 	mp = mi_tpi_ok_ack_alloc(mp);
19754 
19755 	/*
19756 	 * should not happen in practice... T_OK_ACK is smaller than the
19757 	 * original message.
19758 	 */
19759 	if (mp == NULL)
19760 		return (NULL);
19761 
19762 	/*
19763 	 * Don't bzero the ports if its TCP since TCP still needs the
19764 	 * lport to remove it from its own bind hash. TCP will do the
19765 	 * cleanup.
19766 	 */
19767 	if (!IPCL_IS_TCP(connp))
19768 		bzero(&connp->u_port, sizeof (connp->u_port));
19769 
19770 	return (mp);
19771 }
19772 
19773 /*
19774  * Write side put procedure.  Outbound data, IOCTLs, responses from
19775  * resolvers, etc, come down through here.
19776  *
19777  * arg2 is always a queue_t *.
19778  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19779  * the zoneid.
19780  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19781  */
19782 void
19783 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19784 {
19785 	ip_output_options(arg, mp, arg2, caller, &zero_info);
19786 }
19787 
19788 void
19789 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
19790     ip_opt_info_t *infop)
19791 {
19792 	conn_t		*connp = NULL;
19793 	queue_t		*q = (queue_t *)arg2;
19794 	ipha_t		*ipha;
19795 #define	rptr	((uchar_t *)ipha)
19796 	ire_t		*ire = NULL;
19797 	ire_t		*sctp_ire = NULL;
19798 	uint32_t	v_hlen_tos_len;
19799 	ipaddr_t	dst;
19800 	mblk_t		*first_mp = NULL;
19801 	boolean_t	mctl_present;
19802 	ipsec_out_t	*io;
19803 	int		match_flags;
19804 	ill_t		*attach_ill = NULL;
19805 					/* Bind to IPIF_NOFAILOVER ill etc. */
19806 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19807 	ipif_t		*dst_ipif;
19808 	boolean_t	multirt_need_resolve = B_FALSE;
19809 	mblk_t		*copy_mp = NULL;
19810 	int		err;
19811 	zoneid_t	zoneid;
19812 	int	adjust;
19813 	uint16_t iplen;
19814 	boolean_t	need_decref = B_FALSE;
19815 	boolean_t	ignore_dontroute = B_FALSE;
19816 	boolean_t	ignore_nexthop = B_FALSE;
19817 	boolean_t	ip_nexthop = B_FALSE;
19818 	ipaddr_t	nexthop_addr;
19819 	ip_stack_t	*ipst;
19820 
19821 #ifdef	_BIG_ENDIAN
19822 #define	V_HLEN	(v_hlen_tos_len >> 24)
19823 #else
19824 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19825 #endif
19826 
19827 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19828 	    "ip_wput_start: q %p", q);
19829 
19830 	/*
19831 	 * ip_wput fast path
19832 	 */
19833 
19834 	/* is packet from ARP ? */
19835 	if (q->q_next != NULL) {
19836 		zoneid = (zoneid_t)(uintptr_t)arg;
19837 		goto qnext;
19838 	}
19839 
19840 	connp = (conn_t *)arg;
19841 	ASSERT(connp != NULL);
19842 	zoneid = connp->conn_zoneid;
19843 	ipst = connp->conn_netstack->netstack_ip;
19844 
19845 	/* is queue flow controlled? */
19846 	if ((q->q_first != NULL || connp->conn_draining) &&
19847 	    (caller == IP_WPUT)) {
19848 		ASSERT(!need_decref);
19849 		(void) putq(q, mp);
19850 		return;
19851 	}
19852 
19853 	/* Multidata transmit? */
19854 	if (DB_TYPE(mp) == M_MULTIDATA) {
19855 		/*
19856 		 * We should never get here, since all Multidata messages
19857 		 * originating from tcp should have been directed over to
19858 		 * tcp_multisend() in the first place.
19859 		 */
19860 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
19861 		freemsg(mp);
19862 		return;
19863 	} else if (DB_TYPE(mp) != M_DATA)
19864 		goto notdata;
19865 
19866 	if (mp->b_flag & MSGHASREF) {
19867 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19868 		mp->b_flag &= ~MSGHASREF;
19869 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19870 		need_decref = B_TRUE;
19871 	}
19872 	ipha = (ipha_t *)mp->b_rptr;
19873 
19874 	/* is IP header non-aligned or mblk smaller than basic IP header */
19875 #ifndef SAFETY_BEFORE_SPEED
19876 	if (!OK_32PTR(rptr) ||
19877 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19878 		goto hdrtoosmall;
19879 #endif
19880 
19881 	ASSERT(OK_32PTR(ipha));
19882 
19883 	/*
19884 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19885 	 * wrong version, we'll catch it again in ip_output_v6.
19886 	 *
19887 	 * Note that this is *only* locally-generated output here, and never
19888 	 * forwarded data, and that we need to deal only with transports that
19889 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19890 	 * label.)
19891 	 */
19892 	if (is_system_labeled() &&
19893 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19894 	    !connp->conn_ulp_labeled) {
19895 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19896 		    connp->conn_mac_exempt, ipst);
19897 		ipha = (ipha_t *)mp->b_rptr;
19898 		if (err != 0) {
19899 			first_mp = mp;
19900 			if (err == EINVAL)
19901 				goto icmp_parameter_problem;
19902 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19903 			goto discard_pkt;
19904 		}
19905 		iplen = ntohs(ipha->ipha_length) + adjust;
19906 		ipha->ipha_length = htons(iplen);
19907 	}
19908 
19909 	ASSERT(infop != NULL);
19910 
19911 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
19912 		/*
19913 		 * IP_PKTINFO ancillary option is present.
19914 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
19915 		 * allows using address of any zone as the source address.
19916 		 */
19917 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
19918 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
19919 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
19920 		if (ire == NULL)
19921 			goto drop_pkt;
19922 		ire_refrele(ire);
19923 		ire = NULL;
19924 	}
19925 
19926 	/*
19927 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
19928 	 * ill index passed in IP_PKTINFO.
19929 	 */
19930 	if (infop->ip_opt_ill_index != 0 &&
19931 	    connp->conn_xmit_if_ill == NULL &&
19932 	    connp->conn_nofailover_ill == NULL) {
19933 
19934 		xmit_ill = ill_lookup_on_ifindex(
19935 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
19936 		    ipst);
19937 
19938 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
19939 			goto drop_pkt;
19940 		/*
19941 		 * check that there is an ipif belonging
19942 		 * to our zone. IPCL_ZONEID is not used because
19943 		 * IP_ALLZONES option is valid only when the ill is
19944 		 * accessible from all zones i.e has a valid ipif in
19945 		 * all zones.
19946 		 */
19947 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
19948 			goto drop_pkt;
19949 		}
19950 	}
19951 
19952 	/*
19953 	 * If there is a policy, try to attach an ipsec_out in
19954 	 * the front. At the end, first_mp either points to a
19955 	 * M_DATA message or IPSEC_OUT message linked to a
19956 	 * M_DATA message. We have to do it now as we might
19957 	 * lose the "conn" if we go through ip_newroute.
19958 	 */
19959 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19960 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
19961 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
19962 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
19963 			if (need_decref)
19964 				CONN_DEC_REF(connp);
19965 			return;
19966 		} else {
19967 			ASSERT(mp->b_datap->db_type == M_CTL);
19968 			first_mp = mp;
19969 			mp = mp->b_cont;
19970 			mctl_present = B_TRUE;
19971 		}
19972 	} else {
19973 		first_mp = mp;
19974 		mctl_present = B_FALSE;
19975 	}
19976 
19977 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19978 
19979 	/* is wrong version or IP options present */
19980 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19981 		goto version_hdrlen_check;
19982 	dst = ipha->ipha_dst;
19983 
19984 	if (connp->conn_nofailover_ill != NULL) {
19985 		attach_ill = conn_get_held_ill(connp,
19986 		    &connp->conn_nofailover_ill, &err);
19987 		if (err == ILL_LOOKUP_FAILED) {
19988 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
19989 			if (need_decref)
19990 				CONN_DEC_REF(connp);
19991 			freemsg(first_mp);
19992 			return;
19993 		}
19994 	}
19995 
19996 
19997 	/* is packet multicast? */
19998 	if (CLASSD(dst))
19999 		goto multicast;
20000 
20001 	/*
20002 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20003 	 * takes precedence over conn_dontroute and conn_nexthop_set
20004 	 */
20005 	if (xmit_ill != NULL) {
20006 		goto send_from_ill;
20007 	}
20008 
20009 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20010 	    (connp->conn_nexthop_set)) {
20011 		/*
20012 		 * If the destination is a broadcast or a loopback
20013 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20014 		 * through the standard path. But in the case of local
20015 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20016 		 * the standard path not IP_XMIT_IF.
20017 		 */
20018 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20019 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20020 		    (ire->ire_type != IRE_LOOPBACK))) {
20021 			if ((connp->conn_dontroute ||
20022 			    connp->conn_nexthop_set) && (ire != NULL) &&
20023 			    (ire->ire_type == IRE_LOCAL))
20024 				goto standard_path;
20025 
20026 			if (ire != NULL) {
20027 				ire_refrele(ire);
20028 				/* No more access to ire */
20029 				ire = NULL;
20030 			}
20031 			/*
20032 			 * bypass routing checks and go directly to
20033 			 * interface.
20034 			 */
20035 			if (connp->conn_dontroute) {
20036 				goto dontroute;
20037 			} else if (connp->conn_nexthop_set) {
20038 				ip_nexthop = B_TRUE;
20039 				nexthop_addr = connp->conn_nexthop_v4;
20040 				goto send_from_ill;
20041 			}
20042 
20043 			/*
20044 			 * If IP_XMIT_IF socket option is set,
20045 			 * then we allow unicast and multicast
20046 			 * packets to go through the ill. It is
20047 			 * quite possible that the destination
20048 			 * is not in the ire cache table and we
20049 			 * do not want to go to ip_newroute()
20050 			 * instead we call ip_newroute_ipif.
20051 			 */
20052 			xmit_ill = conn_get_held_ill(connp,
20053 			    &connp->conn_xmit_if_ill, &err);
20054 			if (err == ILL_LOOKUP_FAILED) {
20055 				BUMP_MIB(&ipst->ips_ip_mib,
20056 				    ipIfStatsOutDiscards);
20057 				if (attach_ill != NULL)
20058 					ill_refrele(attach_ill);
20059 				if (need_decref)
20060 					CONN_DEC_REF(connp);
20061 				freemsg(first_mp);
20062 				return;
20063 			}
20064 			goto send_from_ill;
20065 		}
20066 standard_path:
20067 		/* Must be a broadcast, a loopback or a local ire */
20068 		if (ire != NULL) {
20069 			ire_refrele(ire);
20070 			/* No more access to ire */
20071 			ire = NULL;
20072 		}
20073 	}
20074 
20075 	if (attach_ill != NULL)
20076 		goto send_from_ill;
20077 
20078 	/*
20079 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20080 	 * this for the tcp global queue and listen end point
20081 	 * as it does not really have a real destination to
20082 	 * talk to.  This is also true for SCTP.
20083 	 */
20084 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20085 	    !connp->conn_fully_bound) {
20086 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20087 		if (ire == NULL)
20088 			goto noirefound;
20089 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20090 		    "ip_wput_end: q %p (%S)", q, "end");
20091 
20092 		/*
20093 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20094 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20095 		 */
20096 		if (ire->ire_flags & RTF_MULTIRT) {
20097 
20098 			/*
20099 			 * Force the TTL of multirouted packets if required.
20100 			 * The TTL of such packets is bounded by the
20101 			 * ip_multirt_ttl ndd variable.
20102 			 */
20103 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20104 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20105 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20106 				    "(was %d), dst 0x%08x\n",
20107 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20108 				    ntohl(ire->ire_addr)));
20109 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20110 			}
20111 			/*
20112 			 * We look at this point if there are pending
20113 			 * unresolved routes. ire_multirt_resolvable()
20114 			 * checks in O(n) that all IRE_OFFSUBNET ire
20115 			 * entries for the packet's destination and
20116 			 * flagged RTF_MULTIRT are currently resolved.
20117 			 * If some remain unresolved, we make a copy
20118 			 * of the current message. It will be used
20119 			 * to initiate additional route resolutions.
20120 			 */
20121 			multirt_need_resolve =
20122 			    ire_multirt_need_resolve(ire->ire_addr,
20123 			    MBLK_GETLABEL(first_mp), ipst);
20124 			ip2dbg(("ip_wput[TCP]: ire %p, "
20125 			    "multirt_need_resolve %d, first_mp %p\n",
20126 			    (void *)ire, multirt_need_resolve,
20127 			    (void *)first_mp));
20128 			if (multirt_need_resolve) {
20129 				copy_mp = copymsg(first_mp);
20130 				if (copy_mp != NULL) {
20131 					MULTIRT_DEBUG_TAG(copy_mp);
20132 				}
20133 			}
20134 		}
20135 
20136 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20137 
20138 		/*
20139 		 * Try to resolve another multiroute if
20140 		 * ire_multirt_need_resolve() deemed it necessary.
20141 		 */
20142 		if (copy_mp != NULL)
20143 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20144 		if (need_decref)
20145 			CONN_DEC_REF(connp);
20146 		return;
20147 	}
20148 
20149 	/*
20150 	 * Access to conn_ire_cache. (protected by conn_lock)
20151 	 *
20152 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20153 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20154 	 * send a packet or two with the IRE_CACHE that is going away.
20155 	 * Access to the ire requires an ire refhold on the ire prior to
20156 	 * its use since an interface unplumb thread may delete the cached
20157 	 * ire and release the refhold at any time.
20158 	 *
20159 	 * Caching an ire in the conn_ire_cache
20160 	 *
20161 	 * o Caching an ire pointer in the conn requires a strict check for
20162 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20163 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20164 	 * in the conn is done after making sure under the bucket lock that the
20165 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20166 	 * caching an ire after the unplumb thread has cleaned up the conn.
20167 	 * If the conn does not send a packet subsequently the unplumb thread
20168 	 * will be hanging waiting for the ire count to drop to zero.
20169 	 *
20170 	 * o We also need to atomically test for a null conn_ire_cache and
20171 	 * set the conn_ire_cache under the the protection of the conn_lock
20172 	 * to avoid races among concurrent threads trying to simultaneously
20173 	 * cache an ire in the conn_ire_cache.
20174 	 */
20175 	mutex_enter(&connp->conn_lock);
20176 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20177 
20178 	if (ire != NULL && ire->ire_addr == dst &&
20179 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20180 
20181 		IRE_REFHOLD(ire);
20182 		mutex_exit(&connp->conn_lock);
20183 
20184 	} else {
20185 		boolean_t cached = B_FALSE;
20186 		connp->conn_ire_cache = NULL;
20187 		mutex_exit(&connp->conn_lock);
20188 		/* Release the old ire */
20189 		if (ire != NULL && sctp_ire == NULL)
20190 			IRE_REFRELE_NOTR(ire);
20191 
20192 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20193 		if (ire == NULL)
20194 			goto noirefound;
20195 		IRE_REFHOLD_NOTR(ire);
20196 
20197 		mutex_enter(&connp->conn_lock);
20198 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20199 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20200 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20201 				if (connp->conn_ulp == IPPROTO_TCP)
20202 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20203 				connp->conn_ire_cache = ire;
20204 				cached = B_TRUE;
20205 			}
20206 			rw_exit(&ire->ire_bucket->irb_lock);
20207 		}
20208 		mutex_exit(&connp->conn_lock);
20209 
20210 		/*
20211 		 * We can continue to use the ire but since it was
20212 		 * not cached, we should drop the extra reference.
20213 		 */
20214 		if (!cached)
20215 			IRE_REFRELE_NOTR(ire);
20216 	}
20217 
20218 
20219 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20220 	    "ip_wput_end: q %p (%S)", q, "end");
20221 
20222 	/*
20223 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20224 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20225 	 */
20226 	if (ire->ire_flags & RTF_MULTIRT) {
20227 
20228 		/*
20229 		 * Force the TTL of multirouted packets if required.
20230 		 * The TTL of such packets is bounded by the
20231 		 * ip_multirt_ttl ndd variable.
20232 		 */
20233 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20234 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20235 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20236 			    "(was %d), dst 0x%08x\n",
20237 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20238 			    ntohl(ire->ire_addr)));
20239 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20240 		}
20241 
20242 		/*
20243 		 * At this point, we check to see if there are any pending
20244 		 * unresolved routes. ire_multirt_resolvable()
20245 		 * checks in O(n) that all IRE_OFFSUBNET ire
20246 		 * entries for the packet's destination and
20247 		 * flagged RTF_MULTIRT are currently resolved.
20248 		 * If some remain unresolved, we make a copy
20249 		 * of the current message. It will be used
20250 		 * to initiate additional route resolutions.
20251 		 */
20252 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20253 		    MBLK_GETLABEL(first_mp), ipst);
20254 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20255 		    "multirt_need_resolve %d, first_mp %p\n",
20256 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20257 		if (multirt_need_resolve) {
20258 			copy_mp = copymsg(first_mp);
20259 			if (copy_mp != NULL) {
20260 				MULTIRT_DEBUG_TAG(copy_mp);
20261 			}
20262 		}
20263 	}
20264 
20265 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20266 
20267 	/*
20268 	 * Try to resolve another multiroute if
20269 	 * ire_multirt_resolvable() deemed it necessary
20270 	 */
20271 	if (copy_mp != NULL)
20272 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20273 	if (need_decref)
20274 		CONN_DEC_REF(connp);
20275 	return;
20276 
20277 qnext:
20278 	/*
20279 	 * Upper Level Protocols pass down complete IP datagrams
20280 	 * as M_DATA messages.	Everything else is a sideshow.
20281 	 *
20282 	 * 1) We could be re-entering ip_wput because of ip_neworute
20283 	 *    in which case we could have a IPSEC_OUT message. We
20284 	 *    need to pass through ip_wput like other datagrams and
20285 	 *    hence cannot branch to ip_wput_nondata.
20286 	 *
20287 	 * 2) ARP, AH, ESP, and other clients who are on the module
20288 	 *    instance of IP stream, give us something to deal with.
20289 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20290 	 *
20291 	 * 3) ICMP replies also could come here.
20292 	 */
20293 	ipst = ILLQ_TO_IPST(q);
20294 
20295 	if (DB_TYPE(mp) != M_DATA) {
20296 notdata:
20297 		if (DB_TYPE(mp) == M_CTL) {
20298 			/*
20299 			 * M_CTL messages are used by ARP, AH and ESP to
20300 			 * communicate with IP. We deal with IPSEC_IN and
20301 			 * IPSEC_OUT here. ip_wput_nondata handles other
20302 			 * cases.
20303 			 */
20304 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20305 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20306 				first_mp = mp->b_cont;
20307 				first_mp->b_flag &= ~MSGHASREF;
20308 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20309 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20310 				CONN_DEC_REF(connp);
20311 				connp = NULL;
20312 			}
20313 			if (ii->ipsec_info_type == IPSEC_IN) {
20314 				/*
20315 				 * Either this message goes back to
20316 				 * IPSEC for further processing or to
20317 				 * ULP after policy checks.
20318 				 */
20319 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20320 				return;
20321 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20322 				io = (ipsec_out_t *)ii;
20323 				if (io->ipsec_out_proc_begin) {
20324 					/*
20325 					 * IPSEC processing has already started.
20326 					 * Complete it.
20327 					 * IPQoS notes: We don't care what is
20328 					 * in ipsec_out_ill_index since this
20329 					 * won't be processed for IPQoS policies
20330 					 * in ipsec_out_process.
20331 					 */
20332 					ipsec_out_process(q, mp, NULL,
20333 					    io->ipsec_out_ill_index);
20334 					return;
20335 				} else {
20336 					connp = (q->q_next != NULL) ?
20337 					    NULL : Q_TO_CONN(q);
20338 					first_mp = mp;
20339 					mp = mp->b_cont;
20340 					mctl_present = B_TRUE;
20341 				}
20342 				zoneid = io->ipsec_out_zoneid;
20343 				ASSERT(zoneid != ALL_ZONES);
20344 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20345 				/*
20346 				 * It's an IPsec control message requesting
20347 				 * an SADB update to be sent to the IPsec
20348 				 * hardware acceleration capable ills.
20349 				 */
20350 				ipsec_ctl_t *ipsec_ctl =
20351 				    (ipsec_ctl_t *)mp->b_rptr;
20352 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20353 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20354 				mblk_t *cmp = mp->b_cont;
20355 
20356 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20357 				ASSERT(cmp != NULL);
20358 
20359 				freeb(mp);
20360 				ill_ipsec_capab_send_all(satype, cmp, sa,
20361 				    ipst->ips_netstack);
20362 				return;
20363 			} else {
20364 				/*
20365 				 * This must be ARP or special TSOL signaling.
20366 				 */
20367 				ip_wput_nondata(NULL, q, mp, NULL);
20368 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20369 				    "ip_wput_end: q %p (%S)", q, "nondata");
20370 				return;
20371 			}
20372 		} else {
20373 			/*
20374 			 * This must be non-(ARP/AH/ESP) messages.
20375 			 */
20376 			ASSERT(!need_decref);
20377 			ip_wput_nondata(NULL, q, mp, NULL);
20378 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20379 			    "ip_wput_end: q %p (%S)", q, "nondata");
20380 			return;
20381 		}
20382 	} else {
20383 		first_mp = mp;
20384 		mctl_present = B_FALSE;
20385 	}
20386 
20387 	ASSERT(first_mp != NULL);
20388 	/*
20389 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20390 	 * to make sure that this packet goes out on the same interface it
20391 	 * came in. We handle that here.
20392 	 */
20393 	if (mctl_present) {
20394 		uint_t ifindex;
20395 
20396 		io = (ipsec_out_t *)first_mp->b_rptr;
20397 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20398 			/*
20399 			 * We may have lost the conn context if we are
20400 			 * coming here from ip_newroute(). Copy the
20401 			 * nexthop information.
20402 			 */
20403 			if (io->ipsec_out_ip_nexthop) {
20404 				ip_nexthop = B_TRUE;
20405 				nexthop_addr = io->ipsec_out_nexthop_addr;
20406 
20407 				ipha = (ipha_t *)mp->b_rptr;
20408 				dst = ipha->ipha_dst;
20409 				goto send_from_ill;
20410 			} else {
20411 				ASSERT(io->ipsec_out_ill_index != 0);
20412 				ifindex = io->ipsec_out_ill_index;
20413 				attach_ill = ill_lookup_on_ifindex(ifindex,
20414 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20415 				if (attach_ill == NULL) {
20416 					ASSERT(xmit_ill == NULL);
20417 					ip1dbg(("ip_output: bad ifindex for "
20418 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20419 					    ifindex));
20420 					freemsg(first_mp);
20421 					BUMP_MIB(&ipst->ips_ip_mib,
20422 					    ipIfStatsOutDiscards);
20423 					ASSERT(!need_decref);
20424 					return;
20425 				}
20426 			}
20427 		}
20428 	}
20429 
20430 	ASSERT(xmit_ill == NULL);
20431 
20432 	/* We have a complete IP datagram heading outbound. */
20433 	ipha = (ipha_t *)mp->b_rptr;
20434 
20435 #ifndef SPEED_BEFORE_SAFETY
20436 	/*
20437 	 * Make sure we have a full-word aligned message and that at least
20438 	 * a simple IP header is accessible in the first message.  If not,
20439 	 * try a pullup.
20440 	 */
20441 	if (!OK_32PTR(rptr) ||
20442 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20443 hdrtoosmall:
20444 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20445 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20446 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20447 			if (first_mp == NULL)
20448 				first_mp = mp;
20449 			goto discard_pkt;
20450 		}
20451 
20452 		/* This function assumes that mp points to an IPv4 packet. */
20453 		if (is_system_labeled() && q->q_next == NULL &&
20454 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20455 		    !connp->conn_ulp_labeled) {
20456 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20457 			    &adjust, connp->conn_mac_exempt, ipst);
20458 			ipha = (ipha_t *)mp->b_rptr;
20459 			if (first_mp != NULL)
20460 				first_mp->b_cont = mp;
20461 			if (err != 0) {
20462 				if (first_mp == NULL)
20463 					first_mp = mp;
20464 				if (err == EINVAL)
20465 					goto icmp_parameter_problem;
20466 				ip2dbg(("ip_wput: label check failed (%d)\n",
20467 				    err));
20468 				goto discard_pkt;
20469 			}
20470 			iplen = ntohs(ipha->ipha_length) + adjust;
20471 			ipha->ipha_length = htons(iplen);
20472 		}
20473 
20474 		ipha = (ipha_t *)mp->b_rptr;
20475 		if (first_mp == NULL) {
20476 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20477 			/*
20478 			 * If we got here because of "goto hdrtoosmall"
20479 			 * We need to attach a IPSEC_OUT.
20480 			 */
20481 			if (connp->conn_out_enforce_policy) {
20482 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20483 				    NULL, ipha->ipha_protocol,
20484 				    ipst->ips_netstack)) == NULL)) {
20485 					BUMP_MIB(&ipst->ips_ip_mib,
20486 					    ipIfStatsOutDiscards);
20487 					if (need_decref)
20488 						CONN_DEC_REF(connp);
20489 					return;
20490 				} else {
20491 					ASSERT(mp->b_datap->db_type == M_CTL);
20492 					first_mp = mp;
20493 					mp = mp->b_cont;
20494 					mctl_present = B_TRUE;
20495 				}
20496 			} else {
20497 				first_mp = mp;
20498 				mctl_present = B_FALSE;
20499 			}
20500 		}
20501 	}
20502 #endif
20503 
20504 	/* Most of the code below is written for speed, not readability */
20505 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20506 
20507 	/*
20508 	 * If ip_newroute() fails, we're going to need a full
20509 	 * header for the icmp wraparound.
20510 	 */
20511 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20512 		uint_t	v_hlen;
20513 version_hdrlen_check:
20514 		ASSERT(first_mp != NULL);
20515 		v_hlen = V_HLEN;
20516 		/*
20517 		 * siphon off IPv6 packets coming down from transport
20518 		 * layer modules here.
20519 		 * Note: high-order bit carries NUD reachability confirmation
20520 		 */
20521 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20522 			/*
20523 			 * XXX implement a IPv4 and IPv6 packet counter per
20524 			 * conn and switch when ratio exceeds e.g. 10:1
20525 			 */
20526 #ifdef notyet
20527 			if (q->q_next == NULL) /* Avoid ill queue */
20528 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
20529 #endif
20530 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20531 			ASSERT(xmit_ill == NULL);
20532 			if (attach_ill != NULL)
20533 				ill_refrele(attach_ill);
20534 			if (need_decref)
20535 				mp->b_flag |= MSGHASREF;
20536 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20537 			return;
20538 		}
20539 
20540 		if ((v_hlen >> 4) != IP_VERSION) {
20541 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20542 			    "ip_wput_end: q %p (%S)", q, "badvers");
20543 			goto discard_pkt;
20544 		}
20545 		/*
20546 		 * Is the header length at least 20 bytes?
20547 		 *
20548 		 * Are there enough bytes accessible in the header?  If
20549 		 * not, try a pullup.
20550 		 */
20551 		v_hlen &= 0xF;
20552 		v_hlen <<= 2;
20553 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20554 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20555 			    "ip_wput_end: q %p (%S)", q, "badlen");
20556 			goto discard_pkt;
20557 		}
20558 		if (v_hlen > (mp->b_wptr - rptr)) {
20559 			if (!pullupmsg(mp, v_hlen)) {
20560 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20561 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20562 				goto discard_pkt;
20563 			}
20564 			ipha = (ipha_t *)mp->b_rptr;
20565 		}
20566 		/*
20567 		 * Move first entry from any source route into ipha_dst and
20568 		 * verify the options
20569 		 */
20570 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20571 		    zoneid, ipst)) {
20572 			ASSERT(xmit_ill == NULL);
20573 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20574 			if (attach_ill != NULL)
20575 				ill_refrele(attach_ill);
20576 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20577 			    "ip_wput_end: q %p (%S)", q, "badopts");
20578 			if (need_decref)
20579 				CONN_DEC_REF(connp);
20580 			return;
20581 		}
20582 	}
20583 	dst = ipha->ipha_dst;
20584 
20585 	/*
20586 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20587 	 * we have to run the packet through ip_newroute which will take
20588 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20589 	 * a resolver, or assigning a default gateway, etc.
20590 	 */
20591 	if (CLASSD(dst)) {
20592 		ipif_t	*ipif;
20593 		uint32_t setsrc = 0;
20594 
20595 multicast:
20596 		ASSERT(first_mp != NULL);
20597 		ip2dbg(("ip_wput: CLASSD\n"));
20598 		if (connp == NULL) {
20599 			/*
20600 			 * Use the first good ipif on the ill.
20601 			 * XXX Should this ever happen? (Appears
20602 			 * to show up with just ppp and no ethernet due
20603 			 * to in.rdisc.)
20604 			 * However, ire_send should be able to
20605 			 * call ip_wput_ire directly.
20606 			 *
20607 			 * XXX Also, this can happen for ICMP and other packets
20608 			 * with multicast source addresses.  Perhaps we should
20609 			 * fix things so that we drop the packet in question,
20610 			 * but for now, just run with it.
20611 			 */
20612 			ill_t *ill = (ill_t *)q->q_ptr;
20613 
20614 			/*
20615 			 * Don't honor attach_if for this case. If ill
20616 			 * is part of the group, ipif could belong to
20617 			 * any ill and we cannot maintain attach_ill
20618 			 * and ipif_ill same anymore and the assert
20619 			 * below would fail.
20620 			 */
20621 			if (mctl_present && io->ipsec_out_attach_if) {
20622 				io->ipsec_out_ill_index = 0;
20623 				io->ipsec_out_attach_if = B_FALSE;
20624 				ASSERT(attach_ill != NULL);
20625 				ill_refrele(attach_ill);
20626 				attach_ill = NULL;
20627 			}
20628 
20629 			ASSERT(attach_ill == NULL);
20630 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20631 			if (ipif == NULL) {
20632 				if (need_decref)
20633 					CONN_DEC_REF(connp);
20634 				freemsg(first_mp);
20635 				return;
20636 			}
20637 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20638 			    ntohl(dst), ill->ill_name));
20639 		} else {
20640 			/*
20641 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
20642 			 * and IP_MULTICAST_IF.
20643 			 * Block comment above this function explains the
20644 			 * locking mechanism used here
20645 			 */
20646 			if (xmit_ill == NULL) {
20647 				xmit_ill = conn_get_held_ill(connp,
20648 				    &connp->conn_xmit_if_ill, &err);
20649 				if (err == ILL_LOOKUP_FAILED) {
20650 					ip1dbg(("ip_wput: No ill for "
20651 					    "IP_XMIT_IF\n"));
20652 					BUMP_MIB(&ipst->ips_ip_mib,
20653 					    ipIfStatsOutNoRoutes);
20654 					goto drop_pkt;
20655 				}
20656 			}
20657 
20658 			if (xmit_ill == NULL) {
20659 				ipif = conn_get_held_ipif(connp,
20660 				    &connp->conn_multicast_ipif, &err);
20661 				if (err == IPIF_LOOKUP_FAILED) {
20662 					ip1dbg(("ip_wput: No ipif for "
20663 					    "multicast\n"));
20664 					BUMP_MIB(&ipst->ips_ip_mib,
20665 					    ipIfStatsOutNoRoutes);
20666 					goto drop_pkt;
20667 				}
20668 			}
20669 			if (xmit_ill != NULL) {
20670 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20671 				if (ipif == NULL) {
20672 					ip1dbg(("ip_wput: No ipif for "
20673 					    "IP_XMIT_IF\n"));
20674 					BUMP_MIB(&ipst->ips_ip_mib,
20675 					    ipIfStatsOutNoRoutes);
20676 					goto drop_pkt;
20677 				}
20678 			} else if (ipif == NULL || ipif->ipif_isv6) {
20679 				/*
20680 				 * We must do this ipif determination here
20681 				 * else we could pass through ip_newroute
20682 				 * and come back here without the conn context.
20683 				 *
20684 				 * Note: we do late binding i.e. we bind to
20685 				 * the interface when the first packet is sent.
20686 				 * For performance reasons we do not rebind on
20687 				 * each packet but keep the binding until the
20688 				 * next IP_MULTICAST_IF option.
20689 				 *
20690 				 * conn_multicast_{ipif,ill} are shared between
20691 				 * IPv4 and IPv6 and AF_INET6 sockets can
20692 				 * send both IPv4 and IPv6 packets. Hence
20693 				 * we have to check that "isv6" matches above.
20694 				 */
20695 				if (ipif != NULL)
20696 					ipif_refrele(ipif);
20697 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20698 				if (ipif == NULL) {
20699 					ip1dbg(("ip_wput: No ipif for "
20700 					    "multicast\n"));
20701 					BUMP_MIB(&ipst->ips_ip_mib,
20702 					    ipIfStatsOutNoRoutes);
20703 					goto drop_pkt;
20704 				}
20705 				err = conn_set_held_ipif(connp,
20706 				    &connp->conn_multicast_ipif, ipif);
20707 				if (err == IPIF_LOOKUP_FAILED) {
20708 					ipif_refrele(ipif);
20709 					ip1dbg(("ip_wput: No ipif for "
20710 					    "multicast\n"));
20711 					BUMP_MIB(&ipst->ips_ip_mib,
20712 					    ipIfStatsOutNoRoutes);
20713 					goto drop_pkt;
20714 				}
20715 			}
20716 		}
20717 		ASSERT(!ipif->ipif_isv6);
20718 		/*
20719 		 * As we may lose the conn by the time we reach ip_wput_ire,
20720 		 * we copy conn_multicast_loop and conn_dontroute on to an
20721 		 * ipsec_out. In case if this datagram goes out secure,
20722 		 * we need the ill_index also. Copy that also into the
20723 		 * ipsec_out.
20724 		 */
20725 		if (mctl_present) {
20726 			io = (ipsec_out_t *)first_mp->b_rptr;
20727 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20728 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20729 		} else {
20730 			ASSERT(mp == first_mp);
20731 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20732 			    BPRI_HI)) == NULL) {
20733 				ipif_refrele(ipif);
20734 				first_mp = mp;
20735 				goto discard_pkt;
20736 			}
20737 			first_mp->b_datap->db_type = M_CTL;
20738 			first_mp->b_wptr += sizeof (ipsec_info_t);
20739 			/* ipsec_out_secure is B_FALSE now */
20740 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20741 			io = (ipsec_out_t *)first_mp->b_rptr;
20742 			io->ipsec_out_type = IPSEC_OUT;
20743 			io->ipsec_out_len = sizeof (ipsec_out_t);
20744 			io->ipsec_out_use_global_policy = B_TRUE;
20745 			io->ipsec_out_ns = ipst->ips_netstack;
20746 			first_mp->b_cont = mp;
20747 			mctl_present = B_TRUE;
20748 		}
20749 		if (attach_ill != NULL) {
20750 			ASSERT(attach_ill == ipif->ipif_ill);
20751 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20752 
20753 			/*
20754 			 * Check if we need an ire that will not be
20755 			 * looked up by anybody else i.e. HIDDEN.
20756 			 */
20757 			if (ill_is_probeonly(attach_ill)) {
20758 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20759 			}
20760 			io->ipsec_out_ill_index =
20761 			    attach_ill->ill_phyint->phyint_ifindex;
20762 			io->ipsec_out_attach_if = B_TRUE;
20763 		} else {
20764 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20765 			io->ipsec_out_ill_index =
20766 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20767 		}
20768 		if (connp != NULL) {
20769 			io->ipsec_out_multicast_loop =
20770 			    connp->conn_multicast_loop;
20771 			io->ipsec_out_dontroute = connp->conn_dontroute;
20772 			io->ipsec_out_zoneid = connp->conn_zoneid;
20773 		}
20774 		/*
20775 		 * If the application uses IP_MULTICAST_IF with
20776 		 * different logical addresses of the same ILL, we
20777 		 * need to make sure that the soruce address of
20778 		 * the packet matches the logical IP address used
20779 		 * in the option. We do it by initializing ipha_src
20780 		 * here. This should keep IPSEC also happy as
20781 		 * when we return from IPSEC processing, we don't
20782 		 * have to worry about getting the right address on
20783 		 * the packet. Thus it is sufficient to look for
20784 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20785 		 * MATCH_IRE_IPIF.
20786 		 *
20787 		 * NOTE : We need to do it for non-secure case also as
20788 		 * this might go out secure if there is a global policy
20789 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20790 		 * address, the source should be initialized already and
20791 		 * hence we won't be initializing here.
20792 		 *
20793 		 * As we do not have the ire yet, it is possible that
20794 		 * we set the source address here and then later discover
20795 		 * that the ire implies the source address to be assigned
20796 		 * through the RTF_SETSRC flag.
20797 		 * In that case, the setsrc variable will remind us
20798 		 * that overwritting the source address by the one
20799 		 * of the RTF_SETSRC-flagged ire is allowed.
20800 		 */
20801 		if (ipha->ipha_src == INADDR_ANY &&
20802 		    (connp == NULL || !connp->conn_unspec_src)) {
20803 			ipha->ipha_src = ipif->ipif_src_addr;
20804 			setsrc = RTF_SETSRC;
20805 		}
20806 		/*
20807 		 * Find an IRE which matches the destination and the outgoing
20808 		 * queue (i.e. the outgoing interface.)
20809 		 * For loopback use a unicast IP address for
20810 		 * the ire lookup.
20811 		 */
20812 		if (IS_LOOPBACK(ipif->ipif_ill))
20813 			dst = ipif->ipif_lcl_addr;
20814 
20815 		/*
20816 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20817 		 * We don't need to lookup ire in ctable as the packet
20818 		 * needs to be sent to the destination through the specified
20819 		 * ill irrespective of ires in the cache table.
20820 		 */
20821 		ire = NULL;
20822 		if (xmit_ill == NULL) {
20823 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20824 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
20825 		}
20826 
20827 		/*
20828 		 * refrele attach_ill as its not needed anymore.
20829 		 */
20830 		if (attach_ill != NULL) {
20831 			ill_refrele(attach_ill);
20832 			attach_ill = NULL;
20833 		}
20834 
20835 		if (ire == NULL) {
20836 			/*
20837 			 * Multicast loopback and multicast forwarding is
20838 			 * done in ip_wput_ire.
20839 			 *
20840 			 * Mark this packet to make it be delivered to
20841 			 * ip_wput_ire after the new ire has been
20842 			 * created.
20843 			 *
20844 			 * The call to ip_newroute_ipif takes into account
20845 			 * the setsrc reminder. In any case, we take care
20846 			 * of the RTF_MULTIRT flag.
20847 			 */
20848 			mp->b_prev = mp->b_next = NULL;
20849 			if (xmit_ill == NULL ||
20850 			    xmit_ill->ill_ipif_up_count > 0) {
20851 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20852 				    setsrc | RTF_MULTIRT, zoneid, infop);
20853 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20854 				    "ip_wput_end: q %p (%S)", q, "noire");
20855 			} else {
20856 				freemsg(first_mp);
20857 			}
20858 			ipif_refrele(ipif);
20859 			if (xmit_ill != NULL)
20860 				ill_refrele(xmit_ill);
20861 			if (need_decref)
20862 				CONN_DEC_REF(connp);
20863 			return;
20864 		}
20865 
20866 		ipif_refrele(ipif);
20867 		ipif = NULL;
20868 		ASSERT(xmit_ill == NULL);
20869 
20870 		/*
20871 		 * Honor the RTF_SETSRC flag for multicast packets,
20872 		 * if allowed by the setsrc reminder.
20873 		 */
20874 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20875 			ipha->ipha_src = ire->ire_src_addr;
20876 		}
20877 
20878 		/*
20879 		 * Unconditionally force the TTL to 1 for
20880 		 * multirouted multicast packets:
20881 		 * multirouted multicast should not cross
20882 		 * multicast routers.
20883 		 */
20884 		if (ire->ire_flags & RTF_MULTIRT) {
20885 			if (ipha->ipha_ttl > 1) {
20886 				ip2dbg(("ip_wput: forcing multicast "
20887 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20888 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20889 				ipha->ipha_ttl = 1;
20890 			}
20891 		}
20892 	} else {
20893 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20894 		if ((ire != NULL) && (ire->ire_type &
20895 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20896 			ignore_dontroute = B_TRUE;
20897 			ignore_nexthop = B_TRUE;
20898 		}
20899 		if (ire != NULL) {
20900 			ire_refrele(ire);
20901 			ire = NULL;
20902 		}
20903 		/*
20904 		 * Guard against coming in from arp in which case conn is NULL.
20905 		 * Also guard against non M_DATA with dontroute set but
20906 		 * destined to local, loopback or broadcast addresses.
20907 		 */
20908 		if (connp != NULL && connp->conn_dontroute &&
20909 		    !ignore_dontroute) {
20910 dontroute:
20911 			/*
20912 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20913 			 * routing protocols from seeing false direct
20914 			 * connectivity.
20915 			 */
20916 			ipha->ipha_ttl = 1;
20917 			/*
20918 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20919 			 * along with SO_DONTROUTE, higher precedence is
20920 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20921 			 */
20922 			if (connp->conn_xmit_if_ill == NULL) {
20923 				/* If suitable ipif not found, drop packet */
20924 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
20925 				    ipst);
20926 				if (dst_ipif == NULL) {
20927 					ip1dbg(("ip_wput: no route for "
20928 					    "dst using SO_DONTROUTE\n"));
20929 					BUMP_MIB(&ipst->ips_ip_mib,
20930 					    ipIfStatsOutNoRoutes);
20931 					mp->b_prev = mp->b_next = NULL;
20932 					if (first_mp == NULL)
20933 						first_mp = mp;
20934 					goto drop_pkt;
20935 				} else {
20936 					/*
20937 					 * If suitable ipif has been found, set
20938 					 * xmit_ill to the corresponding
20939 					 * ipif_ill because we'll be following
20940 					 * the IP_XMIT_IF logic.
20941 					 */
20942 					ASSERT(xmit_ill == NULL);
20943 					xmit_ill = dst_ipif->ipif_ill;
20944 					mutex_enter(&xmit_ill->ill_lock);
20945 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20946 						mutex_exit(&xmit_ill->ill_lock);
20947 						xmit_ill = NULL;
20948 						ipif_refrele(dst_ipif);
20949 						ip1dbg(("ip_wput: no route for"
20950 						    " dst using"
20951 						    " SO_DONTROUTE\n"));
20952 						BUMP_MIB(&ipst->ips_ip_mib,
20953 						    ipIfStatsOutNoRoutes);
20954 						mp->b_prev = mp->b_next = NULL;
20955 						if (first_mp == NULL)
20956 							first_mp = mp;
20957 						goto drop_pkt;
20958 					}
20959 					ill_refhold_locked(xmit_ill);
20960 					mutex_exit(&xmit_ill->ill_lock);
20961 					ipif_refrele(dst_ipif);
20962 				}
20963 			}
20964 
20965 		}
20966 		/*
20967 		 * If we are bound to IPIF_NOFAILOVER address, look for
20968 		 * an IRE_CACHE matching the ill.
20969 		 */
20970 send_from_ill:
20971 		if (attach_ill != NULL) {
20972 			ipif_t	*attach_ipif;
20973 
20974 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20975 
20976 			/*
20977 			 * Check if we need an ire that will not be
20978 			 * looked up by anybody else i.e. HIDDEN.
20979 			 */
20980 			if (ill_is_probeonly(attach_ill)) {
20981 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20982 			}
20983 
20984 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20985 			if (attach_ipif == NULL) {
20986 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20987 				goto discard_pkt;
20988 			}
20989 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20990 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
20991 			ipif_refrele(attach_ipif);
20992 		} else if (xmit_ill != NULL || (connp != NULL &&
20993 		    connp->conn_xmit_if_ill != NULL)) {
20994 			/*
20995 			 * Mark this packet as originated locally
20996 			 */
20997 			mp->b_prev = mp->b_next = NULL;
20998 			/*
20999 			 * xmit_ill could be NULL if SO_DONTROUTE
21000 			 * is also set.
21001 			 */
21002 			if (xmit_ill == NULL) {
21003 				xmit_ill = conn_get_held_ill(connp,
21004 				    &connp->conn_xmit_if_ill, &err);
21005 				if (err == ILL_LOOKUP_FAILED) {
21006 					BUMP_MIB(&ipst->ips_ip_mib,
21007 					    ipIfStatsOutDiscards);
21008 					if (need_decref)
21009 						CONN_DEC_REF(connp);
21010 					freemsg(first_mp);
21011 					return;
21012 				}
21013 				if (xmit_ill == NULL) {
21014 					if (connp->conn_dontroute)
21015 						goto dontroute;
21016 					goto send_from_ill;
21017 				}
21018 			}
21019 			/*
21020 			 * Could be SO_DONTROUTE case also.
21021 			 * check at least one interface is UP as
21022 			 * specified by this ILL
21023 			 */
21024 			if (xmit_ill->ill_ipif_up_count > 0) {
21025 				ipif_t *ipif;
21026 
21027 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21028 				if (ipif == NULL) {
21029 					ip1dbg(("ip_output: "
21030 					    "xmit_ill NULL ipif\n"));
21031 					goto drop_pkt;
21032 				}
21033 				/*
21034 				 * Look for a ire that is part of the group,
21035 				 * if found use it else call ip_newroute_ipif.
21036 				 * IPCL_ZONEID is not used for matching because
21037 				 * IP_ALLZONES option is valid only when the
21038 				 * ill is accessible from all zones i.e has a
21039 				 * valid ipif in all zones.
21040 				 */
21041 				match_flags = MATCH_IRE_ILL_GROUP |
21042 				    MATCH_IRE_SECATTR;
21043 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21044 				    MBLK_GETLABEL(mp), match_flags, ipst);
21045 				/*
21046 				 * If an ire exists use it or else create
21047 				 * an ire but don't add it to the cache.
21048 				 * Adding an ire may cause issues with
21049 				 * asymmetric routing.
21050 				 * In case of multiroute always act as if
21051 				 * ire does not exist.
21052 				 */
21053 				if (ire == NULL ||
21054 				    ire->ire_flags & RTF_MULTIRT) {
21055 					if (ire != NULL)
21056 						ire_refrele(ire);
21057 					ip_newroute_ipif(q, first_mp, ipif,
21058 					    dst, connp, 0, zoneid, infop);
21059 					ipif_refrele(ipif);
21060 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21061 					ill_refrele(xmit_ill);
21062 					if (need_decref)
21063 						CONN_DEC_REF(connp);
21064 					return;
21065 				}
21066 				ipif_refrele(ipif);
21067 			} else {
21068 				goto drop_pkt;
21069 			}
21070 		} else if (ip_nexthop || (connp != NULL &&
21071 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21072 			if (!ip_nexthop) {
21073 				ip_nexthop = B_TRUE;
21074 				nexthop_addr = connp->conn_nexthop_v4;
21075 			}
21076 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21077 			    MATCH_IRE_GW;
21078 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21079 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21080 		} else {
21081 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21082 			    ipst);
21083 		}
21084 		if (!ire) {
21085 			/*
21086 			 * Make sure we don't load spread if this
21087 			 * is IPIF_NOFAILOVER case.
21088 			 */
21089 			if ((attach_ill != NULL) ||
21090 			    (ip_nexthop && !ignore_nexthop)) {
21091 				if (mctl_present) {
21092 					io = (ipsec_out_t *)first_mp->b_rptr;
21093 					ASSERT(first_mp->b_datap->db_type ==
21094 					    M_CTL);
21095 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21096 				} else {
21097 					ASSERT(mp == first_mp);
21098 					first_mp = allocb(
21099 					    sizeof (ipsec_info_t), BPRI_HI);
21100 					if (first_mp == NULL) {
21101 						first_mp = mp;
21102 						goto discard_pkt;
21103 					}
21104 					first_mp->b_datap->db_type = M_CTL;
21105 					first_mp->b_wptr +=
21106 					    sizeof (ipsec_info_t);
21107 					/* ipsec_out_secure is B_FALSE now */
21108 					bzero(first_mp->b_rptr,
21109 					    sizeof (ipsec_info_t));
21110 					io = (ipsec_out_t *)first_mp->b_rptr;
21111 					io->ipsec_out_type = IPSEC_OUT;
21112 					io->ipsec_out_len =
21113 					    sizeof (ipsec_out_t);
21114 					io->ipsec_out_use_global_policy =
21115 					    B_TRUE;
21116 					io->ipsec_out_ns = ipst->ips_netstack;
21117 					first_mp->b_cont = mp;
21118 					mctl_present = B_TRUE;
21119 				}
21120 				if (attach_ill != NULL) {
21121 					io->ipsec_out_ill_index = attach_ill->
21122 					    ill_phyint->phyint_ifindex;
21123 					io->ipsec_out_attach_if = B_TRUE;
21124 				} else {
21125 					io->ipsec_out_ip_nexthop = ip_nexthop;
21126 					io->ipsec_out_nexthop_addr =
21127 					    nexthop_addr;
21128 				}
21129 			}
21130 noirefound:
21131 			/*
21132 			 * Mark this packet as having originated on
21133 			 * this machine.  This will be noted in
21134 			 * ire_add_then_send, which needs to know
21135 			 * whether to run it back through ip_wput or
21136 			 * ip_rput following successful resolution.
21137 			 */
21138 			mp->b_prev = NULL;
21139 			mp->b_next = NULL;
21140 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21141 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21142 			    "ip_wput_end: q %p (%S)", q, "newroute");
21143 			if (attach_ill != NULL)
21144 				ill_refrele(attach_ill);
21145 			if (xmit_ill != NULL)
21146 				ill_refrele(xmit_ill);
21147 			if (need_decref)
21148 				CONN_DEC_REF(connp);
21149 			return;
21150 		}
21151 	}
21152 
21153 	/* We now know where we are going with it. */
21154 
21155 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21156 	    "ip_wput_end: q %p (%S)", q, "end");
21157 
21158 	/*
21159 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21160 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21161 	 */
21162 	if (ire->ire_flags & RTF_MULTIRT) {
21163 		/*
21164 		 * Force the TTL of multirouted packets if required.
21165 		 * The TTL of such packets is bounded by the
21166 		 * ip_multirt_ttl ndd variable.
21167 		 */
21168 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21169 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21170 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21171 			    "(was %d), dst 0x%08x\n",
21172 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21173 			    ntohl(ire->ire_addr)));
21174 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21175 		}
21176 		/*
21177 		 * At this point, we check to see if there are any pending
21178 		 * unresolved routes. ire_multirt_resolvable()
21179 		 * checks in O(n) that all IRE_OFFSUBNET ire
21180 		 * entries for the packet's destination and
21181 		 * flagged RTF_MULTIRT are currently resolved.
21182 		 * If some remain unresolved, we make a copy
21183 		 * of the current message. It will be used
21184 		 * to initiate additional route resolutions.
21185 		 */
21186 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21187 		    MBLK_GETLABEL(first_mp), ipst);
21188 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21189 		    "multirt_need_resolve %d, first_mp %p\n",
21190 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21191 		if (multirt_need_resolve) {
21192 			copy_mp = copymsg(first_mp);
21193 			if (copy_mp != NULL) {
21194 				MULTIRT_DEBUG_TAG(copy_mp);
21195 			}
21196 		}
21197 	}
21198 
21199 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21200 	/*
21201 	 * Try to resolve another multiroute if
21202 	 * ire_multirt_resolvable() deemed it necessary.
21203 	 * At this point, we need to distinguish
21204 	 * multicasts from other packets. For multicasts,
21205 	 * we call ip_newroute_ipif() and request that both
21206 	 * multirouting and setsrc flags are checked.
21207 	 */
21208 	if (copy_mp != NULL) {
21209 		if (CLASSD(dst)) {
21210 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21211 			if (ipif) {
21212 				ASSERT(infop->ip_opt_ill_index == 0);
21213 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21214 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21215 				ipif_refrele(ipif);
21216 			} else {
21217 				MULTIRT_DEBUG_UNTAG(copy_mp);
21218 				freemsg(copy_mp);
21219 				copy_mp = NULL;
21220 			}
21221 		} else {
21222 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21223 		}
21224 	}
21225 	if (attach_ill != NULL)
21226 		ill_refrele(attach_ill);
21227 	if (xmit_ill != NULL)
21228 		ill_refrele(xmit_ill);
21229 	if (need_decref)
21230 		CONN_DEC_REF(connp);
21231 	return;
21232 
21233 icmp_parameter_problem:
21234 	/* could not have originated externally */
21235 	ASSERT(mp->b_prev == NULL);
21236 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21237 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21238 		/* it's the IP header length that's in trouble */
21239 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21240 		first_mp = NULL;
21241 	}
21242 
21243 discard_pkt:
21244 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21245 drop_pkt:
21246 	ip1dbg(("ip_wput: dropped packet\n"));
21247 	if (ire != NULL)
21248 		ire_refrele(ire);
21249 	if (need_decref)
21250 		CONN_DEC_REF(connp);
21251 	freemsg(first_mp);
21252 	if (attach_ill != NULL)
21253 		ill_refrele(attach_ill);
21254 	if (xmit_ill != NULL)
21255 		ill_refrele(xmit_ill);
21256 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21257 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21258 }
21259 
21260 /*
21261  * If this is a conn_t queue, then we pass in the conn. This includes the
21262  * zoneid.
21263  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21264  * in which case we use the global zoneid since those are all part of
21265  * the global zone.
21266  */
21267 void
21268 ip_wput(queue_t *q, mblk_t *mp)
21269 {
21270 	if (CONN_Q(q))
21271 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21272 	else
21273 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21274 }
21275 
21276 /*
21277  *
21278  * The following rules must be observed when accessing any ipif or ill
21279  * that has been cached in the conn. Typically conn_nofailover_ill,
21280  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21281  *
21282  * Access: The ipif or ill pointed to from the conn can be accessed under
21283  * the protection of the conn_lock or after it has been refheld under the
21284  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21285  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21286  * The reason for this is that a concurrent unplumb could actually be
21287  * cleaning up these cached pointers by walking the conns and might have
21288  * finished cleaning up the conn in question. The macros check that an
21289  * unplumb has not yet started on the ipif or ill.
21290  *
21291  * Caching: An ipif or ill pointer may be cached in the conn only after
21292  * making sure that an unplumb has not started. So the caching is done
21293  * while holding both the conn_lock and the ill_lock and after using the
21294  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21295  * flag before starting the cleanup of conns.
21296  *
21297  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21298  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21299  * or a reference to the ipif or a reference to an ire that references the
21300  * ipif. An ipif does not change its ill except for failover/failback. Since
21301  * failover/failback happens only after bringing down the ipif and making sure
21302  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21303  * the above holds.
21304  */
21305 ipif_t *
21306 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21307 {
21308 	ipif_t	*ipif;
21309 	ill_t	*ill;
21310 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21311 
21312 	*err = 0;
21313 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21314 	mutex_enter(&connp->conn_lock);
21315 	ipif = *ipifp;
21316 	if (ipif != NULL) {
21317 		ill = ipif->ipif_ill;
21318 		mutex_enter(&ill->ill_lock);
21319 		if (IPIF_CAN_LOOKUP(ipif)) {
21320 			ipif_refhold_locked(ipif);
21321 			mutex_exit(&ill->ill_lock);
21322 			mutex_exit(&connp->conn_lock);
21323 			rw_exit(&ipst->ips_ill_g_lock);
21324 			return (ipif);
21325 		} else {
21326 			*err = IPIF_LOOKUP_FAILED;
21327 		}
21328 		mutex_exit(&ill->ill_lock);
21329 	}
21330 	mutex_exit(&connp->conn_lock);
21331 	rw_exit(&ipst->ips_ill_g_lock);
21332 	return (NULL);
21333 }
21334 
21335 ill_t *
21336 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21337 {
21338 	ill_t	*ill;
21339 
21340 	*err = 0;
21341 	mutex_enter(&connp->conn_lock);
21342 	ill = *illp;
21343 	if (ill != NULL) {
21344 		mutex_enter(&ill->ill_lock);
21345 		if (ILL_CAN_LOOKUP(ill)) {
21346 			ill_refhold_locked(ill);
21347 			mutex_exit(&ill->ill_lock);
21348 			mutex_exit(&connp->conn_lock);
21349 			return (ill);
21350 		} else {
21351 			*err = ILL_LOOKUP_FAILED;
21352 		}
21353 		mutex_exit(&ill->ill_lock);
21354 	}
21355 	mutex_exit(&connp->conn_lock);
21356 	return (NULL);
21357 }
21358 
21359 static int
21360 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21361 {
21362 	ill_t	*ill;
21363 
21364 	ill = ipif->ipif_ill;
21365 	mutex_enter(&connp->conn_lock);
21366 	mutex_enter(&ill->ill_lock);
21367 	if (IPIF_CAN_LOOKUP(ipif)) {
21368 		*ipifp = ipif;
21369 		mutex_exit(&ill->ill_lock);
21370 		mutex_exit(&connp->conn_lock);
21371 		return (0);
21372 	}
21373 	mutex_exit(&ill->ill_lock);
21374 	mutex_exit(&connp->conn_lock);
21375 	return (IPIF_LOOKUP_FAILED);
21376 }
21377 
21378 /*
21379  * This is called if the outbound datagram needs fragmentation.
21380  *
21381  * NOTE : This function does not ire_refrele the ire argument passed in.
21382  */
21383 static void
21384 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21385     ip_stack_t *ipst)
21386 {
21387 	ipha_t		*ipha;
21388 	mblk_t		*mp;
21389 	uint32_t	v_hlen_tos_len;
21390 	uint32_t	max_frag;
21391 	uint32_t	frag_flag;
21392 	boolean_t	dont_use;
21393 
21394 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21395 		mp = ipsec_mp->b_cont;
21396 	} else {
21397 		mp = ipsec_mp;
21398 	}
21399 
21400 	ipha = (ipha_t *)mp->b_rptr;
21401 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21402 
21403 #ifdef	_BIG_ENDIAN
21404 #define	V_HLEN	(v_hlen_tos_len >> 24)
21405 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21406 #else
21407 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21408 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21409 #endif
21410 
21411 #ifndef SPEED_BEFORE_SAFETY
21412 	/*
21413 	 * Check that ipha_length is consistent with
21414 	 * the mblk length
21415 	 */
21416 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21417 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21418 		    LENGTH, msgdsize(mp)));
21419 		freemsg(ipsec_mp);
21420 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21421 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21422 		    "packet length mismatch");
21423 		return;
21424 	}
21425 #endif
21426 	/*
21427 	 * Don't use frag_flag if pre-built packet or source
21428 	 * routed or if multicast (since multicast packets do not solicit
21429 	 * ICMP "packet too big" messages). Get the values of
21430 	 * max_frag and frag_flag atomically by acquiring the
21431 	 * ire_lock.
21432 	 */
21433 	mutex_enter(&ire->ire_lock);
21434 	max_frag = ire->ire_max_frag;
21435 	frag_flag = ire->ire_frag_flag;
21436 	mutex_exit(&ire->ire_lock);
21437 
21438 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21439 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21440 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21441 
21442 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21443 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21444 }
21445 
21446 /*
21447  * Used for deciding the MSS size for the upper layer. Thus
21448  * we need to check the outbound policy values in the conn.
21449  */
21450 int
21451 conn_ipsec_length(conn_t *connp)
21452 {
21453 	ipsec_latch_t *ipl;
21454 
21455 	ipl = connp->conn_latch;
21456 	if (ipl == NULL)
21457 		return (0);
21458 
21459 	if (ipl->ipl_out_policy == NULL)
21460 		return (0);
21461 
21462 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21463 }
21464 
21465 /*
21466  * Returns an estimate of the IPSEC headers size. This is used if
21467  * we don't want to call into IPSEC to get the exact size.
21468  */
21469 int
21470 ipsec_out_extra_length(mblk_t *ipsec_mp)
21471 {
21472 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21473 	ipsec_action_t *a;
21474 
21475 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21476 	if (!io->ipsec_out_secure)
21477 		return (0);
21478 
21479 	a = io->ipsec_out_act;
21480 
21481 	if (a == NULL) {
21482 		ASSERT(io->ipsec_out_policy != NULL);
21483 		a = io->ipsec_out_policy->ipsp_act;
21484 	}
21485 	ASSERT(a != NULL);
21486 
21487 	return (a->ipa_ovhd);
21488 }
21489 
21490 /*
21491  * Returns an estimate of the IPSEC headers size. This is used if
21492  * we don't want to call into IPSEC to get the exact size.
21493  */
21494 int
21495 ipsec_in_extra_length(mblk_t *ipsec_mp)
21496 {
21497 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21498 	ipsec_action_t *a;
21499 
21500 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21501 
21502 	a = ii->ipsec_in_action;
21503 	return (a == NULL ? 0 : a->ipa_ovhd);
21504 }
21505 
21506 /*
21507  * If there are any source route options, return the true final
21508  * destination. Otherwise, return the destination.
21509  */
21510 ipaddr_t
21511 ip_get_dst(ipha_t *ipha)
21512 {
21513 	ipoptp_t	opts;
21514 	uchar_t		*opt;
21515 	uint8_t		optval;
21516 	uint8_t		optlen;
21517 	ipaddr_t	dst;
21518 	uint32_t off;
21519 
21520 	dst = ipha->ipha_dst;
21521 
21522 	if (IS_SIMPLE_IPH(ipha))
21523 		return (dst);
21524 
21525 	for (optval = ipoptp_first(&opts, ipha);
21526 	    optval != IPOPT_EOL;
21527 	    optval = ipoptp_next(&opts)) {
21528 		opt = opts.ipoptp_cur;
21529 		optlen = opts.ipoptp_len;
21530 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21531 		switch (optval) {
21532 		case IPOPT_SSRR:
21533 		case IPOPT_LSRR:
21534 			off = opt[IPOPT_OFFSET];
21535 			/*
21536 			 * If one of the conditions is true, it means
21537 			 * end of options and dst already has the right
21538 			 * value.
21539 			 */
21540 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21541 				off = optlen - IP_ADDR_LEN;
21542 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21543 			}
21544 			return (dst);
21545 		default:
21546 			break;
21547 		}
21548 	}
21549 
21550 	return (dst);
21551 }
21552 
21553 mblk_t *
21554 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21555     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21556 {
21557 	ipsec_out_t	*io;
21558 	mblk_t		*first_mp;
21559 	boolean_t policy_present;
21560 	ip_stack_t	*ipst;
21561 	ipsec_stack_t	*ipss;
21562 
21563 	ASSERT(ire != NULL);
21564 	ipst = ire->ire_ipst;
21565 	ipss = ipst->ips_netstack->netstack_ipsec;
21566 
21567 	first_mp = mp;
21568 	if (mp->b_datap->db_type == M_CTL) {
21569 		io = (ipsec_out_t *)first_mp->b_rptr;
21570 		/*
21571 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21572 		 *
21573 		 * 1) There is per-socket policy (including cached global
21574 		 *    policy) or a policy on the IP-in-IP tunnel.
21575 		 * 2) There is no per-socket policy, but it is
21576 		 *    a multicast packet that needs to go out
21577 		 *    on a specific interface. This is the case
21578 		 *    where (ip_wput and ip_wput_multicast) attaches
21579 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21580 		 *
21581 		 * In case (2) we check with global policy to
21582 		 * see if there is a match and set the ill_index
21583 		 * appropriately so that we can lookup the ire
21584 		 * properly in ip_wput_ipsec_out.
21585 		 */
21586 
21587 		/*
21588 		 * ipsec_out_use_global_policy is set to B_FALSE
21589 		 * in ipsec_in_to_out(). Refer to that function for
21590 		 * details.
21591 		 */
21592 		if ((io->ipsec_out_latch == NULL) &&
21593 		    (io->ipsec_out_use_global_policy)) {
21594 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21595 			    ire, connp, unspec_src, zoneid));
21596 		}
21597 		if (!io->ipsec_out_secure) {
21598 			/*
21599 			 * If this is not a secure packet, drop
21600 			 * the IPSEC_OUT mp and treat it as a clear
21601 			 * packet. This happens when we are sending
21602 			 * a ICMP reply back to a clear packet. See
21603 			 * ipsec_in_to_out() for details.
21604 			 */
21605 			mp = first_mp->b_cont;
21606 			freeb(first_mp);
21607 		}
21608 		return (mp);
21609 	}
21610 	/*
21611 	 * See whether we need to attach a global policy here. We
21612 	 * don't depend on the conn (as it could be null) for deciding
21613 	 * what policy this datagram should go through because it
21614 	 * should have happened in ip_wput if there was some
21615 	 * policy. This normally happens for connections which are not
21616 	 * fully bound preventing us from caching policies in
21617 	 * ip_bind. Packets coming from the TCP listener/global queue
21618 	 * - which are non-hard_bound - could also be affected by
21619 	 * applying policy here.
21620 	 *
21621 	 * If this packet is coming from tcp global queue or listener,
21622 	 * we will be applying policy here.  This may not be *right*
21623 	 * if these packets are coming from the detached connection as
21624 	 * it could have gone in clear before. This happens only if a
21625 	 * TCP connection started when there is no policy and somebody
21626 	 * added policy before it became detached. Thus packets of the
21627 	 * detached connection could go out secure and the other end
21628 	 * would drop it because it will be expecting in clear. The
21629 	 * converse is not true i.e if somebody starts a TCP
21630 	 * connection and deletes the policy, all the packets will
21631 	 * still go out with the policy that existed before deleting
21632 	 * because ip_unbind sends up policy information which is used
21633 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21634 	 * TCP to attach a dummy IPSEC_OUT and set
21635 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21636 	 * affect performance for normal cases, we are not doing it.
21637 	 * Thus, set policy before starting any TCP connections.
21638 	 *
21639 	 * NOTE - We might apply policy even for a hard bound connection
21640 	 * - for which we cached policy in ip_bind - if somebody added
21641 	 * global policy after we inherited the policy in ip_bind.
21642 	 * This means that the packets that were going out in clear
21643 	 * previously would start going secure and hence get dropped
21644 	 * on the other side. To fix this, TCP attaches a dummy
21645 	 * ipsec_out and make sure that we don't apply global policy.
21646 	 */
21647 	if (ipha != NULL)
21648 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21649 	else
21650 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21651 	if (!policy_present)
21652 		return (mp);
21653 
21654 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21655 	    zoneid));
21656 }
21657 
21658 ire_t *
21659 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21660 {
21661 	ipaddr_t addr;
21662 	ire_t *save_ire;
21663 	irb_t *irb;
21664 	ill_group_t *illgrp;
21665 	int	err;
21666 
21667 	save_ire = ire;
21668 	addr = ire->ire_addr;
21669 
21670 	ASSERT(ire->ire_type == IRE_BROADCAST);
21671 
21672 	illgrp = connp->conn_outgoing_ill->ill_group;
21673 	if (illgrp == NULL) {
21674 		*conn_outgoing_ill = conn_get_held_ill(connp,
21675 		    &connp->conn_outgoing_ill, &err);
21676 		if (err == ILL_LOOKUP_FAILED) {
21677 			ire_refrele(save_ire);
21678 			return (NULL);
21679 		}
21680 		return (save_ire);
21681 	}
21682 	/*
21683 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21684 	 * If it is part of the group, we need to send on the ire
21685 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21686 	 * to this group. This is okay as IP_BOUND_IF really means
21687 	 * any ill in the group. We depend on the fact that the
21688 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21689 	 * if such an ire exists. This is possible only if you have
21690 	 * at least one ill in the group that has not failed.
21691 	 *
21692 	 * First get to the ire that matches the address and group.
21693 	 *
21694 	 * We don't look for an ire with a matching zoneid because a given zone
21695 	 * won't always have broadcast ires on all ills in the group.
21696 	 */
21697 	irb = ire->ire_bucket;
21698 	rw_enter(&irb->irb_lock, RW_READER);
21699 	if (ire->ire_marks & IRE_MARK_NORECV) {
21700 		/*
21701 		 * If the current zone only has an ire broadcast for this
21702 		 * address marked NORECV, the ire we want is ahead in the
21703 		 * bucket, so we look it up deliberately ignoring the zoneid.
21704 		 */
21705 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21706 			if (ire->ire_addr != addr)
21707 				continue;
21708 			/* skip over deleted ires */
21709 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21710 				continue;
21711 		}
21712 	}
21713 	while (ire != NULL) {
21714 		/*
21715 		 * If a new interface is coming up, we could end up
21716 		 * seeing the loopback ire and the non-loopback ire
21717 		 * may not have been added yet. So check for ire_stq
21718 		 */
21719 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21720 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21721 			break;
21722 		}
21723 		ire = ire->ire_next;
21724 	}
21725 	if (ire != NULL && ire->ire_addr == addr &&
21726 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21727 		IRE_REFHOLD(ire);
21728 		rw_exit(&irb->irb_lock);
21729 		ire_refrele(save_ire);
21730 		*conn_outgoing_ill = ire_to_ill(ire);
21731 		/*
21732 		 * Refhold the ill to make the conn_outgoing_ill
21733 		 * independent of the ire. ip_wput_ire goes in a loop
21734 		 * and may refrele the ire. Since we have an ire at this
21735 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21736 		 */
21737 		ill_refhold(*conn_outgoing_ill);
21738 		return (ire);
21739 	}
21740 	rw_exit(&irb->irb_lock);
21741 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21742 	/*
21743 	 * If we can't find a suitable ire, return the original ire.
21744 	 */
21745 	return (save_ire);
21746 }
21747 
21748 /*
21749  * This function does the ire_refrele of the ire passed in as the
21750  * argument. As this function looks up more ires i.e broadcast ires,
21751  * it needs to REFRELE them. Currently, for simplicity we don't
21752  * differentiate the one passed in and looked up here. We always
21753  * REFRELE.
21754  * IPQoS Notes:
21755  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21756  * IPSec packets are done in ipsec_out_process.
21757  *
21758  */
21759 void
21760 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21761     zoneid_t zoneid)
21762 {
21763 	ipha_t		*ipha;
21764 #define	rptr	((uchar_t *)ipha)
21765 	queue_t		*stq;
21766 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21767 	uint32_t	v_hlen_tos_len;
21768 	uint32_t	ttl_protocol;
21769 	ipaddr_t	src;
21770 	ipaddr_t	dst;
21771 	uint32_t	cksum;
21772 	ipaddr_t	orig_src;
21773 	ire_t		*ire1;
21774 	mblk_t		*next_mp;
21775 	uint_t		hlen;
21776 	uint16_t	*up;
21777 	uint32_t	max_frag = ire->ire_max_frag;
21778 	ill_t		*ill = ire_to_ill(ire);
21779 	int		clusterwide;
21780 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21781 	int		ipsec_len;
21782 	mblk_t		*first_mp;
21783 	ipsec_out_t	*io;
21784 	boolean_t	conn_dontroute;		/* conn value for multicast */
21785 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21786 	boolean_t	multicast_forward;	/* Should we forward ? */
21787 	boolean_t	unspec_src;
21788 	ill_t		*conn_outgoing_ill = NULL;
21789 	ill_t		*ire_ill;
21790 	ill_t		*ire1_ill;
21791 	ill_t		*out_ill;
21792 	uint32_t 	ill_index = 0;
21793 	boolean_t	multirt_send = B_FALSE;
21794 	int		err;
21795 	ipxmit_state_t	pktxmit_state;
21796 	ip_stack_t	*ipst = ire->ire_ipst;
21797 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21798 
21799 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21800 	    "ip_wput_ire_start: q %p", q);
21801 
21802 	multicast_forward = B_FALSE;
21803 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21804 
21805 	if (ire->ire_flags & RTF_MULTIRT) {
21806 		/*
21807 		 * Multirouting case. The bucket where ire is stored
21808 		 * probably holds other RTF_MULTIRT flagged ire
21809 		 * to the destination. In this call to ip_wput_ire,
21810 		 * we attempt to send the packet through all
21811 		 * those ires. Thus, we first ensure that ire is the
21812 		 * first RTF_MULTIRT ire in the bucket,
21813 		 * before walking the ire list.
21814 		 */
21815 		ire_t *first_ire;
21816 		irb_t *irb = ire->ire_bucket;
21817 		ASSERT(irb != NULL);
21818 
21819 		/* Make sure we do not omit any multiroute ire. */
21820 		IRB_REFHOLD(irb);
21821 		for (first_ire = irb->irb_ire;
21822 		    first_ire != NULL;
21823 		    first_ire = first_ire->ire_next) {
21824 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21825 			    (first_ire->ire_addr == ire->ire_addr) &&
21826 			    !(first_ire->ire_marks &
21827 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
21828 				break;
21829 			}
21830 		}
21831 
21832 		if ((first_ire != NULL) && (first_ire != ire)) {
21833 			IRE_REFHOLD(first_ire);
21834 			ire_refrele(ire);
21835 			ire = first_ire;
21836 			ill = ire_to_ill(ire);
21837 		}
21838 		IRB_REFRELE(irb);
21839 	}
21840 
21841 	/*
21842 	 * conn_outgoing_ill is used only in the broadcast loop.
21843 	 * for performance we don't grab the mutexs in the fastpath
21844 	 */
21845 	if ((connp != NULL) &&
21846 	    (connp->conn_xmit_if_ill == NULL) &&
21847 	    (ire->ire_type == IRE_BROADCAST) &&
21848 	    ((connp->conn_nofailover_ill != NULL) ||
21849 	    (connp->conn_outgoing_ill != NULL))) {
21850 		/*
21851 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21852 		 * option. So, see if this endpoint is bound to a
21853 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21854 		 * that if the interface is failed, we will still send
21855 		 * the packet on the same ill which is what we want.
21856 		 */
21857 		conn_outgoing_ill = conn_get_held_ill(connp,
21858 		    &connp->conn_nofailover_ill, &err);
21859 		if (err == ILL_LOOKUP_FAILED) {
21860 			ire_refrele(ire);
21861 			freemsg(mp);
21862 			return;
21863 		}
21864 		if (conn_outgoing_ill == NULL) {
21865 			/*
21866 			 * Choose a good ill in the group to send the
21867 			 * packets on.
21868 			 */
21869 			ire = conn_set_outgoing_ill(connp, ire,
21870 			    &conn_outgoing_ill);
21871 			if (ire == NULL) {
21872 				freemsg(mp);
21873 				return;
21874 			}
21875 		}
21876 	}
21877 
21878 	if (mp->b_datap->db_type != M_CTL) {
21879 		ipha = (ipha_t *)mp->b_rptr;
21880 	} else {
21881 		io = (ipsec_out_t *)mp->b_rptr;
21882 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21883 		ASSERT(zoneid == io->ipsec_out_zoneid);
21884 		ASSERT(zoneid != ALL_ZONES);
21885 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21886 		dst = ipha->ipha_dst;
21887 		/*
21888 		 * For the multicast case, ipsec_out carries conn_dontroute and
21889 		 * conn_multicast_loop as conn may not be available here. We
21890 		 * need this for multicast loopback and forwarding which is done
21891 		 * later in the code.
21892 		 */
21893 		if (CLASSD(dst)) {
21894 			conn_dontroute = io->ipsec_out_dontroute;
21895 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21896 			/*
21897 			 * If conn_dontroute is not set or conn_multicast_loop
21898 			 * is set, we need to do forwarding/loopback. For
21899 			 * datagrams from ip_wput_multicast, conn_dontroute is
21900 			 * set to B_TRUE and conn_multicast_loop is set to
21901 			 * B_FALSE so that we neither do forwarding nor
21902 			 * loopback.
21903 			 */
21904 			if (!conn_dontroute || conn_multicast_loop)
21905 				multicast_forward = B_TRUE;
21906 		}
21907 	}
21908 
21909 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21910 	    ire->ire_zoneid != ALL_ZONES) {
21911 		/*
21912 		 * When a zone sends a packet to another zone, we try to deliver
21913 		 * the packet under the same conditions as if the destination
21914 		 * was a real node on the network. To do so, we look for a
21915 		 * matching route in the forwarding table.
21916 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21917 		 * ip_newroute() does.
21918 		 * Note that IRE_LOCAL are special, since they are used
21919 		 * when the zoneid doesn't match in some cases. This means that
21920 		 * we need to handle ipha_src differently since ire_src_addr
21921 		 * belongs to the receiving zone instead of the sending zone.
21922 		 * When ip_restrict_interzone_loopback is set, then
21923 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21924 		 * for loopback between zones when the logical "Ethernet" would
21925 		 * have looped them back.
21926 		 */
21927 		ire_t *src_ire;
21928 
21929 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21930 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21931 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
21932 		if (src_ire != NULL &&
21933 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21934 		    (!ipst->ips_ip_restrict_interzone_loopback ||
21935 		    ire_local_same_ill_group(ire, src_ire))) {
21936 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21937 				ipha->ipha_src = src_ire->ire_src_addr;
21938 			ire_refrele(src_ire);
21939 		} else {
21940 			ire_refrele(ire);
21941 			if (conn_outgoing_ill != NULL)
21942 				ill_refrele(conn_outgoing_ill);
21943 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21944 			if (src_ire != NULL) {
21945 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21946 					ire_refrele(src_ire);
21947 					freemsg(mp);
21948 					return;
21949 				}
21950 				ire_refrele(src_ire);
21951 			}
21952 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
21953 				/* Failed */
21954 				freemsg(mp);
21955 				return;
21956 			}
21957 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
21958 			    ipst);
21959 			return;
21960 		}
21961 	}
21962 
21963 	if (mp->b_datap->db_type == M_CTL ||
21964 	    ipss->ipsec_outbound_v4_policy_present) {
21965 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21966 		    unspec_src, zoneid);
21967 		if (mp == NULL) {
21968 			ire_refrele(ire);
21969 			if (conn_outgoing_ill != NULL)
21970 				ill_refrele(conn_outgoing_ill);
21971 			return;
21972 		}
21973 	}
21974 
21975 	first_mp = mp;
21976 	ipsec_len = 0;
21977 
21978 	if (first_mp->b_datap->db_type == M_CTL) {
21979 		io = (ipsec_out_t *)first_mp->b_rptr;
21980 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21981 		mp = first_mp->b_cont;
21982 		ipsec_len = ipsec_out_extra_length(first_mp);
21983 		ASSERT(ipsec_len >= 0);
21984 		/* We already picked up the zoneid from the M_CTL above */
21985 		ASSERT(zoneid == io->ipsec_out_zoneid);
21986 		ASSERT(zoneid != ALL_ZONES);
21987 
21988 		/*
21989 		 * Drop M_CTL here if IPsec processing is not needed.
21990 		 * (Non-IPsec use of M_CTL extracted any information it
21991 		 * needed above).
21992 		 */
21993 		if (ipsec_len == 0) {
21994 			freeb(first_mp);
21995 			first_mp = mp;
21996 		}
21997 	}
21998 
21999 	/*
22000 	 * Fast path for ip_wput_ire
22001 	 */
22002 
22003 	ipha = (ipha_t *)mp->b_rptr;
22004 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22005 	dst = ipha->ipha_dst;
22006 
22007 	/*
22008 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22009 	 * if the socket is a SOCK_RAW type. The transport checksum should
22010 	 * be provided in the pre-built packet, so we don't need to compute it.
22011 	 * Also, other application set flags, like DF, should not be altered.
22012 	 * Other transport MUST pass down zero.
22013 	 */
22014 	ip_hdr_included = ipha->ipha_ident;
22015 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22016 
22017 	if (CLASSD(dst)) {
22018 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22019 		    ntohl(dst),
22020 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22021 		    ntohl(ire->ire_addr)));
22022 	}
22023 
22024 /* Macros to extract header fields from data already in registers */
22025 #ifdef	_BIG_ENDIAN
22026 #define	V_HLEN	(v_hlen_tos_len >> 24)
22027 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22028 #define	PROTO	(ttl_protocol & 0xFF)
22029 #else
22030 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22031 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22032 #define	PROTO	(ttl_protocol >> 8)
22033 #endif
22034 
22035 
22036 	orig_src = src = ipha->ipha_src;
22037 	/* (The loop back to "another" is explained down below.) */
22038 another:;
22039 	/*
22040 	 * Assign an ident value for this packet.  We assign idents on
22041 	 * a per destination basis out of the IRE.  There could be
22042 	 * other threads targeting the same destination, so we have to
22043 	 * arrange for a atomic increment.  Note that we use a 32-bit
22044 	 * atomic add because it has better performance than its
22045 	 * 16-bit sibling.
22046 	 *
22047 	 * If running in cluster mode and if the source address
22048 	 * belongs to a replicated service then vector through
22049 	 * cl_inet_ipident vector to allocate ip identifier
22050 	 * NOTE: This is a contract private interface with the
22051 	 * clustering group.
22052 	 */
22053 	clusterwide = 0;
22054 	if (cl_inet_ipident) {
22055 		ASSERT(cl_inet_isclusterwide);
22056 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22057 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22058 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22059 			    AF_INET, (uint8_t *)(uintptr_t)src,
22060 			    (uint8_t *)(uintptr_t)dst);
22061 			clusterwide = 1;
22062 		}
22063 	}
22064 	if (!clusterwide) {
22065 		ipha->ipha_ident =
22066 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22067 	}
22068 
22069 #ifndef _BIG_ENDIAN
22070 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22071 #endif
22072 
22073 	/*
22074 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22075 	 * This is needed to obey conn_unspec_src when packets go through
22076 	 * ip_newroute + arp.
22077 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22078 	 */
22079 	if (src == INADDR_ANY && !unspec_src) {
22080 		/*
22081 		 * Assign the appropriate source address from the IRE if none
22082 		 * was specified.
22083 		 */
22084 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22085 
22086 		/*
22087 		 * With IP multipathing, broadcast packets are sent on the ire
22088 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22089 		 * the group. However, this ire might not be in the same zone so
22090 		 * we can't always use its source address. We look for a
22091 		 * broadcast ire in the same group and in the right zone.
22092 		 */
22093 		if (ire->ire_type == IRE_BROADCAST &&
22094 		    ire->ire_zoneid != zoneid) {
22095 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22096 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22097 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22098 			if (src_ire != NULL) {
22099 				src = src_ire->ire_src_addr;
22100 				ire_refrele(src_ire);
22101 			} else {
22102 				ire_refrele(ire);
22103 				if (conn_outgoing_ill != NULL)
22104 					ill_refrele(conn_outgoing_ill);
22105 				freemsg(first_mp);
22106 				if (ill != NULL) {
22107 					BUMP_MIB(ill->ill_ip_mib,
22108 					    ipIfStatsOutDiscards);
22109 				} else {
22110 					BUMP_MIB(&ipst->ips_ip_mib,
22111 					    ipIfStatsOutDiscards);
22112 				}
22113 				return;
22114 			}
22115 		} else {
22116 			src = ire->ire_src_addr;
22117 		}
22118 
22119 		if (connp == NULL) {
22120 			ip1dbg(("ip_wput_ire: no connp and no src "
22121 			    "address for dst 0x%x, using src 0x%x\n",
22122 			    ntohl(dst),
22123 			    ntohl(src)));
22124 		}
22125 		ipha->ipha_src = src;
22126 	}
22127 	stq = ire->ire_stq;
22128 
22129 	/*
22130 	 * We only allow ire chains for broadcasts since there will
22131 	 * be multiple IRE_CACHE entries for the same multicast
22132 	 * address (one per ipif).
22133 	 */
22134 	next_mp = NULL;
22135 
22136 	/* broadcast packet */
22137 	if (ire->ire_type == IRE_BROADCAST)
22138 		goto broadcast;
22139 
22140 	/* loopback ? */
22141 	if (stq == NULL)
22142 		goto nullstq;
22143 
22144 	/* The ill_index for outbound ILL */
22145 	ill_index = Q_TO_INDEX(stq);
22146 
22147 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22148 	ttl_protocol = ((uint16_t *)ipha)[4];
22149 
22150 	/* pseudo checksum (do it in parts for IP header checksum) */
22151 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22152 
22153 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22154 		queue_t *dev_q = stq->q_next;
22155 
22156 		/* flow controlled */
22157 		if ((dev_q->q_next || dev_q->q_first) &&
22158 		    !canput(dev_q))
22159 			goto blocked;
22160 		if ((PROTO == IPPROTO_UDP) &&
22161 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22162 			hlen = (V_HLEN & 0xF) << 2;
22163 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22164 			if (*up != 0) {
22165 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22166 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22167 				/* Software checksum? */
22168 				if (DB_CKSUMFLAGS(mp) == 0) {
22169 					IP_STAT(ipst, ip_out_sw_cksum);
22170 					IP_STAT_UPDATE(ipst,
22171 					    ip_udp_out_sw_cksum_bytes,
22172 					    LENGTH - hlen);
22173 				}
22174 			}
22175 		}
22176 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22177 		hlen = (V_HLEN & 0xF) << 2;
22178 		if (PROTO == IPPROTO_TCP) {
22179 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22180 			/*
22181 			 * The packet header is processed once and for all, even
22182 			 * in the multirouting case. We disable hardware
22183 			 * checksum if the packet is multirouted, as it will be
22184 			 * replicated via several interfaces, and not all of
22185 			 * them may have this capability.
22186 			 */
22187 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22188 			    LENGTH, max_frag, ipsec_len, cksum);
22189 			/* Software checksum? */
22190 			if (DB_CKSUMFLAGS(mp) == 0) {
22191 				IP_STAT(ipst, ip_out_sw_cksum);
22192 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22193 				    LENGTH - hlen);
22194 			}
22195 		} else {
22196 			sctp_hdr_t	*sctph;
22197 
22198 			ASSERT(PROTO == IPPROTO_SCTP);
22199 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22200 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22201 			/*
22202 			 * Zero out the checksum field to ensure proper
22203 			 * checksum calculation.
22204 			 */
22205 			sctph->sh_chksum = 0;
22206 #ifdef	DEBUG
22207 			if (!skip_sctp_cksum)
22208 #endif
22209 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22210 		}
22211 	}
22212 
22213 	/*
22214 	 * If this is a multicast packet and originated from ip_wput
22215 	 * we need to do loopback and forwarding checks. If it comes
22216 	 * from ip_wput_multicast, we SHOULD not do this.
22217 	 */
22218 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22219 
22220 	/* checksum */
22221 	cksum += ttl_protocol;
22222 
22223 	/* fragment the packet */
22224 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22225 		goto fragmentit;
22226 	/*
22227 	 * Don't use frag_flag if packet is pre-built or source
22228 	 * routed or if multicast (since multicast packets do
22229 	 * not solicit ICMP "packet too big" messages).
22230 	 */
22231 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22232 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22233 	    !ip_source_route_included(ipha)) &&
22234 	    !CLASSD(ipha->ipha_dst))
22235 		ipha->ipha_fragment_offset_and_flags |=
22236 		    htons(ire->ire_frag_flag);
22237 
22238 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22239 		/* calculate IP header checksum */
22240 		cksum += ipha->ipha_ident;
22241 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22242 		cksum += ipha->ipha_fragment_offset_and_flags;
22243 
22244 		/* IP options present */
22245 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22246 		if (hlen)
22247 			goto checksumoptions;
22248 
22249 		/* calculate hdr checksum */
22250 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22251 		cksum = ~(cksum + (cksum >> 16));
22252 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22253 	}
22254 	if (ipsec_len != 0) {
22255 		/*
22256 		 * We will do the rest of the processing after
22257 		 * we come back from IPSEC in ip_wput_ipsec_out().
22258 		 */
22259 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22260 
22261 		io = (ipsec_out_t *)first_mp->b_rptr;
22262 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22263 		    ill_phyint->phyint_ifindex;
22264 
22265 		ipsec_out_process(q, first_mp, ire, ill_index);
22266 		ire_refrele(ire);
22267 		if (conn_outgoing_ill != NULL)
22268 			ill_refrele(conn_outgoing_ill);
22269 		return;
22270 	}
22271 
22272 	/*
22273 	 * In most cases, the emission loop below is entered only
22274 	 * once. Only in the case where the ire holds the
22275 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22276 	 * flagged ires in the bucket, and send the packet
22277 	 * through all crossed RTF_MULTIRT routes.
22278 	 */
22279 	if (ire->ire_flags & RTF_MULTIRT) {
22280 		multirt_send = B_TRUE;
22281 	}
22282 	do {
22283 		if (multirt_send) {
22284 			irb_t *irb;
22285 			/*
22286 			 * We are in a multiple send case, need to get
22287 			 * the next ire and make a duplicate of the packet.
22288 			 * ire1 holds here the next ire to process in the
22289 			 * bucket. If multirouting is expected,
22290 			 * any non-RTF_MULTIRT ire that has the
22291 			 * right destination address is ignored.
22292 			 */
22293 			irb = ire->ire_bucket;
22294 			ASSERT(irb != NULL);
22295 
22296 			IRB_REFHOLD(irb);
22297 			for (ire1 = ire->ire_next;
22298 			    ire1 != NULL;
22299 			    ire1 = ire1->ire_next) {
22300 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22301 					continue;
22302 				if (ire1->ire_addr != ire->ire_addr)
22303 					continue;
22304 				if (ire1->ire_marks &
22305 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22306 					continue;
22307 
22308 				/* Got one */
22309 				IRE_REFHOLD(ire1);
22310 				break;
22311 			}
22312 			IRB_REFRELE(irb);
22313 
22314 			if (ire1 != NULL) {
22315 				next_mp = copyb(mp);
22316 				if ((next_mp == NULL) ||
22317 				    ((mp->b_cont != NULL) &&
22318 				    ((next_mp->b_cont =
22319 				    dupmsg(mp->b_cont)) == NULL))) {
22320 					freemsg(next_mp);
22321 					next_mp = NULL;
22322 					ire_refrele(ire1);
22323 					ire1 = NULL;
22324 				}
22325 			}
22326 
22327 			/* Last multiroute ire; don't loop anymore. */
22328 			if (ire1 == NULL) {
22329 				multirt_send = B_FALSE;
22330 			}
22331 		}
22332 
22333 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22334 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22335 		    mblk_t *, mp);
22336 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22337 		    ipst->ips_ipv4firewall_physical_out,
22338 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22339 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22340 		if (mp == NULL)
22341 			goto release_ire_and_ill;
22342 
22343 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22344 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22345 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22346 		if ((pktxmit_state == SEND_FAILED) ||
22347 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22348 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22349 			    "- packet dropped\n"));
22350 release_ire_and_ill:
22351 			ire_refrele(ire);
22352 			if (next_mp != NULL) {
22353 				freemsg(next_mp);
22354 				ire_refrele(ire1);
22355 			}
22356 			if (conn_outgoing_ill != NULL)
22357 				ill_refrele(conn_outgoing_ill);
22358 			return;
22359 		}
22360 
22361 		if (CLASSD(dst)) {
22362 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22363 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22364 			    LENGTH);
22365 		}
22366 
22367 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22368 		    "ip_wput_ire_end: q %p (%S)",
22369 		    q, "last copy out");
22370 		IRE_REFRELE(ire);
22371 
22372 		if (multirt_send) {
22373 			ASSERT(ire1);
22374 			/*
22375 			 * Proceed with the next RTF_MULTIRT ire,
22376 			 * Also set up the send-to queue accordingly.
22377 			 */
22378 			ire = ire1;
22379 			ire1 = NULL;
22380 			stq = ire->ire_stq;
22381 			mp = next_mp;
22382 			next_mp = NULL;
22383 			ipha = (ipha_t *)mp->b_rptr;
22384 			ill_index = Q_TO_INDEX(stq);
22385 			ill = (ill_t *)stq->q_ptr;
22386 		}
22387 	} while (multirt_send);
22388 	if (conn_outgoing_ill != NULL)
22389 		ill_refrele(conn_outgoing_ill);
22390 	return;
22391 
22392 	/*
22393 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22394 	 */
22395 broadcast:
22396 	{
22397 		/*
22398 		 * Avoid broadcast storms by setting the ttl to 1
22399 		 * for broadcasts. This parameter can be set
22400 		 * via ndd, so make sure that for the SO_DONTROUTE
22401 		 * case that ipha_ttl is always set to 1.
22402 		 * In the event that we are replying to incoming
22403 		 * ICMP packets, conn could be NULL.
22404 		 */
22405 		if ((connp != NULL) && connp->conn_dontroute)
22406 			ipha->ipha_ttl = 1;
22407 		else
22408 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22409 
22410 		/*
22411 		 * Note that we are not doing a IRB_REFHOLD here.
22412 		 * Actually we don't care if the list changes i.e
22413 		 * if somebody deletes an IRE from the list while
22414 		 * we drop the lock, the next time we come around
22415 		 * ire_next will be NULL and hence we won't send
22416 		 * out multiple copies which is fine.
22417 		 */
22418 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22419 		ire1 = ire->ire_next;
22420 		if (conn_outgoing_ill != NULL) {
22421 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22422 				ASSERT(ire1 == ire->ire_next);
22423 				if (ire1 != NULL && ire1->ire_addr == dst) {
22424 					ire_refrele(ire);
22425 					ire = ire1;
22426 					IRE_REFHOLD(ire);
22427 					ire1 = ire->ire_next;
22428 					continue;
22429 				}
22430 				rw_exit(&ire->ire_bucket->irb_lock);
22431 				/* Did not find a matching ill */
22432 				ip1dbg(("ip_wput_ire: broadcast with no "
22433 				    "matching IP_BOUND_IF ill %s\n",
22434 				    conn_outgoing_ill->ill_name));
22435 				freemsg(first_mp);
22436 				if (ire != NULL)
22437 					ire_refrele(ire);
22438 				ill_refrele(conn_outgoing_ill);
22439 				return;
22440 			}
22441 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22442 			/*
22443 			 * If the next IRE has the same address and is not one
22444 			 * of the two copies that we need to send, try to see
22445 			 * whether this copy should be sent at all. This
22446 			 * assumes that we insert loopbacks first and then
22447 			 * non-loopbacks. This is acheived by inserting the
22448 			 * loopback always before non-loopback.
22449 			 * This is used to send a single copy of a broadcast
22450 			 * packet out all physical interfaces that have an
22451 			 * matching IRE_BROADCAST while also looping
22452 			 * back one copy (to ip_wput_local) for each
22453 			 * matching physical interface. However, we avoid
22454 			 * sending packets out different logical that match by
22455 			 * having ipif_up/ipif_down supress duplicate
22456 			 * IRE_BROADCASTS.
22457 			 *
22458 			 * This feature is currently used to get broadcasts
22459 			 * sent to multiple interfaces, when the broadcast
22460 			 * address being used applies to multiple interfaces.
22461 			 * For example, a whole net broadcast will be
22462 			 * replicated on every connected subnet of
22463 			 * the target net.
22464 			 *
22465 			 * Each zone has its own set of IRE_BROADCASTs, so that
22466 			 * we're able to distribute inbound packets to multiple
22467 			 * zones who share a broadcast address. We avoid looping
22468 			 * back outbound packets in different zones but on the
22469 			 * same ill, as the application would see duplicates.
22470 			 *
22471 			 * If the interfaces are part of the same group,
22472 			 * we would want to send only one copy out for
22473 			 * whole group.
22474 			 *
22475 			 * This logic assumes that ire_add_v4() groups the
22476 			 * IRE_BROADCAST entries so that those with the same
22477 			 * ire_addr and ill_group are kept together.
22478 			 */
22479 			ire_ill = ire->ire_ipif->ipif_ill;
22480 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22481 				if (ire_ill->ill_group != NULL &&
22482 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22483 					/*
22484 					 * If the current zone only has an ire
22485 					 * broadcast for this address marked
22486 					 * NORECV, the ire we want is ahead in
22487 					 * the bucket, so we look it up
22488 					 * deliberately ignoring the zoneid.
22489 					 */
22490 					for (ire1 = ire->ire_bucket->irb_ire;
22491 					    ire1 != NULL;
22492 					    ire1 = ire1->ire_next) {
22493 						ire1_ill =
22494 						    ire1->ire_ipif->ipif_ill;
22495 						if (ire1->ire_addr != dst)
22496 							continue;
22497 						/* skip over the current ire */
22498 						if (ire1 == ire)
22499 							continue;
22500 						/* skip over deleted ires */
22501 						if (ire1->ire_marks &
22502 						    IRE_MARK_CONDEMNED)
22503 							continue;
22504 						/*
22505 						 * non-loopback ire in our
22506 						 * group: use it for the next
22507 						 * pass in the loop
22508 						 */
22509 						if (ire1->ire_stq != NULL &&
22510 						    ire1_ill->ill_group ==
22511 						    ire_ill->ill_group)
22512 							break;
22513 					}
22514 				}
22515 			} else {
22516 				while (ire1 != NULL && ire1->ire_addr == dst) {
22517 					ire1_ill = ire1->ire_ipif->ipif_ill;
22518 					/*
22519 					 * We can have two broadcast ires on the
22520 					 * same ill in different zones; here
22521 					 * we'll send a copy of the packet on
22522 					 * each ill and the fanout code will
22523 					 * call conn_wantpacket() to check that
22524 					 * the zone has the broadcast address
22525 					 * configured on the ill. If the two
22526 					 * ires are in the same group we only
22527 					 * send one copy up.
22528 					 */
22529 					if (ire1_ill != ire_ill &&
22530 					    (ire1_ill->ill_group == NULL ||
22531 					    ire_ill->ill_group == NULL ||
22532 					    ire1_ill->ill_group !=
22533 					    ire_ill->ill_group)) {
22534 						break;
22535 					}
22536 					ire1 = ire1->ire_next;
22537 				}
22538 			}
22539 		}
22540 		ASSERT(multirt_send == B_FALSE);
22541 		if (ire1 != NULL && ire1->ire_addr == dst) {
22542 			if ((ire->ire_flags & RTF_MULTIRT) &&
22543 			    (ire1->ire_flags & RTF_MULTIRT)) {
22544 				/*
22545 				 * We are in the multirouting case.
22546 				 * The message must be sent at least
22547 				 * on both ires. These ires have been
22548 				 * inserted AFTER the standard ones
22549 				 * in ip_rt_add(). There are thus no
22550 				 * other ire entries for the destination
22551 				 * address in the rest of the bucket
22552 				 * that do not have the RTF_MULTIRT
22553 				 * flag. We don't process a copy
22554 				 * of the message here. This will be
22555 				 * done in the final sending loop.
22556 				 */
22557 				multirt_send = B_TRUE;
22558 			} else {
22559 				next_mp = ip_copymsg(first_mp);
22560 				if (next_mp != NULL)
22561 					IRE_REFHOLD(ire1);
22562 			}
22563 		}
22564 		rw_exit(&ire->ire_bucket->irb_lock);
22565 	}
22566 
22567 	if (stq) {
22568 		/*
22569 		 * A non-NULL send-to queue means this packet is going
22570 		 * out of this machine.
22571 		 */
22572 		out_ill = (ill_t *)stq->q_ptr;
22573 
22574 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22575 		ttl_protocol = ((uint16_t *)ipha)[4];
22576 		/*
22577 		 * We accumulate the pseudo header checksum in cksum.
22578 		 * This is pretty hairy code, so watch close.  One
22579 		 * thing to keep in mind is that UDP and TCP have
22580 		 * stored their respective datagram lengths in their
22581 		 * checksum fields.  This lines things up real nice.
22582 		 */
22583 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22584 		    (src >> 16) + (src & 0xFFFF);
22585 		/*
22586 		 * We assume the udp checksum field contains the
22587 		 * length, so to compute the pseudo header checksum,
22588 		 * all we need is the protocol number and src/dst.
22589 		 */
22590 		/* Provide the checksums for UDP and TCP. */
22591 		if ((PROTO == IPPROTO_TCP) &&
22592 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22593 			/* hlen gets the number of uchar_ts in the IP header */
22594 			hlen = (V_HLEN & 0xF) << 2;
22595 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22596 			IP_STAT(ipst, ip_out_sw_cksum);
22597 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22598 			    LENGTH - hlen);
22599 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22600 		} else if (PROTO == IPPROTO_SCTP &&
22601 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22602 			sctp_hdr_t	*sctph;
22603 
22604 			hlen = (V_HLEN & 0xF) << 2;
22605 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22606 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22607 			sctph->sh_chksum = 0;
22608 #ifdef	DEBUG
22609 			if (!skip_sctp_cksum)
22610 #endif
22611 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22612 		} else {
22613 			queue_t *dev_q = stq->q_next;
22614 
22615 			if ((dev_q->q_next || dev_q->q_first) &&
22616 			    !canput(dev_q)) {
22617 blocked:
22618 				ipha->ipha_ident = ip_hdr_included;
22619 				/*
22620 				 * If we don't have a conn to apply
22621 				 * backpressure, free the message.
22622 				 * In the ire_send path, we don't know
22623 				 * the position to requeue the packet. Rather
22624 				 * than reorder packets, we just drop this
22625 				 * packet.
22626 				 */
22627 				if (ipst->ips_ip_output_queue &&
22628 				    connp != NULL &&
22629 				    caller != IRE_SEND) {
22630 					if (caller == IP_WSRV) {
22631 						connp->conn_did_putbq = 1;
22632 						(void) putbq(connp->conn_wq,
22633 						    first_mp);
22634 						conn_drain_insert(connp);
22635 						/*
22636 						 * This is the service thread,
22637 						 * and the queue is already
22638 						 * noenabled. The check for
22639 						 * canput and the putbq is not
22640 						 * atomic. So we need to check
22641 						 * again.
22642 						 */
22643 						if (canput(stq->q_next))
22644 							connp->conn_did_putbq
22645 							    = 0;
22646 						IP_STAT(ipst, ip_conn_flputbq);
22647 					} else {
22648 						/*
22649 						 * We are not the service proc.
22650 						 * ip_wsrv will be scheduled or
22651 						 * is already running.
22652 						 */
22653 						(void) putq(connp->conn_wq,
22654 						    first_mp);
22655 					}
22656 				} else {
22657 					out_ill = (ill_t *)stq->q_ptr;
22658 					BUMP_MIB(out_ill->ill_ip_mib,
22659 					    ipIfStatsOutDiscards);
22660 					freemsg(first_mp);
22661 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22662 					    "ip_wput_ire_end: q %p (%S)",
22663 					    q, "discard");
22664 				}
22665 				ire_refrele(ire);
22666 				if (next_mp) {
22667 					ire_refrele(ire1);
22668 					freemsg(next_mp);
22669 				}
22670 				if (conn_outgoing_ill != NULL)
22671 					ill_refrele(conn_outgoing_ill);
22672 				return;
22673 			}
22674 			if ((PROTO == IPPROTO_UDP) &&
22675 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22676 				/*
22677 				 * hlen gets the number of uchar_ts in the
22678 				 * IP header
22679 				 */
22680 				hlen = (V_HLEN & 0xF) << 2;
22681 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22682 				max_frag = ire->ire_max_frag;
22683 				if (*up != 0) {
22684 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22685 					    up, PROTO, hlen, LENGTH, max_frag,
22686 					    ipsec_len, cksum);
22687 					/* Software checksum? */
22688 					if (DB_CKSUMFLAGS(mp) == 0) {
22689 						IP_STAT(ipst, ip_out_sw_cksum);
22690 						IP_STAT_UPDATE(ipst,
22691 						    ip_udp_out_sw_cksum_bytes,
22692 						    LENGTH - hlen);
22693 					}
22694 				}
22695 			}
22696 		}
22697 		/*
22698 		 * Need to do this even when fragmenting. The local
22699 		 * loopback can be done without computing checksums
22700 		 * but forwarding out other interface must be done
22701 		 * after the IP checksum (and ULP checksums) have been
22702 		 * computed.
22703 		 *
22704 		 * NOTE : multicast_forward is set only if this packet
22705 		 * originated from ip_wput. For packets originating from
22706 		 * ip_wput_multicast, it is not set.
22707 		 */
22708 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22709 multi_loopback:
22710 			ip2dbg(("ip_wput: multicast, loop %d\n",
22711 			    conn_multicast_loop));
22712 
22713 			/*  Forget header checksum offload */
22714 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22715 
22716 			/*
22717 			 * Local loopback of multicasts?  Check the
22718 			 * ill.
22719 			 *
22720 			 * Note that the loopback function will not come
22721 			 * in through ip_rput - it will only do the
22722 			 * client fanout thus we need to do an mforward
22723 			 * as well.  The is different from the BSD
22724 			 * logic.
22725 			 */
22726 			if (ill != NULL) {
22727 				ilm_t	*ilm;
22728 
22729 				ILM_WALKER_HOLD(ill);
22730 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22731 				    ALL_ZONES);
22732 				ILM_WALKER_RELE(ill);
22733 				if (ilm != NULL) {
22734 					/*
22735 					 * Pass along the virtual output q.
22736 					 * ip_wput_local() will distribute the
22737 					 * packet to all the matching zones,
22738 					 * except the sending zone when
22739 					 * IP_MULTICAST_LOOP is false.
22740 					 */
22741 					ip_multicast_loopback(q, ill, first_mp,
22742 					    conn_multicast_loop ? 0 :
22743 					    IP_FF_NO_MCAST_LOOP, zoneid);
22744 				}
22745 			}
22746 			if (ipha->ipha_ttl == 0) {
22747 				/*
22748 				 * 0 => only to this host i.e. we are
22749 				 * done. We are also done if this was the
22750 				 * loopback interface since it is sufficient
22751 				 * to loopback one copy of a multicast packet.
22752 				 */
22753 				freemsg(first_mp);
22754 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22755 				    "ip_wput_ire_end: q %p (%S)",
22756 				    q, "loopback");
22757 				ire_refrele(ire);
22758 				if (conn_outgoing_ill != NULL)
22759 					ill_refrele(conn_outgoing_ill);
22760 				return;
22761 			}
22762 			/*
22763 			 * ILLF_MULTICAST is checked in ip_newroute
22764 			 * i.e. we don't need to check it here since
22765 			 * all IRE_CACHEs come from ip_newroute.
22766 			 * For multicast traffic, SO_DONTROUTE is interpreted
22767 			 * to mean only send the packet out the interface
22768 			 * (optionally specified with IP_MULTICAST_IF)
22769 			 * and do not forward it out additional interfaces.
22770 			 * RSVP and the rsvp daemon is an example of a
22771 			 * protocol and user level process that
22772 			 * handles it's own routing. Hence, it uses the
22773 			 * SO_DONTROUTE option to accomplish this.
22774 			 */
22775 
22776 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22777 			    ill != NULL) {
22778 				/* Unconditionally redo the checksum */
22779 				ipha->ipha_hdr_checksum = 0;
22780 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22781 
22782 				/*
22783 				 * If this needs to go out secure, we need
22784 				 * to wait till we finish the IPSEC
22785 				 * processing.
22786 				 */
22787 				if (ipsec_len == 0 &&
22788 				    ip_mforward(ill, ipha, mp)) {
22789 					freemsg(first_mp);
22790 					ip1dbg(("ip_wput: mforward failed\n"));
22791 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22792 					    "ip_wput_ire_end: q %p (%S)",
22793 					    q, "mforward failed");
22794 					ire_refrele(ire);
22795 					if (conn_outgoing_ill != NULL)
22796 						ill_refrele(conn_outgoing_ill);
22797 					return;
22798 				}
22799 			}
22800 		}
22801 		max_frag = ire->ire_max_frag;
22802 		cksum += ttl_protocol;
22803 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22804 			/* No fragmentation required for this one. */
22805 			/*
22806 			 * Don't use frag_flag if packet is pre-built or source
22807 			 * routed or if multicast (since multicast packets do
22808 			 * not solicit ICMP "packet too big" messages).
22809 			 */
22810 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22811 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22812 			    !ip_source_route_included(ipha)) &&
22813 			    !CLASSD(ipha->ipha_dst))
22814 				ipha->ipha_fragment_offset_and_flags |=
22815 				    htons(ire->ire_frag_flag);
22816 
22817 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22818 				/* Complete the IP header checksum. */
22819 				cksum += ipha->ipha_ident;
22820 				cksum += (v_hlen_tos_len >> 16)+
22821 				    (v_hlen_tos_len & 0xFFFF);
22822 				cksum += ipha->ipha_fragment_offset_and_flags;
22823 				hlen = (V_HLEN & 0xF) -
22824 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22825 				if (hlen) {
22826 checksumoptions:
22827 					/*
22828 					 * Account for the IP Options in the IP
22829 					 * header checksum.
22830 					 */
22831 					up = (uint16_t *)(rptr+
22832 					    IP_SIMPLE_HDR_LENGTH);
22833 					do {
22834 						cksum += up[0];
22835 						cksum += up[1];
22836 						up += 2;
22837 					} while (--hlen);
22838 				}
22839 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22840 				cksum = ~(cksum + (cksum >> 16));
22841 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22842 			}
22843 			if (ipsec_len != 0) {
22844 				ipsec_out_process(q, first_mp, ire, ill_index);
22845 				if (!next_mp) {
22846 					ire_refrele(ire);
22847 					if (conn_outgoing_ill != NULL)
22848 						ill_refrele(conn_outgoing_ill);
22849 					return;
22850 				}
22851 				goto next;
22852 			}
22853 
22854 			/*
22855 			 * multirt_send has already been handled
22856 			 * for broadcast, but not yet for multicast
22857 			 * or IP options.
22858 			 */
22859 			if (next_mp == NULL) {
22860 				if (ire->ire_flags & RTF_MULTIRT) {
22861 					multirt_send = B_TRUE;
22862 				}
22863 			}
22864 
22865 			/*
22866 			 * In most cases, the emission loop below is
22867 			 * entered only once. Only in the case where
22868 			 * the ire holds the RTF_MULTIRT flag, do we loop
22869 			 * to process all RTF_MULTIRT ires in the bucket,
22870 			 * and send the packet through all crossed
22871 			 * RTF_MULTIRT routes.
22872 			 */
22873 			do {
22874 				if (multirt_send) {
22875 					irb_t *irb;
22876 
22877 					irb = ire->ire_bucket;
22878 					ASSERT(irb != NULL);
22879 					/*
22880 					 * We are in a multiple send case,
22881 					 * need to get the next IRE and make
22882 					 * a duplicate of the packet.
22883 					 */
22884 					IRB_REFHOLD(irb);
22885 					for (ire1 = ire->ire_next;
22886 					    ire1 != NULL;
22887 					    ire1 = ire1->ire_next) {
22888 						if (!(ire1->ire_flags &
22889 						    RTF_MULTIRT)) {
22890 							continue;
22891 						}
22892 						if (ire1->ire_addr !=
22893 						    ire->ire_addr) {
22894 							continue;
22895 						}
22896 						if (ire1->ire_marks &
22897 						    (IRE_MARK_CONDEMNED|
22898 						    IRE_MARK_HIDDEN)) {
22899 							continue;
22900 						}
22901 
22902 						/* Got one */
22903 						IRE_REFHOLD(ire1);
22904 						break;
22905 					}
22906 					IRB_REFRELE(irb);
22907 
22908 					if (ire1 != NULL) {
22909 						next_mp = copyb(mp);
22910 						if ((next_mp == NULL) ||
22911 						    ((mp->b_cont != NULL) &&
22912 						    ((next_mp->b_cont =
22913 						    dupmsg(mp->b_cont))
22914 						    == NULL))) {
22915 							freemsg(next_mp);
22916 							next_mp = NULL;
22917 							ire_refrele(ire1);
22918 							ire1 = NULL;
22919 						}
22920 					}
22921 
22922 					/*
22923 					 * Last multiroute ire; don't loop
22924 					 * anymore. The emission is over
22925 					 * and next_mp is NULL.
22926 					 */
22927 					if (ire1 == NULL) {
22928 						multirt_send = B_FALSE;
22929 					}
22930 				}
22931 
22932 				out_ill = ire->ire_ipif->ipif_ill;
22933 				DTRACE_PROBE4(ip4__physical__out__start,
22934 				    ill_t *, NULL,
22935 				    ill_t *, out_ill,
22936 				    ipha_t *, ipha, mblk_t *, mp);
22937 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
22938 				    ipst->ips_ipv4firewall_physical_out,
22939 				    NULL, out_ill, ipha, mp, mp, ipst);
22940 				DTRACE_PROBE1(ip4__physical__out__end,
22941 				    mblk_t *, mp);
22942 				if (mp == NULL)
22943 					goto release_ire_and_ill_2;
22944 
22945 				ASSERT(ipsec_len == 0);
22946 				mp->b_prev =
22947 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22948 				DTRACE_PROBE2(ip__xmit__2,
22949 				    mblk_t *, mp, ire_t *, ire);
22950 				pktxmit_state = ip_xmit_v4(mp, ire,
22951 				    NULL, B_TRUE);
22952 				if ((pktxmit_state == SEND_FAILED) ||
22953 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22954 release_ire_and_ill_2:
22955 					if (next_mp) {
22956 						freemsg(next_mp);
22957 						ire_refrele(ire1);
22958 					}
22959 					ire_refrele(ire);
22960 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22961 					    "ip_wput_ire_end: q %p (%S)",
22962 					    q, "discard MDATA");
22963 					if (conn_outgoing_ill != NULL)
22964 						ill_refrele(conn_outgoing_ill);
22965 					return;
22966 				}
22967 
22968 				if (CLASSD(dst)) {
22969 					BUMP_MIB(out_ill->ill_ip_mib,
22970 					    ipIfStatsHCOutMcastPkts);
22971 					UPDATE_MIB(out_ill->ill_ip_mib,
22972 					    ipIfStatsHCOutMcastOctets,
22973 					    LENGTH);
22974 				} else if (ire->ire_type == IRE_BROADCAST) {
22975 					BUMP_MIB(out_ill->ill_ip_mib,
22976 					    ipIfStatsHCOutBcastPkts);
22977 				}
22978 
22979 				if (multirt_send) {
22980 					/*
22981 					 * We are in a multiple send case,
22982 					 * need to re-enter the sending loop
22983 					 * using the next ire.
22984 					 */
22985 					ire_refrele(ire);
22986 					ire = ire1;
22987 					stq = ire->ire_stq;
22988 					mp = next_mp;
22989 					next_mp = NULL;
22990 					ipha = (ipha_t *)mp->b_rptr;
22991 					ill_index = Q_TO_INDEX(stq);
22992 				}
22993 			} while (multirt_send);
22994 
22995 			if (!next_mp) {
22996 				/*
22997 				 * Last copy going out (the ultra-common
22998 				 * case).  Note that we intentionally replicate
22999 				 * the putnext rather than calling it before
23000 				 * the next_mp check in hopes of a little
23001 				 * tail-call action out of the compiler.
23002 				 */
23003 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23004 				    "ip_wput_ire_end: q %p (%S)",
23005 				    q, "last copy out(1)");
23006 				ire_refrele(ire);
23007 				if (conn_outgoing_ill != NULL)
23008 					ill_refrele(conn_outgoing_ill);
23009 				return;
23010 			}
23011 			/* More copies going out below. */
23012 		} else {
23013 			int offset;
23014 fragmentit:
23015 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23016 			/*
23017 			 * If this would generate a icmp_frag_needed message,
23018 			 * we need to handle it before we do the IPSEC
23019 			 * processing. Otherwise, we need to strip the IPSEC
23020 			 * headers before we send up the message to the ULPs
23021 			 * which becomes messy and difficult.
23022 			 */
23023 			if (ipsec_len != 0) {
23024 				if ((max_frag < (unsigned int)(LENGTH +
23025 				    ipsec_len)) && (offset & IPH_DF)) {
23026 					out_ill = (ill_t *)stq->q_ptr;
23027 					BUMP_MIB(out_ill->ill_ip_mib,
23028 					    ipIfStatsOutFragFails);
23029 					BUMP_MIB(out_ill->ill_ip_mib,
23030 					    ipIfStatsOutFragReqds);
23031 					ipha->ipha_hdr_checksum = 0;
23032 					ipha->ipha_hdr_checksum =
23033 					    (uint16_t)ip_csum_hdr(ipha);
23034 					icmp_frag_needed(ire->ire_stq, first_mp,
23035 					    max_frag, zoneid, ipst);
23036 					if (!next_mp) {
23037 						ire_refrele(ire);
23038 						if (conn_outgoing_ill != NULL) {
23039 							ill_refrele(
23040 							    conn_outgoing_ill);
23041 						}
23042 						return;
23043 					}
23044 				} else {
23045 					/*
23046 					 * This won't cause a icmp_frag_needed
23047 					 * message. to be generated. Send it on
23048 					 * the wire. Note that this could still
23049 					 * cause fragmentation and all we
23050 					 * do is the generation of the message
23051 					 * to the ULP if needed before IPSEC.
23052 					 */
23053 					if (!next_mp) {
23054 						ipsec_out_process(q, first_mp,
23055 						    ire, ill_index);
23056 						TRACE_2(TR_FAC_IP,
23057 						    TR_IP_WPUT_IRE_END,
23058 						    "ip_wput_ire_end: q %p "
23059 						    "(%S)", q,
23060 						    "last ipsec_out_process");
23061 						ire_refrele(ire);
23062 						if (conn_outgoing_ill != NULL) {
23063 							ill_refrele(
23064 							    conn_outgoing_ill);
23065 						}
23066 						return;
23067 					}
23068 					ipsec_out_process(q, first_mp,
23069 					    ire, ill_index);
23070 				}
23071 			} else {
23072 				/*
23073 				 * Initiate IPPF processing. For
23074 				 * fragmentable packets we finish
23075 				 * all QOS packet processing before
23076 				 * calling:
23077 				 * ip_wput_ire_fragmentit->ip_wput_frag
23078 				 */
23079 
23080 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23081 					ip_process(IPP_LOCAL_OUT, &mp,
23082 					    ill_index);
23083 					if (mp == NULL) {
23084 						out_ill = (ill_t *)stq->q_ptr;
23085 						BUMP_MIB(out_ill->ill_ip_mib,
23086 						    ipIfStatsOutDiscards);
23087 						if (next_mp != NULL) {
23088 							freemsg(next_mp);
23089 							ire_refrele(ire1);
23090 						}
23091 						ire_refrele(ire);
23092 						TRACE_2(TR_FAC_IP,
23093 						    TR_IP_WPUT_IRE_END,
23094 						    "ip_wput_ire: q %p (%S)",
23095 						    q, "discard MDATA");
23096 						if (conn_outgoing_ill != NULL) {
23097 							ill_refrele(
23098 							    conn_outgoing_ill);
23099 						}
23100 						return;
23101 					}
23102 				}
23103 				if (!next_mp) {
23104 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23105 					    "ip_wput_ire_end: q %p (%S)",
23106 					    q, "last fragmentation");
23107 					ip_wput_ire_fragmentit(mp, ire,
23108 					    zoneid, ipst);
23109 					ire_refrele(ire);
23110 					if (conn_outgoing_ill != NULL)
23111 						ill_refrele(conn_outgoing_ill);
23112 					return;
23113 				}
23114 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23115 			}
23116 		}
23117 	} else {
23118 nullstq:
23119 		/* A NULL stq means the destination address is local. */
23120 		UPDATE_OB_PKT_COUNT(ire);
23121 		ire->ire_last_used_time = lbolt;
23122 		ASSERT(ire->ire_ipif != NULL);
23123 		if (!next_mp) {
23124 			/*
23125 			 * Is there an "in" and "out" for traffic local
23126 			 * to a host (loopback)?  The code in Solaris doesn't
23127 			 * explicitly draw a line in its code for in vs out,
23128 			 * so we've had to draw a line in the sand: ip_wput_ire
23129 			 * is considered to be the "output" side and
23130 			 * ip_wput_local to be the "input" side.
23131 			 */
23132 			out_ill = ire->ire_ipif->ipif_ill;
23133 
23134 			DTRACE_PROBE4(ip4__loopback__out__start,
23135 			    ill_t *, NULL, ill_t *, out_ill,
23136 			    ipha_t *, ipha, mblk_t *, first_mp);
23137 
23138 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23139 			    ipst->ips_ipv4firewall_loopback_out,
23140 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23141 
23142 			DTRACE_PROBE1(ip4__loopback__out_end,
23143 			    mblk_t *, first_mp);
23144 
23145 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23146 			    "ip_wput_ire_end: q %p (%S)",
23147 			    q, "local address");
23148 
23149 			if (first_mp != NULL)
23150 				ip_wput_local(q, out_ill, ipha,
23151 				    first_mp, ire, 0, ire->ire_zoneid);
23152 			ire_refrele(ire);
23153 			if (conn_outgoing_ill != NULL)
23154 				ill_refrele(conn_outgoing_ill);
23155 			return;
23156 		}
23157 
23158 		out_ill = ire->ire_ipif->ipif_ill;
23159 
23160 		DTRACE_PROBE4(ip4__loopback__out__start,
23161 		    ill_t *, NULL, ill_t *, out_ill,
23162 		    ipha_t *, ipha, mblk_t *, first_mp);
23163 
23164 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23165 		    ipst->ips_ipv4firewall_loopback_out,
23166 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23167 
23168 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23169 
23170 		if (first_mp != NULL)
23171 			ip_wput_local(q, out_ill, ipha,
23172 			    first_mp, ire, 0, ire->ire_zoneid);
23173 	}
23174 next:
23175 	/*
23176 	 * More copies going out to additional interfaces.
23177 	 * ire1 has already been held. We don't need the
23178 	 * "ire" anymore.
23179 	 */
23180 	ire_refrele(ire);
23181 	ire = ire1;
23182 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23183 	mp = next_mp;
23184 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23185 	ill = ire_to_ill(ire);
23186 	first_mp = mp;
23187 	if (ipsec_len != 0) {
23188 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23189 		mp = mp->b_cont;
23190 	}
23191 	dst = ire->ire_addr;
23192 	ipha = (ipha_t *)mp->b_rptr;
23193 	/*
23194 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23195 	 * Restore ipha_ident "no checksum" flag.
23196 	 */
23197 	src = orig_src;
23198 	ipha->ipha_ident = ip_hdr_included;
23199 	goto another;
23200 
23201 #undef	rptr
23202 #undef	Q_TO_INDEX
23203 }
23204 
23205 /*
23206  * Routine to allocate a message that is used to notify the ULP about MDT.
23207  * The caller may provide a pointer to the link-layer MDT capabilities,
23208  * or NULL if MDT is to be disabled on the stream.
23209  */
23210 mblk_t *
23211 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23212 {
23213 	mblk_t *mp;
23214 	ip_mdt_info_t *mdti;
23215 	ill_mdt_capab_t *idst;
23216 
23217 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23218 		DB_TYPE(mp) = M_CTL;
23219 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23220 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23221 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23222 		idst = &(mdti->mdt_capab);
23223 
23224 		/*
23225 		 * If the caller provides us with the capability, copy
23226 		 * it over into our notification message; otherwise
23227 		 * we zero out the capability portion.
23228 		 */
23229 		if (isrc != NULL)
23230 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23231 		else
23232 			bzero((caddr_t)idst, sizeof (*idst));
23233 	}
23234 	return (mp);
23235 }
23236 
23237 /*
23238  * Routine which determines whether MDT can be enabled on the destination
23239  * IRE and IPC combination, and if so, allocates and returns the MDT
23240  * notification mblk that may be used by ULP.  We also check if we need to
23241  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23242  * MDT usage in the past have been lifted.  This gets called during IP
23243  * and ULP binding.
23244  */
23245 mblk_t *
23246 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23247     ill_mdt_capab_t *mdt_cap)
23248 {
23249 	mblk_t *mp;
23250 	boolean_t rc = B_FALSE;
23251 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23252 
23253 	ASSERT(dst_ire != NULL);
23254 	ASSERT(connp != NULL);
23255 	ASSERT(mdt_cap != NULL);
23256 
23257 	/*
23258 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23259 	 * Multidata, which is handled in tcp_multisend().  This
23260 	 * is the reason why we do all these checks here, to ensure
23261 	 * that we don't enable Multidata for the cases which we
23262 	 * can't handle at the moment.
23263 	 */
23264 	do {
23265 		/* Only do TCP at the moment */
23266 		if (connp->conn_ulp != IPPROTO_TCP)
23267 			break;
23268 
23269 		/*
23270 		 * IPSEC outbound policy present?  Note that we get here
23271 		 * after calling ipsec_conn_cache_policy() where the global
23272 		 * policy checking is performed.  conn_latch will be
23273 		 * non-NULL as long as there's a policy defined,
23274 		 * i.e. conn_out_enforce_policy may be NULL in such case
23275 		 * when the connection is non-secure, and hence we check
23276 		 * further if the latch refers to an outbound policy.
23277 		 */
23278 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23279 			break;
23280 
23281 		/* CGTP (multiroute) is enabled? */
23282 		if (dst_ire->ire_flags & RTF_MULTIRT)
23283 			break;
23284 
23285 		/* Outbound IPQoS enabled? */
23286 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23287 			/*
23288 			 * In this case, we disable MDT for this and all
23289 			 * future connections going over the interface.
23290 			 */
23291 			mdt_cap->ill_mdt_on = 0;
23292 			break;
23293 		}
23294 
23295 		/* socket option(s) present? */
23296 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23297 			break;
23298 
23299 		rc = B_TRUE;
23300 	/* CONSTCOND */
23301 	} while (0);
23302 
23303 	/* Remember the result */
23304 	connp->conn_mdt_ok = rc;
23305 
23306 	if (!rc)
23307 		return (NULL);
23308 	else if (!mdt_cap->ill_mdt_on) {
23309 		/*
23310 		 * If MDT has been previously turned off in the past, and we
23311 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23312 		 * then enable it for this interface.
23313 		 */
23314 		mdt_cap->ill_mdt_on = 1;
23315 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23316 		    "interface %s\n", ill_name));
23317 	}
23318 
23319 	/* Allocate the MDT info mblk */
23320 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23321 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23322 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23323 		return (NULL);
23324 	}
23325 	return (mp);
23326 }
23327 
23328 /*
23329  * Routine to allocate a message that is used to notify the ULP about LSO.
23330  * The caller may provide a pointer to the link-layer LSO capabilities,
23331  * or NULL if LSO is to be disabled on the stream.
23332  */
23333 mblk_t *
23334 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23335 {
23336 	mblk_t *mp;
23337 	ip_lso_info_t *lsoi;
23338 	ill_lso_capab_t *idst;
23339 
23340 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23341 		DB_TYPE(mp) = M_CTL;
23342 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23343 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23344 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23345 		idst = &(lsoi->lso_capab);
23346 
23347 		/*
23348 		 * If the caller provides us with the capability, copy
23349 		 * it over into our notification message; otherwise
23350 		 * we zero out the capability portion.
23351 		 */
23352 		if (isrc != NULL)
23353 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23354 		else
23355 			bzero((caddr_t)idst, sizeof (*idst));
23356 	}
23357 	return (mp);
23358 }
23359 
23360 /*
23361  * Routine which determines whether LSO can be enabled on the destination
23362  * IRE and IPC combination, and if so, allocates and returns the LSO
23363  * notification mblk that may be used by ULP.  We also check if we need to
23364  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23365  * LSO usage in the past have been lifted.  This gets called during IP
23366  * and ULP binding.
23367  */
23368 mblk_t *
23369 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23370     ill_lso_capab_t *lso_cap)
23371 {
23372 	mblk_t *mp;
23373 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23374 
23375 	ASSERT(dst_ire != NULL);
23376 	ASSERT(connp != NULL);
23377 	ASSERT(lso_cap != NULL);
23378 
23379 	connp->conn_lso_ok = B_TRUE;
23380 
23381 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23382 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23383 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23384 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23385 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23386 		connp->conn_lso_ok = B_FALSE;
23387 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23388 			/*
23389 			 * Disable LSO for this and all future connections going
23390 			 * over the interface.
23391 			 */
23392 			lso_cap->ill_lso_on = 0;
23393 		}
23394 	}
23395 
23396 	if (!connp->conn_lso_ok)
23397 		return (NULL);
23398 	else if (!lso_cap->ill_lso_on) {
23399 		/*
23400 		 * If LSO has been previously turned off in the past, and we
23401 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23402 		 * then enable it for this interface.
23403 		 */
23404 		lso_cap->ill_lso_on = 1;
23405 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23406 		    ill_name));
23407 	}
23408 
23409 	/* Allocate the LSO info mblk */
23410 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23411 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23412 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23413 
23414 	return (mp);
23415 }
23416 
23417 /*
23418  * Create destination address attribute, and fill it with the physical
23419  * destination address and SAP taken from the template DL_UNITDATA_REQ
23420  * message block.
23421  */
23422 boolean_t
23423 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23424 {
23425 	dl_unitdata_req_t *dlurp;
23426 	pattr_t *pa;
23427 	pattrinfo_t pa_info;
23428 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23429 	uint_t das_len, das_off;
23430 
23431 	ASSERT(dlmp != NULL);
23432 
23433 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23434 	das_len = dlurp->dl_dest_addr_length;
23435 	das_off = dlurp->dl_dest_addr_offset;
23436 
23437 	pa_info.type = PATTR_DSTADDRSAP;
23438 	pa_info.len = sizeof (**das) + das_len - 1;
23439 
23440 	/* create and associate the attribute */
23441 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23442 	if (pa != NULL) {
23443 		ASSERT(*das != NULL);
23444 		(*das)->addr_is_group = 0;
23445 		(*das)->addr_len = (uint8_t)das_len;
23446 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23447 	}
23448 
23449 	return (pa != NULL);
23450 }
23451 
23452 /*
23453  * Create hardware checksum attribute and fill it with the values passed.
23454  */
23455 boolean_t
23456 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23457     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23458 {
23459 	pattr_t *pa;
23460 	pattrinfo_t pa_info;
23461 
23462 	ASSERT(mmd != NULL);
23463 
23464 	pa_info.type = PATTR_HCKSUM;
23465 	pa_info.len = sizeof (pattr_hcksum_t);
23466 
23467 	/* create and associate the attribute */
23468 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23469 	if (pa != NULL) {
23470 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23471 
23472 		hck->hcksum_start_offset = start_offset;
23473 		hck->hcksum_stuff_offset = stuff_offset;
23474 		hck->hcksum_end_offset = end_offset;
23475 		hck->hcksum_flags = flags;
23476 	}
23477 	return (pa != NULL);
23478 }
23479 
23480 /*
23481  * Create zerocopy attribute and fill it with the specified flags
23482  */
23483 boolean_t
23484 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23485 {
23486 	pattr_t *pa;
23487 	pattrinfo_t pa_info;
23488 
23489 	ASSERT(mmd != NULL);
23490 	pa_info.type = PATTR_ZCOPY;
23491 	pa_info.len = sizeof (pattr_zcopy_t);
23492 
23493 	/* create and associate the attribute */
23494 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23495 	if (pa != NULL) {
23496 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23497 
23498 		zcopy->zcopy_flags = flags;
23499 	}
23500 	return (pa != NULL);
23501 }
23502 
23503 /*
23504  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23505  * block chain. We could rewrite to handle arbitrary message block chains but
23506  * that would make the code complicated and slow. Right now there three
23507  * restrictions:
23508  *
23509  *   1. The first message block must contain the complete IP header and
23510  *	at least 1 byte of payload data.
23511  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23512  *	so that we can use a single Multidata message.
23513  *   3. No frag must be distributed over two or more message blocks so
23514  *	that we don't need more than two packet descriptors per frag.
23515  *
23516  * The above restrictions allow us to support userland applications (which
23517  * will send down a single message block) and NFS over UDP (which will
23518  * send down a chain of at most three message blocks).
23519  *
23520  * We also don't use MDT for payloads with less than or equal to
23521  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23522  */
23523 boolean_t
23524 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23525 {
23526 	int	blocks;
23527 	ssize_t	total, missing, size;
23528 
23529 	ASSERT(mp != NULL);
23530 	ASSERT(hdr_len > 0);
23531 
23532 	size = MBLKL(mp) - hdr_len;
23533 	if (size <= 0)
23534 		return (B_FALSE);
23535 
23536 	/* The first mblk contains the header and some payload. */
23537 	blocks = 1;
23538 	total = size;
23539 	size %= len;
23540 	missing = (size == 0) ? 0 : (len - size);
23541 	mp = mp->b_cont;
23542 
23543 	while (mp != NULL) {
23544 		/*
23545 		 * Give up if we encounter a zero length message block.
23546 		 * In practice, this should rarely happen and therefore
23547 		 * not worth the trouble of freeing and re-linking the
23548 		 * mblk from the chain to handle such case.
23549 		 */
23550 		if ((size = MBLKL(mp)) == 0)
23551 			return (B_FALSE);
23552 
23553 		/* Too many payload buffers for a single Multidata message? */
23554 		if (++blocks > MULTIDATA_MAX_PBUFS)
23555 			return (B_FALSE);
23556 
23557 		total += size;
23558 		/* Is a frag distributed over two or more message blocks? */
23559 		if (missing > size)
23560 			return (B_FALSE);
23561 		size -= missing;
23562 
23563 		size %= len;
23564 		missing = (size == 0) ? 0 : (len - size);
23565 
23566 		mp = mp->b_cont;
23567 	}
23568 
23569 	return (total > ip_wput_frag_mdt_min);
23570 }
23571 
23572 /*
23573  * Outbound IPv4 fragmentation routine using MDT.
23574  */
23575 static void
23576 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23577     uint32_t frag_flag, int offset)
23578 {
23579 	ipha_t		*ipha_orig;
23580 	int		i1, ip_data_end;
23581 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23582 	mblk_t		*hdr_mp, *md_mp = NULL;
23583 	unsigned char	*hdr_ptr, *pld_ptr;
23584 	multidata_t	*mmd;
23585 	ip_pdescinfo_t	pdi;
23586 	ill_t		*ill;
23587 	ip_stack_t	*ipst = ire->ire_ipst;
23588 
23589 	ASSERT(DB_TYPE(mp) == M_DATA);
23590 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23591 
23592 	ill = ire_to_ill(ire);
23593 	ASSERT(ill != NULL);
23594 
23595 	ipha_orig = (ipha_t *)mp->b_rptr;
23596 	mp->b_rptr += sizeof (ipha_t);
23597 
23598 	/* Calculate how many packets we will send out */
23599 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23600 	pkts = (i1 + len - 1) / len;
23601 	ASSERT(pkts > 1);
23602 
23603 	/* Allocate a message block which will hold all the IP Headers. */
23604 	wroff = ipst->ips_ip_wroff_extra;
23605 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23606 
23607 	i1 = pkts * hdr_chunk_len;
23608 	/*
23609 	 * Create the header buffer, Multidata and destination address
23610 	 * and SAP attribute that should be associated with it.
23611 	 */
23612 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23613 	    ((hdr_mp->b_wptr += i1),
23614 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23615 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23616 		freemsg(mp);
23617 		if (md_mp == NULL) {
23618 			freemsg(hdr_mp);
23619 		} else {
23620 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23621 			freemsg(md_mp);
23622 		}
23623 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23624 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23625 		return;
23626 	}
23627 	IP_STAT(ipst, ip_frag_mdt_allocd);
23628 
23629 	/*
23630 	 * Add a payload buffer to the Multidata; this operation must not
23631 	 * fail, or otherwise our logic in this routine is broken.  There
23632 	 * is no memory allocation done by the routine, so any returned
23633 	 * failure simply tells us that we've done something wrong.
23634 	 *
23635 	 * A failure tells us that either we're adding the same payload
23636 	 * buffer more than once, or we're trying to add more buffers than
23637 	 * allowed.  None of the above cases should happen, and we panic
23638 	 * because either there's horrible heap corruption, and/or
23639 	 * programming mistake.
23640 	 */
23641 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23642 		goto pbuf_panic;
23643 
23644 	hdr_ptr = hdr_mp->b_rptr;
23645 	pld_ptr = mp->b_rptr;
23646 
23647 	/* Establish the ending byte offset, based on the starting offset. */
23648 	offset <<= 3;
23649 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23650 	    IP_SIMPLE_HDR_LENGTH;
23651 
23652 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23653 
23654 	while (pld_ptr < mp->b_wptr) {
23655 		ipha_t		*ipha;
23656 		uint16_t	offset_and_flags;
23657 		uint16_t	ip_len;
23658 		int		error;
23659 
23660 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23661 		ipha = (ipha_t *)(hdr_ptr + wroff);
23662 		ASSERT(OK_32PTR(ipha));
23663 		*ipha = *ipha_orig;
23664 
23665 		if (ip_data_end - offset > len) {
23666 			offset_and_flags = IPH_MF;
23667 		} else {
23668 			/*
23669 			 * Last frag. Set len to the length of this last piece.
23670 			 */
23671 			len = ip_data_end - offset;
23672 			/* A frag of a frag might have IPH_MF non-zero */
23673 			offset_and_flags =
23674 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23675 			    IPH_MF;
23676 		}
23677 		offset_and_flags |= (uint16_t)(offset >> 3);
23678 		offset_and_flags |= (uint16_t)frag_flag;
23679 		/* Store the offset and flags in the IP header. */
23680 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23681 
23682 		/* Store the length in the IP header. */
23683 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23684 		ipha->ipha_length = htons(ip_len);
23685 
23686 		/*
23687 		 * Set the IP header checksum.  Note that mp is just
23688 		 * the header, so this is easy to pass to ip_csum.
23689 		 */
23690 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23691 
23692 		/*
23693 		 * Record offset and size of header and data of the next packet
23694 		 * in the multidata message.
23695 		 */
23696 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23697 		PDESC_PLD_INIT(&pdi);
23698 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23699 		ASSERT(i1 > 0);
23700 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23701 		if (i1 == len) {
23702 			pld_ptr += len;
23703 		} else {
23704 			i1 = len - i1;
23705 			mp = mp->b_cont;
23706 			ASSERT(mp != NULL);
23707 			ASSERT(MBLKL(mp) >= i1);
23708 			/*
23709 			 * Attach the next payload message block to the
23710 			 * multidata message.
23711 			 */
23712 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23713 				goto pbuf_panic;
23714 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23715 			pld_ptr = mp->b_rptr + i1;
23716 		}
23717 
23718 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23719 		    KM_NOSLEEP)) == NULL) {
23720 			/*
23721 			 * Any failure other than ENOMEM indicates that we
23722 			 * have passed in invalid pdesc info or parameters
23723 			 * to mmd_addpdesc, which must not happen.
23724 			 *
23725 			 * EINVAL is a result of failure on boundary checks
23726 			 * against the pdesc info contents.  It should not
23727 			 * happen, and we panic because either there's
23728 			 * horrible heap corruption, and/or programming
23729 			 * mistake.
23730 			 */
23731 			if (error != ENOMEM) {
23732 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23733 				    "pdesc logic error detected for "
23734 				    "mmd %p pinfo %p (%d)\n",
23735 				    (void *)mmd, (void *)&pdi, error);
23736 				/* NOTREACHED */
23737 			}
23738 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23739 			/* Free unattached payload message blocks as well */
23740 			md_mp->b_cont = mp->b_cont;
23741 			goto free_mmd;
23742 		}
23743 
23744 		/* Advance fragment offset. */
23745 		offset += len;
23746 
23747 		/* Advance to location for next header in the buffer. */
23748 		hdr_ptr += hdr_chunk_len;
23749 
23750 		/* Did we reach the next payload message block? */
23751 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23752 			mp = mp->b_cont;
23753 			/*
23754 			 * Attach the next message block with payload
23755 			 * data to the multidata message.
23756 			 */
23757 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23758 				goto pbuf_panic;
23759 			pld_ptr = mp->b_rptr;
23760 		}
23761 	}
23762 
23763 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23764 	ASSERT(mp->b_wptr == pld_ptr);
23765 
23766 	/* Update IP statistics */
23767 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23768 
23769 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23770 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23771 
23772 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23773 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23774 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23775 
23776 	if (pkt_type == OB_PKT) {
23777 		ire->ire_ob_pkt_count += pkts;
23778 		if (ire->ire_ipif != NULL)
23779 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23780 	} else {
23781 		/* The type is IB_PKT in the forwarding path. */
23782 		ire->ire_ib_pkt_count += pkts;
23783 		ASSERT(!IRE_IS_LOCAL(ire));
23784 		if (ire->ire_type & IRE_BROADCAST) {
23785 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23786 		} else {
23787 			UPDATE_MIB(ill->ill_ip_mib,
23788 			    ipIfStatsHCOutForwDatagrams, pkts);
23789 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23790 		}
23791 	}
23792 	ire->ire_last_used_time = lbolt;
23793 	/* Send it down */
23794 	putnext(ire->ire_stq, md_mp);
23795 	return;
23796 
23797 pbuf_panic:
23798 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23799 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23800 	    pbuf_idx);
23801 	/* NOTREACHED */
23802 }
23803 
23804 /*
23805  * Outbound IP fragmentation routine.
23806  *
23807  * NOTE : This routine does not ire_refrele the ire that is passed in
23808  * as the argument.
23809  */
23810 static void
23811 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23812     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
23813 {
23814 	int		i1;
23815 	mblk_t		*ll_hdr_mp;
23816 	int 		ll_hdr_len;
23817 	int		hdr_len;
23818 	mblk_t		*hdr_mp;
23819 	ipha_t		*ipha;
23820 	int		ip_data_end;
23821 	int		len;
23822 	mblk_t		*mp = mp_orig, *mp1;
23823 	int		offset;
23824 	queue_t		*q;
23825 	uint32_t	v_hlen_tos_len;
23826 	mblk_t		*first_mp;
23827 	boolean_t	mctl_present;
23828 	ill_t		*ill;
23829 	ill_t		*out_ill;
23830 	mblk_t		*xmit_mp;
23831 	mblk_t		*carve_mp;
23832 	ire_t		*ire1 = NULL;
23833 	ire_t		*save_ire = NULL;
23834 	mblk_t  	*next_mp = NULL;
23835 	boolean_t	last_frag = B_FALSE;
23836 	boolean_t	multirt_send = B_FALSE;
23837 	ire_t		*first_ire = NULL;
23838 	irb_t		*irb = NULL;
23839 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23840 
23841 	ill = ire_to_ill(ire);
23842 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
23843 
23844 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
23845 
23846 	if (max_frag == 0) {
23847 		ip1dbg(("ip_wput_frag: ire frag size is 0"
23848 		    " -  dropping packet\n"));
23849 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23850 		freemsg(mp);
23851 		return;
23852 	}
23853 
23854 	/*
23855 	 * IPSEC does not allow hw accelerated packets to be fragmented
23856 	 * This check is made in ip_wput_ipsec_out prior to coming here
23857 	 * via ip_wput_ire_fragmentit.
23858 	 *
23859 	 * If at this point we have an ire whose ARP request has not
23860 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23861 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23862 	 * This packet and all fragmentable packets for this ire will
23863 	 * continue to get dropped while ire_nce->nce_state remains in
23864 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23865 	 * ND_REACHABLE, all subsquent large packets for this ire will
23866 	 * get fragemented and sent out by this function.
23867 	 */
23868 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23869 		/* If nce_state is ND_INITIAL, trigger ARP query */
23870 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23871 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23872 		    " -  dropping packet\n"));
23873 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23874 		freemsg(mp);
23875 		return;
23876 	}
23877 
23878 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23879 	    "ip_wput_frag_start:");
23880 
23881 	if (mp->b_datap->db_type == M_CTL) {
23882 		first_mp = mp;
23883 		mp_orig = mp = mp->b_cont;
23884 		mctl_present = B_TRUE;
23885 	} else {
23886 		first_mp = mp;
23887 		mctl_present = B_FALSE;
23888 	}
23889 
23890 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23891 	ipha = (ipha_t *)mp->b_rptr;
23892 
23893 	/*
23894 	 * If the Don't Fragment flag is on, generate an ICMP destination
23895 	 * unreachable, fragmentation needed.
23896 	 */
23897 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23898 	if (offset & IPH_DF) {
23899 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23900 		if (is_system_labeled()) {
23901 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
23902 			    ire->ire_max_frag - max_frag, AF_INET);
23903 		}
23904 		/*
23905 		 * Need to compute hdr checksum if called from ip_wput_ire.
23906 		 * Note that ip_rput_forward verifies the checksum before
23907 		 * calling this routine so in that case this is a noop.
23908 		 */
23909 		ipha->ipha_hdr_checksum = 0;
23910 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23911 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
23912 		    ipst);
23913 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23914 		    "ip_wput_frag_end:(%S)",
23915 		    "don't fragment");
23916 		return;
23917 	}
23918 	/*
23919 	 * Labeled systems adjust max_frag if they add a label
23920 	 * to send the correct path mtu.  We need the real mtu since we
23921 	 * are fragmenting the packet after label adjustment.
23922 	 */
23923 	if (is_system_labeled())
23924 		max_frag = ire->ire_max_frag;
23925 	if (mctl_present)
23926 		freeb(first_mp);
23927 	/*
23928 	 * Establish the starting offset.  May not be zero if we are fragging
23929 	 * a fragment that is being forwarded.
23930 	 */
23931 	offset = offset & IPH_OFFSET;
23932 
23933 	/* TODO why is this test needed? */
23934 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23935 	if (((max_frag - LENGTH) & ~7) < 8) {
23936 		/* TODO: notify ulp somehow */
23937 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23938 		freemsg(mp);
23939 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23940 		    "ip_wput_frag_end:(%S)",
23941 		    "len < 8");
23942 		return;
23943 	}
23944 
23945 	hdr_len = (V_HLEN & 0xF) << 2;
23946 
23947 	ipha->ipha_hdr_checksum = 0;
23948 
23949 	/*
23950 	 * Establish the number of bytes maximum per frag, after putting
23951 	 * in the header.
23952 	 */
23953 	len = (max_frag - hdr_len) & ~7;
23954 
23955 	/* Check if we can use MDT to send out the frags. */
23956 	ASSERT(!IRE_IS_LOCAL(ire));
23957 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
23958 	    ipst->ips_ip_multidata_outbound &&
23959 	    !(ire->ire_flags & RTF_MULTIRT) &&
23960 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
23961 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
23962 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23963 		ASSERT(ill->ill_mdt_capab != NULL);
23964 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23965 			/*
23966 			 * If MDT has been previously turned off in the past,
23967 			 * and we currently can do MDT (due to IPQoS policy
23968 			 * removal, etc.) then enable it for this interface.
23969 			 */
23970 			ill->ill_mdt_capab->ill_mdt_on = 1;
23971 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23972 			    ill->ill_name));
23973 		}
23974 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23975 		    offset);
23976 		return;
23977 	}
23978 
23979 	/* Get a copy of the header for the trailing frags */
23980 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
23981 	if (!hdr_mp) {
23982 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23983 		freemsg(mp);
23984 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23985 		    "ip_wput_frag_end:(%S)",
23986 		    "couldn't copy hdr");
23987 		return;
23988 	}
23989 	if (DB_CRED(mp) != NULL)
23990 		mblk_setcred(hdr_mp, DB_CRED(mp));
23991 
23992 	/* Store the starting offset, with the MoreFrags flag. */
23993 	i1 = offset | IPH_MF | frag_flag;
23994 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23995 
23996 	/* Establish the ending byte offset, based on the starting offset. */
23997 	offset <<= 3;
23998 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23999 
24000 	/* Store the length of the first fragment in the IP header. */
24001 	i1 = len + hdr_len;
24002 	ASSERT(i1 <= IP_MAXPACKET);
24003 	ipha->ipha_length = htons((uint16_t)i1);
24004 
24005 	/*
24006 	 * Compute the IP header checksum for the first frag.  We have to
24007 	 * watch out that we stop at the end of the header.
24008 	 */
24009 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24010 
24011 	/*
24012 	 * Now carve off the first frag.  Note that this will include the
24013 	 * original IP header.
24014 	 */
24015 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24016 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24017 		freeb(hdr_mp);
24018 		freemsg(mp_orig);
24019 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24020 		    "ip_wput_frag_end:(%S)",
24021 		    "couldn't carve first");
24022 		return;
24023 	}
24024 
24025 	/*
24026 	 * Multirouting case. Each fragment is replicated
24027 	 * via all non-condemned RTF_MULTIRT routes
24028 	 * currently resolved.
24029 	 * We ensure that first_ire is the first RTF_MULTIRT
24030 	 * ire in the bucket.
24031 	 */
24032 	if (ire->ire_flags & RTF_MULTIRT) {
24033 		irb = ire->ire_bucket;
24034 		ASSERT(irb != NULL);
24035 
24036 		multirt_send = B_TRUE;
24037 
24038 		/* Make sure we do not omit any multiroute ire. */
24039 		IRB_REFHOLD(irb);
24040 		for (first_ire = irb->irb_ire;
24041 		    first_ire != NULL;
24042 		    first_ire = first_ire->ire_next) {
24043 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24044 			    (first_ire->ire_addr == ire->ire_addr) &&
24045 			    !(first_ire->ire_marks &
24046 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24047 				break;
24048 			}
24049 		}
24050 
24051 		if (first_ire != NULL) {
24052 			if (first_ire != ire) {
24053 				IRE_REFHOLD(first_ire);
24054 				/*
24055 				 * Do not release the ire passed in
24056 				 * as the argument.
24057 				 */
24058 				ire = first_ire;
24059 			} else {
24060 				first_ire = NULL;
24061 			}
24062 		}
24063 		IRB_REFRELE(irb);
24064 
24065 		/*
24066 		 * Save the first ire; we will need to restore it
24067 		 * for the trailing frags.
24068 		 * We REFHOLD save_ire, as each iterated ire will be
24069 		 * REFRELEd.
24070 		 */
24071 		save_ire = ire;
24072 		IRE_REFHOLD(save_ire);
24073 	}
24074 
24075 	/*
24076 	 * First fragment emission loop.
24077 	 * In most cases, the emission loop below is entered only
24078 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24079 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24080 	 * bucket, and send the fragment through all crossed
24081 	 * RTF_MULTIRT routes.
24082 	 */
24083 	do {
24084 		if (ire->ire_flags & RTF_MULTIRT) {
24085 			/*
24086 			 * We are in a multiple send case, need to get
24087 			 * the next ire and make a copy of the packet.
24088 			 * ire1 holds here the next ire to process in the
24089 			 * bucket. If multirouting is expected,
24090 			 * any non-RTF_MULTIRT ire that has the
24091 			 * right destination address is ignored.
24092 			 *
24093 			 * We have to take into account the MTU of
24094 			 * each walked ire. max_frag is set by the
24095 			 * the caller and generally refers to
24096 			 * the primary ire entry. Here we ensure that
24097 			 * no route with a lower MTU will be used, as
24098 			 * fragments are carved once for all ires,
24099 			 * then replicated.
24100 			 */
24101 			ASSERT(irb != NULL);
24102 			IRB_REFHOLD(irb);
24103 			for (ire1 = ire->ire_next;
24104 			    ire1 != NULL;
24105 			    ire1 = ire1->ire_next) {
24106 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24107 					continue;
24108 				if (ire1->ire_addr != ire->ire_addr)
24109 					continue;
24110 				if (ire1->ire_marks &
24111 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24112 					continue;
24113 				/*
24114 				 * Ensure we do not exceed the MTU
24115 				 * of the next route.
24116 				 */
24117 				if (ire1->ire_max_frag < max_frag) {
24118 					ip_multirt_bad_mtu(ire1, max_frag);
24119 					continue;
24120 				}
24121 
24122 				/* Got one. */
24123 				IRE_REFHOLD(ire1);
24124 				break;
24125 			}
24126 			IRB_REFRELE(irb);
24127 
24128 			if (ire1 != NULL) {
24129 				next_mp = copyb(mp);
24130 				if ((next_mp == NULL) ||
24131 				    ((mp->b_cont != NULL) &&
24132 				    ((next_mp->b_cont =
24133 				    dupmsg(mp->b_cont)) == NULL))) {
24134 					freemsg(next_mp);
24135 					next_mp = NULL;
24136 					ire_refrele(ire1);
24137 					ire1 = NULL;
24138 				}
24139 			}
24140 
24141 			/* Last multiroute ire; don't loop anymore. */
24142 			if (ire1 == NULL) {
24143 				multirt_send = B_FALSE;
24144 			}
24145 		}
24146 
24147 		ll_hdr_len = 0;
24148 		LOCK_IRE_FP_MP(ire);
24149 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24150 		if (ll_hdr_mp != NULL) {
24151 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24152 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24153 		} else {
24154 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24155 		}
24156 
24157 		/* If there is a transmit header, get a copy for this frag. */
24158 		/*
24159 		 * TODO: should check db_ref before calling ip_carve_mp since
24160 		 * it might give us a dup.
24161 		 */
24162 		if (!ll_hdr_mp) {
24163 			/* No xmit header. */
24164 			xmit_mp = mp;
24165 
24166 		/* We have a link-layer header that can fit in our mblk. */
24167 		} else if (mp->b_datap->db_ref == 1 &&
24168 		    ll_hdr_len != 0 &&
24169 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24170 			/* M_DATA fastpath */
24171 			mp->b_rptr -= ll_hdr_len;
24172 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24173 			xmit_mp = mp;
24174 
24175 		/* Corner case if copyb has failed */
24176 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24177 			UNLOCK_IRE_FP_MP(ire);
24178 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24179 			freeb(hdr_mp);
24180 			freemsg(mp);
24181 			freemsg(mp_orig);
24182 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24183 			    "ip_wput_frag_end:(%S)",
24184 			    "discard");
24185 
24186 			if (multirt_send) {
24187 				ASSERT(ire1);
24188 				ASSERT(next_mp);
24189 
24190 				freemsg(next_mp);
24191 				ire_refrele(ire1);
24192 			}
24193 			if (save_ire != NULL)
24194 				IRE_REFRELE(save_ire);
24195 
24196 			if (first_ire != NULL)
24197 				ire_refrele(first_ire);
24198 			return;
24199 
24200 		/*
24201 		 * Case of res_mp OR the fastpath mp can't fit
24202 		 * in the mblk
24203 		 */
24204 		} else {
24205 			xmit_mp->b_cont = mp;
24206 			if (DB_CRED(mp) != NULL)
24207 				mblk_setcred(xmit_mp, DB_CRED(mp));
24208 			/*
24209 			 * Get priority marking, if any.
24210 			 * We propagate the CoS marking from the
24211 			 * original packet that went to QoS processing
24212 			 * in ip_wput_ire to the newly carved mp.
24213 			 */
24214 			if (DB_TYPE(xmit_mp) == M_DATA)
24215 				xmit_mp->b_band = mp->b_band;
24216 		}
24217 		UNLOCK_IRE_FP_MP(ire);
24218 
24219 		q = ire->ire_stq;
24220 		out_ill = (ill_t *)q->q_ptr;
24221 
24222 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24223 
24224 		DTRACE_PROBE4(ip4__physical__out__start,
24225 		    ill_t *, NULL, ill_t *, out_ill,
24226 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24227 
24228 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24229 		    ipst->ips_ipv4firewall_physical_out,
24230 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24231 
24232 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24233 
24234 		if (xmit_mp != NULL) {
24235 			putnext(q, xmit_mp);
24236 
24237 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24238 			UPDATE_MIB(out_ill->ill_ip_mib,
24239 			    ipIfStatsHCOutOctets, i1);
24240 
24241 			if (pkt_type != OB_PKT) {
24242 				/*
24243 				 * Update the packet count and MIB stats
24244 				 * of trailing RTF_MULTIRT ires.
24245 				 */
24246 				UPDATE_OB_PKT_COUNT(ire);
24247 				BUMP_MIB(out_ill->ill_ip_mib,
24248 				    ipIfStatsOutFragReqds);
24249 			}
24250 		}
24251 
24252 		if (multirt_send) {
24253 			/*
24254 			 * We are in a multiple send case; look for
24255 			 * the next ire and re-enter the loop.
24256 			 */
24257 			ASSERT(ire1);
24258 			ASSERT(next_mp);
24259 			/* REFRELE the current ire before looping */
24260 			ire_refrele(ire);
24261 			ire = ire1;
24262 			ire1 = NULL;
24263 			mp = next_mp;
24264 			next_mp = NULL;
24265 		}
24266 	} while (multirt_send);
24267 
24268 	ASSERT(ire1 == NULL);
24269 
24270 	/* Restore the original ire; we need it for the trailing frags */
24271 	if (save_ire != NULL) {
24272 		/* REFRELE the last iterated ire */
24273 		ire_refrele(ire);
24274 		/* save_ire has been REFHOLDed */
24275 		ire = save_ire;
24276 		save_ire = NULL;
24277 		q = ire->ire_stq;
24278 	}
24279 
24280 	if (pkt_type == OB_PKT) {
24281 		UPDATE_OB_PKT_COUNT(ire);
24282 	} else {
24283 		out_ill = (ill_t *)q->q_ptr;
24284 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24285 		UPDATE_IB_PKT_COUNT(ire);
24286 	}
24287 
24288 	/* Advance the offset to the second frag starting point. */
24289 	offset += len;
24290 	/*
24291 	 * Update hdr_len from the copied header - there might be less options
24292 	 * in the later fragments.
24293 	 */
24294 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24295 	/* Loop until done. */
24296 	for (;;) {
24297 		uint16_t	offset_and_flags;
24298 		uint16_t	ip_len;
24299 
24300 		if (ip_data_end - offset > len) {
24301 			/*
24302 			 * Carve off the appropriate amount from the original
24303 			 * datagram.
24304 			 */
24305 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24306 				mp = NULL;
24307 				break;
24308 			}
24309 			/*
24310 			 * More frags after this one.  Get another copy
24311 			 * of the header.
24312 			 */
24313 			if (carve_mp->b_datap->db_ref == 1 &&
24314 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24315 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24316 				/* Inline IP header */
24317 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24318 				    hdr_mp->b_rptr;
24319 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24320 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24321 				mp = carve_mp;
24322 			} else {
24323 				if (!(mp = copyb(hdr_mp))) {
24324 					freemsg(carve_mp);
24325 					break;
24326 				}
24327 				/* Get priority marking, if any. */
24328 				mp->b_band = carve_mp->b_band;
24329 				mp->b_cont = carve_mp;
24330 			}
24331 			ipha = (ipha_t *)mp->b_rptr;
24332 			offset_and_flags = IPH_MF;
24333 		} else {
24334 			/*
24335 			 * Last frag.  Consume the header. Set len to
24336 			 * the length of this last piece.
24337 			 */
24338 			len = ip_data_end - offset;
24339 
24340 			/*
24341 			 * Carve off the appropriate amount from the original
24342 			 * datagram.
24343 			 */
24344 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24345 				mp = NULL;
24346 				break;
24347 			}
24348 			if (carve_mp->b_datap->db_ref == 1 &&
24349 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24350 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24351 				/* Inline IP header */
24352 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24353 				    hdr_mp->b_rptr;
24354 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24355 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24356 				mp = carve_mp;
24357 				freeb(hdr_mp);
24358 				hdr_mp = mp;
24359 			} else {
24360 				mp = hdr_mp;
24361 				/* Get priority marking, if any. */
24362 				mp->b_band = carve_mp->b_band;
24363 				mp->b_cont = carve_mp;
24364 			}
24365 			ipha = (ipha_t *)mp->b_rptr;
24366 			/* A frag of a frag might have IPH_MF non-zero */
24367 			offset_and_flags =
24368 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24369 			    IPH_MF;
24370 		}
24371 		offset_and_flags |= (uint16_t)(offset >> 3);
24372 		offset_and_flags |= (uint16_t)frag_flag;
24373 		/* Store the offset and flags in the IP header. */
24374 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24375 
24376 		/* Store the length in the IP header. */
24377 		ip_len = (uint16_t)(len + hdr_len);
24378 		ipha->ipha_length = htons(ip_len);
24379 
24380 		/*
24381 		 * Set the IP header checksum.	Note that mp is just
24382 		 * the header, so this is easy to pass to ip_csum.
24383 		 */
24384 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24385 
24386 		/* Attach a transmit header, if any, and ship it. */
24387 		if (pkt_type == OB_PKT) {
24388 			UPDATE_OB_PKT_COUNT(ire);
24389 		} else {
24390 			out_ill = (ill_t *)q->q_ptr;
24391 			BUMP_MIB(out_ill->ill_ip_mib,
24392 			    ipIfStatsHCOutForwDatagrams);
24393 			UPDATE_IB_PKT_COUNT(ire);
24394 		}
24395 
24396 		if (ire->ire_flags & RTF_MULTIRT) {
24397 			irb = ire->ire_bucket;
24398 			ASSERT(irb != NULL);
24399 
24400 			multirt_send = B_TRUE;
24401 
24402 			/*
24403 			 * Save the original ire; we will need to restore it
24404 			 * for the tailing frags.
24405 			 */
24406 			save_ire = ire;
24407 			IRE_REFHOLD(save_ire);
24408 		}
24409 		/*
24410 		 * Emission loop for this fragment, similar
24411 		 * to what is done for the first fragment.
24412 		 */
24413 		do {
24414 			if (multirt_send) {
24415 				/*
24416 				 * We are in a multiple send case, need to get
24417 				 * the next ire and make a copy of the packet.
24418 				 */
24419 				ASSERT(irb != NULL);
24420 				IRB_REFHOLD(irb);
24421 				for (ire1 = ire->ire_next;
24422 				    ire1 != NULL;
24423 				    ire1 = ire1->ire_next) {
24424 					if (!(ire1->ire_flags & RTF_MULTIRT))
24425 						continue;
24426 					if (ire1->ire_addr != ire->ire_addr)
24427 						continue;
24428 					if (ire1->ire_marks &
24429 					    (IRE_MARK_CONDEMNED|
24430 					    IRE_MARK_HIDDEN)) {
24431 						continue;
24432 					}
24433 					/*
24434 					 * Ensure we do not exceed the MTU
24435 					 * of the next route.
24436 					 */
24437 					if (ire1->ire_max_frag < max_frag) {
24438 						ip_multirt_bad_mtu(ire1,
24439 						    max_frag);
24440 						continue;
24441 					}
24442 
24443 					/* Got one. */
24444 					IRE_REFHOLD(ire1);
24445 					break;
24446 				}
24447 				IRB_REFRELE(irb);
24448 
24449 				if (ire1 != NULL) {
24450 					next_mp = copyb(mp);
24451 					if ((next_mp == NULL) ||
24452 					    ((mp->b_cont != NULL) &&
24453 					    ((next_mp->b_cont =
24454 					    dupmsg(mp->b_cont)) == NULL))) {
24455 						freemsg(next_mp);
24456 						next_mp = NULL;
24457 						ire_refrele(ire1);
24458 						ire1 = NULL;
24459 					}
24460 				}
24461 
24462 				/* Last multiroute ire; don't loop anymore. */
24463 				if (ire1 == NULL) {
24464 					multirt_send = B_FALSE;
24465 				}
24466 			}
24467 
24468 			/* Update transmit header */
24469 			ll_hdr_len = 0;
24470 			LOCK_IRE_FP_MP(ire);
24471 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24472 			if (ll_hdr_mp != NULL) {
24473 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24474 				ll_hdr_len = MBLKL(ll_hdr_mp);
24475 			} else {
24476 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24477 			}
24478 
24479 			if (!ll_hdr_mp) {
24480 				xmit_mp = mp;
24481 
24482 			/*
24483 			 * We have link-layer header that can fit in
24484 			 * our mblk.
24485 			 */
24486 			} else if (mp->b_datap->db_ref == 1 &&
24487 			    ll_hdr_len != 0 &&
24488 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24489 				/* M_DATA fastpath */
24490 				mp->b_rptr -= ll_hdr_len;
24491 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24492 				    ll_hdr_len);
24493 				xmit_mp = mp;
24494 
24495 			/*
24496 			 * Case of res_mp OR the fastpath mp can't fit
24497 			 * in the mblk
24498 			 */
24499 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24500 				xmit_mp->b_cont = mp;
24501 				if (DB_CRED(mp) != NULL)
24502 					mblk_setcred(xmit_mp, DB_CRED(mp));
24503 				/* Get priority marking, if any. */
24504 				if (DB_TYPE(xmit_mp) == M_DATA)
24505 					xmit_mp->b_band = mp->b_band;
24506 
24507 			/* Corner case if copyb failed */
24508 			} else {
24509 				/*
24510 				 * Exit both the replication and
24511 				 * fragmentation loops.
24512 				 */
24513 				UNLOCK_IRE_FP_MP(ire);
24514 				goto drop_pkt;
24515 			}
24516 			UNLOCK_IRE_FP_MP(ire);
24517 
24518 			mp1 = mp;
24519 			out_ill = (ill_t *)q->q_ptr;
24520 
24521 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24522 
24523 			DTRACE_PROBE4(ip4__physical__out__start,
24524 			    ill_t *, NULL, ill_t *, out_ill,
24525 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24526 
24527 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24528 			    ipst->ips_ipv4firewall_physical_out,
24529 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24530 
24531 			DTRACE_PROBE1(ip4__physical__out__end,
24532 			    mblk_t *, xmit_mp);
24533 
24534 			if (mp != mp1 && hdr_mp == mp1)
24535 				hdr_mp = mp;
24536 			if (mp != mp1 && mp_orig == mp1)
24537 				mp_orig = mp;
24538 
24539 			if (xmit_mp != NULL) {
24540 				putnext(q, xmit_mp);
24541 
24542 				BUMP_MIB(out_ill->ill_ip_mib,
24543 				    ipIfStatsHCOutTransmits);
24544 				UPDATE_MIB(out_ill->ill_ip_mib,
24545 				    ipIfStatsHCOutOctets, ip_len);
24546 
24547 				if (pkt_type != OB_PKT) {
24548 					/*
24549 					 * Update the packet count of trailing
24550 					 * RTF_MULTIRT ires.
24551 					 */
24552 					UPDATE_OB_PKT_COUNT(ire);
24553 				}
24554 			}
24555 
24556 			/* All done if we just consumed the hdr_mp. */
24557 			if (mp == hdr_mp) {
24558 				last_frag = B_TRUE;
24559 				BUMP_MIB(out_ill->ill_ip_mib,
24560 				    ipIfStatsOutFragOKs);
24561 			}
24562 
24563 			if (multirt_send) {
24564 				/*
24565 				 * We are in a multiple send case; look for
24566 				 * the next ire and re-enter the loop.
24567 				 */
24568 				ASSERT(ire1);
24569 				ASSERT(next_mp);
24570 				/* REFRELE the current ire before looping */
24571 				ire_refrele(ire);
24572 				ire = ire1;
24573 				ire1 = NULL;
24574 				q = ire->ire_stq;
24575 				mp = next_mp;
24576 				next_mp = NULL;
24577 			}
24578 		} while (multirt_send);
24579 		/*
24580 		 * Restore the original ire; we need it for the
24581 		 * trailing frags
24582 		 */
24583 		if (save_ire != NULL) {
24584 			ASSERT(ire1 == NULL);
24585 			/* REFRELE the last iterated ire */
24586 			ire_refrele(ire);
24587 			/* save_ire has been REFHOLDed */
24588 			ire = save_ire;
24589 			q = ire->ire_stq;
24590 			save_ire = NULL;
24591 		}
24592 
24593 		if (last_frag) {
24594 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24595 			    "ip_wput_frag_end:(%S)",
24596 			    "consumed hdr_mp");
24597 
24598 			if (first_ire != NULL)
24599 				ire_refrele(first_ire);
24600 			return;
24601 		}
24602 		/* Otherwise, advance and loop. */
24603 		offset += len;
24604 	}
24605 
24606 drop_pkt:
24607 	/* Clean up following allocation failure. */
24608 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24609 	freemsg(mp);
24610 	if (mp != hdr_mp)
24611 		freeb(hdr_mp);
24612 	if (mp != mp_orig)
24613 		freemsg(mp_orig);
24614 
24615 	if (save_ire != NULL)
24616 		IRE_REFRELE(save_ire);
24617 	if (first_ire != NULL)
24618 		ire_refrele(first_ire);
24619 
24620 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24621 	    "ip_wput_frag_end:(%S)",
24622 	    "end--alloc failure");
24623 }
24624 
24625 /*
24626  * Copy the header plus those options which have the copy bit set
24627  */
24628 static mblk_t *
24629 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24630 {
24631 	mblk_t	*mp;
24632 	uchar_t	*up;
24633 
24634 	/*
24635 	 * Quick check if we need to look for options without the copy bit
24636 	 * set
24637 	 */
24638 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24639 	if (!mp)
24640 		return (mp);
24641 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24642 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24643 		bcopy(rptr, mp->b_rptr, hdr_len);
24644 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24645 		return (mp);
24646 	}
24647 	up  = mp->b_rptr;
24648 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24649 	up += IP_SIMPLE_HDR_LENGTH;
24650 	rptr += IP_SIMPLE_HDR_LENGTH;
24651 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24652 	while (hdr_len > 0) {
24653 		uint32_t optval;
24654 		uint32_t optlen;
24655 
24656 		optval = *rptr;
24657 		if (optval == IPOPT_EOL)
24658 			break;
24659 		if (optval == IPOPT_NOP)
24660 			optlen = 1;
24661 		else
24662 			optlen = rptr[1];
24663 		if (optval & IPOPT_COPY) {
24664 			bcopy(rptr, up, optlen);
24665 			up += optlen;
24666 		}
24667 		rptr += optlen;
24668 		hdr_len -= optlen;
24669 	}
24670 	/*
24671 	 * Make sure that we drop an even number of words by filling
24672 	 * with EOL to the next word boundary.
24673 	 */
24674 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24675 	    hdr_len & 0x3; hdr_len++)
24676 		*up++ = IPOPT_EOL;
24677 	mp->b_wptr = up;
24678 	/* Update header length */
24679 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24680 	return (mp);
24681 }
24682 
24683 /*
24684  * Delivery to local recipients including fanout to multiple recipients.
24685  * Does not do checksumming of UDP/TCP.
24686  * Note: q should be the read side queue for either the ill or conn.
24687  * Note: rq should be the read side q for the lower (ill) stream.
24688  * We don't send packets to IPPF processing, thus the last argument
24689  * to all the fanout calls are B_FALSE.
24690  */
24691 void
24692 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24693     int fanout_flags, zoneid_t zoneid)
24694 {
24695 	uint32_t	protocol;
24696 	mblk_t		*first_mp;
24697 	boolean_t	mctl_present;
24698 	int		ire_type;
24699 #define	rptr	((uchar_t *)ipha)
24700 	ip_stack_t	*ipst = ill->ill_ipst;
24701 
24702 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24703 	    "ip_wput_local_start: q %p", q);
24704 
24705 	if (ire != NULL) {
24706 		ire_type = ire->ire_type;
24707 	} else {
24708 		/*
24709 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24710 		 * packet is not multicast, we can't tell the ire type.
24711 		 */
24712 		ASSERT(CLASSD(ipha->ipha_dst));
24713 		ire_type = IRE_BROADCAST;
24714 	}
24715 
24716 	first_mp = mp;
24717 	if (first_mp->b_datap->db_type == M_CTL) {
24718 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24719 		if (!io->ipsec_out_secure) {
24720 			/*
24721 			 * This ipsec_out_t was allocated in ip_wput
24722 			 * for multicast packets to store the ill_index.
24723 			 * As this is being delivered locally, we don't
24724 			 * need this anymore.
24725 			 */
24726 			mp = first_mp->b_cont;
24727 			freeb(first_mp);
24728 			first_mp = mp;
24729 			mctl_present = B_FALSE;
24730 		} else {
24731 			/*
24732 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24733 			 * security properties for the looped-back packet.
24734 			 */
24735 			mctl_present = B_TRUE;
24736 			mp = first_mp->b_cont;
24737 			ASSERT(mp != NULL);
24738 			ipsec_out_to_in(first_mp);
24739 		}
24740 	} else {
24741 		mctl_present = B_FALSE;
24742 	}
24743 
24744 	DTRACE_PROBE4(ip4__loopback__in__start,
24745 	    ill_t *, ill, ill_t *, NULL,
24746 	    ipha_t *, ipha, mblk_t *, first_mp);
24747 
24748 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24749 	    ipst->ips_ipv4firewall_loopback_in,
24750 	    ill, NULL, ipha, first_mp, mp, ipst);
24751 
24752 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24753 
24754 	if (first_mp == NULL)
24755 		return;
24756 
24757 	ipst->ips_loopback_packets++;
24758 
24759 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24760 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24761 	if (!IS_SIMPLE_IPH(ipha)) {
24762 		ip_wput_local_options(ipha, ipst);
24763 	}
24764 
24765 	protocol = ipha->ipha_protocol;
24766 	switch (protocol) {
24767 	case IPPROTO_ICMP: {
24768 		ire_t		*ire_zone;
24769 		ilm_t		*ilm;
24770 		mblk_t		*mp1;
24771 		zoneid_t	last_zoneid;
24772 
24773 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24774 			ASSERT(ire_type == IRE_BROADCAST);
24775 			/*
24776 			 * In the multicast case, applications may have joined
24777 			 * the group from different zones, so we need to deliver
24778 			 * the packet to each of them. Loop through the
24779 			 * multicast memberships structures (ilm) on the receive
24780 			 * ill and send a copy of the packet up each matching
24781 			 * one. However, we don't do this for multicasts sent on
24782 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24783 			 * they must stay in the sender's zone.
24784 			 *
24785 			 * ilm_add_v6() ensures that ilms in the same zone are
24786 			 * contiguous in the ill_ilm list. We use this property
24787 			 * to avoid sending duplicates needed when two
24788 			 * applications in the same zone join the same group on
24789 			 * different logical interfaces: we ignore the ilm if
24790 			 * it's zoneid is the same as the last matching one.
24791 			 * In addition, the sending of the packet for
24792 			 * ire_zoneid is delayed until all of the other ilms
24793 			 * have been exhausted.
24794 			 */
24795 			last_zoneid = -1;
24796 			ILM_WALKER_HOLD(ill);
24797 			for (ilm = ill->ill_ilm; ilm != NULL;
24798 			    ilm = ilm->ilm_next) {
24799 				if ((ilm->ilm_flags & ILM_DELETED) ||
24800 				    ipha->ipha_dst != ilm->ilm_addr ||
24801 				    ilm->ilm_zoneid == last_zoneid ||
24802 				    ilm->ilm_zoneid == zoneid ||
24803 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24804 					continue;
24805 				mp1 = ip_copymsg(first_mp);
24806 				if (mp1 == NULL)
24807 					continue;
24808 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24809 				    mctl_present, B_FALSE, ill,
24810 				    ilm->ilm_zoneid);
24811 				last_zoneid = ilm->ilm_zoneid;
24812 			}
24813 			ILM_WALKER_RELE(ill);
24814 			/*
24815 			 * Loopback case: the sending endpoint has
24816 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24817 			 * dispatch the multicast packet to the sending zone.
24818 			 */
24819 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24820 				freemsg(first_mp);
24821 				return;
24822 			}
24823 		} else if (ire_type == IRE_BROADCAST) {
24824 			/*
24825 			 * In the broadcast case, there may be many zones
24826 			 * which need a copy of the packet delivered to them.
24827 			 * There is one IRE_BROADCAST per broadcast address
24828 			 * and per zone; we walk those using a helper function.
24829 			 * In addition, the sending of the packet for zoneid is
24830 			 * delayed until all of the other ires have been
24831 			 * processed.
24832 			 */
24833 			IRB_REFHOLD(ire->ire_bucket);
24834 			ire_zone = NULL;
24835 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24836 			    ire)) != NULL) {
24837 				mp1 = ip_copymsg(first_mp);
24838 				if (mp1 == NULL)
24839 					continue;
24840 
24841 				UPDATE_IB_PKT_COUNT(ire_zone);
24842 				ire_zone->ire_last_used_time = lbolt;
24843 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24844 				    mctl_present, B_FALSE, ill,
24845 				    ire_zone->ire_zoneid);
24846 			}
24847 			IRB_REFRELE(ire->ire_bucket);
24848 		}
24849 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24850 		    0, mctl_present, B_FALSE, ill, zoneid);
24851 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24852 		    "ip_wput_local_end: q %p (%S)",
24853 		    q, "icmp");
24854 		return;
24855 	}
24856 	case IPPROTO_IGMP:
24857 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24858 			/* Bad packet - discarded by igmp_input */
24859 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24860 			    "ip_wput_local_end: q %p (%S)",
24861 			    q, "igmp_input--bad packet");
24862 			if (mctl_present)
24863 				freeb(first_mp);
24864 			return;
24865 		}
24866 		/*
24867 		 * igmp_input() may have returned the pulled up message.
24868 		 * So first_mp and ipha need to be reinitialized.
24869 		 */
24870 		ipha = (ipha_t *)mp->b_rptr;
24871 		if (mctl_present)
24872 			first_mp->b_cont = mp;
24873 		else
24874 			first_mp = mp;
24875 		/* deliver to local raw users */
24876 		break;
24877 	case IPPROTO_ENCAP:
24878 		/*
24879 		 * This case is covered by either ip_fanout_proto, or by
24880 		 * the above security processing for self-tunneled packets.
24881 		 */
24882 		break;
24883 	case IPPROTO_UDP: {
24884 		uint16_t	*up;
24885 		uint32_t	ports;
24886 
24887 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24888 		    UDP_PORTS_OFFSET);
24889 		/* Force a 'valid' checksum. */
24890 		up[3] = 0;
24891 
24892 		ports = *(uint32_t *)up;
24893 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24894 		    (ire_type == IRE_BROADCAST),
24895 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24896 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
24897 		    ill, zoneid);
24898 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24899 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24900 		return;
24901 	}
24902 	case IPPROTO_TCP: {
24903 
24904 		/*
24905 		 * For TCP, discard broadcast packets.
24906 		 */
24907 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24908 			freemsg(first_mp);
24909 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
24910 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24911 			return;
24912 		}
24913 
24914 		if (mp->b_datap->db_type == M_DATA) {
24915 			/*
24916 			 * M_DATA mblk, so init mblk (chain) for no struio().
24917 			 */
24918 			mblk_t	*mp1 = mp;
24919 
24920 			do {
24921 				mp1->b_datap->db_struioflag = 0;
24922 			} while ((mp1 = mp1->b_cont) != NULL);
24923 		}
24924 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24925 		    <= mp->b_wptr);
24926 		ip_fanout_tcp(q, first_mp, ill, ipha,
24927 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24928 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
24929 		    mctl_present, B_FALSE, zoneid);
24930 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24931 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24932 		return;
24933 	}
24934 	case IPPROTO_SCTP:
24935 	{
24936 		uint32_t	ports;
24937 
24938 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24939 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24940 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24941 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
24942 		return;
24943 	}
24944 
24945 	default:
24946 		break;
24947 	}
24948 	/*
24949 	 * Find a client for some other protocol.  We give
24950 	 * copies to multiple clients, if more than one is
24951 	 * bound.
24952 	 */
24953 	ip_fanout_proto(q, first_mp, ill, ipha,
24954 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24955 	    mctl_present, B_FALSE, ill, zoneid);
24956 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24957 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24958 #undef	rptr
24959 }
24960 
24961 /*
24962  * Update any source route, record route, or timestamp options.
24963  * Check that we are at end of strict source route.
24964  * The options have been sanity checked by ip_wput_options().
24965  */
24966 static void
24967 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
24968 {
24969 	ipoptp_t	opts;
24970 	uchar_t		*opt;
24971 	uint8_t		optval;
24972 	uint8_t		optlen;
24973 	ipaddr_t	dst;
24974 	uint32_t	ts;
24975 	ire_t		*ire;
24976 	timestruc_t	now;
24977 
24978 	ip2dbg(("ip_wput_local_options\n"));
24979 	for (optval = ipoptp_first(&opts, ipha);
24980 	    optval != IPOPT_EOL;
24981 	    optval = ipoptp_next(&opts)) {
24982 		opt = opts.ipoptp_cur;
24983 		optlen = opts.ipoptp_len;
24984 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24985 		switch (optval) {
24986 			uint32_t off;
24987 		case IPOPT_SSRR:
24988 		case IPOPT_LSRR:
24989 			off = opt[IPOPT_OFFSET];
24990 			off--;
24991 			if (optlen < IP_ADDR_LEN ||
24992 			    off > optlen - IP_ADDR_LEN) {
24993 				/* End of source route */
24994 				break;
24995 			}
24996 			/*
24997 			 * This will only happen if two consecutive entries
24998 			 * in the source route contains our address or if
24999 			 * it is a packet with a loose source route which
25000 			 * reaches us before consuming the whole source route
25001 			 */
25002 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25003 			if (optval == IPOPT_SSRR) {
25004 				return;
25005 			}
25006 			/*
25007 			 * Hack: instead of dropping the packet truncate the
25008 			 * source route to what has been used by filling the
25009 			 * rest with IPOPT_NOP.
25010 			 */
25011 			opt[IPOPT_OLEN] = (uint8_t)off;
25012 			while (off < optlen) {
25013 				opt[off++] = IPOPT_NOP;
25014 			}
25015 			break;
25016 		case IPOPT_RR:
25017 			off = opt[IPOPT_OFFSET];
25018 			off--;
25019 			if (optlen < IP_ADDR_LEN ||
25020 			    off > optlen - IP_ADDR_LEN) {
25021 				/* No more room - ignore */
25022 				ip1dbg((
25023 				    "ip_wput_forward_options: end of RR\n"));
25024 				break;
25025 			}
25026 			dst = htonl(INADDR_LOOPBACK);
25027 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25028 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25029 			break;
25030 		case IPOPT_TS:
25031 			/* Insert timestamp if there is romm */
25032 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25033 			case IPOPT_TS_TSONLY:
25034 				off = IPOPT_TS_TIMELEN;
25035 				break;
25036 			case IPOPT_TS_PRESPEC:
25037 			case IPOPT_TS_PRESPEC_RFC791:
25038 				/* Verify that the address matched */
25039 				off = opt[IPOPT_OFFSET] - 1;
25040 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25041 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25042 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25043 				    ipst);
25044 				if (ire == NULL) {
25045 					/* Not for us */
25046 					break;
25047 				}
25048 				ire_refrele(ire);
25049 				/* FALLTHRU */
25050 			case IPOPT_TS_TSANDADDR:
25051 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25052 				break;
25053 			default:
25054 				/*
25055 				 * ip_*put_options should have already
25056 				 * dropped this packet.
25057 				 */
25058 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25059 				    "unknown IT - bug in ip_wput_options?\n");
25060 				return;	/* Keep "lint" happy */
25061 			}
25062 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25063 				/* Increase overflow counter */
25064 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25065 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25066 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25067 				    (off << 4);
25068 				break;
25069 			}
25070 			off = opt[IPOPT_OFFSET] - 1;
25071 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25072 			case IPOPT_TS_PRESPEC:
25073 			case IPOPT_TS_PRESPEC_RFC791:
25074 			case IPOPT_TS_TSANDADDR:
25075 				dst = htonl(INADDR_LOOPBACK);
25076 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25077 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25078 				/* FALLTHRU */
25079 			case IPOPT_TS_TSONLY:
25080 				off = opt[IPOPT_OFFSET] - 1;
25081 				/* Compute # of milliseconds since midnight */
25082 				gethrestime(&now);
25083 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25084 				    now.tv_nsec / (NANOSEC / MILLISEC);
25085 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25086 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25087 				break;
25088 			}
25089 			break;
25090 		}
25091 	}
25092 }
25093 
25094 /*
25095  * Send out a multicast packet on interface ipif.
25096  * The sender does not have an conn.
25097  * Caller verifies that this isn't a PHYI_LOOPBACK.
25098  */
25099 void
25100 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25101 {
25102 	ipha_t	*ipha;
25103 	ire_t	*ire;
25104 	ipaddr_t	dst;
25105 	mblk_t		*first_mp;
25106 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25107 
25108 	/* igmp_sendpkt always allocates a ipsec_out_t */
25109 	ASSERT(mp->b_datap->db_type == M_CTL);
25110 	ASSERT(!ipif->ipif_isv6);
25111 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25112 
25113 	first_mp = mp;
25114 	mp = first_mp->b_cont;
25115 	ASSERT(mp->b_datap->db_type == M_DATA);
25116 	ipha = (ipha_t *)mp->b_rptr;
25117 
25118 	/*
25119 	 * Find an IRE which matches the destination and the outgoing
25120 	 * queue (i.e. the outgoing interface.)
25121 	 */
25122 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25123 		dst = ipif->ipif_pp_dst_addr;
25124 	else
25125 		dst = ipha->ipha_dst;
25126 	/*
25127 	 * The source address has already been initialized by the
25128 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25129 	 * be sufficient rather than MATCH_IRE_IPIF.
25130 	 *
25131 	 * This function is used for sending IGMP packets. We need
25132 	 * to make sure that we send the packet out of the interface
25133 	 * (ipif->ipif_ill) where we joined the group. This is to
25134 	 * prevent from switches doing IGMP snooping to send us multicast
25135 	 * packets for a given group on the interface we have joined.
25136 	 * If we can't find an ire, igmp_sendpkt has already initialized
25137 	 * ipsec_out_attach_if so that this will not be load spread in
25138 	 * ip_newroute_ipif.
25139 	 */
25140 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25141 	    MATCH_IRE_ILL, ipst);
25142 	if (!ire) {
25143 		/*
25144 		 * Mark this packet to make it be delivered to
25145 		 * ip_wput_ire after the new ire has been
25146 		 * created.
25147 		 */
25148 		mp->b_prev = NULL;
25149 		mp->b_next = NULL;
25150 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25151 		    zoneid, &zero_info);
25152 		return;
25153 	}
25154 
25155 	/*
25156 	 * Honor the RTF_SETSRC flag; this is the only case
25157 	 * where we force this addr whatever the current src addr is,
25158 	 * because this address is set by igmp_sendpkt(), and
25159 	 * cannot be specified by any user.
25160 	 */
25161 	if (ire->ire_flags & RTF_SETSRC) {
25162 		ipha->ipha_src = ire->ire_src_addr;
25163 	}
25164 
25165 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25166 }
25167 
25168 /*
25169  * NOTE : This function does not ire_refrele the ire argument passed in.
25170  *
25171  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25172  * failure. The nce_fp_mp can vanish any time in the case of
25173  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25174  * the ire_lock to access the nce_fp_mp in this case.
25175  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25176  * prepending a fastpath message IPQoS processing must precede it, we also set
25177  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25178  * (IPQoS might have set the b_band for CoS marking).
25179  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25180  * must follow it so that IPQoS can mark the dl_priority field for CoS
25181  * marking, if needed.
25182  */
25183 static mblk_t *
25184 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25185 {
25186 	uint_t	hlen;
25187 	ipha_t *ipha;
25188 	mblk_t *mp1;
25189 	boolean_t qos_done = B_FALSE;
25190 	uchar_t	*ll_hdr;
25191 	ip_stack_t	*ipst = ire->ire_ipst;
25192 
25193 #define	rptr	((uchar_t *)ipha)
25194 
25195 	ipha = (ipha_t *)mp->b_rptr;
25196 	hlen = 0;
25197 	LOCK_IRE_FP_MP(ire);
25198 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25199 		ASSERT(DB_TYPE(mp1) == M_DATA);
25200 		/* Initiate IPPF processing */
25201 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25202 			UNLOCK_IRE_FP_MP(ire);
25203 			ip_process(proc, &mp, ill_index);
25204 			if (mp == NULL)
25205 				return (NULL);
25206 
25207 			ipha = (ipha_t *)mp->b_rptr;
25208 			LOCK_IRE_FP_MP(ire);
25209 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25210 				qos_done = B_TRUE;
25211 				goto no_fp_mp;
25212 			}
25213 			ASSERT(DB_TYPE(mp1) == M_DATA);
25214 		}
25215 		hlen = MBLKL(mp1);
25216 		/*
25217 		 * Check if we have enough room to prepend fastpath
25218 		 * header
25219 		 */
25220 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25221 			ll_hdr = rptr - hlen;
25222 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25223 			/*
25224 			 * Set the b_rptr to the start of the link layer
25225 			 * header
25226 			 */
25227 			mp->b_rptr = ll_hdr;
25228 			mp1 = mp;
25229 		} else {
25230 			mp1 = copyb(mp1);
25231 			if (mp1 == NULL)
25232 				goto unlock_err;
25233 			mp1->b_band = mp->b_band;
25234 			mp1->b_cont = mp;
25235 			/*
25236 			 * certain system generated traffic may not
25237 			 * have cred/label in ip header block. This
25238 			 * is true even for a labeled system. But for
25239 			 * labeled traffic, inherit the label in the
25240 			 * new header.
25241 			 */
25242 			if (DB_CRED(mp) != NULL)
25243 				mblk_setcred(mp1, DB_CRED(mp));
25244 			/*
25245 			 * XXX disable ICK_VALID and compute checksum
25246 			 * here; can happen if nce_fp_mp changes and
25247 			 * it can't be copied now due to insufficient
25248 			 * space. (unlikely, fp mp can change, but it
25249 			 * does not increase in length)
25250 			 */
25251 		}
25252 		UNLOCK_IRE_FP_MP(ire);
25253 	} else {
25254 no_fp_mp:
25255 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25256 		if (mp1 == NULL) {
25257 unlock_err:
25258 			UNLOCK_IRE_FP_MP(ire);
25259 			freemsg(mp);
25260 			return (NULL);
25261 		}
25262 		UNLOCK_IRE_FP_MP(ire);
25263 		mp1->b_cont = mp;
25264 		/*
25265 		 * certain system generated traffic may not
25266 		 * have cred/label in ip header block. This
25267 		 * is true even for a labeled system. But for
25268 		 * labeled traffic, inherit the label in the
25269 		 * new header.
25270 		 */
25271 		if (DB_CRED(mp) != NULL)
25272 			mblk_setcred(mp1, DB_CRED(mp));
25273 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25274 			ip_process(proc, &mp1, ill_index);
25275 			if (mp1 == NULL)
25276 				return (NULL);
25277 		}
25278 	}
25279 	return (mp1);
25280 #undef rptr
25281 }
25282 
25283 /*
25284  * Finish the outbound IPsec processing for an IPv6 packet. This function
25285  * is called from ipsec_out_process() if the IPsec packet was processed
25286  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25287  * asynchronously.
25288  */
25289 void
25290 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25291     ire_t *ire_arg)
25292 {
25293 	in6_addr_t *v6dstp;
25294 	ire_t *ire;
25295 	mblk_t *mp;
25296 	ip6_t *ip6h1;
25297 	uint_t	ill_index;
25298 	ipsec_out_t *io;
25299 	boolean_t attach_if, hwaccel;
25300 	uint32_t flags = IP6_NO_IPPOLICY;
25301 	int match_flags;
25302 	zoneid_t zoneid;
25303 	boolean_t ill_need_rele = B_FALSE;
25304 	boolean_t ire_need_rele = B_FALSE;
25305 	ip_stack_t	*ipst;
25306 
25307 	mp = ipsec_mp->b_cont;
25308 	ip6h1 = (ip6_t *)mp->b_rptr;
25309 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25310 	ASSERT(io->ipsec_out_ns != NULL);
25311 	ipst = io->ipsec_out_ns->netstack_ip;
25312 	ill_index = io->ipsec_out_ill_index;
25313 	if (io->ipsec_out_reachable) {
25314 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25315 	}
25316 	attach_if = io->ipsec_out_attach_if;
25317 	hwaccel = io->ipsec_out_accelerated;
25318 	zoneid = io->ipsec_out_zoneid;
25319 	ASSERT(zoneid != ALL_ZONES);
25320 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25321 	/* Multicast addresses should have non-zero ill_index. */
25322 	v6dstp = &ip6h->ip6_dst;
25323 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25324 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25325 	ASSERT(!attach_if || ill_index != 0);
25326 	if (ill_index != 0) {
25327 		if (ill == NULL) {
25328 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25329 			    B_TRUE, ipst);
25330 
25331 			/* Failure case frees things for us. */
25332 			if (ill == NULL)
25333 				return;
25334 
25335 			ill_need_rele = B_TRUE;
25336 		}
25337 		/*
25338 		 * If this packet needs to go out on a particular interface
25339 		 * honor it.
25340 		 */
25341 		if (attach_if) {
25342 			match_flags = MATCH_IRE_ILL;
25343 
25344 			/*
25345 			 * Check if we need an ire that will not be
25346 			 * looked up by anybody else i.e. HIDDEN.
25347 			 */
25348 			if (ill_is_probeonly(ill)) {
25349 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25350 			}
25351 		}
25352 	}
25353 	ASSERT(mp != NULL);
25354 
25355 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25356 		boolean_t unspec_src;
25357 		ipif_t	*ipif;
25358 
25359 		/*
25360 		 * Use the ill_index to get the right ill.
25361 		 */
25362 		unspec_src = io->ipsec_out_unspec_src;
25363 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25364 		if (ipif == NULL) {
25365 			if (ill_need_rele)
25366 				ill_refrele(ill);
25367 			freemsg(ipsec_mp);
25368 			return;
25369 		}
25370 
25371 		if (ire_arg != NULL) {
25372 			ire = ire_arg;
25373 		} else {
25374 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25375 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25376 			ire_need_rele = B_TRUE;
25377 		}
25378 		if (ire != NULL) {
25379 			ipif_refrele(ipif);
25380 			/*
25381 			 * XXX Do the multicast forwarding now, as the IPSEC
25382 			 * processing has been done.
25383 			 */
25384 			goto send;
25385 		}
25386 
25387 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25388 		mp->b_prev = NULL;
25389 		mp->b_next = NULL;
25390 
25391 		/*
25392 		 * If the IPsec packet was processed asynchronously,
25393 		 * drop it now.
25394 		 */
25395 		if (q == NULL) {
25396 			if (ill_need_rele)
25397 				ill_refrele(ill);
25398 			freemsg(ipsec_mp);
25399 			return;
25400 		}
25401 
25402 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25403 		    unspec_src, zoneid);
25404 		ipif_refrele(ipif);
25405 	} else {
25406 		if (attach_if) {
25407 			ipif_t	*ipif;
25408 
25409 			ipif = ipif_get_next_ipif(NULL, ill);
25410 			if (ipif == NULL) {
25411 				if (ill_need_rele)
25412 					ill_refrele(ill);
25413 				freemsg(ipsec_mp);
25414 				return;
25415 			}
25416 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25417 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25418 			ire_need_rele = B_TRUE;
25419 			ipif_refrele(ipif);
25420 		} else {
25421 			if (ire_arg != NULL) {
25422 				ire = ire_arg;
25423 			} else {
25424 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25425 				    ipst);
25426 				ire_need_rele = B_TRUE;
25427 			}
25428 		}
25429 		if (ire != NULL)
25430 			goto send;
25431 		/*
25432 		 * ire disappeared underneath.
25433 		 *
25434 		 * What we need to do here is the ip_newroute
25435 		 * logic to get the ire without doing the IPSEC
25436 		 * processing. Follow the same old path. But this
25437 		 * time, ip_wput or ire_add_then_send will call us
25438 		 * directly as all the IPSEC operations are done.
25439 		 */
25440 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25441 		mp->b_prev = NULL;
25442 		mp->b_next = NULL;
25443 
25444 		/*
25445 		 * If the IPsec packet was processed asynchronously,
25446 		 * drop it now.
25447 		 */
25448 		if (q == NULL) {
25449 			if (ill_need_rele)
25450 				ill_refrele(ill);
25451 			freemsg(ipsec_mp);
25452 			return;
25453 		}
25454 
25455 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25456 		    zoneid, ipst);
25457 	}
25458 	if (ill != NULL && ill_need_rele)
25459 		ill_refrele(ill);
25460 	return;
25461 send:
25462 	if (ill != NULL && ill_need_rele)
25463 		ill_refrele(ill);
25464 
25465 	/* Local delivery */
25466 	if (ire->ire_stq == NULL) {
25467 		ill_t	*out_ill;
25468 		ASSERT(q != NULL);
25469 
25470 		/* PFHooks: LOOPBACK_OUT */
25471 		out_ill = ire->ire_ipif->ipif_ill;
25472 
25473 		DTRACE_PROBE4(ip6__loopback__out__start,
25474 		    ill_t *, NULL, ill_t *, out_ill,
25475 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25476 
25477 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25478 		    ipst->ips_ipv6firewall_loopback_out,
25479 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25480 
25481 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25482 
25483 		if (ipsec_mp != NULL)
25484 			ip_wput_local_v6(RD(q), out_ill,
25485 			    ip6h, ipsec_mp, ire, 0);
25486 		if (ire_need_rele)
25487 			ire_refrele(ire);
25488 		return;
25489 	}
25490 	/*
25491 	 * Everything is done. Send it out on the wire.
25492 	 * We force the insertion of a fragment header using the
25493 	 * IPH_FRAG_HDR flag in two cases:
25494 	 * - after reception of an ICMPv6 "packet too big" message
25495 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25496 	 * - for multirouted IPv6 packets, so that the receiver can
25497 	 *   discard duplicates according to their fragment identifier
25498 	 */
25499 	/* XXX fix flow control problems. */
25500 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25501 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25502 		if (hwaccel) {
25503 			/*
25504 			 * hardware acceleration does not handle these
25505 			 * "slow path" cases.
25506 			 */
25507 			/* IPsec KSTATS: should bump bean counter here. */
25508 			if (ire_need_rele)
25509 				ire_refrele(ire);
25510 			freemsg(ipsec_mp);
25511 			return;
25512 		}
25513 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25514 		    (mp->b_cont ? msgdsize(mp) :
25515 		    mp->b_wptr - (uchar_t *)ip6h)) {
25516 			/* IPsec KSTATS: should bump bean counter here. */
25517 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25518 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25519 			    msgdsize(mp)));
25520 			if (ire_need_rele)
25521 				ire_refrele(ire);
25522 			freemsg(ipsec_mp);
25523 			return;
25524 		}
25525 		ASSERT(mp->b_prev == NULL);
25526 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25527 		    ntohs(ip6h->ip6_plen) +
25528 		    IPV6_HDR_LEN, ire->ire_max_frag));
25529 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25530 		    ire->ire_max_frag);
25531 	} else {
25532 		UPDATE_OB_PKT_COUNT(ire);
25533 		ire->ire_last_used_time = lbolt;
25534 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25535 	}
25536 	if (ire_need_rele)
25537 		ire_refrele(ire);
25538 	freeb(ipsec_mp);
25539 }
25540 
25541 void
25542 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25543 {
25544 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25545 	da_ipsec_t *hada;	/* data attributes */
25546 	ill_t *ill = (ill_t *)q->q_ptr;
25547 
25548 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25549 
25550 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25551 		/* IPsec KSTATS: Bump lose counter here! */
25552 		freemsg(mp);
25553 		return;
25554 	}
25555 
25556 	/*
25557 	 * It's an IPsec packet that must be
25558 	 * accelerated by the Provider, and the
25559 	 * outbound ill is IPsec acceleration capable.
25560 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25561 	 * to the ill.
25562 	 * IPsec KSTATS: should bump packet counter here.
25563 	 */
25564 
25565 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25566 	if (hada_mp == NULL) {
25567 		/* IPsec KSTATS: should bump packet counter here. */
25568 		freemsg(mp);
25569 		return;
25570 	}
25571 
25572 	hada_mp->b_datap->db_type = M_CTL;
25573 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25574 	hada_mp->b_cont = mp;
25575 
25576 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25577 	bzero(hada, sizeof (da_ipsec_t));
25578 	hada->da_type = IPHADA_M_CTL;
25579 
25580 	putnext(q, hada_mp);
25581 }
25582 
25583 /*
25584  * Finish the outbound IPsec processing. This function is called from
25585  * ipsec_out_process() if the IPsec packet was processed
25586  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25587  * asynchronously.
25588  */
25589 void
25590 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25591     ire_t *ire_arg)
25592 {
25593 	uint32_t v_hlen_tos_len;
25594 	ipaddr_t	dst;
25595 	ipif_t	*ipif = NULL;
25596 	ire_t *ire;
25597 	ire_t *ire1 = NULL;
25598 	mblk_t *next_mp = NULL;
25599 	uint32_t max_frag;
25600 	boolean_t multirt_send = B_FALSE;
25601 	mblk_t *mp;
25602 	mblk_t *mp1;
25603 	ipha_t *ipha1;
25604 	uint_t	ill_index;
25605 	ipsec_out_t *io;
25606 	boolean_t attach_if;
25607 	int match_flags, offset;
25608 	irb_t *irb = NULL;
25609 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25610 	zoneid_t zoneid;
25611 	uint32_t cksum;
25612 	uint16_t *up;
25613 	ipxmit_state_t	pktxmit_state;
25614 	ip_stack_t	*ipst;
25615 
25616 #ifdef	_BIG_ENDIAN
25617 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25618 #else
25619 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25620 #endif
25621 
25622 	mp = ipsec_mp->b_cont;
25623 	ipha1 = (ipha_t *)mp->b_rptr;
25624 	ASSERT(mp != NULL);
25625 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25626 	dst = ipha->ipha_dst;
25627 
25628 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25629 	ill_index = io->ipsec_out_ill_index;
25630 	attach_if = io->ipsec_out_attach_if;
25631 	zoneid = io->ipsec_out_zoneid;
25632 	ASSERT(zoneid != ALL_ZONES);
25633 	ipst = io->ipsec_out_ns->netstack_ip;
25634 	ASSERT(io->ipsec_out_ns != NULL);
25635 
25636 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25637 	if (ill_index != 0) {
25638 		if (ill == NULL) {
25639 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25640 			    ill_index, B_FALSE, ipst);
25641 
25642 			/* Failure case frees things for us. */
25643 			if (ill == NULL)
25644 				return;
25645 
25646 			ill_need_rele = B_TRUE;
25647 		}
25648 		/*
25649 		 * If this packet needs to go out on a particular interface
25650 		 * honor it.
25651 		 */
25652 		if (attach_if) {
25653 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25654 
25655 			/*
25656 			 * Check if we need an ire that will not be
25657 			 * looked up by anybody else i.e. HIDDEN.
25658 			 */
25659 			if (ill_is_probeonly(ill)) {
25660 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25661 			}
25662 		}
25663 	}
25664 
25665 	if (CLASSD(dst)) {
25666 		boolean_t conn_dontroute;
25667 		/*
25668 		 * Use the ill_index to get the right ipif.
25669 		 */
25670 		conn_dontroute = io->ipsec_out_dontroute;
25671 		if (ill_index == 0)
25672 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25673 		else
25674 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25675 		if (ipif == NULL) {
25676 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25677 			    " multicast\n"));
25678 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25679 			freemsg(ipsec_mp);
25680 			goto done;
25681 		}
25682 		/*
25683 		 * ipha_src has already been intialized with the
25684 		 * value of the ipif in ip_wput. All we need now is
25685 		 * an ire to send this downstream.
25686 		 */
25687 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25688 		    MBLK_GETLABEL(mp), match_flags, ipst);
25689 		if (ire != NULL) {
25690 			ill_t *ill1;
25691 			/*
25692 			 * Do the multicast forwarding now, as the IPSEC
25693 			 * processing has been done.
25694 			 */
25695 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25696 			    (ill1 = ire_to_ill(ire))) {
25697 				if (ip_mforward(ill1, ipha, mp)) {
25698 					freemsg(ipsec_mp);
25699 					ip1dbg(("ip_wput_ipsec_out: mforward "
25700 					    "failed\n"));
25701 					ire_refrele(ire);
25702 					goto done;
25703 				}
25704 			}
25705 			goto send;
25706 		}
25707 
25708 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25709 		mp->b_prev = NULL;
25710 		mp->b_next = NULL;
25711 
25712 		/*
25713 		 * If the IPsec packet was processed asynchronously,
25714 		 * drop it now.
25715 		 */
25716 		if (q == NULL) {
25717 			freemsg(ipsec_mp);
25718 			goto done;
25719 		}
25720 
25721 		/*
25722 		 * We may be using a wrong ipif to create the ire.
25723 		 * But it is okay as the source address is assigned
25724 		 * for the packet already. Next outbound packet would
25725 		 * create the IRE with the right IPIF in ip_wput.
25726 		 *
25727 		 * Also handle RTF_MULTIRT routes.
25728 		 */
25729 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25730 		    zoneid, &zero_info);
25731 	} else {
25732 		if (attach_if) {
25733 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25734 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25735 		} else {
25736 			if (ire_arg != NULL) {
25737 				ire = ire_arg;
25738 				ire_need_rele = B_FALSE;
25739 			} else {
25740 				ire = ire_cache_lookup(dst, zoneid,
25741 				    MBLK_GETLABEL(mp), ipst);
25742 			}
25743 		}
25744 		if (ire != NULL) {
25745 			goto send;
25746 		}
25747 
25748 		/*
25749 		 * ire disappeared underneath.
25750 		 *
25751 		 * What we need to do here is the ip_newroute
25752 		 * logic to get the ire without doing the IPSEC
25753 		 * processing. Follow the same old path. But this
25754 		 * time, ip_wput or ire_add_then_put will call us
25755 		 * directly as all the IPSEC operations are done.
25756 		 */
25757 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25758 		mp->b_prev = NULL;
25759 		mp->b_next = NULL;
25760 
25761 		/*
25762 		 * If the IPsec packet was processed asynchronously,
25763 		 * drop it now.
25764 		 */
25765 		if (q == NULL) {
25766 			freemsg(ipsec_mp);
25767 			goto done;
25768 		}
25769 
25770 		/*
25771 		 * Since we're going through ip_newroute() again, we
25772 		 * need to make sure we don't:
25773 		 *
25774 		 *	1.) Trigger the ASSERT() with the ipha_ident
25775 		 *	    overloading.
25776 		 *	2.) Redo transport-layer checksumming, since we've
25777 		 *	    already done all that to get this far.
25778 		 *
25779 		 * The easiest way not do either of the above is to set
25780 		 * the ipha_ident field to IP_HDR_INCLUDED.
25781 		 */
25782 		ipha->ipha_ident = IP_HDR_INCLUDED;
25783 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25784 		    zoneid, ipst);
25785 	}
25786 	goto done;
25787 send:
25788 	if (ipha->ipha_protocol == IPPROTO_UDP &&
25789 	    udp_compute_checksum(ipst->ips_netstack)) {
25790 		/*
25791 		 * ESP NAT-Traversal packet.
25792 		 *
25793 		 * Just do software checksum for now.
25794 		 */
25795 
25796 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25797 		IP_STAT(ipst, ip_out_sw_cksum);
25798 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
25799 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25800 #define	iphs	((uint16_t *)ipha)
25801 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25802 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25803 		    IP_SIMPLE_HDR_LENGTH);
25804 #undef iphs
25805 		cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum);
25806 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25807 			if (mp1->b_wptr - mp1->b_rptr >=
25808 			    offset + sizeof (uint16_t)) {
25809 				up = (uint16_t *)(mp1->b_rptr + offset);
25810 				*up = cksum;
25811 				break;	/* out of for loop */
25812 			} else {
25813 				offset -= (mp->b_wptr - mp->b_rptr);
25814 			}
25815 	} /* Otherwise, just keep the all-zero checksum. */
25816 
25817 	if (ire->ire_stq == NULL) {
25818 		ill_t	*out_ill;
25819 		/*
25820 		 * Loopbacks go through ip_wput_local except for one case.
25821 		 * We come here if we generate a icmp_frag_needed message
25822 		 * after IPSEC processing is over. When this function calls
25823 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25824 		 * icmp_frag_needed. The message generated comes back here
25825 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25826 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25827 		 * source address as it is usually set in ip_wput_ire. As
25828 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25829 		 * and we end up here. We can't enter ip_wput_ire once the
25830 		 * IPSEC processing is over and hence we need to do it here.
25831 		 */
25832 		ASSERT(q != NULL);
25833 		UPDATE_OB_PKT_COUNT(ire);
25834 		ire->ire_last_used_time = lbolt;
25835 		if (ipha->ipha_src == 0)
25836 			ipha->ipha_src = ire->ire_src_addr;
25837 
25838 		/* PFHooks: LOOPBACK_OUT */
25839 		out_ill = ire->ire_ipif->ipif_ill;
25840 
25841 		DTRACE_PROBE4(ip4__loopback__out__start,
25842 		    ill_t *, NULL, ill_t *, out_ill,
25843 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25844 
25845 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25846 		    ipst->ips_ipv4firewall_loopback_out,
25847 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
25848 
25849 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25850 
25851 		if (ipsec_mp != NULL)
25852 			ip_wput_local(RD(q), out_ill,
25853 			    ipha, ipsec_mp, ire, 0, zoneid);
25854 		if (ire_need_rele)
25855 			ire_refrele(ire);
25856 		goto done;
25857 	}
25858 
25859 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25860 		/*
25861 		 * We are through with IPSEC processing.
25862 		 * Fragment this and send it on the wire.
25863 		 */
25864 		if (io->ipsec_out_accelerated) {
25865 			/*
25866 			 * The packet has been accelerated but must
25867 			 * be fragmented. This should not happen
25868 			 * since AH and ESP must not accelerate
25869 			 * packets that need fragmentation, however
25870 			 * the configuration could have changed
25871 			 * since the AH or ESP processing.
25872 			 * Drop packet.
25873 			 * IPsec KSTATS: bump bean counter here.
25874 			 */
25875 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25876 			    "fragmented accelerated packet!\n"));
25877 			freemsg(ipsec_mp);
25878 		} else {
25879 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
25880 		}
25881 		if (ire_need_rele)
25882 			ire_refrele(ire);
25883 		goto done;
25884 	}
25885 
25886 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25887 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25888 	    (void *)ire->ire_ipif, (void *)ipif));
25889 
25890 	/*
25891 	 * Multiroute the secured packet, unless IPsec really
25892 	 * requires the packet to go out only through a particular
25893 	 * interface.
25894 	 */
25895 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25896 		ire_t *first_ire;
25897 		irb = ire->ire_bucket;
25898 		ASSERT(irb != NULL);
25899 		/*
25900 		 * This ire has been looked up as the one that
25901 		 * goes through the given ipif;
25902 		 * make sure we do not omit any other multiroute ire
25903 		 * that may be present in the bucket before this one.
25904 		 */
25905 		IRB_REFHOLD(irb);
25906 		for (first_ire = irb->irb_ire;
25907 		    first_ire != NULL;
25908 		    first_ire = first_ire->ire_next) {
25909 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25910 			    (first_ire->ire_addr == ire->ire_addr) &&
25911 			    !(first_ire->ire_marks &
25912 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
25913 				break;
25914 			}
25915 		}
25916 
25917 		if ((first_ire != NULL) && (first_ire != ire)) {
25918 			/*
25919 			 * Don't change the ire if the packet must
25920 			 * be fragmented if sent via this new one.
25921 			 */
25922 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25923 				IRE_REFHOLD(first_ire);
25924 				if (ire_need_rele)
25925 					ire_refrele(ire);
25926 				else
25927 					ire_need_rele = B_TRUE;
25928 				ire = first_ire;
25929 			}
25930 		}
25931 		IRB_REFRELE(irb);
25932 
25933 		multirt_send = B_TRUE;
25934 		max_frag = ire->ire_max_frag;
25935 	} else {
25936 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25937 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25938 			    "flag, attach_if %d\n", attach_if));
25939 		}
25940 	}
25941 
25942 	/*
25943 	 * In most cases, the emission loop below is entered only once.
25944 	 * Only in the case where the ire holds the RTF_MULTIRT
25945 	 * flag, we loop to process all RTF_MULTIRT ires in the
25946 	 * bucket, and send the packet through all crossed
25947 	 * RTF_MULTIRT routes.
25948 	 */
25949 	do {
25950 		if (multirt_send) {
25951 			/*
25952 			 * ire1 holds here the next ire to process in the
25953 			 * bucket. If multirouting is expected,
25954 			 * any non-RTF_MULTIRT ire that has the
25955 			 * right destination address is ignored.
25956 			 */
25957 			ASSERT(irb != NULL);
25958 			IRB_REFHOLD(irb);
25959 			for (ire1 = ire->ire_next;
25960 			    ire1 != NULL;
25961 			    ire1 = ire1->ire_next) {
25962 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25963 					continue;
25964 				if (ire1->ire_addr != ire->ire_addr)
25965 					continue;
25966 				if (ire1->ire_marks &
25967 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25968 					continue;
25969 				/* No loopback here */
25970 				if (ire1->ire_stq == NULL)
25971 					continue;
25972 				/*
25973 				 * Ensure we do not exceed the MTU
25974 				 * of the next route.
25975 				 */
25976 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25977 					ip_multirt_bad_mtu(ire1, max_frag);
25978 					continue;
25979 				}
25980 
25981 				IRE_REFHOLD(ire1);
25982 				break;
25983 			}
25984 			IRB_REFRELE(irb);
25985 			if (ire1 != NULL) {
25986 				/*
25987 				 * We are in a multiple send case, need to
25988 				 * make a copy of the packet.
25989 				 */
25990 				next_mp = copymsg(ipsec_mp);
25991 				if (next_mp == NULL) {
25992 					ire_refrele(ire1);
25993 					ire1 = NULL;
25994 				}
25995 			}
25996 		}
25997 		/*
25998 		 * Everything is done. Send it out on the wire
25999 		 *
26000 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26001 		 * either send it on the wire or, in the case of
26002 		 * HW acceleration, call ipsec_hw_putnext.
26003 		 */
26004 		if (ire->ire_nce &&
26005 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26006 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26007 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26008 			/*
26009 			 * If ire's link-layer is unresolved (this
26010 			 * would only happen if the incomplete ire
26011 			 * was added to cachetable via forwarding path)
26012 			 * don't bother going to ip_xmit_v4. Just drop the
26013 			 * packet.
26014 			 * There is a slight risk here, in that, if we
26015 			 * have the forwarding path create an incomplete
26016 			 * IRE, then until the IRE is completed, any
26017 			 * transmitted IPSEC packets will be dropped
26018 			 * instead of being queued waiting for resolution.
26019 			 *
26020 			 * But the likelihood of a forwarding packet and a wput
26021 			 * packet sending to the same dst at the same time
26022 			 * and there not yet be an ARP entry for it is small.
26023 			 * Furthermore, if this actually happens, it might
26024 			 * be likely that wput would generate multiple
26025 			 * packets (and forwarding would also have a train
26026 			 * of packets) for that destination. If this is
26027 			 * the case, some of them would have been dropped
26028 			 * anyway, since ARP only queues a few packets while
26029 			 * waiting for resolution
26030 			 *
26031 			 * NOTE: We should really call ip_xmit_v4,
26032 			 * and let it queue the packet and send the
26033 			 * ARP query and have ARP come back thus:
26034 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26035 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26036 			 * hw accel work. But it's too complex to get
26037 			 * the IPsec hw  acceleration approach to fit
26038 			 * well with ip_xmit_v4 doing ARP without
26039 			 * doing IPSEC simplification. For now, we just
26040 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26041 			 * that we can continue with the send on the next
26042 			 * attempt.
26043 			 *
26044 			 * XXX THis should be revisited, when
26045 			 * the IPsec/IP interaction is cleaned up
26046 			 */
26047 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26048 			    " - dropping packet\n"));
26049 			freemsg(ipsec_mp);
26050 			/*
26051 			 * Call ip_xmit_v4() to trigger ARP query
26052 			 * in case the nce_state is ND_INITIAL
26053 			 */
26054 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26055 			goto drop_pkt;
26056 		}
26057 
26058 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26059 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26060 		    mblk_t *, ipsec_mp);
26061 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26062 		    ipst->ips_ipv4firewall_physical_out,
26063 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26064 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26065 		if (ipsec_mp == NULL)
26066 			goto drop_pkt;
26067 
26068 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26069 		pktxmit_state = ip_xmit_v4(mp, ire,
26070 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26071 
26072 		if ((pktxmit_state ==  SEND_FAILED) ||
26073 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26074 
26075 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26076 drop_pkt:
26077 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26078 			    ipIfStatsOutDiscards);
26079 			if (ire_need_rele)
26080 				ire_refrele(ire);
26081 			if (ire1 != NULL) {
26082 				ire_refrele(ire1);
26083 				freemsg(next_mp);
26084 			}
26085 			goto done;
26086 		}
26087 
26088 		freeb(ipsec_mp);
26089 		if (ire_need_rele)
26090 			ire_refrele(ire);
26091 
26092 		if (ire1 != NULL) {
26093 			ire = ire1;
26094 			ire_need_rele = B_TRUE;
26095 			ASSERT(next_mp);
26096 			ipsec_mp = next_mp;
26097 			mp = ipsec_mp->b_cont;
26098 			ire1 = NULL;
26099 			next_mp = NULL;
26100 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26101 		} else {
26102 			multirt_send = B_FALSE;
26103 		}
26104 	} while (multirt_send);
26105 done:
26106 	if (ill != NULL && ill_need_rele)
26107 		ill_refrele(ill);
26108 	if (ipif != NULL)
26109 		ipif_refrele(ipif);
26110 }
26111 
26112 /*
26113  * Get the ill corresponding to the specified ire, and compare its
26114  * capabilities with the protocol and algorithms specified by the
26115  * the SA obtained from ipsec_out. If they match, annotate the
26116  * ipsec_out structure to indicate that the packet needs acceleration.
26117  *
26118  *
26119  * A packet is eligible for outbound hardware acceleration if the
26120  * following conditions are satisfied:
26121  *
26122  * 1. the packet will not be fragmented
26123  * 2. the provider supports the algorithm
26124  * 3. there is no pending control message being exchanged
26125  * 4. snoop is not attached
26126  * 5. the destination address is not a broadcast or multicast address.
26127  *
26128  * Rationale:
26129  *	- Hardware drivers do not support fragmentation with
26130  *	  the current interface.
26131  *	- snoop, multicast, and broadcast may result in exposure of
26132  *	  a cleartext datagram.
26133  * We check all five of these conditions here.
26134  *
26135  * XXX would like to nuke "ire_t *" parameter here; problem is that
26136  * IRE is only way to figure out if a v4 address is a broadcast and
26137  * thus ineligible for acceleration...
26138  */
26139 static void
26140 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26141 {
26142 	ipsec_out_t *io;
26143 	mblk_t *data_mp;
26144 	uint_t plen, overhead;
26145 	ip_stack_t	*ipst;
26146 
26147 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26148 		return;
26149 
26150 	if (ill == NULL)
26151 		return;
26152 	ipst = ill->ill_ipst;
26153 	/*
26154 	 * Destination address is a broadcast or multicast.  Punt.
26155 	 */
26156 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26157 	    IRE_LOCAL)))
26158 		return;
26159 
26160 	data_mp = ipsec_mp->b_cont;
26161 
26162 	if (ill->ill_isv6) {
26163 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26164 
26165 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26166 			return;
26167 
26168 		plen = ip6h->ip6_plen;
26169 	} else {
26170 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26171 
26172 		if (CLASSD(ipha->ipha_dst))
26173 			return;
26174 
26175 		plen = ipha->ipha_length;
26176 	}
26177 	/*
26178 	 * Is there a pending DLPI control message being exchanged
26179 	 * between IP/IPsec and the DLS Provider? If there is, it
26180 	 * could be a SADB update, and the state of the DLS Provider
26181 	 * SADB might not be in sync with the SADB maintained by
26182 	 * IPsec. To avoid dropping packets or using the wrong keying
26183 	 * material, we do not accelerate this packet.
26184 	 */
26185 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26186 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26187 		    "ill_dlpi_pending! don't accelerate packet\n"));
26188 		return;
26189 	}
26190 
26191 	/*
26192 	 * Is the Provider in promiscous mode? If it does, we don't
26193 	 * accelerate the packet since it will bounce back up to the
26194 	 * listeners in the clear.
26195 	 */
26196 	if (ill->ill_promisc_on_phys) {
26197 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26198 		    "ill in promiscous mode, don't accelerate packet\n"));
26199 		return;
26200 	}
26201 
26202 	/*
26203 	 * Will the packet require fragmentation?
26204 	 */
26205 
26206 	/*
26207 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26208 	 * as is used elsewhere.
26209 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26210 	 *	+ 2-byte trailer
26211 	 */
26212 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26213 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26214 
26215 	if ((plen + overhead) > ill->ill_max_mtu)
26216 		return;
26217 
26218 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26219 
26220 	/*
26221 	 * Can the ill accelerate this IPsec protocol and algorithm
26222 	 * specified by the SA?
26223 	 */
26224 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26225 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26226 		return;
26227 	}
26228 
26229 	/*
26230 	 * Tell AH or ESP that the outbound ill is capable of
26231 	 * accelerating this packet.
26232 	 */
26233 	io->ipsec_out_is_capab_ill = B_TRUE;
26234 }
26235 
26236 /*
26237  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26238  *
26239  * If this function returns B_TRUE, the requested SA's have been filled
26240  * into the ipsec_out_*_sa pointers.
26241  *
26242  * If the function returns B_FALSE, the packet has been "consumed", most
26243  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26244  *
26245  * The SA references created by the protocol-specific "select"
26246  * function will be released when the ipsec_mp is freed, thanks to the
26247  * ipsec_out_free destructor -- see spd.c.
26248  */
26249 static boolean_t
26250 ipsec_out_select_sa(mblk_t *ipsec_mp)
26251 {
26252 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26253 	ipsec_out_t *io;
26254 	ipsec_policy_t *pp;
26255 	ipsec_action_t *ap;
26256 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26257 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26258 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26259 
26260 	if (!io->ipsec_out_secure) {
26261 		/*
26262 		 * We came here by mistake.
26263 		 * Don't bother with ipsec processing
26264 		 * We should "discourage" this path in the future.
26265 		 */
26266 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26267 		return (B_FALSE);
26268 	}
26269 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26270 	ASSERT((io->ipsec_out_policy != NULL) ||
26271 	    (io->ipsec_out_act != NULL));
26272 
26273 	ASSERT(io->ipsec_out_failed == B_FALSE);
26274 
26275 	/*
26276 	 * IPSEC processing has started.
26277 	 */
26278 	io->ipsec_out_proc_begin = B_TRUE;
26279 	ap = io->ipsec_out_act;
26280 	if (ap == NULL) {
26281 		pp = io->ipsec_out_policy;
26282 		ASSERT(pp != NULL);
26283 		ap = pp->ipsp_act;
26284 		ASSERT(ap != NULL);
26285 	}
26286 
26287 	/*
26288 	 * We have an action.  now, let's select SA's.
26289 	 * (In the future, we can cache this in the conn_t..)
26290 	 */
26291 	if (ap->ipa_want_esp) {
26292 		if (io->ipsec_out_esp_sa == NULL) {
26293 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26294 			    IPPROTO_ESP);
26295 		}
26296 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26297 	}
26298 
26299 	if (ap->ipa_want_ah) {
26300 		if (io->ipsec_out_ah_sa == NULL) {
26301 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26302 			    IPPROTO_AH);
26303 		}
26304 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26305 		/*
26306 		 * The ESP and AH processing order needs to be preserved
26307 		 * when both protocols are required (ESP should be applied
26308 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26309 		 * when both ESP and AH are required, and an AH ACQUIRE
26310 		 * is needed.
26311 		 */
26312 		if (ap->ipa_want_esp && need_ah_acquire)
26313 			need_esp_acquire = B_TRUE;
26314 	}
26315 
26316 	/*
26317 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26318 	 * Release SAs that got referenced, but will not be used until we
26319 	 * acquire _all_ of the SAs we need.
26320 	 */
26321 	if (need_ah_acquire || need_esp_acquire) {
26322 		if (io->ipsec_out_ah_sa != NULL) {
26323 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26324 			io->ipsec_out_ah_sa = NULL;
26325 		}
26326 		if (io->ipsec_out_esp_sa != NULL) {
26327 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26328 			io->ipsec_out_esp_sa = NULL;
26329 		}
26330 
26331 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26332 		return (B_FALSE);
26333 	}
26334 
26335 	return (B_TRUE);
26336 }
26337 
26338 /*
26339  * Process an IPSEC_OUT message and see what you can
26340  * do with it.
26341  * IPQoS Notes:
26342  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26343  * IPSec.
26344  * XXX would like to nuke ire_t.
26345  * XXX ill_index better be "real"
26346  */
26347 void
26348 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26349 {
26350 	ipsec_out_t *io;
26351 	ipsec_policy_t *pp;
26352 	ipsec_action_t *ap;
26353 	ipha_t *ipha;
26354 	ip6_t *ip6h;
26355 	mblk_t *mp;
26356 	ill_t *ill;
26357 	zoneid_t zoneid;
26358 	ipsec_status_t ipsec_rc;
26359 	boolean_t ill_need_rele = B_FALSE;
26360 	ip_stack_t	*ipst;
26361 	ipsec_stack_t	*ipss;
26362 
26363 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26364 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26365 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26366 	ipst = io->ipsec_out_ns->netstack_ip;
26367 	mp = ipsec_mp->b_cont;
26368 
26369 	/*
26370 	 * Initiate IPPF processing. We do it here to account for packets
26371 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26372 	 * We can check for ipsec_out_proc_begin even for such packets, as
26373 	 * they will always be false (asserted below).
26374 	 */
26375 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26376 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26377 		    io->ipsec_out_ill_index : ill_index);
26378 		if (mp == NULL) {
26379 			ip2dbg(("ipsec_out_process: packet dropped "\
26380 			    "during IPPF processing\n"));
26381 			freeb(ipsec_mp);
26382 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26383 			return;
26384 		}
26385 	}
26386 
26387 	if (!io->ipsec_out_secure) {
26388 		/*
26389 		 * We came here by mistake.
26390 		 * Don't bother with ipsec processing
26391 		 * Should "discourage" this path in the future.
26392 		 */
26393 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26394 		goto done;
26395 	}
26396 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26397 	ASSERT((io->ipsec_out_policy != NULL) ||
26398 	    (io->ipsec_out_act != NULL));
26399 	ASSERT(io->ipsec_out_failed == B_FALSE);
26400 
26401 	ipss = ipst->ips_netstack->netstack_ipsec;
26402 	if (!ipsec_loaded(ipss)) {
26403 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26404 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26405 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26406 		} else {
26407 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26408 		}
26409 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26410 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26411 		    &ipss->ipsec_dropper);
26412 		return;
26413 	}
26414 
26415 	/*
26416 	 * IPSEC processing has started.
26417 	 */
26418 	io->ipsec_out_proc_begin = B_TRUE;
26419 	ap = io->ipsec_out_act;
26420 	if (ap == NULL) {
26421 		pp = io->ipsec_out_policy;
26422 		ASSERT(pp != NULL);
26423 		ap = pp->ipsp_act;
26424 		ASSERT(ap != NULL);
26425 	}
26426 
26427 	/*
26428 	 * Save the outbound ill index. When the packet comes back
26429 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26430 	 * before sending it the accelerated packet.
26431 	 */
26432 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26433 		int ifindex;
26434 		ill = ire_to_ill(ire);
26435 		ifindex = ill->ill_phyint->phyint_ifindex;
26436 		io->ipsec_out_capab_ill_index = ifindex;
26437 	}
26438 
26439 	/*
26440 	 * The order of processing is first insert a IP header if needed.
26441 	 * Then insert the ESP header and then the AH header.
26442 	 */
26443 	if ((io->ipsec_out_se_done == B_FALSE) &&
26444 	    (ap->ipa_want_se)) {
26445 		/*
26446 		 * First get the outer IP header before sending
26447 		 * it to ESP.
26448 		 */
26449 		ipha_t *oipha, *iipha;
26450 		mblk_t *outer_mp, *inner_mp;
26451 
26452 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26453 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26454 			    "ipsec_out_process: "
26455 			    "Self-Encapsulation failed: Out of memory\n");
26456 			freemsg(ipsec_mp);
26457 			if (ill != NULL) {
26458 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26459 			} else {
26460 				BUMP_MIB(&ipst->ips_ip_mib,
26461 				    ipIfStatsOutDiscards);
26462 			}
26463 			return;
26464 		}
26465 		inner_mp = ipsec_mp->b_cont;
26466 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26467 		oipha = (ipha_t *)outer_mp->b_rptr;
26468 		iipha = (ipha_t *)inner_mp->b_rptr;
26469 		*oipha = *iipha;
26470 		outer_mp->b_wptr += sizeof (ipha_t);
26471 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26472 		    sizeof (ipha_t));
26473 		oipha->ipha_protocol = IPPROTO_ENCAP;
26474 		oipha->ipha_version_and_hdr_length =
26475 		    IP_SIMPLE_HDR_VERSION;
26476 		oipha->ipha_hdr_checksum = 0;
26477 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26478 		outer_mp->b_cont = inner_mp;
26479 		ipsec_mp->b_cont = outer_mp;
26480 
26481 		io->ipsec_out_se_done = B_TRUE;
26482 		io->ipsec_out_tunnel = B_TRUE;
26483 	}
26484 
26485 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26486 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26487 	    !ipsec_out_select_sa(ipsec_mp))
26488 		return;
26489 
26490 	/*
26491 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26492 	 * to do the heavy lifting.
26493 	 */
26494 	zoneid = io->ipsec_out_zoneid;
26495 	ASSERT(zoneid != ALL_ZONES);
26496 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26497 		ASSERT(io->ipsec_out_esp_sa != NULL);
26498 		io->ipsec_out_esp_done = B_TRUE;
26499 		/*
26500 		 * Note that since hw accel can only apply one transform,
26501 		 * not two, we skip hw accel for ESP if we also have AH
26502 		 * This is an design limitation of the interface
26503 		 * which should be revisited.
26504 		 */
26505 		ASSERT(ire != NULL);
26506 		if (io->ipsec_out_ah_sa == NULL) {
26507 			ill = (ill_t *)ire->ire_stq->q_ptr;
26508 			ipsec_out_is_accelerated(ipsec_mp,
26509 			    io->ipsec_out_esp_sa, ill, ire);
26510 		}
26511 
26512 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26513 		switch (ipsec_rc) {
26514 		case IPSEC_STATUS_SUCCESS:
26515 			break;
26516 		case IPSEC_STATUS_FAILED:
26517 			if (ill != NULL) {
26518 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26519 			} else {
26520 				BUMP_MIB(&ipst->ips_ip_mib,
26521 				    ipIfStatsOutDiscards);
26522 			}
26523 			/* FALLTHRU */
26524 		case IPSEC_STATUS_PENDING:
26525 			return;
26526 		}
26527 	}
26528 
26529 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26530 		ASSERT(io->ipsec_out_ah_sa != NULL);
26531 		io->ipsec_out_ah_done = B_TRUE;
26532 		if (ire == NULL) {
26533 			int idx = io->ipsec_out_capab_ill_index;
26534 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26535 			    NULL, NULL, NULL, NULL, ipst);
26536 			ill_need_rele = B_TRUE;
26537 		} else {
26538 			ill = (ill_t *)ire->ire_stq->q_ptr;
26539 		}
26540 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26541 		    ire);
26542 
26543 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26544 		switch (ipsec_rc) {
26545 		case IPSEC_STATUS_SUCCESS:
26546 			break;
26547 		case IPSEC_STATUS_FAILED:
26548 			if (ill != NULL) {
26549 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26550 			} else {
26551 				BUMP_MIB(&ipst->ips_ip_mib,
26552 				    ipIfStatsOutDiscards);
26553 			}
26554 			/* FALLTHRU */
26555 		case IPSEC_STATUS_PENDING:
26556 			if (ill != NULL && ill_need_rele)
26557 				ill_refrele(ill);
26558 			return;
26559 		}
26560 	}
26561 	/*
26562 	 * We are done with IPSEC processing. Send it over
26563 	 * the wire.
26564 	 */
26565 done:
26566 	mp = ipsec_mp->b_cont;
26567 	ipha = (ipha_t *)mp->b_rptr;
26568 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26569 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26570 	} else {
26571 		ip6h = (ip6_t *)ipha;
26572 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26573 	}
26574 	if (ill != NULL && ill_need_rele)
26575 		ill_refrele(ill);
26576 }
26577 
26578 /* ARGSUSED */
26579 void
26580 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26581 {
26582 	opt_restart_t	*or;
26583 	int	err;
26584 	conn_t	*connp;
26585 
26586 	ASSERT(CONN_Q(q));
26587 	connp = Q_TO_CONN(q);
26588 
26589 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26590 	or = (opt_restart_t *)first_mp->b_rptr;
26591 	/*
26592 	 * We don't need to pass any credentials here since this is just
26593 	 * a restart. The credentials are passed in when svr4_optcom_req
26594 	 * is called the first time (from ip_wput_nondata).
26595 	 */
26596 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26597 		err = svr4_optcom_req(q, first_mp, NULL,
26598 		    &ip_opt_obj);
26599 	} else {
26600 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26601 		err = tpi_optcom_req(q, first_mp, NULL,
26602 		    &ip_opt_obj);
26603 	}
26604 	if (err != EINPROGRESS) {
26605 		/* operation is done */
26606 		CONN_OPER_PENDING_DONE(connp);
26607 	}
26608 }
26609 
26610 /*
26611  * ioctls that go through a down/up sequence may need to wait for the down
26612  * to complete. This involves waiting for the ire and ipif refcnts to go down
26613  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26614  */
26615 /* ARGSUSED */
26616 void
26617 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26618 {
26619 	struct iocblk *iocp;
26620 	mblk_t *mp1;
26621 	ip_ioctl_cmd_t *ipip;
26622 	int err;
26623 	sin_t	*sin;
26624 	struct lifreq *lifr;
26625 	struct ifreq *ifr;
26626 
26627 	iocp = (struct iocblk *)mp->b_rptr;
26628 	ASSERT(ipsq != NULL);
26629 	/* Existence of mp1 verified in ip_wput_nondata */
26630 	mp1 = mp->b_cont->b_cont;
26631 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26632 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26633 		/*
26634 		 * Special case where ipsq_current_ipif is not set:
26635 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26636 		 * ill could also have become part of a ipmp group in the
26637 		 * process, we are here as were not able to complete the
26638 		 * operation in ipif_set_values because we could not become
26639 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26640 		 * will not be set so we need to set it.
26641 		 */
26642 		ill_t *ill = q->q_ptr;
26643 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26644 	}
26645 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26646 
26647 	if (ipip->ipi_cmd_type == IF_CMD) {
26648 		/* This a old style SIOC[GS]IF* command */
26649 		ifr = (struct ifreq *)mp1->b_rptr;
26650 		sin = (sin_t *)&ifr->ifr_addr;
26651 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26652 		/* This a new style SIOC[GS]LIF* command */
26653 		lifr = (struct lifreq *)mp1->b_rptr;
26654 		sin = (sin_t *)&lifr->lifr_addr;
26655 	} else {
26656 		sin = NULL;
26657 	}
26658 
26659 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26660 	    ipip, mp1->b_rptr);
26661 
26662 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26663 }
26664 
26665 /*
26666  * ioctl processing
26667  *
26668  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26669  * the ioctl command in the ioctl tables and determines the copyin data size
26670  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26671  * size.
26672  *
26673  * ioctl processing then continues when the M_IOCDATA makes its way down.
26674  * Now the ioctl is looked up again in the ioctl table, and its properties are
26675  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26676  * and the general ioctl processing function ip_process_ioctl is called.
26677  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26678  * so goes thru the serialization primitive ipsq_try_enter. Then the
26679  * appropriate function to handle the ioctl is called based on the entry in
26680  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26681  * which also refreleases the 'conn' that was refheld at the start of the
26682  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26683  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26684  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26685  *
26686  * Many exclusive ioctls go thru an internal down up sequence as part of
26687  * the operation. For example an attempt to change the IP address of an
26688  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26689  * does all the cleanup such as deleting all ires that use this address.
26690  * Then we need to wait till all references to the interface go away.
26691  */
26692 void
26693 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26694 {
26695 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26696 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26697 	cmd_info_t ci;
26698 	int err;
26699 	boolean_t entered_ipsq = B_FALSE;
26700 
26701 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26702 
26703 	if (ipip == NULL)
26704 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26705 
26706 	/*
26707 	 * SIOCLIFADDIF needs to go thru a special path since the
26708 	 * ill may not exist yet. This happens in the case of lo0
26709 	 * which is created using this ioctl.
26710 	 */
26711 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26712 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26713 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26714 		return;
26715 	}
26716 
26717 	ci.ci_ipif = NULL;
26718 	switch (ipip->ipi_cmd_type) {
26719 	case IF_CMD:
26720 	case LIF_CMD:
26721 		/*
26722 		 * ioctls that pass in a [l]ifreq appear here.
26723 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26724 		 * ci.ci_ipif
26725 		 */
26726 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26727 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26728 		if (err != 0) {
26729 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26730 			return;
26731 		}
26732 		ASSERT(ci.ci_ipif != NULL);
26733 		break;
26734 
26735 	case TUN_CMD:
26736 		/*
26737 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26738 		 * a refheld ipif in ci.ci_ipif
26739 		 */
26740 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26741 		if (err != 0) {
26742 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26743 			return;
26744 		}
26745 		ASSERT(ci.ci_ipif != NULL);
26746 		break;
26747 
26748 	case MISC_CMD:
26749 		/*
26750 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26751 		 * For eg. SIOCGLIFCONF will appear here.
26752 		 */
26753 		switch (ipip->ipi_cmd) {
26754 		case IF_UNITSEL:
26755 			/* ioctl comes down the ill */
26756 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26757 			ipif_refhold(ci.ci_ipif);
26758 			break;
26759 		case SIOCGMSFILTER:
26760 		case SIOCSMSFILTER:
26761 		case SIOCGIPMSFILTER:
26762 		case SIOCSIPMSFILTER:
26763 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26764 			    ip_process_ioctl);
26765 			if (err != 0) {
26766 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
26767 				    NULL);
26768 			}
26769 			break;
26770 		}
26771 		err = 0;
26772 		ci.ci_sin = NULL;
26773 		ci.ci_sin6 = NULL;
26774 		ci.ci_lifr = NULL;
26775 		break;
26776 	}
26777 
26778 	/*
26779 	 * If ipsq is non-null, we are already being called exclusively
26780 	 */
26781 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26782 	if (!(ipip->ipi_flags & IPI_WR)) {
26783 		/*
26784 		 * A return value of EINPROGRESS means the ioctl is
26785 		 * either queued and waiting for some reason or has
26786 		 * already completed.
26787 		 */
26788 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26789 		    ci.ci_lifr);
26790 		if (ci.ci_ipif != NULL)
26791 			ipif_refrele(ci.ci_ipif);
26792 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26793 		return;
26794 	}
26795 
26796 	ASSERT(ci.ci_ipif != NULL);
26797 
26798 	if (ipsq == NULL) {
26799 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26800 		    ip_process_ioctl, NEW_OP, B_TRUE);
26801 		entered_ipsq = B_TRUE;
26802 	}
26803 	/*
26804 	 * Release the ipif so that ipif_down and friends that wait for
26805 	 * references to go away are not misled about the current ipif_refcnt
26806 	 * values. We are writer so we can access the ipif even after releasing
26807 	 * the ipif.
26808 	 */
26809 	ipif_refrele(ci.ci_ipif);
26810 	if (ipsq == NULL)
26811 		return;
26812 
26813 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26814 
26815 	/*
26816 	 * For most set ioctls that come here, this serves as a single point
26817 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26818 	 * be any new references to the ipif. This helps functions that go
26819 	 * through this path and end up trying to wait for the refcnts
26820 	 * associated with the ipif to go down to zero. Some exceptions are
26821 	 * Failover, Failback, and Groupname commands that operate on more than
26822 	 * just the ci.ci_ipif. These commands internally determine the
26823 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26824 	 * flags on that set. Another exception is the Removeif command that
26825 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26826 	 * ipif to operate on.
26827 	 */
26828 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26829 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26830 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26831 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26832 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26833 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26834 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26835 
26836 	/*
26837 	 * A return value of EINPROGRESS means the ioctl is
26838 	 * either queued and waiting for some reason or has
26839 	 * already completed.
26840 	 */
26841 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26842 
26843 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26844 
26845 	if (entered_ipsq)
26846 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26847 }
26848 
26849 /*
26850  * Complete the ioctl. Typically ioctls use the mi package and need to
26851  * do mi_copyout/mi_copy_done.
26852  */
26853 void
26854 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26855 {
26856 	conn_t	*connp = NULL;
26857 
26858 	if (err == EINPROGRESS)
26859 		return;
26860 
26861 	if (CONN_Q(q)) {
26862 		connp = Q_TO_CONN(q);
26863 		ASSERT(connp->conn_ref >= 2);
26864 	}
26865 
26866 	switch (mode) {
26867 	case COPYOUT:
26868 		if (err == 0)
26869 			mi_copyout(q, mp);
26870 		else
26871 			mi_copy_done(q, mp, err);
26872 		break;
26873 
26874 	case NO_COPYOUT:
26875 		mi_copy_done(q, mp, err);
26876 		break;
26877 
26878 	default:
26879 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
26880 		break;
26881 	}
26882 
26883 	/*
26884 	 * The refhold placed at the start of the ioctl is released here.
26885 	 */
26886 	if (connp != NULL)
26887 		CONN_OPER_PENDING_DONE(connp);
26888 
26889 	if (ipsq != NULL)
26890 		ipsq_current_finish(ipsq);
26891 }
26892 
26893 /*
26894  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26895  */
26896 /* ARGSUSED */
26897 void
26898 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26899 {
26900 	conn_t *connp = arg;
26901 	tcp_t	*tcp;
26902 
26903 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26904 	tcp = connp->conn_tcp;
26905 
26906 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26907 		freemsg(mp);
26908 	else
26909 		tcp_rput_other(tcp, mp);
26910 	CONN_OPER_PENDING_DONE(connp);
26911 }
26912 
26913 /* Called from ip_wput for all non data messages */
26914 /* ARGSUSED */
26915 void
26916 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26917 {
26918 	mblk_t		*mp1;
26919 	ire_t		*ire, *fake_ire;
26920 	ill_t		*ill;
26921 	struct iocblk	*iocp;
26922 	ip_ioctl_cmd_t	*ipip;
26923 	cred_t		*cr;
26924 	conn_t		*connp;
26925 	int		cmd, err;
26926 	nce_t		*nce;
26927 	ipif_t		*ipif;
26928 	ip_stack_t	*ipst;
26929 	char		*proto_str;
26930 
26931 	if (CONN_Q(q)) {
26932 		connp = Q_TO_CONN(q);
26933 		ipst = connp->conn_netstack->netstack_ip;
26934 	} else {
26935 		connp = NULL;
26936 		ipst = ILLQ_TO_IPST(q);
26937 	}
26938 
26939 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26940 
26941 	/* Check if it is a queue to /dev/sctp. */
26942 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26943 	    connp->conn_rq == NULL) {
26944 		sctp_wput(q, mp);
26945 		return;
26946 	}
26947 
26948 	switch (DB_TYPE(mp)) {
26949 	case M_IOCTL:
26950 		/*
26951 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26952 		 * will arrange to copy in associated control structures.
26953 		 */
26954 		ip_sioctl_copyin_setup(q, mp);
26955 		return;
26956 	case M_IOCDATA:
26957 		/*
26958 		 * Ensure that this is associated with one of our trans-
26959 		 * parent ioctls.  If it's not ours, discard it if we're
26960 		 * running as a driver, or pass it on if we're a module.
26961 		 */
26962 		iocp = (struct iocblk *)mp->b_rptr;
26963 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26964 		if (ipip == NULL) {
26965 			if (q->q_next == NULL) {
26966 				goto nak;
26967 			} else {
26968 				putnext(q, mp);
26969 			}
26970 			return;
26971 		} else if ((q->q_next != NULL) &&
26972 		    !(ipip->ipi_flags & IPI_MODOK)) {
26973 			/*
26974 			 * the ioctl is one we recognise, but is not
26975 			 * consumed by IP as a module, pass M_IOCDATA
26976 			 * for processing downstream, but only for
26977 			 * common Streams ioctls.
26978 			 */
26979 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26980 				putnext(q, mp);
26981 				return;
26982 			} else {
26983 				goto nak;
26984 			}
26985 		}
26986 
26987 		/* IOCTL continuation following copyin or copyout. */
26988 		if (mi_copy_state(q, mp, NULL) == -1) {
26989 			/*
26990 			 * The copy operation failed.  mi_copy_state already
26991 			 * cleaned up, so we're out of here.
26992 			 */
26993 			return;
26994 		}
26995 		/*
26996 		 * If we just completed a copy in, we become writer and
26997 		 * continue processing in ip_sioctl_copyin_done.  If it
26998 		 * was a copy out, we call mi_copyout again.  If there is
26999 		 * nothing more to copy out, it will complete the IOCTL.
27000 		 */
27001 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27002 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27003 				mi_copy_done(q, mp, EPROTO);
27004 				return;
27005 			}
27006 			/*
27007 			 * Check for cases that need more copying.  A return
27008 			 * value of 0 means a second copyin has been started,
27009 			 * so we return; a return value of 1 means no more
27010 			 * copying is needed, so we continue.
27011 			 */
27012 			cmd = iocp->ioc_cmd;
27013 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27014 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27015 			    MI_COPY_COUNT(mp) == 1) {
27016 				if (ip_copyin_msfilter(q, mp) == 0)
27017 					return;
27018 			}
27019 			/*
27020 			 * Refhold the conn, till the ioctl completes. This is
27021 			 * needed in case the ioctl ends up in the pending mp
27022 			 * list. Every mp in the ill_pending_mp list and
27023 			 * the ipsq_pending_mp must have a refhold on the conn
27024 			 * to resume processing. The refhold is released when
27025 			 * the ioctl completes. (normally or abnormally)
27026 			 * In all cases ip_ioctl_finish is called to finish
27027 			 * the ioctl.
27028 			 */
27029 			if (connp != NULL) {
27030 				/* This is not a reentry */
27031 				ASSERT(ipsq == NULL);
27032 				CONN_INC_REF(connp);
27033 			} else {
27034 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27035 					mi_copy_done(q, mp, EINVAL);
27036 					return;
27037 				}
27038 			}
27039 
27040 			ip_process_ioctl(ipsq, q, mp, ipip);
27041 
27042 		} else {
27043 			mi_copyout(q, mp);
27044 		}
27045 		return;
27046 nak:
27047 		iocp->ioc_error = EINVAL;
27048 		mp->b_datap->db_type = M_IOCNAK;
27049 		iocp->ioc_count = 0;
27050 		qreply(q, mp);
27051 		return;
27052 
27053 	case M_IOCNAK:
27054 		/*
27055 		 * The only way we could get here is if a resolver didn't like
27056 		 * an IOCTL we sent it.	 This shouldn't happen.
27057 		 */
27058 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27059 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27060 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27061 		freemsg(mp);
27062 		return;
27063 	case M_IOCACK:
27064 		/* /dev/ip shouldn't see this */
27065 		if (CONN_Q(q))
27066 			goto nak;
27067 
27068 		/* Finish socket ioctls passed through to ARP. */
27069 		ip_sioctl_iocack(q, mp);
27070 		return;
27071 	case M_FLUSH:
27072 		if (*mp->b_rptr & FLUSHW)
27073 			flushq(q, FLUSHALL);
27074 		if (q->q_next) {
27075 			putnext(q, mp);
27076 			return;
27077 		}
27078 		if (*mp->b_rptr & FLUSHR) {
27079 			*mp->b_rptr &= ~FLUSHW;
27080 			qreply(q, mp);
27081 			return;
27082 		}
27083 		freemsg(mp);
27084 		return;
27085 	case IRE_DB_REQ_TYPE:
27086 		if (connp == NULL) {
27087 			proto_str = "IRE_DB_REQ_TYPE";
27088 			goto protonak;
27089 		}
27090 		/* An Upper Level Protocol wants a copy of an IRE. */
27091 		ip_ire_req(q, mp);
27092 		return;
27093 	case M_CTL:
27094 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27095 			break;
27096 
27097 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27098 		    TUN_HELLO) {
27099 			ASSERT(connp != NULL);
27100 			connp->conn_flags |= IPCL_IPTUN;
27101 			freeb(mp);
27102 			return;
27103 		}
27104 
27105 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27106 		    IP_ULP_OUT_LABELED) {
27107 			out_labeled_t *olp;
27108 
27109 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27110 				break;
27111 			olp = (out_labeled_t *)mp->b_rptr;
27112 			connp->conn_ulp_labeled = olp->out_qnext == q;
27113 			freemsg(mp);
27114 			return;
27115 		}
27116 
27117 		/* M_CTL messages are used by ARP to tell us things. */
27118 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27119 			break;
27120 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27121 		case AR_ENTRY_SQUERY:
27122 			ip_wput_ctl(q, mp);
27123 			return;
27124 		case AR_CLIENT_NOTIFY:
27125 			ip_arp_news(q, mp);
27126 			return;
27127 		case AR_DLPIOP_DONE:
27128 			ASSERT(q->q_next != NULL);
27129 			ill = (ill_t *)q->q_ptr;
27130 			/* qwriter_ip releases the refhold */
27131 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27132 			ill_refhold(ill);
27133 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27134 			return;
27135 		case AR_ARP_CLOSING:
27136 			/*
27137 			 * ARP (above us) is closing. If no ARP bringup is
27138 			 * currently pending, ack the message so that ARP
27139 			 * can complete its close. Also mark ill_arp_closing
27140 			 * so that new ARP bringups will fail. If any
27141 			 * ARP bringup is currently in progress, we will
27142 			 * ack this when the current ARP bringup completes.
27143 			 */
27144 			ASSERT(q->q_next != NULL);
27145 			ill = (ill_t *)q->q_ptr;
27146 			mutex_enter(&ill->ill_lock);
27147 			ill->ill_arp_closing = 1;
27148 			if (!ill->ill_arp_bringup_pending) {
27149 				mutex_exit(&ill->ill_lock);
27150 				qreply(q, mp);
27151 			} else {
27152 				mutex_exit(&ill->ill_lock);
27153 				freemsg(mp);
27154 			}
27155 			return;
27156 		case AR_ARP_EXTEND:
27157 			/*
27158 			 * The ARP module above us is capable of duplicate
27159 			 * address detection.  Old ATM drivers will not send
27160 			 * this message.
27161 			 */
27162 			ASSERT(q->q_next != NULL);
27163 			ill = (ill_t *)q->q_ptr;
27164 			ill->ill_arp_extend = B_TRUE;
27165 			freemsg(mp);
27166 			return;
27167 		default:
27168 			break;
27169 		}
27170 		break;
27171 	case M_PROTO:
27172 	case M_PCPROTO:
27173 		/*
27174 		 * The only PROTO messages we expect are ULP binds and
27175 		 * copies of option negotiation acknowledgements.
27176 		 */
27177 		switch (((union T_primitives *)mp->b_rptr)->type) {
27178 		case O_T_BIND_REQ:
27179 		case T_BIND_REQ: {
27180 			/* Request can get queued in bind */
27181 			if (connp == NULL) {
27182 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27183 				goto protonak;
27184 			}
27185 			/*
27186 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27187 			 * instead of going through this path.  We only get
27188 			 * here in the following cases:
27189 			 *
27190 			 * a. Bind retries, where ipsq is non-NULL.
27191 			 * b. T_BIND_REQ is issued from non TCP/UDP
27192 			 *    transport, e.g. icmp for raw socket,
27193 			 *    in which case ipsq will be NULL.
27194 			 */
27195 			ASSERT(ipsq != NULL ||
27196 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27197 
27198 			/* Don't increment refcnt if this is a re-entry */
27199 			if (ipsq == NULL)
27200 				CONN_INC_REF(connp);
27201 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27202 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27203 			if (mp == NULL)
27204 				return;
27205 			if (IPCL_IS_TCP(connp)) {
27206 				/*
27207 				 * In the case of TCP endpoint we
27208 				 * come here only for bind retries
27209 				 */
27210 				ASSERT(ipsq != NULL);
27211 				CONN_INC_REF(connp);
27212 				squeue_fill(connp->conn_sqp, mp,
27213 				    ip_resume_tcp_bind, connp,
27214 				    SQTAG_BIND_RETRY);
27215 				return;
27216 			} else if (IPCL_IS_UDP(connp)) {
27217 				/*
27218 				 * In the case of UDP endpoint we
27219 				 * come here only for bind retries
27220 				 */
27221 				ASSERT(ipsq != NULL);
27222 				udp_resume_bind(connp, mp);
27223 				return;
27224 			}
27225 			qreply(q, mp);
27226 			CONN_OPER_PENDING_DONE(connp);
27227 			return;
27228 		}
27229 		case T_SVR4_OPTMGMT_REQ:
27230 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27231 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27232 
27233 			if (connp == NULL) {
27234 				proto_str = "T_SVR4_OPTMGMT_REQ";
27235 				goto protonak;
27236 			}
27237 
27238 			if (!snmpcom_req(q, mp, ip_snmp_set,
27239 			    ip_snmp_get, cr)) {
27240 				/*
27241 				 * Call svr4_optcom_req so that it can
27242 				 * generate the ack. We don't come here
27243 				 * if this operation is being restarted.
27244 				 * ip_restart_optmgmt will drop the conn ref.
27245 				 * In the case of ipsec option after the ipsec
27246 				 * load is complete conn_restart_ipsec_waiter
27247 				 * drops the conn ref.
27248 				 */
27249 				ASSERT(ipsq == NULL);
27250 				CONN_INC_REF(connp);
27251 				if (ip_check_for_ipsec_opt(q, mp))
27252 					return;
27253 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27254 				if (err != EINPROGRESS) {
27255 					/* Operation is done */
27256 					CONN_OPER_PENDING_DONE(connp);
27257 				}
27258 			}
27259 			return;
27260 		case T_OPTMGMT_REQ:
27261 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27262 			/*
27263 			 * Note: No snmpcom_req support through new
27264 			 * T_OPTMGMT_REQ.
27265 			 * Call tpi_optcom_req so that it can
27266 			 * generate the ack.
27267 			 */
27268 			if (connp == NULL) {
27269 				proto_str = "T_OPTMGMT_REQ";
27270 				goto protonak;
27271 			}
27272 
27273 			ASSERT(ipsq == NULL);
27274 			/*
27275 			 * We don't come here for restart. ip_restart_optmgmt
27276 			 * will drop the conn ref. In the case of ipsec option
27277 			 * after the ipsec load is complete
27278 			 * conn_restart_ipsec_waiter drops the conn ref.
27279 			 */
27280 			CONN_INC_REF(connp);
27281 			if (ip_check_for_ipsec_opt(q, mp))
27282 				return;
27283 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27284 			if (err != EINPROGRESS) {
27285 				/* Operation is done */
27286 				CONN_OPER_PENDING_DONE(connp);
27287 			}
27288 			return;
27289 		case T_UNBIND_REQ:
27290 			if (connp == NULL) {
27291 				proto_str = "T_UNBIND_REQ";
27292 				goto protonak;
27293 			}
27294 			mp = ip_unbind(q, mp);
27295 			qreply(q, mp);
27296 			return;
27297 		default:
27298 			/*
27299 			 * Have to drop any DLPI messages coming down from
27300 			 * arp (such as an info_req which would cause ip
27301 			 * to receive an extra info_ack if it was passed
27302 			 * through.
27303 			 */
27304 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27305 			    (int)*(uint_t *)mp->b_rptr));
27306 			freemsg(mp);
27307 			return;
27308 		}
27309 		/* NOTREACHED */
27310 	case IRE_DB_TYPE: {
27311 		nce_t		*nce;
27312 		ill_t		*ill;
27313 		in6_addr_t	gw_addr_v6;
27314 
27315 
27316 		/*
27317 		 * This is a response back from a resolver.  It
27318 		 * consists of a message chain containing:
27319 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27320 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27321 		 * The LL_HDR_MBLK is the DLPI header to use to get
27322 		 * the attached packet, and subsequent ones for the
27323 		 * same destination, transmitted.
27324 		 */
27325 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27326 			break;
27327 		/*
27328 		 * First, check to make sure the resolution succeeded.
27329 		 * If it failed, the second mblk will be empty.
27330 		 * If it is, free the chain, dropping the packet.
27331 		 * (We must ire_delete the ire; that frees the ire mblk)
27332 		 * We're doing this now to support PVCs for ATM; it's
27333 		 * a partial xresolv implementation. When we fully implement
27334 		 * xresolv interfaces, instead of freeing everything here
27335 		 * we'll initiate neighbor discovery.
27336 		 *
27337 		 * For v4 (ARP and other external resolvers) the resolver
27338 		 * frees the message, so no check is needed. This check
27339 		 * is required, though, for a full xresolve implementation.
27340 		 * Including this code here now both shows how external
27341 		 * resolvers can NACK a resolution request using an
27342 		 * existing design that has no specific provisions for NACKs,
27343 		 * and also takes into account that the current non-ARP
27344 		 * external resolver has been coded to use this method of
27345 		 * NACKing for all IPv6 (xresolv) cases,
27346 		 * whether our xresolv implementation is complete or not.
27347 		 *
27348 		 */
27349 		ire = (ire_t *)mp->b_rptr;
27350 		ill = ire_to_ill(ire);
27351 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27352 		if (mp1->b_rptr == mp1->b_wptr) {
27353 			if (ire->ire_ipversion == IPV6_VERSION) {
27354 				/*
27355 				 * XRESOLV interface.
27356 				 */
27357 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27358 				mutex_enter(&ire->ire_lock);
27359 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27360 				mutex_exit(&ire->ire_lock);
27361 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27362 					nce = ndp_lookup_v6(ill,
27363 					    &ire->ire_addr_v6, B_FALSE);
27364 				} else {
27365 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27366 					    B_FALSE);
27367 				}
27368 				if (nce != NULL) {
27369 					nce_resolv_failed(nce);
27370 					ndp_delete(nce);
27371 					NCE_REFRELE(nce);
27372 				}
27373 			}
27374 			mp->b_cont = NULL;
27375 			freemsg(mp1);		/* frees the pkt as well */
27376 			ASSERT(ire->ire_nce == NULL);
27377 			ire_delete((ire_t *)mp->b_rptr);
27378 			return;
27379 		}
27380 
27381 		/*
27382 		 * Split them into IRE_MBLK and pkt and feed it into
27383 		 * ire_add_then_send. Then in ire_add_then_send
27384 		 * the IRE will be added, and then the packet will be
27385 		 * run back through ip_wput. This time it will make
27386 		 * it to the wire.
27387 		 */
27388 		mp->b_cont = NULL;
27389 		mp = mp1->b_cont;		/* now, mp points to pkt */
27390 		mp1->b_cont = NULL;
27391 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27392 		if (ire->ire_ipversion == IPV6_VERSION) {
27393 			/*
27394 			 * XRESOLV interface. Find the nce and put a copy
27395 			 * of the dl_unitdata_req in nce_res_mp
27396 			 */
27397 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27398 			mutex_enter(&ire->ire_lock);
27399 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27400 			mutex_exit(&ire->ire_lock);
27401 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27402 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27403 				    B_FALSE);
27404 			} else {
27405 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27406 			}
27407 			if (nce != NULL) {
27408 				/*
27409 				 * We have to protect nce_res_mp here
27410 				 * from being accessed by other threads
27411 				 * while we change the mblk pointer.
27412 				 * Other functions will also lock the nce when
27413 				 * accessing nce_res_mp.
27414 				 *
27415 				 * The reason we change the mblk pointer
27416 				 * here rather than copying the resolved address
27417 				 * into the template is that, unlike with
27418 				 * ethernet, we have no guarantee that the
27419 				 * resolved address length will be
27420 				 * smaller than or equal to the lla length
27421 				 * with which the template was allocated,
27422 				 * (for ethernet, they're equal)
27423 				 * so we have to use the actual resolved
27424 				 * address mblk - which holds the real
27425 				 * dl_unitdata_req with the resolved address.
27426 				 *
27427 				 * Doing this is the same behavior as was
27428 				 * previously used in the v4 ARP case.
27429 				 */
27430 				mutex_enter(&nce->nce_lock);
27431 				if (nce->nce_res_mp != NULL)
27432 					freemsg(nce->nce_res_mp);
27433 				nce->nce_res_mp = mp1;
27434 				mutex_exit(&nce->nce_lock);
27435 				/*
27436 				 * We do a fastpath probe here because
27437 				 * we have resolved the address without
27438 				 * using Neighbor Discovery.
27439 				 * In the non-XRESOLV v6 case, the fastpath
27440 				 * probe is done right after neighbor
27441 				 * discovery completes.
27442 				 */
27443 				if (nce->nce_res_mp != NULL) {
27444 					int res;
27445 					nce_fastpath_list_add(nce);
27446 					res = ill_fastpath_probe(ill,
27447 					    nce->nce_res_mp);
27448 					if (res != 0 && res != EAGAIN)
27449 						nce_fastpath_list_delete(nce);
27450 				}
27451 
27452 				ire_add_then_send(q, ire, mp);
27453 				/*
27454 				 * Now we have to clean out any packets
27455 				 * that may have been queued on the nce
27456 				 * while it was waiting for address resolution
27457 				 * to complete.
27458 				 */
27459 				mutex_enter(&nce->nce_lock);
27460 				mp1 = nce->nce_qd_mp;
27461 				nce->nce_qd_mp = NULL;
27462 				mutex_exit(&nce->nce_lock);
27463 				while (mp1 != NULL) {
27464 					mblk_t *nxt_mp;
27465 					queue_t *fwdq = NULL;
27466 					ill_t   *inbound_ill;
27467 					uint_t ifindex;
27468 
27469 					nxt_mp = mp1->b_next;
27470 					mp1->b_next = NULL;
27471 					/*
27472 					 * Retrieve ifindex stored in
27473 					 * ip_rput_data_v6()
27474 					 */
27475 					ifindex =
27476 					    (uint_t)(uintptr_t)mp1->b_prev;
27477 					inbound_ill =
27478 					    ill_lookup_on_ifindex(ifindex,
27479 					    B_TRUE, NULL, NULL, NULL,
27480 					    NULL, ipst);
27481 					mp1->b_prev = NULL;
27482 					if (inbound_ill != NULL)
27483 						fwdq = inbound_ill->ill_rq;
27484 
27485 					if (fwdq != NULL) {
27486 						put(fwdq, mp1);
27487 						ill_refrele(inbound_ill);
27488 					} else
27489 						put(WR(ill->ill_rq), mp1);
27490 					mp1 = nxt_mp;
27491 				}
27492 				NCE_REFRELE(nce);
27493 			} else {	/* nce is NULL; clean up */
27494 				ire_delete(ire);
27495 				freemsg(mp);
27496 				freemsg(mp1);
27497 				return;
27498 			}
27499 		} else {
27500 			nce_t *arpce;
27501 			/*
27502 			 * Link layer resolution succeeded. Recompute the
27503 			 * ire_nce.
27504 			 */
27505 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27506 			if ((arpce = ndp_lookup_v4(ill,
27507 			    (ire->ire_gateway_addr != INADDR_ANY ?
27508 			    &ire->ire_gateway_addr : &ire->ire_addr),
27509 			    B_FALSE)) == NULL) {
27510 				freeb(ire->ire_mp);
27511 				freeb(mp1);
27512 				freemsg(mp);
27513 				return;
27514 			}
27515 			mutex_enter(&arpce->nce_lock);
27516 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27517 			if (arpce->nce_state == ND_REACHABLE) {
27518 				/*
27519 				 * Someone resolved this before us;
27520 				 * cleanup the res_mp. Since ire has
27521 				 * not been added yet, the call to ire_add_v4
27522 				 * from ire_add_then_send (when a dup is
27523 				 * detected) will clean up the ire.
27524 				 */
27525 				freeb(mp1);
27526 			} else {
27527 				ASSERT(arpce->nce_res_mp == NULL);
27528 				arpce->nce_res_mp = mp1;
27529 				arpce->nce_state = ND_REACHABLE;
27530 			}
27531 			mutex_exit(&arpce->nce_lock);
27532 			if (ire->ire_marks & IRE_MARK_NOADD) {
27533 				/*
27534 				 * this ire will not be added to the ire
27535 				 * cache table, so we can set the ire_nce
27536 				 * here, as there are no atomicity constraints.
27537 				 */
27538 				ire->ire_nce = arpce;
27539 				/*
27540 				 * We are associating this nce with the ire
27541 				 * so change the nce ref taken in
27542 				 * ndp_lookup_v4() from
27543 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27544 				 */
27545 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27546 			} else {
27547 				NCE_REFRELE(arpce);
27548 			}
27549 			ire_add_then_send(q, ire, mp);
27550 		}
27551 		return;	/* All is well, the packet has been sent. */
27552 	}
27553 	case IRE_ARPRESOLVE_TYPE: {
27554 
27555 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27556 			break;
27557 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27558 		mp->b_cont = NULL;
27559 		/*
27560 		 * First, check to make sure the resolution succeeded.
27561 		 * If it failed, the second mblk will be empty.
27562 		 */
27563 		if (mp1->b_rptr == mp1->b_wptr) {
27564 			/* cleanup  the incomplete ire, free queued packets */
27565 			freemsg(mp); /* fake ire */
27566 			freeb(mp1);  /* dl_unitdata response */
27567 			return;
27568 		}
27569 
27570 		/*
27571 		 * update any incomplete nce_t found. we lookup the ctable
27572 		 * and find the nce from the ire->ire_nce because we need
27573 		 * to pass the ire to ip_xmit_v4 later, and can find both
27574 		 * ire and nce in one lookup from the ctable.
27575 		 */
27576 		fake_ire = (ire_t *)mp->b_rptr;
27577 		/*
27578 		 * By the time we come back here from ARP
27579 		 * the logical outgoing interface  of the incomplete ire
27580 		 * we added in ire_forward could have disappeared,
27581 		 * causing the incomplete ire to also have
27582 		 * dissapeared. So we need to retreive the
27583 		 * proper ipif for the ire  before looking
27584 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27585 		 */
27586 		ill = q->q_ptr;
27587 
27588 		/* Get the outgoing ipif */
27589 		mutex_enter(&ill->ill_lock);
27590 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27591 			mutex_exit(&ill->ill_lock);
27592 			freemsg(mp); /* fake ire */
27593 			freeb(mp1);  /* dl_unitdata response */
27594 			return;
27595 		}
27596 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27597 
27598 		if (ipif == NULL) {
27599 			mutex_exit(&ill->ill_lock);
27600 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27601 			freemsg(mp);
27602 			freeb(mp1);
27603 			return;
27604 		}
27605 		ipif_refhold_locked(ipif);
27606 		mutex_exit(&ill->ill_lock);
27607 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27608 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27609 		    ipif, fake_ire->ire_zoneid, NULL,
27610 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27611 		ipif_refrele(ipif);
27612 		if (ire == NULL) {
27613 			/*
27614 			 * no ire was found; check if there is an nce
27615 			 * for this lookup; if it has no ire's pointing at it
27616 			 * cleanup.
27617 			 */
27618 			if ((nce = ndp_lookup_v4(ill,
27619 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27620 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27621 			    B_FALSE)) != NULL) {
27622 				/*
27623 				 * cleanup:
27624 				 * We check for refcnt 2 (one for the nce
27625 				 * hash list + 1 for the ref taken by
27626 				 * ndp_lookup_v4) to check that there are
27627 				 * no ire's pointing at the nce.
27628 				 */
27629 				if (nce->nce_refcnt == 2)
27630 					ndp_delete(nce);
27631 				NCE_REFRELE(nce);
27632 			}
27633 			freeb(mp1);  /* dl_unitdata response */
27634 			freemsg(mp); /* fake ire */
27635 			return;
27636 		}
27637 		nce = ire->ire_nce;
27638 		DTRACE_PROBE2(ire__arpresolve__type,
27639 		    ire_t *, ire, nce_t *, nce);
27640 		ASSERT(nce->nce_state != ND_INITIAL);
27641 		mutex_enter(&nce->nce_lock);
27642 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27643 		if (nce->nce_state == ND_REACHABLE) {
27644 			/*
27645 			 * Someone resolved this before us;
27646 			 * our response is not needed any more.
27647 			 */
27648 			mutex_exit(&nce->nce_lock);
27649 			freeb(mp1);  /* dl_unitdata response */
27650 		} else {
27651 			ASSERT(nce->nce_res_mp == NULL);
27652 			nce->nce_res_mp = mp1;
27653 			nce->nce_state = ND_REACHABLE;
27654 			mutex_exit(&nce->nce_lock);
27655 			nce_fastpath(nce);
27656 		}
27657 		/*
27658 		 * The cached nce_t has been updated to be reachable;
27659 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27660 		 */
27661 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27662 		freemsg(mp);
27663 		/*
27664 		 * send out queued packets.
27665 		 */
27666 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27667 
27668 		IRE_REFRELE(ire);
27669 		return;
27670 	}
27671 	default:
27672 		break;
27673 	}
27674 	if (q->q_next) {
27675 		putnext(q, mp);
27676 	} else
27677 		freemsg(mp);
27678 	return;
27679 
27680 protonak:
27681 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27682 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27683 		qreply(q, mp);
27684 }
27685 
27686 /*
27687  * Process IP options in an outbound packet.  Modify the destination if there
27688  * is a source route option.
27689  * Returns non-zero if something fails in which case an ICMP error has been
27690  * sent and mp freed.
27691  */
27692 static int
27693 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27694     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27695 {
27696 	ipoptp_t	opts;
27697 	uchar_t		*opt;
27698 	uint8_t		optval;
27699 	uint8_t		optlen;
27700 	ipaddr_t	dst;
27701 	intptr_t	code = 0;
27702 	mblk_t		*mp;
27703 	ire_t		*ire = NULL;
27704 
27705 	ip2dbg(("ip_wput_options\n"));
27706 	mp = ipsec_mp;
27707 	if (mctl_present) {
27708 		mp = ipsec_mp->b_cont;
27709 	}
27710 
27711 	dst = ipha->ipha_dst;
27712 	for (optval = ipoptp_first(&opts, ipha);
27713 	    optval != IPOPT_EOL;
27714 	    optval = ipoptp_next(&opts)) {
27715 		opt = opts.ipoptp_cur;
27716 		optlen = opts.ipoptp_len;
27717 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27718 		    optval, optlen));
27719 		switch (optval) {
27720 			uint32_t off;
27721 		case IPOPT_SSRR:
27722 		case IPOPT_LSRR:
27723 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27724 				ip1dbg((
27725 				    "ip_wput_options: bad option offset\n"));
27726 				code = (char *)&opt[IPOPT_OLEN] -
27727 				    (char *)ipha;
27728 				goto param_prob;
27729 			}
27730 			off = opt[IPOPT_OFFSET];
27731 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27732 			    ntohl(dst)));
27733 			/*
27734 			 * For strict: verify that dst is directly
27735 			 * reachable.
27736 			 */
27737 			if (optval == IPOPT_SSRR) {
27738 				ire = ire_ftable_lookup(dst, 0, 0,
27739 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27740 				    MBLK_GETLABEL(mp),
27741 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27742 				if (ire == NULL) {
27743 					ip1dbg(("ip_wput_options: SSRR not"
27744 					    " directly reachable: 0x%x\n",
27745 					    ntohl(dst)));
27746 					goto bad_src_route;
27747 				}
27748 				ire_refrele(ire);
27749 			}
27750 			break;
27751 		case IPOPT_RR:
27752 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27753 				ip1dbg((
27754 				    "ip_wput_options: bad option offset\n"));
27755 				code = (char *)&opt[IPOPT_OLEN] -
27756 				    (char *)ipha;
27757 				goto param_prob;
27758 			}
27759 			break;
27760 		case IPOPT_TS:
27761 			/*
27762 			 * Verify that length >=5 and that there is either
27763 			 * room for another timestamp or that the overflow
27764 			 * counter is not maxed out.
27765 			 */
27766 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27767 			if (optlen < IPOPT_MINLEN_IT) {
27768 				goto param_prob;
27769 			}
27770 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27771 				ip1dbg((
27772 				    "ip_wput_options: bad option offset\n"));
27773 				code = (char *)&opt[IPOPT_OFFSET] -
27774 				    (char *)ipha;
27775 				goto param_prob;
27776 			}
27777 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27778 			case IPOPT_TS_TSONLY:
27779 				off = IPOPT_TS_TIMELEN;
27780 				break;
27781 			case IPOPT_TS_TSANDADDR:
27782 			case IPOPT_TS_PRESPEC:
27783 			case IPOPT_TS_PRESPEC_RFC791:
27784 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27785 				break;
27786 			default:
27787 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27788 				    (char *)ipha;
27789 				goto param_prob;
27790 			}
27791 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27792 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27793 				/*
27794 				 * No room and the overflow counter is 15
27795 				 * already.
27796 				 */
27797 				goto param_prob;
27798 			}
27799 			break;
27800 		}
27801 	}
27802 
27803 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27804 		return (0);
27805 
27806 	ip1dbg(("ip_wput_options: error processing IP options."));
27807 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27808 
27809 param_prob:
27810 	/*
27811 	 * Since ip_wput() isn't close to finished, we fill
27812 	 * in enough of the header for credible error reporting.
27813 	 */
27814 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27815 		/* Failed */
27816 		freemsg(ipsec_mp);
27817 		return (-1);
27818 	}
27819 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27820 	return (-1);
27821 
27822 bad_src_route:
27823 	/*
27824 	 * Since ip_wput() isn't close to finished, we fill
27825 	 * in enough of the header for credible error reporting.
27826 	 */
27827 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27828 		/* Failed */
27829 		freemsg(ipsec_mp);
27830 		return (-1);
27831 	}
27832 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27833 	return (-1);
27834 }
27835 
27836 /*
27837  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27838  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27839  * thru /etc/system.
27840  */
27841 #define	CONN_MAXDRAINCNT	64
27842 
27843 static void
27844 conn_drain_init(ip_stack_t *ipst)
27845 {
27846 	int i;
27847 
27848 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27849 
27850 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27851 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27852 		/*
27853 		 * Default value of the number of drainers is the
27854 		 * number of cpus, subject to maximum of 8 drainers.
27855 		 */
27856 		if (boot_max_ncpus != -1)
27857 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27858 		else
27859 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27860 	}
27861 
27862 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27863 	    sizeof (idl_t), KM_SLEEP);
27864 
27865 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
27866 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
27867 		    MUTEX_DEFAULT, NULL);
27868 	}
27869 }
27870 
27871 static void
27872 conn_drain_fini(ip_stack_t *ipst)
27873 {
27874 	int i;
27875 
27876 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
27877 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
27878 	kmem_free(ipst->ips_conn_drain_list,
27879 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27880 	ipst->ips_conn_drain_list = NULL;
27881 }
27882 
27883 /*
27884  * Note: For an overview of how flowcontrol is handled in IP please see the
27885  * IP Flowcontrol notes at the top of this file.
27886  *
27887  * Flow control has blocked us from proceeding. Insert the given conn in one
27888  * of the conn drain lists. These conn wq's will be qenabled later on when
27889  * STREAMS flow control does a backenable. conn_walk_drain will enable
27890  * the first conn in each of these drain lists. Each of these qenabled conns
27891  * in turn enables the next in the list, after it runs, or when it closes,
27892  * thus sustaining the drain process.
27893  *
27894  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27895  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27896  * running at any time, on a given conn, since there can be only 1 service proc
27897  * running on a queue at any time.
27898  */
27899 void
27900 conn_drain_insert(conn_t *connp)
27901 {
27902 	idl_t	*idl;
27903 	uint_t	index;
27904 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
27905 
27906 	mutex_enter(&connp->conn_lock);
27907 	if (connp->conn_state_flags & CONN_CLOSING) {
27908 		/*
27909 		 * The conn is closing as a result of which CONN_CLOSING
27910 		 * is set. Return.
27911 		 */
27912 		mutex_exit(&connp->conn_lock);
27913 		return;
27914 	} else if (connp->conn_idl == NULL) {
27915 		/*
27916 		 * Assign the next drain list round robin. We dont' use
27917 		 * a lock, and thus it may not be strictly round robin.
27918 		 * Atomicity of load/stores is enough to make sure that
27919 		 * conn_drain_list_index is always within bounds.
27920 		 */
27921 		index = ipst->ips_conn_drain_list_index;
27922 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
27923 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
27924 		index++;
27925 		if (index == ipst->ips_conn_drain_list_cnt)
27926 			index = 0;
27927 		ipst->ips_conn_drain_list_index = index;
27928 	}
27929 	mutex_exit(&connp->conn_lock);
27930 
27931 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27932 	if ((connp->conn_drain_prev != NULL) ||
27933 	    (connp->conn_state_flags & CONN_CLOSING)) {
27934 		/*
27935 		 * The conn is already in the drain list, OR
27936 		 * the conn is closing. We need to check again for
27937 		 * the closing case again since close can happen
27938 		 * after we drop the conn_lock, and before we
27939 		 * acquire the CONN_DRAIN_LIST_LOCK.
27940 		 */
27941 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27942 		return;
27943 	} else {
27944 		idl = connp->conn_idl;
27945 	}
27946 
27947 	/*
27948 	 * The conn is not in the drain list. Insert it at the
27949 	 * tail of the drain list. The drain list is circular
27950 	 * and doubly linked. idl_conn points to the 1st element
27951 	 * in the list.
27952 	 */
27953 	if (idl->idl_conn == NULL) {
27954 		idl->idl_conn = connp;
27955 		connp->conn_drain_next = connp;
27956 		connp->conn_drain_prev = connp;
27957 	} else {
27958 		conn_t *head = idl->idl_conn;
27959 
27960 		connp->conn_drain_next = head;
27961 		connp->conn_drain_prev = head->conn_drain_prev;
27962 		head->conn_drain_prev->conn_drain_next = connp;
27963 		head->conn_drain_prev = connp;
27964 	}
27965 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27966 }
27967 
27968 /*
27969  * This conn is closing, and we are called from ip_close. OR
27970  * This conn has been serviced by ip_wsrv, and we need to do the tail
27971  * processing.
27972  * If this conn is part of the drain list, we may need to sustain the drain
27973  * process by qenabling the next conn in the drain list. We may also need to
27974  * remove this conn from the list, if it is done.
27975  */
27976 static void
27977 conn_drain_tail(conn_t *connp, boolean_t closing)
27978 {
27979 	idl_t *idl;
27980 
27981 	/*
27982 	 * connp->conn_idl is stable at this point, and no lock is needed
27983 	 * to check it. If we are called from ip_close, close has already
27984 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27985 	 * called us only because conn_idl is non-null. If we are called thru
27986 	 * service, conn_idl could be null, but it cannot change because
27987 	 * service is single-threaded per queue, and there cannot be another
27988 	 * instance of service trying to call conn_drain_insert on this conn
27989 	 * now.
27990 	 */
27991 	ASSERT(!closing || (connp->conn_idl != NULL));
27992 
27993 	/*
27994 	 * If connp->conn_idl is null, the conn has not been inserted into any
27995 	 * drain list even once since creation of the conn. Just return.
27996 	 */
27997 	if (connp->conn_idl == NULL)
27998 		return;
27999 
28000 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28001 
28002 	if (connp->conn_drain_prev == NULL) {
28003 		/* This conn is currently not in the drain list.  */
28004 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28005 		return;
28006 	}
28007 	idl = connp->conn_idl;
28008 	if (idl->idl_conn_draining == connp) {
28009 		/*
28010 		 * This conn is the current drainer. If this is the last conn
28011 		 * in the drain list, we need to do more checks, in the 'if'
28012 		 * below. Otherwwise we need to just qenable the next conn,
28013 		 * to sustain the draining, and is handled in the 'else'
28014 		 * below.
28015 		 */
28016 		if (connp->conn_drain_next == idl->idl_conn) {
28017 			/*
28018 			 * This conn is the last in this list. This round
28019 			 * of draining is complete. If idl_repeat is set,
28020 			 * it means another flow enabling has happened from
28021 			 * the driver/streams and we need to another round
28022 			 * of draining.
28023 			 * If there are more than 2 conns in the drain list,
28024 			 * do a left rotate by 1, so that all conns except the
28025 			 * conn at the head move towards the head by 1, and the
28026 			 * the conn at the head goes to the tail. This attempts
28027 			 * a more even share for all queues that are being
28028 			 * drained.
28029 			 */
28030 			if ((connp->conn_drain_next != connp) &&
28031 			    (idl->idl_conn->conn_drain_next != connp)) {
28032 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28033 			}
28034 			if (idl->idl_repeat) {
28035 				qenable(idl->idl_conn->conn_wq);
28036 				idl->idl_conn_draining = idl->idl_conn;
28037 				idl->idl_repeat = 0;
28038 			} else {
28039 				idl->idl_conn_draining = NULL;
28040 			}
28041 		} else {
28042 			/*
28043 			 * If the next queue that we are now qenable'ing,
28044 			 * is closing, it will remove itself from this list
28045 			 * and qenable the subsequent queue in ip_close().
28046 			 * Serialization is acheived thru idl_lock.
28047 			 */
28048 			qenable(connp->conn_drain_next->conn_wq);
28049 			idl->idl_conn_draining = connp->conn_drain_next;
28050 		}
28051 	}
28052 	if (!connp->conn_did_putbq || closing) {
28053 		/*
28054 		 * Remove ourself from the drain list, if we did not do
28055 		 * a putbq, or if the conn is closing.
28056 		 * Note: It is possible that q->q_first is non-null. It means
28057 		 * that these messages landed after we did a enableok() in
28058 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28059 		 * service them.
28060 		 */
28061 		if (connp->conn_drain_next == connp) {
28062 			/* Singleton in the list */
28063 			ASSERT(connp->conn_drain_prev == connp);
28064 			idl->idl_conn = NULL;
28065 			idl->idl_conn_draining = NULL;
28066 		} else {
28067 			connp->conn_drain_prev->conn_drain_next =
28068 			    connp->conn_drain_next;
28069 			connp->conn_drain_next->conn_drain_prev =
28070 			    connp->conn_drain_prev;
28071 			if (idl->idl_conn == connp)
28072 				idl->idl_conn = connp->conn_drain_next;
28073 			ASSERT(idl->idl_conn_draining != connp);
28074 
28075 		}
28076 		connp->conn_drain_next = NULL;
28077 		connp->conn_drain_prev = NULL;
28078 	}
28079 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28080 }
28081 
28082 /*
28083  * Write service routine. Shared perimeter entry point.
28084  * ip_wsrv can be called in any of the following ways.
28085  * 1. The device queue's messages has fallen below the low water mark
28086  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28087  *    the drain lists and backenable the first conn in each list.
28088  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28089  *    qenabled non-tcp upper layers. We start dequeing messages and call
28090  *    ip_wput for each message.
28091  */
28092 
28093 void
28094 ip_wsrv(queue_t *q)
28095 {
28096 	conn_t	*connp;
28097 	ill_t	*ill;
28098 	mblk_t	*mp;
28099 
28100 	if (q->q_next) {
28101 		ill = (ill_t *)q->q_ptr;
28102 		if (ill->ill_state_flags == 0) {
28103 			/*
28104 			 * The device flow control has opened up.
28105 			 * Walk through conn drain lists and qenable the
28106 			 * first conn in each list. This makes sense only
28107 			 * if the stream is fully plumbed and setup.
28108 			 * Hence the if check above.
28109 			 */
28110 			ip1dbg(("ip_wsrv: walking\n"));
28111 			conn_walk_drain(ill->ill_ipst);
28112 		}
28113 		return;
28114 	}
28115 
28116 	connp = Q_TO_CONN(q);
28117 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28118 
28119 	/*
28120 	 * 1. Set conn_draining flag to signal that service is active.
28121 	 *
28122 	 * 2. ip_output determines whether it has been called from service,
28123 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28124 	 *    has been called from service.
28125 	 *
28126 	 * 3. Message ordering is preserved by the following logic.
28127 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28128 	 *    the message at the tail, if conn_draining is set (i.e. service
28129 	 *    is running) or if q->q_first is non-null.
28130 	 *
28131 	 *    ii. If ip_output is called from service, and if ip_output cannot
28132 	 *    putnext due to flow control, it does a putbq.
28133 	 *
28134 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28135 	 *    (causing an infinite loop).
28136 	 */
28137 	ASSERT(!connp->conn_did_putbq);
28138 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28139 		connp->conn_draining = 1;
28140 		noenable(q);
28141 		while ((mp = getq(q)) != NULL) {
28142 			ASSERT(CONN_Q(q));
28143 
28144 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28145 			if (connp->conn_did_putbq) {
28146 				/* ip_wput did a putbq */
28147 				break;
28148 			}
28149 		}
28150 		/*
28151 		 * At this point, a thread coming down from top, calling
28152 		 * ip_wput, may end up queueing the message. We have not yet
28153 		 * enabled the queue, so ip_wsrv won't be called again.
28154 		 * To avoid this race, check q->q_first again (in the loop)
28155 		 * If the other thread queued the message before we call
28156 		 * enableok(), we will catch it in the q->q_first check.
28157 		 * If the other thread queues the message after we call
28158 		 * enableok(), ip_wsrv will be called again by STREAMS.
28159 		 */
28160 		connp->conn_draining = 0;
28161 		enableok(q);
28162 	}
28163 
28164 	/* Enable the next conn for draining */
28165 	conn_drain_tail(connp, B_FALSE);
28166 
28167 	connp->conn_did_putbq = 0;
28168 }
28169 
28170 /*
28171  * Walk the list of all conn's calling the function provided with the
28172  * specified argument for each.	 Note that this only walks conn's that
28173  * have been bound.
28174  * Applies to both IPv4 and IPv6.
28175  */
28176 static void
28177 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28178 {
28179 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28180 	    ipst->ips_ipcl_udp_fanout_size,
28181 	    func, arg, zoneid);
28182 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28183 	    ipst->ips_ipcl_conn_fanout_size,
28184 	    func, arg, zoneid);
28185 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28186 	    ipst->ips_ipcl_bind_fanout_size,
28187 	    func, arg, zoneid);
28188 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28189 	    IPPROTO_MAX, func, arg, zoneid);
28190 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28191 	    IPPROTO_MAX, func, arg, zoneid);
28192 }
28193 
28194 /*
28195  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28196  * of conns that need to be drained, check if drain is already in progress.
28197  * If so set the idl_repeat bit, indicating that the last conn in the list
28198  * needs to reinitiate the drain once again, for the list. If drain is not
28199  * in progress for the list, initiate the draining, by qenabling the 1st
28200  * conn in the list. The drain is self-sustaining, each qenabled conn will
28201  * in turn qenable the next conn, when it is done/blocked/closing.
28202  */
28203 static void
28204 conn_walk_drain(ip_stack_t *ipst)
28205 {
28206 	int i;
28207 	idl_t *idl;
28208 
28209 	IP_STAT(ipst, ip_conn_walk_drain);
28210 
28211 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28212 		idl = &ipst->ips_conn_drain_list[i];
28213 		mutex_enter(&idl->idl_lock);
28214 		if (idl->idl_conn == NULL) {
28215 			mutex_exit(&idl->idl_lock);
28216 			continue;
28217 		}
28218 		/*
28219 		 * If this list is not being drained currently by
28220 		 * an ip_wsrv thread, start the process.
28221 		 */
28222 		if (idl->idl_conn_draining == NULL) {
28223 			ASSERT(idl->idl_repeat == 0);
28224 			qenable(idl->idl_conn->conn_wq);
28225 			idl->idl_conn_draining = idl->idl_conn;
28226 		} else {
28227 			idl->idl_repeat = 1;
28228 		}
28229 		mutex_exit(&idl->idl_lock);
28230 	}
28231 }
28232 
28233 /*
28234  * Walk an conn hash table of `count' buckets, calling func for each entry.
28235  */
28236 static void
28237 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28238     zoneid_t zoneid)
28239 {
28240 	conn_t	*connp;
28241 
28242 	while (count-- > 0) {
28243 		mutex_enter(&connfp->connf_lock);
28244 		for (connp = connfp->connf_head; connp != NULL;
28245 		    connp = connp->conn_next) {
28246 			if (zoneid == GLOBAL_ZONEID ||
28247 			    zoneid == connp->conn_zoneid) {
28248 				CONN_INC_REF(connp);
28249 				mutex_exit(&connfp->connf_lock);
28250 				(*func)(connp, arg);
28251 				mutex_enter(&connfp->connf_lock);
28252 				CONN_DEC_REF(connp);
28253 			}
28254 		}
28255 		mutex_exit(&connfp->connf_lock);
28256 		connfp++;
28257 	}
28258 }
28259 
28260 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28261 static void
28262 conn_report1(conn_t *connp, void *mp)
28263 {
28264 	char	buf1[INET6_ADDRSTRLEN];
28265 	char	buf2[INET6_ADDRSTRLEN];
28266 	uint_t	print_len, buf_len;
28267 
28268 	ASSERT(connp != NULL);
28269 
28270 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28271 	if (buf_len <= 0)
28272 		return;
28273 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28274 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28275 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28276 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28277 	    "%5d %s/%05d %s/%05d\n",
28278 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28279 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28280 	    buf1, connp->conn_lport,
28281 	    buf2, connp->conn_fport);
28282 	if (print_len < buf_len) {
28283 		((mblk_t *)mp)->b_wptr += print_len;
28284 	} else {
28285 		((mblk_t *)mp)->b_wptr += buf_len;
28286 	}
28287 }
28288 
28289 /*
28290  * Named Dispatch routine to produce a formatted report on all conns
28291  * that are listed in one of the fanout tables.
28292  * This report is accessed by using the ndd utility to "get" ND variable
28293  * "ip_conn_status".
28294  */
28295 /* ARGSUSED */
28296 static int
28297 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28298 {
28299 	conn_t *connp = Q_TO_CONN(q);
28300 
28301 	(void) mi_mpprintf(mp,
28302 	    "CONN      " MI_COL_HDRPAD_STR
28303 	    "rfq      " MI_COL_HDRPAD_STR
28304 	    "stq      " MI_COL_HDRPAD_STR
28305 	    " zone local                 remote");
28306 
28307 	/*
28308 	 * Because of the ndd constraint, at most we can have 64K buffer
28309 	 * to put in all conn info.  So to be more efficient, just
28310 	 * allocate a 64K buffer here, assuming we need that large buffer.
28311 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28312 	 */
28313 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28314 		/* The following may work even if we cannot get a large buf. */
28315 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28316 		return (0);
28317 	}
28318 
28319 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28320 	    connp->conn_netstack->netstack_ip);
28321 	return (0);
28322 }
28323 
28324 /*
28325  * Determine if the ill and multicast aspects of that packets
28326  * "matches" the conn.
28327  */
28328 boolean_t
28329 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28330     zoneid_t zoneid)
28331 {
28332 	ill_t *in_ill;
28333 	boolean_t found;
28334 	ipif_t *ipif;
28335 	ire_t *ire;
28336 	ipaddr_t dst, src;
28337 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28338 
28339 	dst = ipha->ipha_dst;
28340 	src = ipha->ipha_src;
28341 
28342 	/*
28343 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28344 	 * unicast, broadcast and multicast reception to
28345 	 * conn_incoming_ill. conn_wantpacket itself is called
28346 	 * only for BROADCAST and multicast.
28347 	 *
28348 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28349 	 *    is part of a group. Hence, we should be receiving
28350 	 *    just one copy of broadcast for the whole group.
28351 	 *    Thus, if it is part of the group the packet could
28352 	 *    come on any ill of the group and hence we need a
28353 	 *    match on the group. Otherwise, match on ill should
28354 	 *    be sufficient.
28355 	 *
28356 	 * 2) ip_rput does not suppress duplicate multicast packets.
28357 	 *    If there are two interfaces in a ill group and we have
28358 	 *    2 applications (conns) joined a multicast group G on
28359 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28360 	 *    will give us two packets because we join G on both the
28361 	 *    interfaces rather than nominating just one interface
28362 	 *    for receiving multicast like broadcast above. So,
28363 	 *    we have to call ilg_lookup_ill to filter out duplicate
28364 	 *    copies, if ill is part of a group.
28365 	 */
28366 	in_ill = connp->conn_incoming_ill;
28367 	if (in_ill != NULL) {
28368 		if (in_ill->ill_group == NULL) {
28369 			if (in_ill != ill)
28370 				return (B_FALSE);
28371 		} else if (in_ill->ill_group != ill->ill_group) {
28372 			return (B_FALSE);
28373 		}
28374 	}
28375 
28376 	if (!CLASSD(dst)) {
28377 		if (IPCL_ZONE_MATCH(connp, zoneid))
28378 			return (B_TRUE);
28379 		/*
28380 		 * The conn is in a different zone; we need to check that this
28381 		 * broadcast address is configured in the application's zone and
28382 		 * on one ill in the group.
28383 		 */
28384 		ipif = ipif_get_next_ipif(NULL, ill);
28385 		if (ipif == NULL)
28386 			return (B_FALSE);
28387 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28388 		    connp->conn_zoneid, NULL,
28389 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28390 		ipif_refrele(ipif);
28391 		if (ire != NULL) {
28392 			ire_refrele(ire);
28393 			return (B_TRUE);
28394 		} else {
28395 			return (B_FALSE);
28396 		}
28397 	}
28398 
28399 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28400 	    connp->conn_zoneid == zoneid) {
28401 		/*
28402 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28403 		 * disabled, therefore we don't dispatch the multicast packet to
28404 		 * the sending zone.
28405 		 */
28406 		return (B_FALSE);
28407 	}
28408 
28409 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28410 		/*
28411 		 * Multicast packet on the loopback interface: we only match
28412 		 * conns who joined the group in the specified zone.
28413 		 */
28414 		return (B_FALSE);
28415 	}
28416 
28417 	if (connp->conn_multi_router) {
28418 		/* multicast packet and multicast router socket: send up */
28419 		return (B_TRUE);
28420 	}
28421 
28422 	mutex_enter(&connp->conn_lock);
28423 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28424 	mutex_exit(&connp->conn_lock);
28425 	return (found);
28426 }
28427 
28428 /*
28429  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28430  */
28431 /* ARGSUSED */
28432 static void
28433 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28434 {
28435 	ill_t *ill = (ill_t *)q->q_ptr;
28436 	mblk_t	*mp1, *mp2;
28437 	ipif_t  *ipif;
28438 	int err = 0;
28439 	conn_t *connp = NULL;
28440 	ipsq_t	*ipsq;
28441 	arc_t	*arc;
28442 
28443 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28444 
28445 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28446 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28447 
28448 	ASSERT(IAM_WRITER_ILL(ill));
28449 	mp2 = mp->b_cont;
28450 	mp->b_cont = NULL;
28451 
28452 	/*
28453 	 * We have now received the arp bringup completion message
28454 	 * from ARP. Mark the arp bringup as done. Also if the arp
28455 	 * stream has already started closing, send up the AR_ARP_CLOSING
28456 	 * ack now since ARP is waiting in close for this ack.
28457 	 */
28458 	mutex_enter(&ill->ill_lock);
28459 	ill->ill_arp_bringup_pending = 0;
28460 	if (ill->ill_arp_closing) {
28461 		mutex_exit(&ill->ill_lock);
28462 		/* Let's reuse the mp for sending the ack */
28463 		arc = (arc_t *)mp->b_rptr;
28464 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28465 		arc->arc_cmd = AR_ARP_CLOSING;
28466 		qreply(q, mp);
28467 	} else {
28468 		mutex_exit(&ill->ill_lock);
28469 		freeb(mp);
28470 	}
28471 
28472 	ipsq = ill->ill_phyint->phyint_ipsq;
28473 	ipif = ipsq->ipsq_pending_ipif;
28474 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28475 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28476 	if (mp1 == NULL) {
28477 		/* bringup was aborted by the user */
28478 		freemsg(mp2);
28479 		return;
28480 	}
28481 
28482 	/*
28483 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28484 	 * must have an associated conn_t.  Otherwise, we're bringing this
28485 	 * interface back up as part of handling an asynchronous event (e.g.,
28486 	 * physical address change).
28487 	 */
28488 	if (ipsq->ipsq_current_ioctl != 0) {
28489 		ASSERT(connp != NULL);
28490 		q = CONNP_TO_WQ(connp);
28491 	} else {
28492 		ASSERT(connp == NULL);
28493 		q = ill->ill_rq;
28494 	}
28495 
28496 	/*
28497 	 * If the DL_BIND_REQ fails, it is noted
28498 	 * in arc_name_offset.
28499 	 */
28500 	err = *((int *)mp2->b_rptr);
28501 	if (err == 0) {
28502 		if (ipif->ipif_isv6) {
28503 			if ((err = ipif_up_done_v6(ipif)) != 0)
28504 				ip0dbg(("ip_arp_done: init failed\n"));
28505 		} else {
28506 			if ((err = ipif_up_done(ipif)) != 0)
28507 				ip0dbg(("ip_arp_done: init failed\n"));
28508 		}
28509 	} else {
28510 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28511 	}
28512 
28513 	freemsg(mp2);
28514 
28515 	if ((err == 0) && (ill->ill_up_ipifs)) {
28516 		err = ill_up_ipifs(ill, q, mp1);
28517 		if (err == EINPROGRESS)
28518 			return;
28519 	}
28520 
28521 	if (ill->ill_up_ipifs)
28522 		ill_group_cleanup(ill);
28523 
28524 	/*
28525 	 * The operation must complete without EINPROGRESS since
28526 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28527 	 * Otherwise, the operation will be stuck forever in the ipsq.
28528 	 */
28529 	ASSERT(err != EINPROGRESS);
28530 	if (ipsq->ipsq_current_ioctl != 0)
28531 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28532 	else
28533 		ipsq_current_finish(ipsq);
28534 }
28535 
28536 /* Allocate the private structure */
28537 static int
28538 ip_priv_alloc(void **bufp)
28539 {
28540 	void	*buf;
28541 
28542 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28543 		return (ENOMEM);
28544 
28545 	*bufp = buf;
28546 	return (0);
28547 }
28548 
28549 /* Function to delete the private structure */
28550 void
28551 ip_priv_free(void *buf)
28552 {
28553 	ASSERT(buf != NULL);
28554 	kmem_free(buf, sizeof (ip_priv_t));
28555 }
28556 
28557 /*
28558  * The entry point for IPPF processing.
28559  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28560  * routine just returns.
28561  *
28562  * When called, ip_process generates an ipp_packet_t structure
28563  * which holds the state information for this packet and invokes the
28564  * the classifier (via ipp_packet_process). The classification, depending on
28565  * configured filters, results in a list of actions for this packet. Invoking
28566  * an action may cause the packet to be dropped, in which case the resulting
28567  * mblk (*mpp) is NULL. proc indicates the callout position for
28568  * this packet and ill_index is the interface this packet on or will leave
28569  * on (inbound and outbound resp.).
28570  */
28571 void
28572 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28573 {
28574 	mblk_t		*mp;
28575 	ip_priv_t	*priv;
28576 	ipp_action_id_t	aid;
28577 	int		rc = 0;
28578 	ipp_packet_t	*pp;
28579 #define	IP_CLASS	"ip"
28580 
28581 	/* If the classifier is not loaded, return  */
28582 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28583 		return;
28584 	}
28585 
28586 	mp = *mpp;
28587 	ASSERT(mp != NULL);
28588 
28589 	/* Allocate the packet structure */
28590 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28591 	if (rc != 0) {
28592 		*mpp = NULL;
28593 		freemsg(mp);
28594 		return;
28595 	}
28596 
28597 	/* Allocate the private structure */
28598 	rc = ip_priv_alloc((void **)&priv);
28599 	if (rc != 0) {
28600 		*mpp = NULL;
28601 		freemsg(mp);
28602 		ipp_packet_free(pp);
28603 		return;
28604 	}
28605 	priv->proc = proc;
28606 	priv->ill_index = ill_index;
28607 	ipp_packet_set_private(pp, priv, ip_priv_free);
28608 	ipp_packet_set_data(pp, mp);
28609 
28610 	/* Invoke the classifier */
28611 	rc = ipp_packet_process(&pp);
28612 	if (pp != NULL) {
28613 		mp = ipp_packet_get_data(pp);
28614 		ipp_packet_free(pp);
28615 		if (rc != 0) {
28616 			freemsg(mp);
28617 			*mpp = NULL;
28618 		}
28619 	} else {
28620 		*mpp = NULL;
28621 	}
28622 #undef	IP_CLASS
28623 }
28624 
28625 /*
28626  * Propagate a multicast group membership operation (add/drop) on
28627  * all the interfaces crossed by the related multirt routes.
28628  * The call is considered successful if the operation succeeds
28629  * on at least one interface.
28630  */
28631 static int
28632 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28633     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28634     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28635     mblk_t *first_mp)
28636 {
28637 	ire_t		*ire_gw;
28638 	irb_t		*irb;
28639 	int		error = 0;
28640 	opt_restart_t	*or;
28641 	ip_stack_t	*ipst = ire->ire_ipst;
28642 
28643 	irb = ire->ire_bucket;
28644 	ASSERT(irb != NULL);
28645 
28646 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28647 
28648 	or = (opt_restart_t *)first_mp->b_rptr;
28649 	IRB_REFHOLD(irb);
28650 	for (; ire != NULL; ire = ire->ire_next) {
28651 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28652 			continue;
28653 		if (ire->ire_addr != group)
28654 			continue;
28655 
28656 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28657 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28658 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28659 		/* No resolver exists for the gateway; skip this ire. */
28660 		if (ire_gw == NULL)
28661 			continue;
28662 
28663 		/*
28664 		 * This function can return EINPROGRESS. If so the operation
28665 		 * will be restarted from ip_restart_optmgmt which will
28666 		 * call ip_opt_set and option processing will restart for
28667 		 * this option. So we may end up calling 'fn' more than once.
28668 		 * This requires that 'fn' is idempotent except for the
28669 		 * return value. The operation is considered a success if
28670 		 * it succeeds at least once on any one interface.
28671 		 */
28672 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28673 		    NULL, fmode, src, first_mp);
28674 		if (error == 0)
28675 			or->or_private = CGTP_MCAST_SUCCESS;
28676 
28677 		if (ip_debug > 0) {
28678 			ulong_t	off;
28679 			char	*ksym;
28680 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28681 			ip2dbg(("ip_multirt_apply_membership: "
28682 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28683 			    "error %d [success %u]\n",
28684 			    ksym ? ksym : "?",
28685 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28686 			    error, or->or_private));
28687 		}
28688 
28689 		ire_refrele(ire_gw);
28690 		if (error == EINPROGRESS) {
28691 			IRB_REFRELE(irb);
28692 			return (error);
28693 		}
28694 	}
28695 	IRB_REFRELE(irb);
28696 	/*
28697 	 * Consider the call as successful if we succeeded on at least
28698 	 * one interface. Otherwise, return the last encountered error.
28699 	 */
28700 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28701 }
28702 
28703 
28704 /*
28705  * Issue a warning regarding a route crossing an interface with an
28706  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28707  * amount of time is logged.
28708  */
28709 static void
28710 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28711 {
28712 	hrtime_t	current = gethrtime();
28713 	char		buf[INET_ADDRSTRLEN];
28714 	ip_stack_t	*ipst = ire->ire_ipst;
28715 
28716 	/* Convert interval in ms to hrtime in ns */
28717 	if (ipst->ips_multirt_bad_mtu_last_time +
28718 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28719 	    current) {
28720 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28721 		    "to %s, incorrect MTU %u (expected %u)\n",
28722 		    ip_dot_addr(ire->ire_addr, buf),
28723 		    ire->ire_max_frag, max_frag);
28724 
28725 		ipst->ips_multirt_bad_mtu_last_time = current;
28726 	}
28727 }
28728 
28729 
28730 /*
28731  * Get the CGTP (multirouting) filtering status.
28732  * If 0, the CGTP hooks are transparent.
28733  */
28734 /* ARGSUSED */
28735 static int
28736 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28737 {
28738 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28739 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28740 
28741 	/*
28742 	 * Only applies to the shared stack since the filter_ops
28743 	 * do not carry an ip_stack_t or zoneid.
28744 	 */
28745 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
28746 		return (ENOTSUP);
28747 
28748 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28749 	return (0);
28750 }
28751 
28752 
28753 /*
28754  * Set the CGTP (multirouting) filtering status.
28755  * If the status is changed from active to transparent
28756  * or from transparent to active, forward the new status
28757  * to the filtering module (if loaded).
28758  */
28759 /* ARGSUSED */
28760 static int
28761 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28762     cred_t *ioc_cr)
28763 {
28764 	long		new_value;
28765 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28766 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28767 
28768 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
28769 		return (EPERM);
28770 
28771 	/*
28772 	 * Only applies to the shared stack since the filter_ops
28773 	 * do not carry an ip_stack_t or zoneid.
28774 	 */
28775 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
28776 		return (ENOTSUP);
28777 
28778 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28779 	    new_value < 0 || new_value > 1) {
28780 		return (EINVAL);
28781 	}
28782 
28783 	/*
28784 	 * Do not enable CGTP filtering - thus preventing the hooks
28785 	 * from being invoked - if the version number of the
28786 	 * filtering module hooks does not match.
28787 	 */
28788 	if ((ip_cgtp_filter_ops != NULL) &&
28789 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
28790 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
28791 		    "(module hooks version %d, expecting %d)\n",
28792 		    ip_cgtp_filter_ops->cfo_filter_rev,
28793 		    CGTP_FILTER_REV);
28794 		return (ENOTSUP);
28795 	}
28796 
28797 	if ((!*ip_cgtp_filter_value) && new_value) {
28798 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28799 		    ip_cgtp_filter_ops == NULL ?
28800 		    " (module not loaded)" : "");
28801 	}
28802 	if (*ip_cgtp_filter_value && (!new_value)) {
28803 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28804 		    ip_cgtp_filter_ops == NULL ?
28805 		    " (module not loaded)" : "");
28806 	}
28807 
28808 	if (ip_cgtp_filter_ops != NULL) {
28809 		int	res;
28810 
28811 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
28812 		if (res)
28813 			return (res);
28814 	}
28815 
28816 	*ip_cgtp_filter_value = (boolean_t)new_value;
28817 
28818 	return (0);
28819 }
28820 
28821 
28822 /*
28823  * Return the expected CGTP hooks version number.
28824  */
28825 int
28826 ip_cgtp_filter_supported(void)
28827 {
28828 	ip_stack_t *ipst;
28829 	int ret;
28830 
28831 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
28832 	if (ipst == NULL)
28833 		return (-1);
28834 	ret = ip_cgtp_filter_rev;
28835 	netstack_rele(ipst->ips_netstack);
28836 	return (ret);
28837 }
28838 
28839 
28840 /*
28841  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
28842  * or by invoking this function. In the first case, the version number
28843  * of the registered structure is checked at hooks activation time
28844  * in ip_cgtp_filter_set().
28845  *
28846  * Only applies to the shared stack since the filter_ops
28847  * do not carry an ip_stack_t or zoneid.
28848  */
28849 int
28850 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
28851 {
28852 	ip_stack_t *ipst;
28853 
28854 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28855 		return (ENOTSUP);
28856 
28857 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
28858 	if (ipst == NULL)
28859 		return (EINVAL);
28860 
28861 	ip_cgtp_filter_ops = ops;
28862 	netstack_rele(ipst->ips_netstack);
28863 	return (0);
28864 }
28865 
28866 static squeue_func_t
28867 ip_squeue_switch(int val)
28868 {
28869 	squeue_func_t rval = squeue_fill;
28870 
28871 	switch (val) {
28872 	case IP_SQUEUE_ENTER_NODRAIN:
28873 		rval = squeue_enter_nodrain;
28874 		break;
28875 	case IP_SQUEUE_ENTER:
28876 		rval = squeue_enter;
28877 		break;
28878 	default:
28879 		break;
28880 	}
28881 	return (rval);
28882 }
28883 
28884 /* ARGSUSED */
28885 static int
28886 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28887     caddr_t addr, cred_t *cr)
28888 {
28889 	int *v = (int *)addr;
28890 	long new_value;
28891 
28892 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28893 		return (EPERM);
28894 
28895 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28896 		return (EINVAL);
28897 
28898 	ip_input_proc = ip_squeue_switch(new_value);
28899 	*v = new_value;
28900 	return (0);
28901 }
28902 
28903 /* ARGSUSED */
28904 static int
28905 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28906     caddr_t addr, cred_t *cr)
28907 {
28908 	int *v = (int *)addr;
28909 	long new_value;
28910 
28911 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28912 		return (EPERM);
28913 
28914 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28915 		return (EINVAL);
28916 
28917 	*v = new_value;
28918 	return (0);
28919 }
28920 
28921 /*
28922  * Handle changes to ipmp_hook_emulation ndd variable.
28923  * Need to update phyint_hook_ifindex.
28924  * Also generate a nic plumb event should a new ifidex be assigned to a group.
28925  */
28926 static void
28927 ipmp_hook_emulation_changed(ip_stack_t *ipst)
28928 {
28929 	phyint_t *phyi;
28930 	phyint_t *phyi_tmp;
28931 	char *groupname;
28932 	int namelen;
28933 	ill_t	*ill;
28934 	boolean_t new_group;
28935 
28936 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
28937 	/*
28938 	 * Group indicies are stored in the phyint - a common structure
28939 	 * to both IPv4 and IPv6.
28940 	 */
28941 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
28942 	for (; phyi != NULL;
28943 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
28944 	    phyi, AVL_AFTER)) {
28945 		/* Ignore the ones that do not have a group */
28946 		if (phyi->phyint_groupname_len == 0)
28947 			continue;
28948 
28949 		/*
28950 		 * Look for other phyint in group.
28951 		 * Clear name/namelen so the lookup doesn't find ourselves.
28952 		 */
28953 		namelen = phyi->phyint_groupname_len;
28954 		groupname = phyi->phyint_groupname;
28955 		phyi->phyint_groupname_len = 0;
28956 		phyi->phyint_groupname = NULL;
28957 
28958 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
28959 		/* Restore */
28960 		phyi->phyint_groupname_len = namelen;
28961 		phyi->phyint_groupname = groupname;
28962 
28963 		new_group = B_FALSE;
28964 		if (ipst->ips_ipmp_hook_emulation) {
28965 			/*
28966 			 * If the group already exists and has already
28967 			 * been assigned a group ifindex, we use the existing
28968 			 * group_ifindex, otherwise we pick a new group_ifindex
28969 			 * here.
28970 			 */
28971 			if (phyi_tmp != NULL &&
28972 			    phyi_tmp->phyint_group_ifindex != 0) {
28973 				phyi->phyint_group_ifindex =
28974 				    phyi_tmp->phyint_group_ifindex;
28975 			} else {
28976 				/* XXX We need a recovery strategy here. */
28977 				if (!ip_assign_ifindex(
28978 				    &phyi->phyint_group_ifindex, ipst))
28979 					cmn_err(CE_PANIC,
28980 					    "ip_assign_ifindex() failed");
28981 				new_group = B_TRUE;
28982 			}
28983 		} else {
28984 			phyi->phyint_group_ifindex = 0;
28985 		}
28986 		if (ipst->ips_ipmp_hook_emulation)
28987 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
28988 		else
28989 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
28990 
28991 		/*
28992 		 * For IP Filter to find out the relationship between
28993 		 * names and interface indicies, we need to generate
28994 		 * a NE_PLUMB event when a new group can appear.
28995 		 * We always generate events when a new interface appears
28996 		 * (even when ipmp_hook_emulation is set) so there
28997 		 * is no need to generate NE_PLUMB events when
28998 		 * ipmp_hook_emulation is turned off.
28999 		 * And since it isn't critical for IP Filter to get
29000 		 * the NE_UNPLUMB events we skip those here.
29001 		 */
29002 		if (new_group) {
29003 			/*
29004 			 * First phyint in group - generate group PLUMB event.
29005 			 * Since we are not running inside the ipsq we do
29006 			 * the dispatch immediately.
29007 			 */
29008 			if (phyi->phyint_illv4 != NULL)
29009 				ill = phyi->phyint_illv4;
29010 			else
29011 				ill = phyi->phyint_illv6;
29012 
29013 			if (ill != NULL) {
29014 				mutex_enter(&ill->ill_lock);
29015 				ill_nic_info_plumb(ill, B_TRUE);
29016 				ill_nic_info_dispatch(ill);
29017 				mutex_exit(&ill->ill_lock);
29018 			}
29019 		}
29020 	}
29021 	rw_exit(&ipst->ips_ill_g_lock);
29022 }
29023 
29024 /* ARGSUSED */
29025 static int
29026 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29027     caddr_t addr, cred_t *cr)
29028 {
29029 	int *v = (int *)addr;
29030 	long new_value;
29031 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29032 
29033 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29034 		return (EINVAL);
29035 
29036 	if (*v != new_value) {
29037 		*v = new_value;
29038 		ipmp_hook_emulation_changed(ipst);
29039 	}
29040 	return (0);
29041 }
29042 
29043 static void *
29044 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29045 {
29046 	kstat_t *ksp;
29047 
29048 	ip_stat_t template = {
29049 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29050 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29051 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29052 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29053 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29054 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29055 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29056 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29057 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29058 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29059 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29060 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29061 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29062 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29063 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29064 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29065 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29066 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29067 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29068 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29069 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29070 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29071 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29072 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29073 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29074 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29075 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29076 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29077 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29078 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29079 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29080 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29081 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29082 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29083 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29084 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29085 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29086 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29087 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29088 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29089 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29090 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29091 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29092 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29093 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29094 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29095 	};
29096 
29097 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29098 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29099 	    KSTAT_FLAG_VIRTUAL, stackid);
29100 
29101 	if (ksp == NULL)
29102 		return (NULL);
29103 
29104 	bcopy(&template, ip_statisticsp, sizeof (template));
29105 	ksp->ks_data = (void *)ip_statisticsp;
29106 	ksp->ks_private = (void *)(uintptr_t)stackid;
29107 
29108 	kstat_install(ksp);
29109 	return (ksp);
29110 }
29111 
29112 static void
29113 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29114 {
29115 	if (ksp != NULL) {
29116 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29117 		kstat_delete_netstack(ksp, stackid);
29118 	}
29119 }
29120 
29121 static void *
29122 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29123 {
29124 	kstat_t	*ksp;
29125 
29126 	ip_named_kstat_t template = {
29127 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29128 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29129 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29130 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29131 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29132 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29133 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29134 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29135 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29136 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29137 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29138 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29139 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29140 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29141 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29142 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29143 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29144 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29145 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29146 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29147 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29148 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29149 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29150 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29151 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29152 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29153 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29154 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29155 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29156 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29157 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29158 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29159 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29160 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29161 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29162 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29163 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29164 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29165 	};
29166 
29167 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29168 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29169 	if (ksp == NULL || ksp->ks_data == NULL)
29170 		return (NULL);
29171 
29172 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29173 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29174 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29175 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29176 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29177 
29178 	template.netToMediaEntrySize.value.i32 =
29179 	    sizeof (mib2_ipNetToMediaEntry_t);
29180 
29181 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29182 
29183 	bcopy(&template, ksp->ks_data, sizeof (template));
29184 	ksp->ks_update = ip_kstat_update;
29185 	ksp->ks_private = (void *)(uintptr_t)stackid;
29186 
29187 	kstat_install(ksp);
29188 	return (ksp);
29189 }
29190 
29191 static void
29192 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29193 {
29194 	if (ksp != NULL) {
29195 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29196 		kstat_delete_netstack(ksp, stackid);
29197 	}
29198 }
29199 
29200 static int
29201 ip_kstat_update(kstat_t *kp, int rw)
29202 {
29203 	ip_named_kstat_t *ipkp;
29204 	mib2_ipIfStatsEntry_t ipmib;
29205 	ill_walk_context_t ctx;
29206 	ill_t *ill;
29207 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29208 	netstack_t	*ns;
29209 	ip_stack_t	*ipst;
29210 
29211 	if (kp == NULL || kp->ks_data == NULL)
29212 		return (EIO);
29213 
29214 	if (rw == KSTAT_WRITE)
29215 		return (EACCES);
29216 
29217 	ns = netstack_find_by_stackid(stackid);
29218 	if (ns == NULL)
29219 		return (-1);
29220 	ipst = ns->netstack_ip;
29221 	if (ipst == NULL) {
29222 		netstack_rele(ns);
29223 		return (-1);
29224 	}
29225 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29226 
29227 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29228 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29229 	ill = ILL_START_WALK_V4(&ctx, ipst);
29230 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29231 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29232 	rw_exit(&ipst->ips_ill_g_lock);
29233 
29234 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29235 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29236 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29237 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29238 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29239 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29240 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29241 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29242 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29243 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29244 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29245 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29246 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29247 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29248 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29249 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29250 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29251 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29252 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29253 
29254 	ipkp->routingDiscards.value.ui32 =	0;
29255 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29256 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29257 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29258 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29259 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29260 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29261 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29262 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29263 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29264 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29265 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29266 
29267 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29268 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29269 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29270 
29271 	netstack_rele(ns);
29272 
29273 	return (0);
29274 }
29275 
29276 static void *
29277 icmp_kstat_init(netstackid_t stackid)
29278 {
29279 	kstat_t	*ksp;
29280 
29281 	icmp_named_kstat_t template = {
29282 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29283 		{ "inErrors",		KSTAT_DATA_UINT32 },
29284 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29285 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29286 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29287 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29288 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29289 		{ "inEchos",		KSTAT_DATA_UINT32 },
29290 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29291 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29292 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29293 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29294 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29295 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29296 		{ "outErrors",		KSTAT_DATA_UINT32 },
29297 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29298 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29299 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29300 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29301 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29302 		{ "outEchos",		KSTAT_DATA_UINT32 },
29303 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29304 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29305 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29306 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29307 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29308 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29309 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29310 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29311 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29312 		{ "outDrops",		KSTAT_DATA_UINT32 },
29313 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29314 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29315 	};
29316 
29317 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29318 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29319 	if (ksp == NULL || ksp->ks_data == NULL)
29320 		return (NULL);
29321 
29322 	bcopy(&template, ksp->ks_data, sizeof (template));
29323 
29324 	ksp->ks_update = icmp_kstat_update;
29325 	ksp->ks_private = (void *)(uintptr_t)stackid;
29326 
29327 	kstat_install(ksp);
29328 	return (ksp);
29329 }
29330 
29331 static void
29332 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29333 {
29334 	if (ksp != NULL) {
29335 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29336 		kstat_delete_netstack(ksp, stackid);
29337 	}
29338 }
29339 
29340 static int
29341 icmp_kstat_update(kstat_t *kp, int rw)
29342 {
29343 	icmp_named_kstat_t *icmpkp;
29344 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29345 	netstack_t	*ns;
29346 	ip_stack_t	*ipst;
29347 
29348 	if ((kp == NULL) || (kp->ks_data == NULL))
29349 		return (EIO);
29350 
29351 	if (rw == KSTAT_WRITE)
29352 		return (EACCES);
29353 
29354 	ns = netstack_find_by_stackid(stackid);
29355 	if (ns == NULL)
29356 		return (-1);
29357 	ipst = ns->netstack_ip;
29358 	if (ipst == NULL) {
29359 		netstack_rele(ns);
29360 		return (-1);
29361 	}
29362 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29363 
29364 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29365 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29366 	icmpkp->inDestUnreachs.value.ui32 =
29367 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29368 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29369 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29370 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29371 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29372 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29373 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29374 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29375 	icmpkp->inTimestampReps.value.ui32 =
29376 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29377 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29378 	icmpkp->inAddrMaskReps.value.ui32 =
29379 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29380 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29381 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29382 	icmpkp->outDestUnreachs.value.ui32 =
29383 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29384 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29385 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29386 	icmpkp->outSrcQuenchs.value.ui32 =
29387 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29388 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29389 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29390 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29391 	icmpkp->outTimestamps.value.ui32 =
29392 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29393 	icmpkp->outTimestampReps.value.ui32 =
29394 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29395 	icmpkp->outAddrMasks.value.ui32 =
29396 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29397 	icmpkp->outAddrMaskReps.value.ui32 =
29398 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29399 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29400 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29401 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29402 	icmpkp->outFragNeeded.value.ui32 =
29403 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29404 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29405 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29406 	icmpkp->inBadRedirects.value.ui32 =
29407 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29408 
29409 	netstack_rele(ns);
29410 	return (0);
29411 }
29412 
29413 /*
29414  * This is the fanout function for raw socket opened for SCTP.  Note
29415  * that it is called after SCTP checks that there is no socket which
29416  * wants a packet.  Then before SCTP handles this out of the blue packet,
29417  * this function is called to see if there is any raw socket for SCTP.
29418  * If there is and it is bound to the correct address, the packet will
29419  * be sent to that socket.  Note that only one raw socket can be bound to
29420  * a port.  This is assured in ipcl_sctp_hash_insert();
29421  */
29422 void
29423 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29424     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29425     zoneid_t zoneid)
29426 {
29427 	conn_t		*connp;
29428 	queue_t		*rq;
29429 	mblk_t		*first_mp;
29430 	boolean_t	secure;
29431 	ip6_t		*ip6h;
29432 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29433 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29434 
29435 	first_mp = mp;
29436 	if (mctl_present) {
29437 		mp = first_mp->b_cont;
29438 		secure = ipsec_in_is_secure(first_mp);
29439 		ASSERT(mp != NULL);
29440 	} else {
29441 		secure = B_FALSE;
29442 	}
29443 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29444 
29445 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29446 	if (connp == NULL) {
29447 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29448 		return;
29449 	}
29450 	rq = connp->conn_rq;
29451 	if (!canputnext(rq)) {
29452 		CONN_DEC_REF(connp);
29453 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29454 		freemsg(first_mp);
29455 		return;
29456 	}
29457 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29458 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29459 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29460 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29461 		if (first_mp == NULL) {
29462 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29463 			CONN_DEC_REF(connp);
29464 			return;
29465 		}
29466 	}
29467 	/*
29468 	 * We probably should not send M_CTL message up to
29469 	 * raw socket.
29470 	 */
29471 	if (mctl_present)
29472 		freeb(first_mp);
29473 
29474 	/* Initiate IPPF processing here if needed. */
29475 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29476 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29477 		ip_process(IPP_LOCAL_IN, &mp,
29478 		    recv_ill->ill_phyint->phyint_ifindex);
29479 		if (mp == NULL) {
29480 			CONN_DEC_REF(connp);
29481 			return;
29482 		}
29483 	}
29484 
29485 	if (connp->conn_recvif || connp->conn_recvslla ||
29486 	    ((connp->conn_ip_recvpktinfo ||
29487 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29488 	    (flags & IP_FF_IPINFO))) {
29489 		int in_flags = 0;
29490 
29491 		/*
29492 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29493 		 * IPF_RECVIF.
29494 		 */
29495 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29496 			in_flags = IPF_RECVIF;
29497 		}
29498 		if (connp->conn_recvslla) {
29499 			in_flags |= IPF_RECVSLLA;
29500 		}
29501 		if (isv4) {
29502 			mp = ip_add_info(mp, recv_ill, in_flags,
29503 			    IPCL_ZONEID(connp), ipst);
29504 		} else {
29505 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29506 			if (mp == NULL) {
29507 				BUMP_MIB(recv_ill->ill_ip_mib,
29508 				    ipIfStatsInDiscards);
29509 				CONN_DEC_REF(connp);
29510 				return;
29511 			}
29512 		}
29513 	}
29514 
29515 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29516 	/*
29517 	 * We are sending the IPSEC_IN message also up. Refer
29518 	 * to comments above this function.
29519 	 */
29520 	putnext(rq, mp);
29521 	CONN_DEC_REF(connp);
29522 }
29523 
29524 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29525 {									\
29526 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29527 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29528 }
29529 /*
29530  * This function should be called only if all packet processing
29531  * including fragmentation is complete. Callers of this function
29532  * must set mp->b_prev to one of these values:
29533  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29534  * prior to handing over the mp as first argument to this function.
29535  *
29536  * If the ire passed by caller is incomplete, this function
29537  * queues the packet and if necessary, sends ARP request and bails.
29538  * If the ire passed is fully resolved, we simply prepend
29539  * the link-layer header to the packet, do ipsec hw acceleration
29540  * work if necessary, and send the packet out on the wire.
29541  *
29542  * NOTE: IPSEC will only call this function with fully resolved
29543  * ires if hw acceleration is involved.
29544  * TODO list :
29545  * 	a Handle M_MULTIDATA so that
29546  *	  tcp_multisend->tcp_multisend_data can
29547  *	  call ip_xmit_v4 directly
29548  *	b Handle post-ARP work for fragments so that
29549  *	  ip_wput_frag can call this function.
29550  */
29551 ipxmit_state_t
29552 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29553 {
29554 	nce_t		*arpce;
29555 	queue_t		*q;
29556 	int		ill_index;
29557 	mblk_t		*nxt_mp, *first_mp;
29558 	boolean_t	xmit_drop = B_FALSE;
29559 	ip_proc_t	proc;
29560 	ill_t		*out_ill;
29561 	int		pkt_len;
29562 
29563 	arpce = ire->ire_nce;
29564 	ASSERT(arpce != NULL);
29565 
29566 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29567 
29568 	mutex_enter(&arpce->nce_lock);
29569 	switch (arpce->nce_state) {
29570 	case ND_REACHABLE:
29571 		/* If there are other queued packets, queue this packet */
29572 		if (arpce->nce_qd_mp != NULL) {
29573 			if (mp != NULL)
29574 				nce_queue_mp_common(arpce, mp, B_FALSE);
29575 			mp = arpce->nce_qd_mp;
29576 		}
29577 		arpce->nce_qd_mp = NULL;
29578 		mutex_exit(&arpce->nce_lock);
29579 
29580 		/*
29581 		 * Flush the queue.  In the common case, where the
29582 		 * ARP is already resolved,  it will go through the
29583 		 * while loop only once.
29584 		 */
29585 		while (mp != NULL) {
29586 
29587 			nxt_mp = mp->b_next;
29588 			mp->b_next = NULL;
29589 			ASSERT(mp->b_datap->db_type != M_CTL);
29590 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29591 			/*
29592 			 * This info is needed for IPQOS to do COS marking
29593 			 * in ip_wput_attach_llhdr->ip_process.
29594 			 */
29595 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29596 			mp->b_prev = NULL;
29597 
29598 			/* set up ill index for outbound qos processing */
29599 			out_ill = ire->ire_ipif->ipif_ill;
29600 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29601 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29602 			    ill_index);
29603 			if (first_mp == NULL) {
29604 				xmit_drop = B_TRUE;
29605 				BUMP_MIB(out_ill->ill_ip_mib,
29606 				    ipIfStatsOutDiscards);
29607 				goto next_mp;
29608 			}
29609 			/* non-ipsec hw accel case */
29610 			if (io == NULL || !io->ipsec_out_accelerated) {
29611 				/* send it */
29612 				q = ire->ire_stq;
29613 				if (proc == IPP_FWD_OUT) {
29614 					UPDATE_IB_PKT_COUNT(ire);
29615 				} else {
29616 					UPDATE_OB_PKT_COUNT(ire);
29617 				}
29618 				ire->ire_last_used_time = lbolt;
29619 
29620 				if (flow_ctl_enabled || canputnext(q)) {
29621 					if (proc == IPP_FWD_OUT) {
29622 
29623 					BUMP_MIB(out_ill->ill_ip_mib,
29624 					    ipIfStatsHCOutForwDatagrams);
29625 
29626 					}
29627 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29628 					    pkt_len);
29629 
29630 					putnext(q, first_mp);
29631 				} else {
29632 					BUMP_MIB(out_ill->ill_ip_mib,
29633 					    ipIfStatsOutDiscards);
29634 					xmit_drop = B_TRUE;
29635 					freemsg(first_mp);
29636 				}
29637 			} else {
29638 				/*
29639 				 * Safety Pup says: make sure this
29640 				 *  is going to the right interface!
29641 				 */
29642 				ill_t *ill1 =
29643 				    (ill_t *)ire->ire_stq->q_ptr;
29644 				int ifindex =
29645 				    ill1->ill_phyint->phyint_ifindex;
29646 				if (ifindex !=
29647 				    io->ipsec_out_capab_ill_index) {
29648 					xmit_drop = B_TRUE;
29649 					freemsg(mp);
29650 				} else {
29651 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29652 					    pkt_len);
29653 					ipsec_hw_putnext(ire->ire_stq, mp);
29654 				}
29655 			}
29656 next_mp:
29657 			mp = nxt_mp;
29658 		} /* while (mp != NULL) */
29659 		if (xmit_drop)
29660 			return (SEND_FAILED);
29661 		else
29662 			return (SEND_PASSED);
29663 
29664 	case ND_INITIAL:
29665 	case ND_INCOMPLETE:
29666 
29667 		/*
29668 		 * While we do send off packets to dests that
29669 		 * use fully-resolved CGTP routes, we do not
29670 		 * handle unresolved CGTP routes.
29671 		 */
29672 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29673 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29674 
29675 		if (mp != NULL) {
29676 			/* queue the packet */
29677 			nce_queue_mp_common(arpce, mp, B_FALSE);
29678 		}
29679 
29680 		if (arpce->nce_state == ND_INCOMPLETE) {
29681 			mutex_exit(&arpce->nce_lock);
29682 			DTRACE_PROBE3(ip__xmit__incomplete,
29683 			    (ire_t *), ire, (mblk_t *), mp,
29684 			    (ipsec_out_t *), io);
29685 			return (LOOKUP_IN_PROGRESS);
29686 		}
29687 
29688 		arpce->nce_state = ND_INCOMPLETE;
29689 		mutex_exit(&arpce->nce_lock);
29690 		/*
29691 		 * Note that ire_add() (called from ire_forward())
29692 		 * holds a ref on the ire until ARP is completed.
29693 		 */
29694 
29695 		ire_arpresolve(ire, ire_to_ill(ire));
29696 		return (LOOKUP_IN_PROGRESS);
29697 	default:
29698 		ASSERT(0);
29699 		mutex_exit(&arpce->nce_lock);
29700 		return (LLHDR_RESLV_FAILED);
29701 	}
29702 }
29703 
29704 #undef	UPDATE_IP_MIB_OB_COUNTERS
29705 
29706 /*
29707  * Return B_TRUE if the buffers differ in length or content.
29708  * This is used for comparing extension header buffers.
29709  * Note that an extension header would be declared different
29710  * even if all that changed was the next header value in that header i.e.
29711  * what really changed is the next extension header.
29712  */
29713 boolean_t
29714 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29715     uint_t blen)
29716 {
29717 	if (!b_valid)
29718 		blen = 0;
29719 
29720 	if (alen != blen)
29721 		return (B_TRUE);
29722 	if (alen == 0)
29723 		return (B_FALSE);	/* Both zero length */
29724 	return (bcmp(abuf, bbuf, alen));
29725 }
29726 
29727 /*
29728  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29729  * Return B_FALSE if memory allocation fails - don't change any state!
29730  */
29731 boolean_t
29732 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29733     const void *src, uint_t srclen)
29734 {
29735 	void *dst;
29736 
29737 	if (!src_valid)
29738 		srclen = 0;
29739 
29740 	ASSERT(*dstlenp == 0);
29741 	if (src != NULL && srclen != 0) {
29742 		dst = mi_alloc(srclen, BPRI_MED);
29743 		if (dst == NULL)
29744 			return (B_FALSE);
29745 	} else {
29746 		dst = NULL;
29747 	}
29748 	if (*dstp != NULL)
29749 		mi_free(*dstp);
29750 	*dstp = dst;
29751 	*dstlenp = dst == NULL ? 0 : srclen;
29752 	return (B_TRUE);
29753 }
29754 
29755 /*
29756  * Replace what is in *dst, *dstlen with the source.
29757  * Assumes ip_allocbuf has already been called.
29758  */
29759 void
29760 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29761     const void *src, uint_t srclen)
29762 {
29763 	if (!src_valid)
29764 		srclen = 0;
29765 
29766 	ASSERT(*dstlenp == srclen);
29767 	if (src != NULL && srclen != 0)
29768 		bcopy(src, *dstp, srclen);
29769 }
29770 
29771 /*
29772  * Free the storage pointed to by the members of an ip6_pkt_t.
29773  */
29774 void
29775 ip6_pkt_free(ip6_pkt_t *ipp)
29776 {
29777 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29778 
29779 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29780 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29781 		ipp->ipp_hopopts = NULL;
29782 		ipp->ipp_hopoptslen = 0;
29783 	}
29784 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29785 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29786 		ipp->ipp_rtdstopts = NULL;
29787 		ipp->ipp_rtdstoptslen = 0;
29788 	}
29789 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29790 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29791 		ipp->ipp_dstopts = NULL;
29792 		ipp->ipp_dstoptslen = 0;
29793 	}
29794 	if (ipp->ipp_fields & IPPF_RTHDR) {
29795 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29796 		ipp->ipp_rthdr = NULL;
29797 		ipp->ipp_rthdrlen = 0;
29798 	}
29799 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29800 	    IPPF_RTHDR);
29801 }
29802